BaseUtil.cs 26 KB

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