123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547 |
- 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.Net;
- using System.Net.Sockets;
- using System.Text.RegularExpressions;
- namespace FileWatcher
- {
- public partial class AutoAnalysisDevice : Form
- {
- DataHelper dh;
- DataTable dt;
- DataTable DB;
- /// <summary>
- /// 用户编号
- /// </summary>
- string iusercode;
- /// <summary>
- /// 岗位资源
- /// </summary>
- string isource;
- Tip tipform;
- Thread InitDB;
- /// <summary>
- /// 线别
- /// </summary>
- string ilinecode;
- /// <summary>
- /// 不良代码组
- /// </summary>
- string ibadgroup;
- /// <summary>
- /// 当前工序
- /// </summary>
- string istepcode;
- StringBuilder sql = new StringBuilder();
- /// <summary>
- /// 缓存的文件
- /// </summary>
- public static string CachePath = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/Cache.xml";
- /// <summary>
- /// 缓存的文件夹
- /// </summary>
- public static string CachePathFolder = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/";
- /// <summary>
- /// 需要解析的文件名
- /// </summary>
- List<string> _FileName = new List<string>();
- string master = "HUAG";
- ftpOperater ftp = new ftpOperater();
- public AutoAnalysisDevice()
- {
- tipform = new Tip();
- InitializeComponent();
- StartPosition = FormStartPosition.CenterScreen;
- }
- public AutoAnalysisDevice(string iUserName, string iSource, string iMaster)
- {
- tipform = new Tip();
- InitializeComponent();
- iusercode = iUserName;
- isource = iSource.ToUpper();
- master = iMaster;
- StartPosition = FormStartPosition.CenterScreen;
- }
- string IPAddress = "";
- private void Form1_Load(object sender, EventArgs e)
- {
- tipform.Show();
- CheckForIllegalCrossThreadCalls = false;
- FormBorderStyle = FormBorderStyle.FixedSingle;
- InitDB = new Thread(ConnectDB);
- //添加监控事件
- XmlWatcher.Changed += new FileSystemEventHandler(XmlWatcher_Created);
- //ATEFile.Changed += new FileSystemEventHandler(XmlWatcher_Created);
- SetLoadingWindow stw = new SetLoadingWindow(InitDB, "正在启动程序");
- stw.StartPosition = FormStartPosition.CenterScreen;
- stw.ShowDialog();
- List<string> CacheInf = new List<string>();
- IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
- for (int i = 0; i < IpEntry.AddressList.Length; i++)
- {
- if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
- IPAddress = IpEntry.AddressList[i].ToString();
- }
- //获取缓存信息
- try
- {
- FolderPath.Text = BaseUtil.GetCacheData("FolderPath").ToString();
- Device.Text = BaseUtil.GetCacheData("Device").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); }
- //获取岗位资源相关信息
- 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();
- }
- StartWatch.PerformClick();
- }
- private void ConnectDB()
- {
- DataHelper.DBConnectionString = "Connection Timeout=0;Pooling=false;Password=select!#%*(;User ID="+Master+";Pooling=false;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=81.71.42.91)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl)));";
- 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;
- }
- }
- XmlWatcher.Path = FolderPath.Text;
- XmlWatcher.EnableRaisingEvents = true;
- XmlWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
- //ATEFile.Path = FolderPath.Text;
- //ATEFile.EnableRaisingEvents = true;
- //ATEFile.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
- //设置缓存数据
- BaseUtil.SetCacheData("FolderPath", FolderPath.Text);
- BaseUtil.SetCacheData("Device", Device.Text);
- //BaseUtil.SetCacheData("BackUpFolderPath", BackUpFolderPath.Text);
- //BaseUtil.SetCacheData("Master", Master.Text);
- //BaseUtil.SetCacheData("AutoStart", AutoStart.Checked);
- Timer.Interval = 1000 * 60;
- Timer.Start();
- //设置按钮不可点击
- StartWatch.Enabled = false;
- ChooseFolder.Enabled = false;
- Master.Enabled = false;
- ma_code.Enabled = false;
- StopWatch.Enabled = true;
- OperateResult.AppendText("开始执行监控\n");
- }
- private void XmlWatcher_Created(object sender, FileSystemEventArgs e)
- {
- OperateResult.AppendText("文件修改:" + e.FullPath + "\n");
- TxtHandleProcess(e.FullPath);
- }
- string nextLine;
- private void TxtHandleProcess(string FileName)
- {
- List<string> badcode = new List<string>();
- List<string> badlocation = new List<string>();
- List<string> badprod = new List<string>();
- if (Device.Text == "老化设备")
- {
- StreamReader sR = new StreamReader(FileName, Encoding.Default);
- Console.WriteLine(sR.CurrentEncoding);
- 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)
- {
- switch (i)
- {
- case 0:
- filedt.Columns.Add("登陆的账号");
- break;
- case 1:
- filedt.Columns.Add("工位固定号");
- break;
- case 2:
- filedt.Columns.Add("区域");
- break;
- case 3:
- filedt.Columns.Add("产品代码");
- break;
- case 4:
- filedt.Columns.Add("计划单号");
- break;
- case 5:
- filedt.Columns.Add("上架时间");
- break;
- case 6:
- filedt.Columns.Add("下架时间");
- break;
- case 7:
- filedt.Columns.Add("上架数量");
- break;
- case 8:
- filedt.Columns.Add("合格数量");
- break;
- case 9:
- filedt.Columns.Add("不良数量");
- break;
- case 10:
- filedt.Columns.Add("文件路径");
- break;
- default:
- break;
- }
- }
- dr[filedt.Columns[i].ColumnName] = title[i];
- }
- filedt.Rows.Add(dr);
- Rowindex = Rowindex + 1;
- }
- sR.Close();
- OperateResult.AppendText("文件修改" + filedt.Rows.Count + "\n");
- for (int i = 0; i < filedt.Rows.Count; i++)
- {
- if (!dh.CheckExist("Devicetestinfo", "(dti_uptime)=to_date('" + filedt.Rows[i]["上架时间"].ToString() + "','yyyy/mm/dd hh24:mi:ss') and dti_ipaddress='" + IPAddress + "'"))
- {
- string filename = filedt.Rows[i]["文件路径"].ToString();
- Dictionary<string, object> dic = new Dictionary<string, object>
- {
- { "em_name", "管理员" },
- { "em_code", "ADMIN" },
- { "caller", "AGING" }
- };
- string fp_id;
- string fp_path;
- UploadFilesToRemoteUrl("http://192.168.101.253:8099/mes/MEScommon/uploadFiles.action?_noc=1", filename, dic, out fp_path, out fp_id);
- fp_path = "http://192.168.101.253:8099/" + fp_path.Replace("/app/uas/webapps/", "");
- fp_path = fp_path.Replace("\"", "");
- dh.ExecuteSql("insert into Devicetestinfo(dti_id,dti_account,dti_stepcode,dti_makecode,dti_prodcode,dti_area,dti_uptime,dti_downtime,dti_upqty,dti_okqty,dti_ngqty,dti_ipaddress,dti_filepath,dti_indate,dti_fpid,dti_type)values(Devicetestinfo_seq.nextval,'" + filedt.Rows[i]["登陆的账号"].ToString() + "','"+ filedt.Rows[i]["工位固定号"].ToString() + "','"+ filedt.Rows[i]["计划单号"].ToString() + "','" + 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");
- OperateResult.AppendText("上传文件" + filename + "\n");
- }
- }
- }
- else if (Device.Text == "ATE设备")
- {
- if (!FileName.Contains("ATE日志文件")) {
- return;
- }
- StreamReader sR = new StreamReader(FileName, Encoding.Default);
- Console.WriteLine(sR.CurrentEncoding);
- 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)
- {
- switch (i)
- {
- case 0:
- filedt.Columns.Add("登录的账号");
- break;
- case 1:
- filedt.Columns.Add("工位固定号");
- break;
- case 2:
- filedt.Columns.Add("产品代码");
- break;
- case 3:
- filedt.Columns.Add("计划单号");
- break;
- case 4:
- filedt.Columns.Add("使用参数名");
- break;
- case 5:
- filedt.Columns.Add("通道");
- break;
- case 6:
- filedt.Columns.Add("开始时间");
- break;
- case 7:
- filedt.Columns.Add("结束时间");
- break;
- case 8:
- filedt.Columns.Add("上架数量");
- break;
- case 9:
- filedt.Columns.Add("合格数量");
- break;
- case 10:
- filedt.Columns.Add("不良数量");
- break;
- case 11:
- filedt.Columns.Add("文件路径");
- break;
- default:
- break;
- }
- }
- dr[filedt.Columns[i].ColumnName] = title[i];
- }
- filedt.Rows.Add(dr);
- Rowindex = Rowindex + 1;
- }
- sR.Close();
- OperateResult.AppendText("文件修改" + filedt.Rows.Count + "\n");
- for (int i = 0; i < filedt.Rows.Count; i++)
- {
- if (!dh.CheckExist("Devicetestinfo", "(dti_uptime)=to_date('" + filedt.Rows[i]["开始时间"].ToString() + "','yyyy/mm/dd hh24:mi:ss') and dti_ipaddress='" + IPAddress + "'"))
- {
- string filename = filedt.Rows[i]["文件路径"].ToString();
- Dictionary<string, object> dic = new Dictionary<string, object>
- {
- { "em_name", "管理员" },
- { "em_code", "ADMIN" },
- { "caller", "AGING" }
- };
- string fp_id;
- string fp_path;
- UploadFilesToRemoteUrl("http://192.168.101.253:8099/mes/MEScommon/uploadFiles.action?_noc=1", filename, dic, out fp_path, out fp_id);
- fp_path = "http://192.168.101.253:8099/" + fp_path.Replace("/app/uas/webapps/", "");
- fp_path = fp_path.Replace("\"", "");
- dh.ExecuteSql("insert into Devicetestinfo(dti_id,dti_prodcode,dti_uptime,dti_downtime,dti_upqty,dti_okqty,dti_ngqty,dti_ipaddress,dti_filepath,dti_indate,dti_fpid,dti_account,dti_stepcode,dti_makecode,dti_param,dti_route,dti_type)values(Devicetestinfo_seq.nextval,'" + 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 + "','" + filedt.Rows[i]["登录的账号"].ToString() + "','" + filedt.Rows[i]["工位固定号"].ToString() + "','" + filedt.Rows[i]["计划单号"].ToString() + "','" + filedt.Rows[i]["使用参数名"].ToString() + "','" + filedt.Rows[i]["通道"].ToString() + "','ATE')", "insert");
- OperateResult.AppendText("上传文件" + filename + "\n");
- }
- }
- }
- }
- 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;
- 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("FileWatcher.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("FileWatcher.exe", false);
- rk2.Close();
- rk.Close();
- }
- }
- private void BatchAnalysus_Click(object sender, EventArgs e)
- {
- TxtHandleProcess(@"C:\Users\callm\Desktop\导入数据\客户资料\睿德电子\新建文本文档.log");
- //TxtHandleProcess(@"C:\Users\callm\Desktop\导入数据\客户资料\睿德电子\PowerTestTj.ini");
- }
- private void Timer_Tick(object sender, EventArgs e)
- {
- var AllXmls = Directory.GetFiles(FolderPath.Text, "*.txt");
- foreach (var Xml in AllXmls)
- {
- TxtHandleProcess(Xml);
- }
- }
- /// <summary>
- /// 请求上传图片到阿里云
- /// </summary>
- /// <param name="url">上传地址</param>
- /// <param name="filepath">本地文件路径</param>
- /// <param name="dic">上传的数据信息</param>
- /// <returns></returns>
- public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic, out string fp_path, out string fp_id)
- {
- fp_id = "";
- fp_path = "";
- try
- {
- ServicePointManager.DefaultConnectionLimit = 50;
- string boundary = DateTime.Now.Ticks.ToString("x");
- byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
- request.Method = "POST";
- request.Timeout = 10 * 10000;
- request.ContentType = "multipart/form-data; boundary=" + boundary;
- Stream rs = request.GetRequestStream();
- var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
- string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
- if (dic != null)
- {
- foreach (string key in dic.Keys)
- {
- rs.Write(boundarybytes, 0, boundarybytes.Length);
- string formitem = string.Format(formdataTemplate, key, dic[key]);
- byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
- rs.Write(formitembytes, 0, formitembytes.Length);
- }
- }
- string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
- {
- rs.Write(boundarybytes, 0, boundarybytes.Length);
- var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
- var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
- rs.Write(headerbytes, 0, headerbytes.Length);
- using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
- {
- var buffer = new byte[1024];
- var bytesRead = 0;
- while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
- {
- rs.Write(buffer, 0, bytesRead);
- }
- }
- var cr = Encoding.UTF8.GetBytes("\r\n");
- rs.Write(cr, 0, cr.Length);
- }
- rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
- var response = request.GetResponse() as HttpWebResponse;
- StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
- string Content = newReader.ReadToEnd();
- Dictionary<string, object> dic1 = new Dictionary<string, object>();
- List<Dictionary<string, object>> dic2 = null;
- dic1 = BaseUtil.ToDictionary(Content);
- dic2 = dic1["data"] as List<Dictionary<string, object>>;
- if (dic2[0]["filepath"] != null)
- {
- fp_id = dic2[0]["filepath"].ToString();
- fp_path = dic2[0]["path"].ToString();
- }
- if (response.StatusCode == HttpStatusCode.OK)
- {
- Console.WriteLine(fp_id);
- return fp_id;
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message + e.StackTrace);
- }
- return "";
- }
- }
- }
|