[성현모] MiddleWare.Log 프로젝트 추가

This commit is contained in:
SHM
2024-06-26 11:34:28 +09:00
parent edf0aedc6b
commit d463bfa084
39 changed files with 7357 additions and 3 deletions

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,268 @@
using DevExpress.Data.Helpers;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Navigation;
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using SystemX.Net;
using SystemX.Common;
using SystemX.Net.BaseProtocol;
using SystemX.Net.Comm;
using SystemX.Net.Schedule;
using SystemX.Net.DB.LogProcess;
using SystemX.Common.Serialization;
using SystemX.Common.Archive;
//using SystemX.Common.Protocol.SIA;
using DevExpress.Utils.Extensions;
using static SystemX.Net.Platform.Common.Util.LogMessage;
using static SystemX.Net.DB.LogProcess.XLogDBConnManager;
using SystemX.Net.Platform.SystemX.Common;
namespace SystemX.Net.MiddlewareUI
{
public partial class MainForm : DevExpress.XtraBars.FluentDesignSystem.FluentDesignForm
{
private async void WatchRecvCommandQueue()
{
await Task.Delay(250);
while (!m_bTaskCommandBlock)
{
try
{
CT.ThrowIfCancellationRequested();
}
catch (OperationCanceledException CancelEx)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" Work Canceled. [SystemX.Net.MiddlewareUI : MainForm.WatchRecvCommndQueue]\r\n" + CancelEx.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
break;
}
//
try
{
if (bTaskCommandWaitLock == false)
QueryRecvCommandQueue();
}
catch (Exception e)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General Queue Process failed.[1] [SystemX.Net.MiddlewareUI : MainForm.WatchRecvCommndQueue]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
await Task.Delay(500);
}
}
private bool LogMemoryPushProcess(int nPos, int nStPos)
{
int nSetSize = int.MaxValue;
byte[] ucSetLogArray = null;
bool bProcResult = false;
using (LogSharedMemory memLog = new LogSharedMemory(ParamterMapLog))
{
if (memLog.CheckFile(nPos))
{
LogMappedPacket LogMapFile = new LogMappedPacket();
nSetSize = Marshal.SizeOf(LogMapFile);
ucSetLogArray = new byte[nSetSize];
LogMapFile = (LogMappedPacket)SystemXNetSerialization.RawDeSerialize(ucSetLogArray, LogMapFile.GetType());
bool bFindLogResult = false;
LogMapFile = memLog.Get(nPos, nStPos, out bFindLogResult, nSetSize).Value;
if (bFindLogResult == false)
return false;
if (LogMapFile.bLogFileReadComplete == false)
{
LogMapFile.bLogFileReadComplete = true;
memLog.Set(nPos, LogMapFile);
StringBuilder sb = new StringBuilder();
sb.Append("[" + (++nEnqueueCount).ToString() + "][Enqueue]");
sb.Append("[");
sb.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sb.Append("], ");
sb.Append("Type [" + LogMapFile.objLogType[0].Data.ToString() + "], ");
sb.Append("S Port [" + LogMapFile.nStreamPort.ToString() + "], ");
sb.Append("C Port [" + LogMapFile.nCommandPort.ToString() + "], ");
sb.Append("Size [" + LogMapFile.nLogDataSize.ToString() + "], ");
sb.Append("Number [" + LogMapFile.nNumber.ToString() + "], ");
sb.Append("Host [" + LogMapFile.objHost[0].Data + "], ");
sb.Append("Section [" + LogMapFile.objSection[0].Data + "], ");
sb.Append("St Name [" + LogMapFile.objStationName[0].Data + "], ");
sb.Append("St ID [" + LogMapFile.nStationID.ToString() + "], ");
sb.Append("File Name [" + LogMapFile.objOptionFileName[0].Data + "], ");
sb.Append("File Extension [" + LogMapFile.objOptionFileExtension[0].Data + "] ");
/*
sb.Append("TL ID[" + LogMapFile.objResultTestListCntID[0].Data + "], ");
sb.Append("V[" + LogMapFile.objProdPNo[0].Data + "], ");
sb.Append("PN[" + LogMapFile.objProdCNo[0].Data + "], ");
sb.Append("TT[" + LogMapFile.objTestType[0].Data + "], ");
sb.Append("TC[" + LogMapFile.objTestCode[0].Data + "], ");
sb.Append("Ver[" + LogMapFile.objVersion[0].Data + "], ");
sb.Append("PC[" + LogMapFile.objProdCode[0].Data + "], ");
sb.Append("DB V No[" + LogMapFile.nTestListVariantNo.ToString() + "] ");
*/
sb.AppendLine();
if (nEnqueueCount >= Int64.MaxValue)
nEnqueueCount = 0;
LogDataRecvText.Enqueue(sb);
LogDataQueue[nPos].Enqueue(LogMapFile);
bProcResult = true;
}
}
}
return bProcResult;
}
private bool QueryRecvCommandQueue()
{
bool bState = true;
string strProcessDebugInfo = string.Empty;
long l1 = long.MinValue;
long l2 = long.MinValue;
try
{
bTaskCommandWaitLock = true;
Stopwatch stProcessTimeChk = new Stopwatch();
stProcessTimeChk.Start();
using (InfoLogSharedMemory memInfoLog = new InfoLogSharedMemory(ParamterMapInfoLog))
{
InfoLogMappedPacket InfoLogMapFile = new InfoLogMappedPacket();
int nSetSize = Marshal.SizeOf(InfoLogMapFile);
byte[] ucSetLogArray = new byte[nSetSize];
InfoLogMapFile = (InfoLogMappedPacket)SystemXNetSerialization.RawDeSerialize(ucSetLogArray, InfoLogMapFile.GetType());
if (memInfoLog.CheckFile())
{
bool bFindInfoLogResult = false;
//로그 처리가 필요한 위치 조회
bool[] bGetStationReadyLog = memInfoLog.Get(out bFindInfoLogResult, nSetSize);
if (bFindInfoLogResult == false)
return bState;
//Array.Copy(bGetStationReadyLog, 0, InfoLogMapFile.bLogDataReady, 0, SharedMemory.nMaxInfoFullAccessSize);
Array.Clear(bCompareLogReadyState, 0, SharedMemory.nMaxInfoFullAccessSize);
for (int i = 0; i < SharedMemory.nMaxInfoFullAccessSize; i++)
{
if (bGetStationReadyLog[i] != bBeforeLogReadyState[i])
bCompareLogReadyState[i] = true;
}
//존재할 경우
if (bCompareLogReadyState.Any(x => x == true))
{
//존재하는 개수 파악
bool[] arrCheckNum = Array.FindAll(bCompareLogReadyState, x => x == true);
//개수 확인
int nFindCount = arrCheckNum.Count();
//개수 만큼 Index 확인
for (int i = 0; i < nFindCount; i++)
{
Stopwatch stItemTimeChk = new Stopwatch();
stItemTimeChk.Start();
int nIdx = Array.FindIndex(bCompareLogReadyState, x => x == true);
//Index 포트 변환 및 Station(최대 8) 확인
int nPos = (nIdx / SharedMemory.nMaxStationSize) + PORT_DISTRIBUTION_NUM;
int nAccessPart = nIdx / SharedMemory.nMaxStationSize;
int nSubPos = nIdx % SharedMemory.nMaxStationSize;
if (bCompareLogReadyState[nIdx])
{
LogMemoryPushProcess(nPos, nSubPos);
bCompareLogReadyState[nIdx] = false;
}
l2 = stItemTimeChk.ElapsedMilliseconds;
}
/*for (int i = PORT_DISTRIBUTION_NUM; i < ALL_MANAGE_NUM && !m_bTaskStreamBlock; i++)
{
for (int j = (i - PORT_DISTRIBUTION_NUM) * SharedMemory.nMaxStationSize;
j < ((i - PORT_DISTRIBUTION_NUM) * SharedMemory.nMaxStationSize) + SharedMemory.nMaxStationSize; j++)
{
if (bGetStationReadyLog[j])
{
LogMemoryProcess(i, j);
bGetStationReadyLog[j] = false;
}
}
Thread.Sleep(10);
}*/
//memInfoLog.Set(bGetStationReadyLog);
Array.Copy(bGetStationReadyLog, 0, bBeforeLogReadyState, 0, SharedMemory.nMaxInfoFullAccessSize);
}
}
}
l1 = stProcessTimeChk.ElapsedMilliseconds;
if (l1 != long.MinValue && l2 != long.MinValue)
{
LogDataRecvText.Enqueue(new StringBuilder(">>[Enqueue-Process][" + l1.ToString() + "][Enqueue-Item][" + l2.ToString() + "]\r\n"));
}
}
catch (Exception e)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + strProcessDebugInfo + @" Recv queue process fail.[SystemX.Net.MiddlewareUI : MainForm.QueryRecvCommandQueue]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
bState = false;
}
finally
{
bTaskCommandWaitLock = false;
}
return bState;
}
}
}

