using Microsoft.Win32; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Threading; using System.Windows.Forms; using System.Xml; using System.Text; using System.Media; namespace FileWatcher { public partial class AutoAnalysisXml : Form { DataHelper dh; DataTable dt; DataTable DB; /// /// 用户编号 /// string iusercode; /// /// 岗位资源 /// string isource; Tip tipform; Thread InitDB; /// /// 线别 /// string ilinecode; /// /// 不良代码组 /// string ibadgroup; /// /// 当前工序 /// string istepcode; StringBuilder sql = new StringBuilder(); /// /// 缓存的文件 /// public static string CachePath = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/Cache.xml"; /// /// 缓存的文件夹 /// public static string CachePathFolder = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/"; /// /// 需要解析的文件名 /// List _FileName = new List(); ftpOperater ftp = new ftpOperater(); public AutoAnalysisXml() { tipform = new Tip(); InitializeComponent(); StartPosition = FormStartPosition.CenterScreen; } public AutoAnalysisXml(string iUserName, string iSource) { tipform = new Tip(); InitializeComponent(); iusercode = iUserName; isource = iSource.ToUpper(); StartPosition = FormStartPosition.CenterScreen; } private void Form1_Load(object sender, EventArgs e) { tipform.Show(); CheckForIllegalCrossThreadCalls = false; FormBorderStyle = FormBorderStyle.FixedSingle; InitDB = new Thread(ConnectDB); //添加监控事件 SetLoadingWindow stw = new SetLoadingWindow(InitDB, "正在启动程序"); stw.StartPosition = FormStartPosition.CenterScreen; stw.ShowDialog(); List CacheInf = new List(); DB = (DataTable)dh.ExecuteSql("select ms_pwd,ma_user,ma_address,ma_inneraddress from master where ma_user='MES'", "select"); Master.DataSource = DB; Master.DisplayMember = "ma_user"; Master.ValueMember = "ma_user"; //获取缓存信息 try { //FolderPath.Text = BaseUtil.GetCacheData("FolderPath").ToString(); //BackUpFolderPath.Text = BaseUtil.GetCacheData("BackUpFolderPath").ToString(); //Master.Text = BaseUtil.GetCacheData("Master").ToString(); //AutoStart.Checked = (bool)BaseUtil.GetCacheData("AutoStart"); } catch (Exception ex) { MessageBox.Show(ex.Message); } for (int i = 0; i < DB.Rows.Count; i++) { if (Master.Text == DB.Rows[i]["ma_user"].ToString()) { DataHelper.DBConnectionString = "Connection Timeout=0;Pooling=false;Password=select!#%*(;User ID=DGW;Pooling=false;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=113.98.196.181)(PORT=1520)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl)));"; dh = new DataHelper(); } } //获取岗位资源相关信息 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"); if (dt.Rows.Count > 0) { ilinecode = dt.Rows[0]["sc_linecode"].ToString(); istepcode = dt.Rows[0]["sc_stepcode"].ToString(); ibadgroup = dt.Rows[0]["st_badgroupcode"].ToString(); } } private void ConnectDB() { dh = new DataHelper(); } private void StartWatch_Click(object sender, EventArgs e) { if (FolderPath.Text == "") { OperateResult.AppendText("请选择监控文件夹\n"); return; } else { if (!Directory.Exists(FolderPath.Text)) { OperateResult.AppendText("监控文件夹不存在\n"); return; } } for (int i = 0; i < DB.Rows.Count; i++) { if (Master.Text == DB.Rows[i]["ma_user"].ToString()) { DataHelper.DBConnectionString = "Connection Timeout=0;Pooling=false;Password=select!#%*(;User ID=DGW;Pooling=false;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=113.98.196.181)(PORT=1520)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl)));"; dh = new DataHelper(); LogicHandler.dh = new DataHelper(); } } //存在工单必须是已下放状态 if ((!dh.CheckExist("make", "ma_statuscode='STARTED' and ma_code='" + ma_code.Text + "'") || ma_code.Text == "") && Device.Text == "AOI设备") { OperateResult.AppendText("工单不存在或者未下放\n"); return; } //设置缓存数据 //BaseUtil.SetCacheData("FolderPath", FolderPath.Text); //BaseUtil.SetCacheData("BackUpFolderPath", BackUpFolderPath.Text); //BaseUtil.SetCacheData("Master", Master.Text); //BaseUtil.SetCacheData("AutoStart", AutoStart.Checked); //设置按钮不可点击 StartWatch.Enabled = false; ChooseFolder.Enabled = false; Master.Enabled = false; ma_code.Enabled = false; StopWatch.Enabled = true; GetFiles.Start(); OperateResult.AppendText("开始执行监控\n"); } public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value) { XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null); node.InnerText = value; parentNode.AppendChild(node); } string nextLine; private void TxtHandleProcess(string FileName) { List badcode = new List(); List badlocation = new List(); List badprod = new List(); if (Device.Text == "AOI设备") { StreamReader sR = File.OpenText(FileName); DataTable filedt = new DataTable(); //文件内的行,用一个DataTable存储 int Rowindex = 0; while ((nextLine = sR.ReadLine()) != null) { //DataTable用第一行的数据作为列名 string[] title = nextLine.Split(','); DataRow dr = filedt.NewRow(); for (int i = 0; i < title.Length; i++) { if (Rowindex == 0) { filedt.Columns.Add(title[i]); } else { dr[filedt.Columns[i].ColumnName] = title[i]; } } //除了第一行,然后添加到表格中 if (Rowindex > 0) { filedt.Rows.Add(dr); } Rowindex = Rowindex + 1; } sR.Close(); string SN = FileName.Substring(FileName.LastIndexOf(@"\") + 1).Replace("-", "/").ToUpper().Replace(".TXT", ""); string Result = "OK"; string makecode = ""; string stepcode = ""; string oErrMessage = ""; string oMSID = ""; isource = "SMT_01_AOI"; iusercode = "SMT_01_AOI"; 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"); if (dt.Rows.Count > 0) { ilinecode = dt.Rows[0]["sc_linecode"].ToString(); istepcode = dt.Rows[0]["sc_stepcode"].ToString(); ibadgroup = dt.Rows[0]["st_badgroupcode"].ToString(); } if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, isource, SN, iusercode, out makecode, out oMSID, out oErrMessage)) { for (int i = 0; i < filedt.Rows.Count; i++) { if (filedt.Rows[i]["c_result"].ToString() != "OK" && filedt.Rows[i]["c_result"].ToString() != "FC") { Result = "NG"; //只添加一条记录 if (badcode.Count == 0) { badcode.Add(filedt.Rows[i]["w_ng_name"].ToString()); badlocation.Add(filedt.Rows[i]["c_subboard_number"].ToString()); badprod.Add(filedt.Rows[i]["c_subboard_number"].ToString()); } } } //获取序列号ID最大的工单 dt = (DataTable)dh.ExecuteSql("select ms_makecode,ms_id,ms_stepcode from makeserial where ms_sncode='" + SN + "' order by ms_id desc", "select"); if (dt.Rows.Count > 0) { ma_code.Text = dt.Rows[0]["ms_makecode"].ToString(); makecode = dt.Rows[0]["ms_makecode"].ToString(); stepcode = dt.Rows[0]["ms_stepcode"].ToString(); if (stepcode == istepcode) { tipform.startthread("序列号 " + SN + "已执行过" + istepcode, "NG"); OperateResult.AppendText("序列号 " + SN + "已执行过" + istepcode + "\n"); } switch (Result) { case "OK": if (!LogicHandler.SetStepResult(makecode, isource, SN, "自动过站采集", Result, iusercode, out oErrMessage)) { OperateResult.AppendText(oErrMessage + "\n"); tipform.startthread(oErrMessage, Result); File.Delete(FileName); } tipform.startthread("序列号 " + SN + "通过检测", Result); OperateResult.AppendText("序列号 " + SN + "通过检测" + "\n"); break; case "NG": RecordBadInfo(SN, makecode, FileName, "", badcode.ToArray(), badlocation.ToArray(), badprod.ToArray()); //所有的序列号均采集为良品 if (!LogicHandler.SetTestNGDetail(SN, makecode, iusercode, isource, Result, out oErrMessage)) { OperateResult.AppendText(oErrMessage + "\n"); tipform.startthread(oErrMessage, Result); File.Delete(FileName); } tipform.startthread("序列号 " + SN + "未通过检测", Result); OperateResult.AppendText("序列号 " + SN + "未通过检测" + "\n"); break; default: break; } } } else { OperateResult.AppendText(oErrMessage + "\n"); tipform.startthread(oErrMessage, Result); // File.Delete(FileName); } } else if (Device.Text == "测试设备") { try { string filename = FileName; if (filename.Substring(filename.LastIndexOf(".") + 1).ToUpper() == "TXT" && !filename.ToUpper().Contains("TEMP")) { string folderpath = FileName.Substring(0, FileName.LastIndexOf(@"\")); string SN = FileName.Substring(FileName.LastIndexOf(@"\") + 1).Replace("-", "/").ToUpper().Replace(".TXT", ""); if (MAC.Checked) { string Result = ""; string makecode = ma_code.Text; string oErrMessage = ""; string oMSID = ""; string ms_sncode = dh.getFieldDataByCondition("makeserial", "ms_sncode", "substr(ms_sncode,0,12)='" + SN + "' order by ms_id").ToString(); isource = "SMT_01_TEST01"; iusercode = "SMT_01_TEST01"; 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"); if (dt.Rows.Count > 0) { ilinecode = dt.Rows[0]["sc_linecode"].ToString(); istepcode = dt.Rows[0]["sc_stepcode"].ToString(); ibadgroup = dt.Rows[0]["st_badgroupcode"].ToString(); } if (LogicHandler.CheckStepSNAndMacode("", isource, ms_sncode, iusercode, out makecode, out oMSID, out oErrMessage)) { ma_code.Text = makecode; if (LogicHandler.SetStepResult(makecode, isource, ms_sncode, "自动过站采集", "OK", iusercode, out oErrMessage)) { try { string ftppath = "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/"; ftp.UpLoadFile(folderpath, SN + ".txt", ftppath, ""); int num = int.Parse(dh.ExecuteSql("insert into STEPTESTDETAIL (std_id,std_sn,std_makecode,std_indate,std_class)select STEPTESTDETAIL_seq.nextval,ms_sncode,ms_makecode,sysdate,'http://113.98.196.181:8099/ftp" + ftppath + SN + ".txt" + "' from makeserial where substr(ms_sncode,0,12)='" + SN + "'", "insert").ToString()); if (num > 0) { OperateResult.AppendText("序列号:" + SN + "上传成功\n"); File.Delete(FileName); } else { OperateResult.AppendText("序列号: " + SN + "前工段未扫描\n"); MessageBox.Show("序列号: " + ms_sncode + "前工段未扫描", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } else { OperateResult.AppendText(oErrMessage + "\n"); tipform.startthread(oErrMessage, Result); } tipform.startthread("序列号 " + ms_sncode + "通过检测", Result); } else { //File.Delete(FileName); OperateResult.AppendText(oErrMessage + "\n"); tipform.startthread(oErrMessage, Result); } } else { string Result = ""; string makecode = ma_code.Text; string oErrMessage = ""; string oMSID = ""; string ms_sncode = dh.getFieldDataByCondition("makeserial", "ms_sncode", "ms_sncode='" + SN + "' order by ms_id").ToString(); isource = "SMT_01_TEST01"; iusercode = "SMT_01_TEST01"; 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"); if (dt.Rows.Count > 0) { ilinecode = dt.Rows[0]["sc_linecode"].ToString(); istepcode = dt.Rows[0]["sc_stepcode"].ToString(); ibadgroup = dt.Rows[0]["st_badgroupcode"].ToString(); } if (LogicHandler.CheckStepSNAndMacode("", isource, ms_sncode, iusercode, out makecode, out oMSID, out oErrMessage)) { ma_code.Text = makecode; if (LogicHandler.SetStepResult(makecode, isource, ms_sncode, "自动过站采集", "OK", iusercode, out oErrMessage)) { try { string ftppath = "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/"; ftp.UpLoadFile(folderpath, SN + ".txt", ftppath, ""); int num = int.Parse(dh.ExecuteSql("insert into STEPTESTDETAIL (std_id,std_sn,std_makecode,std_indate,std_class)select STEPTESTDETAIL_seq.nextval,ms_sncode,ms_makecode,sysdate,'http://113.98.196.181:8099/ftp" + ftppath + SN + ".txt" + "' from makeserial where ms_sncode='" + SN + "'", "insert").ToString()); if (num > 0) { OperateResult.AppendText("序列号:" + SN + "上传成功\n"); File.Delete(FileName); } else { OperateResult.AppendText("序列号: " + SN + "前工段未扫描\n"); MessageBox.Show("序列号: " + ms_sncode + "前工段未扫描", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } else { OperateResult.AppendText(oErrMessage + "\n"); tipform.startthread(oErrMessage, Result); } tipform.startthread("序列号 " + ms_sncode + "通过检测", Result); } else { // File.Delete(FileName); OperateResult.AppendText(oErrMessage + "\n"); tipform.startthread(oErrMessage, Result); } } OperateResult.AppendText("解析成功:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\n" + FileName + "\n"); } } catch (Exception e) { OperateResult.AppendText("解析失败:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\n" + FileName + "\n" + e.Message + "\n"); } } } /// /// 使用进程处理文件,避免界面假死 /// private void RecordBadInfo(string sncode, string makecode, string filename, string combine, string[] badcode, string[] badlocation, string[] soncode) { string[] ID = dh.GetSEQ("makebad_seq", badcode.Length); sql.Clear(); sql.Append("update makebad set mb_status=-1 where mb_sncode='" + sncode + "' and mb_stepcode='" + istepcode + "' and mb_makecode='" + makecode + "' and mb_status=0"); dh.ExecuteSql(sql.ToString(), "update"); sql.Clear(); sql.Append("insert into makebad(mb_id,mb_makecode,mb_mscode,mb_sncode,mb_inman,mb_indate,mb_stepcode"); sql.Append(",mb_sourcecode,mb_badname,mb_bgcode,mb_badtable,mb_status,mb_badlocation,mb_soncode,mb_content) select :ID"); sql.Append(",ma_code,ms_code,ms_sncode,'" + iusercode + "',sysdate,'" + istepcode + "','" + isource + "',"); sql.Append(":bc_code,'WG','','0',:location,:soncode,'" + nextLine + "' from make left join makeSerial on ms_makecode=ma_code "); sql.Append("where ms_sncode='" + sncode + "' and ms_makecode='" + makecode + "'"); dh.BatchInsert(sql.ToString(), new string[] { "ID", "bc_code", "location", "soncode" }, ID, badcode, badlocation, soncode); sql.Clear(); sql.Append("update makebad set mb_badcode=(select DISTINCT bc_code from badcode where bc_name=mb_badcode),mb_badname=mb_badcode,mb_bgname=(select DISTINCT bg_name from badgroup where bg_code=mb_bgcode) "); sql.Append("where mb_id=:ID"); dh.BatchInsert(sql.ToString(), new string[] { "ID" }, ID); //记录判断日志 if (dh.getFieldDataByCondition("source", "sc_scantype", "sc_code='" + isource + "'").ToString() == "REJUCE") { LogicHandler.AutoPassJudge(sncode, makecode, isource, filename, ilinecode, combine); } } private void StopWatch_Click(object sender, EventArgs e) { XmlWatcher.EnableRaisingEvents = false; StartWatch.Enabled = true; ma_code.Enabled = true; Master.Enabled = true; ChooseFolder.Enabled = true; StopWatch.Enabled = false; GetFiles.Stop(); OperateResult.AppendText("停止执行监控\n"); } private void Clean_Click(object sender, EventArgs e) { OperateResult.Clear(); } private void ChooseFolder_Click(object sender, EventArgs e) { FolderBrowserDialog folder = new FolderBrowserDialog(); folder.Description = "选择监控文件夹"; DialogResult result = folder.ShowDialog(); if (result == DialogResult.OK) { FolderPath.Text = folder.SelectedPath; } } private void ChooseBackUpFolder_Click(object sender, EventArgs e) { FolderBrowserDialog folder = new FolderBrowserDialog(); folder.Description = "选择备份文件夹"; DialogResult result = folder.ShowDialog(); if (result == DialogResult.OK) { } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { string ExitConfirm = MessageBox.Show(this, "确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString(); if (ExitConfirm != "Yes") { WindowState = FormWindowState.Minimized; e.Cancel = true; } } private void AutoStart_CheckedChanged(object sender, EventArgs e) { SetAutoRun(); } private void SetAutoRun() { if (AutoStart.Checked) //设置开机自启动 { string path = Application.ExecutablePath; RegistryKey rk = Registry.LocalMachine; RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); rk2.SetValue("UAS自动过站解析器.exe", path); rk2.Close(); rk.Close(); } else //取消开机自启动 { string path = Application.ExecutablePath; RegistryKey rk = Registry.LocalMachine; RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); rk2.DeleteValue("UAS自动过站解析器.exe", false); rk2.Close(); rk.Close(); } } private void BatchAnalysus_Click(object sender, EventArgs e) { var AllXmls = Directory.GetFiles(FolderPath.Text, "*.txt"); foreach (var Xml in AllXmls) { TxtHandleProcess(Xml); } } private void Timer_Tick(object sender, EventArgs e) { dh.ExecuteSql("select sysdate from dual", "select"); } private void GetFiles_Tick(object sender, EventArgs e) { var AllXmls = Directory.GetFiles(FolderPath.Text, "*.txt"); foreach (var Xml in AllXmls) { TxtHandleProcess(Xml); } } } }