AutoAnalysisDevice.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. using Microsoft.Win32;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.IO;
  6. using System.Threading;
  7. using System.Windows.Forms;
  8. using System.Xml;
  9. using System.Text;
  10. using System.Net;
  11. using System.Net.Sockets;
  12. using System.Text.RegularExpressions;
  13. namespace FileWatcher
  14. {
  15. public partial class AutoAnalysisDevice : Form
  16. {
  17. DataHelper dh;
  18. DataTable dt;
  19. DataTable DB;
  20. /// <summary>
  21. /// 用户编号
  22. /// </summary>
  23. string iusercode;
  24. /// <summary>
  25. /// 岗位资源
  26. /// </summary>
  27. string isource;
  28. Tip tipform;
  29. Thread InitDB;
  30. /// <summary>
  31. /// 线别
  32. /// </summary>
  33. string ilinecode;
  34. /// <summary>
  35. /// 不良代码组
  36. /// </summary>
  37. string ibadgroup;
  38. /// <summary>
  39. /// 当前工序
  40. /// </summary>
  41. string istepcode;
  42. StringBuilder sql = new StringBuilder();
  43. /// <summary>
  44. /// 缓存的文件
  45. /// </summary>
  46. public static string CachePath = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/Cache.xml";
  47. /// <summary>
  48. /// 缓存的文件夹
  49. /// </summary>
  50. public static string CachePathFolder = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/";
  51. /// <summary>
  52. /// 需要解析的文件名
  53. /// </summary>
  54. List<string> _FileName = new List<string>();
  55. string master = "WKS";
  56. ftpOperater ftp = new ftpOperater();
  57. public AutoAnalysisDevice()
  58. {
  59. tipform = new Tip();
  60. InitializeComponent();
  61. StartPosition = FormStartPosition.CenterScreen;
  62. }
  63. public AutoAnalysisDevice(string iUserName, string iSource, string iMaster)
  64. {
  65. tipform = new Tip();
  66. InitializeComponent();
  67. iusercode = iUserName;
  68. isource = iSource.ToUpper();
  69. master = iMaster;
  70. StartPosition = FormStartPosition.CenterScreen;
  71. }
  72. string IPAddress = "";
  73. private void Form1_Load(object sender, EventArgs e)
  74. {
  75. tipform.Show();
  76. CheckForIllegalCrossThreadCalls = false;
  77. FormBorderStyle = FormBorderStyle.FixedSingle;
  78. InitDB = new Thread(ConnectDB);
  79. //添加监控事件
  80. XmlWatcher.Changed += new FileSystemEventHandler(XmlWatcher_Created);
  81. //ATEFile.Changed += new FileSystemEventHandler(XmlWatcher_Created);
  82. SetLoadingWindow stw = new SetLoadingWindow(InitDB, "正在启动程序");
  83. stw.StartPosition = FormStartPosition.CenterScreen;
  84. stw.ShowDialog();
  85. List<string> CacheInf = new List<string>();
  86. IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
  87. for (int i = 0; i < IpEntry.AddressList.Length; i++)
  88. {
  89. if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
  90. IPAddress = IpEntry.AddressList[i].ToString();
  91. }
  92. //获取缓存信息
  93. try
  94. {
  95. FolderPath.Text = BaseUtil.GetCacheData("FolderPath").ToString();
  96. Device.Text = BaseUtil.GetCacheData("Device").ToString();
  97. //BackUpFolderPath.Text = BaseUtil.GetCacheData("BackUpFolderPath").ToString();
  98. //Master.Text = BaseUtil.GetCacheData("Master").ToString();
  99. //AutoStart.Checked = (bool)BaseUtil.GetCacheData("AutoStart");
  100. }
  101. catch (Exception ex) { MessageBox.Show(ex.Message); }
  102. //获取岗位资源相关信息
  103. DataTable dt = (DataTable)dh.ExecuteSql("select sc_linecode,sc_stepcode,st_badgroupcode from source left join step on sc_stepcode=st_code where sc_code='" + isource + "'", "select");
  104. if (dt.Rows.Count > 0)
  105. {
  106. ilinecode = dt.Rows[0]["sc_linecode"].ToString();
  107. istepcode = dt.Rows[0]["sc_stepcode"].ToString();
  108. ibadgroup = dt.Rows[0]["st_badgroupcode"].ToString();
  109. }
  110. StartWatch.PerformClick();
  111. }
  112. private void ConnectDB()
  113. {
  114. DataHelper.DBConnectionString = "Connection Timeout=0;Pooling=false;Password=select!#%*(;User ID=N_MES;Pooling=false;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.6.253)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl)));";
  115. dh = new DataHelper();
  116. }
  117. private void StartWatch_Click(object sender, EventArgs e)
  118. {
  119. if (FolderPath.Text == "")
  120. {
  121. OperateResult.AppendText("请选择监控文件夹\n");
  122. return;
  123. }
  124. else
  125. {
  126. if (!Directory.Exists(FolderPath.Text))
  127. {
  128. OperateResult.AppendText("监控文件夹不存在\n");
  129. return;
  130. }
  131. }
  132. XmlWatcher.Path = FolderPath.Text;
  133. XmlWatcher.EnableRaisingEvents = true;
  134. XmlWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
  135. //ATEFile.Path = FolderPath.Text;
  136. //ATEFile.EnableRaisingEvents = true;
  137. //ATEFile.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
  138. //设置缓存数据
  139. BaseUtil.SetCacheData("FolderPath", FolderPath.Text);
  140. BaseUtil.SetCacheData("Device", Device.Text);
  141. //BaseUtil.SetCacheData("BackUpFolderPath", BackUpFolderPath.Text);
  142. //BaseUtil.SetCacheData("Master", Master.Text);
  143. //BaseUtil.SetCacheData("AutoStart", AutoStart.Checked);
  144. Timer.Interval = 1000 * 60;
  145. Timer.Start();
  146. //设置按钮不可点击
  147. StartWatch.Enabled = false;
  148. ChooseFolder.Enabled = false;
  149. Master.Enabled = false;
  150. ma_code.Enabled = false;
  151. StopWatch.Enabled = true;
  152. OperateResult.AppendText("开始执行监控\n");
  153. }
  154. private void XmlWatcher_Created(object sender, FileSystemEventArgs e)
  155. {
  156. OperateResult.AppendText("文件修改:" + e.FullPath + "\n");
  157. TxtHandleProcess(e.FullPath);
  158. }
  159. string nextLine;
  160. private void TxtHandleProcess(string FileName)
  161. {
  162. List<string> badcode = new List<string>();
  163. List<string> badlocation = new List<string>();
  164. List<string> badprod = new List<string>();
  165. if (Device.Text == "老化设备")
  166. {
  167. StreamReader sR = new StreamReader(FileName, Encoding.Default);
  168. Console.WriteLine(sR.CurrentEncoding);
  169. DataTable filedt = new DataTable();
  170. //文件内的行,用一个DataTable存储
  171. int Rowindex = 0;
  172. while ((nextLine = sR.ReadLine()) != null)
  173. {
  174. //DataTable用第一行的数据作为列名
  175. string[] title = nextLine.Split(',');
  176. DataRow dr = filedt.NewRow();
  177. for (int i = 0; i < title.Length; i++)
  178. {
  179. if (Rowindex == 0)
  180. {
  181. switch (i)
  182. {
  183. case 0:
  184. filedt.Columns.Add("区域");
  185. break;
  186. case 1:
  187. filedt.Columns.Add("产品代码");
  188. break;
  189. case 2:
  190. filedt.Columns.Add("上架时间");
  191. break;
  192. case 3:
  193. filedt.Columns.Add("下架时间");
  194. break;
  195. case 4:
  196. filedt.Columns.Add("上架数量");
  197. break;
  198. case 5:
  199. filedt.Columns.Add("合格数量");
  200. break;
  201. case 6:
  202. filedt.Columns.Add("不良数量");
  203. break;
  204. case 7:
  205. filedt.Columns.Add("文件路径");
  206. break;
  207. default:
  208. break;
  209. }
  210. }
  211. dr[filedt.Columns[i].ColumnName] = title[i];
  212. }
  213. filedt.Rows.Add(dr);
  214. Rowindex = Rowindex + 1;
  215. }
  216. sR.Close();
  217. OperateResult.AppendText("文件修改" + filedt.Rows.Count + "\n");
  218. for (int i = 0; i < filedt.Rows.Count; i++)
  219. {
  220. if (!dh.CheckExist("Devicetestinfo", "(dti_uptime)=to_date('" + filedt.Rows[i]["上架时间"].ToString() + "','yyyy/mm/dd hh24:mi:ss') and dti_ipaddress='" + IPAddress + "'"))
  221. {
  222. string filename = filedt.Rows[i]["文件路径"].ToString();
  223. Dictionary<string, object> dic = new Dictionary<string, object>
  224. {
  225. { "em_name", "管理员" },
  226. { "em_code", "ADMIN" },
  227. { "caller", "AGING" }
  228. };
  229. string fp_id;
  230. string fp_path;
  231. UploadFilesToRemoteUrl("http://192.168.6.253:8099/mes/MEScommon/uploadFiles.action?_noc=1", filename, dic, out fp_path, out fp_id);
  232. fp_path = "http://192.168.6.253:8099/" + fp_path.Replace("/app/uas/webapps/", "");
  233. fp_path = fp_path.Replace("\"", "");
  234. dh.ExecuteSql("insert into Devicetestinfo(dti_id,dti_prodcode,dti_area,dti_uptime,dti_downtime,dti_upqty,dti_okqty,dti_ngqty,dti_ipaddress,dti_filepath,dti_indate,dti_fpid,dti_type)values(Devicetestinfo_seq.nextval,'" + filedt.Rows[i]["产品代码"].ToString() + "','" + filedt.Rows[i]["区域"].ToString() + "',to_date('" + filedt.Rows[i]["上架时间"].ToString() + "','yyyy/mm/dd hh24:mi:ss'),to_date('" + filedt.Rows[i]["下架时间"].ToString() + "','yyyy/mm/dd hh24:mi:ss'),'" + filedt.Rows[i]["上架数量"].ToString() + "','" + filedt.Rows[i]["合格数量"].ToString() + "','" + filedt.Rows[i]["不良数量"].ToString() + "','" + IPAddress + "','" + fp_path + "',sysdate,'" + fp_id + "','老化')", "insert");
  235. OperateResult.AppendText("上传文件" + filename + "\n");
  236. }
  237. }
  238. }
  239. else if (Device.Text == "ATE设备")
  240. {
  241. if (!FileName.Contains("ATE日志文件")) {
  242. return;
  243. }
  244. StreamReader sR = new StreamReader(FileName, Encoding.Default);
  245. Console.WriteLine(sR.CurrentEncoding);
  246. DataTable filedt = new DataTable();
  247. //文件内的行,用一个DataTable存储
  248. int Rowindex = 0;
  249. while ((nextLine = sR.ReadLine()) != null)
  250. {
  251. //DataTable用第一行的数据作为列名
  252. string[] title = nextLine.Split(',');
  253. DataRow dr = filedt.NewRow();
  254. for (int i = 0; i < title.Length; i++)
  255. {
  256. if (Rowindex == 0)
  257. {
  258. switch (i)
  259. {
  260. case 0:
  261. filedt.Columns.Add("登录的账号");
  262. break;
  263. case 1:
  264. filedt.Columns.Add("工位固定号");
  265. break;
  266. case 2:
  267. filedt.Columns.Add("产品代码");
  268. break;
  269. case 3:
  270. filedt.Columns.Add("计划单号");
  271. break;
  272. case 4:
  273. filedt.Columns.Add("使用参数名");
  274. break;
  275. case 5:
  276. filedt.Columns.Add("通道");
  277. break;
  278. case 6:
  279. filedt.Columns.Add("开始时间");
  280. break;
  281. case 7:
  282. filedt.Columns.Add("结束时间");
  283. break;
  284. case 8:
  285. filedt.Columns.Add("上架数量");
  286. break;
  287. case 9:
  288. filedt.Columns.Add("合格数量");
  289. break;
  290. case 10:
  291. filedt.Columns.Add("不良数量");
  292. break;
  293. case 11:
  294. filedt.Columns.Add("文件路径");
  295. break;
  296. default:
  297. break;
  298. }
  299. }
  300. dr[filedt.Columns[i].ColumnName] = title[i];
  301. }
  302. filedt.Rows.Add(dr);
  303. Rowindex = Rowindex + 1;
  304. }
  305. sR.Close();
  306. OperateResult.AppendText("文件修改" + filedt.Rows.Count + "\n");
  307. for (int i = 0; i < filedt.Rows.Count; i++)
  308. {
  309. if (!dh.CheckExist("Devicetestinfo", "(dti_uptime)=to_date('" + filedt.Rows[i]["开始时间"].ToString() + "','yyyy/mm/dd hh24:mi:ss') and dti_ipaddress='" + IPAddress + "'"))
  310. {
  311. string filename = filedt.Rows[i]["文件路径"].ToString();
  312. Dictionary<string, object> dic = new Dictionary<string, object>
  313. {
  314. { "em_name", "管理员" },
  315. { "em_code", "ADMIN" },
  316. { "caller", "AGING" }
  317. };
  318. string fp_id;
  319. string fp_path;
  320. UploadFilesToRemoteUrl("http://192.168.6.253:8099/mes/MEScommon/uploadFiles.action?_noc=1", filename, dic, out fp_path, out fp_id);
  321. fp_path = "http://192.168.6.253:8099/" + fp_path.Replace("/app/uas/webapps/", "");
  322. fp_path = fp_path.Replace("\"", "");
  323. dh.ExecuteSql("insert into Devicetestinfo(dti_id,dti_prodcode,dti_uptime,dti_downtime,dti_upqty,dti_okqty,dti_ngqty,dti_ipaddress,dti_filepath,dti_indate,dti_fpid,dti_account,dti_stepcode,dti_makecode,dti_param,dti_route,dti_type)values(Devicetestinfo_seq.nextval,'" + filedt.Rows[i]["产品代码"].ToString() + "',to_date('" + filedt.Rows[i]["开始时间"].ToString() + "','yyyy/mm/dd hh24:mi:ss'),to_date('" + filedt.Rows[i]["结束时间"].ToString() + "','yyyy/mm/dd hh24:mi:ss'),'" + filedt.Rows[i]["上架数量"].ToString() + "','" + filedt.Rows[i]["合格数量"].ToString() + "','" + filedt.Rows[i]["不良数量"].ToString() + "','" + IPAddress + "','" + fp_path + "',sysdate,'" + fp_id + "','" + filedt.Rows[i]["登录的账号"].ToString() + "','" + filedt.Rows[i]["工位固定号"].ToString() + "','" + filedt.Rows[i]["计划单号"].ToString() + "','" + filedt.Rows[i]["使用参数名"].ToString() + "','" + filedt.Rows[i]["通道"].ToString() + "','ATE')", "insert");
  324. OperateResult.AppendText("上传文件" + filename + "\n");
  325. }
  326. }
  327. }
  328. }
  329. private void StopWatch_Click(object sender, EventArgs e)
  330. {
  331. XmlWatcher.EnableRaisingEvents = false;
  332. StartWatch.Enabled = true;
  333. ma_code.Enabled = true;
  334. Master.Enabled = true;
  335. ChooseFolder.Enabled = true;
  336. StopWatch.Enabled = false;
  337. OperateResult.AppendText("停止执行监控\n");
  338. }
  339. private void Clean_Click(object sender, EventArgs e)
  340. {
  341. OperateResult.Clear();
  342. }
  343. private void ChooseFolder_Click(object sender, EventArgs e)
  344. {
  345. FolderBrowserDialog folder = new FolderBrowserDialog();
  346. folder.Description = "选择监控文件夹";
  347. DialogResult result = folder.ShowDialog();
  348. if (result == DialogResult.OK)
  349. {
  350. FolderPath.Text = folder.SelectedPath;
  351. }
  352. }
  353. private void ChooseBackUpFolder_Click(object sender, EventArgs e)
  354. {
  355. FolderBrowserDialog folder = new FolderBrowserDialog();
  356. folder.Description = "选择备份文件夹";
  357. DialogResult result = folder.ShowDialog();
  358. if (result == DialogResult.OK)
  359. {
  360. }
  361. }
  362. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  363. {
  364. string ExitConfirm = MessageBox.Show(this, "确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
  365. if (ExitConfirm != "Yes")
  366. {
  367. WindowState = FormWindowState.Minimized;
  368. e.Cancel = true;
  369. }
  370. }
  371. private void AutoStart_CheckedChanged(object sender, EventArgs e)
  372. {
  373. SetAutoRun();
  374. }
  375. private void SetAutoRun()
  376. {
  377. if (AutoStart.Checked) //设置开机自启动
  378. {
  379. string path = Application.ExecutablePath;
  380. RegistryKey rk = Registry.LocalMachine;
  381. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  382. rk2.SetValue("FileWatcher.exe", path);
  383. rk2.Close();
  384. rk.Close();
  385. }
  386. else //取消开机自启动
  387. {
  388. string path = Application.ExecutablePath;
  389. RegistryKey rk = Registry.LocalMachine;
  390. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  391. rk2.DeleteValue("FileWatcher.exe", false);
  392. rk2.Close();
  393. rk.Close();
  394. }
  395. }
  396. private void BatchAnalysus_Click(object sender, EventArgs e)
  397. {
  398. TxtHandleProcess(@"C:\Users\callm\Desktop\导入数据\客户资料\睿德电子\新建文本文档.log");
  399. //TxtHandleProcess(@"C:\Users\callm\Desktop\导入数据\客户资料\睿德电子\PowerTestTj.ini");
  400. }
  401. private void Timer_Tick(object sender, EventArgs e)
  402. {
  403. var AllXmls = Directory.GetFiles(FolderPath.Text, "*.txt");
  404. foreach (var Xml in AllXmls)
  405. {
  406. TxtHandleProcess(Xml);
  407. }
  408. }
  409. /// <summary>
  410. /// 请求上传图片到阿里云
  411. /// </summary>
  412. /// <param name="url">上传地址</param>
  413. /// <param name="filepath">本地文件路径</param>
  414. /// <param name="dic">上传的数据信息</param>
  415. /// <returns></returns>
  416. public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic, out string fp_path, out string fp_id)
  417. {
  418. fp_id = "";
  419. fp_path = "";
  420. try
  421. {
  422. ServicePointManager.DefaultConnectionLimit = 50;
  423. string boundary = DateTime.Now.Ticks.ToString("x");
  424. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  425. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  426. request.Method = "POST";
  427. request.Timeout = 10 * 10000;
  428. request.ContentType = "multipart/form-data; boundary=" + boundary;
  429. Stream rs = request.GetRequestStream();
  430. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  431. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  432. if (dic != null)
  433. {
  434. foreach (string key in dic.Keys)
  435. {
  436. rs.Write(boundarybytes, 0, boundarybytes.Length);
  437. string formitem = string.Format(formdataTemplate, key, dic[key]);
  438. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  439. rs.Write(formitembytes, 0, formitembytes.Length);
  440. }
  441. }
  442. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  443. {
  444. rs.Write(boundarybytes, 0, boundarybytes.Length);
  445. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  446. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  447. rs.Write(headerbytes, 0, headerbytes.Length);
  448. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  449. {
  450. var buffer = new byte[1024];
  451. var bytesRead = 0;
  452. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  453. {
  454. rs.Write(buffer, 0, bytesRead);
  455. }
  456. }
  457. var cr = Encoding.UTF8.GetBytes("\r\n");
  458. rs.Write(cr, 0, cr.Length);
  459. }
  460. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  461. var response = request.GetResponse() as HttpWebResponse;
  462. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  463. string Content = newReader.ReadToEnd();
  464. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  465. List<Dictionary<string, object>> dic2 = null;
  466. dic1 = BaseUtil.ToDictionary(Content);
  467. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  468. if (dic2[0]["filepath"] != null)
  469. {
  470. fp_id = dic2[0]["filepath"].ToString();
  471. fp_path = dic2[0]["path"].ToString();
  472. }
  473. if (response.StatusCode == HttpStatusCode.OK)
  474. {
  475. Console.WriteLine(fp_id);
  476. return fp_id;
  477. }
  478. }
  479. catch (Exception e)
  480. {
  481. Console.WriteLine(e.Message + e.StackTrace);
  482. }
  483. return "";
  484. }
  485. }
  486. }