Make_ParseLog.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. using BarTender;
  2. using DevExpress.Utils.OAuth.Provider;
  3. using DevExpress.Xpo.Logger;
  4. using DevExpress.XtraEditors.Controls;
  5. using DevExpress.XtraExport;
  6. using DevExpress.XtraPrinting;
  7. using NPOI.SS.Formula.Functions;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.ComponentModel;
  11. using System.Data;
  12. using System.Drawing;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Net;
  16. using System.Security;
  17. using System.Security.AccessControl;
  18. using System.Security.Principal;
  19. using System.Text;
  20. using System.Threading.Tasks;
  21. using System.Web.Services.Description;
  22. using System.Web.UI.WebControls;
  23. using System.Windows.Forms;
  24. using System.Xml;
  25. using UAS_MES_NEW.CustomControl.ButtonUtil;
  26. using UAS_MES_NEW.CustomControl.TextBoxWithIcon;
  27. using UAS_MES_NEW.DataOperate;
  28. using UAS_MES_NEW.Entity;
  29. using UAS_MES_NEW.PublicMethod;
  30. using static DevExpress.Xpo.DB.DataStoreLongrunnersWatch;
  31. using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;
  32. namespace UAS_MES_NEW.Make
  33. {
  34. public partial class Make_ParseLog : Form
  35. {
  36. public Make_ParseLog()
  37. {
  38. InitializeComponent();
  39. }
  40. FileSystemWatcher watcher;
  41. LogStringBuilder sql = new LogStringBuilder();
  42. DataTable Dbfind;
  43. DataTable dt;
  44. DataHelper dh;
  45. string currFileType = "",equiType = "";
  46. string SN, omakeCode, oMsid, oErrorMessage = "";
  47. List<string> fileList = new List<string>();
  48. Timer formsTimer;
  49. private void Make_ParseLog_Load(object sender, EventArgs e)
  50. {
  51. dh = SystemInf.dh;
  52. fileList.Add("C:\\Users\\MI\\Desktop");
  53. formsTimer = new Timer();
  54. formsTimer.Interval = 10000;
  55. formsTimer.Tick += timer1_Tick;
  56. //formsTimer.Start();
  57. //formsTimer.Stop();
  58. watcher = new FileSystemWatcher();
  59. watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
  60. watcher.Created += OnFileCreated;
  61. watcher.Changed += OnFileChanged;
  62. /*watcher.Deleted += OnFileChanged;
  63. watcher.Renamed += OnFileChanged;*/
  64. //设置锁定工单
  65. LockMakeCode.GetMakeCodeCtl(ma_code);
  66. ma_code.SetLockCheckBox(LockMakeCode);
  67. //工单号放大镜配置
  68. ma_code.TableName = "make left join product on ma_prodcode=pr_code";
  69. ma_code.SelectField = "ma_code # 工单号,pr_code # 产品编号,pr_detail # 产品名称";
  70. ma_code.FormName = Name;
  71. ma_code.SetValueField = new string[] { "ma_code", "pr_code", "pr_detail" };
  72. ma_code.Condition = "ma_statuscode='STARTED'";
  73. ma_code.DbChange += Ma_code_DbChange;
  74. }
  75. private void Ma_code_DbChange(object sender, EventArgs e)
  76. {
  77. Dbfind = ma_code.ReturnData;
  78. BaseUtil.SetFormValue(this.Controls, Dbfind);
  79. //获取工单的其他信息
  80. sql.Clear();
  81. sql.Append("select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode as pr_code ,pr_detail,");
  82. sql.Append("pr_spec,ma_qty - nvl(mcd_inqty, 0) mcd_remainqty from make left join makecraftdetail on ");
  83. sql.Append("mcd_maid=ma_id left join product on pr_code=ma_prodcode where ma_code='" + ma_code.Text + "' and mcd_stepcode='" + User.CurrentStepCode + "'");
  84. dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
  85. if (dt.Rows.Count > 0)
  86. {
  87. BaseUtil.SetFormValue(this.Controls, dt);
  88. }
  89. }
  90. private void Device_SelectedIndexChanged(object sender, EventArgs e)
  91. {
  92. if (Device.SelectedIndex == -1) return;
  93. switch (Device.SelectedIndex)
  94. {
  95. case 0:
  96. currFileType = "Log";
  97. equiType = "设备";
  98. break;
  99. }
  100. if (string.IsNullOrEmpty(ma_code.Text))
  101. {
  102. Device.SelectedIndex = -1;
  103. txtPath.Text = "";
  104. MessageBox.Show(this.ParentForm, "请选择工单", "提示");
  105. return;
  106. }
  107. txtPath.Text = fileList[Device.SelectedIndex];
  108. txtPath.Focus();
  109. txtPath.SelectAll();
  110. ma_code.Enabled = true;
  111. txtPath.Enabled = false;
  112. }
  113. private void Choose_Click(object sender, EventArgs e)
  114. {
  115. using (var dialog = new FolderBrowserDialog())
  116. {
  117. switch (Device.SelectedIndex)
  118. {
  119. case 0:
  120. dialog.Description = "请选择读取设备文件夹";
  121. currFileType = "Log";
  122. equiType = "设备";
  123. break;
  124. }
  125. if (dialog.ShowDialog() == DialogResult.OK)
  126. {
  127. txtPath.Text = dialog.SelectedPath;
  128. txtPath.Enabled = false;
  129. Device.Enabled = false;
  130. watcher.EnableRaisingEvents = false;
  131. }
  132. }
  133. }
  134. private void claerBtn_Click(object sender, EventArgs e)
  135. {
  136. lstFiles.Items.Clear();
  137. }
  138. private void allParse_Click(object sender, EventArgs e)
  139. {
  140. if (Device.SelectedIndex == 0)
  141. {
  142. if (string.IsNullOrEmpty(ma_code.Text))
  143. {
  144. MessageBox.Show(this.ParentForm, "请选择工单", "提示");
  145. return;
  146. }
  147. }
  148. if (Device.SelectedIndex == -1)
  149. {
  150. Device.Focus();
  151. Device.SelectAll();
  152. MessageBox.Show(this.ParentForm, "请选择设备", "提示");
  153. return;
  154. }
  155. if (String.IsNullOrEmpty(txtPath.Text))
  156. {
  157. txtPath.Focus();
  158. txtPath.SelectAll();
  159. return;
  160. }
  161. string[] txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
  162. if (txtFiles.Length == 0)
  163. {
  164. LogMessage($"当前{txtPath.Text},没有{equiType}设备输出的{currFileType.ToLower()}文件");
  165. return;
  166. }
  167. RefreshFileList();
  168. }
  169. private void onWatch_Click(object sender, EventArgs e)
  170. {
  171. if (Device.SelectedIndex == 0)
  172. {
  173. if (string.IsNullOrEmpty(ma_code.Text))
  174. {
  175. MessageBox.Show(this.ParentForm, "请选择工单", "提示");
  176. return;
  177. }
  178. }
  179. if (Device.SelectedIndex == -1)
  180. {
  181. Device.Focus();
  182. Device.SelectAll();
  183. MessageBox.Show(this.ParentForm, "请选择设备", "提示");
  184. return;
  185. }
  186. if (String.IsNullOrEmpty(txtPath.Text))
  187. {
  188. txtPath.Focus();
  189. txtPath.SelectAll();
  190. return;
  191. }
  192. try
  193. {
  194. watcher.Path = txtPath.Text;
  195. watcher.Filter = $"*.{currFileType}";
  196. if (onWatch.Text == "开启解析")
  197. {
  198. watcher.EnableRaisingEvents = true;
  199. onWatch.Text = "关闭解析";
  200. }
  201. else
  202. {
  203. watcher.EnableRaisingEvents = false;
  204. onWatch.Text = "开启解析";
  205. }
  206. }
  207. catch (Exception ex)
  208. {
  209. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  210. }
  211. }
  212. private void OnFileCreated(object sender, FileSystemEventArgs e)
  213. {
  214. RefreshFileList();
  215. }
  216. private void OnFileChanged(object sender, FileSystemEventArgs e)
  217. {
  218. if (e.ChangeType == WatcherChangeTypes.Changed)
  219. {
  220. RefreshFileList();
  221. }
  222. }
  223. private void RefreshFileList()
  224. {
  225. if (lstFiles.InvokeRequired)
  226. {
  227. lstFiles.Invoke(new Action(RefreshFileList));
  228. lstFiles.BeginInvoke(new Action(RefreshFileList));
  229. return;
  230. }
  231. try
  232. {
  233. if (!Directory.Exists(txtPath.Text))
  234. {
  235. LogMessage($"目录不存在: {txtPath.Text}");
  236. return;
  237. }
  238. string[] txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
  239. if (txtFiles.Length == 0)
  240. {
  241. return;
  242. }
  243. else
  244. {
  245. foreach (string file in txtFiles)
  246. {
  247. if (!File.Exists(file))
  248. {
  249. LogMessage($"文件不存在: {file}");
  250. }
  251. string outFileMsg = CheckFileAccess(file);
  252. if (outFileMsg != "OK")
  253. {
  254. LogMessage(outFileMsg);
  255. continue;
  256. }
  257. if(File.ReadAllText(file).Length == 0)
  258. {
  259. continue;
  260. }
  261. if (Device.SelectedIndex == 0)
  262. {
  263. ParseLogInsert(file);
  264. }
  265. }
  266. }
  267. }
  268. catch (Exception ex)
  269. {
  270. LogMessage($"Error: 解析文件列表失败: {ex.Message}");
  271. }
  272. }
  273. private void ParseLogInsert(string PathName)
  274. {
  275. try
  276. {
  277. StreamReader SR = File.OpenText(PathName);
  278. string restOfStream = SR.ReadToEnd();
  279. SR.Close();
  280. SR.Dispose();
  281. List<Log> logArr = new List<Log>() { };
  282. string[] lines = restOfStream.Split(new string[] { "\r\n" }, StringSplitOptions.None);
  283. int fileNum = string.IsNullOrEmpty(lines[lines.Length - 1]) ? lines.Length - 1 : lines.Length;
  284. foreach (var item in lines)
  285. {
  286. if (string.IsNullOrEmpty(item)) break;
  287. string[] currItem = item.Split(',');
  288. if(equiType == "设备")
  289. {
  290. string[] resultArr = currItem[0].Split('=');
  291. sql.Clear();
  292. sql.Append($@"select MAL_SNCODE from makeaddresslist where MAL_SN1_USER = '" + currItem[1] + "'");
  293. dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
  294. if (dt.Rows.Count == 0 || dt.Rows[0]["MAL_SNCODE"].ToString() == "")
  295. {
  296. LogMessage($"文件 {PathName}, 匹配NG: {currItem[1]}无对应SN");
  297. break;
  298. }
  299. Log itemLog = new Log()
  300. {
  301. SN = dt.Rows[0]["MAL_SNCODE"].ToString(),
  302. Result = resultArr[1],
  303. };
  304. logArr.Add(itemLog);
  305. }
  306. }
  307. if(logArr.Count == 0)
  308. {
  309. return;
  310. }
  311. if (InsertDb(logArr, PathName, fileNum))
  312. {
  313. if (ConsoleLog(restOfStream, PathName))
  314. {
  315. File.WriteAllText(PathName, string.Empty);
  316. /*File.Delete(PathName);*/
  317. }
  318. }
  319. }
  320. catch (Exception ex)
  321. {
  322. LogMessage($"Error: 文件 {PathName}, {ex.Message}");
  323. }
  324. }
  325. private bool InsertDb(List<Log> logs, string PathName,int fileNum)
  326. {
  327. try
  328. {
  329. StringBuilder sql = new StringBuilder();
  330. List<string> param = new List<string>() { };
  331. foreach (var item in logs)
  332. {
  333. if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, item.SN, User.UserCode,false ,out omakeCode, out oMsid, out oErrorMessage))
  334. {
  335. if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, item.SN, "日志解析", "OK", User.UserCode, false ,out oErrorMessage))
  336. {
  337. string sqlStr = $@"select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode,pr_detail,ma_qty - nvl(mcd_okqty, 0) remain_qty
  338. from make left join makecraftdetail on mcd_maid=ma_id left join product on pr_code = ma_prodcode
  339. where ma_code='" + omakeCode + "' and mcd_stepcode='" + User.CurrentStepCode + "'";
  340. dt = (DataTable)dh.ExecuteSql(sqlStr, "select");
  341. BaseUtil.SetFormValue(Controls, dt);
  342. //记录操作日志
  343. LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, ma_code.Text, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析成功", item.SN, "");
  344. string outMsg = "";
  345. param.Add(item.SN);
  346. param.Add(omakeCode);
  347. param.Add(User.UserSourceCode);
  348. param.Add(item.Result);
  349. param.Add(outMsg);
  350. string[] paramList = param.ToArray();
  351. dh.CallProcedure("cs_insert_testdetail", ref paramList);
  352. LogMessage($"文件: {PathName},共{fileNum}条记录SN: {item.SN}解析已过站");
  353. param.Clear();
  354. if (logs.IndexOf(item) == logs.Count - 1)
  355. {
  356. return true;
  357. }
  358. }
  359. else
  360. {
  361. LogMessage($"处理过站NG:{oErrorMessage}");
  362. break;
  363. }
  364. }
  365. else
  366. {
  367. LogMessage($"过站核对NG:{oErrorMessage}");
  368. break;
  369. }
  370. }
  371. return false;
  372. }
  373. catch (Exception ex)
  374. {
  375. LogMessage($"处理解析写入error:{ex.Message}");
  376. return false;
  377. }
  378. }
  379. private void timer1_Tick(object sender, EventArgs e)
  380. {
  381. try
  382. {
  383. }
  384. catch (Exception ex)
  385. {
  386. LogMessage($"定时器异常: {ex.Message}");
  387. }
  388. }
  389. private bool ConsoleLog(string Content, string PathName)
  390. {
  391. try
  392. {
  393. string sourceDir = Path.GetDirectoryName(PathName);
  394. string newFolderName = "Logs";
  395. string newFolderPath = Path.Combine(sourceDir, newFolderName);
  396. if (!Directory.Exists(newFolderPath))
  397. {
  398. Directory.CreateDirectory(newFolderPath);
  399. }
  400. string newFileName = "Log_" + Path.GetFileName(PathName);
  401. string newFilePath = Path.Combine(newFolderPath, newFileName);
  402. File.AppendAllText(newFilePath, Content + Environment.NewLine);
  403. return true;
  404. }
  405. catch (Exception ex)
  406. {
  407. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  408. return false;
  409. }
  410. }
  411. private void LogMessage(string message)
  412. {
  413. bool isNg;
  414. if (message.ToUpper().Contains("NG"))
  415. {
  416. isNg = true;
  417. }
  418. else if (message.ToUpper().Contains("ERROR"))
  419. {
  420. isNg = true;
  421. }
  422. else
  423. {
  424. isNg = false;
  425. }
  426. if (isNg)
  427. {
  428. if (lstFiles.InvokeRequired)
  429. {
  430. lstFiles.Invoke(new Action<string>(LogMessage), message);
  431. return;
  432. }
  433. lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  434. lstFiles.TopIndex = lstFiles.Items.Count - 1;
  435. lstFiles.DrawMode = DrawMode.OwnerDrawFixed;
  436. }
  437. else
  438. {
  439. if (lstOk.InvokeRequired)
  440. {
  441. lstOk.Invoke(new Action<string>(LogMessage), message);
  442. return;
  443. }
  444. lstOk.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  445. lstOk.TopIndex = lstFiles.Items.Count - 1;
  446. }
  447. }
  448. private void lstFiles_DrawItem_1(object sender, DrawItemEventArgs e)
  449. {
  450. e.DrawBackground();
  451. Brush mybsh = Brushes.Black;
  452. if (lstFiles.Items[e.Index].ToString().Contains("NG"))
  453. {
  454. mybsh = Brushes.Red;
  455. }
  456. else if (lstFiles.Items[e.Index].ToString().Contains("ERROR"))
  457. {
  458. mybsh = Brushes.Red;
  459. }
  460. e.DrawFocusRectangle();
  461. e.Graphics.DrawString(lstFiles.Items[e.Index].ToString(), e.Font, mybsh, e.Bounds, StringFormat.GenericDefault);
  462. }
  463. public string CheckFileAccess(string filePath)
  464. {
  465. try
  466. {
  467. using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
  468. {
  469. return "OK";
  470. }
  471. }
  472. catch (IOException ex)
  473. {
  474. return "文件被占用: " + ex.Message;
  475. }
  476. catch (UnauthorizedAccessException ex)
  477. {
  478. return "权限不足,无法访问文件: " + ex.Message;
  479. }
  480. catch (Exception ex)
  481. {
  482. return ex.Message;
  483. }
  484. }
  485. private class Log
  486. {
  487. public string SN { set; get; }
  488. public string Result { set; get; }
  489. }
  490. }
  491. }