BaseUtil.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. using SpeechLib;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.IO;
  6. using System.Net;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Web.Script.Serialization;
  10. using System.Windows.Forms;
  11. using System.Xml;
  12. using static System.Windows.Forms.Control;
  13. namespace FileWatcher
  14. {
  15. class BaseUtil
  16. {
  17. public static void ShowError(string errorMessage)
  18. {
  19. throw new Exception(errorMessage);
  20. }
  21. public static string AddField(string[] Fields)
  22. {
  23. string sql = " ";
  24. foreach (string field in Fields)
  25. sql += field + ",";
  26. return sql.Substring(0, sql.Length - 1);
  27. }
  28. static int SortByIndex(Control A, Control B)
  29. {
  30. return A.TabIndex.CompareTo(B.TabIndex);
  31. }
  32. public static void PlaySound(string FileName)
  33. {
  34. SpVoice voice = new SpVoice();
  35. voice.Speak(FileName, SpeechVoiceSpeakFlags.SVSFDefault);
  36. }
  37. public static void SetFormValue(ControlCollection collection, DataTable dt)
  38. {
  39. List<Control> ctl = new List<Control>();
  40. //将控件按照索引排序
  41. for (int i = 0; i < collection.Count; i++)
  42. {
  43. for (int j = 0; j < ctl.Count; j++)
  44. {
  45. if (!ctl.Contains(collection[i]))
  46. {
  47. if (collection[i].TabIndex > ctl[j].TabIndex)
  48. {
  49. ctl.Add(collection[i]);
  50. break;
  51. }
  52. else
  53. {
  54. ctl.Insert(j, collection[i]);
  55. break;
  56. }
  57. }
  58. }
  59. if (ctl.Count == 0)
  60. {
  61. ctl.Add(collection[i]);
  62. }
  63. }
  64. ctl.Sort(SortByIndex);
  65. //DataTable存在数据才进行赋值操作
  66. if (dt.Rows.Count > 0)
  67. {
  68. for (int i = 0; i < ctl.Count; i++)
  69. {
  70. //如果含有子控件则进行递归调用
  71. if (ctl[i].Controls.Count > 0)
  72. SetFormValue(ctl[i].Controls, dt);
  73. string controlName = ctl[i].Name;
  74. string controlsTag = ctl[i].Tag == null ? "" : ctl[i].Tag.ToString();
  75. //默认给TextBox和Label赋值
  76. if (ctl[i] is TextBox || ctl[i] is Label || ctl[i] is SearchTextBox || ctl[i] is EnterTextBox || ctl[i] is NumericUpDown || ctl[i] is RichTextBox)
  77. {
  78. for (int j = 0; j < dt.Columns.Count; j++)
  79. {
  80. if (controlName.ToUpper() == dt.Columns[j].Caption.ToUpper() || controlsTag.ToUpper() == dt.Columns[j].Caption.ToUpper())
  81. {
  82. //字段含有Status内容的才进行转换
  83. if (controlName.ToUpper().Contains("STATUS") || controlsTag.ToUpper().Contains("STATUS"))
  84. {
  85. //对审批状态进行判断
  86. switch (dt.Rows[0][j].ToString().ToUpper())
  87. {
  88. case "ENTERING":
  89. ctl[i].Text = "在录入";
  90. break;
  91. case "UNAPPROVED":
  92. ctl[i].Text = "未批准";
  93. break;
  94. case "COMMITED":
  95. ctl[i].Text = "已提交";
  96. break;
  97. case "APPROVE":
  98. ctl[i].Text = "已批准";
  99. break;
  100. case "AUDITED":
  101. ctl[i].Text = "已审核";
  102. break;
  103. case "STARTED":
  104. ctl[i].Text = "已下放";
  105. break;
  106. case "UNCHECK":
  107. ctl[i].Text = "待检验";
  108. break;
  109. case "CHECKING":
  110. ctl[i].Text = "检验中";
  111. break;
  112. default:
  113. ctl[i].Text = dt.Rows[0][j].ToString();
  114. break;
  115. }
  116. }
  117. else
  118. ctl[i].Text = dt.Rows[0][j].ToString();
  119. }
  120. }
  121. }
  122. //对封装在GroupBox的和Panel的控件进行批量赋值
  123. if (ctl[i] is GroupBox || ctl[i] is Panel)
  124. {
  125. for (int j = 0; j < ctl[i].Controls.Count; j++)
  126. {
  127. controlName = ctl[i].Controls[j].Name;
  128. if (ctl[i].Controls[j] is TextBox || ctl[i].Controls[j] is Label || ctl[i].Controls[j] is SearchTextBox)
  129. {
  130. for (int k = 0; k < dt.Columns.Count; k++)
  131. {
  132. if (controlName.ToUpper() == dt.Columns[k].Caption.ToUpper())
  133. {
  134. ctl[i].Controls[j].Text = dt.Rows[0][k].ToString();
  135. }
  136. }
  137. }
  138. }
  139. }
  140. }
  141. }
  142. //如果没有记录的话,将dt中含有的列的对应值设置为空
  143. else
  144. {
  145. for (int i = 0; i < ctl.Count; i++)
  146. {
  147. if (ctl[i] is TextBox || ctl[i] is Label || ctl[i] is SearchTextBox)
  148. {
  149. for (int j = 0; j < dt.Columns.Count; j++)
  150. {
  151. if (ctl[i].Name.ToUpper() == dt.Columns[j].Caption.ToUpper())
  152. {
  153. ctl[i].Text = "";
  154. }
  155. }
  156. }
  157. }
  158. }
  159. }
  160. public static string GetScreenSqlCondition(params Control[] Condition)
  161. {
  162. string condition = "";
  163. //用于统计传入的控件的空值数
  164. int EmptyControlCount = 0;
  165. for (int i = 0; i < Condition.Length; i++)
  166. {
  167. //如果Text不为空再进行条件的拼接
  168. if (Condition[i].Text != "")
  169. {
  170. if (Condition[i] is ComboBox)
  171. {
  172. condition += "(" + Condition[i].Tag + " like " + "'%" + (Condition[i] as ComboBox).SelectedValue + "%' )";
  173. }
  174. else
  175. {
  176. condition += "(" + Condition[i].Tag + " like " + "'%" + Condition[i].Text + "%' )";
  177. }
  178. //如果不是最后要判断之后有没有空值的如果有一个Text的值不为空都需要添加and
  179. //添加了一次And之后跳出循环,因为如果后面多项有值会重复添加and
  180. for (int j = i + 1; j < Condition.Length; j++)
  181. {
  182. if (j < Condition.Length)
  183. {
  184. if (Condition[j].Text != "")
  185. {
  186. condition += " and ";
  187. break;
  188. }
  189. }
  190. }
  191. }
  192. else
  193. {
  194. EmptyControlCount = EmptyControlCount + 1;
  195. }
  196. }
  197. //如果所有的控件传入的都是空值则返回也为空
  198. if (EmptyControlCount == Condition.Length)
  199. return "";
  200. else
  201. condition = " where " + condition;
  202. return condition;
  203. }
  204. public static void CreateXml(string iSN, string iTestResult)
  205. {
  206. //创建XML文档
  207. FileStream fcaches = new FileStream(iSN + ".xml", FileMode.OpenOrCreate, FileAccess.ReadWrite);
  208. fcaches.Close();
  209. FileInfo info = new FileInfo(iSN + ".xml");
  210. if (info.Length == 0)
  211. {
  212. XmlDocument doc = new XmlDocument();
  213. //创建类型声明节点
  214. XmlNode node = doc.CreateXmlDeclaration("1.0", "utf-8", "");
  215. doc.AppendChild(node);
  216. //创建根节点
  217. XmlElement xeRoot = doc.CreateElement("cacheInfo");
  218. doc.AppendChild(xeRoot);
  219. doc.Save(iSN + ".xml");
  220. }
  221. }
  222. public static void FillDgvWithDataTable(DataGridView dgv, DataTable dt, params DataGridViewImageColumn[] operate)
  223. {
  224. dgv.AutoGenerateColumns = false;
  225. dgv.DataSource = dt;
  226. if (operate.Length > 0)
  227. {
  228. if (dgv.Columns[operate[0].Name] != null)
  229. {
  230. dgv.Columns.Remove(dgv.Columns[operate[0].Name]);
  231. }
  232. dgv.Columns.Add(operate[0]);
  233. }
  234. ////纯英文的列不予展示
  235. //Regex regEnglish = new Regex("^[A-z]+$");
  236. //foreach (DataGridViewColumn dgvc in dgv.Columns)
  237. //{
  238. // if (regEnglish.IsMatch(dgvc.HeaderText))
  239. // {
  240. // dgvc.Visible = false;
  241. // }
  242. //}
  243. }
  244. public static string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic, out string fp_path, out string fp_id)
  245. {
  246. fp_id = "";
  247. fp_path = "";
  248. try
  249. {
  250. ServicePointManager.DefaultConnectionLimit = 50;
  251. string boundary = DateTime.Now.Ticks.ToString("x");
  252. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  253. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  254. request.Method = "POST";
  255. request.Timeout = 10 * 10000;
  256. request.ContentType = "multipart/form-data; boundary=" + boundary;
  257. Stream rs = request.GetRequestStream();
  258. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  259. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  260. if (dic != null)
  261. {
  262. foreach (string key in dic.Keys)
  263. {
  264. rs.Write(boundarybytes, 0, boundarybytes.Length);
  265. string formitem = string.Format(formdataTemplate, key, dic[key]);
  266. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  267. rs.Write(formitembytes, 0, formitembytes.Length);
  268. }
  269. }
  270. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  271. {
  272. rs.Write(boundarybytes, 0, boundarybytes.Length);
  273. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  274. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  275. rs.Write(headerbytes, 0, headerbytes.Length);
  276. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  277. {
  278. var buffer = new byte[1024];
  279. var bytesRead = 0;
  280. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  281. {
  282. rs.Write(buffer, 0, bytesRead);
  283. }
  284. }
  285. var cr = Encoding.UTF8.GetBytes("\r\n");
  286. rs.Write(cr, 0, cr.Length);
  287. }
  288. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  289. var response = request.GetResponse() as HttpWebResponse;
  290. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  291. string Content = newReader.ReadToEnd();
  292. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  293. List<Dictionary<string, object>> dic2 = null;
  294. dic1 = BaseUtil.ToDictionary(Content);
  295. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  296. if (dic2[0]["filepath"] != null)
  297. {
  298. fp_id = dic2[0]["filepath"].ToString();
  299. fp_path = dic2[0]["path"].ToString();
  300. }
  301. if (response.StatusCode == HttpStatusCode.OK)
  302. {
  303. Console.WriteLine(fp_id);
  304. return fp_id;
  305. }
  306. }
  307. catch (Exception e)
  308. {
  309. Console.WriteLine(e.Message + e.StackTrace);
  310. }
  311. return "";
  312. }
  313. public static Dictionary<string, object> ToDictionary(string JsonData)
  314. {
  315. object Data = null;
  316. Dictionary<string, object> Dic = new Dictionary<string, object>();
  317. if (JsonData.StartsWith("["))
  318. {
  319. //如果目标直接就为数组类型,则将会直接输出一个Key为List的List<Dictionary<string, object>>集合
  320. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["List"];
  321. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  322. MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  323. foreach (Match ListItem in ListMatch)
  324. {
  325. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  326. }
  327. Data = List;
  328. Dic.Add("List", Data);
  329. }
  330. else
  331. {
  332. MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值
  333. foreach (Match item in Match)
  334. {
  335. try
  336. {
  337. if (item.Groups[2].ToString().StartsWith("["))
  338. {
  339. //如果目标是数组,将会输出一个Key为当前Json的List<Dictionary<string, object>>集合
  340. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["Json中的Key"];
  341. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  342. MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  343. foreach (Match ListItem in ListMatch)
  344. {
  345. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  346. }
  347. Data = List;
  348. }
  349. else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null
  350. else Data = item.Groups[2].ToString(); //数据为数字、字符串中的一类,直接写入
  351. Dic.Add(item.Groups[1].ToString(), Data);
  352. }
  353. catch { }
  354. }
  355. }
  356. return Dic;
  357. }
  358. public static Dictionary<string, object> ToDictionary(string JsonData, string Type)
  359. {
  360. //实例化JavaScriptSerializer类的新实例
  361. JavaScriptSerializer jss = new JavaScriptSerializer();
  362. try
  363. {
  364. //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
  365. return jss.Deserialize<Dictionary<string, object>>(JsonData);
  366. }
  367. catch (Exception ex)
  368. {
  369. throw new Exception(ex.Message);
  370. }
  371. }
  372. public static object GetCacheData(string ParamName)
  373. {
  374. try
  375. {
  376. object returnData = null;
  377. //根据地址读取xml文件
  378. XmlDocument doc = new XmlDocument();
  379. XmlReaderSettings settings = new XmlReaderSettings();
  380. //忽略文档里面的注释
  381. settings.IgnoreComments = true;
  382. XmlReader reader = XmlReader.Create(AutoAnalysisXml.CachePath, settings);
  383. doc.Load(reader);
  384. //先得到根节点
  385. XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
  386. //再由根节点去找制定的节点
  387. XmlNodeList nodeList = rootNode.ChildNodes;
  388. foreach (XmlNode node in nodeList)
  389. {
  390. //找到了这个节点名字
  391. if (node.Name == ParamName)
  392. {
  393. //返回节点的内容
  394. switch (((XmlElement)node).GetAttribute("Type"))
  395. {
  396. case "System.String":
  397. returnData = node.InnerText;
  398. break;
  399. case "System.Int32":
  400. returnData = int.Parse(node.InnerText);
  401. break;
  402. case "System.Boolean":
  403. returnData = node.InnerText == "True" ? true : false;
  404. break;
  405. default:
  406. break;
  407. }
  408. break;
  409. }
  410. }
  411. //关闭reader
  412. reader.Close();
  413. if (returnData == null)
  414. return "";
  415. else
  416. return returnData;
  417. }
  418. catch (Exception e)
  419. {
  420. Console.WriteLine(e.Message + e.StackTrace);
  421. return "";
  422. }
  423. }
  424. public static void SetCacheData(string ParamName, object Value)
  425. {
  426. try
  427. {
  428. //根据地址读取xml文件
  429. XmlDocument doc = new XmlDocument();
  430. XmlReaderSettings settings = new XmlReaderSettings();
  431. //忽略文档里面的注释
  432. settings.IgnoreComments = true;
  433. XmlReader reader = XmlReader.Create(AutoAnalysisXml.CachePath, settings);
  434. doc.Load(reader);
  435. //先得到根节点
  436. XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
  437. //再由根节点去找制定的节点
  438. XmlNodeList nodeList = rootNode.ChildNodes;
  439. bool flag = false;
  440. foreach (XmlNode node in nodeList)
  441. {
  442. //找到了这个节点名字
  443. if (node.Name == ParamName)
  444. {
  445. //就直接赋值
  446. node.InnerText = Value.ToString();
  447. flag = true;
  448. }
  449. }
  450. //如果没有该节点,就创建节点保存结果
  451. if (!flag)
  452. {
  453. //创建节点
  454. XmlElement newNode = doc.CreateElement(ParamName);
  455. XmlAttribute attr = doc.CreateAttribute("Type");
  456. attr.InnerText = Value.GetType().ToString();
  457. newNode.InnerText = Value.ToString();
  458. newNode.SetAttributeNode(attr);
  459. //讲新建的节点挂到根节点上
  460. rootNode.AppendChild(newNode);
  461. }
  462. //关闭Reader
  463. reader.Close();
  464. doc.Save(AutoAnalysisXml.CachePath);
  465. }
  466. catch (Exception ex)
  467. {
  468. Console.WriteLine(ex.Message + ex.StackTrace);
  469. }
  470. }
  471. public void Speak(string text)
  472. {
  473. }
  474. //播放音频文件
  475. public static void GetWriteInfo(string FilePath, out Dictionary<string, string> Dic)
  476. {
  477. Dic = new Dictionary<string, string>();
  478. string txt = "";
  479. StreamReader sr = new StreamReader(FilePath);
  480. while (!sr.EndOfStream)
  481. {
  482. string str = sr.ReadLine();
  483. txt += str + "\n";
  484. }
  485. sr.Close();
  486. sr.Dispose();
  487. Dic.Add("atd_sncode", FilePath.Substring(FilePath.LastIndexOf("\\") + 1).Replace(".txt", ""));
  488. Dic.Add("atd_software", Regex.Match(txt, "Program Name,\\S+").Value.Replace("Program Name,", ""));
  489. Dic.Add("atd_pot", Regex.Match(txt, "Board Segment,\\S+").Value.Replace("Board Segment,", ""));
  490. Dic.Add("atd_size", Regex.Match(txt, "Baord Size \\(L x W\\) \\[mm\\],\\S+").Value.Replace("Baord Size (L x W) [mm],", ""));
  491. Dic.Add("atd_pot1set", Regex.Match(txt, "Pot-1 Set Temp. \\[deg],\\S+").Value.Replace("Pot-1 Set Temp. [deg],", ""));
  492. Dic.Add("atd_pot2set", Regex.Match(txt, "Pot-2 Set Temp. \\[deg],\\S+").Value.Replace("Pot-2 Set Temp. [deg],", ""));
  493. Dic.Add("atd_pot1avgtemp", Regex.Match(txt, "Pot-1 Avg. Temp. \\[deg],\\S+").Value.Replace("Pot-1 Avg. Temp. [deg],", ""));
  494. Dic.Add("atd_pot2avgtemp", Regex.Match(txt, "Pot-2 Avg. Temp. \\[deg],\\S+").Value.Replace("Pot-2 Avg. Temp. [deg],", ""));
  495. Dic.Add("atd_boardtime", Regex.Match(txt, "Machine Duration \\[s],\\S+").Value.Replace("Machine Duration [s],", ""));
  496. //开始时间
  497. MatchCollection starttime = Regex.Matches(txt, "Start TimeStamp,\\S+ \\S+");
  498. for (int i = 0; i < starttime.Count; i++)
  499. {
  500. switch (i)
  501. {
  502. case 0:
  503. Dic.Add("atd_boardstarttime", starttime[i].Value.Replace("Start TimeStamp,", ""));
  504. break;
  505. case 1:
  506. Dic.Add("atd_flstarttime", starttime[i].Value.Replace("Start TimeStamp,", ""));
  507. break;
  508. case 2:
  509. Dic.Add("atd_phstarttime", starttime[i].Value.Replace("Start TimeStamp,", ""));
  510. break;
  511. case 3:
  512. Dic.Add("atd_sostarttime", starttime[i].Value.Replace("Start TimeStamp,", ""));
  513. break;
  514. default:
  515. break;
  516. }
  517. }
  518. MatchCollection endtime = Regex.Matches(txt, "End TimeStamp,\\S+ \\S+");
  519. for (int i = 0; i < starttime.Count; i++)
  520. {
  521. switch (i)
  522. {
  523. case 0:
  524. Dic.Add("atd_boardendtime", endtime[i].Value.Replace("End TimeStamp,", ""));
  525. break;
  526. case 1:
  527. Dic.Add("atd_flendtime", endtime[i].Value.Replace("End TimeStamp,", ""));
  528. break;
  529. case 2:
  530. Dic.Add("atd_phendtime", endtime[i].Value.Replace("End TimeStamp,", ""));
  531. break;
  532. case 3:
  533. Dic.Add("atd_soendtime", endtime[i].Value.Replace("End TimeStamp,", ""));
  534. break;
  535. default:
  536. break;
  537. }
  538. }
  539. MatchCollection duration = Regex.Matches(txt, "Total Zone Duration \\[s],\\S+");
  540. for (int i = 0; i < starttime.Count; i++)
  541. {
  542. switch (i)
  543. {
  544. case 0:
  545. Dic.Add("atd_fltime", duration[i].Value.Replace("Total Zone Duration [s],", ""));
  546. break;
  547. case 1:
  548. Dic.Add("atd_phtime", duration[i].Value.Replace("Total Zone Duration [s],", ""));
  549. break;
  550. case 2:
  551. Dic.Add("atd_sotime", duration[i].Value.Replace("Total Zone Duration [s],", ""));
  552. break;
  553. default:
  554. break;
  555. }
  556. }
  557. }
  558. }
  559. }