AutoAnalysisDevice.cs 23 KB

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