AutoAnalysisDevice.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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 = "HUAG";
  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="+Master+";Pooling=false;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=81.71.42.91)(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. case 8:
  208. filedt.Columns.Add("合格数量");
  209. break;
  210. case 9:
  211. filedt.Columns.Add("不良数量");
  212. break;
  213. case 10:
  214. filedt.Columns.Add("文件路径");
  215. break;
  216. default:
  217. break;
  218. }
  219. }
  220. dr[filedt.Columns[i].ColumnName] = title[i];
  221. }
  222. filedt.Rows.Add(dr);
  223. Rowindex = Rowindex + 1;
  224. }
  225. sR.Close();
  226. OperateResult.AppendText("文件修改" + filedt.Rows.Count + "\n");
  227. for (int i = 0; i < filedt.Rows.Count; i++)
  228. {
  229. if (!dh.CheckExist("Devicetestinfo", "(dti_uptime)=to_date('" + filedt.Rows[i]["上架时间"].ToString() + "','yyyy/mm/dd hh24:mi:ss') and dti_ipaddress='" + IPAddress + "'"))
  230. {
  231. string filename = filedt.Rows[i]["文件路径"].ToString();
  232. Dictionary<string, object> dic = new Dictionary<string, object>
  233. {
  234. { "em_name", "管理员" },
  235. { "em_code", "ADMIN" },
  236. { "caller", "AGING" }
  237. };
  238. string fp_id;
  239. string fp_path;
  240. UploadFilesToRemoteUrl("http://192.168.101.253:8099/mes/MEScommon/uploadFiles.action?_noc=1", filename, dic, out fp_path, out fp_id);
  241. fp_path = "http://192.168.101.253:8099/" + fp_path.Replace("/app/uas/webapps/", "");
  242. fp_path = fp_path.Replace("\"", "");
  243. dh.ExecuteSql("insert into Devicetestinfo(dti_id,dti_account,dti_stepcode,dti_makecode,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() + "','"+ filedt.Rows[i]["计划单号"].ToString() + "','" + 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");
  244. OperateResult.AppendText("上传文件" + filename + "\n");
  245. }
  246. }
  247. }
  248. else if (Device.Text == "ATE设备")
  249. {
  250. if (!FileName.Contains("ATE日志文件")) {
  251. return;
  252. }
  253. StreamReader sR = new StreamReader(FileName, Encoding.Default);
  254. Console.WriteLine(sR.CurrentEncoding);
  255. DataTable filedt = new DataTable();
  256. //文件内的行,用一个DataTable存储
  257. int Rowindex = 0;
  258. while ((nextLine = sR.ReadLine()) != null)
  259. {
  260. //DataTable用第一行的数据作为列名
  261. string[] title = nextLine.Split(',');
  262. DataRow dr = filedt.NewRow();
  263. for (int i = 0; i < title.Length; i++)
  264. {
  265. if (Rowindex == 0)
  266. {
  267. switch (i)
  268. {
  269. case 0:
  270. filedt.Columns.Add("登录的账号");
  271. break;
  272. case 1:
  273. filedt.Columns.Add("工位固定号");
  274. break;
  275. case 2:
  276. filedt.Columns.Add("产品代码");
  277. break;
  278. case 3:
  279. filedt.Columns.Add("计划单号");
  280. break;
  281. case 4:
  282. filedt.Columns.Add("使用参数名");
  283. break;
  284. case 5:
  285. filedt.Columns.Add("通道");
  286. break;
  287. case 6:
  288. filedt.Columns.Add("开始时间");
  289. break;
  290. case 7:
  291. filedt.Columns.Add("结束时间");
  292. break;
  293. case 8:
  294. filedt.Columns.Add("上架数量");
  295. break;
  296. case 9:
  297. filedt.Columns.Add("合格数量");
  298. break;
  299. case 10:
  300. filedt.Columns.Add("不良数量");
  301. break;
  302. case 11:
  303. filedt.Columns.Add("文件路径");
  304. break;
  305. default:
  306. break;
  307. }
  308. }
  309. dr[filedt.Columns[i].ColumnName] = title[i];
  310. }
  311. filedt.Rows.Add(dr);
  312. Rowindex = Rowindex + 1;
  313. }
  314. sR.Close();
  315. OperateResult.AppendText("文件修改" + filedt.Rows.Count + "\n");
  316. for (int i = 0; i < filedt.Rows.Count; i++)
  317. {
  318. if (!dh.CheckExist("Devicetestinfo", "(dti_uptime)=to_date('" + filedt.Rows[i]["开始时间"].ToString() + "','yyyy/mm/dd hh24:mi:ss') and dti_ipaddress='" + IPAddress + "'"))
  319. {
  320. string filename = filedt.Rows[i]["文件路径"].ToString();
  321. Dictionary<string, object> dic = new Dictionary<string, object>
  322. {
  323. { "em_name", "管理员" },
  324. { "em_code", "ADMIN" },
  325. { "caller", "AGING" }
  326. };
  327. string fp_id;
  328. string fp_path;
  329. UploadFilesToRemoteUrl("http://192.168.101.253:8099/mes/MEScommon/uploadFiles.action?_noc=1", filename, dic, out fp_path, out fp_id);
  330. fp_path = "http://192.168.101.253:8099/" + fp_path.Replace("/app/uas/webapps/", "");
  331. fp_path = fp_path.Replace("\"", "");
  332. 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");
  333. OperateResult.AppendText("上传文件" + filename + "\n");
  334. }
  335. }
  336. }
  337. }
  338. private void StopWatch_Click(object sender, EventArgs e)
  339. {
  340. XmlWatcher.EnableRaisingEvents = false;
  341. StartWatch.Enabled = true;
  342. ma_code.Enabled = true;
  343. Master.Enabled = true;
  344. ChooseFolder.Enabled = true;
  345. StopWatch.Enabled = false;
  346. OperateResult.AppendText("停止执行监控\n");
  347. }
  348. private void Clean_Click(object sender, EventArgs e)
  349. {
  350. OperateResult.Clear();
  351. }
  352. private void ChooseFolder_Click(object sender, EventArgs e)
  353. {
  354. FolderBrowserDialog folder = new FolderBrowserDialog();
  355. folder.Description = "选择监控文件夹";
  356. DialogResult result = folder.ShowDialog();
  357. if (result == DialogResult.OK)
  358. {
  359. FolderPath.Text = folder.SelectedPath;
  360. }
  361. }
  362. private void ChooseBackUpFolder_Click(object sender, EventArgs e)
  363. {
  364. FolderBrowserDialog folder = new FolderBrowserDialog();
  365. folder.Description = "选择备份文件夹";
  366. DialogResult result = folder.ShowDialog();
  367. if (result == DialogResult.OK)
  368. {
  369. }
  370. }
  371. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  372. {
  373. string ExitConfirm = MessageBox.Show(this, "确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
  374. if (ExitConfirm != "Yes")
  375. {
  376. WindowState = FormWindowState.Minimized;
  377. e.Cancel = true;
  378. }
  379. }
  380. private void AutoStart_CheckedChanged(object sender, EventArgs e)
  381. {
  382. SetAutoRun();
  383. }
  384. private void SetAutoRun()
  385. {
  386. if (AutoStart.Checked) //设置开机自启动
  387. {
  388. string path = Application.ExecutablePath;
  389. RegistryKey rk = Registry.LocalMachine;
  390. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  391. rk2.SetValue("FileWatcher.exe", path);
  392. rk2.Close();
  393. rk.Close();
  394. }
  395. else //取消开机自启动
  396. {
  397. string path = Application.ExecutablePath;
  398. RegistryKey rk = Registry.LocalMachine;
  399. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  400. rk2.DeleteValue("FileWatcher.exe", false);
  401. rk2.Close();
  402. rk.Close();
  403. }
  404. }
  405. private void BatchAnalysus_Click(object sender, EventArgs e)
  406. {
  407. TxtHandleProcess(@"C:\Users\callm\Desktop\导入数据\客户资料\睿德电子\新建文本文档.log");
  408. //TxtHandleProcess(@"C:\Users\callm\Desktop\导入数据\客户资料\睿德电子\PowerTestTj.ini");
  409. }
  410. private void Timer_Tick(object sender, EventArgs e)
  411. {
  412. var AllXmls = Directory.GetFiles(FolderPath.Text, "*.txt");
  413. foreach (var Xml in AllXmls)
  414. {
  415. TxtHandleProcess(Xml);
  416. }
  417. }
  418. /// <summary>
  419. /// 请求上传图片到阿里云
  420. /// </summary>
  421. /// <param name="url">上传地址</param>
  422. /// <param name="filepath">本地文件路径</param>
  423. /// <param name="dic">上传的数据信息</param>
  424. /// <returns></returns>
  425. public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic, out string fp_path, out string fp_id)
  426. {
  427. fp_id = "";
  428. fp_path = "";
  429. try
  430. {
  431. ServicePointManager.DefaultConnectionLimit = 50;
  432. string boundary = DateTime.Now.Ticks.ToString("x");
  433. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  434. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  435. request.Method = "POST";
  436. request.Timeout = 10 * 10000;
  437. request.ContentType = "multipart/form-data; boundary=" + boundary;
  438. Stream rs = request.GetRequestStream();
  439. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  440. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  441. if (dic != null)
  442. {
  443. foreach (string key in dic.Keys)
  444. {
  445. rs.Write(boundarybytes, 0, boundarybytes.Length);
  446. string formitem = string.Format(formdataTemplate, key, dic[key]);
  447. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  448. rs.Write(formitembytes, 0, formitembytes.Length);
  449. }
  450. }
  451. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  452. {
  453. rs.Write(boundarybytes, 0, boundarybytes.Length);
  454. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  455. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  456. rs.Write(headerbytes, 0, headerbytes.Length);
  457. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  458. {
  459. var buffer = new byte[1024];
  460. var bytesRead = 0;
  461. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  462. {
  463. rs.Write(buffer, 0, bytesRead);
  464. }
  465. }
  466. var cr = Encoding.UTF8.GetBytes("\r\n");
  467. rs.Write(cr, 0, cr.Length);
  468. }
  469. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  470. var response = request.GetResponse() as HttpWebResponse;
  471. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  472. string Content = newReader.ReadToEnd();
  473. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  474. List<Dictionary<string, object>> dic2 = null;
  475. dic1 = BaseUtil.ToDictionary(Content);
  476. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  477. if (dic2[0]["filepath"] != null)
  478. {
  479. fp_id = dic2[0]["filepath"].ToString();
  480. fp_path = dic2[0]["path"].ToString();
  481. }
  482. if (response.StatusCode == HttpStatusCode.OK)
  483. {
  484. Console.WriteLine(fp_id);
  485. return fp_id;
  486. }
  487. }
  488. catch (Exception e)
  489. {
  490. Console.WriteLine(e.Message + e.StackTrace);
  491. }
  492. return "";
  493. }
  494. }
  495. }