[성현모] CPXV2 Init

This commit is contained in:
SHM
2024-06-26 10:30:00 +09:00
parent cdf12248c5
commit 5958993b6a
588 changed files with 698420 additions and 0 deletions

View File

@ -0,0 +1,933 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using SystemX.Net;
using SystemX.Net.BaseProtocol;
using SystemX.Net.DB;
using CpTesterPlatform.CpLogUtil;
using static SystemX.Net.Platform.Common.Util.LogMessage;
using static SystemX.Net.DB.XDBConnManager;
namespace SystemX.Common.Log.LSU
{
public class AnalysisLog_LSU : IDisposable
{
public bool STATE { set; get; }
//DataBase
private XDBConnManager MngDBConn;
//QueryInfo
public LogProcessInfo_LSU qiLogProcessInfo;
//Log Scan Process Task
private Task taskScanProcess;
private bool m_bTaskBlock;
//
private Stopwatch stProcessTime;
private long lLastProcessTime;
private long lLastItemTime;
private long lLastProcessNum;
private CancellationTokenSource cts;
public int SET_LOG_PROC_POS { set; get; }
public int SET_LOG_DELETE_MANAGE_POS { set; get; }
public int SET_LOG_SCAN_SHIFT_TIME { set; get; }
public int SET_LOG_MANAGE_SCAN_TIME { set; get; }
//
private string strLogDataFilePath { set; get; }
private eLogDataType eGetLogDataType { set; get; }
private eLogAccessType eGetAccessType { set; get; }
private CpLogHeader getCpLogHeader;
//
public bool[] LOG_DATA_CHECK_STATE { set; get; }
public int[] PROC_NO_LIST;
public long GET_LAST_PROCESS_TIME()
{
return lLastProcessTime;
}
public long GET_LAST_PROCESS_NUM()
{
return lLastProcessNum;
}
public long GET_LAST_ITEM_TIME()
{
return lLastItemTime;
}
~AnalysisLog_LSU()
{
Dispose(false);
}
public AnalysisLog_LSU()
{
STATE = true;
//Proc Position
SET_LOG_PROC_POS = 0;
SET_LOG_DELETE_MANAGE_POS = 0;
//1초 마다 미 처리 로그 스캔
SET_LOG_SCAN_SHIFT_TIME = 500;
//24시간 마다 삭제 대상 데이터 스캔
SET_LOG_MANAGE_SCAN_TIME = 86400000;
//PROC NO LIST
PROC_NO_LIST = new int[10];
PROC_NO_LIST[0] = 180; //PL, CDA
PROC_NO_LIST[1] = 190; //PH, PM
PROC_NO_LIST[2] = 200; //LK,
PROC_NO_LIST[3] = 210; //LT
PROC_NO_LIST[4] = 220; //LTV, IR
PROC_NO_LIST[5] = 230; //CA
PROC_NO_LIST[6] = 240; //FT
PROC_NO_LIST[7] = 250; //OSP
PROC_NO_LIST[8] = 260; //PV, LVDT
PROC_NO_LIST[9] = 270; //UL
//Unused
//PROC_NO_LIST[10] = 280; //GD
//PROC_NO_LIST[11] = 290; //P
XLogDataControl_.SetLogFieldInfo();
stProcessTime = new Stopwatch();
stProcessTime.Start();
lLastProcessTime = 0;
lLastItemTime = 0;
lLastProcessNum = 0;
MessageOutput.PrintLogLevel = LogMessageLevel.INFO;
string strExcutePos = Environment.CurrentDirectory;
string strDBInfoPos = strExcutePos + @"\Configure\DBConnInfo.xml";
string strQueryInfoPos = strExcutePos + @"\Configure\LogProcessInfo.xml";
qiLogProcessInfo = new LogProcessInfo_LSU(strQueryInfoPos);
if (qiLogProcessInfo.Load())
{
LOG_DATA_CHECK_STATE = new bool[qiLogProcessInfo.GeManageInfo().Count()];
for (int i = 0; i < qiLogProcessInfo.GeManageInfo().Count(); i++)
LOG_DATA_CHECK_STATE[i] = true;
MngDBConn = new XDBConnManager();
MngDBConn.ConfigPath = strDBInfoPos;
if (MngDBConn.OpenConnection())
{
/*
taskScanProcess = null;
m_bTaskBlock = false;
cts = new CancellationTokenSource();
taskScanProcess = new Task(new Action<object>(WatchResultTable), cts.Token);
taskScanProcess.Start();
*/
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" Success to connect to DB. [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.AnalysisLog_]", ConsoleColor.White, LogMessageLevel.DEBUG);
}
else
{
STATE = false;
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" Failed to connect to DB. [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.AnalysisLog_]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
else
{
STATE = false;
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" Read to configure failed. [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.AnalysisLog_]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool bDisposing)
{
if (bDisposing)
{
}
if (taskScanProcess != null)
{
cts.Cancel();
taskScanProcess.Wait();
m_bTaskBlock = true;
}
// do releasing unmanaged resource (종결자가 없는 객체의 자원 해제)
// i.e. close file handle of operating systems
// suppress calling of Finalizer
GC.SuppressFinalize(this);
}
private DataSet QueryProcess(string strGetQuery, ref bool bResult)//, out byte[] ucQueryByteArray)
{
bResult = false;
SqlDataReader xSqlReader = null;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
int iFieldCnt = 0;
int iRecordsAffectedCnt = 0;
bool bHasRow = false;
//ucQueryByteArray = null;
try
{
try
{
xSqlReader = MngDBConn.QueryDatabase(eConnCategory.Main, strGetQuery);
if (xSqlReader != null)
{
iFieldCnt = xSqlReader.FieldCount;
iRecordsAffectedCnt = xSqlReader.RecordsAffected;
bHasRow = xSqlReader.HasRows;
dt.Load(xSqlReader);
ds.Tables.Add(dt);
}
}
catch (Exception ex)
{
xSqlReader = null;
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + strGetQuery + "> Query process fail![SystemX.Net.Platform.Log : AnalysisLog_.QueryProcess]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
finally
{
if (xSqlReader != null)
xSqlReader.Close();
}
if (iFieldCnt > 0 || iRecordsAffectedCnt > 0 || bHasRow == true)
bResult = true;
return ds;
}
private async void WatchResultTable(object objState)
{
CancellationToken token = (CancellationToken)objState;
Stopwatch stLogScanTimer = new Stopwatch();
stLogScanTimer.Start();
Stopwatch stLogManageTimer = new Stopwatch();
stLogManageTimer.Start();
while (!m_bTaskBlock)
{
if (token.IsCancellationRequested)
break;
try
{
if (stLogScanTimer.ElapsedMilliseconds >= SET_LOG_SCAN_SHIFT_TIME)
{
int[] iGetLogNo = QueryStatusResultTable(PROC_NO_LIST[SET_LOG_PROC_POS], token);
if (iGetLogNo != null)
{
bool bResult = QueryInfoResultTable(PROC_NO_LIST[SET_LOG_PROC_POS], token, iGetLogNo);
}
SET_LOG_PROC_POS++;
if (PROC_NO_LIST.Length <= SET_LOG_PROC_POS)
SET_LOG_PROC_POS = 0;
stLogScanTimer.Restart();
}
if ((stLogManageTimer.ElapsedMilliseconds >= SET_LOG_MANAGE_SCAN_TIME))
{
//LOG_DATA_CHECK_STATE = false;
if (qiLogProcessInfo.USE_TABLE_DATA_DELETE_MANAGER)
{
foreach (KeyValuePair<int, Tuple<bool, string, int>> infoM in qiLogProcessInfo.GeManageInfo())
{
if (infoM.Value.Item1)
{
int[] iGetDeleteNo = QueryManageDateTable(infoM.Value.Item2, infoM.Value.Item3.ToString(), token);
if (iGetDeleteNo != null)
{
ManageTableDataDelete(iGetDeleteNo, infoM.Value.Item2, infoM.Value.Item3.ToString(), token);
}
iGetDeleteNo = QueryManageDateTable(infoM.Value.Item2, infoM.Value.Item3.ToString(), token);
//if (iGetDeleteNo != null)
// LOG_DATA_CHECK_STATE = true;
}
}
}
stLogManageTimer.Restart();
}
}
catch (Exception ex)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General Queue Process failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_LSU.WatchResultTable]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
await Task.Delay(1);
}
}
public int[] QueryManageDateTable(string strTableName, string strDateDiff, CancellationToken token)
{
bool bGetQueryResult = false;
int[] iQueryNoArr = null;
DataSet ds = QueryProcess("SELECT TOP(100) * FROM [" + strTableName + "] WHERE No " +
"IN(SELECT No FROM [" + strTableName + "] WHERE " +
"CONVERT(VARCHAR(8), UpdateDT, 112) <= CONVERT(VARCHAR(8), GETDATE() - " + strDateDiff + ", 112)) ORDER BY No;", ref bGetQueryResult);
bool hasRows = XCommons.isHasRow(ds);
if (hasRows)
{
int iRowNum = ds.Tables[0].Rows.Count;
iQueryNoArr = new int[iRowNum];
Array.Clear(iQueryNoArr, 0, iQueryNoArr.Length);
for (int i = 0; i < iRowNum; i++)
{
if (token.IsCancellationRequested)
return null;
var getValue = ds.Tables[0].Rows[i]["No"];
iQueryNoArr[i] = int.Parse(getValue.ToString());
}
}
stProcessTime.Restart();
return iQueryNoArr;
}
public bool ManageTableDataDelete(int[] iGetNoArray, string strTableName, string strDateDiff, CancellationToken token)
{
bool bGetQueryResult = false;
bool bFindItem = false;
long lDataNum = 0;
foreach (int iGetNo in iGetNoArray)
{
bFindItem = true;
lDataNum = iGetNoArray.Count();
if (token.IsCancellationRequested)
break;
/*
QueryProcess("DELETE [" + strTableName + "] WHERE " +
"CONVERT(VARCHAR(8), UpdateDT, 112) <= CONVERT(VARCHAR(8), GETDATE() - " + strDateDiff + ", 112);", ref bGetQueryResult);
*/
QueryProcess("DELETE [" + strTableName + "] WHERE No = " + iGetNo + ";", ref bGetQueryResult);
}
if (bFindItem)
{
lLastProcessTime = stProcessTime.ElapsedMilliseconds;
lLastProcessNum = lDataNum;
}
return true;
}
public int[] QueryStatusResultTable(int iProcNum, CancellationToken token)
{
bool bGetQueryResult = false;
int[] iQueryNoArr = null;
DataSet ds = QueryProcess("SELECT TOP (50) A.No, A.Status FROM HIST_TestResultData_" + iProcNum.ToString() + " AS A WHERE A.Status = 0 OR A.Status = 10 OR A.Status = 20 OR A.Status = 30 ORDER BY No DESC;", ref bGetQueryResult);
bool hasRows = XCommons.isHasRow(ds);
if (hasRows)
{
int iRowNum = ds.Tables[0].Rows.Count;
iQueryNoArr = new int[iRowNum];
Array.Clear(iQueryNoArr, 0, iQueryNoArr.Length);
for (int i = 0; i < iRowNum; i++)
{
if (token.IsCancellationRequested)
return null;
var getValue = ds.Tables[0].Rows[i]["No"];
iQueryNoArr[i] = int.Parse(getValue.ToString());
}
}
stProcessTime.Restart();
return iQueryNoArr;
}
private bool SetLogData(int iProcNum, int iGetNo)
{
bool bGetQueryResult = false;
DataSet dsLogData = null;
DataSet dsModeData = null;
DataSet dsPalletData = null;
strLogDataFilePath = "";
eGetLogDataType = eLogDataType.None;
try
{
dsLogData = QueryProcess("SELECT A.No, A.LogAccessKey, A.ProcNo, A.PalletNumber, A.PalletID, A.PIndex, A.ProdNo, A.ProdID, A.TestID, A.LogDataPath, A.Status, A.UpdateDT " +
"FROM HIST_TestResultData_" + iProcNum.ToString() + " AS A WHERE A.No =" + iGetNo.ToString() + ";", ref bGetQueryResult);
bool hasRows = XCommons.isHasRow(dsLogData);
if (hasRows)
{
var Data = dsLogData.Tables[0].Rows[0]["LogDataPath"].ToString().Trim();
strLogDataFilePath = Data;
var vStatus = dsLogData.Tables[0].Rows[0]["Status"];
if ((short)eLogDataType.Normal == (Convert.ToInt16(vStatus) / 10))
eGetLogDataType = eLogDataType.Normal;
else if ((short)eLogDataType.CSV_Type0 == (Convert.ToInt16(vStatus) / 10))
eGetLogDataType = eLogDataType.CSV_Type0;
else if ((short)eLogDataType.CSV_Type1 == (Convert.ToInt16(vStatus) / 10))
eGetLogDataType = eLogDataType.CSV_Type1;
else if ((short)eLogDataType.CSV_Type2 == (Convert.ToInt16(vStatus) / 10))
eGetLogDataType = eLogDataType.CSV_Type2;
else
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General log processing [Log type select] failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.SetLogData]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
throw new Exception();
}
var vLogAccessKey = dsLogData.Tables[0].Rows[0]["LogAccessKey"].ToString().Trim();
var vProcNo = dsLogData.Tables[0].Rows[0]["ProcNo"].ToString().Trim();
var vPalletNum = dsLogData.Tables[0].Rows[0]["PalletNumber"].ToString().Trim();
var vPalletID = dsLogData.Tables[0].Rows[0]["PalletID"].ToString().Trim();
var vPIndex = dsLogData.Tables[0].Rows[0]["PIndex"].ToString().Trim();
var vProdNo = dsLogData.Tables[0].Rows[0]["ProdNo"].ToString().Trim();
var vProdID = dsLogData.Tables[0].Rows[0]["ProdID"].ToString().Trim();
var vTestID = dsLogData.Tables[0].Rows[0]["TestID"].ToString().Trim();
dsModeData = QueryProcess("SELECT ModeID FROM CONST_WorkMode WHERE PalletNumber = '" + vPalletNum + "';", ref bGetQueryResult);
dsPalletData = QueryProcess("SELECT * FROM STAT_ProdLoad A WHERE A.PalletNumber = '" + vPalletNum + "' ORDER BY A.No;", ref bGetQueryResult);
if (XCommons.isHasRow(dsModeData) == false ||
XCommons.isHasRow(dsPalletData) == false)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General log processing [Query mode/pallet information (1)] failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.SetLogData]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
throw new Exception();
}
var vpModeID = dsModeData.Tables[0].Rows[0]["ModeID"].ToString().Trim();
if (eGetLogDataType == eLogDataType.Normal)
{
CpLogStoreData.vLSaveTableName = qiLogProcessInfo.GetSaveTableName(vTestID.ToString());
CpLogStoreData.vLSaveDetailTable = qiLogProcessInfo.GetSaveDetailTable(vTestID.ToString());
CpLogStoreData.ExtrctInfo = qiLogProcessInfo.GetExtractInfo(vTestID.ToString());
foreach (DataRow dr in dsPalletData.Tables[0].Rows)
{
int iIndex = dsPalletData.Tables[0].Rows.IndexOf(dr);
int iLogIndex = XLogDataControl_.ConvertTextToTryValue<int>(vPIndex.ToString(), -1);
if (iLogIndex == -1)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General log processing [Query mode/pallet information (2)] failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.SetLogData]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
throw new Exception();
}
else
{
iLogIndex -= 1;
CpLogStoreData.vLLogAccessKey = vLogAccessKey;
CpLogStoreData.vLProcNo = vProcNo;
CpLogStoreData.vLPalletNumber = dsPalletData.Tables[0].Rows[iLogIndex]["PalletNumber"].ToString().Trim();
CpLogStoreData.vLPalletID = dsPalletData.Tables[0].Rows[iLogIndex]["PalletID"].ToString().Trim();
CpLogStoreData.vLPIndex = dsPalletData.Tables[0].Rows[iLogIndex]["PIndex"].ToString().Trim();
CpLogStoreData.vLProdNo = dsPalletData.Tables[0].Rows[iLogIndex]["ProdNo"].ToString().Trim();
CpLogStoreData.vLProdID = dsPalletData.Tables[0].Rows[iLogIndex]["ProdID"].ToString().Trim();
CpLogStoreData.vLSensorType = dsPalletData.Tables[0].Rows[iLogIndex]["SensorType"].ToString().Trim();
CpLogStoreData.vLStatus = "-";
CpLogStoreData.vLTestID = vTestID;
CpLogStoreData.vLResult = "-";
CpLogStoreData.vLTestDuration = "-";
break;
}
}
}
else
{
CustomLogStoreData.vLSaveTableName = qiLogProcessInfo.GetSaveTableName(vTestID.ToString());
CustomLogStoreData.vLSaveDetailTable = qiLogProcessInfo.GetSaveDetailTable(vTestID.ToString());
CustomLogStoreData.ExtrctInfo = qiLogProcessInfo.GetExtractInfo(vTestID.ToString());
foreach (DataRow dr in dsPalletData.Tables[0].Rows)
{
int iIndex = dsPalletData.Tables[0].Rows.IndexOf(dr);
CustomLogStoreData.vLLogAccessKey[iIndex] = vLogAccessKey;
CustomLogStoreData.vLProcNo[iIndex] = vProcNo;
CustomLogStoreData.vLPalletNumber[iIndex] = vPalletNum;
//CustomLogStoreData.vLPalletNumber[iIndex] = dsPalletData.Tables[0].Rows[0]["PalletNumber"].ToString().Trim();
CustomLogStoreData.vLPalletID[iIndex] = dsPalletData.Tables[0].Rows[iIndex]["PalletID"].ToString().Trim();
CustomLogStoreData.vLPIndex[iIndex] = dsPalletData.Tables[0].Rows[iIndex]["PIndex"].ToString().Trim();
CustomLogStoreData.vLProdNo[iIndex] = dsPalletData.Tables[0].Rows[iIndex]["ProdNo"].ToString().Trim();
CustomLogStoreData.vLProdID[iIndex] = dsPalletData.Tables[0].Rows[iIndex]["ProdID"].ToString().Trim();
CustomLogStoreData.vLSensorType[iIndex] = dsPalletData.Tables[0].Rows[iIndex]["SensorType"].ToString().Trim();
CustomLogStoreData.SelectProdNo = CustomLogStoreData.vLProdNo[iIndex];
if (vpModeID.ToString() == "1")
CustomLogStoreData.vLStatus[iIndex] = "NORMAL";
else if (vpModeID.ToString() == "2")
CustomLogStoreData.vLStatus[iIndex] = "REWORK";
else if (vpModeID.ToString() == "3")
CustomLogStoreData.vLStatus[iIndex] = "RETEST";
else
CustomLogStoreData.vLStatus[iIndex] = "-";
CustomLogStoreData.vLTestID[iIndex] = vTestID;
CustomLogStoreData.vLResult[iIndex] = "-";
CustomLogStoreData.vLVal_Min[iIndex] = "-";
CustomLogStoreData.vLVal_Max[iIndex] = "-";
CustomLogStoreData.vLVal_Meas[iIndex] = "-";
}
}
}
}
catch (Exception ex)
{
bGetQueryResult = false;
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General shift log data failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.SetLogData]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
return bGetQueryResult;
}
private bool FileAccessCheck()
{
bool bAccessCheck = true;
//File Access Check
FileStream fs = null;
try
{
fs = new FileStream(@strLogDataFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (Exception ex)
{
//File Access fail next file
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"File access check fail. [" + @strLogDataFilePath + "] [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.FileAccessCheck]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
bAccessCheck = false;
}
finally
{
//FIle Access ok
if (fs != null)
fs.Close();
}
return bAccessCheck;
}
private bool GetNoramlDataAccessResult(string strLogDataPath, ref DataSet dsGetSet)
{
bool bStatusCheck = true;
dsGetSet = null;
try
{
//CpLogCompUtil
//CpLogCompUtil.CopyToMemory()
DataTable dt = CpLogFileIO.GetLogData(@strLogDataPath, out getCpLogHeader);
DataSet dsLog = new DataSet();
dsLog.Tables.Add(dt);
dsGetSet = dsLog.Copy();
bStatusCheck = XCommons.isHasRow(dsLog);
if (bStatusCheck)
{
//추출 정보 존재시
if (CpLogStoreData.ExtrctInfo.Count > 0)
{
CpLogStoreData.SetMeasLength(CpLogStoreData.ExtrctInfo.Count);
foreach (KeyValuePair<int, Tuple<string, bool, string, int, string, string, string>> k in CpLogStoreData.ExtrctInfo)
{
DataRow[] dr = null;
if (k.Value.Item2)
{
foreach (DataRow getDr in dsLog.Tables[0].Rows)
{
string strGetMO = getDr.ItemArray[2].ToString().Trim();
if (strGetMO.IndexOf(k.Value.Item3.ToString()) >= 0)
{
dr = new DataRow[1];
dr[0] = getDr;
break;
}
}
//dsLog.Tables[0].Select("Mo = '" + k.Value.Item3.ToString() + "'");
}
else
dsLog.Tables[0].Select("Step = " + k.Value.Item4.ToString());
int iGetCnt = (dr != null) ? dr.Count() : 0;
if (iGetCnt > 0)
{
string strSetValue = XLogDataControl_.ConvertTextToTryValue<double>(dr[0].ItemArray[5].ToString(), 0).ToString();
CpLogStoreData.SetMeasValue(k.Key, strSetValue);
}
else
CpLogStoreData.SetMeasValue(k.Key, "0");
}
}
CpLogStoreData.SetCpLogHeaderData(getCpLogHeader);
}
}
catch (Exception ex)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"CpLog file access get header failed. [" + @strLogDataPath + "] [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.GetNoramlDataAccessResult]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
bStatusCheck = false;
}
return bStatusCheck;
}
private bool GetCustomDataSubProcess(string strDataPath)
{
bool bStatusCheck = true;
DataSet dsLogData = null;
try
{
if (XLogDataControl_.ReadFileData(eGetLogDataType, @strDataPath))
{
if (eGetLogDataType == eLogDataType.CSV_Type0)
{
dsLogData = QueryProcess("SELECT " +
"PrsFail_LSpec AS Val_Min, " +
"PrsFail_USpec AS Val_Max " +
"FROM PROD_ModelChar_LK " +
"WHERE " +
"PrtProdNo = " +
"(SELECT PrtProdNo FROM PROD_ModelChild WHERE ProdNo = '" +
CustomLogStoreData.SelectProdNo + "');", ref bStatusCheck);
for (int i = 0; i < CustomLogStoreData.vLVal_Min.Length; i++)
CustomLogStoreData.vLVal_Min[i] = dsLogData.Tables[0].Rows[0]["Val_Min"].ToString().Trim();
for (int i = 0; i < CustomLogStoreData.vLVal_Min.Length; i++)
CustomLogStoreData.vLVal_Max[i] = dsLogData.Tables[0].Rows[0]["Val_Max"].ToString().Trim();
}
}
}
catch (Exception ex)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"Custom file sub process failed. [" + @strDataPath + "] [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.GetCustomDataSubProcess]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
bStatusCheck = false;
}
return bStatusCheck;
}
private SqlCommand[] GetCommandList(int iProcNum, int iGetNo, eLogDataType eCurLogType, eLogAccessType eCurAccessType, ref SqlCommand[] getSubCmd)
{
bool bGetQueryResult = true;
bool hasData = false;
SqlCommand[] getCmd;
getSubCmd = null;
DataSet dsLogData = null;
DataSet dsCpLogRawData = null;
string strTempFileName = @"D:\TempCreateFolder\";
try
{
if (eCurAccessType == eLogAccessType.FileData)
{
if (FileAccessCheck())
{
//CP
if (eGetLogDataType == eLogDataType.Normal)
hasData = GetNoramlDataAccessResult(strLogDataFilePath, ref dsCpLogRawData);
//CSV
else
hasData = GetCustomDataSubProcess(strLogDataFilePath);
}
}
else if (eCurAccessType == eLogAccessType.VarBinaryData)
{
dsLogData = QueryProcess("SELECT A.No, A.LogAccessKey, A.ProcNo, A.PalletNumber, A.PalletID, A.PIndex, A.ProdNo, A.ProdID, A.TestID, A.LogData, A.Status, A.UpdateDT " +
"FROM HIST_TestResultData_" + iProcNum.ToString() + " AS A WHERE A.No =" + iGetNo.ToString() + ";", ref bGetQueryResult);
var Data = dsLogData.Tables[0].Rows[0]["LogData"];
/*
N: cd26ccf675d64521884f1693c62ed303
D: cd26ccf6-75d6-4521-884f-1693c62ed303
B: {cd26ccf6-75d6-4521-884f-1693c62ed303}
P: (cd26ccf6-75d6-4521-884f-1693c62ed303)
X: {0xcd26ccf6,0x75d6,0x4521,{0x88,0x4f,0x16,0x93,0xc6,0x2e,0xd3,0x03}}
*/
Guid uguid = Guid.NewGuid();
strTempFileName = @"D:\TempCreateFolder\";
if (Directory.Exists(strTempFileName) == false)
Directory.CreateDirectory(strTempFileName);
strTempFileName += uguid.ToString("B") + ".CpLog";
File.WriteAllBytes(strTempFileName, (byte[])Data);
//CP
if (eGetLogDataType == eLogDataType.Normal)
hasData = GetNoramlDataAccessResult(strTempFileName, ref dsCpLogRawData);
//CSV
else
hasData = GetCustomDataSubProcess(strTempFileName);
}
else
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General log processing [Unknown access data] failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.GetCommandList]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
throw new Exception();
}
//
if (hasData)
{
getCmd = XLogDataControl_.HISTTableProcess(eGetLogDataType);
if (eGetLogDataType == eLogDataType.Normal)
{
//디테일 테이블 저장
if (CpLogStoreData.vLSaveDetailTable)
{
//STEP,POSITION,MO,FNC_NAME,MIN_VALUE,MEASURE_VALUE,MAX_VALUE,DIM,CHECK_RETURN,SPENT_TIME,INFO
string columns = "STEP,POSITION,MO,FNC_NAME,MIN_VALUE,MEASURE_VALUE,MAX_VALUE,DIM,CHECK_RETURN,SPENT_TIME,INFO";
//columns = string.Join(",", dsCpLogRawData.Tables[0].Columns.Cast<DataColumn>().Select(c => c.ColumnName));
string values = string.Join(",", columns.Split(',').Select(c => string.Format("@{0}", c)));
//values = string.Join(",", dsCpLogRawData.Tables[0].Columns.Cast<DataColumn>().Select(c => string.Format("@{0}", c.ColumnName)));
String sqlCommandInsert = string.Format("INSERT INTO HIST_TestResultDatail_" + iProcNum.ToString() + " (LogAccessKey, {0}) VALUES (@LogAccessKey, {1})", columns, values);
getSubCmd = new SqlCommand[dsCpLogRawData.Tables[0].Rows.Count];
foreach (DataRow row in dsCpLogRawData.Tables[0].Rows)
{
int irIndex = dsCpLogRawData.Tables[0].Rows.IndexOf(row);
getSubCmd[irIndex] = new SqlCommand(sqlCommandInsert);
getSubCmd[irIndex].Parameters.Clear();
getSubCmd[irIndex].Parameters.AddWithValue("@LogAccessKey", CpLogStoreData.vLLogAccessKey);
foreach (DataColumn col in dsCpLogRawData.Tables[0].Columns)
{
int icIndex = dsCpLogRawData.Tables[0].Columns.IndexOf(col);
string strSetValue = row[col].ToString().Trim();
getSubCmd[irIndex].Parameters.AddWithValue("@" + columns.Split(',')[icIndex], strSetValue);
}
}
}
}
}
else
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General log processing [" + eCurAccessType.ToString() + " : file no has data] failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.GetCommandList]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
throw new Exception();
}
}
catch (Exception ex)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General log processing [" + eGetLogDataType.ToString() + "] [" + eCurAccessType.ToString() + "] failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.GetCommandList]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
getCmd = null;
int iSetStatus = GetStatusCode(false);
QueryProcess("UPDATE HIST_TestResultData_" + iProcNum.ToString() + " SET Status = " + iSetStatus + ", UpdateDT = GETDATE() WHERE No = " + iGetNo.ToString() + ";", ref bGetQueryResult);
}
finally
{
if (File.Exists(strTempFileName))
File.Delete(strTempFileName);
}
return getCmd;
}
public bool QueryInfoResultTable(int iProcNum, CancellationToken token, int[] iGetNoArray)
{
bool bGetQueryResult = false;
bool bFindItem = false;
long lDataNum = 0;
foreach (int iGetNo in iGetNoArray)
{
if (token.IsCancellationRequested)
break;
lDataNum = iGetNoArray.Count();
bFindItem = true;
Stopwatch stMeasTime = new Stopwatch();
stMeasTime.Start();
if (SetLogData(iProcNum, iGetNo) == false)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"No : " + iGetNo.ToString() + " General log processing [Log data base information] failed. [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.QueryInfoResultTable]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
continue;
}
else
{
;//
}
if (File.Exists(strLogDataFilePath))
eGetAccessType = eLogAccessType.FileData;
else
eGetAccessType = eLogAccessType.VarBinaryData;
//Detatil Command List
SqlCommand[] getSubCmd = null;
//HIST Command and Extractinfo - Update table Command
SqlCommand[] getCmd = GetCommandList(iProcNum, iGetNo, eGetLogDataType, eGetAccessType, ref getSubCmd);
//Command Process
bool bCommandProcessResult = true;
int iSetStatus = GetStatusCode(true);
int iSetFailStatus = GetStatusCode(false);
if (getCmd == null)
{
bCommandProcessResult = false;
goto FAILED_PROCESS;
}
foreach (SqlCommand sc in getCmd)
{
if (sc == null)
continue;
if (MngDBConn.CurrentConnection(eConnCategory.Main).ExecuteNonQuery(sc) == false)
bCommandProcessResult = false;
}
if (getSubCmd != null)
{
foreach (SqlCommand sc in getSubCmd)
{
if (sc == null)
continue;
if (MngDBConn.CurrentConnection(eConnCategory.Main).ExecuteNonQuery(sc) == false)
bCommandProcessResult = false;
}
}
FAILED_PROCESS:
if(bCommandProcessResult)
QueryProcess("UPDATE HIST_TestResultData_" + iProcNum.ToString() + " SET Status = " + iSetStatus + ", UpdateDT = GETDATE() WHERE No = " + iGetNo.ToString() + ";", ref bGetQueryResult);
else
QueryProcess("UPDATE HIST_TestResultData_" + iProcNum.ToString() + " SET Status = " + iSetFailStatus + ", UpdateDT = GETDATE() WHERE No = " + iGetNo.ToString() + ";", ref bGetQueryResult);
lLastItemTime = stMeasTime.ElapsedMilliseconds;
}
if (bFindItem)
{
lLastProcessTime = stProcessTime.ElapsedMilliseconds;
lLastProcessNum = lDataNum;
}
return bGetQueryResult;
}
private int GetStatusCode(bool bResult)
{
int iSetStatus = 0;
if (eGetLogDataType == eLogDataType.Normal)
iSetStatus = 0;
else if (eGetLogDataType == eLogDataType.CSV_Type0)
iSetStatus = 10;
else if (eGetLogDataType == eLogDataType.CSV_Type1)
iSetStatus = 20;
else if (eGetLogDataType == eLogDataType.CSV_Type2)
iSetStatus = 30;
else
iSetStatus = 100;
if (bResult)
iSetStatus += 1;
else
iSetStatus += 2;
return iSetStatus;
}
}
}

