Make_ParseLog.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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}, 解析SN: {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 (InsertDb(logArr, PathName, fileNum))
  308. {
  309. if (ConsoleLog(restOfStream, PathName))
  310. {
  311. File.WriteAllText(PathName, string.Empty);
  312. /*File.Delete(PathName);*/
  313. }
  314. }
  315. }
  316. catch (Exception ex)
  317. {
  318. LogMessage($"Error: 文件 {PathName}, {ex.Message}");
  319. }
  320. }
  321. private bool InsertDb(List<Log> logs, string PathName,int fileNum)
  322. {
  323. try
  324. {
  325. StringBuilder sql = new StringBuilder();
  326. List<string> param = new List<string>() { };
  327. foreach (var item in logs)
  328. {
  329. if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, item.SN, User.UserCode, out omakeCode, out oMsid, out oErrorMessage))
  330. {
  331. if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, item.SN, "日志解析", "OK", User.UserCode, out oErrorMessage))
  332. {
  333. string sqlStr = $@"select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode,pr_detail,ma_qty - nvl(mcd_okqty, 0) remain_qty
  334. from make left join makecraftdetail on mcd_maid=ma_id left join product on pr_code = ma_prodcode
  335. where ma_code='" + omakeCode + "' and mcd_stepcode='" + User.CurrentStepCode + "'";
  336. dt = (DataTable)dh.ExecuteSql(sqlStr, "select");
  337. BaseUtil.SetFormValue(Controls, dt);
  338. //记录操作日志
  339. LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, ma_code.Text, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析成功", item.SN, "");
  340. string outMsg = "";
  341. param.Add(item.SN);
  342. param.Add(omakeCode);
  343. param.Add(User.UserSourceCode);
  344. param.Add(item.Result);
  345. param.Add(outMsg);
  346. string[] paramList = param.ToArray();
  347. dh.CallProcedure("cs_insert_testdetail", ref paramList);
  348. LogMessage($"文件: {PathName},共{fileNum}条记录SN: {item.SN}解析已过站");
  349. param.Clear();
  350. }
  351. else
  352. {
  353. LogMessage($"处理过站NG:{oErrorMessage}");
  354. break;
  355. }
  356. }
  357. else
  358. {
  359. LogMessage($"过站核对NG:{oErrorMessage}");
  360. }
  361. }
  362. return false;
  363. }
  364. catch (Exception ex)
  365. {
  366. LogMessage($"处理解析写入error:{ex.Message}");
  367. return false;
  368. }
  369. }
  370. private void timer1_Tick(object sender, EventArgs e)
  371. {
  372. try
  373. {
  374. }
  375. catch (Exception ex)
  376. {
  377. LogMessage($"定时器异常: {ex.Message}");
  378. }
  379. }
  380. private bool ConsoleLog(string Content, string PathName)
  381. {
  382. try
  383. {
  384. string sourceDir = Path.GetDirectoryName(PathName);
  385. string newFolderName = "Logs";
  386. string newFolderPath = Path.Combine(sourceDir, newFolderName);
  387. if (!Directory.Exists(newFolderPath))
  388. {
  389. Directory.CreateDirectory(newFolderPath);
  390. }
  391. string newFileName = "Log_" + Path.GetFileName(PathName);
  392. string newFilePath = Path.Combine(newFolderPath, newFileName);
  393. File.AppendAllText(newFilePath, Content + Environment.NewLine);
  394. return true;
  395. }
  396. catch (Exception ex)
  397. {
  398. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  399. return false;
  400. }
  401. }
  402. private void LogMessage(string message)
  403. {
  404. if (lstFiles.InvokeRequired)
  405. {
  406. lstFiles.Invoke(new Action<string>(LogMessage), message);
  407. return;
  408. }
  409. lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  410. lstFiles.TopIndex = lstFiles.Items.Count - 1;
  411. lstFiles.DrawMode = DrawMode.OwnerDrawFixed;
  412. }
  413. private void lstFiles_DrawItem_1(object sender, DrawItemEventArgs e)
  414. {
  415. e.DrawBackground();
  416. Brush mybsh = Brushes.Black;
  417. if (lstFiles.Items[e.Index].ToString().Contains("NG"))
  418. {
  419. mybsh = Brushes.Red;
  420. }
  421. else if (lstFiles.Items[e.Index].ToString().Contains("ERROR"))
  422. {
  423. mybsh = Brushes.Red;
  424. }
  425. e.DrawFocusRectangle();
  426. e.Graphics.DrawString(lstFiles.Items[e.Index].ToString(), e.Font, mybsh, e.Bounds, StringFormat.GenericDefault);
  427. }
  428. public string CheckFileAccess(string filePath)
  429. {
  430. try
  431. {
  432. using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
  433. {
  434. return "OK";
  435. }
  436. }
  437. catch (IOException ex)
  438. {
  439. return "文件被占用: " + ex.Message;
  440. }
  441. catch (UnauthorizedAccessException ex)
  442. {
  443. return "权限不足,无法访问文件: " + ex.Message;
  444. }
  445. catch (Exception ex)
  446. {
  447. return ex.Message;
  448. }
  449. }
  450. private class Log
  451. {
  452. public string SN { set; get; }
  453. public string Result { set; get; }
  454. }
  455. }
  456. }