| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539 |
- using BarTender;
- using DevExpress.Utils.OAuth.Provider;
- using DevExpress.Xpo.Logger;
- using DevExpress.XtraEditors.Controls;
- using DevExpress.XtraExport;
- using DevExpress.XtraPrinting;
- using NPOI.SS.Formula.Functions;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Security;
- using System.Security.AccessControl;
- using System.Security.Principal;
- using System.Text;
- using System.Threading.Tasks;
- using System.Web.Services.Description;
- using System.Web.UI.WebControls;
- using System.Windows.Forms;
- using System.Xml;
- using UAS_MES_NEW.CustomControl.ButtonUtil;
- using UAS_MES_NEW.CustomControl.TextBoxWithIcon;
- using UAS_MES_NEW.DataOperate;
- using UAS_MES_NEW.Entity;
- using UAS_MES_NEW.PublicMethod;
- using static DevExpress.Xpo.DB.DataStoreLongrunnersWatch;
- using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;
- namespace UAS_MES_NEW.Make
- {
- public partial class Make_ParseLog : Form
- {
- public Make_ParseLog()
- {
- InitializeComponent();
- }
- FileSystemWatcher watcher;
- LogStringBuilder sql = new LogStringBuilder();
- DataTable Dbfind;
- DataTable dt;
- DataHelper dh;
- string currFileType = "",equiType = "";
- string SN, omakeCode, oMsid, oErrorMessage = "";
- List<string> fileList = new List<string>();
- Timer formsTimer;
- private void Make_ParseLog_Load(object sender, EventArgs e)
- {
- dh = SystemInf.dh;
- fileList.Add("C:\\Users\\MI\\Desktop");
- formsTimer = new Timer();
- formsTimer.Interval = 10000;
- formsTimer.Tick += timer1_Tick;
- //formsTimer.Start();
- //formsTimer.Stop();
- watcher = new FileSystemWatcher();
- watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
- watcher.Created += OnFileCreated;
- watcher.Changed += OnFileChanged;
- /*watcher.Deleted += OnFileChanged;
- watcher.Renamed += OnFileChanged;*/
- //设置锁定工单
- LockMakeCode.GetMakeCodeCtl(ma_code);
- ma_code.SetLockCheckBox(LockMakeCode);
- //工单号放大镜配置
- ma_code.TableName = "make left join product on ma_prodcode=pr_code";
- ma_code.SelectField = "ma_code # 工单号,pr_code # 产品编号,pr_detail # 产品名称";
- ma_code.FormName = Name;
- ma_code.SetValueField = new string[] { "ma_code", "pr_code", "pr_detail" };
- ma_code.Condition = "ma_statuscode='STARTED'";
- ma_code.DbChange += Ma_code_DbChange;
- }
- private void Ma_code_DbChange(object sender, EventArgs e)
- {
- Dbfind = ma_code.ReturnData;
- BaseUtil.SetFormValue(this.Controls, Dbfind);
- //获取工单的其他信息
- sql.Clear();
- sql.Append("select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode as pr_code ,pr_detail,");
- sql.Append("pr_spec,ma_qty - nvl(mcd_inqty, 0) mcd_remainqty from make left join makecraftdetail on ");
- 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 + "'");
- dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
- if (dt.Rows.Count > 0)
- {
- BaseUtil.SetFormValue(this.Controls, dt);
- }
- }
- private void Device_SelectedIndexChanged(object sender, EventArgs e)
- {
- if (Device.SelectedIndex == -1) return;
- switch (Device.SelectedIndex)
- {
- case 0:
- currFileType = "Log";
- equiType = "设备";
- break;
- }
- if (string.IsNullOrEmpty(ma_code.Text))
- {
- Device.SelectedIndex = -1;
- txtPath.Text = "";
- MessageBox.Show(this.ParentForm, "请选择工单", "提示");
- return;
- }
- txtPath.Text = fileList[Device.SelectedIndex];
- txtPath.Focus();
- txtPath.SelectAll();
- ma_code.Enabled = true;
- txtPath.Enabled = false;
- }
- private void Choose_Click(object sender, EventArgs e)
- {
- using (var dialog = new FolderBrowserDialog())
- {
- switch (Device.SelectedIndex)
- {
- case 0:
- dialog.Description = "请选择读取设备文件夹";
- currFileType = "Log";
- equiType = "设备";
- break;
- }
- if (dialog.ShowDialog() == DialogResult.OK)
- {
- txtPath.Text = dialog.SelectedPath;
- txtPath.Enabled = false;
- Device.Enabled = false;
- watcher.EnableRaisingEvents = false;
- }
- }
- }
- private void claerBtn_Click(object sender, EventArgs e)
- {
- lstFiles.Items.Clear();
- }
- private void allParse_Click(object sender, EventArgs e)
- {
- if (Device.SelectedIndex == 0)
- {
- if (string.IsNullOrEmpty(ma_code.Text))
- {
- MessageBox.Show(this.ParentForm, "请选择工单", "提示");
- return;
- }
- }
- if (Device.SelectedIndex == -1)
- {
- Device.Focus();
- Device.SelectAll();
- MessageBox.Show(this.ParentForm, "请选择设备", "提示");
- return;
- }
- if (String.IsNullOrEmpty(txtPath.Text))
- {
- txtPath.Focus();
- txtPath.SelectAll();
- return;
- }
- string[] txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
- if (txtFiles.Length == 0)
- {
- LogMessage($"当前{txtPath.Text},没有{equiType}设备输出的{currFileType.ToLower()}文件");
- return;
- }
- RefreshFileList();
- }
- private void onWatch_Click(object sender, EventArgs e)
- {
- if (Device.SelectedIndex == 0)
- {
- if (string.IsNullOrEmpty(ma_code.Text))
- {
- MessageBox.Show(this.ParentForm, "请选择工单", "提示");
- return;
- }
- }
- if (Device.SelectedIndex == -1)
- {
- Device.Focus();
- Device.SelectAll();
- MessageBox.Show(this.ParentForm, "请选择设备", "提示");
- return;
- }
- if (String.IsNullOrEmpty(txtPath.Text))
- {
- txtPath.Focus();
- txtPath.SelectAll();
- return;
- }
- try
- {
- watcher.Path = txtPath.Text;
- watcher.Filter = $"*.{currFileType}";
- if (onWatch.Text == "开启解析")
- {
- watcher.EnableRaisingEvents = true;
- onWatch.Text = "关闭解析";
- }
- else
- {
- watcher.EnableRaisingEvents = false;
- onWatch.Text = "开启解析";
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show(this.ParentForm, ex.Message, "警告");
- }
- }
- private void OnFileCreated(object sender, FileSystemEventArgs e)
- {
- RefreshFileList();
- }
- private void OnFileChanged(object sender, FileSystemEventArgs e)
- {
- if (e.ChangeType == WatcherChangeTypes.Changed)
- {
- RefreshFileList();
- }
- }
- private void RefreshFileList()
- {
- if (lstFiles.InvokeRequired)
- {
- lstFiles.Invoke(new Action(RefreshFileList));
- lstFiles.BeginInvoke(new Action(RefreshFileList));
- return;
- }
- try
- {
- if (!Directory.Exists(txtPath.Text))
- {
- LogMessage($"目录不存在: {txtPath.Text}");
- return;
- }
- string[] txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
- if (txtFiles.Length == 0)
- {
- return;
- }
- else
- {
- foreach (string file in txtFiles)
- {
- if (!File.Exists(file))
- {
- LogMessage($"文件不存在: {file}");
- }
- string outFileMsg = CheckFileAccess(file);
- if (outFileMsg != "OK")
- {
- LogMessage(outFileMsg);
- continue;
- }
- if(File.ReadAllText(file).Length == 0)
- {
- continue;
- }
- if (Device.SelectedIndex == 0)
- {
- ParseLogInsert(file);
- }
-
- }
- }
- }
- catch (Exception ex)
- {
- LogMessage($"Error: 解析文件列表失败: {ex.Message}");
- }
- }
- private void ParseLogInsert(string PathName)
- {
- try
- {
- StreamReader SR = File.OpenText(PathName);
- string restOfStream = SR.ReadToEnd();
- SR.Close();
- SR.Dispose();
- List<Log> logArr = new List<Log>() { };
- string[] lines = restOfStream.Split(new string[] { "\r\n" }, StringSplitOptions.None);
- int fileNum = string.IsNullOrEmpty(lines[lines.Length - 1]) ? lines.Length - 1 : lines.Length;
- foreach (var item in lines)
- {
- if (string.IsNullOrEmpty(item)) break;
- string[] currItem = item.Split(',');
- if(equiType == "设备")
- {
- string[] resultArr = currItem[0].Split('=');
- sql.Clear();
- sql.Append($@"select MAL_SNCODE from makeaddresslist where MAL_SN1_USER = '" + currItem[1] + "'");
- dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
- if (dt.Rows.Count == 0 || dt.Rows[0]["MAL_SNCODE"].ToString() == "")
- {
- LogMessage($"文件 {PathName}, 匹配NG: {currItem[1]}无对应SN");
- break;
- }
- Log itemLog = new Log()
- {
- SN = dt.Rows[0]["MAL_SNCODE"].ToString(),
- Result = resultArr[1],
- };
- logArr.Add(itemLog);
- }
- }
- if(logArr.Count == 0)
- {
- return;
- }
- if (InsertDb(logArr, PathName, fileNum))
- {
- if (ConsoleLog(restOfStream, PathName))
- {
- File.WriteAllText(PathName, string.Empty);
- /*File.Delete(PathName);*/
- }
- }
- }
- catch (Exception ex)
- {
- LogMessage($"Error: 文件 {PathName}, {ex.Message}");
- }
- }
- private bool InsertDb(List<Log> logs, string PathName,int fileNum)
- {
- try
- {
- StringBuilder sql = new StringBuilder();
- List<string> param = new List<string>() { };
- foreach (var item in logs)
- {
- if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, item.SN, User.UserCode,false ,out omakeCode, out oMsid, out oErrorMessage))
- {
- if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, item.SN, "日志解析", "OK", User.UserCode, false ,out oErrorMessage))
- {
- string sqlStr = $@"select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode,pr_detail,ma_qty - nvl(mcd_okqty, 0) remain_qty
- from make left join makecraftdetail on mcd_maid=ma_id left join product on pr_code = ma_prodcode
- where ma_code='" + omakeCode + "' and mcd_stepcode='" + User.CurrentStepCode + "'";
- dt = (DataTable)dh.ExecuteSql(sqlStr, "select");
- BaseUtil.SetFormValue(Controls, dt);
- //记录操作日志
- LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, ma_code.Text, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析成功", item.SN, "");
- string outMsg = "";
- param.Add(item.SN);
- param.Add(omakeCode);
- param.Add(User.UserSourceCode);
- param.Add(item.Result);
- param.Add(outMsg);
- string[] paramList = param.ToArray();
- dh.CallProcedure("cs_insert_testdetail", ref paramList);
- LogMessage($"文件: {PathName},共{fileNum}条记录SN: {item.SN}解析已过站");
- param.Clear();
- if (logs.IndexOf(item) == logs.Count - 1)
- {
- return true;
- }
- }
- else
- {
- LogMessage($"处理过站NG:{oErrorMessage}");
- break;
- }
- }
- else
- {
- LogMessage($"过站核对NG:{oErrorMessage}");
- break;
- }
- }
- return false;
- }
- catch (Exception ex)
- {
- LogMessage($"处理解析写入error:{ex.Message}");
- return false;
- }
- }
- private void timer1_Tick(object sender, EventArgs e)
- {
- try
- {
- }
- catch (Exception ex)
- {
- LogMessage($"定时器异常: {ex.Message}");
- }
- }
- private bool ConsoleLog(string Content, string PathName)
- {
- try
- {
- string sourceDir = Path.GetDirectoryName(PathName);
- string newFolderName = "Logs";
- string newFolderPath = Path.Combine(sourceDir, newFolderName);
- if (!Directory.Exists(newFolderPath))
- {
- Directory.CreateDirectory(newFolderPath);
- }
- string newFileName = "Log_" + Path.GetFileName(PathName);
- string newFilePath = Path.Combine(newFolderPath, newFileName);
- File.AppendAllText(newFilePath, Content + Environment.NewLine);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show(this.ParentForm, ex.Message, "警告");
- return false;
- }
- }
- private void LogMessage(string message)
- {
- bool isNg;
- if (message.ToUpper().Contains("NG"))
- {
- isNg = true;
- }
- else if (message.ToUpper().Contains("ERROR"))
- {
- isNg = true;
- }
- else
- {
- isNg = false;
- }
- if (isNg)
- {
- if (lstFiles.InvokeRequired)
- {
- lstFiles.Invoke(new Action<string>(LogMessage), message);
- return;
- }
- lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
- lstFiles.TopIndex = lstFiles.Items.Count - 1;
- lstFiles.DrawMode = DrawMode.OwnerDrawFixed;
- }
- else
- {
- if (lstOk.InvokeRequired)
- {
- lstOk.Invoke(new Action<string>(LogMessage), message);
- return;
- }
- lstOk.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
- lstOk.TopIndex = lstFiles.Items.Count - 1;
- }
- }
- private void lstFiles_DrawItem_1(object sender, DrawItemEventArgs e)
- {
- e.DrawBackground();
- Brush mybsh = Brushes.Black;
- if (lstFiles.Items[e.Index].ToString().Contains("NG"))
- {
- mybsh = Brushes.Red;
- }
- else if (lstFiles.Items[e.Index].ToString().Contains("ERROR"))
- {
- mybsh = Brushes.Red;
- }
- e.DrawFocusRectangle();
- e.Graphics.DrawString(lstFiles.Items[e.Index].ToString(), e.Font, mybsh, e.Bounds, StringFormat.GenericDefault);
- }
- public string CheckFileAccess(string filePath)
- {
- try
- {
- using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
- {
- return "OK";
- }
- }
- catch (IOException ex)
- {
- return "文件被占用: " + ex.Message;
- }
- catch (UnauthorizedAccessException ex)
- {
- return "权限不足,无法访问文件: " + ex.Message;
- }
- catch (Exception ex)
- {
- return ex.Message;
- }
- }
- private class Log
- {
- public string SN { set; get; }
- public string Result { set; get; }
- }
- }
- }
|