View File

@ -0,0 +1,180 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using SystemX.Net.BaseProtocol;
using SystemX.Net.DB;
using CpTesterPlatform.CpLogUtil;
using static SystemX.Net.Platform.Common.Util.LogMessage;
namespace SystemX.Common.Log.LSU
{
/// <summary>
/// Query Base Infomation
/// </summary>
///
public class LogProcessInfo_LSU
{
public bool READ_INFO_STATE { set; get; }
private string strInfoFilePos;
//TestID, TableName
private Dictionary<string, Tuple<int, string>> dicBaseIDInfo;
//TestID, DetailLogUse
private Dictionary<string, bool> dicDetailInfo;
//KEY - STEP, Name, UpdateTableName, ToField
private Dictionary<int, Tuple<string, bool, string, int, string, string, string>> dicSubExtrctionInfo;
public bool USE_TABLE_DATA_DELETE_MANAGER { internal set; get; }
//KEY - TableName, USE
private Dictionary<string, bool> dicTableDataDeleteList;
//KEY - No, USE, TableName, Set Date
private Dictionary<int, Tuple<bool, string, int>> dicTableDataDeleteManager;
public LogProcessInfo_LSU(string strGetInfoPath)
{
strInfoFilePos = strGetInfoPath;
dicBaseIDInfo = new Dictionary<string, Tuple<int, string>>();
dicDetailInfo = new Dictionary<string, bool>();
dicSubExtrctionInfo = new Dictionary<int, Tuple<string, bool, string, int, string, string, string>>();
//
dicTableDataDeleteList = new Dictionary<string, bool>();
dicTableDataDeleteManager = new Dictionary<int, Tuple<bool, string, int>>();
}
public string GetSaveTableName(string strTestID)
{
if (dicBaseIDInfo.Keys.Contains(strTestID))
{
return dicBaseIDInfo[strTestID].Item2;
}
else
return "";
}
public bool GetSaveDetailTable(string strTestID)
{
if (dicDetailInfo.Keys.Contains(strTestID))
return dicDetailInfo[strTestID];
else
return false;
}
public List<KeyValuePair<int, Tuple<string, bool, string, int, string, string, string>>> GetExtractInfo(string strTestID)
{
if (dicBaseIDInfo.Keys.Contains(strTestID))
return dicSubExtrctionInfo.ToList().FindAll(x => x.Value.Item1 == strTestID);
else
return null;
}
public List<KeyValuePair<int, Tuple<bool, string, int>>> GeManageInfo()
{
return dicTableDataDeleteManager.ToList();
}
public bool Load()
{
READ_INFO_STATE = true;
int iSetPos = 0;
try
{
XDocument xDoc = XDocument.Load(strInfoFilePos);
var xElement = xDoc.Element("ROOT");
if (xElement != null)
{
var ListGetElement = xElement.Elements("TableDataDeleteManager").ToList();
foreach (var getXElement in ListGetElement)
{
USE_TABLE_DATA_DELETE_MANAGER = Convert.ToBoolean(getXElement.Attribute("USE").Value);
if (getXElement.Elements().ToList().Count > 0)
{
iSetPos = 0;
for (int i = 0; i < getXElement.Elements().ToList().Count; i++)
{
int iGetDateDiff = 0;
if (int.TryParse(getXElement.Element("Management" + (i + 1).ToString()).Attribute("DateDifference").Value.ToString(), out iGetDateDiff))
{
dicTableDataDeleteList.Add(getXElement.Element("Management" + (i + 1).ToString()).Attribute("TableName").Value,
Convert.ToBoolean(getXElement.Element("Management" + (i + 1).ToString()).Attribute("USE").Value));
dicTableDataDeleteManager.Add(iSetPos++,
new Tuple<bool, string, int>(
Convert.ToBoolean(getXElement.Element("Management" + (i + 1).ToString()).Attribute("USE").Value),
getXElement.Element("Management" + (i + 1).ToString()).Attribute("TableName").Value,
iGetDateDiff));
}
else
throw new Exception("DateDifference value error.");
}
}
}
ListGetElement = xElement.Elements("QueryInfo").ToList();
foreach (var getXElement in ListGetElement)
{
string strBaseID = getXElement.Attribute("ID").Value;
bool bGetDetailSelect = false;
int iGetProcNo = int.Parse(getXElement.Attribute("ProcNo").Value);
dicBaseIDInfo.Add(strBaseID, new Tuple<int, string>(iGetProcNo, getXElement.Attribute("Table").Value));
dicDetailInfo.Add(strBaseID, bool.TryParse(getXElement.Attribute("DetailProcess").Value, out bGetDetailSelect) == true ? bGetDetailSelect : false);
if (getXElement.Elements().ToList().Count > 0)
{
iSetPos = 0;
for (int i = 0; i < getXElement.Elements().ToList().Count; i++)
{
int iGetStep = 0;
if (int.TryParse(getXElement.Element("ExtractionInfo" + (i + 1).ToString()).Attribute("Step").Value.ToString(), out iGetStep))
{
string strUpdateTable = getXElement.Element("ExtractionInfo" + (i + 1).ToString()).Attribute("UpdateTableName").Value;
bool bUpdateTableDiff = dicSubExtrctionInfo.ToList().FindAll(x => x.Value.Item1 == strBaseID).All(x => x.Value.Item6 == strUpdateTable);
if (bUpdateTableDiff == false)
throw new Exception();
dicSubExtrctionInfo.Add(iSetPos++,
new Tuple<string, bool, string, int, string, string, string>(
strBaseID,
Convert.ToBoolean(getXElement.Element("ExtractionInfo" + (i + 1).ToString()).Attribute("MO_Find").Value),
getXElement.Element("ExtractionInfo" + (i + 1).ToString()).Attribute("MO").Value,
iGetStep,
getXElement.Element("ExtractionInfo" + (i + 1).ToString()).Attribute("Name").Value,
getXElement.Element("ExtractionInfo" + (i + 1).ToString()).Attribute("UpdateTableName").Value,
getXElement.Element("ExtractionInfo" + (i + 1).ToString()).Attribute("ToField").Value));
}
else
throw new Exception("Step value error.");
}
}
}
}
}
catch (Exception ex)
{
READ_INFO_STATE = false;
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"LogProcessInfo read failed. [SystemX.Common.Protocol.Log.LSU : LogProcessInfo_LSU.Load]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
return READ_INFO_STATE;
}
}
}

View File

@ -0,0 +1,490 @@
using CpTesterPlatform.CpLogUtil;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Xml.Linq;
using SystemX.Net;
using SystemX.Net.BaseProtocol;
using SystemX.Net.DB;
using SystemX.Net.Platform.Common.ExtensionMethods;
using static SystemX.Net.Platform.Common.Util.LogMessage;
namespace SystemX.Common.Log.LSU
{
public static class CpLogStoreData
{
public static string vLSaveTableName = string.Empty;
public static bool vLSaveDetailTable = false;
public static List<KeyValuePair<int, Tuple<string, bool, string, int, string, string, string>>> ExtrctInfo = null;
public static string vLLogAccessKey = string.Empty;
public static string vLProcNo = string.Empty;
public static string vLStation = string.Empty;
public static string vLPosition = string.Empty;
public static string vLPalletNumber = string.Empty;
public static string vLPalletID = string.Empty;
public static string vLPIndex = string.Empty;
public static string vLProdNo = string.Empty;
public static string vLProdID = string.Empty;
public static string vLSensorType = string.Empty;
public static string vLStatus = string.Empty;
public static string vLTestID = string.Empty;
public static string vLResult = string.Empty;
public static string vLTestDuration = string.Empty;
public static string[] vLVal_Meas;
public static void SetMeasLength(int iCnt)
{
vLVal_Meas = new string[iCnt];
Array.Clear(vLVal_Meas, 0, iCnt);
}
public static void SetMeasValue(int iPos, string strValue)
{
vLVal_Meas[iPos] = strValue;
}
public static string GetMeasValue(int iPos)
{
return vLVal_Meas[iPos];
}
public static void SetCpLogHeaderData(CpLogHeader cpLh)
{
vLStation = (cpLh.CHANNEL).Trim();
vLPosition = (cpLh.WORK_POSITION).Trim();
vLStatus = (cpLh.CONTROL + @"/" + cpLh.TYPE).Trim();
vLResult = (cpLh.RESULT).Trim();
var vTestDuration = (cpLh.DURATION).Trim();
double dGetDurtion = 0;
double.TryParse(vTestDuration.ToString().Trim(), out dGetDurtion);
dGetDurtion /= 1000.0;
vLTestDuration = dGetDurtion.ToString("F3");
}
}
public static class CustomLogStoreData
{
public static string vLSaveTableName = string.Empty;
public static bool vLSaveDetailTable = false;
public static List<KeyValuePair<int, Tuple<string, bool, string, int, string, string, string>>> ExtrctInfo = null;
public static string SelectProdNo = string.Empty;
public static string[] vLLogAccessKey = new string[6] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
public static string[] vLProcNo = new string[6] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
public static string[] vLPalletNumber = new string[6] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
public static string[] vLPalletID = new string[6] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
public static string[] vLPIndex = new string[6] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
public static string[] vLProdNo = new string[6] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
public static string[] vLProdID = new string[6] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
public static string[] vLSensorType = new string[6] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
public static string[] vLStatus = new string[6] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
public static string[] vLTestID = new string[6] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
public static string[] vLResult = new string[6] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
public static string[] vLVal_Min = new string[6] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
public static string[] vLVal_Max = new string[6] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
public static string[] vLVal_Meas = new string[6] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
}
public static class XLogDataControl_
{
public static DataTable dtCSVFileData = new DataTable();
private static Dictionary<string, Tuple<SqlDbType, int>> dicLogField;
public static void SetLogFieldInfo()
{
dicLogField = new Dictionary<string, Tuple<SqlDbType, int>>();
dicLogField.Clear();
dicLogField.Add("LogAccessKey", new Tuple<SqlDbType, int>(SqlDbType.NVarChar, 64));
dicLogField.Add("ProcNo", new Tuple<SqlDbType, int>(SqlDbType.BigInt, 0));
dicLogField.Add("Station", new Tuple<SqlDbType, int>(SqlDbType.NChar, 30));
dicLogField.Add("Position", new Tuple<SqlDbType, int>(SqlDbType.NChar, 30));
dicLogField.Add("PalletNumber", new Tuple<SqlDbType, int>(SqlDbType.NChar, 20));
dicLogField.Add("PalletID", new Tuple<SqlDbType, int>(SqlDbType.NChar, 30));
dicLogField.Add("PIndex", new Tuple<SqlDbType, int>(SqlDbType.TinyInt, 0));
dicLogField.Add("ProdNo", new Tuple<SqlDbType, int>(SqlDbType.NChar, 30));
dicLogField.Add("ProdID", new Tuple<SqlDbType, int>(SqlDbType.NChar, 50));
dicLogField.Add("SensorType", new Tuple<SqlDbType, int>(SqlDbType.TinyInt, 0));
dicLogField.Add("Status", new Tuple<SqlDbType, int>(SqlDbType.NChar, 50));
dicLogField.Add("TestID", new Tuple<SqlDbType, int>(SqlDbType.NChar, 20));
dicLogField.Add("Result", new Tuple<SqlDbType, int>(SqlDbType.Bit, 0));
dicLogField.Add("TestDuration", new Tuple<SqlDbType, int>(SqlDbType.Float, 0));
dicLogField.Add("Val_Min", new Tuple<SqlDbType, int>(SqlDbType.Float, 0));
dicLogField.Add("Val_Max", new Tuple<SqlDbType, int>(SqlDbType.Float, 0));
dicLogField.Add("Val_Meas", new Tuple<SqlDbType, int>(SqlDbType.Float, 0));
}
private static void AddLogField(string strName, SqlDbType setType, int iSize)
{
if (dicLogField.ContainsKey(strName) == false)
dicLogField.Add(strName, new Tuple<SqlDbType, int>(setType, iSize));
}
private static SqlParameter GetMakeSqlParameterInfo(string strSetName, object objValue)
{
if (dicLogField.ContainsKey(strSetName))
{
SqlParameter param = new SqlParameter("@" + strSetName, dicLogField[strSetName].Item1, dicLogField[strSetName].Item2);
param.Value = objValue;
return param;
}
else
return null;
}
public static T ConvertTextToTryValue<T>(string strText, object objFailValue)
{
object obj;
obj = typeof(T);
int iGetValue = 0;
byte ucGetValue = 0;
uint uiGetValue = 0;
double dGetValue = 0;
if (obj.ToString().IndexOf("Byte") >= 0)
{
if (!byte.TryParse(strText, out ucGetValue))
obj = objFailValue;
else
obj = ucGetValue;
}
if (obj.ToString().IndexOf("Int") >= 0)
{
if (!int.TryParse(strText, out iGetValue))
obj = objFailValue;
else
obj = iGetValue;
}
if (obj.ToString().IndexOf("UInt") >= 0)
{
if (!uint.TryParse(strText, out uiGetValue))
obj = objFailValue;
else
obj = uiGetValue;
}
if (obj.ToString().IndexOf("Double") >= 0)
{
if (!double.TryParse(strText, out dGetValue))
obj = objFailValue;
else
obj = dGetValue;
}
return (T)Convert.ChangeType(obj, typeof(T));
}
public static SqlCommand[] HISTTableProcess(eLogDataType eGetLogType)
{
SqlCommand[] cmd = null;
try
{
try
{
if (eGetLogType == eLogDataType.Normal)
{
cmd = new SqlCommand[3];
String sqlCommandInsert = "";
String sqlCommandSubInsert = "";
String sqlCommandUpdate = "";
string columns = string.Empty;
string subColumns = string.Empty;
if (CpLogStoreData.ExtrctInfo.Count > 0)
{
columns = "LogAccessKey,ProcNo,Station,Position,PalletNumber,PalletID,PIndex,ProdNo,ProdID,SensorType,Status,TestID,Result,TestDuration,";
subColumns = "LogAccessKey,ProcNo,PalletNumber,PalletID,PIndex,ProdNo,ProdID,TestID";
sqlCommandUpdate = "UPDATE " + CpLogStoreData.ExtrctInfo[0].Value.Item6 + " SET ";
foreach (KeyValuePair<int, Tuple<string, bool, string, int, string, string, string>> k in CpLogStoreData.ExtrctInfo)
{
sqlCommandUpdate += k.Value.Item7 + " = " + CpLogStoreData.GetMeasValue(k.Key) + ", ";
columns += k.Value.Item7 + ",";
AddLogField(k.Value.Item7, SqlDbType.Float, 0);
}
sqlCommandUpdate = sqlCommandUpdate.Remove(sqlCommandUpdate.Length - 2, 1);
sqlCommandUpdate += "WHERE PalletNumber = '" + CpLogStoreData.vLPalletNumber + "' AND PIndex = " + CpLogStoreData.vLPIndex + ";";
columns = columns.Remove(columns.Length - 1, 1);
cmd[2] = new SqlCommand(sqlCommandUpdate);
}
else
{
columns = "LogAccessKey,ProcNo,Station,Position,PalletNumber,PalletID,PIndex,ProdNo,ProdID,SensorType,Status,TestID,Result,TestDuration";
subColumns = "LogAccessKey,ProcNo,PalletNumber,PalletID,PIndex,ProdNo,ProdID,TestID";
cmd[2] = null;
}
string values = string.Join(",", columns.Split(',').Select(c => string.Format("@{0}", c)));
string subValues = string.Join(",", subColumns.Split(',').Select(c => string.Format("@{0}", c)));
sqlCommandInsert = string.Format("INSERT INTO " + CpLogStoreData.vLSaveTableName + " ({0}) VALUES ({1})", columns, values);
sqlCommandSubInsert = string.Format("INSERT INTO [HIST_TestNgResult] ({0}) VALUES ({1})", subColumns, subValues);
cmd[0] = new SqlCommand(sqlCommandInsert);
cmd[1] = new SqlCommand(sqlCommandSubInsert);
SqlParameter[] setParams = new SqlParameter[columns.Split(',').Count()];
SqlParameter[] setSubParams = new SqlParameter[subColumns.Split(',').Count()];
setParams[0] = GetMakeSqlParameterInfo("LogAccessKey", CpLogStoreData.vLLogAccessKey);
setParams[1] = GetMakeSqlParameterInfo("ProcNo", CpLogStoreData.vLProcNo);
setParams[2] = GetMakeSqlParameterInfo("Station", CpLogStoreData.vLStation);
setParams[3] = GetMakeSqlParameterInfo("Position", CpLogStoreData.vLPosition);
setParams[4] = GetMakeSqlParameterInfo("PalletNumber", CpLogStoreData.vLPalletNumber);
setParams[5] = GetMakeSqlParameterInfo("PalletID", CpLogStoreData.vLPalletID);
setParams[6] = GetMakeSqlParameterInfo("PIndex", ConvertTextToTryValue<byte>(CpLogStoreData.vLPIndex, 0));
setParams[7] = GetMakeSqlParameterInfo("ProdNo", CpLogStoreData.vLProdNo);
setParams[8] = GetMakeSqlParameterInfo("ProdID", CpLogStoreData.vLProdID);
setParams[9] = GetMakeSqlParameterInfo("SensorType", CpLogStoreData.vLSensorType);
setParams[10] = GetMakeSqlParameterInfo("Status", CpLogStoreData.vLStatus);
setParams[11] = GetMakeSqlParameterInfo("TestID", CpLogStoreData.vLTestID);
setSubParams[0] = GetMakeSqlParameterInfo("LogAccessKey", CpLogStoreData.vLLogAccessKey);
setSubParams[1] = GetMakeSqlParameterInfo("ProcNo", CpLogStoreData.vLProcNo);
setSubParams[2] = GetMakeSqlParameterInfo("PalletNumber", CpLogStoreData.vLPalletNumber);
setSubParams[3] = GetMakeSqlParameterInfo("PalletID", CpLogStoreData.vLPalletID);
setSubParams[4] = GetMakeSqlParameterInfo("PIndex", ConvertTextToTryValue<byte>(CpLogStoreData.vLPIndex, 0));
setSubParams[5] = GetMakeSqlParameterInfo("ProdNo", CpLogStoreData.vLProdNo);
setSubParams[6] = GetMakeSqlParameterInfo("ProdID", CpLogStoreData.vLProdID);
setSubParams[7] = GetMakeSqlParameterInfo("TestID", CpLogStoreData.vLTestID);
if (CpLogStoreData.vLResult.IndexOf("OK") >= 0)
{
setParams[12] = GetMakeSqlParameterInfo("Result", 1);
cmd[1] = null;
}
else
setParams[12] = GetMakeSqlParameterInfo("Result", 0);
setParams[13] = GetMakeSqlParameterInfo("TestDuration", ConvertTextToTryValue<double>(CpLogStoreData.vLTestDuration, 0));
int iSetPos = 14;
if (CpLogStoreData.ExtrctInfo.Count > 0)
{
foreach (KeyValuePair<int, Tuple<string, bool, string, int, string, string, string>> k in CpLogStoreData.ExtrctInfo)
setParams[iSetPos++] = GetMakeSqlParameterInfo(k.Value.Item7, ConvertTextToTryValue<double>(CpLogStoreData.GetMeasValue(k.Key), 0));
}
cmd[0].Parameters.AddRange(setParams);
if(cmd[1] != null)
cmd[1].Parameters.AddRange(setSubParams);
}
else
{
object[] objItems;
if (dtCSVFileData.Rows.Count == 0)
throw new Exception();
cmd = new SqlCommand[dtCSVFileData.Rows.Count + dtCSVFileData.Rows.Count];
string columns = string.Empty;
string subColumns = string.Empty;
String sqlCommandInsert = "";
String sqlCommandSubInsert = "";
if (eGetLogType == eLogDataType.CSV_Type0)
{
columns = "LogAccessKey,ProcNo,PalletNumber,PalletID,PIndex,ProdNo,ProdID,SensorType,Status,TestID,Result,Val_Min,Val_Max,Val_Meas";
string values = string.Join(",", columns.Split(',').Select(c => string.Format("@{0}", c)));
sqlCommandInsert = string.Format("INSERT INTO " + CustomLogStoreData.vLSaveTableName + " ({0}) VALUES ({1})", columns, values);
}
else
{
columns = "LogAccessKey,ProcNo,PalletNumber,PalletID,PIndex,ProdNo,ProdID,SensorType,Status,TestID,Result";
string values = string.Join(",", columns.Split(',').Select(c => string.Format("@{0}", c)));
sqlCommandInsert = string.Format("INSERT INTO " + CustomLogStoreData.vLSaveTableName + " ({0}) VALUES ({1})", columns, values);
}
subColumns = "LogAccessKey,ProcNo,PalletNumber,PalletID,PIndex,ProdNo,ProdID,TestID";
string subValues = string.Join(",", subColumns.Split(',').Select(c => string.Format("@{0}", c)));
sqlCommandSubInsert = string.Format("INSERT INTO [HIST_TestNgResult] ({0}) VALUES ({1})", subColumns, subValues);
int iSubPos = 0;
for (int i = 0; i < dtCSVFileData.Rows.Count; i++)
{
iSubPos = dtCSVFileData.Rows.Count + i;
cmd[i] = null;
cmd[iSubPos] = null;
objItems = dtCSVFileData.Rows[i].ItemArray;
cmd[i] = new SqlCommand(sqlCommandInsert);
cmd[iSubPos] = new SqlCommand(sqlCommandSubInsert);
int iIndex = 0;
if (eGetLogType == eLogDataType.CSV_Type0)
iIndex = ConvertTextToTryValue<int>(objItems[1].ToString(), 0);
else
iIndex = ConvertTextToTryValue<int>(objItems[0].ToString(), 0);
if (iIndex == 0)
throw new Exception();
else
iIndex -= 1;
SqlParameter[] setParams = new SqlParameter[columns.Split(',').Count()];
SqlParameter[] setSubParams = new SqlParameter[subColumns.Split(',').Count()];
setParams[0] = GetMakeSqlParameterInfo("LogAccessKey", CustomLogStoreData.vLLogAccessKey[iIndex]);
setParams[1] = GetMakeSqlParameterInfo("ProcNo", CustomLogStoreData.vLProcNo[iIndex]);
setParams[2] = GetMakeSqlParameterInfo("PalletNumber", CustomLogStoreData.vLPalletNumber[iIndex]);
setParams[3] = GetMakeSqlParameterInfo("PalletID", CustomLogStoreData.vLPalletID[iIndex]);
setParams[4] = GetMakeSqlParameterInfo("PIndex", ConvertTextToTryValue<byte>(CustomLogStoreData.vLPIndex[iIndex], 0));
setParams[5] = GetMakeSqlParameterInfo("ProdNo", CustomLogStoreData.vLProdNo[iIndex]);
setParams[6] = GetMakeSqlParameterInfo("ProdID", CustomLogStoreData.vLProdID[iIndex]);
setParams[7] = GetMakeSqlParameterInfo("SensorType", CustomLogStoreData.vLSensorType[iIndex]);
setParams[8] = GetMakeSqlParameterInfo("Status", CustomLogStoreData.vLStatus[iIndex]);
setParams[9] = GetMakeSqlParameterInfo("TestID", CustomLogStoreData.vLTestID[iIndex]);
setSubParams[0] = GetMakeSqlParameterInfo("LogAccessKey", CustomLogStoreData.vLLogAccessKey[iIndex]);
setSubParams[1] = GetMakeSqlParameterInfo("ProcNo", CustomLogStoreData.vLProcNo[iIndex]);
setSubParams[2] = GetMakeSqlParameterInfo("PalletNumber", CustomLogStoreData.vLPalletNumber[iIndex]);
setSubParams[3] = GetMakeSqlParameterInfo("PalletID", CustomLogStoreData.vLPalletID[iIndex]);
setSubParams[4] = GetMakeSqlParameterInfo("PIndex", ConvertTextToTryValue<byte>(CustomLogStoreData.vLPIndex[iIndex], 0));
setSubParams[5] = GetMakeSqlParameterInfo("ProdNo", CustomLogStoreData.vLProdNo[iIndex]);
setSubParams[6] = GetMakeSqlParameterInfo("ProdID", CustomLogStoreData.vLProdID[iIndex]);
setSubParams[7] = GetMakeSqlParameterInfo("TestID", CustomLogStoreData.vLTestID[iIndex]);
if (eGetLogType == eLogDataType.CSV_Type0)
{
if (objItems[4].ToString().Trim().IndexOf("OK") >= 0)
CustomLogStoreData.vLResult[iIndex] = "1";
else
CustomLogStoreData.vLResult[iIndex] = "0";
CustomLogStoreData.vLVal_Meas[iIndex] = objItems[3].ToString().Trim();
}
else
{
if (objItems[1].ToString().IndexOf("OK") >= 0)
CustomLogStoreData.vLResult[iIndex] = "1";
else
CustomLogStoreData.vLResult[iIndex] = "0";
}
//
if (CustomLogStoreData.vLResult[iIndex].IndexOf("1") >= 0)
cmd[iSubPos] = null;
setParams[10] = GetMakeSqlParameterInfo("Result", ConvertTextToTryValue<byte>(CustomLogStoreData.vLResult[iIndex], 0));
if (eGetLogType == eLogDataType.CSV_Type0)
{
setParams[11] = GetMakeSqlParameterInfo("Val_Min", ConvertTextToTryValue<double>(CustomLogStoreData.vLVal_Min[iIndex], 0));
setParams[12] = GetMakeSqlParameterInfo("Val_Max", ConvertTextToTryValue<double>(CustomLogStoreData.vLVal_Max[iIndex], 0));
setParams[13] = GetMakeSqlParameterInfo("Val_Meas", ConvertTextToTryValue<double>(CustomLogStoreData.vLVal_Meas[iIndex], 0));
}
cmd[i].Parameters.AddRange(setParams);
if(cmd[iSubPos] != null)
cmd[iSubPos].Parameters.AddRange(setSubParams);
}
}
}
catch (Exception ex)
{
for (int i = 0; i < cmd.Count(); i++)
cmd[i] = null;
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" " + eGetLogType.ToString() + " General log processing [Command create] failed. " + ex.Message + " [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : XLogDataControl_.HISTTableProcess]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
cmd = null;
}
}
finally
{
;//
}
return cmd; //(SqlCommand[])cmd.Clone();
}
public static bool ReadFileData(eLogDataType eType, string strFileName)
{
string strSetHeader = string.Empty;
bool bReadStatus = true;
try
{
if (eType == eLogDataType.CSV_Type0)
strSetHeader = "No,Index,Time,MeasValue,Result";
else if (eType == eLogDataType.CSV_Type1)
strSetHeader = "Pallet_Num,Result,Time,X1,X2,X3,Y,Broken,LockingPinArea";
else if (eType == eLogDataType.CSV_Type2)
strSetHeader = "Pallet_Num,Result,Time,Pin_1_X_Position,Pin_1_Y_Position,Pin_2_X_Position,Pin_2_Y_Position,Pin_3_X_Position,Pin_3_Y_Position,Pin_4_X_Position,Pin_4_Y_Position,Pin_5_X_Position, Pin_5_Y_Position,Pin_6_X_Position,Pin_6_Y_Position,Pin_1_Thickness,Pin_2_Thickness,Pin_3_Thickness,Pin_4_Thickness,Pin_5_Thickness,Pin_6_Thickness,Locking Pin Area,Locking Pin Position";
using (StreamReader sr = new StreamReader(strFileName))
{
if (eType != eLogDataType.CSV_Type0)
sr.ReadLine();
dtCSVFileData = new DataTable();
while (!sr.EndOfStream)
{
string strGetData = sr.ReadLine();
strGetData = strGetData.Trim();
if (strGetData.Length <= 0)
continue;
string[] tempList = strGetData.Split(',');
for (int i = 0; i < tempList.Length; i++)
{
if (tempList[i].Length <= 0)
{
List<string> listData = tempList.ToList();
listData.RemoveAt(i);
tempList = listData.ToArray();
}
}
object[] objRows = tempList;
if (dtCSVFileData.Columns.Count <= 0)
{
foreach (string strData in strSetHeader.Split(','))
{
DataColumn dc = new DataColumn(strData);
dtCSVFileData.Columns.Add(dc);
}
dtCSVFileData.Rows.Add(objRows);
}
else
dtCSVFileData.Rows.Add(objRows);
}
}
}
catch (Exception ex)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General log processing [Read file] failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : STATIC XLogDataControl.ReadFileData]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
bReadStatus = false;
}
return bReadStatus;
}
}
}

