BaseUtil.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.IO;
  5. using System.Net;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using System.Web.Script.Serialization;
  9. using System.Windows.Forms;
  10. using System.Xml;
  11. namespace FileWatcher
  12. {
  13. class BaseUtil
  14. {
  15. public static void CreateXml(string iSN, string iTestResult)
  16. {
  17. //创建XML文档
  18. FileStream fcaches = new FileStream(iSN + ".xml", FileMode.OpenOrCreate, FileAccess.ReadWrite);
  19. fcaches.Close();
  20. FileInfo info = new FileInfo(iSN + ".xml");
  21. if (info.Length == 0)
  22. {
  23. XmlDocument doc = new XmlDocument();
  24. //创建类型声明节点
  25. XmlNode node = doc.CreateXmlDeclaration("1.0", "utf-8", "");
  26. doc.AppendChild(node);
  27. //创建根节点
  28. XmlElement xeRoot = doc.CreateElement("cacheInfo");
  29. doc.AppendChild(xeRoot);
  30. doc.Save(iSN + ".xml");
  31. }
  32. }
  33. public static void FillDgvWithDataTable(DataGridView dgv, DataTable dt, params DataGridViewImageColumn[] operate)
  34. {
  35. dgv.AutoGenerateColumns = false;
  36. dgv.DataSource = dt;
  37. if (operate.Length > 0)
  38. {
  39. if (dgv.Columns[operate[0].Name] != null)
  40. {
  41. dgv.Columns.Remove(dgv.Columns[operate[0].Name]);
  42. }
  43. dgv.Columns.Add(operate[0]);
  44. }
  45. ////纯英文的列不予展示
  46. //Regex regEnglish = new Regex("^[A-z]+$");
  47. //foreach (DataGridViewColumn dgvc in dgv.Columns)
  48. //{
  49. // if (regEnglish.IsMatch(dgvc.HeaderText))
  50. // {
  51. // dgvc.Visible = false;
  52. // }
  53. //}
  54. }
  55. public static string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic, out string fp_path, out string fp_id)
  56. {
  57. fp_id = "";
  58. fp_path = "";
  59. try
  60. {
  61. ServicePointManager.DefaultConnectionLimit = 50;
  62. string boundary = DateTime.Now.Ticks.ToString("x");
  63. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  64. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  65. request.Method = "POST";
  66. request.Timeout = 10 * 10000;
  67. request.ContentType = "multipart/form-data; boundary=" + boundary;
  68. Stream rs = request.GetRequestStream();
  69. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  70. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  71. if (dic != null)
  72. {
  73. foreach (string key in dic.Keys)
  74. {
  75. rs.Write(boundarybytes, 0, boundarybytes.Length);
  76. string formitem = string.Format(formdataTemplate, key, dic[key]);
  77. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  78. rs.Write(formitembytes, 0, formitembytes.Length);
  79. }
  80. }
  81. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  82. {
  83. rs.Write(boundarybytes, 0, boundarybytes.Length);
  84. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  85. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  86. rs.Write(headerbytes, 0, headerbytes.Length);
  87. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  88. {
  89. var buffer = new byte[1024];
  90. var bytesRead = 0;
  91. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  92. {
  93. rs.Write(buffer, 0, bytesRead);
  94. }
  95. }
  96. var cr = Encoding.UTF8.GetBytes("\r\n");
  97. rs.Write(cr, 0, cr.Length);
  98. }
  99. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  100. var response = request.GetResponse() as HttpWebResponse;
  101. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  102. string Content = newReader.ReadToEnd();
  103. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  104. List<Dictionary<string, object>> dic2 = null;
  105. dic1 = BaseUtil.ToDictionary(Content);
  106. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  107. if (dic2[0]["filepath"] != null)
  108. {
  109. fp_id = dic2[0]["filepath"].ToString();
  110. fp_path = dic2[0]["path"].ToString();
  111. }
  112. if (response.StatusCode == HttpStatusCode.OK)
  113. {
  114. Console.WriteLine(fp_id);
  115. return fp_id;
  116. }
  117. }
  118. catch (Exception e)
  119. {
  120. Console.WriteLine(e.Message + e.StackTrace);
  121. }
  122. return "";
  123. }
  124. public static Dictionary<string, object> ToDictionary(string JsonData)
  125. {
  126. object Data = null;
  127. Dictionary<string, object> Dic = new Dictionary<string, object>();
  128. if (JsonData.StartsWith("["))
  129. {
  130. //如果目标直接就为数组类型,则将会直接输出一个Key为List的List<Dictionary<string, object>>集合
  131. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["List"];
  132. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  133. MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  134. foreach (Match ListItem in ListMatch)
  135. {
  136. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  137. }
  138. Data = List;
  139. Dic.Add("List", Data);
  140. }
  141. else
  142. {
  143. MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值
  144. foreach (Match item in Match)
  145. {
  146. try
  147. {
  148. if (item.Groups[2].ToString().StartsWith("["))
  149. {
  150. //如果目标是数组,将会输出一个Key为当前Json的List<Dictionary<string, object>>集合
  151. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["Json中的Key"];
  152. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  153. MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  154. foreach (Match ListItem in ListMatch)
  155. {
  156. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  157. }
  158. Data = List;
  159. }
  160. else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null
  161. else Data = item.Groups[2].ToString(); //数据为数字、字符串中的一类,直接写入
  162. Dic.Add(item.Groups[1].ToString(), Data);
  163. }
  164. catch { }
  165. }
  166. }
  167. return Dic;
  168. }
  169. public static Dictionary<string, object> ToDictionary(string JsonData, string Type)
  170. {
  171. //实例化JavaScriptSerializer类的新实例
  172. JavaScriptSerializer jss = new JavaScriptSerializer();
  173. try
  174. {
  175. //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
  176. return jss.Deserialize<Dictionary<string, object>>(JsonData);
  177. }
  178. catch (Exception ex)
  179. {
  180. throw new Exception(ex.Message);
  181. }
  182. }
  183. public static object GetCacheData(string ParamName)
  184. {
  185. try
  186. {
  187. object returnData = null;
  188. //根据地址读取xml文件
  189. XmlDocument doc = new XmlDocument();
  190. XmlReaderSettings settings = new XmlReaderSettings();
  191. //忽略文档里面的注释
  192. settings.IgnoreComments = true;
  193. XmlReader reader = XmlReader.Create(AutoAnalysisXml.CachePath, settings);
  194. doc.Load(reader);
  195. //先得到根节点
  196. XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
  197. //再由根节点去找制定的节点
  198. XmlNodeList nodeList = rootNode.ChildNodes;
  199. foreach (XmlNode node in nodeList)
  200. {
  201. //找到了这个节点名字
  202. if (node.Name == ParamName)
  203. {
  204. //返回节点的内容
  205. switch (((XmlElement)node).GetAttribute("Type"))
  206. {
  207. case "System.String":
  208. returnData = node.InnerText;
  209. break;
  210. case "System.Int32":
  211. returnData = int.Parse(node.InnerText);
  212. break;
  213. case "System.Boolean":
  214. returnData = node.InnerText == "True" ? true : false;
  215. break;
  216. default:
  217. break;
  218. }
  219. break;
  220. }
  221. }
  222. //关闭reader
  223. reader.Close();
  224. if (returnData == null)
  225. return "";
  226. else
  227. return returnData;
  228. }
  229. catch (Exception e)
  230. {
  231. Console.WriteLine(e.Message + e.StackTrace);
  232. return "";
  233. }
  234. }
  235. public static void SetCacheData(string ParamName, object Value)
  236. {
  237. try
  238. {
  239. //根据地址读取xml文件
  240. XmlDocument doc = new XmlDocument();
  241. XmlReaderSettings settings = new XmlReaderSettings();
  242. //忽略文档里面的注释
  243. settings.IgnoreComments = true;
  244. XmlReader reader = XmlReader.Create(AutoAnalysisXml.CachePath, settings);
  245. doc.Load(reader);
  246. //先得到根节点
  247. XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
  248. //再由根节点去找制定的节点
  249. XmlNodeList nodeList = rootNode.ChildNodes;
  250. bool flag = false;
  251. foreach (XmlNode node in nodeList)
  252. {
  253. //找到了这个节点名字
  254. if (node.Name == ParamName)
  255. {
  256. //就直接赋值
  257. node.InnerText = Value.ToString();
  258. flag = true;
  259. }
  260. }
  261. //如果没有该节点,就创建节点保存结果
  262. if (!flag)
  263. {
  264. //创建节点
  265. XmlElement newNode = doc.CreateElement(ParamName);
  266. XmlAttribute attr = doc.CreateAttribute("Type");
  267. attr.InnerText = Value.GetType().ToString();
  268. newNode.InnerText = Value.ToString();
  269. newNode.SetAttributeNode(attr);
  270. //讲新建的节点挂到根节点上
  271. rootNode.AppendChild(newNode);
  272. }
  273. //关闭Reader
  274. reader.Close();
  275. doc.Save(AutoAnalysisXml.CachePath);
  276. }
  277. catch (Exception ex)
  278. {
  279. Console.WriteLine(ex.Message + ex.StackTrace);
  280. }
  281. }
  282. //播放音频文件
  283. public static void PlaySound(string FileName)
  284. {
  285. //要加载COM组件:Microsoft speech object Library
  286. if (!System.IO.File.Exists(FileName))
  287. {
  288. return;
  289. }
  290. //SpeechLib.SpVoiceClass pp = new SpeechLib.SpVoiceClass();
  291. //SpeechLib.SpFileStreamClass spFs = new SpeechLib.SpFileStreamClass();
  292. //spFs.Open(FileName, SpeechLib.SpeechStreamFileMode.SSFMOpenForRead, true);
  293. //SpeechLib.ISpeechBaseStream Istream = spFs as SpeechLib.ISpeechBaseStream;
  294. //pp.SpeakStream(Istream, SpeechLib.SpeechVoiceSpeakFlags.SVSFIsFilename);
  295. //spFs.Close();
  296. }
  297. public static void GetWriteInfo(string FilePath, out Dictionary<string, string> Dic)
  298. {
  299. Dic = new Dictionary<string, string>();
  300. string txt = "";
  301. StreamReader sr = new StreamReader(FilePath);
  302. while (!sr.EndOfStream)
  303. {
  304. string str = sr.ReadLine();
  305. txt += str + "\n";
  306. }
  307. sr.Close();
  308. sr.Dispose();
  309. Dic.Add("atd_sncode", FilePath.Substring(FilePath.LastIndexOf("\\") + 1).Replace(".txt", ""));
  310. Dic.Add("atd_software", Regex.Match(txt, "Program Name,\\S+").Value.Replace("Program Name,", ""));
  311. Dic.Add("atd_pot", Regex.Match(txt, "Board Segment,\\S+").Value.Replace("Board Segment,", ""));
  312. Dic.Add("atd_size", Regex.Match(txt, "Baord Size \\(L x W\\) \\[mm\\],\\S+").Value.Replace("Baord Size (L x W) [mm],", ""));
  313. Dic.Add("atd_pot1set", Regex.Match(txt, "Pot-1 Set Temp. \\[deg],\\S+").Value.Replace("Pot-1 Set Temp. [deg],", ""));
  314. Dic.Add("atd_pot2set", Regex.Match(txt, "Pot-2 Set Temp. \\[deg],\\S+").Value.Replace("Pot-2 Set Temp. [deg],", ""));
  315. Dic.Add("atd_pot1avgtemp", Regex.Match(txt, "Pot-1 Avg. Temp. \\[deg],\\S+").Value.Replace("Pot-1 Avg. Temp. [deg],", ""));
  316. Dic.Add("atd_pot2avgtemp", Regex.Match(txt, "Pot-2 Avg. Temp. \\[deg],\\S+").Value.Replace("Pot-2 Avg. Temp. [deg],", ""));
  317. Dic.Add("atd_boardtime", Regex.Match(txt, "Machine Duration \\[s],\\S+").Value.Replace("Machine Duration [s],", ""));
  318. //开始时间
  319. MatchCollection starttime = Regex.Matches(txt, "Start TimeStamp,\\S+ \\S+");
  320. for (int i = 0; i < starttime.Count; i++)
  321. {
  322. switch (i)
  323. {
  324. case 0:
  325. Dic.Add("atd_boardstarttime", starttime[i].Value.Replace("Start TimeStamp,", ""));
  326. break;
  327. case 1:
  328. Dic.Add("atd_flstarttime", starttime[i].Value.Replace("Start TimeStamp,", ""));
  329. break;
  330. case 2:
  331. Dic.Add("atd_phstarttime", starttime[i].Value.Replace("Start TimeStamp,", ""));
  332. break;
  333. case 3:
  334. Dic.Add("atd_sostarttime", starttime[i].Value.Replace("Start TimeStamp,", ""));
  335. break;
  336. default:
  337. break;
  338. }
  339. }
  340. MatchCollection endtime = Regex.Matches(txt, "End TimeStamp,\\S+ \\S+");
  341. for (int i = 0; i < starttime.Count; i++)
  342. {
  343. switch (i)
  344. {
  345. case 0:
  346. Dic.Add("atd_boardendtime", endtime[i].Value.Replace("End TimeStamp,", ""));
  347. break;
  348. case 1:
  349. Dic.Add("atd_flendtime", endtime[i].Value.Replace("End TimeStamp,", ""));
  350. break;
  351. case 2:
  352. Dic.Add("atd_phendtime", endtime[i].Value.Replace("End TimeStamp,", ""));
  353. break;
  354. case 3:
  355. Dic.Add("atd_soendtime", endtime[i].Value.Replace("End TimeStamp,", ""));
  356. break;
  357. default:
  358. break;
  359. }
  360. }
  361. MatchCollection duration = Regex.Matches(txt, "Total Zone Duration \\[s],\\S+");
  362. for (int i = 0; i < starttime.Count; i++)
  363. {
  364. switch (i)
  365. {
  366. case 0:
  367. Dic.Add("atd_fltime", duration[i].Value.Replace("Total Zone Duration [s],", ""));
  368. break;
  369. case 1:
  370. Dic.Add("atd_phtime", duration[i].Value.Replace("Total Zone Duration [s],", ""));
  371. break;
  372. case 2:
  373. Dic.Add("atd_sotime", duration[i].Value.Replace("Total Zone Duration [s],", ""));
  374. break;
  375. default:
  376. break;
  377. }
  378. }
  379. }
  380. }
  381. }