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;
///
/// 用户编号
///
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();
string master = "WKS";
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.Created += new FileSystemEventHandler(XmlWatcher_Created);
XmlWatcher.Changed += new FileSystemEventHandler(XmlWatcher_Created);
SetLoadingWindow stw = new SetLoadingWindow(InitDB, "正在启动程序");
stw.StartPosition = FormStartPosition.CenterScreen;
stw.ShowDialog();
List CacheInf = new List();
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();
//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();
}
}
private void ConnectDB()
{
DataHelper.DBConnectionString = "Connection Timeout=0;Pooling=false;Password=select!#%*(;User ID=N_MES;Pooling=false;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.101.253)(PORT=11678)))(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.Filter = "*.log|*.ini";
XmlWatcher.EnableRaisingEvents = true;
//设置缓存数据
//BaseUtil.SetCacheData("FolderPath", FolderPath.Text);
//BaseUtil.SetCacheData("BackUpFolderPath", BackUpFolderPath.Text);
//BaseUtil.SetCacheData("Master", Master.Text);
//BaseUtil.SetCacheData("AutoStart", AutoStart.Checked);
Timer.Interval = 1000 * 10;
Timer.Start();
//设置按钮不可点击
StartWatch.Enabled = false;
ChooseFolder.Enabled = false;
Master.Enabled = false;
ma_code.Enabled = false;
StopWatch.Enabled = true;
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);
}
private void XmlWatcher_Created(object sender, FileSystemEventArgs e)
{
}
string nextLine;
private void TxtHandleProcess(string FileName)
{
List badcode = new List();
List badlocation = new List();
List badprod = new List();
if (Device.Text == "老化设备")
{
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)
{
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;
default:
break;
}
}
dr[filedt.Columns[i].ColumnName] = title[i];
}
filedt.Rows.Add(dr);
Rowindex = Rowindex + 1;
}
sR.Close();
for (int i = 0; i < filedt.Rows.Count; i++)
{
string filename = filedt.Rows[i]["文件路径"].ToString();
string ftppath = "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
string folderpath = filename.Substring(0, filename.LastIndexOf(@"\"));
ftp.UpLoadFile(folderpath, filename, ftppath, "");
dh.ExecuteSql("insert into Devicetestinfo(dti_id,dti_prodcode,dti_area,dti_uptime,dti_downtime,dti_upqty,dti_okqty,dti_ngqty,dti_ipaddress,dti_filepath,dti_indate)values(Devicetestinfo_seq.nextval,'" + 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 + "','http://192.168.6.253:8099/ftp" + ftppath + filename + "',sysdate)", "insert");
}
}
else if (Device.Text == "ATE设备")
{
try
{
StreamReader sR = File.OpenText(FileName);
string filename = FileName;
List programname = new List();
List data = new List();
Regex re = new Regex(@"\d+");
if (filename.Substring(filename.LastIndexOf(".") + 1).ToUpper() == "INI")
{
while ((nextLine = sR.ReadLine()) != null)
{
programname.Add(nextLine);
}
string[] str = programname.ToArray();
for (int i = str.Length - 4; i < str.Length; i++)
{
if (str[i].Contains("["))
{
data.Add(str[i]);
}
else
{
data.Add(re.Match(str[i]).Groups[0].Value);
}
}
dh.ExecuteSql("insert into ATETESTDATA(atd_id,atd_name,atd_passqty,atd_ngqty,atd_lastqty,atd_ipaddress,atd_makecode,atd_makecode)values(ATETESTDATA_seq.nextval,'" + data.ToArray()[0] + "','" + data.ToArray()[1] + "','" + data.ToArray()[2] + "','" + data.ToArray()[3] + "','" + IPAddress + "','" + ma_code.Text + "',sysdate)", "insert");
}
}
catch (Exception e)
{
OperateResult.AppendText("解析失败:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\n" + FileName + "\n" + e.Message + "\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("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);
//}
//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);
}
}
}
}