BaseUtil.cs 17 KB

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