View File

@ -0,0 +1,73 @@
using DevExpress.Data.Helpers;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Navigation;
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.IO;
using System.Diagnostics;
using SystemX.Net;
using SystemX.Common;
using SystemX.Net.BaseProtocol;
using SystemX.Net.Comm;
using SystemX.Net.Schedule;
using SystemX.Net.DB.LogProcess;
using SystemX.Common.Serialization;
using SystemX.Common.Archive;
using System.Threading.Tasks;
//using SystemX.Common.Protocol.SIA;
using static SystemX.Net.Platform.Common.Util.LogMessage;
using SystemX.Net.Platform.Common.ExtensionMethods;
using SystemX.Net.Platform.SystemX.Common;
namespace SystemX.Net.MiddlewareUI
{
public partial class MainForm : DevExpress.XtraBars.FluentDesignSystem.FluentDesignForm
{
/*
private string GetFileName(int iPos, LogMappedPacket GetMappedInfo, string strCreateName, string strSubName)
{
Random randNumber = new Random();
string strFileName = strCreateName;
if (GetMappedInfo.objOptionFileName[0].Data.CompareTo("-") == 0)
strFileName += @strSubName + @randNumber.Next().ToString() + @GetMappedInfo.objOptionFileExtension[0].Data;
else
strFileName += @GetMappedInfo.objOptionFileName[0].Data + @GetMappedInfo.objOptionFileExtension[0].Data;
if (File.Exists(strFileName) == true)
{
while (true)
{
strFileName = strCreateName;
if (GetMappedInfo.objOptionFileName[0].Data.CompareTo("-") == 0)
strFileName += @strSubName + @randNumber.Next().ToString() + @GetMappedInfo.objOptionFileExtension[0].Data;
else
strFileName += @GetMappedInfo.objOptionFileName[0].Data + "_" + @randNumber.Next().ToString() + @GetMappedInfo.objOptionFileExtension[0].Data;
if (File.Exists(strFileName) == false)
break;
}
}
return strFileName;
}
*/
}
}

View File

