AutoAnalysisDevice.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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.Created += 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. }
  111. private void ConnectDB()
  112. {
  113. 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)));";
  114. dh = new DataHelper();
  115. }
  116. private void StartWatch_Click(object sender, EventArgs e)
  117. {
  118. if (FolderPath.Text == "")
  119. {
  120. OperateResult.AppendText("请选择监控文件夹\n");
  121. return;
  122. }
  123. else
  124. {
  125. if (!Directory.Exists(FolderPath.Text))
  126. {
  127. OperateResult.AppendText("监控文件夹不存在\n");
  128. return;
  129. }
  130. }
  131. XmlWatcher.Path = FolderPath.Text;
  132. XmlWatcher.EnableRaisingEvents = true;
  133. XmlWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
  134. ATEFile.Path = FolderPath.Text;
  135. ATEFile.EnableRaisingEvents = true;
  136. ATEFile.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
  137. //设置缓存数据
  138. BaseUtil.SetCacheData("FolderPath", FolderPath.Text);
  139. BaseUtil.SetCacheData("Device", Device.Text);
  140. //BaseUtil.SetCacheData("BackUpFolderPath", BackUpFolderPath.Text);
  141. //BaseUtil.SetCacheData("Master", Master.Text);
  142. //BaseUtil.SetCacheData("AutoStart", AutoStart.Checked);
  143. Timer.Interval = 1000 * 10;
  144. Timer.Start();
  145. //设置按钮不可点击
  146. StartWatch.Enabled = false;
  147. ChooseFolder.Enabled = false;
  148. Master.Enabled = false;
  149. ma_code.Enabled = false;
  150. StopWatch.Enabled = true;
  151. OperateResult.AppendText("开始执行监控\n");
  152. }
  153. private void XmlWatcher_Created(object sender, FileSystemEventArgs e)
  154. {
  155. OperateResult.AppendText("文件修改:" + e.FullPath + "\n");
  156. TxtHandleProcess(e.FullPath);
  157. }
  158. string nextLine;
  159. private void TxtHandleProcess(string FileName)
  160. {
  161. List<string> badcode = new List<string>();
  162. List<string> badlocation = new List<string>();
  163. List<string> badprod = new List<string>();
  164. if (Device.Text == "老化设备")
  165. {
  166. StreamReader sR = new StreamReader(FileName, Encoding.Default);
  167. Console.WriteLine(sR.CurrentEncoding);
  168. DataTable filedt = new DataTable();
  169. //文件内的行,用一个DataTable存储
  170. int Rowindex = 0;
  171. while ((nextLine = sR.ReadLine()) != null)
  172. {
  173. //DataTable用第一行的数据作为列名
  174. string[] title = nextLine.Split(',');
  175. DataRow dr = filedt.NewRow();
  176. for (int i = 0; i < title.Length; i++)
  177. {
  178. if (Rowindex == 0)
  179. {
  180. switch (i)
  181. {
  182. case 0:
  183. filedt.Columns.Add("区域");
  184. break;
  185. case 1:
  186. filedt.Columns.Add("产品代码");
  187. break;
  188. case 2:
  189. filedt.Columns.Add("上架时间");
  190. break;
  191. case 3:
  192. filedt.Columns.Add("下架时间");
  193. break;
  194. case 4:
  195. filedt.Columns.Add("上架数量");
  196. break;
  197. case 5:
  198. filedt.Columns.Add("合格数量");
  199. break;
  200. case 6:
  201. filedt.Columns.Add("不良数量");
  202. break;
  203. case 7:
  204. filedt.Columns.Add("文件路径");
  205. break;
  206. default:
  207. break;
  208. }
  209. }
  210. dr[filedt.Columns[i].ColumnName] = title[i];
  211. }
  212. filedt.Rows.Add(dr);
  213. Rowindex = Rowindex + 1;
  214. }
  215. sR.Close();
  216. OperateResult.AppendText("文件修改" + filedt.Rows.Count + "\n");
  217. for (int i = 0; i < filedt.Rows.Count; i++)
  218. {
  219. if (!dh.CheckExist("Devicetestinfo", "(dti_uptime)=to_date('" + filedt.Rows[i]["上架时间"].ToString() + "','yyyy/mm/dd hh24:mi:ss') and dti_ipaddress='" + IPAddress + "'"))
  220. {
  221. string filename = filedt.Rows[i]["文件路径"].ToString();
  222. Dictionary<string, object> dic = new Dictionary<string, object>
  223. {
  224. { "em_name", "管理员" },
  225. { "em_code", "ADMIN" },
  226. { "caller", "AGING" }
  227. };
  228. string fp_id;
  229. string fp_path;
  230. UploadFilesToRemoteUrl("http://192.168.6.253:8099/mes/MEScommon/uploadFiles.action?_noc=1", filename, dic,out fp_path, out fp_id);
  231. fp_path = "http://192.168.6.253:8099/" + fp_path.Replace("/app/uas/webapps/", "");
  232. fp_path= fp_path.Replace("\"","");
  233. 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)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");
  234. OperateResult.AppendText("上传文件" + filename + "\n");
  235. }
  236. }
  237. }
  238. else if (Device.Text == "ATE设备")
  239. {
  240. try
  241. {
  242. StreamReader sR = File.OpenText(FileName);
  243. string filename = FileName;
  244. List<string> programname = new List<string>();
  245. List<string> data = new List<string>();
  246. Regex re = new Regex(@"\d+");
  247. if (filename.Substring(filename.LastIndexOf(".") + 1).ToUpper() == "INI")
  248. {
  249. while ((nextLine = sR.ReadLine()) != null)
  250. {
  251. programname.Add(nextLine);
  252. }
  253. string[] str = programname.ToArray();
  254. for (int i = str.Length - 4; i < str.Length; i++)
  255. {
  256. if (str[i].Contains("["))
  257. {
  258. data.Add(str[i]);
  259. }
  260. else
  261. {
  262. data.Add(re.Match(str[i]).Groups[0].Value);
  263. }
  264. }
  265. dh.ExecuteSql("insert into ATETESTDATA(atd_id,atd_name,atd_passqty,atd_ngqty,atd_lastqty,atd_ipaddress,atd_makecode,atd_makecode)values(ATETESTDATA_seq.nextval,'" + data.ToArray()[0] + "','" + data.ToArray()[1] + "','" + data.ToArray()[2] + "','" + data.ToArray()[3] + "','" + IPAddress + "','" + ma_code.Text + "',sysdate)", "insert");
  266. }
  267. }
  268. catch (Exception e)
  269. {
  270. OperateResult.AppendText("解析失败:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\n" + FileName + "\n" + e.Message + "\n");
  271. }
  272. }
  273. }
  274. private void StopWatch_Click(object sender, EventArgs e)
  275. {
  276. XmlWatcher.EnableRaisingEvents = false;
  277. StartWatch.Enabled = true;
  278. ma_code.Enabled = true;
  279. Master.Enabled = true;
  280. ChooseFolder.Enabled = true;
  281. StopWatch.Enabled = false;
  282. OperateResult.AppendText("停止执行监控\n");
  283. }
  284. private void Clean_Click(object sender, EventArgs e)
  285. {
  286. OperateResult.Clear();
  287. }
  288. private void ChooseFolder_Click(object sender, EventArgs e)
  289. {
  290. FolderBrowserDialog folder = new FolderBrowserDialog();
  291. folder.Description = "选择监控文件夹";
  292. DialogResult result = folder.ShowDialog();
  293. if (result == DialogResult.OK)
  294. {
  295. FolderPath.Text = folder.SelectedPath;
  296. }
  297. }
  298. private void ChooseBackUpFolder_Click(object sender, EventArgs e)
  299. {
  300. FolderBrowserDialog folder = new FolderBrowserDialog();
  301. folder.Description = "选择备份文件夹";
  302. DialogResult result = folder.ShowDialog();
  303. if (result == DialogResult.OK)
  304. {
  305. }
  306. }
  307. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  308. {
  309. string ExitConfirm = MessageBox.Show(this, "确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
  310. if (ExitConfirm != "Yes")
  311. {
  312. WindowState = FormWindowState.Minimized;
  313. e.Cancel = true;
  314. }
  315. }
  316. private void AutoStart_CheckedChanged(object sender, EventArgs e)
  317. {
  318. SetAutoRun();
  319. }
  320. private void SetAutoRun()
  321. {
  322. if (AutoStart.Checked) //设置开机自启动
  323. {
  324. string path = Application.ExecutablePath;
  325. RegistryKey rk = Registry.LocalMachine;
  326. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  327. rk2.SetValue("UAS自动过站解析器.exe", path);
  328. rk2.Close();
  329. rk.Close();
  330. }
  331. else //取消开机自启动
  332. {
  333. string path = Application.ExecutablePath;
  334. RegistryKey rk = Registry.LocalMachine;
  335. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  336. rk2.DeleteValue("UAS自动过站解析器.exe", false);
  337. rk2.Close();
  338. rk.Close();
  339. }
  340. }
  341. private void BatchAnalysus_Click(object sender, EventArgs e)
  342. {
  343. TxtHandleProcess(@"C:\Users\callm\Desktop\导入数据\客户资料\睿德电子\新建文本文档.log");
  344. //TxtHandleProcess(@"C:\Users\callm\Desktop\导入数据\客户资料\睿德电子\PowerTestTj.ini");
  345. }
  346. private void Timer_Tick(object sender, EventArgs e)
  347. {
  348. //var AllXmls = Directory.GetFiles(FolderPath.Text, "*.txt");
  349. //foreach (var Xml in AllXmls)
  350. //{
  351. // TxtHandleProcess(Xml);
  352. //}
  353. }
  354. /// <summary>
  355. /// 请求上传图片到阿里云
  356. /// </summary>
  357. /// <param name="url">上传地址</param>
  358. /// <param name="filepath">本地文件路径</param>
  359. /// <param name="dic">上传的数据信息</param>
  360. /// <returns></returns>
  361. public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic,out string fp_path,out string fp_id)
  362. {
  363. fp_id = "";
  364. fp_path = "";
  365. try
  366. {
  367. ServicePointManager.DefaultConnectionLimit = 50;
  368. string boundary = DateTime.Now.Ticks.ToString("x");
  369. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  370. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  371. request.Method = "POST";
  372. request.Timeout = 10 * 10000;
  373. request.ContentType = "multipart/form-data; boundary=" + boundary;
  374. Stream rs = request.GetRequestStream();
  375. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  376. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  377. if (dic != null)
  378. {
  379. foreach (string key in dic.Keys)
  380. {
  381. rs.Write(boundarybytes, 0, boundarybytes.Length);
  382. string formitem = string.Format(formdataTemplate, key, dic[key]);
  383. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  384. rs.Write(formitembytes, 0, formitembytes.Length);
  385. }
  386. }
  387. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  388. {
  389. rs.Write(boundarybytes, 0, boundarybytes.Length);
  390. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  391. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  392. rs.Write(headerbytes, 0, headerbytes.Length);
  393. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  394. {
  395. var buffer = new byte[1024];
  396. var bytesRead = 0;
  397. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  398. {
  399. rs.Write(buffer, 0, bytesRead);
  400. }
  401. }
  402. var cr = Encoding.UTF8.GetBytes("\r\n");
  403. rs.Write(cr, 0, cr.Length);
  404. }
  405. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  406. var response = request.GetResponse() as HttpWebResponse;
  407. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  408. string Content = newReader.ReadToEnd();
  409. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  410. List<Dictionary<string, object>> dic2 = null;
  411. dic1 = BaseUtil.ToDictionary(Content);
  412. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  413. if (dic2[0]["filepath"] != null)
  414. {
  415. fp_id = dic2[0]["filepath"].ToString();
  416. fp_path= dic2[0]["path"].ToString();
  417. }
  418. if (response.StatusCode == HttpStatusCode.OK)
  419. {
  420. Console.WriteLine(fp_id);
  421. return fp_id;
  422. }
  423. }
  424. catch (Exception e)
  425. {
  426. Console.WriteLine(e.Message + e.StackTrace);
  427. }
  428. return "";
  429. }
  430. }
  431. }