天津投入产出系统后端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

521 lines
24 KiB

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using QM.Data.DBProvider.SqlServer;
using QMAPP.FJC.Entity;
using QMAPP.FJC.Entity.ProcessParameter;
using QMAPP.FJC.Entity.FileCopy;
using QMAPP.FJC.BLL.FileCopy;
using QMAPP.FJC.Entity.Basic;
using QMAPP.FJC.BLL.Basic;
using QMAPP.FJC.BLL.Process;
using System.Linq;
using QMFrameWork.Log;
namespace AutoFileCopyNet.EngelFileAnalytic
{
public class Engel
{
public void Run()
{
try
{
//取恩格尔设备编号
StringBuilder sb1 = new StringBuilder();
string engeltype = ConfigurationManager.AppSettings["DCS_ET_START_TYPE"].ToString();
List<MachineInfo> listMachine = new MachineInfoBLL().GetAllList(new MachineInfo { EQUIPMENT_TYPE_CODE = engeltype });
foreach (MachineInfo dr in listMachine)
{
//复制文件
LogFileAccess.WriteLogFile("服务开始复制" + "---" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
CopyFile(dr);
//解析文件
LogFileAccess.WriteLogFile("服务开始解析" + "---" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
ExpFile(dr);
//定时删除文件
if ("1".Equals(ConfigurationManager.AppSettings["NEEDDEL"].ToString()))
{
AutoFileCopy.AutoFileDelete(dr, ConfigurationManager.AppSettings["SHARESERVER_IP"].ToString()
, ConfigurationManager.AppSettings["DCSLocalDriverPath"].ToString()
, DirHandler.GetNewPrefix()
, ConstParam.ERROR_MESSAGE_HEAD
, ConfigurationManager.AppSettings["CONWAY"].ToString()
, ConfigurationManager.AppSettings["DELDAY"].ToString()
, ConfigurationManager.AppSettings["STARTTIME"].ToString()
, ConfigurationManager.AppSettings["ENDTIME"].ToString()
, ConfigurationManager.AppSettings["DELTIME"].ToString()
, ConfigurationManager.AppSettings["DCS_FILEPATH_BAK"].ToString()+ dr.MACHINECODDE +"\\");
}
}
}
catch (Exception e)
{
LogFileAccess.WriteLogFile("恩格尔数据文件解析失败" + e.Message + e.Source + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
/// <summary>
/// 复制文件
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
private bool CopyFile(MachineInfo info)
{
bool result = false;
try
{
String equipmentType = ConfigurationManager.AppSettings["DCS_ET_START_TYPE"].ToString();
String toDir = ConfigurationManager.AppSettings["DCS_FILEPATH"].ToString();//目标目录
String localDriverPath = ConfigurationManager.AppSettings["DCSLocalDriverPath"].ToString();//磁盘映射名
String fileRenamePrefix = DirHandler.GetNewPrefix();//随机数
String errorMessageHead = ConstParam.ERROR_MESSAGE_HEAD;//错误信息
string server_ip = ConfigurationManager.AppSettings["SHARESERVER_IP"].ToString();//服务IP
string conn_way = ConfigurationManager.AppSettings["CONWAY"].ToString();//打开连接方式
AutoFileCopy.AutoFileCopyFromEquipmentByType(info, equipmentType, server_ip, toDir, localDriverPath, fileRenamePrefix, errorMessageHead, conn_way);
}
catch (Exception ex)
{
LogFileAccess.WriteLogFile("恩格尔网络共享文件抓取失败" + ex.Message + ex.Source + "---" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}
return result;
}
/// <summary>
/// 解析文件
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
private bool ExpFile(MachineInfo dr)
{
bool result = false;
string ekey = dr.PID.ToString();
List<FileCopyRecord> listFile = new FileCopyRecordBLL().GetAllList(new FileCopyRecord { EQUIPMENT_INFO_KEY = ekey, FILE_HOSTNAME = Dns.GetHostName(), IsOperation = true });
foreach (FileCopyRecord row in listFile)
{
string filepath = row.RECORD_EQUIPMENT_DIRECTORY.ToString();
string filename = row.RECORD_FILENAME.ToString();
filepath = filepath + filename;
if (File.Exists(filepath))
{
//修改为使用西欧字符集
System.IO.StreamReader b = new System.IO.StreamReader(filepath, System.Text.Encoding.GetEncoding("iso-8859-1"));
string s = string.Empty;
string modelType = "";//定义当前注塑机加工产品类型
string[] modelTypes = ConfigurationManager.AppSettings["PRODUCT_TYPES"].Split(',');
while ((s = b.ReadLine()) != null)
{
if (s.Trim().Length > 0)
{
string[] st = modelTypes.Intersect(s.Trim().Split(';')).ToArray();
if (st.Length > 0)
{
modelType = st[0];
}
}
//s就是 取到的每行的值
if (!string.IsNullOrEmpty(modelType) && s.Contains("ASZ") && s.Length > 50)
{
string strtitle = GetExcelTitle(s);
string opDate = new InjectionProcess().GetMaxEDate(new InJectionParameter() { MACHINECODDE = dr.MACHINECODDE });
//读下一行
string dataline = string.Empty;
while ((dataline = b.ReadLine()) != null)
{
string insertdata = GetExcelValues(dataline.Replace(",", "."));
if (insertdata != "0")
{
if (string.IsNullOrEmpty(insertdata))
{
break;
}
try
{
if (insertdata.Split(',').Length < strtitle.Split(',').Length)//列头与数据数量不匹配
{
continue;
}
SaveImpor(ekey, strtitle, insertdata, dr, modelType, opDate);
}
catch (Exception ex)
{
LogFileAccess.WriteLogFile("恩格尔解析行数据失败" + ex.Message + ex.Source + "---" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
continue;
}
}
}
modelType = "";
}
}
b.Close();
updateFile(ekey, filename, Dns.GetHostName());
}
}
return result;
}
private void updatecopyfile(string fromDir, string EQUIPMENT_INFO_KEY, string EQUIPMENT_Code, string EQUIPMENT_Type_Code, string toDir)
{
FileCopyRecordBLL bll = new FileCopyRecordBLL();
FileCopyRecord record = new FileCopyRecord();
if (!System.IO.Directory.Exists(fromDir))
{
//创建磁盘映射Y
return;
}
if (toDir[toDir.Length - 1] != System.IO.Path.DirectorySeparatorChar)
{
toDir += System.IO.Path.DirectorySeparatorChar;
}
if (!System.IO.Directory.Exists(toDir))
{
System.IO.Directory.CreateDirectory(toDir);
}
DirectoryInfo Dir = new DirectoryInfo(fromDir);
try
{
foreach (FileInfo f in Dir.GetFiles()) //查找文件
{
string hostname = Dns.GetHostName();
string lastwritetime = f.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
//查询该文件是否复制过,如果没有复制过,则开始复制该文件
List<FileCopyRecord> list = bll.GetAllList(new FileCopyRecord { RECORD_FILENAME =f.Name, EQUIPMENT_INFO_KEY = EQUIPMENT_INFO_KEY, FILE_HOSTNAME =hostname});
//判断数据库中是否有记录,如果没有则插入数据
string templastwrit = "";
if (list.Count > 0)
{
templastwrit = list[0].FILE_LASTWRITETIME.ToString();
}
if (list.Count <= 0)
{
File.Copy(f.FullName, toDir + f.Name, true);
#region "把文件复制记录写入数据库"
record.RECORD_KEY = Guid.NewGuid().ToString();
record.RECORD_EQUIPMENT_CODE = EQUIPMENT_Code;
record.RECORD_EQUIPMENT_TYPE_CODE = EQUIPMENT_Type_Code;
record.RECORD_EQUIPMENT_DIRECTORY = toDir;
record.RECORD_KEYWORDS = EQUIPMENT_Code;
record.RECORD_COPY_DATETIME = DateTime.Now;
record.RECORD_READFLAG = "0";
record.RECORD_FILENAME = f.Name;
record.EQUIPMENT_INFO_KEY = EQUIPMENT_INFO_KEY;
//record.FILE_LASTWRITETIME = lastwritetime;
record.FILE_HOSTNAME = hostname;
bll.Insert(record);
#endregion
}
else if (lastwritetime != templastwrit)
{
File.Copy(f.FullName, toDir + f.Name, true);//复制后覆盖原文件
#region "把修改数据库中文件复制时间"
record = list[0];
record.RECORD_COPY_DATETIME = DateTime.Now;
//record.FILE_LASTWRITETIME = lastwritetime;
record.RECORD_FILENAME = f.Name;
record.FILE_HOSTNAME = Dns.GetHostName();
bll.Update(record);
#endregion
}
else if (!File.Exists(@toDir + f.Name))
{
File.Copy(f.FullName, toDir + f.Name, true);
}
}
}
catch (Exception e)
{
LogFileAccess.WriteLogFile("恩格尔数据复制文件失败" + e.Message + e.Source + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
private void updateFile(string ekey, string filename, string file_hostname)
{
string strdatatime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
try
{
new FileCopyRecordBLL().UpdateForTime(ekey, filename, file_hostname, strdatatime);
}
catch (Exception ex)
{
LogFileAccess.WriteLogFile("恩格尔更新数据失败" + ex.Message + ex.Source + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
/// <summary>
/// 保存解析后的数据。
/// </summary>
/// <param name="strtitle"></param>
/// <param name="insertdata"></param>
private void SaveImpor(string eqkey, string strtitle, string insertdata,MachineInfo machine,string productType,string opDate)
{
InJectionParameter injectPara = new InJectionParameter();
string tempbarcode = productType;//设置当前零件类别
//有日期取出来和数据库最大时间比较,小的不插
bool insertflg = false;
//insertflg = new InjectionProcess().CheckParameter(tempbarcode, barcode);//判断数据库是否存在相同条码的零件
if (insertflg == false)
{
//插入数据库
////把日期和时间两列手动加入到序列中,最后拼写sql插入数据时,根据datetime拆分为日期和时间
string[] strtitles = strtitle.Split(',');
string[] insertdatas = insertdata.Split(',');
int index = -1;
index = Array.IndexOf(strtitles, "SZX");//产品序列号
//if (index >= 0)
// injectPara.SZX = insertdatas[index];
index = Array.IndexOf(strtitles, "");//生成日期
//if (index >= 0 && index < strtitles.Length - 3)
//{
// DateTime dtGet = new DateTime();
// if (DateTime.TryParse(insertdatas[index],out dtGet))
// {
// injectPara.EDATE = insertdatas[index];
// //LogFileAccess.WriteLogFile("恩格尔解析行数据-------opdate:" + opDate + "---injectPara.EDATE:" + injectPara.EDATE);
// if (!string.IsNullOrEmpty(opDate) && Convert.ToDateTime(opDate) >= Convert.ToDateTime(injectPara.EDATE))//如果加工日期小于数据库存储最大日期则不执行
// {
// return;
// }
// injectPara.EMACHINECODE = insertdatas[index + 1];//机器设备号
// injectPara.EOPERATORCODE = insertdatas[index + 2];//操作人员号
// }
// else
// {
// int newCode = 0;
// if (int.TryParse(insertdatas[index],out newCode))
// {
// injectPara.SZX = insertdatas[index];
// }
// injectPara.EDATE = insertdatas[index+1];
// //LogFileAccess.WriteLogFile("恩格尔解析行数据-------opdate:" + opDate + "---injectPara.EDATE:" + injectPara.EDATE);
// if (!string.IsNullOrEmpty(opDate) && Convert.ToDateTime(opDate) >= Convert.ToDateTime(injectPara.EDATE))//如果加工日期小于数据库存储最大日期则不执行
// {
// return;
// }
// injectPara.EMACHINECODE = insertdatas[index +2];//机器设备号
// injectPara.EOPERATORCODE = insertdatas[index + 3];//操作人员号
// }
//}
//index = Array.IndexOf(strtitles, "SFS");//
//if (index >= 0)
// injectPara.SFS = insertdatas[index];
//index = Array.IndexOf(strtitles, "PNS");//
//if (index >= 0)
// injectPara.PNS = insertdatas[index];
//index = Array.IndexOf(strtitles, "PVS");//
//if (index >= 0)
// injectPara.PVS = insertdatas[index];
//index = Array.IndexOf(strtitles, "PSS");//
//if (index >= 0)
// injectPara.PSS = insertdatas[index];
//index = Array.IndexOf(strtitles, "ZDX");//
//if (index >= 0)
// injectPara.ZDX = insertdatas[index];
//index = Array.IndexOf(strtitles, "ZSX");//
//if (index >= 0)
// injectPara.ZSX = insertdatas[index];
//index = Array.IndexOf(strtitles, "ZNACH");
//if (index >= 0)
// injectPara.ZNACH = insertdatas[index];
//index = Array.IndexOf(strtitles, "SSX");
//if (index >= 0)
// injectPara.SSX = insertdatas[index];
//index = Array.IndexOf(strtitles, "C3U");
//if (index >= 0)
// injectPara.C3U = insertdatas[index];
//index = Array.IndexOf(strtitles, "CPX");
//if (index >= 0)
// injectPara.CPX = insertdatas[index];
//index = Array.IndexOf(strtitles, "PSCFX");
//if (index >= 0)
// injectPara.PSCFX = insertdatas[index];
//index = Array.IndexOf(strtitles, "PSCFDROP");
//if (index >= 0)
// injectPara.PSCFDROP = insertdatas[index];
//index = Array.IndexOf(strtitles, "H2X");
//if (index >= 0)
// injectPara.H2X = insertdatas[index];
//index = Array.IndexOf(strtitles, "H12X");
//if (index >= 0)
// injectPara.H12X = insertdatas[index];
//index = Array.IndexOf(strtitles, "H3X");
//if (index >= 0)
// injectPara.H3X = insertdatas[index];
//index = Array.IndexOf(strtitles, "H4X");
//if (index >= 0)
// injectPara.H4X = insertdatas[index];
//index = Array.IndexOf(strtitles, "H5X");
//if (index >= 0)
// injectPara.H5X = insertdatas[index];
//index = Array.IndexOf(strtitles, "H6X");
//if (index >= 0)
// injectPara.H6X = insertdatas[index];
//index = Array.IndexOf(strtitles, "H7X");
//if (index >= 0)
// injectPara.H7X = insertdatas[index];
//index = Array.IndexOf(strtitles, "H9X");
//if (index >= 0)
// injectPara.H9X = insertdatas[index];
//if (string.IsNullOrEmpty(injectPara.EDATE))
//{
// injectPara.OPERATEDATE = Convert.ToDateTime(DateTime.Now, DateTimeFormatInfo.InvariantInfo);
//}
//else
//{
// injectPara.OPERATEDATE = Convert.ToDateTime(injectPara.EDATE, DateTimeFormatInfo.InvariantInfo);
//}
//tempbarcode += injectPara.OPERATEDATE.ToString("yyMMddHHmm");
//tempbarcode += injectPara.EMACHINECODE;//前面是设备码,
//tempbarcode += injectPara.EOPERATORCODE.Length == 1 ? "0" + injectPara.EOPERATORCODE : injectPara.EOPERATORCODE;//如果是一位数则转为2位数
//tempbarcode += injectPara.SZX.Substring(injectPara.SZX.Length - 4);
//injectPara.PRODUCTCODE = tempbarcode;
//injectPara.MACHINECODDE = machine.MACHINECODDE;
//injectPara.MACHINENAME = machine.MACHINENAME;
try
{
new InjectionProcess().ProcessAuto(machine, injectPara);
}
catch (Exception ex)
{
LogFileAccess.WriteLogFile("恩格尔数据文件拷贝复制文件服务启动失败" + ex.Message + ex.Source + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
}
/// <summary>
/// 判断是否可以添加
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public bool CheckEngelpar(string sql)
{
DataTable dt = SqlHelper.QueryReturnDataTable(sql.ToString());
if (dt.Rows.Count == 0)
{
return true;
}
else
{
return false;
}
}
Dictionary<string, int> dir;
int titlecount = 0;
//条码索引
int indexbarcode = -1;
string barcode = string.Empty;
//设备编号
string KEY_FORIMPORT = string.Empty;
//生产加工时间
string tempdatetime = string.Empty;
/// <summary>
/// 获取要解析EXCEL的列头
/// </summary>
/// <param name="readlines"></param>
/// <returns></returns>
private string GetExcelTitle(string readlines)
{
indexbarcode = -1;
dir = new Dictionary<string, int>();
StringBuilder sqlTitle = new StringBuilder();
string[] titleline = readlines.Split(';');
titlecount = titleline.Length;
for (int i = 0; i < titleline.Length; i++)
{
string[] col = titleline[i].Split('[');
string colName = col[0].Trim().Replace(" ", "").ToUpper();
sqlTitle.Append(colName);
sqlTitle.Append(",");
}
string strtitle = sqlTitle.ToString().Substring(0, sqlTitle.Length - 1);
return strtitle;
}
string qidate = "";
string qitime = "";
/// <summary>
/// 获取EXCEL要解析值
/// </summary>
/// <param name="readlines"></param>
/// <returns></returns>
private string GetExcelValues(string readlines)
{
try
{
qidate = "";
qitime = "";
string[] strdata = readlines.Split(';');
////当解析的列头和列的值不一致时。直接返回null.
//if (titlecount != strdata.Length)
//{
// return "";
//}
//StringBuilder sqlData = new StringBuilder();
//foreach (KeyValuePair<string, int> a in dir)
//{
// //处理日期列
// if (a.Key == "date&time")
// {
// //获取日期列的值
// tempdatetime = Convert.ToDateTime(strdata[a.Value], DateTimeFormatInfo.InvariantInfo).ToString("yyyy-MM-dd HH:mm:ss");
// sqlData.Append("" + tempdatetime + ",");
// }
// else
// {
// if (a.Key == "DATUM")
// {
// qidate = strdata[a.Value];
// }
// if (a.Key == "ZEIT")
// {
// qitime = strdata[a.Value];
// }
// sqlData.Append("" + strdata[a.Value] + ",");
// }
//}
//if (indexbarcode != -1)
//{
// //获取条码列所在值
// barcode = strdata[indexbarcode];
//}
//else
//{
// barcode = "No Barcode";
//}
//if (qidate != "" && qitime != "")
//{
// tempdatetime = qidate + " " + qitime;
//}
//返回去掉最后一个,号值。
//return sqlData.ToString().Substring(0, sqlData.Length - 1);
return string.Join(",", strdata);
}
catch (Exception e)
{
LogFileAccess.WriteLogFile("恩格尔数据文件数值解析失败" + e.Message + e.Source + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
return "0";
}
}
}
}