@ -0,0 +1,214 @@
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.IO;
using System.Diagnostics;
using SystemX.Net;
using SystemX.Common;
using SystemX.Net.BaseProtocol;
using SystemX.Net.Comm;
using SystemX.Net.Schedule;
using SystemX.Net.DB.LogProcess;
using SystemX.Common.Serialization;
using SystemX.Common.Archive;
using System.Threading.Tasks;
//using SystemX.Common.Protocol.SIA;
using static SystemX.Net.Platform.Common.Util.LogMessage;
using System.Threading;
using SystemX.Net.Platform.Common.ExtensionMethods;
using DevExpress.Data.Helpers;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Navigation;
using static SystemX.Net.DB.LogProcess.XLogDBConnManager;
using System.Net.NetworkInformation;
namespace SystemX.Net.MiddlewareUI
{
public partial class MainForm : DevExpress.XtraBars.FluentDesignSystem.FluentDesignForm
{
public bool CPX_ReadVRFYList(int nConnId, int nTestListNo, string strProcessDebugInfo, out int nReadStepVersion, /*int nSetReadStepVersion,*/ int nLoadPosition = 0, bool bForceRead = true)
{
nReadStepVersion = int.MaxValue;
try
{
string strGetVersionTableName = MngDBLogConn.GetDBConnectInfo().ConnMain.VERSION_TABLE;
string strGetVRFYTableName = MngDBLogConn.GetDBConnectInfo().ConnMain.VRFY_TABLE;
try
{
//해당 테스트리스 정보 마지막 업데이트 번호 가져오기
thisConnInfo[nConnId].getLatestStepVer = QueryStreamProcess(eConnCategory.Main, "SELECT LatestStepVersion FROM [" + strGetVersionTableName + "] WHERE TestlistNo = " + nTestListNo + ";");
nReadStepVersion = Convert.ToInt32(thisConnInfo[nConnId].getLatestStepVer.Tables[0].Rows[0]["LatestStepVersion"]);
}
catch
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + strProcessDebugInfo +
@" CpLogProcess [" + strGetVersionTableName + "] MSV failed to obtain the most recent update number for VRFY (VRFY could not be found with the loading test list information.). [SystemX.Net.MiddlewareUI : MainForm.ReadVRFYList]", ConsoleColor.Red, LogMessageLevel.FATAL);
throw new Exception();
}
//이전 버전 사용 일시
if (nLoadPosition > 0)
nReadStepVersion -= nLoadPosition;
/* Changed
* 마지막 업데이트 번호가 다를때만 테스트리스트(VRFY) 갱신(Enabled Step 별 가장 최근 업데이트 번호 목록 정리)
* > 항상 최근 해당 테스트리스트(VRFY) 조회로 변경
* > 매번 조회시 속도 문제로 동일한 VRFY일 경우 SKIP
* > INDEX 사용
*/
if (bForceRead ||
(thisConnInfo[nConnId].bQueryVRFYLoaded == false ||
thisConnInfo[nConnId].nLastQueryTLFileNumber != nTestListNo ||
thisConnInfo[nConnId].nLastQueryTLStepVersion != nReadStepVersion))
{
try
{
thisConnInfo[nConnId].dsLatestVRFYRel = QueryStreamProcess(eConnCategory.Main, "SELECT * FROM ( " +
"SELECT *, ROW_NUMBER() OVER(PARTITION BY StepID ORDER BY StepVersion DESC) " +
"AS RN FROM [" + strGetVRFYTableName + "] WITH (INDEX=[CSK_VRFY_Release_1]) WHERE TestlistNo = " + nTestListNo + " " +
"AND StepVersion <= " + nReadStepVersion + ") X WHERE RN = 1 ORDER BY X.StepID ASC;");
thisConnInfo[nConnId].dsLongTermLatestVRFYRel = thisConnInfo[nConnId].dsLatestVRFYRel.Copy();
DataColumn[] keys1 = new DataColumn[1];
keys1[0] = new DataColumn();
keys1[0] = thisConnInfo[nConnId].dsLatestVRFYRel.Tables[0].Columns["StepID"];
thisConnInfo[nConnId].dsLatestVRFYRel.Tables[0].PrimaryKey = keys1;
DataColumn[] keys2 = new DataColumn[1];
keys2[0] = new DataColumn();
keys2[0] = thisConnInfo[nConnId].dsLongTermLatestVRFYRel.Tables[0].Columns["StepID"];
thisConnInfo[nConnId].dsLongTermLatestVRFYRel.Tables[0].PrimaryKey = keys2;
thisConnInfo[nConnId].nLastQueryTLFileNumber = nTestListNo;
thisConnInfo[nConnId].nLastQueryTLStepVersion = nReadStepVersion;
thisConnInfo[nConnId].bQueryVRFYLoaded = true;
}
catch
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + strProcessDebugInfo +
@" CpLogProcess Failed to get list from [" + strGetVRFYTableName + "]. [SystemX.Net.MiddlewareUI : MainForm.ReadVRFYList]", ConsoleColor.Red, LogMessageLevel.FATAL);
throw new Exception();
}
}
}
catch
{
return false;
}
return true;
}
public bool CPXV2_ReadVRFYList(int nConnId, int nTestListFileNo, int nTestListVariantNo, string strProcessDebugInfo, out int nReadStepVersion, /*int nSetReadStepVersion,*/ int nLoadPosition = 0, bool bForceRead = true)
{
nReadStepVersion = int.MaxValue;
try
{
//HIST_TestListFileLatestStepVersion
//VRFY_TestListFileRelease
string strGetVersionTableName = MngDBLogConn.GetDBConnectInfo().ConnMain.VERSION_TABLE;
string strGetVRFYTableName = MngDBLogConn.GetDBConnectInfo().ConnMain.VRFY_TABLE;
try
{
//해당 테스트리스 정보 마지막 업데이트 번호 가져오기
thisConnInfo[nConnId].getLatestStepVer = QueryStreamProcess(eConnCategory.Main, "SELECT LatestStepVersion FROM [" + strGetVersionTableName + "] WITH(NOLOCK) WHERE TestListFileNo = " + nTestListFileNo + ";");
nReadStepVersion = Convert.ToInt32(thisConnInfo[nConnId].getLatestStepVer.Tables[0].Rows[0]["LatestStepVersion"]);
}
catch
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + strProcessDebugInfo +
@" CpLogProcess [" + strGetVersionTableName + "] MSV failed to obtain the most recent update number for VRFY (VRFY could not be found with the loading test list information.). [SystemX.Net.MiddlewareUI : MainForm.ReadVRFYList]", ConsoleColor.Red, LogMessageLevel.FATAL);
throw new Exception();
}
//이전 버전 사용 일시
if (nLoadPosition > 0)
nReadStepVersion -= nLoadPosition;
/* Changed
* 마지막 업데이트 번호가 다를때만 테스트리스트(VRFY) 갱신(Enabled Step 별 가장 최근 업데이트 번호 목록 정리)
* > 항상 최근 해당 테스트리스트(VRFY) 조회로 변경
* > 매번 조회시 속도 문제로 동일한 VRFY일 경우 SKIP
* > INDEX 사용
*/
if (bForceRead ||
(thisConnInfo[nConnId].bQueryVRFYLoaded == false ||
thisConnInfo[nConnId].nLastQueryTLFileNumber != nTestListFileNo ||
thisConnInfo[nConnId].nLastQueryTLVariantNumber != nTestListVariantNo ||
thisConnInfo[nConnId].nLastQueryTLStepVersion != nReadStepVersion))
{
try
{
string strQueryVRFY = "SELECT * FROM ( " +
"SELECT *, ROW_NUMBER() OVER(PARTITION BY StepID ORDER BY StepVersion DESC) " +
"AS RN FROM [" + strGetVRFYTableName + "] WITH (NOLOCK, INDEX=[CSK_VRFY_Release_2]) WHERE TestListFileNo = " + nTestListFileNo + " " +
"AND StepVersion <= " + nReadStepVersion + ") X WHERE RN = 1 ORDER BY X.StepID ASC;";
thisConnInfo[nConnId].dsLatestVRFYRel = QueryStreamProcess(eConnCategory.Main, strQueryVRFY);
thisConnInfo[nConnId].dsLongTermLatestVRFYRel = thisConnInfo[nConnId].dsLatestVRFYRel.Copy();
DataColumn[] keys1 = new DataColumn[1];
keys1[0] = new DataColumn();
keys1[0] = thisConnInfo[nConnId].dsLatestVRFYRel.Tables[0].Columns["StepID"];
thisConnInfo[nConnId].dsLatestVRFYRel.Tables[0].PrimaryKey = keys1;
DataColumn[] keys2 = new DataColumn[1];
keys2[0] = new DataColumn();
keys2[0] = thisConnInfo[nConnId].dsLongTermLatestVRFYRel.Tables[0].Columns["StepID"];
thisConnInfo[nConnId].dsLongTermLatestVRFYRel.Tables[0].PrimaryKey = keys2;
thisConnInfo[nConnId].nLastQueryTLFileNumber = nTestListFileNo;
thisConnInfo[nConnId].nLastQueryTLVariantNumber = nTestListVariantNo;
thisConnInfo[nConnId].nLastQueryTLStepVersion = nReadStepVersion;
thisConnInfo[nConnId].bQueryVRFYLoaded = true;
}
catch
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + strProcessDebugInfo +
@" CpLogProcess Failed to get list from [" + strGetVRFYTableName + "]. [SystemX.Net.MiddlewareUI : MainForm.ReadVRFYList]", ConsoleColor.Red, LogMessageLevel.FATAL);
throw new Exception();
}
}
}
catch
{
return false;
}
return true;
}
}
}

View File