View File

@ -0,0 +1,213 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using SystemX.Net.BaseProtocol;
using SystemX.Net.DB;
using CpTesterPlatform.CpLogUtil;
using static SystemX.Net.Platform.Common.Util.LogMessage;
namespace SystemX.Common.Log.Query
{
/// <summary>
/// Query Base Infomation
/// </summary>
///
public class CallPreMadeQueryInfo
{
public bool bReadInfoState { set; get; }
public bool bHasItem { set; get; }
public bool bLoading { set; get; }
private string strInfoFilePos;
//TestID, TableName
private Dictionary<string, int> dicIDInfo;
//ID - FROM - QUERY TEXT - RETURN FIELD(INDEX OR FIELD NAME)
private Dictionary<int, Tuple<string, string, string, string>> dicUserQueryItem;
public CallPreMadeQueryInfo(string strGetInfoPath)
{
strInfoFilePos = strGetInfoPath;
dicIDInfo = new Dictionary<string, int>();
dicUserQueryItem = new Dictionary<int, Tuple<string, string, string, string>>();
bHasItem = false;
bReadInfoState = false;
bLoading = false;
}
public List<KeyValuePair<int, Tuple<string, string, string, string>>> GetUserQueryInfo(string strTestID)
{
if (dicIDInfo.Keys.Contains(strTestID))
return dicUserQueryItem.ToList().FindAll(x => x.Value.Item1 == strTestID);
else
return null;
}
public Tuple<string, string> GetUserQueryText(string strTestID, List<string> LstParam = null)
{
string strResultQueryText = string.Empty;
string strMakeQueryText = string.Empty;
string strVarParam1 = string.Empty;
try
{
if (bHasItem == false)
throw new Exception("User query no have item.");
if (dicIDInfo.Keys.Contains(strTestID) == false)
throw new Exception("Can't find call id.");
var getQuery = dicUserQueryItem.ToList().FindAll(x => x.Value.Item1 == strTestID);
if (getQuery == null)
throw new Exception("Can't find [" + strTestID + "] ID user query.");
//받은 파라미터 개수
int nParamNum = LstParam != null ? LstParam.Count() : 0;
string strQueryID = getQuery[0].Value.Item1;
string strQueryFrom = getQuery[0].Value.Item2;
strMakeQueryText = getQuery[0].Value.Item3;
strVarParam1 = getQuery[0].Value.Item4;
//From 부분 대체
int nParamPos = 0;
if (strQueryFrom.Length > 0)
{
if (strMakeQueryText.IndexOf("@$UseFrom@$") < 0)
throw new Exception("Access table argument format [@$UseFrom@$] syntax does not exist.");
string[] strLstQueryForms = strQueryFrom.Split(';');
foreach (string strFormParam in strLstQueryForms)
{
if (strMakeQueryText.IndexOf("@$UseFrom@$") < 0)
throw new Exception("The number of parameters and the number of argument types do not match.");
strMakeQueryText = strMakeQueryText.Replace("@$UseFrom@$[" + (nParamPos + 1).ToString() + "]", strFormParam);
nParamPos++;
}
}
//사용자 입력 쿼리 텍스트 파라미터 개수 파악
if (nParamNum > 0)
{
int nQueryParamNum = 0;
string strTemp = strMakeQueryText;
while (true)
{
if (strTemp.IndexOf("@$PARAM@$") >= 0)
nQueryParamNum++;
else
break;
strTemp = strTemp.Remove(strTemp.IndexOf("@$PARAM@$"), 12);
}
if (nParamNum != nQueryParamNum)
throw new Exception("The number of parameters does not match.");
//파라미터 위치 값으로 대체
nParamPos = 0;
foreach (string strParamValue in LstParam)
{
strMakeQueryText = strMakeQueryText.Replace("@$PARAM@$[" + (nParamPos + 1).ToString() + "]", strParamValue);
nParamPos++;
}
}
}
catch
{
;//
}
finally
{
strResultQueryText = strMakeQueryText;
}
//Query Text, Return Field Pos or Field Name
return new Tuple<string, string>(strResultQueryText, strVarParam1);
}
private void GetUserQueryItemInfo(List<XElement> ListGetElement)
{
bLoading = true;
dicIDInfo.Clear();
dicUserQueryItem.Clear();
int nSetPos = 0;
foreach (var getXElement in ListGetElement)
{
bHasItem = true;
string strBaseID = getXElement.Attribute("ID").Value;
string strUseFrom = getXElement.Attribute("UseFrom").Value;
dicIDInfo.Add(strBaseID, nSetPos);
if (getXElement.Elements().ToList().Count == 1)
{
for (int i = 0; i < getXElement.Elements().ToList().Count; i++)
{
string strQueryText = getXElement.Element("QueryDetail").Attribute("QueryText").Value;
string strVarParam1 = getXElement.Element("QueryDetail").Attribute("ReturnField").Value;
dicUserQueryItem.Add(nSetPos++,
new Tuple<string, string, string, string>(
strBaseID,
strUseFrom,
strQueryText,
strVarParam1));
}
}
else
throw new Exception("Need only one by one Query-Information!");
}
bLoading = false;
}
public bool Load()
{
bReadInfoState = true;
try
{
XDocument xDoc = XDocument.Load(strInfoFilePos);
var xElement = xDoc.Element("ROOT");
if (xElement != null)
{
var ListGetElement = xElement.Elements("UserQueryItem").ToList();
GetUserQueryItemInfo(ListGetElement);
}
}
catch (Exception ex)
{
bReadInfoState = false;
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"UserQueryItem read failed. [SystemX.Common.Protocol.Log.Query : UserQueryInfo.Load]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
return bReadInfoState;
}
}
}

View File

@ -0,0 +1,325 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using SystemX.Net;
using SystemX.Net.BaseProtocol;
using SystemX.Net.DB;
using CpTesterPlatform.CpLogUtil;
using static SystemX.Net.Platform.Common.Util.LogMessage;
using static SystemX.Net.DB.XDBConnManager;
namespace SystemX.Common.Log.SIA
{
public class AnalysisLog_SIA : IDisposable
{
public bool STATE { set; get; }
//DataBase
private XDBConnManager MngDBConn;
//QueryInfo
public LogProcessInfo_SIA qiLogProcessInfo;
//Log Scan Process Task
private Task taskScanProcess;
private bool m_bTaskBlock;
//
private Stopwatch stProcessTime;
private long lLastProcessTime;
private long lLastItemTime;
private long lLastProcessNum;
private CancellationTokenSource cts;
public int SET_LOG_PROC_POS { set; get; }
public int SET_LOG_DELETE_MANAGE_POS { set; get; }
public int SET_LOG_SCAN_SHIFT_TIME { set; get; }
public int SET_LOG_MANAGE_SCAN_TIME { set; get; }
//
private string strLogDataFilePath { set; get; }
private eLogDataType eGetLogDataType { set; get; }
private eLogAccessType eGetAccessType { set; get; }
private CpLogHeader getCpLogHeader;
//
public bool[] LOG_DATA_CHECK_STATE { set; get; }
public long GET_LAST_PROCESS_TIME()
{
return lLastProcessTime;
}
public long GET_LAST_PROCESS_NUM()
{
return lLastProcessNum;
}
public long GET_LAST_ITEM_TIME()
{
return lLastItemTime;
}
~AnalysisLog_SIA()
{
Dispose(false);
}
public AnalysisLog_SIA()
{
STATE = true;
//Proc Position
SET_LOG_PROC_POS = 0;
SET_LOG_DELETE_MANAGE_POS = 0;
//1초 마다 미 처리 로그 스캔
SET_LOG_SCAN_SHIFT_TIME = 500;
//24시간 마다 삭제 대상 데이터 스캔
SET_LOG_MANAGE_SCAN_TIME = 86400000;
stProcessTime = new Stopwatch();
stProcessTime.Start();
lLastProcessTime = 0;
lLastItemTime = 0;
lLastProcessNum = 0;
MessageOutput.PrintLogLevel = LogMessageLevel.INFO;
string strExcutePos = Environment.CurrentDirectory;
string strDBInfoPos = strExcutePos + @"\Configure\DBConnInfo.xml";
string strLogProcessInfoPos = strExcutePos + @"\Configure\LogProcessInfo.xml";
qiLogProcessInfo = new LogProcessInfo_SIA(strLogProcessInfoPos);
if (qiLogProcessInfo.Load())
{
LOG_DATA_CHECK_STATE = new bool[qiLogProcessInfo.GeManageInfo().Count()];
for (int i = 0; i < qiLogProcessInfo.GeManageInfo().Count(); i++)
LOG_DATA_CHECK_STATE[i] = true;
MngDBConn = new XDBConnManager();
MngDBConn.ConfigPath = strDBInfoPos;
if (MngDBConn.OpenConnection())
{
taskScanProcess = null;
m_bTaskBlock = false;
cts = new CancellationTokenSource();
taskScanProcess = new Task(new Action<object>(WatchResultTable), cts.Token);
taskScanProcess.Start();
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" Success to connect to DB. [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.AnalysisLog_]", ConsoleColor.White, LogMessageLevel.DEBUG);
}
else
{
STATE = false;
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" Failed to connect to DB. [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.AnalysisLog_]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
else
{
STATE = false;
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" Read to configure failed. [SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_.AnalysisLog_]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool bDisposing)
{
if (bDisposing)
{
}
if (taskScanProcess != null)
{
cts.Cancel();
taskScanProcess.Wait();
m_bTaskBlock = true;
}
// do releasing unmanaged resource (종결자가 없는 객체의 자원 해제)
// i.e. close file handle of operating systems
// suppress calling of Finalizer
GC.SuppressFinalize(this);
}
private DataSet QueryProcess(string strGetQuery, ref bool bResult)//, out byte[] ucQueryByteArray)
{
bResult = false;
SqlDataReader xSqlReader = null;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
int iFieldCnt = 0;
int iRecordsAffectedCnt = 0;
bool bHasRow = false;
//ucQueryByteArray = null;
try
{
try
{
xSqlReader = MngDBConn.QueryDatabase(eConnCategory.Main, strGetQuery);
if (xSqlReader != null)
{
iFieldCnt = xSqlReader.FieldCount;
iRecordsAffectedCnt = xSqlReader.RecordsAffected;
bHasRow = xSqlReader.HasRows;
dt.Load(xSqlReader);
ds.Tables.Add(dt);
}
}
catch (Exception ex)
{
xSqlReader = null;
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + strGetQuery + "> Query process fail![SystemX.Net.Platform.Log : AnalysisLog_.QueryProcess]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
finally
{
if (xSqlReader != null)
xSqlReader.Close();
}
if (iFieldCnt > 0 || iRecordsAffectedCnt > 0 || bHasRow == true)
bResult = true;
return ds;
}
private async void WatchResultTable(object objState)
{
CancellationToken token = (CancellationToken)objState;
Stopwatch stLogManageTimer = new Stopwatch();
stLogManageTimer.Start();
while (!m_bTaskBlock)
{
if (token.IsCancellationRequested)
break;
try
{
if ((stLogManageTimer.ElapsedMilliseconds >= SET_LOG_MANAGE_SCAN_TIME))
{
if (qiLogProcessInfo.USE_TABLE_DATA_DELETE_MANAGER)
{
foreach (KeyValuePair<int, Tuple<bool, string, int>> infoM in qiLogProcessInfo.GeManageInfo())
{
if (infoM.Value.Item1)
{
int[] iGetDeleteNo = QueryManageDateTable(infoM.Value.Item2, infoM.Value.Item3.ToString(), token);
if (iGetDeleteNo != null)
{
ManageTableDataDelete(iGetDeleteNo, infoM.Value.Item2, infoM.Value.Item3.ToString(), token);
}
iGetDeleteNo = QueryManageDateTable(infoM.Value.Item2, infoM.Value.Item3.ToString(), token);
}
}
}
stLogManageTimer.Restart();
}
}
catch (Exception ex)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General Queue Process failed.[SystemX.Common.Protocol.Log.LSU_Trimming_4Th : AnalysisLog_SIA.WatchResultTable]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
await Task.Delay(1);
}
}
public int[] QueryManageDateTable(string strTableName, string strDateDiff, CancellationToken token)
{
bool bGetQueryResult = false;
int[] iQueryNoArr = null;
DataSet ds = QueryProcess("SELECT TOP(100) * FROM [" + strTableName + "] WHERE No " +
"IN(SELECT No FROM [" + strTableName + "] WHERE " +
"CONVERT(VARCHAR(8), UpdateDT, 112) <= CONVERT(VARCHAR(8), GETDATE() - " + strDateDiff + ", 112)) ORDER BY No;", ref bGetQueryResult);
bool hasRows = XCommons.isHasRow(ds);
if (hasRows)
{
int iRowNum = ds.Tables[0].Rows.Count;
iQueryNoArr = new int[iRowNum];
Array.Clear(iQueryNoArr, 0, iQueryNoArr.Length);
for (int i = 0; i < iRowNum; i++)
{
if (token.IsCancellationRequested)
return null;
var getValue = ds.Tables[0].Rows[i]["No"];
iQueryNoArr[i] = int.Parse(getValue.ToString());
}
}
stProcessTime.Restart();
return iQueryNoArr;
}
public bool ManageTableDataDelete(int[] iGetNoArray, string strTableName, string strDateDiff, CancellationToken token)
{
bool bGetQueryResult = false;
bool bFindItem = false;
long lDataNum = 0;
foreach (int iGetNo in iGetNoArray)
{
bFindItem = true;
lDataNum = iGetNoArray.Count();
if (token.IsCancellationRequested)
break;
/*
QueryProcess("DELETE [" + strTableName + "] WHERE " +
"CONVERT(VARCHAR(8), UpdateDT, 112) <= CONVERT(VARCHAR(8), GETDATE() - " + strDateDiff + ", 112);", ref bGetQueryResult);
*/
QueryProcess("DELETE [" + strTableName + "] WHERE No = " + iGetNo + ";", ref bGetQueryResult);
}
if (bFindItem)
{
lLastProcessTime = stProcessTime.ElapsedMilliseconds;
lLastProcessNum = lDataNum;
}
return true;
}
}
}

View File

@ -0,0 +1,179 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using SystemX.Net.BaseProtocol;
using SystemX.Net.DB;
using CpTesterPlatform.CpLogUtil;
using static SystemX.Net.Platform.Common.Util.LogMessage;
namespace SystemX.Common.Log.SIA
{
/// <summary>
/// Query Base Infomation
/// </summary>
///
public class LogProcessInfo_SIA
{
public bool READ_INFO_STATE { set; get; }
private string strInfoFilePos;
//TestID, TableName
private Dictionary<string, Tuple<int, string>> dicBaseIDInfo;
//TestID, DetailLogUse
private Dictionary<string, bool> dicDetailInfo;
//KEY - STEP, Name, UpdateTableName, ToField
private Dictionary<int, Tuple<string, bool, string, int, string, string, string>> dicSubExtrctionInfo;
public bool USE_TABLE_DATA_DELETE_MANAGER { internal set; get; }
//KEY - TableName, USE
private Dictionary<string, bool> dicTableDataDeleteList;
//KEY - No, USE, TableName, Set Date
private Dictionary<int, Tuple<bool, string, int>> dicTableDataDeleteManager;
public LogProcessInfo_SIA(string strGetInfoPath)
{
strInfoFilePos = strGetInfoPath;
dicBaseIDInfo = new Dictionary<string, Tuple<int, string>>();
dicDetailInfo = new Dictionary<string, bool>();
dicSubExtrctionInfo = new Dictionary<int, Tuple<string, bool, string, int, string, string, string>>();
//
dicTableDataDeleteList = new Dictionary<string, bool>();
dicTableDataDeleteManager = new Dictionary<int, Tuple<bool, string, int>>();
}
public string GetSaveTableName(string strTestID)
{
if (dicBaseIDInfo.Keys.Contains(strTestID))
{
return dicBaseIDInfo[strTestID].Item2;
}
else
return "";
}
public bool GetSaveDetailTable(string strTestID)
{
if (dicDetailInfo.Keys.Contains(strTestID))
return dicDetailInfo[strTestID];
else
return false;
}
public List<KeyValuePair<int, Tuple<string, bool, string, int, string, string, string>>> GetExtractInfo(string strTestID)
{
if (dicBaseIDInfo.Keys.Contains(strTestID))
return dicSubExtrctionInfo.ToList().FindAll(x => x.Value.Item1 == strTestID);
else
return null;
}
public List<KeyValuePair<int, Tuple<bool, string, int>>> GeManageInfo()
{
return dicTableDataDeleteManager.ToList();
}
public bool Load()
{
READ_INFO_STATE = true;
int iSetPos = 0;
try
{
XDocument xDoc = XDocument.Load(strInfoFilePos);
var xElement = xDoc.Element("ROOT");
if (xElement != null)
{
var ListGetElement = xElement.Elements("TableDataDeleteManager").ToList();
foreach (var getXElement in ListGetElement)
{
USE_TABLE_DATA_DELETE_MANAGER = Convert.ToBoolean(getXElement.Attribute("USE").Value);
if (getXElement.Elements().ToList().Count > 0)
{
iSetPos = 0;
for (int i = 0; i < getXElement.Elements().ToList().Count; i++)
{
int iGetDateDiff = 0;
if (int.TryParse(getXElement.Element("Management" + (i + 1).ToString()).Attribute("DateDifference").Value.ToString(), out iGetDateDiff))
{
dicTableDataDeleteList.Add(getXElement.Element("Management" + (i + 1).ToString()).Attribute("TableName").Value,
Convert.ToBoolean(getXElement.Element("Management" + (i + 1).ToString()).Attribute("USE").Value));
dicTableDataDeleteManager.Add(iSetPos++,
new Tuple<bool, string, int>(
Convert.ToBoolean(getXElement.Element("Management" + (i + 1).ToString()).Attribute("USE").Value),
getXElement.Element("Management" + (i + 1).ToString()).Attribute("TableName").Value,
iGetDateDiff));
}
else
throw new Exception("DateDifference value error.");
}
}
}
ListGetElement = xElement.Elements("QueryInfo").ToList();
foreach (var getXElement in ListGetElement)
{
string strBaseID = getXElement.Attribute("ID").Value;
bool bGetDetailSelect = false;
int iGetProcNo = int.Parse(getXElement.Attribute("ProcNo").Value);
dicBaseIDInfo.Add(strBaseID, new Tuple<int, string>(iGetProcNo, getXElement.Attribute("Table").Value));
dicDetailInfo.Add(strBaseID, bool.TryParse(getXElement.Attribute("DetailProcess").Value, out bGetDetailSelect) == true ? bGetDetailSelect : false);
if (getXElement.Elements().ToList().Count > 0)
{
iSetPos = 0;
for (int i = 0; i < getXElement.Elements().ToList().Count; i++)
{
int iGetStep = 0;
if (int.TryParse(getXElement.Element("ExtractionInfo" + (i + 1).ToString()).Attribute("Step").Value.ToString(), out iGetStep))
{
string strUpdateTable = getXElement.Element("ExtractionInfo" + (i + 1).ToString()).Attribute("UpdateTableName").Value;
bool bUpdateTableDiff = dicSubExtrctionInfo.ToList().FindAll(x => x.Value.Item1 == strBaseID).All(x => x.Value.Item6 == strUpdateTable);
if (bUpdateTableDiff == false)
throw new Exception();
dicSubExtrctionInfo.Add(iSetPos++,
new Tuple<string, bool, string, int, string, string, string>(
strBaseID,
Convert.ToBoolean(getXElement.Element("ExtractionInfo" + (i + 1).ToString()).Attribute("MO_Find").Value),
getXElement.Element("ExtractionInfo" + (i + 1).ToString()).Attribute("MO").Value,
iGetStep,
getXElement.Element("ExtractionInfo" + (i + 1).ToString()).Attribute("Name").Value,
getXElement.Element("ExtractionInfo" + (i + 1).ToString()).Attribute("UpdateTableName").Value,
getXElement.Element("ExtractionInfo" + (i + 1).ToString()).Attribute("ToField").Value));
}
else
throw new Exception("Step value error.");
}
}
}
}
}
catch (Exception ex)
{
READ_INFO_STATE = false;
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"LogProcessInfo read failed. [SystemX.Common.Protocol.Log.SIA : LogProcessInfo_SIA.Load]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
return READ_INFO_STATE;
}
}
}