AutoAnalysisDevice.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. string ftppath = "/AGING/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("yyyy-MM") + "/" + DateTime.Now.ToString("MM-dd") + "/";
  223. string folderpath = filename.Substring(0, filename.LastIndexOf(@"\"));
  224. //ftp.UpLoadFile(folderpath, filename.Substring(filename.LastIndexOf(@"\")), ftppath, "");
  225. Dictionary<string, object> dic = new Dictionary<string, object>();
  226. dic.Add("em_name", "管理员");
  227. dic.Add("em_code", "ADMIN");
  228. dic.Add("caller", "AGING");
  229. string fp_id;
  230. string fp_path;
  231. UploadFilesToRemoteUrl("http://192.168.199.173:8080/mes/MEScommon/uploadFiles.action?_noc=1", filename, dic,out fp_path, out fp_id);
  232. fp_path = "http://192.168.199.173:8080/" + 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)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. try
  242. {
  243. StreamReader sR = File.OpenText(FileName);
  244. string filename = FileName;
  245. List<string> programname = new List<string>();
  246. List<string> data = new List<string>();
  247. Regex re = new Regex(@"\d+");
  248. if (filename.Substring(filename.LastIndexOf(".") + 1).ToUpper() == "INI")
  249. {
  250. while ((nextLine = sR.ReadLine()) != null)
  251. {
  252. programname.Add(nextLine);
  253. }
  254. string[] str = programname.ToArray();
  255. for (int i = str.Length - 4; i < str.Length; i++)
  256. {
  257. if (str[i].Contains("["))
  258. {
  259. data.Add(str[i]);
  260. }
  261. else
  262. {
  263. data.Add(re.Match(str[i]).Groups[0].Value);
  264. }
  265. }
  266. 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");
  267. }
  268. }
  269. catch (Exception e)
  270. {
  271. OperateResult.AppendText("解析失败:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\n" + FileName + "\n" + e.Message + "\n");
  272. }
  273. }
  274. }
  275. private void StopWatch_Click(object sender, EventArgs e)
  276. {
  277. XmlWatcher.EnableRaisingEvents = false;
  278. StartWatch.Enabled = true;
  279. ma_code.Enabled = true;
  280. Master.Enabled = true;
  281. ChooseFolder.Enabled = true;
  282. StopWatch.Enabled = false;
  283. OperateResult.AppendText("停止执行监控\n");
  284. }
  285. private void Clean_Click(object sender, EventArgs e)
  286. {
  287. OperateResult.Clear();
  288. }
  289. private void ChooseFolder_Click(object sender, EventArgs e)
  290. {
  291. FolderBrowserDialog folder = new FolderBrowserDialog();
  292. folder.Description = "选择监控文件夹";
  293. DialogResult result = folder.ShowDialog();
  294. if (result == DialogResult.OK)
  295. {
  296. FolderPath.Text = folder.SelectedPath;
  297. }
  298. }
  299. private void ChooseBackUpFolder_Click(object sender, EventArgs e)
  300. {
  301. FolderBrowserDialog folder = new FolderBrowserDialog();
  302. folder.Description = "选择备份文件夹";
  303. DialogResult result = folder.ShowDialog();
  304. if (result == DialogResult.OK)
  305. {
  306. }
  307. }
  308. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  309. {
  310. string ExitConfirm = MessageBox.Show(this, "确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
  311. if (ExitConfirm != "Yes")
  312. {
  313. WindowState = FormWindowState.Minimized;
  314. e.Cancel = true;
  315. }
  316. }
  317. private void AutoStart_CheckedChanged(object sender, EventArgs e)
  318. {
  319. SetAutoRun();
  320. }
  321. private void SetAutoRun()
  322. {
  323. if (AutoStart.Checked) //设置开机自启动
  324. {
  325. string path = Application.ExecutablePath;
  326. RegistryKey rk = Registry.LocalMachine;
  327. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  328. rk2.SetValue("UAS自动过站解析器.exe", path);
  329. rk2.Close();
  330. rk.Close();
  331. }
  332. else //取消开机自启动
  333. {
  334. string path = Application.ExecutablePath;
  335. RegistryKey rk = Registry.LocalMachine;
  336. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  337. rk2.DeleteValue("UAS自动过站解析器.exe", false);
  338. rk2.Close();
  339. rk.Close();
  340. }
  341. }
  342. private void BatchAnalysus_Click(object sender, EventArgs e)
  343. {
  344. TxtHandleProcess(@"C:\Users\callm\Desktop\导入数据\客户资料\睿德电子\新建文本文档.log");
  345. //TxtHandleProcess(@"C:\Users\callm\Desktop\导入数据\客户资料\睿德电子\PowerTestTj.ini");
  346. }
  347. private void Timer_Tick(object sender, EventArgs e)
  348. {
  349. //var AllXmls = Directory.GetFiles(FolderPath.Text, "*.txt");
  350. //foreach (var Xml in AllXmls)
  351. //{
  352. // TxtHandleProcess(Xml);
  353. //}
  354. }
  355. /// <summary>
  356. /// 请求上传图片到阿里云
  357. /// </summary>
  358. /// <param name="url">上传地址</param>
  359. /// <param name="filepath">本地文件路径</param>
  360. /// <param name="dic">上传的数据信息</param>
  361. /// <returns></returns>
  362. public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic,out string fp_path,out string fp_id)
  363. {
  364. fp_id = "";
  365. fp_path = "";
  366. try
  367. {
  368. ServicePointManager.DefaultConnectionLimit = 50;
  369. string boundary = DateTime.Now.Ticks.ToString("x");
  370. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  371. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  372. request.Method = "POST";
  373. request.Timeout = 10 * 10000;
  374. request.ContentType = "multipart/form-data; boundary=" + boundary;
  375. Stream rs = request.GetRequestStream();
  376. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  377. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  378. if (dic != null)
  379. {
  380. foreach (string key in dic.Keys)
  381. {
  382. rs.Write(boundarybytes, 0, boundarybytes.Length);
  383. string formitem = string.Format(formdataTemplate, key, dic[key]);
  384. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  385. rs.Write(formitembytes, 0, formitembytes.Length);
  386. }
  387. }
  388. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  389. {
  390. rs.Write(boundarybytes, 0, boundarybytes.Length);
  391. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  392. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  393. rs.Write(headerbytes, 0, headerbytes.Length);
  394. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  395. {
  396. var buffer = new byte[1024];
  397. var bytesRead = 0;
  398. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  399. {
  400. rs.Write(buffer, 0, bytesRead);
  401. }
  402. }
  403. var cr = Encoding.UTF8.GetBytes("\r\n");
  404. rs.Write(cr, 0, cr.Length);
  405. }
  406. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  407. var response = request.GetResponse() as HttpWebResponse;
  408. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  409. string Content = newReader.ReadToEnd();
  410. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  411. List<Dictionary<string, object>> dic2 = null;
  412. dic1 = BaseUtil.ToDictionary(Content);
  413. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  414. if (dic2[0]["filepath"] != null)
  415. {
  416. fp_id = dic2[0]["filepath"].ToString();
  417. fp_path= dic2[0]["path"].ToString();
  418. }
  419. if (response.StatusCode == HttpStatusCode.OK)
  420. {
  421. Console.WriteLine(fp_id);
  422. return fp_id;
  423. }
  424. }
  425. catch (Exception e)
  426. {
  427. Console.WriteLine(e.Message + e.StackTrace);
  428. }
  429. return "";
  430. }
  431. }
  432. }