@ -0,0 +1,456 @@
using DevExpress.Data.Helpers;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Navigation;
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.IO;
using System.Diagnostics;
using SystemX.Net;
using SystemX.Common;
using SystemX.Net.BaseProtocol;
using SystemX.Net.Comm;
using SystemX.Net.Schedule;
using SystemX.Net.DB.LogProcess;
using SystemX.Common.Serialization;
using SystemX.Common.Archive;
using System.Threading.Tasks;
//using SystemX.Common.Protocol.SIA;
using SystemX.Net.Middleware.Log.Commons;
using static SystemX.Net.Platform.Common.Util.LogMessage;
using System.Threading;
using static SystemX.Net.DB.LogProcess.XLogDBConnManager;
namespace SystemX.Net.MiddlewareUI
{
public partial class MainForm : DevExpress.XtraBars.FluentDesignSystem.FluentDesignForm
{
private bool IsImageExtension(string strFileNameInfo, bool bOnlyExtension = true)
{
if (bOnlyExtension)
return -1 != Array.IndexOf(COMMON.mediaExtensions, strFileNameInfo.ToUpperInvariant());
else
return -1 != Array.IndexOf(COMMON.mediaExtensions, Path.GetExtension(strFileNameInfo).ToUpperInvariant());
}
public List<byte[]> QueryStreamProcess(string strGetQuery, out byte[] ucQueryByteArray, out DataSet setResultDataSet)
{
SqlDataReader xSqlReader = null;
int iFieldCnt = 0;
int iRecordsAffectedCnt = 0;
bool bHasRow = false;
ucQueryByteArray = null;
setResultDataSet = null;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataSet getDS = Task.Run(() =>
{
try
{
try
{
xSqlReader = MngDBLogConn.CurrentConnection(eConnCategory.Main).QueryDatabase(strGetQuery);
if (xSqlReader != null)
{
iFieldCnt = xSqlReader.FieldCount;
iRecordsAffectedCnt = xSqlReader.RecordsAffected;
bHasRow = xSqlReader.HasRows;
dt.Load(xSqlReader);
ds.Tables.Add(dt);
}
}
catch (Exception e)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + strGetQuery + "> Query process fail![SystemX.Net.MiddlewareUI : MainForm.QueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
finally
{
if (xSqlReader != null)
xSqlReader.Close();
xSqlReader = null;
}
return ds;
}).Result;
if(XCommons.isHasRow(ds))
setResultDataSet = ds.Copy();
List<byte[]> getStreamList = XCommons.ObjectToByteStreamList(new BASE_PROTOCOL(BASE_PROTOCOL.PROTOCOL_CODE.RAW_SIZE), getDS);
return getStreamList;
}
public void QueryResultRemake(DataSet dsResult, int iSetFieldCnt, int iSetRecordsAffectedCnt, bool bSetHasRow, out byte[] ucQueryByteArray, params string[] strParameters)
{
int iFieldCnt = iSetFieldCnt;
int iRecordsAffectedCnt = iSetRecordsAffectedCnt;
bool bHasRow = bSetHasRow;
ucQueryByteArray = null;
ucQueryByteArray = XCommons.ObjectToByteStream(new BASE_PROTOCOL(BASE_PROTOCOL.PROTOCOL_CODE.DATASET_TRANSEFER),
dsResult,
null,
0,
iRecordsAffectedCnt,
bHasRow,
iFieldCnt,
strParameters);
}
public Tuple<DataSet, int, int, bool> QueryProcess(string strGetQuery, out byte[] ucQueryByteArray, params string[] strParameters)
{
SqlDataReader xSqlReader = null;
int iFieldCnt = 0;
int iRecordsAffectedCnt = 0;
bool bHasRow = false;
ucQueryByteArray = null;
DataSet getDS = Task.Run(() =>
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
try
{
try
{
xSqlReader = MngDBLogConn.CurrentConnection(eConnCategory.Main).QueryDatabase(strGetQuery);
if (xSqlReader != null)
{
iFieldCnt = xSqlReader.FieldCount;
iRecordsAffectedCnt = xSqlReader.RecordsAffected;
bHasRow = xSqlReader.HasRows;
dt.Load(xSqlReader);
ds.Tables.Add(dt);
}
}
catch (Exception e)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + strGetQuery + "> Query process fail![SystemX.Net.MiddlewareUI : MainForm.QueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
finally
{
if (xSqlReader != null)
xSqlReader.Close();
xSqlReader = null;
}
return ds;
}).Result;
ucQueryByteArray = XCommons.ObjectToByteStream(new BASE_PROTOCOL(BASE_PROTOCOL.PROTOCOL_CODE.DATASET_TRANSEFER),
getDS,
null,
0,
iRecordsAffectedCnt,
bHasRow,
iFieldCnt,
strParameters);
return new Tuple<DataSet, int, int, bool>(getDS, iRecordsAffectedCnt, iFieldCnt, bHasRow);
}
private bool ExcuteNonQueryCommandProcess(SqlCommand cmd)
{
return Task.Run(() =>
{
bool bExcuteResult = true;
try
{
try
{
bExcuteResult = MngDBLogConn.CurrentConnection(eConnCategory.Main).ExecuteNonCommandQuery(cmd);
}
catch (Exception e)
{
bExcuteResult = false;
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + cmd.CommandText + "> Query excute fail![SystemX.Net.MiddlewareUI : MainForm.AsyncExcuteNonQueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
finally
{
;
}
return bExcuteResult;
}).Result;
}
private bool ExcuteNonQueryStreamProcess(eConnCategory eConnType, SqlCommand cmd)
{
return Task.Run(() =>
{
bool bExcuteResult = true;
try
{
try
{
bExcuteResult = MngDBLogConn.CurrentConnection(eConnType).ExecuteNonStreamQuery(cmd);
}
catch (Exception e)
{
bExcuteResult = false;
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + cmd.CommandText + "> Query excute fail![SystemX.Net.MiddlewareUI : MainForm.AsyncExcuteNonQueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
finally
{
;
}
return bExcuteResult;
}).Result;
}
private DataSet QueryCommandProcess(eConnCategory eConnType, string strGetQuery, bool bUseTransaction = false)
{
return Task.Run(() =>
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
try
{
SqlDataReader xSqlReader = null;
try
{
int iFieldCnt = 0;
int iRecordsAffectedCnt = 0;
bool bHasRow = false;
try
{
xSqlReader = MngDBLogConn.CurrentConnection(eConnType).QueryCommandDatabase(strGetQuery, bUseTransaction);
if (xSqlReader != null)
{
iFieldCnt = xSqlReader.FieldCount;
iRecordsAffectedCnt = xSqlReader.RecordsAffected;
bHasRow = xSqlReader.HasRows;
dt.Load(xSqlReader);
ds.Tables.Add(dt);
}
}
catch (Exception e)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + strGetQuery + "> Query process fail![SystemX.Net.MiddlewareUI : MainForm.AsyncQueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
finally
{
if (xSqlReader != null)
xSqlReader.Close();
xSqlReader = null;
}
}
finally
{
;
}
return ds;
}).Result;
}
private DataSet QueryStreamProcess(eConnCategory eConnType, string strGetQuery)
{
return Task.Run(() =>
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
try
{
SqlDataReader xSqlReader = null;
try
{
int iFieldCnt = 0;
int iRecordsAffectedCnt = 0;
bool bHasRow = false;
try
{
xSqlReader = MngDBLogConn.CurrentConnection(eConnType).QueryStreamDatabase(strGetQuery);
if (xSqlReader != null)
{
iFieldCnt = xSqlReader.FieldCount;
iRecordsAffectedCnt = xSqlReader.RecordsAffected;
bHasRow = xSqlReader.HasRows;
dt.Load(xSqlReader);
ds.Tables.Add(dt);
}
}
catch (Exception e)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + strGetQuery + "> Query process fail![SystemX.Net.MiddlewareUI : MainForm.AsyncQueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
finally
{
if (xSqlReader != null)
xSqlReader.Close();
xSqlReader = null;
}
}
finally
{
;
}
return ds;
}).Result;
}
private DataSet QueryStreamProcess(eConnCategory eConnType, string strGetQuery, ref int nRecAffectedCnt)
{
nRecAffectedCnt = -2;
int iFieldCnt = 0;
int iRecordsAffectedCnt = -2;
bool bHasRow = false;
DataSet dsResult = null;
dsResult = Task.Run(() =>
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
try
{
SqlDataReader xSqlReader = null;
try
{
try
{
xSqlReader = MngDBLogConn.CurrentConnection(eConnType).QueryStreamDatabase(strGetQuery);
if (xSqlReader != null)
{
iFieldCnt = xSqlReader.FieldCount;
//Default -2 Fail 0 Select -1
iRecordsAffectedCnt = xSqlReader.RecordsAffected;
bHasRow = xSqlReader.HasRows;
dt.Load(xSqlReader);
ds.Tables.Add(dt);
}
}
catch (Exception e)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + strGetQuery + "> Query process fail![SystemX.Net.MiddlewareUI : MainForm.AsyncQueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
finally
{
if (xSqlReader != null)
xSqlReader.Close();
xSqlReader = null;
}
}
finally
{
;
}
return ds;
}).Result;
nRecAffectedCnt = iRecordsAffectedCnt;
return dsResult;
}
private DataSet QueryProcess(string strGetQuery)
{
return Task.Run(() =>
{
SqlDataReader xSqlReader = null;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
int iFieldCnt = 0;
int iRecordsAffectedCnt = 0;
bool bHasRow = false;
try
{
try
{
xSqlReader = MngDBLogConn.CurrentConnection(eConnCategory.Main).QueryDatabaseSub(strGetQuery);
if (xSqlReader != null)
{
iFieldCnt = xSqlReader.FieldCount;
iRecordsAffectedCnt = xSqlReader.RecordsAffected;
bHasRow = xSqlReader.HasRows;
dt.Load(xSqlReader);
ds.Tables.Add(dt);
}
}
catch (Exception e)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + strGetQuery + "> Query process fail![SystemX.Net.MiddlewareUI : MainForm.QueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
finally
{
if (xSqlReader != null)
xSqlReader.Close();
xSqlReader = null;
}
return ds;
}).Result;
}
}
}

View File

@ -0,0 +1,701 @@
using DevExpress.Data.Helpers;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Navigation;
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.IO;
using System.IO.Compression;
using System.Diagnostics;
using SystemX.Net;
using SystemX.Common;
using SystemX.Net.BaseProtocol;
using SystemX.Net.Comm;
using SystemX.Net.Schedule;
using SystemX.Net.DB.LogProcess;
using SystemX.Common.Serialization;
using SystemX.Common.Archive;
using System.Threading.Tasks;
//using SystemX.Common.Protocol.SIA;
using static SystemX.Net.Platform.Common.Util.LogMessage;
using System.Threading;
using SystemX.Net.Middleware.Log.Commons;
using SystemX.Net.Platform.SystemX.Common;
using static SystemX.Net.DB.LogProcess.XLogDBConnManager;
using SystemX.Net.Middleware.Log.DeleteProc;
using SystemX.Net.Comm.IIS_FTP;
namespace SystemX.Net.MiddlewareUI
{
public partial class MainForm : DevExpress.XtraBars.FluentDesignSystem.FluentDesignForm
{
private async void WatchRecvStreamQueue()
{
await Task.Delay(250);
stCheckTermBulkWaitTime.Start();
while (!m_bTaskStreamBlock)
{
try
{
CT.ThrowIfCancellationRequested();
}
catch (OperationCanceledException CancelEx)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" Work Canceled. [SystemX.Net.MiddlewareUI : MainForm.WatchRecvStreamQueue]\r\n" + CancelEx.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
break;
}
//
try
{
if (bDatabaseConnResult == false)
continue;
if (MngDBLogConn.GetMainDBAccessTime() >= 120000)
QueryStreamProcess(eConnCategory.Main, "SELECT GETDATE() AS 'CHECK PING';");
if (MngDBLogConn.GetShortTermDBAccessTime() >= 120000)
QueryStreamProcess(eConnCategory.ShortTerm, "SELECT GETDATE() AS 'CHECK PING';");
if (MngDBLogConn.GetLongTermDBAccessTime() >= 120000)
QueryStreamProcess(eConnCategory.LongTerm, "SELECT GETDATE() AS 'CHECK PING';");
nBulkLogCount = lstBulkTermLogInfo.Count;
nBulkLongTermCount = lstBulkShortTermLog.Count;
nBulkShortTermCount = lstBulkLongTermLog.Count;
nBulkTimeValue = stCheckTermBulkWaitTime.ElapsedMilliseconds;
if (stCheckTermBulkWaitTime.ElapsedMilliseconds >= LoadInfo.BULK_ProcessTime_ms || bTryBulkInsertBuffer)
{
Stopwatch stMeasProcTime = new Stopwatch();
if (lstBulkTermLogInfo.Count > 0)
{
stMeasProcTime.Start();
foreach (string str in lstBulkTermLogInfo.ToArray())
{
LogDataRecvText.Enqueue(new StringBuilder(str));
LogDataRecvText.Enqueue(new StringBuilder("\r\n"));
}
lstBulkTermLogInfo.Clear();
}
//
if(lstBulkShortTermLog.Count > 0)
SetLogDataInsertProc(eConnCategory.ShortTerm);
if (lstBulkLongTermLog.Count > 0)
SetLogDataInsertProc(eConnCategory.LongTerm);
BULK_INSERT_EXIT:
if (stMeasProcTime.IsRunning)
{
LogDataRecvText.Enqueue(new StringBuilder(">>[BulkInsert-Process][" + stMeasProcTime.ElapsedMilliseconds.ToString() + "]\r\n"));
//Check Server Time And Db Change
bDatabaseConnResult = MngDBLogConn.CheckDatabaseConnection();
}
bTryBulkInsertBuffer = false;
stCheckTermBulkWaitTime.Restart();
}
//Map Log File Check
if (bTaskStreamWaitLock == false)
QueryRecvStreamQueue();
// TODO : FTP ALIS
if (StateFTP != eFTPServiceStatus.Connected)
goto ROUTINE_END;
//FTP Server Check
nFTPTimeValue = stProcessCheckFTPTime.ElapsedMilliseconds;
if (stProcessCheckFTPTime.ElapsedMilliseconds >= LoadInfo.FTP_ScanTime_ms)
{
List<string> lstFile = ControlFTP.PositionRootCheckList();
List<string> lstDownlaodFile = new List<string>();
List<string> lstDeleteFailedFile = new List<string>();
if (lstFile.Count == 0)
goto BRANCH_EXIT;
string strGetDownloadPath = GetFTPDownloadPath();
foreach (string f in lstFile)
lstDownlaodFile.Add(await ControlFTP.FileDownload(f, strGetDownloadPath));
foreach (string f in lstDownlaodFile)
{
string strGetFileName = Path.GetFileName(f);
if (ControlFTP.DeleteFile(strGetFileName) == false)
lstDeleteFailedFile.Add(strGetFileName);
}
BRANCH_EXIT:
ProcFTPCheckLogFiles();
foreach (string f in lstDeleteFailedFile)
{
string strGetFileName = Path.GetFileName(f);
if (ControlFTP.DeleteFile(strGetFileName) == false)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"FTP > file delete process failed. [SystemX.Net.MiddlewareUI : MainForm.WatchRecvStreamQueue]\r\n", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
stProcessCheckFTPTime.Restart();
}
ROUTINE_END:;
}
catch (Exception e)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General Queue Process failed. [SystemX.Net.MiddlewareUI : MainForm.WatchRecvStreamQueue]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
await Task.Delay(100);
}
}
private void SetLogDataInsertProc(eConnCategory SetCategory)
{
bool bBulkCopyResult = true;
string strSetLogTable = string.Empty;
string strAddText = string.Empty;
if (SetCategory == eConnCategory.ShortTerm)
{
strSetLogTable = MngDBLogConn.GetDBConnectInfo().ConnShortTerm.LOG_TABLE;
strAddText = "ShortTerm";
}
else if (SetCategory == eConnCategory.LongTerm)
{
strSetLogTable = MngDBLogConn.GetDBConnectInfo().ConnLongTerm.LOG_TABLE;
strAddText = "LongTerm";
}
try
{
//LogData Set Bulk
using (SqlTransaction sqlTran = MngDBLogConn.CurrentConnection(SetCategory).getConnection().BeginTransaction())
{
//Sql Bulk Insert 준비 - Short Log
//Make Result Command
SqlBulkCopy sbc = new SqlBulkCopy(sqlTran.Connection,
SqlBulkCopyOptions.CheckConstraints |
SqlBulkCopyOptions.FireTriggers |
SqlBulkCopyOptions.KeepNulls, sqlTran);
sbc.BatchSize = 5000;
sbc.DestinationTableName = "dbo." + strSetLogTable;
sbc.BulkCopyTimeout = 120;
try
{
// Write from the source to the destination.
//생성된 DataRow 들을 Bulk Copy 실시
if (SetCategory == eConnCategory.ShortTerm)
sbc.WriteToServer(lstBulkShortTermLog.ToArray());
else if (SetCategory == eConnCategory.LongTerm)
sbc.WriteToServer(lstBulkLongTermLog.ToArray());
//if (MngDBConn.InfoConnection.UTSI_STATE)
//{
// //Long Log
// SqlBulkCopy sbcL = new SqlBulkCopy(sqlTran.Connection,
// SqlBulkCopyOptions.CheckConstraints |
// SqlBulkCopyOptions.FireTriggers |
// SqlBulkCopyOptions.KeepNulls, sqlTran);
// sbcL.BatchSize = 5000;
// sbcL.DestinationTableName = "dbo.HIST_TestResultLongTerm";
// sbcL.BulkCopyTimeout = 120;
//
// sbcL.WriteToServer(SetMakeLogRows);
//}
}
catch (Exception ex)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + $@" CPXV2 CpLogProcess fail.({strAddText} - Bulk Upload) [SystemX.Net.MiddlewareUI : MainForm.SetLogDataInsertProc]\r\n" + ex.Message, ConsoleColor.Red, LogMessageLevel.FATAL);
bBulkCopyResult = false;
}
finally
{
// Close the SqlDataReader. The SqlBulkCopy
// object is automatically closed at the end
// of the using block.
if (bBulkCopyResult)
{
sqlTran.Commit();
if (SetCategory == eConnCategory.ShortTerm)
lstBulkShortTermLog.Clear();
else if (SetCategory == eConnCategory.LongTerm)
lstBulkLongTermLog.Clear();
LogDataRecvText.Enqueue(new StringBuilder($"<{strAddText} - All CpLogs(Bulk)Process Result [OK]>\r\n"));
}
else
{
sqlTran.Rollback();
LogDataRecvText.Enqueue(new StringBuilder($"<{strAddText} - All CpLogs(Bulk)Process Result [NOK]>\r\n"));
//throw new Exception();
}
}
}
}
catch
{
;//
}
finally
{
;//
}
if (bBulkCopyResult == false)
{
CommonProtocol cp = new CommonProtocol();
List<DataRow> lstRefRow = null;
if (SetCategory == eConnCategory.ShortTerm)
lstRefRow = lstBulkShortTermLog;
else if (SetCategory == eConnCategory.LongTerm)
lstRefRow = lstBulkLongTermLog;
foreach (DataRow dr in lstRefRow)
{
if (Convert.ToInt64(dr["No"]) == Int64.MinValue)
continue;
//Summary 객체를 이용해 DB 삽입할 SqlCommand 생성
SqlCommand cmd = cp.LogDataResultInsert(strSetLogTable, dr);
//Summary 삽입 > 실패시 처리
bool bProcessResult = ExcuteNonQueryStreamProcess(SetCategory, cmd);
if (bProcessResult == false)
{
LogDataRecvText.Enqueue(new StringBuilder($"<{strAddText} - CpLogs(Command) Process Result [NOK]>\r\n"));
continue;
}
else
LogDataRecvText.Enqueue(new StringBuilder($"<{strAddText} - CpLogs(Command) Process Result [OK]>\r\n"));
}
if (SetCategory == eConnCategory.ShortTerm)
lstBulkShortTermLog.Clear();
else if (SetCategory == eConnCategory.LongTerm)
lstBulkLongTermLog.Clear();
}
}
private bool QueryRecvStreamQueue()
{
//StackTrace st = new StackTrace(true);
bool bState = true;
string strProcessDebugInfo = string.Empty;
long l1 = long.MinValue;
long l2 = long.MinValue;
try
{
bTaskStreamWaitLock = true;
//Log Process
Stopwatch stProcessTimeChk = new Stopwatch();
stProcessTimeChk.Start();
for (int i = PORT_DISTRIBUTION_NUM; i < ALL_MANAGE_NUM && !m_bTaskCommandBlock; i++)
{
Stopwatch stItemTimeChk = new Stopwatch();
stItemTimeChk.Start();
if (LogDataQueue[i].Count <= 0)
continue;
LogMappedPacket LogMapFile = new LogMappedPacket();
int nSetSize = Marshal.SizeOf(LogMapFile);
byte[] ucSetLogArray = new byte[nSetSize];
LogMapFile = (LogMappedPacket)SystemXNetSerialization.RawDeSerialize(ucSetLogArray, LogMapFile.GetType());
int iPos = LogMapFile.nNumber;
strProcessDebugInfo = "[" + (iPos).ToString("D2") + "]" +
"[" + LogMapFile.nCommandPort + "]" +
"[" + LogMapFile.objHost[0].Data + "]" +
"[" + LogMapFile.objSection[0].Data + "]";
//
if (LogDataQueue[i].TryPeek(out LogMapFile)) //LogDataQueue[i].TryDequeue(out LogMapFile))
{
if (bShowCpLogProcessTime)
LogMapFile.bShowCpLogProcessTime = true;
StringBuilder sb = new StringBuilder();
sb.Append("[" + (++nDequeueCount).ToString() + "][TryDequeue]");
sb.Append("[");
sb.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
sb.Append("], ");
sb.Append("Type [" + LogMapFile.objLogType[0].Data.ToString() + "], ");
sb.Append("S Port [" + LogMapFile.nStreamPort.ToString() + "], ");
sb.Append("C Port [" + LogMapFile.nCommandPort.ToString() + "], ");
sb.Append("Size [" + LogMapFile.nLogDataSize.ToString() + "], ");
sb.Append("Number [" + LogMapFile.nNumber.ToString() + "], ");
sb.Append("Host [" + LogMapFile.objHost[0].Data + "], ");
sb.Append("Section [" + LogMapFile.objSection[0].Data + "], ");
sb.Append("St Name [" + LogMapFile.objStationName[0].Data + "], ");
sb.Append("St ID [" + LogMapFile.nStationID.ToString() + "], ");
sb.Append("File Name [" + LogMapFile.objOptionFileName[0].Data + "], ");
sb.Append("File Extension [" + LogMapFile.objOptionFileExtension[0].Data + "] ");
sb.Append("TL ID[" + LogMapFile.objResultTestListCntID[0].Data + "], ");
sb.Append("V[" + LogMapFile.objProdPNo[0].Data + "], ");
sb.Append("PN[" + LogMapFile.objProdCNo[0].Data + "], ");
sb.Append("TT[" + LogMapFile.objTestType[0].Data + "], ");
sb.Append("TC[" + LogMapFile.objTestCode[0].Data + "], ");
sb.Append("Ver[" + LogMapFile.objVersion[0].Data + "], ");
sb.Append("PC[" + LogMapFile.objProdCode[0].Data + "], ");
sb.Append("DB V No[" + LogMapFile.nTestListVariantNo.ToString() + "], ");
if (nDequeueCount >= Int64.MaxValue)
nDequeueCount = 0;
bool bProcResult = false;
if (MngDBLogConn.GetDBConnectInfo().ConnVersion == XDBConnInfo.eVersion.CPX)
{
sb.Append("!Use Log Process Version [CPX] - No longer supported.");
//bProcResult = CPX_CpLogProcess(LogMapFile);
bProcResult = false;
}
else if (MngDBLogConn.GetDBConnectInfo().ConnVersion == XDBConnInfo.eVersion.CPXV2)
{
bProcResult = CPXV2_CpLogProcess(LogMapFile);
if(bProcResult == true)
lstBulkTermLogInfo.Add(sb.ToString());
sb.Append("!Use Log Process Version [CPXV2] ");
}
if (bProcResult)
sb.Append("<CpLogProcess Make Log Result [OK]>");
else
sb.Append("<CpLogProcess Make Log Result [NOK]>");
sb.AppendLine();
LogDataProcessText.Enqueue(sb);
if (LogDataQueue[i].TryDequeue(out LogMapFile) == false)
{
if (LogDataQueue[i].TryDequeue(out LogMapFile) == false)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + strProcessDebugInfo + @" Recv queue try-dequeue failed. [SystemX.Net.MiddlewareUI : MainForm.QueryRecvStreamQueue]\r\n", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
}
}
}
l2 = stItemTimeChk.ElapsedMilliseconds;
}
l1 = stProcessTimeChk.ElapsedMilliseconds;
if (l1 != long.MinValue && l2 != long.MinValue)
{
LogDataProcessText.Enqueue(new StringBuilder(">>[TryDequeue-Process][" + l1.ToString() + "][TryDequeue-Item][" + l2.ToString() + "]\r\n"));
}
}
catch (Exception e)
{
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + strProcessDebugInfo + @" Recv queue stream process unknown fail. [SystemX.Net.MiddlewareUI : MainForm.QueryRecvStreamQueue]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
bState = false;
}
finally
{
bTaskStreamWaitLock = false;
}
return bState;
}
// TODO : FTP ALIS
internal eFTPServiceStatus StartFTPService()
{
ControlFTP = new CtrlFTP(LoadInfo.FTP_Use,
IPAddress.Parse(LoadInfo.FTP_IPAddress), Convert.ToInt32(LoadInfo.FTP_Port),
LoadInfo.FTP_Account, LoadInfo.FTP_Password);
if (ControlFTP.FTPConnState)
return eFTPServiceStatus.Connected;
else
return eFTPServiceStatus.Disconnected;
}
private string GetFTPDownloadPath()
{
string strYYYY = DateTime.Today.ToString("yyyy");
string strMM = DateTime.Today.ToString("MM");
string strdd = DateTime.Today.ToString("dd");
string strHHmmssfff = DateTime.Now.ToString("HHmmssfff");
string strGetRoot = Path.GetPathRoot(Environment.CurrentDirectory);
string DirPath = @strGetRoot + $@"\XProc\FTP\CpLog\{strYYYY}\{strMM}\{strdd}\";
//string CpLogDirPath = @strGetRoot + $@"XProcCpLog\Temp\{strYYYY}\{strMM}\{strdd}\{strHHmmssfff}\";
DirectoryInfo di1 = new DirectoryInfo(@DirPath);
if (!di1.Exists) Directory.CreateDirectory(@DirPath);
//DirectoryInfo di2 = new DirectoryInfo(@CpLogDirPath);
//if (!di2.Exists) Directory.CreateDirectory(@CpLogDirPath);
return DirPath;
}
private void ProcFTPCheckLogFiles()
{
//Scan And Send File
string strGetRoot = Path.GetPathRoot(Environment.CurrentDirectory);
//오늘 포함 -6일전까지 검색
string[] strScanYYYY = new string[7];
string[] strScanMM = new string[7];
string[] strScandd = new string[7];
for (int n = 6; n >= 0; n--)
{
DateTime dtSet = DateTime.Today.AddDays(-n);
strScanYYYY[n] = dtSet.ToString("yyyy");
strScanMM[n] = dtSet.ToString("MM");
strScandd[n] = dtSet.ToString("dd");
}
//
// 7일치 위치 확인
//
for (int n = 0; n < 7; n++)
{
string DirPath = strGetRoot + $@"\XProc\FTP\CpLog\{strScanYYYY[n]}\{strScanMM[n]}\{strScandd[n]}\";
string DirMovePath = strGetRoot + $@"\XProc\FTP\CpLog\{strScanYYYY[n]}\{strScanMM[n]}\{strScandd[n]}\History\";
//생성 폴더가 없을경우 SKIP
if (Directory.Exists(DirPath) == false)
continue;
if (Directory.Exists(DirMovePath) == false)
Directory.CreateDirectory(DirMovePath);
string fileExtension = "zip";
string[] dirs = Directory.GetDirectories(DirPath);
string[] files = Directory.GetFiles(DirPath, $"*.{fileExtension}", SearchOption.TopDirectoryOnly);
if (files.Length <= 0)
continue;
ProcFTPLogFiles(files, DirPath, DirMovePath);
}
}
private void ProcFTPLogFiles(string[] strArrFiles, string strReadDirPath, string strMoveDirPath)
{
string strExtractFilePos = string.Empty;
string strOrgRemoveFilePos = string.Empty;
string strHeaderInfo = string.Empty;
string strLogFileNameInfo = string.Empty;
long l1 = long.MinValue;
//Log Process
Stopwatch stProcessTimeChk = new Stopwatch();
stProcessTimeChk.Start();
foreach (string f in strArrFiles)
{
strOrgRemoveFilePos = f;
strHeaderInfo = string.Empty;
strLogFileNameInfo = string.Empty;
string[] strInfos = f.Split(';');
//파일정보 확인(로그 저장관련 정보)
/*
string strSetDateTime = strInfos[1];
string strSetStationName = strInfos[2];
int nSetTestListVariantNo = int.Parse(strInfos[3]);
string strSetProcNoP = strInfos[4];
string strSetProcNoC = strInfos[5];
string strSetTestType = strInfos[6];
string strSetTestCode = strInfos[7];
string strSetVersion = strInfos[8];
string strSetProdCode = strInfos[9];
string strSetTestListCntID = strInfos[10];
string strHost = strInfos[11];
string strSection = strInfos[12];
*/
int nSetTryNo = int.Parse(strInfos[13]);
Dictionary<string, string> dicSetLogInfo = new Dictionary<string, string>();
dicSetLogInfo.Add("DATE_TIME", strInfos[1]);
dicSetLogInfo.Add("STATION_NAME", strInfos[2]);
dicSetLogInfo.Add("VARIANT_NO", strInfos[3]);
dicSetLogInfo.Add("P_TTNR", strInfos[4]);
dicSetLogInfo.Add("TTNR", strInfos[5]);
dicSetLogInfo.Add("TEST_TYPE", strInfos[6]);
dicSetLogInfo.Add("TEST_CODE", strInfos[7]);
dicSetLogInfo.Add("VERSION", strInfos[8]);
dicSetLogInfo.Add("PROD_CODE", strInfos[9]);
dicSetLogInfo.Add("TESTLIST_ID", strInfos[10]);
dicSetLogInfo.Add("HOST", strInfos[11]);
dicSetLogInfo.Add("SECTION", strInfos[12]);
for (int m = 1; m < 12; m++)
strHeaderInfo += (strInfos[m + 1] + ";");
strHeaderInfo = strHeaderInfo.Remove(strHeaderInfo.Length - 1, 1);
//압축해제 하여 로그 파일 추출
using (FileStream fs = new FileStream(f, FileMode.Open))
using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Update, false))
{
foreach (ZipArchiveEntry zae in zip.Entries)
{
strLogFileNameInfo = zae.FullName;
if (strLogFileNameInfo.IndexOf(".txt") >= 0)
continue;
strExtractFilePos = strReadDirPath + strLogFileNameInfo;
//ZipFileExtensions
zae.ExtractToFile(strExtractFilePos, true);
}
}
//Sometihing Procee
LogMappedPacket EmptyLogMapFile = new LogMappedPacket();
StringBuilder sb = new StringBuilder();
sb.Append("[" + (++nDequeueCount).ToString() + "][TryDequeue]");
sb.Append("[");
sb.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
sb.Append("], ");
sb.Append("Type [FTP], ");
sb.Append("Host [" + dicSetLogInfo["HOST"] + "], ");
sb.Append("Section [" + dicSetLogInfo["SECTION"] + "], ");
sb.Append("St Name [" + dicSetLogInfo["STATION_NAME"] + "], ");
sb.Append("File Name [" + Path.GetFileName(strExtractFilePos) + "], ");
sb.Append("File Extension [" + Path.GetExtension(strExtractFilePos) + "] ");
sb.Append("TL ID[" + dicSetLogInfo["TESTLIST_ID"] + "], ");
sb.Append("V[" + dicSetLogInfo["P_TTNR"] + "], ");
sb.Append("PN[" + dicSetLogInfo["TTNR"] + "], ");
sb.Append("TT[" + dicSetLogInfo["TEST_TYPE"] + "], ");
sb.Append("TC[" + dicSetLogInfo["TEST_CODE"] + "], ");
sb.Append("Ver[" + dicSetLogInfo["VERSION"] + "], ");
sb.Append("PC[" + dicSetLogInfo["PROD_CODE"] + "], ");
sb.Append("DB V No[" + dicSetLogInfo["VARIANT_NO"] + "], ");
if (nDequeueCount >= Int64.MaxValue)
nDequeueCount = 0;
bool bGetLogProcResult = CPXV2_CpLogProcess(EmptyLogMapFile, dicSetLogInfo, strExtractFilePos);
if (bGetLogProcResult == true)
lstBulkTermLogInfo.Add(sb.ToString());
sb.Append("!Use Log Process Version [FTP-CPXV2] ");
if (bGetLogProcResult)
sb.Append("<CpLogProcess Make Log Result [OK]>");
else
sb.Append("<CpLogProcess Make Log Result [NOK]>");
sb.AppendLine();
LogDataProcessText.Enqueue(sb);
l1 = stProcessTimeChk.ElapsedMilliseconds;
if (l1 != long.MinValue)
{
LogDataProcessText.Enqueue(new StringBuilder(">>[FTP-Process][" + l1.ToString() + "]\r\n"));
}
//Failed
if (bGetLogProcResult == false)
{
//실패시
nSetTryNo++;
string strTryNo = string.Empty;
string strCopyPos = string.Empty;
//재시도 3회 초과 일시 히스토리로 이동
if (nSetTryNo > 3)
{
strCopyPos = strMoveDirPath;
strTryNo = "X";
}
else
{
strCopyPos = strReadDirPath;
strTryNo = nSetTryNo.ToString();
}
for (int m = 0; m < 12; m++)
strCopyPos += (";" + strInfos[m + 1]);
strCopyPos += (";" + strTryNo + ";.zip");
File.Copy(f, strCopyPos, true);
}
//압축해제 파일 삭제
if (File.Exists(strExtractFilePos))
File.Delete(strExtractFilePos);
//성공시나 실패시 새로운 파일생성 되기 때문에 기존 파일 삭제
if (strOrgRemoveFilePos != string.Empty)
{
if (File.Exists(strOrgRemoveFilePos))
File.Delete(strOrgRemoveFilePos);
}
stProcessTimeChk.Restart();
}
}
}
}

View File

@ -0,0 +1,166 @@
using DevExpress.Data.Helpers;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Navigation;
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.IO;
using System.Diagnostics;
using SystemX.Net;
using SystemX.Common;
using SystemX.Net.BaseProtocol;
using SystemX.Net.Comm;
using SystemX.Net.Schedule;
using SystemX.Net.DB.LogProcess;
using SystemX.Common.Serialization;
using SystemX.Common.Archive;
using System.Threading.Tasks;
//using SystemX.Common.Protocol.SIA;
using static SystemX.Net.Platform.Common.Util.LogMessage;
using System.Threading;
using SystemX.Net.Platform.Common.Util;
using SystemX.Net.Platform.Common.ExtensionMethods;
using SystemX.Net.Middleware.Log.Commons;
using static SystemX.Net.DB.LogProcess.XLogDBConnManager;
namespace SystemX.Net.MiddlewareUI
{
public partial class MainForm : DevExpress.XtraBars.FluentDesignSystem.FluentDesignForm
{
private void Chktimer_Tick(object sender, EventArgs e)
{
Chktimer.Enabled = false;
if (MiddlewareLogStartState == false)
{
ConsoleUtil.ConsoleVisibleControl();
//The program is automatically terminated.
MessageBox.Show("Server information could not be retrieved. Check the console error text.", "SystemX.Net.Middleware.UI.Log", MessageBoxButtons.OK, MessageBoxIcon.Error);
// TODO : FTP ALIS
this.Close();
}
}
private void UItimer_Tick(object sender, EventArgs e)
{
if (m_bTimerLock[(int)TIMER_LOCK.UI_TIMER] == false)
{
m_bTimerLock[(int)TIMER_LOCK.UI_TIMER] = true;
if (bTryBulkInsertBuffer)
{
if (buttonBulkInsertStart.BackColor != Color.Yellow)
buttonBulkInsertStart.BackColor = Color.Yellow;
}
else
{
if (buttonBulkInsertStart.BackColor != Color.Silver)
buttonBulkInsertStart.BackColor = Color.Silver;
}
labelBulkCntInfo1.Text = nBulkLogCount.ToString();
labelBulkCntInfo2.Text = nBulkShortTermCount.ToString();
labelBulkCntInfo3.Text = nBulkLongTermCount.ToString();
labelBulkTime.Text = nBulkTimeValue.ToString();
labelFTPTime.Text = nFTPTimeValue.ToString();
labelDBMain.Text = "Information [" + MngDBLogConn.GetDBConnectInfo().ConnMain.SCHEMA + "]";
labelDBShortTerm.Text = "ShortTerm [" + MngDBLogConn.GetDBConnectInfo().ConnShortTerm.SCHEMA + "]";
labelShortTermSummaryTableName.Text = "└ [" + MngDBLogConn.GetDBConnectInfo().ConnShortTerm.SUMMARY_TABLE + "]";
labelShortTermLogTableName.Text = "└ [" + MngDBLogConn.GetDBConnectInfo().ConnShortTerm.LOG_TABLE + "]";
labelDBLongTerm.Text = "LongTerm [" + MngDBLogConn.GetDBConnectInfo().ConnLongTerm.SCHEMA + "]";
if (bDatabaseConnResult)
{
if (panelDBMain2.BackColor != Color.LimeGreen) panelDBMain2.BackColor = Color.LimeGreen;
if (panelDBShortTerm2.BackColor != Color.LimeGreen) panelDBShortTerm2.BackColor = Color.LimeGreen;
if (panelDBLongTerm2.BackColor != Color.LimeGreen) panelDBLongTerm2.BackColor = Color.LimeGreen;
if (buttonDbConnect.Visible) buttonDbConnect.Visible = false;
}
else
{
if (panelDBMain2.BackColor != Color.Red) panelDBMain2.BackColor = Color.Red;
if (panelDBShortTerm2.BackColor != Color.Red) panelDBShortTerm2.BackColor = Color.Red;
if (panelDBLongTerm2.BackColor != Color.Red) panelDBLongTerm2.BackColor = Color.Red;
if (buttonDbConnect.Visible == false) buttonDbConnect.Visible = true;
}
if (progressBarProgram.Value + 20 <= 100)
progressBarProgram.Value += 20;
else
progressBarProgram.Value = 0;
int nPanelHeight = panelMain.Height / 2;
panelRecv.Height = nPanelHeight - 20;
panelProcess.Height = nPanelHeight - 20;
int n1 = richTextBoxRecv.Lines.Count();
int n2 = richTextBoxProcess.Lines.Count();
if (richTextBoxRecv.Lines.Count() > 8192)
richTextBoxRecv.Clear();
if (richTextBoxProcess.Lines.Count() > 8192)
richTextBoxProcess.Clear();
if (LogDataRecvText.Count > 0)
{
StringBuilder sb = null;
if (LogDataRecvText.TryDequeue(out sb))
{
//richTextBoxRecv.SuspendLayout();
richTextBoxRecv.AppendText(sb.ToString());
richTextBoxRecv.ScrollToCaret();
//richTextBoxRecv.ResumeLayout();
}
}
if (LogDataProcessText.Count > 0)
{
StringBuilder sb = null;
if (LogDataProcessText.TryDequeue(out sb))
{
//richTextBoxProcess.SuspendLayout();
richTextBoxProcess.AppendText(sb.ToString());
richTextBoxProcess.ScrollToCaret();
//richTextBoxProcess.ResumeLayout();
}
}
m_bTimerLock[(int)TIMER_LOCK.UI_TIMER] = false;
}
}
private string MakeInfoConnectProcessText(int nPos, int nCommandPort, int nStreamPort)
{
string strSetProcessInfo = nPos.ToString("D2") + ":" +
nCommandPort.ToString("D4") + ":" +
nStreamPort.ToString("D4");
return strSetProcessInfo;
}
}
}