[성현모] CPXV2 Init
This commit is contained in:
@ -0,0 +1,36 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해
|
||||
// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면
|
||||
// 이러한 특성 값을 변경하세요.
|
||||
[assembly: AssemblyTitle("SystemX.Net.Platform")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("SystemX.Net.Platform")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2020")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에
|
||||
// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면
|
||||
// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다.
|
||||
[assembly: Guid("9e024203-a0d4-4a08-8041-9d31248b6f7b")]
|
||||
|
||||
// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다.
|
||||
//
|
||||
// 주 버전
|
||||
// 부 버전
|
||||
// 빌드 번호
|
||||
// 수정 버전
|
||||
//
|
||||
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를
|
||||
// 기본값으로 할 수 있습니다.
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
@ -0,0 +1,361 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Common.Serialization;
|
||||
using SystemX.Net.BaseProtocol;
|
||||
using SystemX.Net.Schedule;
|
||||
|
||||
namespace SystemX.Common.Protocol
|
||||
{
|
||||
using static SystemX.Net.Platform.Common.Util.LogMessage;
|
||||
|
||||
public class PacketProgressChangedEventArgs : EventArgs
|
||||
{
|
||||
public PacketProgressChangedEventArgs(int progressPercentage, object userState)
|
||||
{
|
||||
this.ProgressPercentage = progressPercentage;
|
||||
|
||||
this.UserState = userState;
|
||||
}
|
||||
|
||||
public int ProgressPercentage { get; private set; }
|
||||
|
||||
public object UserState { get; private set; }
|
||||
}
|
||||
|
||||
public class PacketAnalyzerCompletedEventArgs : AsyncCompletedEventArgs
|
||||
{
|
||||
private object result;
|
||||
|
||||
public PacketAnalyzerCompletedEventArgs(object result, Exception error, bool cancelled, object userState) : base(error, cancelled, userState)
|
||||
{
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
public object Result
|
||||
{
|
||||
get
|
||||
{
|
||||
base.RaiseExceptionIfNecessary();
|
||||
|
||||
return this.result;
|
||||
}
|
||||
}
|
||||
|
||||
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
|
||||
public new object UserState
|
||||
{
|
||||
get
|
||||
{
|
||||
return base.UserState;
|
||||
}
|
||||
}
|
||||
}
|
||||
public class PacketCalculate
|
||||
{
|
||||
public event EventHandler<PacketAnalyzerCompletedEventArgs> PacketAnalyzerCompleted;
|
||||
public event EventHandler<PacketProgressChangedEventArgs> ProgressChanged;
|
||||
|
||||
/// <summary>
|
||||
/// ThreadContext에서 실행하기 위한 AsyncOperation.
|
||||
/// </summary>
|
||||
private AsyncOperation asyncOperation;
|
||||
|
||||
/// <summary>
|
||||
/// AsyncOperation 로 Completed 호출을 위한 델리게이트.
|
||||
/// </summary>
|
||||
private SendOrPostCallback operationCompleted;
|
||||
|
||||
/// <summary>
|
||||
/// AsyncOperation 로 ProgressChanged 호출을 위한 델리게이트.
|
||||
/// </summary>
|
||||
private SendOrPostCallback progressReporter;
|
||||
|
||||
public bool IsBusy { get; private set; }
|
||||
public bool CancellationPending { get; private set; }
|
||||
|
||||
private readonly Action<object> startDelegate;
|
||||
public bool WorkerReportsProgress { get; set; }
|
||||
|
||||
public bool WorkerSupportsCancellation { get; set; }
|
||||
|
||||
#region CREATE
|
||||
public PacketCalculate()
|
||||
{
|
||||
this.startDelegate = this.WorkerThreadStart;
|
||||
this.operationCompleted = this.SendOperationCompletedEvent;
|
||||
this.progressReporter = this.SendProgressChangedEvent;
|
||||
}
|
||||
#endregion
|
||||
private void SendOperationCompletedEvent(object arg)
|
||||
{
|
||||
this.IsBusy = false;
|
||||
|
||||
this.CancellationPending = false;
|
||||
|
||||
var eventArgs = arg as PacketAnalyzerCompletedEventArgs;
|
||||
|
||||
if (eventArgs == null)
|
||||
return;
|
||||
|
||||
var completed = this.PacketAnalyzerCompleted;
|
||||
|
||||
if (completed != null)
|
||||
completed(this, eventArgs);
|
||||
}
|
||||
private void SendProgressChangedEvent(object arg)
|
||||
{
|
||||
var eventArgs = arg as PacketProgressChangedEventArgs;
|
||||
|
||||
if (eventArgs == null)
|
||||
return;
|
||||
|
||||
var progressChanged = this.ProgressChanged;
|
||||
|
||||
if (progressChanged != null)
|
||||
progressChanged(this, eventArgs);
|
||||
}
|
||||
private void WorkerThreadStart(object argument)
|
||||
{
|
||||
object result = null;
|
||||
|
||||
Exception error = null;
|
||||
|
||||
try
|
||||
{
|
||||
result = this.Calculate(argument, true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = ex;
|
||||
}
|
||||
|
||||
this.asyncOperation.PostOperationCompleted(this.operationCompleted, new PacketAnalyzerCompletedEventArgs(result, error, this.CancellationPending, null));
|
||||
}
|
||||
private void ReportProgress(int percentProgress)
|
||||
{
|
||||
if (!this.WorkerReportsProgress)
|
||||
{
|
||||
//throw new InvalidOperationException("BackgroundWorker_WorkerDoesntReportProgress.[SystemX.Common.AsyncEvent : PacketCalculate.ReportProgress]");
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"BackgroundWorker_WorkerDoesntReportProgress.[SystemX.Common.AsyncEvent : PacketCalculate.ReportProgress]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
var arg = new PacketProgressChangedEventArgs(percentProgress, null);
|
||||
|
||||
if (this.asyncOperation != null)
|
||||
{
|
||||
this.asyncOperation.Post(this.progressReporter, arg);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.progressReporter(arg);
|
||||
}
|
||||
}
|
||||
public void CalculateAsync(object argument)
|
||||
{
|
||||
this.IsBusy = true;
|
||||
|
||||
this.CancellationPending = false;
|
||||
|
||||
this.asyncOperation = AsyncOperationManager.CreateOperation(null);
|
||||
|
||||
this.startDelegate.BeginInvoke(argument, null, null);
|
||||
}
|
||||
|
||||
public void CancelAsync()
|
||||
{
|
||||
if (!this.WorkerSupportsCancellation)
|
||||
{
|
||||
//throw new InvalidOperationException("BackgroundWorker_WorkerDoesntSupportCancellation.[SystemX.Common.AsyncEvent : PacketCalculate.CancelAsync]");
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General packet marshalling failed.[SystemX.Common : COMMON.GetHeaderProtocol]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
this.CancellationPending = true;
|
||||
}
|
||||
public XData Calculate(object objPacket, bool isAsync = false)
|
||||
{
|
||||
XData ResultData = null;
|
||||
|
||||
XPacket getPacket = (XPacket)objPacket;
|
||||
|
||||
int iStoreCnt = getPacket.ucPacketBytes.Count();
|
||||
byte[] recvStoreBuffer = getPacket.ucPacketBytes;
|
||||
|
||||
BASE_PROTOCOL GET_PROTOCOL = new BASE_PROTOCOL();
|
||||
BASE_PROTOCOL.PROTOCOL_CODE GET_CODE = new BASE_PROTOCOL.PROTOCOL_CODE();
|
||||
HEADER_PACKET GET_HEADER = new HEADER_PACKET();
|
||||
|
||||
byte ucSetLabel = getPacket.nLabel;
|
||||
|
||||
bool bReplayResult = true;
|
||||
object objData = null;
|
||||
|
||||
try
|
||||
{
|
||||
GET_PROTOCOL = XCommons.GetHeaderProtocol(iStoreCnt, recvStoreBuffer);
|
||||
GET_HEADER = XCommons.GetHeaderPacket(iStoreCnt, recvStoreBuffer);
|
||||
|
||||
GET_CODE = GET_PROTOCOL.GET_CURRENT_PROTOCOL;
|
||||
|
||||
if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.CONNECT_STATE)
|
||||
{
|
||||
PING_PACKET PacketData = new PING_PACKET();
|
||||
PacketData = XCommons.ByteStreamToSpecialObject<PING_PACKET>(GET_CODE, iStoreCnt, recvStoreBuffer);
|
||||
|
||||
objData = PacketData;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.MIDDLEWARE_MESSAGE)
|
||||
{
|
||||
MESSAGE_PACKET PacketData = new MESSAGE_PACKET();
|
||||
PacketData = XCommons.ByteStreamToSpecialObject<MESSAGE_PACKET>(GET_CODE, iStoreCnt, recvStoreBuffer);
|
||||
|
||||
objData = PacketData;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.HOST_INFO_CHECK)
|
||||
{
|
||||
SYSTEM_HOST_PACKET PacketData = new SYSTEM_HOST_PACKET();
|
||||
PacketData = XCommons.ByteStreamToSpecialObject<SYSTEM_HOST_PACKET>(GET_CODE, iStoreCnt, recvStoreBuffer);
|
||||
|
||||
objData = PacketData;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.SYNC_TIME_SERVER)
|
||||
{
|
||||
TIME_PACKET PacketData = new TIME_PACKET();
|
||||
PacketData = XCommons.ByteStreamToSpecialObject<TIME_PACKET>(GET_CODE, iStoreCnt, recvStoreBuffer);
|
||||
|
||||
objData = PacketData;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.FILE_TRANSFER)
|
||||
{
|
||||
byte[] PacketData = XCommons.ByteStreamToObject<byte[]>(GET_CODE, iStoreCnt, recvStoreBuffer);
|
||||
|
||||
objData = PacketData;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.DATASET_TRANSEFER)
|
||||
{
|
||||
DataSet PacketData = XCommons.ByteStreamToObject<DataSet>(GET_CODE, iStoreCnt, recvStoreBuffer);
|
||||
|
||||
bReplayResult = GET_HEADER.bResponsState;
|
||||
|
||||
objData = PacketData;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.RAW_SIZE)
|
||||
{
|
||||
byte[] PacketData = XCommons.ByteStreamToObject<byte[]>(GET_CODE, iStoreCnt, recvStoreBuffer);
|
||||
|
||||
objData = PacketData;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.INITILALIZE_INFO)
|
||||
{
|
||||
COMM_INFO_PACKET PacketData = new COMM_INFO_PACKET();
|
||||
PacketData = XCommons.ByteStreamToSpecialObject<COMM_INFO_PACKET>(GET_CODE, iStoreCnt, recvStoreBuffer);
|
||||
|
||||
objData = PacketData;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.SYSTEM_QUERY)
|
||||
{
|
||||
QUERY_PACKET PacketData = new QUERY_PACKET();
|
||||
PacketData = XCommons.ByteStreamToSpecialObject<QUERY_PACKET>(GET_CODE, iStoreCnt, recvStoreBuffer);
|
||||
|
||||
objData = PacketData;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.USER_QUERY)
|
||||
{
|
||||
QUERY_PACKET PacketData = new QUERY_PACKET();
|
||||
PacketData = XCommons.ByteStreamToSpecialObject<QUERY_PACKET>(GET_CODE, iStoreCnt, recvStoreBuffer);
|
||||
|
||||
objData = PacketData;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.TRANSFER_RESULT)
|
||||
{
|
||||
TRANSFER_PACKET PacketData = new TRANSFER_PACKET();
|
||||
PacketData = XCommons.ByteStreamToSpecialObject<TRANSFER_PACKET>(GET_CODE, iStoreCnt, recvStoreBuffer);
|
||||
|
||||
objData = PacketData;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.ETC)
|
||||
{
|
||||
USER_PACKET PacketData = new USER_PACKET();
|
||||
PacketData = XCommons.ByteStreamToSpecialObject<USER_PACKET>(GET_CODE, iStoreCnt, recvStoreBuffer);
|
||||
|
||||
objData = PacketData;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.PROCESS_QUERY)
|
||||
{
|
||||
PROCESS_PACKET PacketData = new PROCESS_PACKET();
|
||||
PacketData = XCommons.ByteStreamToSpecialObject<PROCESS_PACKET>(GET_CODE, iStoreCnt, recvStoreBuffer);
|
||||
|
||||
objData = PacketData;
|
||||
}
|
||||
else
|
||||
{
|
||||
GET_PROTOCOL = new BASE_PROTOCOL(BASE_PROTOCOL.PROTOCOL_CODE.NONE);
|
||||
|
||||
bReplayResult = false;
|
||||
|
||||
objData = null;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
GET_PROTOCOL = new BASE_PROTOCOL(BASE_PROTOCOL.PROTOCOL_CODE.NONE);
|
||||
|
||||
bReplayResult = false;
|
||||
|
||||
objData = null;
|
||||
|
||||
string strErrMsg = e.Message;
|
||||
}
|
||||
|
||||
ResultData = new XData();
|
||||
ResultData.dtTime = DateTime.Now;
|
||||
ResultData.bReplayResult = bReplayResult;
|
||||
ResultData.BaseProtocol = GET_PROTOCOL;
|
||||
ResultData.HeaderPacket = GET_HEADER;
|
||||
ResultData.objData = objData;
|
||||
ResultData.nLabel = ucSetLabel;
|
||||
|
||||
return ResultData;
|
||||
}
|
||||
}
|
||||
|
||||
public class EventBaseAsyncPattern
|
||||
{
|
||||
public void Run(int p)
|
||||
{
|
||||
var PacketAnalyzerWait = new PacketCalculate
|
||||
{
|
||||
WorkerReportsProgress = true,
|
||||
|
||||
WorkerSupportsCancellation = true
|
||||
};
|
||||
|
||||
PacketAnalyzerWait.PacketAnalyzerCompleted += calculatorPacket_CalculateCompleted;
|
||||
PacketAnalyzerWait.ProgressChanged += calculatorPacket_ProgressChanged;
|
||||
|
||||
var i = 0;
|
||||
while (i < 5)
|
||||
{
|
||||
if (PacketAnalyzerWait.IsBusy)
|
||||
continue;
|
||||
|
||||
PacketAnalyzerWait.CalculateAsync(p + i);
|
||||
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
void calculatorPacket_ProgressChanged(object sender, PacketProgressChangedEventArgs e)
|
||||
{
|
||||
//"Calculating : {0}% Completed", e.ProgressPercentage;
|
||||
}
|
||||
|
||||
void calculatorPacket_CalculateCompleted(object sender, PacketAnalyzerCompletedEventArgs e)
|
||||
{
|
||||
//e.Result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,91 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Net;
|
||||
using SystemX.Net.BaseProtocol;
|
||||
|
||||
namespace SystemX.Common.Protocol
|
||||
{
|
||||
using ParamElement = Tuple<SqlDbType, int, byte, byte>;
|
||||
|
||||
public static class CommonParamSet
|
||||
{
|
||||
public static Dictionary<string, ParamElement> fParam= new Dictionary<string, ParamElement>();
|
||||
|
||||
public static void TestResultField()
|
||||
{
|
||||
fParam.Clear();
|
||||
fParam = new Dictionary<string, ParamElement>();
|
||||
fParam.Add("No", new ParamElement(SqlDbType.BigInt, 0, 0, 0));
|
||||
fParam.Add("TestDT", new ParamElement(SqlDbType.DateTime2, 7, 0, 0));
|
||||
fParam.Add("LogData", new ParamElement(SqlDbType.NVarChar, -1, 0, 0));
|
||||
}
|
||||
|
||||
|
||||
public static SqlParameter GetMakeSqlParameterInfo(Dictionary<string, ParamElement> refField, string strSetName, object objValue)
|
||||
{
|
||||
if (refField.ContainsKey(strSetName))
|
||||
{
|
||||
SqlParameter param = null;
|
||||
|
||||
if (refField[strSetName].Item2 != 0)
|
||||
param = new SqlParameter("@" + strSetName, refField[strSetName].Item1, refField[strSetName].Item2);
|
||||
else
|
||||
param = new SqlParameter("@" + strSetName, refField[strSetName].Item1);
|
||||
|
||||
if (refField[strSetName].Item1 == SqlDbType.Decimal)
|
||||
{
|
||||
param.Precision = refField[strSetName].Item3;
|
||||
param.Scale = refField[strSetName].Item4;
|
||||
}
|
||||
|
||||
param.Value = objValue;
|
||||
return param;
|
||||
}
|
||||
else
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public class CommonCustomProtocol : BASE_PROTOCOL
|
||||
{
|
||||
public CommonCustomProtocol() : base()
|
||||
{
|
||||
}
|
||||
|
||||
public CommonCustomProtocol(ushort usGetCommnad, ushort usGetSubCommand) : base(usGetCommnad, usGetSubCommand)
|
||||
{
|
||||
}
|
||||
|
||||
public CommonCustomProtocol(PROTOCOL_CODE SET_CODE) : base(SET_CODE)
|
||||
{
|
||||
}
|
||||
|
||||
public SqlCommand LogDataResultInsert(string strTableName, DataRow itemData)
|
||||
{
|
||||
string columns = string.Empty;
|
||||
columns = "No,TestDT,DataLog";
|
||||
|
||||
string values = string.Join(",", columns.Split(',').Select(c => string.Format("@{0}", c)));
|
||||
string sqlCommand = string.Format("INSERT INTO [" + strTableName + "] ({0}) VALUES ({1})", columns, values);
|
||||
|
||||
CommonParamSet.TestResultField();
|
||||
|
||||
SqlCommand cmd = new SqlCommand(sqlCommand);
|
||||
|
||||
SqlParameter[] setParams = new SqlParameter[columns.Split(',').Count()];
|
||||
|
||||
setParams[0] = CommonParamSet.GetMakeSqlParameterInfo(CommonParamSet.fParam, "No", itemData["No"]);
|
||||
setParams[1] = CommonParamSet.GetMakeSqlParameterInfo(CommonParamSet.fParam, "TestDT", itemData["TestDT"]);
|
||||
setParams[2] = CommonParamSet.GetMakeSqlParameterInfo(CommonParamSet.fParam, "LogData", itemData["LogData"]);
|
||||
|
||||
cmd.Parameters.AddRange(setParams);
|
||||
|
||||
return cmd;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,593 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Net;
|
||||
using SystemX.Net.BaseProtocol;
|
||||
|
||||
namespace SystemX.Common.Protocol.LSU
|
||||
{
|
||||
public class CustomProtocol_ : BASE_PROTOCOL
|
||||
{
|
||||
public CustomProtocol_() : base()
|
||||
{
|
||||
}
|
||||
public CustomProtocol_(ushort usGetCommnad, ushort usGetSubCommand) : base(usGetCommnad, usGetSubCommand)
|
||||
{
|
||||
}
|
||||
public CustomProtocol_(PROTOCOL_CODE SET_CODE) : base(SET_CODE)
|
||||
{
|
||||
}
|
||||
//REF
|
||||
public string QueryRefModelList()
|
||||
{
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
strQueryInfo = "SELECT * FROM REFS_Model ORDER BY No";
|
||||
|
||||
return strQueryInfo;
|
||||
}
|
||||
public string QueryRefModelAllInfo(string strSensorID)
|
||||
{
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
//INNER JOIN REFS_Model C ON C.RefSnrsID = A.RefSnrsID
|
||||
strQueryInfo = "SELECT B.Model_Type, B.RefSnrsID, B.Name, B.Status, " +
|
||||
"A.Pressure, A.ZeroPoint, A.SetPointPM, A.SetPointFT, A.MRG1, A.MRG3, A.MRG4, A.MRG5, A.SFG20, A.SFG45, A.RI, " +
|
||||
"X.CountWarning, X.CountLimit " +
|
||||
"FROM REFS_Model AS B, REFS_UsagePlan AS X, REFS_ModelChar AS A " +
|
||||
"WHERE B.RefSnrsID = '" + strSensorID + "' AND B.RefSnrsID = A.RefSnrsID AND A.RefSnrsID = X.RefSnrsID;";
|
||||
|
||||
|
||||
return strQueryInfo;
|
||||
}
|
||||
public string QueryRefModelPlanInfo(string strSensorID)
|
||||
{
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
strQueryInfo = "SELECT A.Model_Type, A.RefSnrsID, A.Name, A.Status, " +
|
||||
"X.CountWarning, X.CountLimit " +
|
||||
"FROM REFS_Model AS A, REFS_UsagePlan AS X " +
|
||||
"WHERE A.RefSnrsID = '" + strSensorID + "' AND A.RefSnrsID = X.RefSnrsID;";
|
||||
|
||||
|
||||
return strQueryInfo;
|
||||
}
|
||||
public string QueryRefModelGetCnt(string strSensroID, string strUsageID)
|
||||
{
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
strQueryInfo = "SELECT A.RefSnrsID, A.UsagePlaceID, A.LastUpdateDT, A.Count, A.AccumulateCount " +
|
||||
"FROM REFS_UsageHistory AS A " +
|
||||
"INNER JOIN(SELECT MAX(B.LastUpdateDT) AS LAST_DATE, B.RefSnrsID AS ID, B.UsagePlaceID AS UPI " +
|
||||
"FROM REFS_UsageHistory AS B WHERE B.RefSnrsID = '" + strSensroID + "' AND B.UsagePlaceID = '" + strUsageID + "' GROUP BY B.RefSnrsID, B.UsagePlaceID) AS SUB " +
|
||||
"ON SUB.LAST_DATE = A.LastUpdateDT " +
|
||||
"AND A.RefSnrsID = SUB.ID " +
|
||||
"AND A.UsagePlaceID = SUB.UPI;";
|
||||
|
||||
return strQueryInfo;
|
||||
}
|
||||
public string QueryRefModelSetCnt(string strSensroID, string strUsageID)
|
||||
{
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
strQueryInfo = "UPDATE A SET A.Count = A.Count + 1, A.AccumulateCount = A.AccumulateCount + 1, A.LastUpdateDT = GETDATE() " +
|
||||
"FROM REFS_UsageHistory A " +
|
||||
"JOIN(SELECT MAX(B.LastUpdateDT) AS LAST_DATE, B.RefSnrsID AS ID, B.UsagePlaceID AS UPI " +
|
||||
"FROM REFS_UsageHistory AS B WHERE B.RefSnrsID = '" + strSensroID + "' AND B.UsagePlaceID = '" + strUsageID + "' GROUP BY B.RefSnrsID, B.UsagePlaceID) AS SUB " +
|
||||
"ON SUB.LAST_DATE = A.LastUpdateDT " +
|
||||
"AND A.RefSnrsID = SUB.ID " +
|
||||
"AND A.UsagePlaceID = SUB.UPI;";
|
||||
|
||||
return strQueryInfo;
|
||||
}
|
||||
public string QueryRefModelChangeKnowNewPlace(string strSensroID, string strUsageID, string strNewUsageID)
|
||||
{
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
strQueryInfo = "INSERT INTO REFS_UsageHistory (RefSnrsID, UsagePlaceID, Count, AccumulateCount, Description) " +
|
||||
"SELECT RefSnrsID, '" + strNewUsageID + "', '0', AccumulateCount, Description FROM REFS_UsageHistory AS A " +
|
||||
"INNER JOIN(SELECT MAX(B.LastUpdateDT) AS LAST_DATE, B.RefSnrsID AS ID, B.UsagePlaceID AS UPI " +
|
||||
"FROM REFS_UsageHistory AS B WHERE B.RefSnrsID = '" + strSensroID + "' AND B.UsagePlaceID = '" + strUsageID + "' GROUP BY B.RefSnrsID, B.UsagePlaceID) AS SUB " +
|
||||
"ON SUB.LAST_DATE = A.LastUpdateDT " +
|
||||
"AND A.RefSnrsID = SUB.ID " +
|
||||
"AND A.UsagePlaceID = SUB.UPI;";
|
||||
|
||||
return strQueryInfo;
|
||||
}
|
||||
public string QueryRefModelChange(string strSensroID, string strNewUsageID)
|
||||
{
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
strQueryInfo = "INSERT INTO REFS_UsageHistory(RefSnrsID, UsagePlaceID, Count, AccumulateCount, Description) " +
|
||||
"SELECT A.RefSnrsID, '" + strNewUsageID + "', '0', A.AccumulateCount, A.Description FROM REFS_UsageHistory AS A " +
|
||||
"INNER JOIN(SELECT * FROM REFS_UsageHistory WHERE " +
|
||||
"LastUpdateDT = (SELECT MAX(LastUpdateDT) FROM REFS_UsageHistory B WHERE B.RefSnrsID = '" + strSensroID + "' " +
|
||||
"GROUP BY B.RefSnrsID)) AS SUB " +
|
||||
"ON SUB.LastUpdateDT = A.LastUpdateDT " +
|
||||
"AND A.RefSnrsID = SUB.RefSnrsID " +
|
||||
"AND A.UsagePlaceID = SUB.UsagePlaceID;";
|
||||
|
||||
return strQueryInfo;
|
||||
}
|
||||
public string QueryRefModelRegister(string strSensroID, string strUsageID)
|
||||
{
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
strQueryInfo = "IF EXISTS(SELECT RefSnrsID FROM [REFS_Model] AS B WHERE B.RefSnrsID = '" + strSensroID + "') " +
|
||||
"BEGIN " +
|
||||
"IF NOT EXISTS(SELECT RefSnrsID FROM REFS_UsageHistory AS A WHERE A.RefSnrsID = '" + strSensroID + "') " +
|
||||
"BEGIN " +
|
||||
"INSERT INTO REFS_UsageHistory (RefSnrsID, UsagePlaceID, Count, AccumulateCount, Description) VALUES('" + strSensroID + "', '" + strUsageID + "', 0, 0, '-'); " +
|
||||
"END " +
|
||||
"END;";
|
||||
|
||||
return strQueryInfo;
|
||||
}
|
||||
public string QueryRefModelLastSensorAtPlaceID(string strUsageID)
|
||||
{
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
strQueryInfo = "SELECT * FROM[REFS_UsageHistory] A " +
|
||||
"WHERE LastUpdateDT = (SELECT MAX(LastUpdateDT) " +
|
||||
"FROM[REFS_UsageHistory] B " +
|
||||
"WHERE B.UsagePlaceID = '" + strUsageID + "' " +
|
||||
"GROUP BY B.UsagePlaceID);";
|
||||
|
||||
return strQueryInfo;
|
||||
}
|
||||
/*
|
||||
*
|
||||
*/
|
||||
/*
|
||||
public string QueryMakeModeInfo(PROCESS_PACKET getPaket)
|
||||
{
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
strQueryInfo = "SELECT ModeID FROM [CONST_WorkMode] WHERE PalletNumber = '" + getPaket.objPalletNumber[0].Data + "';";
|
||||
|
||||
return strQueryInfo;
|
||||
}
|
||||
public string QueryFindTrimmingImage(int iProcNum, PROCESS_PACKET getPaket)
|
||||
{
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
int iSetType = 0;
|
||||
|
||||
if (getPaket.objPalletID[0].Data.IndexOf("-") >= 0)
|
||||
iSetType = 1;
|
||||
if (getPaket.objPalletNumber[0].Data.IndexOf("-") >= 0)
|
||||
iSetType = 2;
|
||||
|
||||
//Normal
|
||||
strQueryInfo = "SELECT TOP 1 No, LogData, UpdateDT FROM [HIST_TestResultData_" + iProcNum.ToString() + "] WHERE No " +
|
||||
"IN(SELECT No FROM [HIST_TestResultData_" + iProcNum.ToString() + "] WHERE " +
|
||||
"PalletNumber = '" + getPaket.objPalletNumber[0].Data + "' " +
|
||||
"AND PalletID = '" + getPaket.objPalletID[0].Data + "' " +
|
||||
"AND ProdID = '" + getPaket.objProductID[0].Data + "' " +
|
||||
"AND TestID = 'LTV' " +
|
||||
"AND Status = 50) " +
|
||||
"ORDER BY No DESC;";
|
||||
|
||||
if(iSetType == 1)
|
||||
{
|
||||
strQueryInfo = "SELECT TOP 1 No, LogData, UpdateDT FROM [HIST_TestResultData_" + iProcNum.ToString() + "] WHERE No " +
|
||||
"IN(SELECT No FROM [HIST_TestResultData_" + iProcNum.ToString() + "] WHERE " +
|
||||
"PalletNumber = '" + getPaket.objPalletNumber[0].Data + "' " +
|
||||
"AND ProdID = '" + getPaket.objProductID[0].Data + "' " +
|
||||
"AND TestID = 'LTV' " +
|
||||
"AND Status = 50) " +
|
||||
"ORDER BY No DESC;";
|
||||
}
|
||||
else if (iSetType == 2)
|
||||
{
|
||||
strQueryInfo = "SELECT TOP 1 No, LogData, UpdateDT FROM [HIST_TestResultData_" + iProcNum.ToString() + "] WHERE No " +
|
||||
"IN(SELECT No FROM [HIST_TestResultData_" + iProcNum.ToString() + "] WHERE " +
|
||||
"ProdID = '" + getPaket.objProductID[0].Data + "' " +
|
||||
"AND TestID = 'LTV' " +
|
||||
"AND Status = 50) " +
|
||||
"ORDER BY No DESC;";
|
||||
}
|
||||
|
||||
|
||||
return strQueryInfo;
|
||||
}
|
||||
public string QueryMakePalletInfo(PROCESS_PACKET getPaket)
|
||||
{
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
//Unused Pallet Position
|
||||
if (getPaket.objProductID[0].Data.Length == 0)
|
||||
strQueryInfo = "SELECT * FROM STAT_ProdLoad A WHERE A.PalletNumber = '" + getPaket.objPalletNumber[0].Data + "' ORDER BY A.No;";
|
||||
else
|
||||
strQueryInfo = "SELECT * FROM STAT_ProdLoad A WHERE A.PalletNumber = '" + getPaket.objPalletNumber[0].Data +
|
||||
"' AND A.ProdID = '" + getPaket.objProductID[0].Data + "' ORDER BY A.No;";
|
||||
|
||||
return strQueryInfo;
|
||||
}
|
||||
*/
|
||||
public string QueryMakePalletInfo(string strPalletNumber, string strProductID = "")
|
||||
{
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
//Unused Pallet Position
|
||||
if (strProductID.Length == 0)
|
||||
strQueryInfo = "SELECT * FROM STAT_ProdLoad A WHERE A.PalletNumber = '" + strPalletNumber + "' ORDER BY A.No;";
|
||||
else
|
||||
strQueryInfo = "SELECT * FROM STAT_ProdLoad A WHERE A.PalletNumber = '" + strPalletNumber +
|
||||
"' AND A.ProdID = '" + strProductID + "' ORDER BY A.No;";
|
||||
|
||||
return strQueryInfo;
|
||||
}
|
||||
public string QueryMakeModelInfo(int iPos, ServerInfo getServerInfo, XTableInfo getSchemaTableInfo, string strProdNo)
|
||||
{
|
||||
//int iGetProcessCode = getServerInfo.ConnectInfo[iPos].Item4;
|
||||
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
/*IEnumerable<InfoProcess> queryFindProcessInfo =
|
||||
from Process in getServerInfo.ProcessInfo
|
||||
where Process.nNum == (iPos + 1)
|
||||
select Process;
|
||||
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
foreach (InfoProcess fpi in queryFindProcessInfo)
|
||||
{
|
||||
//Find Process Info
|
||||
|
||||
//기본 Child 및 Parent Model info Inner join Query 문 생성
|
||||
if (fpi.bParameterInfoUse == false)
|
||||
{
|
||||
strQueryInfo = "SELECT B.Model_Type, A.PrtProdNo, A.Plug_Type AS 'C Plug Type', B.Plug_Type AS 'P Plug Type', A.ProdNo, A.Name AS 'C Name', A.CableLength, A.FillPrs_Target, A.FillPrs_USpec, A.FillPrs_LSpec," +
|
||||
"B.Name AS 'P Name', B.RegulationType, B.ProtTubeType, B.RiSetPoint" +
|
||||
//
|
||||
" FROM PROD_ModelParent AS B, " +
|
||||
//
|
||||
"PROD_ModelChild AS A INNER JOIN PROD_ModelParent C ON C.PrtProdNo = A.PrtProdNo" +
|
||||
" WHERE A.ProdNo = '" + strProdNo + "' AND B.PrtProdNo = A.PrtProdNo;";
|
||||
}
|
||||
else
|
||||
{
|
||||
strQueryInfo = "SELECT B.Model_Type, A.PrtProdNo, A.Plug_Type AS 'C Plug Type', B.Plug_Type AS 'P Plug Type', A.ProdNo, A.Name AS 'C Name', A.CableLength, A.FillPrs_Target, A.FillPrs_USpec, A.FillPrs_LSpec," +
|
||||
"B.Name AS 'P Name', B.RegulationType, B.ProtTubeType, B.RiSetPoint,";
|
||||
|
||||
string[] strParameterTableList = null;
|
||||
strParameterTableList = fpi.strParameterInfoTableName.Split(',');
|
||||
|
||||
if (strParameterTableList.Count() > 3)
|
||||
return "ERROR - Parameter table use max 3.";
|
||||
|
||||
string[] strSubAs = new string[3] { "X", "Y", "Z" };
|
||||
string[] strSubTable = new string[3] { "", "", "" };
|
||||
|
||||
int iSet = 0;
|
||||
foreach (string strName in strParameterTableList)
|
||||
{
|
||||
int iTp = Array.FindIndex<XTable>(getSchemaTableInfo._table.ToArray(), x => x.tableName == strName);
|
||||
XTable xt = getSchemaTableInfo._table[iTp];
|
||||
|
||||
string[] strAddModelInfo = new string[xt.lstName.Count];
|
||||
for (int i = 0; i < xt.lstName.Count; i++)
|
||||
{
|
||||
strAddModelInfo[i] = string.Empty;
|
||||
strAddModelInfo[i] = @" " + strSubAs[iSet] + "." + xt.lstName[i] + " AS '" + strName + " " + xt.lstName[i] + "',";
|
||||
//'SUB" + (iSet+1).ToString() + " " + xt.lstName[i] + "',";
|
||||
|
||||
if (xt.lstName[i].CompareTo("No") == 0)
|
||||
continue;
|
||||
else if (xt.lstName[i].CompareTo("UpdateDT") == 0)
|
||||
continue;
|
||||
else if (xt.lstName[i].CompareTo("Revision") == 0)
|
||||
continue;
|
||||
else if (xt.lstName[i].CompareTo("Description") == 0)
|
||||
continue;
|
||||
|
||||
strQueryInfo += strAddModelInfo[i];
|
||||
}
|
||||
|
||||
strSubTable[iSet] = strName + " AS " + strSubAs[iSet] + ",";
|
||||
|
||||
iSet++;
|
||||
}
|
||||
|
||||
strQueryInfo = strQueryInfo.Remove(strQueryInfo.Length - 1, 1);
|
||||
|
||||
strQueryInfo +=
|
||||
" FROM ";
|
||||
|
||||
foreach (string strSubT in strSubTable)
|
||||
{
|
||||
if (strSubT.Length > 0)
|
||||
strQueryInfo += strSubT;
|
||||
}
|
||||
|
||||
strQueryInfo +=
|
||||
" PROD_ModelParent AS B, " +
|
||||
"PROD_ModelChild AS A INNER JOIN PROD_ModelParent C ON C.PrtProdNo = A.PrtProdNo" +
|
||||
" WHERE A.ProdNo = '" + strProdNo + "' AND B.PrtProdNo = A.PrtProdNo ";
|
||||
|
||||
iSet = 0;
|
||||
foreach (string strSubT in strSubTable)
|
||||
{
|
||||
if (strSubT.Length > 0)
|
||||
strQueryInfo += "AND B.PrtProdNo = " + strSubAs[iSet] + ".PrtProdNo ";
|
||||
|
||||
iSet++;
|
||||
}
|
||||
|
||||
strQueryInfo += ";";
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
*/
|
||||
|
||||
return strQueryInfo;
|
||||
}
|
||||
|
||||
public string[] GetProcessPPITableList(int iPos, ServerInfo getServerInfo, XTableInfo getSchemaTableInfo)
|
||||
{
|
||||
//int iGetProcessCode = getServerInfo.ConnectInfo[iPos].Item4;
|
||||
|
||||
string[] strPPITableList = null;
|
||||
|
||||
/*IEnumerable<InfoProcess> queryFindProcessInfo =
|
||||
from Process in getServerInfo.ProcessInfo
|
||||
where Process.nNum == (iPos + 1)
|
||||
select Process;
|
||||
|
||||
foreach (InfoProcess fpi in queryFindProcessInfo)
|
||||
{
|
||||
//Find Process Info
|
||||
strPPITableList = fpi.strPreviousProcessInquiryTableName.Split(',');
|
||||
|
||||
break;
|
||||
}*/
|
||||
|
||||
return strPPITableList;
|
||||
}
|
||||
|
||||
public SqlCommand[] InsertLogData(
|
||||
ref string strOutLogKey,
|
||||
string strSetAddLogKey,
|
||||
Int64 SetNumber,
|
||||
|
||||
string strTestID,
|
||||
int iProcNum,
|
||||
DataSet dsPalletInfo,
|
||||
|
||||
string strFilePath,
|
||||
byte[] ucDataArray,
|
||||
|
||||
ushort usPalletIndex = ushort.MaxValue,
|
||||
string strSetPalletNumber = "",
|
||||
string strSetPalletID = "",
|
||||
string strSetPIndex = "",
|
||||
string strSeProdNo = "",
|
||||
string strSetProdID = "",
|
||||
|
||||
int iSetStatus = 0)
|
||||
{
|
||||
SqlCommand[] cmd = new SqlCommand[2];
|
||||
|
||||
strOutLogKey = string.Empty;
|
||||
strOutLogKey = "";
|
||||
|
||||
string strNullPath = "NULL";
|
||||
byte[] ucNullByte = new byte[1];
|
||||
ucNullByte[0] = 0x01;
|
||||
|
||||
if (dsPalletInfo != null)
|
||||
{
|
||||
bool hasRows = dsPalletInfo.Tables.Cast<DataTable>().Any(table => table.Rows.Count != 0);
|
||||
|
||||
if (hasRows)
|
||||
{
|
||||
string strPalletNumber = string.Empty;
|
||||
string strPalletID = string.Empty;
|
||||
|
||||
string strPIndex = string.Empty;
|
||||
string strProdNo = string.Empty;
|
||||
string strProdID = string.Empty;
|
||||
|
||||
if (usPalletIndex == ushort.MaxValue)
|
||||
{
|
||||
strPalletNumber = strSetPalletNumber;
|
||||
strPalletID = strSetPalletID;
|
||||
|
||||
strPIndex = strSetPIndex;
|
||||
strProdNo = strSeProdNo;
|
||||
strProdID = strSetProdID;
|
||||
}
|
||||
else
|
||||
{
|
||||
int iAccessPos = 0;
|
||||
|
||||
if (usPalletIndex != ushort.MaxValue)
|
||||
iAccessPos = usPalletIndex - 1;
|
||||
|
||||
strPalletNumber = dsPalletInfo.Tables[0].Rows[iAccessPos]["PalletNumber"].ToString();
|
||||
strPalletID = dsPalletInfo.Tables[0].Rows[iAccessPos]["PalletID"].ToString();
|
||||
|
||||
strPIndex = dsPalletInfo.Tables[0].Rows[iAccessPos]["PIndex"].ToString();
|
||||
strProdNo = dsPalletInfo.Tables[0].Rows[iAccessPos]["ProdNo"].ToString();
|
||||
strProdID = dsPalletInfo.Tables[0].Rows[iAccessPos]["ProdID"].ToString();
|
||||
}
|
||||
|
||||
strPalletNumber = strPalletNumber.Trim();
|
||||
strPalletID = strPalletID.Trim();
|
||||
|
||||
strPIndex = strPIndex.Trim();
|
||||
strProdNo = strProdNo.Trim();
|
||||
strProdID = strProdID.Trim();
|
||||
|
||||
cmd[0] = new SqlCommand("INSERT INTO HIST_TestResultData_" + iProcNum.ToString() + " (LogAccessKey, ProcNo, PalletNumber, PalletID, PIndex, ProdNo, ProdID, TestID, LogDataPath, LogData, Status) VALUES (@LogAccessKey, @ProcNo, @PalletNumber, @PalletID, @PIndex, @ProdNo, @ProdID, @TestID, @LogDataPath, @LogData, @Status)");
|
||||
cmd[1] = new SqlCommand("INSERT INTO HIST_TestResultData (LogAccessKey, ProcNo, PalletNumber, PalletID, PIndex, ProdNo, ProdID, TestID, LogDataPath, LogData, Status) VALUES (@LogAccessKey, @ProcNo, @PalletNumber, @PalletID, @PIndex, @ProdNo, @ProdID, @TestID, @LogDataPath, @LogData, @Status)");
|
||||
|
||||
if (strSetAddLogKey.Length == 0)
|
||||
strOutLogKey = SetNumber.ToString() + "-" + iProcNum.ToString();
|
||||
else
|
||||
strOutLogKey = SetNumber.ToString() + "-" + iProcNum.ToString() + "-" + strSetAddLogKey;
|
||||
|
||||
SqlParameter param0 = new SqlParameter("@LogAccessKey", SqlDbType.NVarChar, 64);
|
||||
param0.Value = strOutLogKey;
|
||||
cmd[0].Parameters.Add(param0);
|
||||
|
||||
/*
|
||||
* ProcNo : 공정 코드 180 ~ 290
|
||||
*/
|
||||
param0 = new SqlParameter("@ProcNo", SqlDbType.BigInt);
|
||||
param0.Value = iProcNum;
|
||||
cmd[0].Parameters.Add(param0);
|
||||
|
||||
param0 = new SqlParameter("@PalletNumber", SqlDbType.NVarChar, 20);
|
||||
param0.Value = strPalletNumber;
|
||||
cmd[0].Parameters.Add(param0);
|
||||
|
||||
param0 = new SqlParameter("@PalletID", SqlDbType.NVarChar, 30);
|
||||
param0.Value = strPalletID;
|
||||
cmd[0].Parameters.Add(param0);
|
||||
|
||||
param0 = new SqlParameter("@PIndex", SqlDbType.TinyInt);
|
||||
param0.Value = Convert.ToByte(strPIndex);
|
||||
cmd[0].Parameters.Add(param0);
|
||||
|
||||
param0 = new SqlParameter("@ProdNo", SqlDbType.NVarChar, 30);
|
||||
param0.Value = strProdNo;
|
||||
cmd[0].Parameters.Add(param0);
|
||||
|
||||
param0 = new SqlParameter("@ProdID", SqlDbType.NVarChar, 50);
|
||||
param0.Value = strProdID;
|
||||
cmd[0].Parameters.Add(param0);
|
||||
|
||||
/*
|
||||
* TestID 공정 위치별 ID
|
||||
*/
|
||||
param0 = new SqlParameter("@TestID", SqlDbType.NVarChar, 20);
|
||||
param0.Value = strTestID;
|
||||
cmd[0].Parameters.Add(param0);
|
||||
|
||||
param0 = new SqlParameter("@LogDataPath", SqlDbType.NVarChar, 256);
|
||||
param0.Value = strFilePath;
|
||||
cmd[0].Parameters.Add(param0);
|
||||
|
||||
param0 = new SqlParameter("@LogData", SqlDbType.VarBinary, -1);
|
||||
param0.Value = ucDataArray; // byte[]로 지정함
|
||||
cmd[0].Parameters.Add(param0);
|
||||
|
||||
param0 = new SqlParameter("@Status", SqlDbType.TinyInt);
|
||||
param0.Value = iSetStatus;
|
||||
cmd[0].Parameters.Add(param0);
|
||||
//
|
||||
//
|
||||
SqlParameter param1 = new SqlParameter("@LogAccessKey", SqlDbType.NVarChar, 64);
|
||||
param1.Value = strOutLogKey;
|
||||
cmd[1].Parameters.Add(param1);
|
||||
|
||||
/*
|
||||
* ProcNo : 공정 코드 180 ~ 290
|
||||
*/
|
||||
param1 = new SqlParameter("@ProcNo", SqlDbType.BigInt);
|
||||
param1.Value = iProcNum;
|
||||
cmd[1].Parameters.Add(param1);
|
||||
|
||||
param1 = new SqlParameter("@PalletNumber", SqlDbType.NChar, 20);
|
||||
param1.Value = strPalletNumber;
|
||||
cmd[1].Parameters.Add(param1);
|
||||
|
||||
param1 = new SqlParameter("@PalletID", SqlDbType.NChar, 30);
|
||||
param1.Value = strPalletID;
|
||||
cmd[1].Parameters.Add(param1);
|
||||
|
||||
param1 = new SqlParameter("@PIndex", SqlDbType.TinyInt);
|
||||
param1.Value = Convert.ToByte(strPIndex);
|
||||
cmd[1].Parameters.Add(param1);
|
||||
|
||||
param1 = new SqlParameter("@ProdNo", SqlDbType.NChar, 30);
|
||||
param1.Value = strProdNo;
|
||||
cmd[1].Parameters.Add(param1);
|
||||
|
||||
param1 = new SqlParameter("@ProdID", SqlDbType.NChar, 50);
|
||||
param1.Value = strProdID;
|
||||
cmd[1].Parameters.Add(param1);
|
||||
|
||||
/*
|
||||
* TestID 공정 위치별 ID
|
||||
*/
|
||||
param1 = new SqlParameter("@TestID", SqlDbType.NChar, 20);
|
||||
param1.Value = strTestID;
|
||||
cmd[1].Parameters.Add(param1);
|
||||
|
||||
param1 = new SqlParameter("@LogDataPath", SqlDbType.NVarChar, 256);
|
||||
param1.Value = strNullPath;
|
||||
cmd[1].Parameters.Add(param1);
|
||||
|
||||
param1 = new SqlParameter("@LogData", SqlDbType.VarBinary, -1);
|
||||
param1.Value = ucNullByte; // byte[]로 지정함
|
||||
cmd[1].Parameters.Add(param1);
|
||||
|
||||
param1 = new SqlParameter("@Status", SqlDbType.TinyInt);
|
||||
param1.Value = iSetStatus;
|
||||
cmd[1].Parameters.Add(param1);
|
||||
}
|
||||
}
|
||||
|
||||
return cmd;
|
||||
}
|
||||
public string QueryMakePPIInfo(string strTableName, string strProdNo, string strPalletID)
|
||||
{
|
||||
string strQueryInfo = string.Empty;
|
||||
|
||||
//오늘 부터 10일 이내 데이터만 필요시
|
||||
strQueryInfo = "SELECT A.PalletID, A.PIndex, A.ProdID, A.Result AS RESULT, A.UpdateDT " +
|
||||
"FROM " + strTableName + " AS A " +
|
||||
"INNER JOIN" +
|
||||
"(" +
|
||||
"SELECT MAX(UpdateDT) AS LAST_DATE, B.ProdID " +
|
||||
"FROM " + strTableName + " AS B WHERE ProdID = '" + strProdNo + "' " +
|
||||
"GROUP BY ProdID" +
|
||||
") AS SUB " +
|
||||
"ON A.UpdateDT = SUB.LAST_DATE " +
|
||||
//"AND SUB.LAST_DATE BETWEEN CONVERT(VARCHAR, GETDATE() - 10, 112) AND CONVERT(VARCHAR, GETDATE(), 112) " +
|
||||
"AND A.ProdID = SUB.ProdID " +
|
||||
"AND A.PalletID = '" + strPalletID + "';";
|
||||
/*
|
||||
if (strPalletID.Length > 0 && iPalletIndex > 0)
|
||||
{
|
||||
strQueryInfo = "SELECT A.PalletID, A.PIndex, A.ProdID, A.Result AS RESULT, A.UpdateDT " +
|
||||
"FROM " + strTableName + " AS A " +
|
||||
"INNER JOIN" +
|
||||
"(" +
|
||||
"SELECT MAX(UpdateDT) AS LAST_DATE, B.ProdID " +
|
||||
"FROM " + strTableName + " AS B WHERE ProdID = '" + strProdNo + "' " +
|
||||
"GROUP BY ProdID" +
|
||||
") AS SUB " +
|
||||
"ON A.UpdateDT = SUB.LAST_DATE " +
|
||||
"AND SUB.LAST_DATE BETWEEN CONVERT(VARCHAR, GETDATE() - 15, 112) AND CONVERT(VARCHAR, GETDATE(), 112) " +
|
||||
"AND A.ProdID = SUB.ProdID " +
|
||||
"AND A.PalletID = '" + strPalletID + "';";
|
||||
}
|
||||
else
|
||||
{
|
||||
strQueryInfo = "SELECT A.PalletID, A.PIndex, A.ProdID, A.Result AS RESULT, A.UpdateDT " +
|
||||
"FROM " + strTableName + " AS A " +
|
||||
"INNER JOIN" +
|
||||
"(" +
|
||||
"SELECT MAX(UpdateDT) AS LAST_DATE, B.ProdID " +
|
||||
"FROM " + strTableName + " AS B WHERE ProdID = '" + strProdNo + "' " +
|
||||
"GROUP BY ProdID" +
|
||||
") AS SUB " +
|
||||
"ON A.UpdateDT = SUB.LAST_DATE " +
|
||||
"AND SUB.LAST_DATE BETWEEN CONVERT(VARCHAR, GETDATE() - 15, 112) AND CONVERT(VARCHAR, GETDATE(), 112) " +
|
||||
"AND A.ProdID = SUB.ProdID";
|
||||
}
|
||||
*/
|
||||
|
||||
return strQueryInfo;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,660 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Net;
|
||||
using SystemX.Net.BaseProtocol;
|
||||
|
||||
namespace SystemX.Common.Protocol.SIA
|
||||
{
|
||||
using ParamElement = Tuple<SqlDbType, int, byte, byte>;
|
||||
|
||||
public class HISTTesterSummary
|
||||
{
|
||||
public string StationName { set; get; }
|
||||
public string TestType { set; get; }
|
||||
public string Version { set; get; }
|
||||
public string ProdCode { set; get; }
|
||||
public int TestListFileNo { set; get; }
|
||||
public int TestListVariantNo { set; get; }
|
||||
public string TestListCntID { set; get; }
|
||||
|
||||
public int StepVersion { set; get; }
|
||||
public string Host { set; get; }
|
||||
public string Section { set; get; }
|
||||
public string ProdNoC { set; get; }
|
||||
public string ProdNoP { set; get; }
|
||||
public string TestCode { set; get; }
|
||||
public string TestListFileName { set; get; }
|
||||
public string ProductID { set; get; }
|
||||
public string Result { set; get; }
|
||||
public string Duration { set; get; }
|
||||
public DateTime TestDT { set; get; }
|
||||
}
|
||||
|
||||
public class HISTLogSummary
|
||||
{
|
||||
public Int64 AccessStart { set; get; }
|
||||
public Int64 AccessEnd { set; get; }
|
||||
public Int64 LogNo { set; get; }
|
||||
public int LogCount { set; get; }
|
||||
public string StationName { set; get; }
|
||||
public string TestType { set; get; }
|
||||
public string Version { set; get; }
|
||||
public string ProdCode { set; get; }
|
||||
public int TestListFileNo { set; get; }
|
||||
public int TestListVariantNo { set; get; }
|
||||
public string TestListCntID { set; get; }
|
||||
|
||||
public int StepVersion { set; get; }
|
||||
public string Host { set; get; }
|
||||
public string Section { set; get; }
|
||||
public string ProdNoC { set; get; }
|
||||
public string ProdNoP { set; get; }
|
||||
public string TestCode { set; get; }
|
||||
public string TestListFileName { set; get; }
|
||||
public string ProductID { set; get; }
|
||||
public string Result { set; get; }
|
||||
public string Duration { set; get; }
|
||||
public DateTime TestDT { set; get; }
|
||||
}
|
||||
|
||||
public static class ParamSet
|
||||
{
|
||||
public static Dictionary<string, ParamElement> fParam= new Dictionary<string, ParamElement>();
|
||||
|
||||
public static void TesterSummaryField()
|
||||
{
|
||||
fParam.Clear();
|
||||
fParam = new Dictionary<string, ParamElement>();
|
||||
fParam.Add("StationName", new ParamElement(SqlDbType.NVarChar, 128, 0, 0));
|
||||
fParam.Add("TestType", new ParamElement(SqlDbType.NVarChar, 8, 0, 0));
|
||||
fParam.Add("Version", new ParamElement(SqlDbType.NVarChar, 4, 0, 0));
|
||||
fParam.Add("ProdCode", new ParamElement(SqlDbType.NVarChar, 4, 0, 0));
|
||||
fParam.Add("TestListFileNo", new ParamElement(SqlDbType.Int, 0, 0, 0));
|
||||
fParam.Add("TestListVariantNo", new ParamElement(SqlDbType.Int, 0, 0, 0));
|
||||
fParam.Add("TestListCntID", new ParamElement(SqlDbType.NVarChar, 256, 0, 0));
|
||||
fParam.Add("StepVersion", new ParamElement(SqlDbType.Int, 0, 0, 0));
|
||||
fParam.Add("HostID", new ParamElement(SqlDbType.NVarChar, 64, 0, 0));
|
||||
fParam.Add("Section", new ParamElement(SqlDbType.NVarChar, 64, 0, 0));
|
||||
fParam.Add("ProdNo_C", new ParamElement(SqlDbType.NVarChar, 32, 0, 0));
|
||||
fParam.Add("ProdNo_P", new ParamElement(SqlDbType.NVarChar, 32, 0, 0));
|
||||
fParam.Add("Testcode", new ParamElement(SqlDbType.NVarChar, 16, 0, 0));
|
||||
fParam.Add("TestListFileName", new ParamElement(SqlDbType.NVarChar, 256, 0, 0));
|
||||
fParam.Add("ProductID", new ParamElement(SqlDbType.NVarChar, 64, 0, 0));
|
||||
fParam.Add("Result", new ParamElement(SqlDbType.NVarChar, 16, 0, 0));
|
||||
fParam.Add("Duration", new ParamElement(SqlDbType.NVarChar, 16, 0, 0));
|
||||
fParam.Add("TestDT", new ParamElement(SqlDbType.DateTime2, 7, 0, 0));
|
||||
}
|
||||
|
||||
public static void LogSummaryField()
|
||||
{
|
||||
fParam.Clear();
|
||||
fParam = new Dictionary<string, ParamElement>();
|
||||
fParam.Add("AccessStart", new ParamElement(SqlDbType.BigInt, 0, 0, 0));
|
||||
fParam.Add("AccessEnd", new ParamElement(SqlDbType.BigInt, 0, 0, 0));
|
||||
fParam.Add("LogNo", new ParamElement(SqlDbType.BigInt, 0, 0, 0));
|
||||
fParam.Add("LogCount", new ParamElement(SqlDbType.Int, 0, 0, 0));
|
||||
fParam.Add("StationName", new ParamElement(SqlDbType.NVarChar, 128, 0, 0));
|
||||
fParam.Add("TestType", new ParamElement(SqlDbType.NVarChar, 8, 0, 0));
|
||||
fParam.Add("Version", new ParamElement(SqlDbType.NVarChar, 4, 0, 0));
|
||||
fParam.Add("ProdCode", new ParamElement(SqlDbType.NVarChar, 4, 0, 0));
|
||||
fParam.Add("TestListFileNo", new ParamElement(SqlDbType.Int, 0, 0, 0));
|
||||
fParam.Add("TestListVariantNo", new ParamElement(SqlDbType.Int, 0, 0, 0));
|
||||
fParam.Add("TestListCntID", new ParamElement(SqlDbType.NVarChar, 256, 0, 0));
|
||||
fParam.Add("StepVersion", new ParamElement(SqlDbType.Int, 0, 0, 0));
|
||||
fParam.Add("HostID", new ParamElement(SqlDbType.NVarChar, 64, 0, 0));
|
||||
fParam.Add("Section", new ParamElement(SqlDbType.NVarChar, 64, 0, 0));
|
||||
fParam.Add("ProdNo_C", new ParamElement(SqlDbType.NVarChar, 32, 0, 0));
|
||||
fParam.Add("ProdNo_P", new ParamElement(SqlDbType.NVarChar, 32, 0, 0));
|
||||
fParam.Add("Testcode", new ParamElement(SqlDbType.NVarChar, 16, 0, 0));
|
||||
fParam.Add("TestListFileName", new ParamElement(SqlDbType.NVarChar, 256, 0, 0));
|
||||
fParam.Add("ProductID", new ParamElement(SqlDbType.NVarChar, 64, 0, 0));
|
||||
fParam.Add("Result", new ParamElement(SqlDbType.NVarChar, 16, 0, 0));
|
||||
fParam.Add("Duration", new ParamElement(SqlDbType.NVarChar, 16, 0, 0));
|
||||
fParam.Add("TestDT", new ParamElement(SqlDbType.DateTime2, 7, 0, 0));
|
||||
}
|
||||
|
||||
public static void TestResultField()
|
||||
{
|
||||
fParam.Clear();
|
||||
fParam = new Dictionary<string, ParamElement>();
|
||||
fParam.Add("AccessKey", new ParamElement(SqlDbType.BigInt, 0, 0, 0));
|
||||
fParam.Add("StepID", new ParamElement(SqlDbType.BigInt, 0, 0, 0));
|
||||
fParam.Add("MeasVal", new ParamElement(SqlDbType.Decimal, 0, 15, 5));
|
||||
fParam.Add("MeasValStr", new ParamElement(SqlDbType.NVarChar, 1024, 0, 0));
|
||||
fParam.Add("Message", new ParamElement(SqlDbType.NVarChar, 2048, 0, 0));
|
||||
fParam.Add("GlobalMin", new ParamElement(SqlDbType.NVarChar, 1024, 0, 0));
|
||||
fParam.Add("GlobalMax", new ParamElement(SqlDbType.NVarChar, 1024, 0, 0));
|
||||
fParam.Add("Result", new ParamElement(SqlDbType.NVarChar, 16, 0, 0));
|
||||
fParam.Add("SpentTime", new ParamElement(SqlDbType.NVarChar, 64, 0, 0));
|
||||
fParam.Add("DataDT", new ParamElement(SqlDbType.DateTime2, 7, 0, 0));
|
||||
}
|
||||
|
||||
public static SqlParameter GetMakeSqlParameterInfo(Dictionary<string, ParamElement> refField, string strSetName, object objValue)
|
||||
{
|
||||
if (refField.ContainsKey(strSetName))
|
||||
{
|
||||
SqlParameter param = null;
|
||||
|
||||
if (refField[strSetName].Item2 != 0)
|
||||
param = new SqlParameter("@" + strSetName, refField[strSetName].Item1, refField[strSetName].Item2);
|
||||
else
|
||||
param = new SqlParameter("@" + strSetName, refField[strSetName].Item1);
|
||||
|
||||
if (refField[strSetName].Item1 == SqlDbType.Decimal)
|
||||
{
|
||||
param.Precision = refField[strSetName].Item3;
|
||||
param.Scale = refField[strSetName].Item4;
|
||||
}
|
||||
|
||||
param.Value = objValue;
|
||||
return param;
|
||||
}
|
||||
else
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static class LogParamInfo
|
||||
{
|
||||
public static readonly int MessageLength = 2048;
|
||||
public static readonly int MessageValLength = 1024;
|
||||
|
||||
public static string STEP = "";
|
||||
public static string POSITION = "";
|
||||
public static string MO = "";
|
||||
public static string FNC_NAME = "";
|
||||
public static string MIN = "";
|
||||
public static string MEASURE = "";
|
||||
public static string MAX = "";
|
||||
public static string DIM = "";
|
||||
public static string CHECK = "";
|
||||
public static string SPENT_TIME = "";
|
||||
public static string INFO = "";
|
||||
|
||||
public static bool GLOBAL_SPEC = false;
|
||||
public static string VRFY_MIN = "";
|
||||
public static string VRFY_MAX = "";
|
||||
}
|
||||
|
||||
public class CustomProtocol_ : BASE_PROTOCOL
|
||||
{
|
||||
public CustomProtocol_() : base()
|
||||
{
|
||||
}
|
||||
|
||||
public CustomProtocol_(ushort usGetCommnad, ushort usGetSubCommand) : base(usGetCommnad, usGetSubCommand)
|
||||
{
|
||||
}
|
||||
|
||||
public CustomProtocol_(PROTOCOL_CODE SET_CODE) : base(SET_CODE)
|
||||
{
|
||||
}
|
||||
|
||||
public string CheckTestListUpdate(string strProdC, string strTestCode, string strTestType, string strVersion, string strProdCode)
|
||||
{
|
||||
StringBuilder sbSetQuery = new StringBuilder();
|
||||
|
||||
/*
|
||||
sbSetQuery.Append("SELECT A.TestListNo, A.ProdNo_C, B.ProdNo_P, B.UpdateDT, D.TestCode, " +
|
||||
"B.TestType, B.Version, B.ProdCode FROM PROD_Release AS A WITH(NOLOCK) ");
|
||||
*/
|
||||
|
||||
sbSetQuery.Append("SELECT A.VariantNo AS 'TestListNo', A.ProdNo_C, B.ProdNo_P, B.UpdateDT, D.TestCode, " +
|
||||
"E.TestType, E.Version, E.ProdCode, B.TestListFileNo, A.VariantNo, E.UpdateDT AS 'TestListFileUpdateDT' FROM PROD_Release AS A WITH(NOLOCK) ");
|
||||
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM [PROD_Variant] WITH(NOLOCK)) AS B ");
|
||||
sbSetQuery.Append("ON A.VariantNo = B.No ");
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM [PROD_Group] WITH(NOLOCK)) AS C ");
|
||||
sbSetQuery.Append("ON B.GroupNo = C.No ");
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM [STAT_TestCode] WITH(NOLOCK)) AS D ");
|
||||
sbSetQuery.Append("ON A.TestCodeNo = D.No ");
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM [STOR_TestListFile] WITH(NOLOCK)) AS E ");
|
||||
sbSetQuery.Append("ON B.TestListFileNo = E.No ");
|
||||
|
||||
sbSetQuery.Append("WHERE A.ProdNo_C = '" + strProdC + "' ");
|
||||
if (strTestCode.Length > 0)
|
||||
sbSetQuery.Append("AND D.TestCode = '" + strTestCode + "' ");
|
||||
if (strTestType.Length > 0)
|
||||
sbSetQuery.Append("AND E.TestType = '" + strTestType + "' ");
|
||||
if (strVersion.Length > 0)
|
||||
sbSetQuery.Append("AND E.Version = '" + strVersion + "' ");
|
||||
if (strProdCode.Length > 0)
|
||||
sbSetQuery.Append("AND E.ProdCode = '" + strProdCode + "' ");
|
||||
|
||||
return sbSetQuery.ToString();
|
||||
|
||||
/*
|
||||
string[] strGetTestListFindInfo = new string[3];
|
||||
strGetTestListFindInfo[0] = strTestType;
|
||||
strGetTestListFindInfo[1] = strVersion;
|
||||
strGetTestListFindInfo[2] = strProdCode;
|
||||
|
||||
bool bFirstAppend = false;
|
||||
int iParameterCnt = 0;
|
||||
for (int i = 0; i < strGetTestListFindInfo.Length; i++)
|
||||
{
|
||||
if (strGetTestListFindInfo[i].Length > 0)
|
||||
{
|
||||
iParameterCnt++;
|
||||
|
||||
if (bFirstAppend == false)
|
||||
{
|
||||
bFirstAppend = true;
|
||||
|
||||
sbSetQuery.Append("WHERE ");
|
||||
}
|
||||
|
||||
if (iParameterCnt > 1)
|
||||
sbSetQuery.Append("AND ");
|
||||
|
||||
switch (i)
|
||||
{
|
||||
case 0:
|
||||
sbSetQuery.Append("TestType = '" + strGetTestListFindInfo[i] + "' ");
|
||||
break;
|
||||
case 1:
|
||||
sbSetQuery.Append("Version = '" + strGetTestListFindInfo[i] + "' ");
|
||||
break;
|
||||
case 2:
|
||||
sbSetQuery.Append("ProdCode = '" + strGetTestListFindInfo[i] + "' ");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
sbSetQuery.Append(") AS B ");
|
||||
|
||||
sbSetQuery.Append("ON B.No = A.TestListNo ");
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM PROD_Group AS Y WITH(NOLOCK)) AS C ");
|
||||
sbSetQuery.Append("ON C.No = B.GroupNo ");
|
||||
|
||||
if (strTestCode.Length > 0)
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM STAT_TestCode AS Z WITH(NOLOCK) WHERE Z.TestCode = '" + strTestCode + "') AS D ");
|
||||
else
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM STAT_TestCode AS Z WITH(NOLOCK)) AS D ");
|
||||
|
||||
sbSetQuery.Append("ON A.ProdNo_C = '" + strProdC + "' AND B.No = A.TestListNo AND D.No = A.TestCodeNo;");
|
||||
*/
|
||||
|
||||
return sbSetQuery.ToString();
|
||||
}
|
||||
|
||||
public string QueryFindTestList(PROCESS_PACKET getPaket, bool bJustCheck = false)
|
||||
{
|
||||
StringBuilder sbSetQuery = new StringBuilder();
|
||||
|
||||
/*
|
||||
if (bJustCheck)
|
||||
{
|
||||
sbSetQuery.Append("SELECT A.ProdNo_C, B.ProdNo_P, B.UpdateDT, D.TestCode, D.Gate1, D.Gate2, " +
|
||||
"B.FileName, A.RegUserComment, E.Description, C.GroupName, C.ModelName, " +
|
||||
"A.TestListNo, A.Config, " +
|
||||
"B.TestType, B.Version, B.ProdCode, B.UseTLPosition FROM PROD_Release AS A ");
|
||||
}
|
||||
else
|
||||
{
|
||||
sbSetQuery.Append("SELECT A.ProdNo_C, B.ProdNo_P, B.UpdateDT, D.TestCode, D.Gate1, D.Gate2, " +
|
||||
"B.FileName, A.RegUserComment, E.Description, C.GroupName, C.ModelName, " +
|
||||
"A.TestListNo, A.Config, " +
|
||||
"B.TestType, B.Version, B.ProdCode, B.TestListData, B.UseTLPosition FROM PROD_Release AS A ");
|
||||
}
|
||||
*/
|
||||
|
||||
if (bJustCheck)
|
||||
{
|
||||
sbSetQuery.Append("SELECT A.ProdNo_C, B.ProdNo_P, B.UpdateDT, D.TestCode, D.Gate1, D.Gate2, " +
|
||||
"E.FileName, A.RegUserComment, E.Description, C.GroupName, C.ModelName, " +
|
||||
"A.VariantNo AS 'TestListNo', A.Config, " +
|
||||
"E.TestType, E.Version, E.ProdCode, B.UseTLPosition, B.TestListFileNo, E.UpdateDT AS 'TestListFileUpdateDT', A.VariantNo FROM [PROD_Release] AS A WITH(NOLOCK) ");
|
||||
}
|
||||
else
|
||||
{
|
||||
sbSetQuery.Append("SELECT A.ProdNo_C, B.ProdNo_P, B.UpdateDT, D.TestCode, D.Gate1, D.Gate2, " +
|
||||
"E.FileName, A.RegUserComment, E.Description, C.GroupName, C.ModelName, " +
|
||||
"A.VariantNo AS 'TestListNo', A.Config, " +
|
||||
"E.TestType, E.Version, E.ProdCode, E.TestListData, B.UseTLPosition, B.TestListFileNo, E.UpdateDT AS 'TestListFileUpdateDT', A.VariantNo FROM [PROD_Release] AS A WITH(NOLOCK) ");
|
||||
}
|
||||
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM [PROD_Variant] WITH(NOLOCK)) AS B ");
|
||||
sbSetQuery.Append("ON A.VariantNo = B.No ");
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM [PROD_Group] WITH(NOLOCK)) AS C ");
|
||||
sbSetQuery.Append("ON B.GroupNo = C.No ");
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM [STAT_TestCode] WITH(NOLOCK)) AS D ");
|
||||
sbSetQuery.Append("ON A.TestCodeNo = D.No ");
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM [STOR_TestListFile] WITH(NOLOCK)) AS E ");
|
||||
sbSetQuery.Append("ON B.TestListFileNo = E.No ");
|
||||
sbSetQuery.Append("WHERE A.ProdNo_C = '" + getPaket.objProdNo_C[0].Data + "' ");
|
||||
|
||||
if (getPaket.objTestCode[0].Data.Length > 0)
|
||||
sbSetQuery.Append("AND D.TestCode = '" + getPaket.objTestCode[0].Data + "' ");
|
||||
if (getPaket.objTestType[0].Data.Length > 0)
|
||||
sbSetQuery.Append("AND E.TestType = '" + getPaket.objTestType[0].Data + "' ");
|
||||
if (getPaket.objTestListFileVersion[0].Data.Length > 0)
|
||||
sbSetQuery.Append("AND E.Version = '" + getPaket.objTestListFileVersion[0].Data + "' ");
|
||||
if (getPaket.objProductionCode[0].Data.Length > 0)
|
||||
sbSetQuery.Append("AND E.ProdCode = '" + getPaket.objProductionCode[0].Data + "' ");
|
||||
|
||||
return sbSetQuery.ToString();
|
||||
|
||||
/*
|
||||
string[] strGetTestListFindInfo = new string[3];
|
||||
strGetTestListFindInfo[0] = getPaket.objTestType[0].Data;
|
||||
strGetTestListFindInfo[1] = getPaket.objTestListFileVersion[0].Data;
|
||||
strGetTestListFindInfo[2] = getPaket.objProductionCode[0].Data;
|
||||
|
||||
bool bFirstAppend = false;
|
||||
int iParameterCnt = 0;
|
||||
for (int i = 0; i < strGetTestListFindInfo.Length; i++)
|
||||
{
|
||||
if (strGetTestListFindInfo[i].Length > 0)
|
||||
{
|
||||
iParameterCnt++;
|
||||
|
||||
if (bFirstAppend == false)
|
||||
{
|
||||
bFirstAppend = true;
|
||||
|
||||
sbSetQuery.Append("WHERE ");
|
||||
}
|
||||
|
||||
if (iParameterCnt > 1)
|
||||
sbSetQuery.Append("AND ");
|
||||
|
||||
switch (i)
|
||||
{
|
||||
case 0:
|
||||
sbSetQuery.Append("TestType = '" + strGetTestListFindInfo[i] + "' ");
|
||||
break;
|
||||
case 1:
|
||||
sbSetQuery.Append("Version = '" + strGetTestListFindInfo[i] + "' ");
|
||||
break;
|
||||
case 2:
|
||||
sbSetQuery.Append("ProdCode = '" + strGetTestListFindInfo[i] + "' ");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
public string QuerySelectTestListData(PROCESS_PACKET getPaket, int nLoadPosition)
|
||||
{
|
||||
StringBuilder sbSetQuery = new StringBuilder();
|
||||
|
||||
sbSetQuery.Append("SELECT A.ProdNo_C, B.ProdNo_P, B.UpdateDT, E.UpdateDT AS 'TestListFileUpdateDT', D.TestCode, D.Gate1, D.Gate2, " +
|
||||
"E.FileName, A.RegUserComment, E.Description, C.GroupName, C.ModelName, " +
|
||||
"A.VariantNo, A.VariantNo AS 'TestListNo', A.Config, " +
|
||||
"E.TestType, E.Version, E.ProdCode, ");
|
||||
|
||||
switch (nLoadPosition)
|
||||
{
|
||||
case 1: sbSetQuery.Append("F.TestListData1 AS 'TestListData', "); break;
|
||||
case 2: sbSetQuery.Append("F.TestListData2 AS 'TestListData', "); break;
|
||||
case 3: sbSetQuery.Append("F.TestListData3 AS 'TestListData', "); break;
|
||||
case 4: sbSetQuery.Append("F.TestListData4 AS 'TestListData', "); break;
|
||||
case 5: sbSetQuery.Append("F.TestListData5 AS 'TestListData', "); break;
|
||||
case 6: sbSetQuery.Append("F.TestListData6 AS 'TestListData', "); break;
|
||||
case 7: sbSetQuery.Append("F.TestListData7 AS 'TestListData', "); break;
|
||||
case 8: sbSetQuery.Append("F.TestListData8 AS 'TestListData', "); break;
|
||||
case 9: sbSetQuery.Append("F.TestListData9 AS 'TestListData', "); break;
|
||||
case 10: sbSetQuery.Append("F.TestListData10 AS 'TestListData', "); break;
|
||||
}
|
||||
|
||||
sbSetQuery.Append("B.TestListFileNo, B.UseTLPosition FROM [PROD_Release] AS A WITH(NOLOCK) ");
|
||||
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM [PROD_Variant] WITH(NOLOCK)) AS B ");
|
||||
sbSetQuery.Append("ON A.VariantNo = B.No ");
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM [PROD_Group] WITH(NOLOCK)) AS C ");
|
||||
sbSetQuery.Append("ON B.GroupNo = C.No ");
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM [STAT_TestCode] WITH(NOLOCK)) AS D ");
|
||||
sbSetQuery.Append("ON A.TestCodeNo = D.No ");
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM [STOR_TestListFile] WITH(NOLOCK)) AS E ");
|
||||
sbSetQuery.Append("ON B.TestListFileNo = E.No ");
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM [HIST_TestListFile] WITH(NOLOCK)) AS F ");
|
||||
sbSetQuery.Append("ON B.TestListFileNo = F.TestListFileNo ");
|
||||
sbSetQuery.Append("WHERE A.ProdNo_C = '" + getPaket.objProdNo_C[0].Data + "' ");
|
||||
|
||||
if (getPaket.objTestCode[0].Data.Length > 0)
|
||||
sbSetQuery.Append("AND D.TestCode = '" + getPaket.objTestCode[0].Data + "' ");
|
||||
if (getPaket.objTestType[0].Data.Length > 0)
|
||||
sbSetQuery.Append("AND E.TestType = '" + getPaket.objTestType[0].Data + "' ");
|
||||
if (getPaket.objTestListFileVersion[0].Data.Length > 0)
|
||||
sbSetQuery.Append("AND E.Version = '" + getPaket.objTestListFileVersion[0].Data + "' ");
|
||||
if (getPaket.objProductionCode[0].Data.Length > 0)
|
||||
sbSetQuery.Append("AND E.ProdCode = '" + getPaket.objProductionCode[0].Data + "' ");
|
||||
|
||||
/*
|
||||
string[] strGetTestListFindInfo = new string[3];
|
||||
strGetTestListFindInfo[0] = getPaket.objTestType[0].Data;
|
||||
strGetTestListFindInfo[1] = getPaket.objTestListFileVersion[0].Data;
|
||||
strGetTestListFindInfo[2] = getPaket.objProductionCode[0].Data;
|
||||
|
||||
bool bFirstAppend = false;
|
||||
int iParameterCnt = 0;
|
||||
for (int i = 0; i < strGetTestListFindInfo.Length; i++)
|
||||
{
|
||||
if (strGetTestListFindInfo[i].Length > 0)
|
||||
{
|
||||
iParameterCnt++;
|
||||
|
||||
if (bFirstAppend == false)
|
||||
{
|
||||
bFirstAppend = true;
|
||||
|
||||
sbSetQuery.Append("WHERE ");
|
||||
}
|
||||
|
||||
if (iParameterCnt > 1)
|
||||
sbSetQuery.Append("AND ");
|
||||
|
||||
switch (i)
|
||||
{
|
||||
case 0:
|
||||
sbSetQuery.Append("TestType = '" + strGetTestListFindInfo[i] + "' ");
|
||||
break;
|
||||
case 1:
|
||||
sbSetQuery.Append("Version = '" + strGetTestListFindInfo[i] + "' ");
|
||||
break;
|
||||
case 2:
|
||||
sbSetQuery.Append("ProdCode = '" + strGetTestListFindInfo[i] + "' ");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
sbSetQuery.Append(") AS B ");
|
||||
|
||||
sbSetQuery.Append("ON B.No = A.TestListNo ");
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM PROD_Group AS Y) AS C ");
|
||||
sbSetQuery.Append("ON C.No = B.GroupNo ");
|
||||
|
||||
sbSetQuery.Append("INNER JOIN(SELECT* FROM HIST_TestList) AS K ON K.TestListNo = A.TestListNo ");
|
||||
|
||||
if (getPaket.objTestCode[0].Data.Length > 0)
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM STAT_TestCode AS Z WHERE Z.TestCode = '" + getPaket.objTestCode[0].Data + "') AS D ");
|
||||
else
|
||||
sbSetQuery.Append("INNER JOIN(SELECT * FROM STAT_TestCode AS Z) AS D ");
|
||||
|
||||
sbSetQuery.Append("ON A.ProdNo_C = '" + getPaket.objProdNo_C[0].Data + "' AND B.No = A.TestListNo AND D.No = A.TestCodeNo;");
|
||||
*/
|
||||
|
||||
return sbSetQuery.ToString();
|
||||
}
|
||||
|
||||
public SqlCommand LoginInfoSummaryInsert(
|
||||
string strHostID,
|
||||
string strSection,
|
||||
bool bConnectState)
|
||||
{
|
||||
string columns = "TestType,Version,ProdCode,TestListFileNo,TestListVariantNo,StepVersion,HostID,Section,ProdNo_C,ProdNo_P,Testcode,TestListFileName,ProductID,Result,Duration";
|
||||
string values = string.Join(",", columns.Split(',').Select(c => string.Format("@{0}", c)));
|
||||
string sqlCommand = string.Format("INSERT INTO [HIST_TesterSummary] ({0}) VALUES ({1})", columns, values);
|
||||
|
||||
ParamSet.TesterSummaryField();
|
||||
|
||||
SqlCommand cmd = new SqlCommand(sqlCommand);
|
||||
|
||||
SqlParameter[] setParams = new SqlParameter[columns.Split(',').Count()];
|
||||
|
||||
setParams[0] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestType", "-");
|
||||
setParams[1] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Version", "-");
|
||||
setParams[2] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProdCode", "-");
|
||||
setParams[3] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestListFileNo", -1);
|
||||
setParams[4] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestListVariantNo", -1);
|
||||
setParams[5] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "StepVersion", -1);
|
||||
setParams[6] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "HostID", strHostID);
|
||||
setParams[7] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Section", strSection);
|
||||
setParams[8] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProdNo_C", "-");
|
||||
setParams[9] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProdNo_P", "-");
|
||||
setParams[10] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Testcode", "-");
|
||||
setParams[11] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestListFileName", "-");
|
||||
|
||||
if (bConnectState)
|
||||
setParams[12] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProductID", "PowerON");
|
||||
else
|
||||
setParams[12] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProductID", "PowerOFF");
|
||||
|
||||
setParams[13] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Result", "-");
|
||||
setParams[14] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Duration", "-");
|
||||
|
||||
cmd.Parameters.AddRange(setParams);
|
||||
|
||||
return cmd;
|
||||
}
|
||||
|
||||
public SqlCommand QueryTestListInfoSummaryInsert(
|
||||
//Int64 No,
|
||||
string strHostID,
|
||||
string strSection,
|
||||
|
||||
string strTestListCntID,
|
||||
|
||||
int nResultType,
|
||||
|
||||
string strProdNo_C = "-",
|
||||
string strTestType = "-",
|
||||
string strVersion = "-",
|
||||
string strProdCode = "-",
|
||||
string strTestcode = "-",
|
||||
|
||||
int nTestListFileNo = -1,
|
||||
int nTestListVariantNo = -1,
|
||||
string strProdNo_P = "-",
|
||||
string strTestlistFile = "-")
|
||||
{
|
||||
string columns = "TestType,Version,ProdCode,TestListFileNo,TestListVariantNo,TestListCntID,StepVersion,HostID,Section,ProdNo_C,ProdNo_P,Testcode,TestListFileName,ProductID,Result,Duration";
|
||||
string values = string.Join(",", columns.Split(',').Select(c => string.Format("@{0}", c)));
|
||||
string sqlCommand = string.Format("INSERT INTO [HIST_TesterSummary] ({0}) VALUES ({1})", columns, values);
|
||||
|
||||
if (strProdNo_C.Length <= 0) strProdNo_C = "-";
|
||||
if (strTestType.Length <= 0) strTestType = "-";
|
||||
if (strVersion.Length <= 0) strVersion = "-";
|
||||
if (strProdCode.Length <= 0) strProdCode = "-";
|
||||
if (strTestcode.Length <= 0) strTestcode = "-";
|
||||
if (strProdNo_P.Length <= 0) strProdNo_P = "-";
|
||||
if (strTestlistFile.Length <= 0) strTestlistFile = "-";
|
||||
|
||||
ParamSet.TesterSummaryField();
|
||||
|
||||
SqlCommand cmd = new SqlCommand(sqlCommand);
|
||||
SqlParameter[] setParams = new SqlParameter[columns.Split(',').Count()];
|
||||
//setParams[0] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestID", No);
|
||||
setParams[0] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestType", strTestType);
|
||||
setParams[1] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Version", strVersion);
|
||||
setParams[2] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProdCode", strProdCode);
|
||||
setParams[3] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestListFileNo", nTestListFileNo);
|
||||
setParams[4] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestListVariantNo", nTestListVariantNo);
|
||||
setParams[5] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestListCntID", strTestListCntID);
|
||||
setParams[6] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "StepVersion", -1);
|
||||
setParams[7] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "HostID", strHostID);
|
||||
setParams[8] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Section", strSection);
|
||||
setParams[9] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProdNo_C", strProdNo_C);
|
||||
setParams[10] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProdNo_P", strProdNo_P);
|
||||
setParams[11] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Testcode", strTestcode);
|
||||
setParams[12] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestListFileName", strTestlistFile);
|
||||
setParams[13] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProductID", "QUERY");
|
||||
|
||||
switch (nResultType)
|
||||
{
|
||||
case 0: setParams[14] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Result", "FAIL"); break;
|
||||
case 1: setParams[14] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Result", "FIND"); break;
|
||||
case 2: setParams[14] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Result", "CHECK"); break;
|
||||
case 3: setParams[14] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Result", "ERROR"); break;
|
||||
default: setParams[14] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Result", "-"); break;
|
||||
}
|
||||
|
||||
setParams[15] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Duration", "-");
|
||||
|
||||
cmd.Parameters.AddRange(setParams);
|
||||
|
||||
return cmd;
|
||||
}
|
||||
|
||||
public SqlCommand LogDataSummaryInsert(HISTLogSummary itemSummary)
|
||||
{
|
||||
string columns = string.Empty;
|
||||
if(itemSummary.TestListCntID == string.Empty)
|
||||
columns = "StationName,TestType,Version,ProdCode,TestListFileNo,TestListVariantNo,StepVersion,HostID,Section,ProdNo_C,ProdNo_P,Testcode,TestListFileName,ProductID,Result,Duration,TestDT";
|
||||
else
|
||||
columns = "StationName,TestType,Version,ProdCode,TestListFileNo,TestListVariantNo,TestListCntID,StepVersion,HostID,Section,ProdNo_C,ProdNo_P,Testcode,TestListFileName,ProductID,Result,Duration,TestDT";
|
||||
|
||||
string values = string.Join(",", columns.Split(',').Select(c => string.Format("@{0}", c)));
|
||||
string sqlCommand = string.Format("INSERT INTO [HIST_LogSummary] ({0}) VALUES ({1})", columns, values);
|
||||
|
||||
ParamSet.LogSummaryField();
|
||||
|
||||
SqlCommand cmd = new SqlCommand(sqlCommand);
|
||||
|
||||
SqlParameter[] setParams = new SqlParameter[columns.Split(',').Count()];
|
||||
|
||||
if (itemSummary.TestListCntID == string.Empty)
|
||||
{
|
||||
setParams[0] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "StationName", itemSummary.StationName);
|
||||
setParams[1] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestType", itemSummary.TestType);
|
||||
setParams[2] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Version", itemSummary.Version);
|
||||
setParams[3] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProdCode", itemSummary.ProdCode);
|
||||
setParams[4] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestListFileNo", itemSummary.TestListFileNo);
|
||||
setParams[5] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestListVariantNo", itemSummary.TestListVariantNo);
|
||||
setParams[6] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "StepVersion", itemSummary.StepVersion);
|
||||
setParams[7] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "HostID", itemSummary.Host);
|
||||
setParams[8] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Section", itemSummary.Section);
|
||||
setParams[9] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProdNo_C", itemSummary.ProdNoC);
|
||||
setParams[10] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProdNo_P", itemSummary.ProdNoP);
|
||||
setParams[11] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Testcode", itemSummary.TestCode);
|
||||
setParams[12] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestListFileName", itemSummary.TestListFileName);
|
||||
setParams[13] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProductID", itemSummary.ProductID);
|
||||
setParams[14] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Result", itemSummary.Result);
|
||||
setParams[15] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Duration", itemSummary.Duration);
|
||||
setParams[16] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestDT", itemSummary.TestDT);
|
||||
}
|
||||
else
|
||||
{
|
||||
setParams[0] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "StationName", itemSummary.StationName);
|
||||
setParams[1] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestType", itemSummary.TestType);
|
||||
setParams[2] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Version", itemSummary.Version);
|
||||
setParams[3] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProdCode", itemSummary.ProdCode);
|
||||
setParams[4] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestListFileNo", itemSummary.TestListFileNo);
|
||||
setParams[5] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestListVariantNo", itemSummary.TestListVariantNo);
|
||||
setParams[6] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestListCntID", itemSummary.TestListCntID);
|
||||
setParams[7] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "StepVersion", itemSummary.StepVersion);
|
||||
setParams[8] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "HostID", itemSummary.Host);
|
||||
setParams[9] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Section", itemSummary.Section);
|
||||
setParams[10] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProdNo_C", itemSummary.ProdNoC);
|
||||
setParams[11] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProdNo_P", itemSummary.ProdNoP);
|
||||
setParams[12] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Testcode", itemSummary.TestCode);
|
||||
setParams[13] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestListFileName", itemSummary.TestListFileName);
|
||||
setParams[14] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "ProductID", itemSummary.ProductID);
|
||||
setParams[15] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Result", itemSummary.Result);
|
||||
setParams[16] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "Duration", itemSummary.Duration);
|
||||
setParams[17] = ParamSet.GetMakeSqlParameterInfo(ParamSet.fParam, "TestDT", itemSummary.TestDT);
|
||||
}
|
||||
|
||||
cmd.Parameters.AddRange(setParams);
|
||||
|
||||
return cmd;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,141 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization.Formatters.Binary;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
// 데이터 압축/해제 관련
|
||||
namespace SystemX.Common.Archive
|
||||
{
|
||||
public static class XDataArchive
|
||||
{
|
||||
public static byte[] CompressDeflateByteToByte(byte[] ucData)
|
||||
{
|
||||
byte[] ucCompressedByte;
|
||||
using (MemoryStream ms = new MemoryStream())
|
||||
{
|
||||
using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress))
|
||||
{
|
||||
ds.Write(ucData, 0, ucData.Length);
|
||||
}
|
||||
ucCompressedByte = ms.ToArray();
|
||||
}
|
||||
|
||||
return ucCompressedByte;
|
||||
}
|
||||
public static byte[] CompressGZipByteToByte(byte[] ucData)
|
||||
{
|
||||
byte[] ucCompressedByte;
|
||||
using (MemoryStream ms = new MemoryStream())
|
||||
{
|
||||
using (GZipStream gs = new GZipStream(ms, CompressionMode.Compress))
|
||||
{
|
||||
gs.Write(ucData, 0, ucData.Length);
|
||||
}
|
||||
ucCompressedByte = ms.ToArray();
|
||||
}
|
||||
|
||||
return ucCompressedByte;
|
||||
}
|
||||
public static byte[] DecompressDeflateByteToByte(byte[] ucCompressedData)
|
||||
{
|
||||
byte[] ucDecompressedByte;
|
||||
|
||||
MemoryStream resultStream = new MemoryStream();
|
||||
using (MemoryStream ms = new MemoryStream(ucCompressedData))
|
||||
{
|
||||
using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress))
|
||||
{
|
||||
ds.CopyTo(resultStream);
|
||||
ds.Close();
|
||||
|
||||
ucDecompressedByte = resultStream.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
return ucDecompressedByte;
|
||||
}
|
||||
public static byte[] DecompressGZipByteToByte(byte[] ucCompressedData)
|
||||
{
|
||||
byte[] ucDecompressedByte;
|
||||
|
||||
MemoryStream resultStream = new MemoryStream();
|
||||
using (MemoryStream ms = new MemoryStream(ucCompressedData))
|
||||
{
|
||||
using (GZipStream gs = new GZipStream(ms, CompressionMode.Decompress))
|
||||
{
|
||||
gs.CopyTo(resultStream);
|
||||
gs.Close();
|
||||
|
||||
ucDecompressedByte = resultStream.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
return ucDecompressedByte;
|
||||
}
|
||||
public static byte[] CompressDatasetToByte(DataSet ds)
|
||||
{
|
||||
//1. 데이터셋 Serialize
|
||||
ds.RemotingFormat = SerializationFormat.Binary;
|
||||
BinaryFormatter bf = new BinaryFormatter();
|
||||
MemoryStream ms = new MemoryStream();
|
||||
bf.Serialize(ms, ds);
|
||||
byte[] inbyt = ms.ToArray();
|
||||
|
||||
//2. 데이터 압축
|
||||
System.IO.MemoryStream objStream = new MemoryStream();
|
||||
System.IO.Compression.DeflateStream objZS = new System.IO.
|
||||
Compression.DeflateStream(objStream, System.IO.Compression.
|
||||
CompressionMode.Compress);
|
||||
objZS.Write(inbyt, 0, inbyt.Length);
|
||||
objZS.Flush();
|
||||
objZS.Close();
|
||||
|
||||
//3. 데이터 리턴
|
||||
return objStream.ToArray();
|
||||
}
|
||||
public static DataSet DecompressByteToDataset(byte[] bytDs)
|
||||
{
|
||||
DataSet outDs = new DataSet();
|
||||
MemoryStream inMs = new MemoryStream(bytDs);
|
||||
inMs.Seek(0, 0); //스트림으로 가져오기
|
||||
|
||||
//1. 압축객체 생성- 압축 풀기
|
||||
DeflateStream zipStream = new DeflateStream(inMs,
|
||||
CompressionMode.Decompress, true);
|
||||
byte[] outByt = ReadFullStreamToByte(zipStream);
|
||||
zipStream.Flush();
|
||||
zipStream.Close();
|
||||
MemoryStream outMs = new MemoryStream(outByt);
|
||||
outMs.Seek(0, 0); //2. 스트림으로 다시변환
|
||||
outDs.RemotingFormat = SerializationFormat.Binary;
|
||||
|
||||
//3. 데이터셋으로 Deserialize
|
||||
BinaryFormatter bf = new BinaryFormatter();
|
||||
outDs = (DataSet)bf.Deserialize(outMs, null);
|
||||
|
||||
return outDs;
|
||||
}
|
||||
private static byte[] ReadFullStreamToByte(Stream stream)
|
||||
{
|
||||
//스트림을 Byte 배열로 변환
|
||||
byte[] buffer = new byte[1000000];
|
||||
using (MemoryStream ms = new MemoryStream())
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
int read = stream.Read(buffer, 0, buffer.Length);
|
||||
|
||||
if (read <= 0)
|
||||
return ms.ToArray();
|
||||
|
||||
ms.Write(buffer, 0, read);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SystemX.Net.Platform.Common
|
||||
{
|
||||
public static class DataTableQuery
|
||||
{
|
||||
public static List<DataRow> FindDataRow(DataTable dtTable, string strKeyName, string strFindingValue)
|
||||
{
|
||||
List<DataRow> adrResult = (from dtRow in dtTable.AsEnumerable() where dtRow[strKeyName].ToString() == strFindingValue select dtRow).ToList();
|
||||
|
||||
return adrResult;
|
||||
}
|
||||
|
||||
public static int GetDataRowHandle(DataTable dtTable, string strKeyFieldName, string strComparingValue)
|
||||
{
|
||||
int nIdx = 0;
|
||||
|
||||
foreach (DataRow dtRow in dtTable.AsEnumerable())
|
||||
{
|
||||
if (dtRow[strKeyFieldName].ToString() == strComparingValue)
|
||||
return nIdx;
|
||||
|
||||
nIdx++;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,158 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Reactive.Subjects;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Event
|
||||
{
|
||||
public interface ISysXEventField : ISynchronizeInvoke
|
||||
{
|
||||
void ProcessEvent(IObservableEvent evt);
|
||||
}
|
||||
|
||||
public class OSCAREventHandler : ISubscribable
|
||||
{
|
||||
public Subject<IObservableEvent> ApplicationSubject = new Subject<IObservableEvent>();
|
||||
protected List<IDisposable> _applicationSubscriptions = new List<IDisposable>();
|
||||
public ISysXEventField TheApplicationTarget { get; set; }
|
||||
public static OSCAREventHandler TheApplication { get; private set; }
|
||||
|
||||
public OSCAREventHandler(ISysXEventField eventField)
|
||||
{
|
||||
Contract.Requires(eventField is Form);
|
||||
Contract.Requires(TheApplication == null);
|
||||
|
||||
TheApplication = this;
|
||||
TheApplicationTarget = eventField;
|
||||
|
||||
var observable = Observable
|
||||
.Interval(TimeSpan.FromSeconds(1))
|
||||
.Take(5);
|
||||
|
||||
var observer = System.Reactive.Observer.Create<long>(
|
||||
x => Console.WriteLine("Value published to subject #1: {0}", x),
|
||||
() => Console.WriteLine("Sequence Completed."));
|
||||
|
||||
AddSubscription(ApplicationSubject.Subscribe(evt => OnApplicationEvent(evt)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applicatino event 처리.
|
||||
/// Note: ObservableEventTask{Starting, Finished} 는 별도 subscription 을 통해서 처리 됨.
|
||||
/// </summary>
|
||||
/// <param name="evt"></param>
|
||||
private void OnApplicationEvent(IObservableEvent evt)
|
||||
{
|
||||
// 샘플 코드
|
||||
bool onMainThread = !TheApplicationTarget.InvokeRequired;
|
||||
|
||||
//System.Media.SystemSounds.Beep.Play();
|
||||
|
||||
// thread 상에서 호출되었다면, main UI thread 상에서 수행되도록 한다.
|
||||
//TheApplicationForm.Do(() =>
|
||||
//{
|
||||
//logger.Info($"Application got event : {evt}");
|
||||
//((IOSCAREventField)TheApplicationForm).HandleStationEvent(evt);
|
||||
|
||||
ProcessObservableEventHandler(evt);
|
||||
//});
|
||||
}
|
||||
|
||||
protected delegate void ObservableEventHandler(IObservableEvent evt);
|
||||
private void ProcessObservableEventHandler(IObservableEvent evt)
|
||||
{
|
||||
if (TheApplicationTarget.InvokeRequired)
|
||||
{
|
||||
ObservableEventHandler delState = new ObservableEventHandler(ProcessObservableEventHandler);
|
||||
(TheApplicationTarget as Control).Invoke(delState, evt);
|
||||
}
|
||||
else
|
||||
{
|
||||
TheApplicationTarget.ProcessEvent(evt);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddSubscription(IDisposable subscription)
|
||||
{
|
||||
_applicationSubscriptions.Add(subscription);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true); // true : 명시적 dispose 호출
|
||||
|
||||
GC.SuppressFinalize(this); // 사용자에 의해서 명시적으로 dispose 되었으므로, GC 는 이 객체에 대해서 손대지 말것을 알림.
|
||||
}
|
||||
|
||||
private bool _disposed;
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
|
||||
if (disposing)
|
||||
{
|
||||
// AwaitTermination() call hangs. Need to check Akka document.
|
||||
// CommonApplication.ActorSystem.AwaitTermination();
|
||||
_applicationSubscriptions.ForEach(s => s.Dispose());
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
public class TestEvent : IObservableEvent
|
||||
{
|
||||
public string Process { private set; get; }
|
||||
public string Path { set; get; }
|
||||
|
||||
public TestEvent(string process, string strPath)
|
||||
{
|
||||
Process = process;
|
||||
Path = strPath;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rx event 에 대한 subscribe 가 가능한 객체가 구현해야 할 interface
|
||||
/// Dispose 시에 모든 subscription 을 dispose 해야 한다.
|
||||
/// </summary>
|
||||
public interface ISubscribable : IDisposable
|
||||
{
|
||||
/* Usage sample
|
||||
private List<IDisposable> _subscriptions = new List<IDisposable>();
|
||||
public void AddSubscription(IDisposable subscription) { _subscriptions.Add(subscription); }
|
||||
|
||||
// Requires disposal of subscriptions on Dispose() method
|
||||
*
|
||||
*/
|
||||
void AddSubscription(IDisposable subscription);
|
||||
}
|
||||
|
||||
/// <summary> Configuration interface </summary>
|
||||
[Guid("8501C86A-61E7-4F92-B90A-1779CCF6AAF3")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
|
||||
[ComVisible(true)]
|
||||
public interface IConfiguration : ICloneable
|
||||
{
|
||||
/// <summary> Save configuration to file </summary>
|
||||
void QSave(string fileName);
|
||||
/// <summary> Load configuration from file </summary>
|
||||
void QLoad(string fileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rx: System.Reactive.Subjects.Subject 에 대한 base interface
|
||||
/// </summary>
|
||||
[ComVisible(false)]
|
||||
public interface IObservableEvent
|
||||
{
|
||||
}
|
||||
|
||||
public interface IObservableUIEvent : IObservableEvent { }
|
||||
}
|
||||
@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Event
|
||||
{
|
||||
public class FunctionEventHandler
|
||||
{
|
||||
public FunctionEventHandler() { }
|
||||
|
||||
public delegate void evtReceiveHandler(object sender, object data);
|
||||
public event evtReceiveHandler OnReceive;
|
||||
|
||||
public void DoReceive(object sender, object data)
|
||||
{
|
||||
if (OnReceive != null)
|
||||
OnReceive(sender, data);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,63 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Event
|
||||
{
|
||||
public class PauseTokenSource
|
||||
{
|
||||
private volatile TaskCompletionSource<bool> m_paused;
|
||||
internal static readonly Task s_completedTask = Task.FromResult(true);
|
||||
|
||||
public void Pause()
|
||||
{
|
||||
Interlocked.CompareExchange(
|
||||
ref m_paused, new TaskCompletionSource<bool>(), null);
|
||||
}
|
||||
|
||||
public void Resume()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var tcs = m_paused;
|
||||
if (tcs == null) return;
|
||||
if (Interlocked.CompareExchange(ref m_paused, null, tcs) == tcs)
|
||||
{
|
||||
tcs.SetResult(true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsPaused
|
||||
{
|
||||
get { return m_paused != null; }
|
||||
}
|
||||
|
||||
public PauseToken Token { get { return new PauseToken(this); } }
|
||||
|
||||
internal Task WaitWhilePausedAsync()
|
||||
{
|
||||
var cur = m_paused;
|
||||
return cur != null ? cur.Task : s_completedTask;
|
||||
}
|
||||
}
|
||||
|
||||
public struct PauseToken
|
||||
{
|
||||
private readonly PauseTokenSource m_source;
|
||||
internal PauseToken(PauseTokenSource source) { m_source = source; }
|
||||
|
||||
public bool IsPaused { get { return m_source != null && m_source.IsPaused; } }
|
||||
|
||||
public Task WaitWhilePausedAsync()
|
||||
{
|
||||
return IsPaused ?
|
||||
m_source.WaitWhilePausedAsync() :
|
||||
PauseTokenSource.s_completedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,153 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.ExtensionMethods
|
||||
{
|
||||
public static class EmAsync
|
||||
{
|
||||
public static TResult WaitResultAsyncFunction<TResult>(this Func<Task<TResult>> function)
|
||||
{
|
||||
var task = Task.Run(() => function());
|
||||
task.Wait();
|
||||
return task.Result;
|
||||
}
|
||||
|
||||
public static void WaitAsyncFunction(this Func<Task> function)
|
||||
{
|
||||
function().Wait();
|
||||
}
|
||||
|
||||
|
||||
//private static Action WrapExceptionSafe(this Action action, Action<Exception> exceptionHandler)
|
||||
//{
|
||||
// return new Action(() =>
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// action();
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// if (exceptionHandler == null)
|
||||
// {
|
||||
// if ( FormAppCommon.UISynchronizationContext == null )
|
||||
// MessageBox.Show(ex.Message, "Exception occurred!", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
// else
|
||||
// FormAppCommon.UISynchronizationContext.Send(ignore => UnhandledExceptionHandler.ShowUnhandledException(ex), null);
|
||||
// }
|
||||
// else
|
||||
// exceptionHandler(ex);
|
||||
// }
|
||||
// });
|
||||
//}
|
||||
|
||||
|
||||
//public static Func<Task<T>> WrapExceptionSafe<T>(this Func<Task<T>> function, Action<Exception> exceptionHandler)
|
||||
//{
|
||||
// return new Func<Task<T>>(() =>
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// return function();
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// if (exceptionHandler == null)
|
||||
// {
|
||||
// if (FormAppCommon.UISynchronizationContext == null)
|
||||
// MessageBox.Show(ex.Message, "Exception occurred!", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
// else
|
||||
// FormAppCommon.UISynchronizationContext.Send(ignore => UnhandledExceptionHandler.ShowUnhandledException(ex), null);
|
||||
// }
|
||||
// else
|
||||
// exceptionHandler(ex);
|
||||
|
||||
// return null;
|
||||
// }
|
||||
// });
|
||||
|
||||
//}
|
||||
|
||||
///// <summary>
|
||||
///// 단순히 Task.Run(()=>{}) 수행시, exception 을 catch 할수 없으므로, 다음 extension 을 사용해서 해결함
|
||||
///// </summary>
|
||||
///// <param name="action"></param>
|
||||
///// <param name="exceptionHandler"></param>
|
||||
//public static Task ExceptionSafeTaskRun(this Action action, Action<Exception> exceptionHandler=null)
|
||||
//{
|
||||
// return Task.Run(WrapExceptionSafe(action, exceptionHandler));
|
||||
//}
|
||||
//public static Task<T> ExceptionSafeTaskRun<T>(this Func<Task<T>> function, Action<Exception> exceptionHandler=null)
|
||||
//{
|
||||
// return Task.Run(WrapExceptionSafe(function, exceptionHandler));
|
||||
//}
|
||||
|
||||
|
||||
//private static void HandleException(this Task task)
|
||||
//{
|
||||
// var ex = task.Exception;
|
||||
// if (ex != null)
|
||||
// {
|
||||
// System.Diagnostics.Trace.WriteLine(ex.ToString());
|
||||
// Globals.Logger?.Error(ex.ToString());
|
||||
// }
|
||||
//}
|
||||
|
||||
///// <summary>
|
||||
///// Disabling CS4014
|
||||
///// http://stackoverflow.com/questions/22629951/suppressing-warning-cs4014-because-this-call-is-not-awaited-execution-of-the
|
||||
///// warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed.
|
||||
///// Consider applying the 'await' operator to the result of the call.
|
||||
///// </summary>
|
||||
///// <param name="task"></param>
|
||||
//public static void Forget(this Task task)
|
||||
//{
|
||||
// // Async in C# 5.0, pp.57
|
||||
// // Task 를 실행만 하고, await 하지 않는 fire & forget 모델에서, exception 이 발생하였을 경우를 체크 하기 위한 용도.
|
||||
// task.ContinueWith(ant => HandleException(ant));
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// http://stackoverflow.com/questions/2565166/net-best-way-to-execute-a-lambda-on-ui-thread-after-a-delay
|
||||
/// </summary>
|
||||
/// Usage
|
||||
/// <code>
|
||||
/// SynchronizationContext.Current.Post(TimeSpan.FromSeconds(1), () => textBlock.Text="Done");
|
||||
/// </code>
|
||||
public static void Post(this SynchronizationContext context, TimeSpan delay, Action action)
|
||||
{
|
||||
System.Threading.Timer timer = null;
|
||||
|
||||
timer = new System.Threading.Timer((ignore) =>
|
||||
{
|
||||
timer.Dispose();
|
||||
|
||||
context.Post(ignore2 => action(), null);
|
||||
}, null, delay, TimeSpan.FromMilliseconds(-1));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes action after delay.
|
||||
/// C# 5.0 in a Nutshell, pp. 573
|
||||
/// </summary>
|
||||
/// <param name="action"></param>
|
||||
/// <param name="delayMillisec"></param>
|
||||
/// <returns></returns>
|
||||
public static Task ExecuteWithDelay(this Action action, int delayMillisec)
|
||||
{
|
||||
return Task.Delay(delayMillisec).ContinueWith(ant => action);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// pp.20. Concurrency in C# Cookbook
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static Task<T> FromResult<T>(this T value)
|
||||
{
|
||||
return Task.FromResult(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,161 @@
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.IO;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.ExtensionMethods
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// http://stackoverflow.com/questions/2368757/easy-way-to-convert-a-bitmap-and-png-image-to-text-and-vice-versa
|
||||
/// http://www.developerfusion.com/thread/47978/how-can-i-convert-image-type-to-bitmap-type-in-cnet/
|
||||
/// http://stackoverflow.com/questions/10442269/scaling-a-system-drawing-bitmap-to-a-given-size-while-maintaining-aspect-ratio
|
||||
public static class EmBitmap
|
||||
{
|
||||
public static string EncodeToString(this Bitmap bitmap)
|
||||
{
|
||||
if ( bitmap == null )
|
||||
return String.Empty;
|
||||
|
||||
MemoryStream memoryStream = new MemoryStream();
|
||||
bitmap.Save(memoryStream, ImageFormat.Png);
|
||||
byte[] bitmapBytes = memoryStream.GetBuffer();
|
||||
return Convert.ToBase64String(bitmapBytes, Base64FormattingOptions.InsertLineBreaks);
|
||||
}
|
||||
|
||||
public static Bitmap FromEncodedString(string bitmapString)
|
||||
{
|
||||
byte[] bitmapBytes = Convert.FromBase64String(bitmapString);
|
||||
MemoryStream memoryStream = new MemoryStream(bitmapBytes);
|
||||
return new Bitmap(Image.FromStream(memoryStream));
|
||||
}
|
||||
|
||||
public static Bitmap Resize(this Bitmap bitmap, int width)
|
||||
{
|
||||
double height = width * ((double)bitmap.Height / bitmap.Width);
|
||||
return new Bitmap(bitmap, new Size(width, (int)height));
|
||||
}
|
||||
|
||||
|
||||
public static Icon ToIcon(this Bitmap bitmap)
|
||||
{
|
||||
return Icon.FromHandle(bitmap.GetHicon());
|
||||
}
|
||||
|
||||
public static Bitmap ToBitmap(this Image image)
|
||||
{
|
||||
return (Bitmap) image;
|
||||
}
|
||||
|
||||
public static Icon ToIcon(this Image image)
|
||||
{
|
||||
return Icon.FromHandle(((Bitmap)image).GetHicon());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class ImageHelper
|
||||
{
|
||||
#region CropUnwantedBackground
|
||||
public static Bitmap CropUnwantedBackground(Bitmap bmp)
|
||||
{
|
||||
var backColor = GetMatchedBackColor(bmp);
|
||||
if (backColor.HasValue)
|
||||
{
|
||||
var bounds = GetImageBounds(bmp, backColor);
|
||||
var diffX = bounds[1].X - bounds[0].X + 1;
|
||||
var diffY = bounds[1].Y - bounds[0].Y + 1;
|
||||
var croppedBmp = new Bitmap(diffX, diffY);
|
||||
var g = Graphics.FromImage(croppedBmp);
|
||||
var destRect = new Rectangle(0, 0, croppedBmp.Width, croppedBmp.Height);
|
||||
var srcRect = new Rectangle(bounds[0].X, bounds[0].Y, diffX, diffY);
|
||||
g.DrawImage(bmp, destRect, srcRect, GraphicsUnit.Pixel);
|
||||
return croppedBmp;
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Private Methods
|
||||
|
||||
#region GetImageBounds
|
||||
private static Point[] GetImageBounds(Bitmap bmp, Color? backColor)
|
||||
{
|
||||
//--------------------------------------------------------------------
|
||||
// Finding the Bounds of Crop Area bu using Unsafe Code and Image Proccesing
|
||||
Color c;
|
||||
int width = bmp.Width, height = bmp.Height;
|
||||
bool upperLeftPointFounded = false;
|
||||
var bounds = new Point[2];
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
for (int x = 0; x < width; x++)
|
||||
{
|
||||
c = bmp.GetPixel(x, y);
|
||||
bool sameAsBackColor = ((c.R <= backColor.Value.R * 1.1 && c.R >= backColor.Value.R * 0.9) &&
|
||||
(c.G <= backColor.Value.G * 1.1 && c.G >= backColor.Value.G * 0.9) &&
|
||||
(c.B <= backColor.Value.B * 1.1 && c.B >= backColor.Value.B * 0.9));
|
||||
if (!sameAsBackColor)
|
||||
{
|
||||
if (!upperLeftPointFounded)
|
||||
{
|
||||
bounds[0] = new Point(x, y);
|
||||
bounds[1] = new Point(x, y);
|
||||
upperLeftPointFounded = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (x > bounds[1].X)
|
||||
bounds[1].X = x;
|
||||
else if (x < bounds[0].X)
|
||||
bounds[0].X = x;
|
||||
if (y >= bounds[1].Y)
|
||||
bounds[1].Y = y;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return bounds;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region GetMatchedBackColor
|
||||
private static Color? GetMatchedBackColor(Bitmap bmp)
|
||||
{
|
||||
// Getting The Background Color by checking Corners of Original Image
|
||||
var corners = new Point[]{
|
||||
new Point(0, 0),
|
||||
new Point(0, bmp.Height - 1),
|
||||
new Point(bmp.Width - 1, 0),
|
||||
new Point(bmp.Width - 1, bmp.Height - 1)
|
||||
}; // four corners (Top, Left), (Top, Right), (Bottom, Left), (Bottom, Right)
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
var cornerMatched = 0;
|
||||
var backColor = bmp.GetPixel(corners[i].X, corners[i].Y);
|
||||
for (int j = 0; j < 4; j++)
|
||||
{
|
||||
var cornerColor = bmp.GetPixel(corners[j].X, corners[j].Y);// Check RGB with some offset
|
||||
if ((cornerColor.R <= backColor.R * 1.1 && cornerColor.R >= backColor.R * 0.9) &&
|
||||
(cornerColor.G <= backColor.G * 1.1 && cornerColor.G >= backColor.G * 0.9) &&
|
||||
(cornerColor.B <= backColor.B * 1.1 && cornerColor.B >= backColor.B * 0.9))
|
||||
{
|
||||
cornerMatched++;
|
||||
}
|
||||
}
|
||||
if (cornerMatched > 2)
|
||||
{
|
||||
return backColor;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,75 @@
|
||||
using System;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.ExtensionMethods
|
||||
{
|
||||
public static class EmComparable
|
||||
{
|
||||
/// <summary>
|
||||
/// [min, max]
|
||||
/// value 값이 from, to 사이에 존재하는지를 검사한다.
|
||||
/// http://stackoverflow.com/questions/8776624/if-value-in-rangex-y-function-c-sharp
|
||||
/// </summary>
|
||||
[Pure]
|
||||
public static bool InClosedRange<T>(this T val, T min, T max) where T : IComparable<T>
|
||||
{
|
||||
Contract.Requires(min.CompareTo(max) <= 0);
|
||||
return min.CompareTo(val) <= 0 && val.CompareTo(max) <= 0;
|
||||
}
|
||||
|
||||
[Pure]
|
||||
public static bool InRange<T>(this T val, T min, T max) where T : IComparable<T>
|
||||
{
|
||||
return val.InClosedRange(min, max);
|
||||
}
|
||||
|
||||
/// <summary> [min, max) </summary>
|
||||
[Pure]
|
||||
public static bool InClampRange<T>(this T val, T min, T max) where T : IComparable<T>
|
||||
{
|
||||
Contract.Requires(min.CompareTo(max) <= 0);
|
||||
return min.CompareTo(val) <= 0 && val.CompareTo(max) < 0;
|
||||
}
|
||||
|
||||
/// <summary> (min, max) </summary>
|
||||
[Pure]
|
||||
public static bool InOpenRange<T>(this T val, T min, T max) where T : IComparable<T>
|
||||
{
|
||||
Contract.Requires(min.CompareTo(max) <= 0);
|
||||
return min.CompareTo(val) < 0 && val.CompareTo(max) < 0;
|
||||
}
|
||||
|
||||
|
||||
[Pure]
|
||||
public static bool EpsilonEqual(this double value1, double value2, double epsilon = Double.Epsilon)
|
||||
{
|
||||
return Math.Abs(value1 - value2) < epsilon;
|
||||
}
|
||||
|
||||
[Pure]
|
||||
public static bool EpsilonEqual(this float value1, float value2, float epsilon = Single.Epsilon)
|
||||
{
|
||||
return Math.Abs(value1 - value2) < epsilon;
|
||||
}
|
||||
|
||||
/// <summary> Key 값이 set 에 포함되는지 여부를 검사한다. </summary>
|
||||
[Pure]
|
||||
public static bool IsOneOf(this IComparable key, params IComparable[] set)
|
||||
{
|
||||
return set.Any(e => e.CompareTo(key) == 0);
|
||||
}
|
||||
|
||||
|
||||
public static bool IsOneOf(this object key, params object[] set)
|
||||
{
|
||||
return set.Any(e => e == key);
|
||||
}
|
||||
|
||||
public static bool IsOneOf(this Type type, params Type[] set)
|
||||
{
|
||||
return set.Any(t => t.IsAssignableFrom(type));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,427 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
|
||||
namespace SystemX.Net.Platform.Common.ExtensionMethods
|
||||
{
|
||||
/// <summary>
|
||||
/// http://lostechies.com/derickbailey/2011/01/24/asynchronous-control-updates-in-c-net-winforms/
|
||||
/// </summary>
|
||||
public static class EmControl
|
||||
{
|
||||
public static void Do<TControl>(this TControl control, Action<TControl> action)
|
||||
where TControl : Control
|
||||
{
|
||||
try
|
||||
{
|
||||
if (control.InvokeRequired)
|
||||
{
|
||||
try
|
||||
{
|
||||
control.Invoke(action, control);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ex is ObjectDisposedException)
|
||||
Trace.WriteLine(ex);
|
||||
else
|
||||
throw;
|
||||
}
|
||||
}
|
||||
else if (control.IsHandleCreated)
|
||||
action(control);
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Error : Before windows handle created.. 창 핸들을 만들기 전까지는....");
|
||||
Trace.WriteLine("Error : Before windows handle created.. 창 핸들을 만들기 전까지는....");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Trace.WriteLine($"Exception on Control.Do(): {ex}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Control.Invoke is synchronous
|
||||
/// </summary>
|
||||
/// <param name="control"></param>
|
||||
/// <param name="action"></param>
|
||||
public static void Do(this Control control, Action action)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (control.InvokeRequired)
|
||||
{
|
||||
try
|
||||
{
|
||||
control.Invoke(action);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ex is ObjectDisposedException)
|
||||
Trace.WriteLine(ex);
|
||||
else
|
||||
throw;
|
||||
}
|
||||
}
|
||||
else if (control.IsHandleCreated)
|
||||
action();
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Error : Before windows handle created (2).. 창 핸들을 만들기 전까지는....");
|
||||
Trace.WriteLine("Error : Before windows handle created (2).. 창 핸들을 만들기 전까지는....");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Trace.WriteLine($"Exception on Control.Do(): {ex}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void Do(this SynchronizationContext context, Action action)
|
||||
{
|
||||
context.Send(ignore => { action(); }, null);
|
||||
}
|
||||
public static void DoAsync(this SynchronizationContext context, Action action)
|
||||
{
|
||||
context.Post(ignore => { action(); }, null);
|
||||
}
|
||||
|
||||
public static SynchronizationContext GetSynchronizationContext(this Control control)
|
||||
{
|
||||
SynchronizationContext context = null;
|
||||
control.Do(() =>
|
||||
{
|
||||
context = SynchronizationContext.Current;
|
||||
});
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
public static TaskScheduler GetTaskScheduler(this Control control)
|
||||
{
|
||||
TaskScheduler scheduler = null;
|
||||
control.Do(() =>
|
||||
{
|
||||
scheduler = TaskScheduler.FromCurrentSynchronizationContext();
|
||||
});
|
||||
|
||||
return scheduler;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// form 에 대해서, 아직 창 핸들이 만들어 지지 않은 경우, form 이 보여진 후에 해당 action 을 수행한다.
|
||||
/// </summary>
|
||||
/// <param name="form"></param>
|
||||
/// <param name="action"></param>
|
||||
public static void DoNowOrLater(this Form form, Action action)
|
||||
{
|
||||
if (form.InvokeRequired)
|
||||
form.Invoke(action);
|
||||
else if (form.IsHandleCreated)
|
||||
action();
|
||||
else
|
||||
form.Shown += (sender, args) => { action(); };
|
||||
}
|
||||
|
||||
public static async Task DoAsync(this Control control, Action action)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (control.InvokeRequired)
|
||||
await Task.Factory.FromAsync(control.BeginInvoke(action), result => { });
|
||||
else if (control.IsHandleCreated)
|
||||
action();
|
||||
else
|
||||
Console.WriteLine("Error : 창 핸들을 만들기 전까지는....");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Trace.WriteLine($"Exception on Control.Do(): {ex}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// How to get return value when BeginInvoke/Invoke is called in C#
|
||||
/// http://stackoverflow.com/questions/2214002/how-to-get-return-value-when-begininvoke-invoke-is-called-in-c-sharp
|
||||
/// </summary>
|
||||
public static T DoGet<T>(this Control control, Func<T> func)
|
||||
{
|
||||
if (control.InvokeRequired)
|
||||
return (T)control.Invoke(func);
|
||||
|
||||
return func();
|
||||
}
|
||||
|
||||
public static IEnumerable<Control> CollectAncestors(this Control control, bool includeMe = false)
|
||||
{
|
||||
if (includeMe)
|
||||
yield return control;
|
||||
if (control == null || control.Parent == null)
|
||||
yield break;
|
||||
|
||||
foreach (var ancestor in control.Parent.CollectAncestors(true))
|
||||
yield return ancestor;
|
||||
}
|
||||
|
||||
public static IEnumerable<Control> CollectAncestorsTo(this Control control, Control stopAncestorControl,
|
||||
bool includeMe = false)
|
||||
{
|
||||
if (includeMe)
|
||||
yield return control;
|
||||
|
||||
if (control == stopAncestorControl || control.Parent == null)
|
||||
yield break;
|
||||
|
||||
foreach (var ancestor in control.Parent.CollectAncestorsTo(stopAncestorControl, true))
|
||||
yield return ancestor;
|
||||
}
|
||||
|
||||
|
||||
public static IEnumerable<Control> CollectChildren(this Control control, bool includeMe = false)
|
||||
{
|
||||
if (includeMe)
|
||||
yield return control;
|
||||
|
||||
foreach (var child in control.Controls.Cast<Control>())
|
||||
{
|
||||
foreach (var descendant in child.CollectChildren(true))
|
||||
yield return descendant;
|
||||
}
|
||||
|
||||
if (control is TabControl)
|
||||
{
|
||||
var tab = (TabControl) control;
|
||||
foreach (var page in tab.TabPages.Cast<TabPage>())
|
||||
{
|
||||
foreach (var descendant in page.CollectChildren(true))
|
||||
{
|
||||
yield return descendant;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static IEnumerable<T> CollectChildren<T>(this Control control, bool includeMe = false) where T : Control
|
||||
{
|
||||
return control.CollectChildren(includeMe).OfType<T>();
|
||||
|
||||
//if (includeMe && control is T)
|
||||
// yield return control as T;
|
||||
|
||||
//foreach (var child in control.Controls.Cast<Control>())
|
||||
//{
|
||||
// foreach (var descendant in child.CollectChildren<T>(true))
|
||||
// yield return descendant;
|
||||
//}
|
||||
|
||||
//if (control is TabControl)
|
||||
//{
|
||||
// var tab = (TabControl)control;
|
||||
// foreach (var page in tab.TabPages.Cast<TabPage>())
|
||||
// {
|
||||
// foreach (var descendant in page.CollectChildren<T>(true))
|
||||
// {
|
||||
// yield return descendant;
|
||||
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// reference 의 LT 좌표 기준으로, control 의 LT 좌표의 offset 값을 반환한다.
|
||||
/// </summary>
|
||||
/// <param name="control"></param>
|
||||
/// <param name="reference"></param>
|
||||
/// <returns></returns>
|
||||
public static Point GetRelativePoint(this Control control, Control reference)
|
||||
{
|
||||
return reference.PointToClient(control.PointToScreen(control.Location));
|
||||
}
|
||||
|
||||
public static Rectangle GetRelativeRectangle(this Control control, Control reference)
|
||||
{
|
||||
return reference.RectangleToClient(control.RectangleToScreen(control.ClientRectangle));
|
||||
}
|
||||
|
||||
public static void SetBackgroundImage(this Control control, Image image)
|
||||
{
|
||||
if (control.BackgroundImage != null)
|
||||
control.BackgroundImage.Dispose();
|
||||
|
||||
control.BackgroundImage = image;
|
||||
}
|
||||
|
||||
public static void MakeTransparent(this Control control)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (control is Button)
|
||||
((Button) control).FlatStyle = FlatStyle.Flat;
|
||||
|
||||
control.ForceMakeTransparent();
|
||||
control.BackColor = Color.Transparent;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// http://solvedstack.com/questions/transparency-for-windows-forms-textbox
|
||||
/// <c>
|
||||
/// bool itWorked = SetStyle(xControl, ControlStyles.SupportsTransparentBackColor, true);
|
||||
/// </c>
|
||||
/// </summary>
|
||||
/// <param name="control"></param>
|
||||
/// <param name="style"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static bool ForceSetStyle(this Control control, ControlStyles style, bool value)
|
||||
{
|
||||
Type typeTB = typeof (Control);
|
||||
System.Reflection.MethodInfo misSetStyle = typeTB.GetMethod("SetStyle",
|
||||
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
|
||||
if (misSetStyle != null && control != null)
|
||||
{
|
||||
misSetStyle.Invoke(control, new object[] {style, value});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool ForceMakeTransparent(this Control control, bool transparent = true)
|
||||
{
|
||||
return control.ForceSetStyle(ControlStyles.SupportsTransparentBackColor, transparent);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// http://stackoverflow.com/questions/435433/what-is-the-preferred-way-to-find-focused-control-in-winforms-app
|
||||
/// </summary>
|
||||
/// <param name="control"></param>
|
||||
/// <returns></returns>
|
||||
public static Control FindFocusedControl(this Control control)
|
||||
{
|
||||
var container = control as IContainerControl;
|
||||
while (container != null)
|
||||
{
|
||||
control = container.ActiveControl;
|
||||
container = control as IContainerControl;
|
||||
}
|
||||
return control;
|
||||
}
|
||||
|
||||
|
||||
// http://stackoverflow.com/questions/4747935/c-sharp-winform-check-if-control-is-physicaly-visible
|
||||
[DllImport("user32.dll")]
|
||||
static extern IntPtr WindowFromPoint(POINT Point);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct POINT
|
||||
{
|
||||
public int X;
|
||||
public int Y;
|
||||
|
||||
public POINT(int x, int y) { X = x; Y = y; }
|
||||
public static implicit operator Point(POINT p) => new Point(p.X, p.Y);
|
||||
public static implicit operator POINT(Point p) => new POINT(p.X, p.Y);
|
||||
}
|
||||
|
||||
/// control 이 실제로 사용자에게 보이는지 여부를 반환
|
||||
public static bool IsControlVisibleToUser(this Control control)
|
||||
{
|
||||
return control.DoGet(() =>
|
||||
{
|
||||
if (!control.IsHandleCreated)
|
||||
return false;
|
||||
|
||||
var pos = control.PointToScreen(control.Location);
|
||||
var pointsToCheck = new POINT[] {
|
||||
pos,
|
||||
new Point(pos.X + control.Width - 1, pos.Y),
|
||||
new Point(pos.X, pos.Y + control.Height - 1),
|
||||
new Point(pos.X + control.Width - 1, pos.Y + control.Height - 1),
|
||||
new Point(pos.X + control.Width/2, pos.Y + control.Height/2),
|
||||
};
|
||||
|
||||
foreach (var p in pointsToCheck)
|
||||
{
|
||||
var hwnd = WindowFromPoint(p);
|
||||
var other = Control.FromChildHandle(hwnd);
|
||||
if (other == null)
|
||||
continue;
|
||||
|
||||
if (control == other || control.Contains(other))
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
#region Detect cursor
|
||||
//// http://stackoverflow.com/questions/586479/is-there-a-quick-way-to-get-the-control-thats-under-the-mouse
|
||||
//[DllImport("user32.dll")]
|
||||
//private static extern IntPtr WindowFromPoint(Point pnt);
|
||||
|
||||
//public static Control ControlUnderPoint(this Point pt)
|
||||
//{
|
||||
// IntPtr hWnd = WindowFromPoint(pt);
|
||||
// if (hWnd != IntPtr.Zero)
|
||||
// return Control.FromHandle(hWnd);
|
||||
|
||||
// return null;
|
||||
//}
|
||||
|
||||
//public static Control ControlUnderMouseCursor()
|
||||
//{
|
||||
// return Control.MousePosition.ControlUnderPoint();
|
||||
//}
|
||||
|
||||
/// <summary> Checks whether mouse is over given control </summary>
|
||||
public static bool IsMouseOver(this Control control)
|
||||
{
|
||||
return control.ClientRectangle.Contains(control.PointToClient(Cursor.Position));
|
||||
}
|
||||
|
||||
/// <summary> Collects controls under mouse cursor </summary>
|
||||
public static IEnumerable<Control> GetChildrenUnderMouse(this Control parent)
|
||||
{
|
||||
foreach (var c in parent.Controls.Cast<Control>())
|
||||
{
|
||||
if (c.IsMouseOver())
|
||||
yield return c;
|
||||
foreach (var cc in GetChildrenUnderMouse(c))
|
||||
yield return cc;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
/// Button 에 image 를 입힌다. text 는 왼쪽, image 는 오른쪽
|
||||
public static void AddImage(this Button button, Image image)
|
||||
{
|
||||
button.Image = image;
|
||||
button.ImageAlign = ContentAlignment.MiddleRight;
|
||||
button.TextAlign = ContentAlignment.MiddleLeft;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
using System;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.ExtensionMethods
|
||||
{
|
||||
public static class EmEventHandler
|
||||
{
|
||||
public static void Handle(this EventHandler eventHandler, object sender, EventArgs eventArgs)
|
||||
{
|
||||
var handler = eventHandler;
|
||||
if (handler != null)
|
||||
handler(sender, eventArgs);
|
||||
}
|
||||
|
||||
public static void Handle<T>(this EventHandler<T> eventHandler, object sender, T eventArgs)
|
||||
{
|
||||
var handler = eventHandler;
|
||||
if ( handler != null )
|
||||
handler(sender, eventArgs);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,133 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.ExtensionMethods
|
||||
{
|
||||
public static class EmGeneral
|
||||
{
|
||||
/// <summary>Indicates whether the specified array is null or has a length of zero.</summary>
|
||||
/// <param name="array">The array to test.</param>
|
||||
/// <returns>true if the array parameter is null or has a length of zero; otherwise, false.</returns>
|
||||
[Pure]
|
||||
public static bool IsNullOrEmpty(this Array array)
|
||||
{
|
||||
return (array == null || array.Length == 0);
|
||||
}
|
||||
|
||||
|
||||
[Pure]
|
||||
public static bool IsNullOrEmpty(this IEnumerable enumerable)
|
||||
{
|
||||
return (enumerable == null || enumerable.Cast<object>().Count() == 0);
|
||||
}
|
||||
|
||||
[Pure]
|
||||
public static bool NonNullAny<TSource>(this IEnumerable<TSource> source)
|
||||
{
|
||||
if (source == null)
|
||||
return false;
|
||||
return source.Any();
|
||||
}
|
||||
|
||||
[Pure]
|
||||
public static bool NonNullAny<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
|
||||
{
|
||||
if (source == null)
|
||||
return false;
|
||||
return source.Any(predicate);
|
||||
}
|
||||
|
||||
[Pure]
|
||||
public static int Clamp(this int val, int min, int max)
|
||||
{
|
||||
return val > max ? max : val < min ? min : val;
|
||||
}
|
||||
|
||||
public static double Clamp(this double val, double min, double max)
|
||||
{
|
||||
return val > max ? max : val < min ? min : val;
|
||||
}
|
||||
|
||||
[Pure]
|
||||
public static bool XOR(this bool val1, bool val2)
|
||||
{
|
||||
return (val1 && !val2) || (!val1 && val2);
|
||||
}
|
||||
|
||||
[Pure]
|
||||
public static bool XOR(this object obj1, object obj2)
|
||||
{
|
||||
return (obj1 != null && obj2 == null) || (obj1 == null && obj2 != null);
|
||||
}
|
||||
|
||||
[Pure]
|
||||
public static bool Toggle(this bool fact, bool toggle)
|
||||
{
|
||||
return toggle ? ! fact : fact;
|
||||
}
|
||||
|
||||
[Pure]
|
||||
public static string NonNullEmptySelector(this string str1, string str2)
|
||||
{
|
||||
return String.IsNullOrEmpty(str1) ? str2 : str1;
|
||||
}
|
||||
|
||||
|
||||
[Pure]
|
||||
public static bool NonNullEqual(this string str1, string str2)
|
||||
{
|
||||
return !String.IsNullOrEmpty(str1) && !String.IsNullOrEmpty(str2) && str1 == str2;
|
||||
}
|
||||
|
||||
[Pure]
|
||||
public static bool NullableEqual(this string str1, string str2)
|
||||
{
|
||||
return (str1.IsNullOrEmpty() && str2.IsNullOrEmpty()) || NonNullEqual(str1, str2);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static bool HasTrueValue(this Nullable<bool> nullable)
|
||||
{
|
||||
return nullable.HasValue && nullable.Value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// http://stackoverflow.com/questions/12447156/how-can-i-set-the-column-width-of-a-property-grid
|
||||
/// </summary>
|
||||
public static class PropertyGridColumnWidthSetter
|
||||
{
|
||||
public static void SetLabelColumnWidth(this PropertyGrid grid, int width)
|
||||
{
|
||||
if (grid == null)
|
||||
return;
|
||||
|
||||
FieldInfo fi = grid.GetType().GetField("gridView", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
if (fi == null)
|
||||
return;
|
||||
|
||||
Control view = fi.GetValue(grid) as Control;
|
||||
if (view == null)
|
||||
return;
|
||||
|
||||
MethodInfo mi = view.GetType().GetMethod("MoveSplitterTo", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
if (mi == null)
|
||||
return;
|
||||
mi.Invoke(view, new object[] {width});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,374 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.ExtensionMethods
|
||||
{
|
||||
/// <summary>
|
||||
/// Linq extension methods
|
||||
/// </summary>
|
||||
public static partial class EmLinq
|
||||
{
|
||||
// http://stackoverflow.com/questions/1883920/call-a-function-for-each-value-in-a-generic-c-sharp-collection
|
||||
/// <summary>
|
||||
/// Generic IEnumerable ForEach extension : typename T is optional. deducible from source
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="action"></param>
|
||||
|
||||
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
|
||||
{
|
||||
foreach (T item in source)
|
||||
action(item);
|
||||
}
|
||||
|
||||
public static void Iter<T>(this IEnumerable<T> source, Action<T> action) => ForEach(source, action);
|
||||
public static void Iter<T>(this IEnumerable<T> source, Action<T, int> action)
|
||||
{
|
||||
int i = 0;
|
||||
foreach (T item in source)
|
||||
action(item, i++);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lazy Foreach : Not evaluated until on demand
|
||||
/// </summary>
|
||||
public static IEnumerable<T> ForEachTee<T>(this IEnumerable<T> source, Action<T> action)
|
||||
{
|
||||
foreach (T item in source)
|
||||
{
|
||||
action(item);
|
||||
yield return item;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Non-Generic IEnumerable ForEach extension : typename T should be provided.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="action"></param>
|
||||
public static void ForEach<T>(this IEnumerable source, Action<T> action)
|
||||
{
|
||||
foreach (T item in source)
|
||||
action(item);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Non-Generic IEnumerable ForEach extension : typename T should be provided.
|
||||
/// Lazy Foreach : Not evaluated until on demand
|
||||
/// </summary>
|
||||
public static IEnumerable ForEachTee<T>(this IEnumerable source, Action<T> action)
|
||||
{
|
||||
foreach (T item in source)
|
||||
{
|
||||
action(item);
|
||||
yield return item;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Non-Generic IEnumerable Select extension : typename T should be provided.
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <typeparam name="TResult"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="selector"></param>
|
||||
/// <returns></returns>
|
||||
public static IEnumerable<TResult> SelectEx<TSource, TResult>(this IEnumerable source, Func<TSource, TResult> selector)
|
||||
{
|
||||
foreach (TSource item in source)
|
||||
yield return selector(item);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TResult type 의 enumerable 중에서 TNotCheckType type 이 아닌 것들만 골라서 반환한다. (System.Linq.OfType 의 negation)
|
||||
/// <para/> System.Linq.SkipWhile() 구문과 같은 역할
|
||||
/// <para/> TNotCheck 는 TResult type 이어야 함.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResult">enumerable 들의 base type. 동시에 반환될 enumerable 의 type</typeparam>
|
||||
/// <typeparam name="TNotCheckType">제외할 type</typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static IEnumerable<TResult> OfNotType<TResult, TNotCheckType>(this IEnumerable source) where TNotCheckType : TResult
|
||||
{
|
||||
if (source == null) throw new ArgumentNullException("source");
|
||||
return OfNotTypeIterator<TResult, TNotCheckType>(source);
|
||||
}
|
||||
|
||||
|
||||
private static IEnumerable<TResult> OfNotTypeIterator<TResult, TNotCheckType>(IEnumerable source)
|
||||
{
|
||||
foreach (object obj in source)
|
||||
{
|
||||
if (!(obj is TNotCheckType))
|
||||
yield return (TResult)obj;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Select Non null element from enumerable
|
||||
/// </summary>
|
||||
public static IEnumerable<TResult> OfNotNull<TResult>(this IEnumerable<TResult> source) where TResult : class
|
||||
{
|
||||
if (source == null) throw new ArgumentNullException("source");
|
||||
foreach (var s in source)
|
||||
{
|
||||
if ( s != null )
|
||||
yield return s;
|
||||
}
|
||||
}
|
||||
|
||||
// http://stackoverflow.com/questions/2471588/how-to-get-index-using-linq
|
||||
public static Nullable<int> FindIndex<T>(this IEnumerable<T> items, Predicate<T> predicate)
|
||||
{
|
||||
int index = 0;
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (predicate(item))
|
||||
return index;
|
||||
index++;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> items)
|
||||
{
|
||||
var hash = new HashSet<T>();
|
||||
items.ForEach(i => hash.Add(i));
|
||||
return hash;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 두개의 set 이 동일한지 비교. see SequenceEqual
|
||||
/// </summary>
|
||||
public static bool SetEqual<T>(this IEnumerable<T> first, IEnumerable<T> second)
|
||||
{
|
||||
HashSet<T> firstSet = first.ToHashSet();
|
||||
foreach (var e in second)
|
||||
{
|
||||
if (!firstSet.Contains(e))
|
||||
return false;
|
||||
}
|
||||
|
||||
HashSet<T> secondSet = second.ToHashSet();
|
||||
foreach (var e in first)
|
||||
{
|
||||
if (!secondSet.Contains(e))
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public static bool RemoveTail(this IList list)
|
||||
{
|
||||
if (list.IsNullOrEmpty())
|
||||
return false;
|
||||
|
||||
list.RemoveAt(list.Count - 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static T[] ConcatArrays<T>(params T[][] list)
|
||||
{
|
||||
var result = new T[list.Sum(a => a.Length)];
|
||||
int offset = 0;
|
||||
for (int x = 0; x < list.Length; x++)
|
||||
{
|
||||
list[x].CopyTo(result, offset);
|
||||
offset += list[x].Length;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
private static Tuple<bool, T> ExtractFirst<T>(this IEnumerable<T> seq)
|
||||
{
|
||||
using (var enumerator = seq.GetEnumerator())
|
||||
{
|
||||
if (enumerator.MoveNext())
|
||||
return Tuple.Create(true, enumerator.Current); // => return new Tuple<bool, T>(..) 와 동일
|
||||
|
||||
return Tuple.Create(false, default(T));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// http://stackoverflow.com/questions/4354902/check-that-all-items-of-ienumerablet-has-the-same-value-using-linq
|
||||
/// </summary>
|
||||
public static bool AllEqual<T>(this IEnumerable<T> source, T target)
|
||||
{
|
||||
using (var enumerator = source.GetEnumerator())
|
||||
{
|
||||
if (!enumerator.MoveNext())
|
||||
{
|
||||
// empty case
|
||||
return true;
|
||||
}
|
||||
|
||||
var comparer = EqualityComparer<T>.Default;
|
||||
|
||||
do
|
||||
{
|
||||
if (!comparer.Equals(target, enumerator.Current))
|
||||
return false;
|
||||
} while (enumerator.MoveNext());
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool AllEqual<T>(this IEnumerable<T> source)
|
||||
{
|
||||
var pr = source.ExtractFirst();
|
||||
if (pr.Item1)
|
||||
return AllEqual(source, pr.Item2);
|
||||
|
||||
// empty case
|
||||
return true;
|
||||
}
|
||||
|
||||
public static T Tee<T>(this T input, Action action)
|
||||
{
|
||||
action();
|
||||
return input;
|
||||
}
|
||||
public static T Tee<T>(this T input, Action<T> action)
|
||||
{
|
||||
action(input);
|
||||
return input;
|
||||
}
|
||||
|
||||
public static bool ForAll<T>(this IEnumerable<T> source, Func<T, bool> predicate)
|
||||
{
|
||||
foreach (var s in source)
|
||||
{
|
||||
if (!predicate(s))
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool ForAll<T>(this IEnumerable<T> source, Func<T, int, bool> predicate)
|
||||
{
|
||||
int i = 0;
|
||||
foreach (var s in source)
|
||||
{
|
||||
if (!predicate(s, i++))
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public static bool NoForAll<T>(this IEnumerable<T> source, Func<T, bool> predicate)
|
||||
{
|
||||
foreach (var s in source)
|
||||
{
|
||||
if (predicate(s))
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// source 를 n 개씩 분할한 sequence 를 반환
|
||||
/// http://stackoverflow.com/questions/419019/split-list-into-sublists-with-linq
|
||||
/// </summary>
|
||||
public static IEnumerable<IEnumerable<T>> SplitByN<T>(this IEnumerable<T> source, int n)
|
||||
{
|
||||
return source
|
||||
.Select((x, i) => new { Index = i, Value = x })
|
||||
.GroupBy(x => x.Index / n)
|
||||
.Select(x => x.Select(v => v.Value))
|
||||
;
|
||||
}
|
||||
|
||||
public static IEnumerable<T> EveryNth<T>(this IEnumerable<T> source, int n)
|
||||
{
|
||||
return source.Where((v, i) => i % n == 0);
|
||||
}
|
||||
|
||||
|
||||
public static IEnumerable<TResult> Zip2<TS1, TS2, TResult>(
|
||||
this IEnumerable<TS1> s1,
|
||||
IEnumerable<TS2> s2,
|
||||
Func<TS1, TS2, TResult> resultSelector) => s1.Zip(s2, resultSelector);
|
||||
|
||||
public static IEnumerable<TResult> Zip3<TS1, TS2, TS3, TResult>(
|
||||
this IEnumerable<TS1> s1,
|
||||
IEnumerable<TS2> s2,
|
||||
IEnumerable<TS3> s3,
|
||||
Func<TS1, TS2, TS3, TResult> resultSelector)
|
||||
{
|
||||
using (var e1 = s1.GetEnumerator())
|
||||
using (var e2 = s2.GetEnumerator())
|
||||
using (var e3 = s3.GetEnumerator())
|
||||
{
|
||||
while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext())
|
||||
yield return resultSelector(e1.Current, e2.Current, e3.Current);
|
||||
}
|
||||
}
|
||||
|
||||
public static IEnumerable<TResult> Zip4<TS1, TS2, TS3, TS4, TResult>(
|
||||
this IEnumerable<TS1> s1,
|
||||
IEnumerable<TS2> s2,
|
||||
IEnumerable<TS3> s3,
|
||||
IEnumerable<TS4> s4,
|
||||
Func<TS1, TS2, TS3, TS4, TResult> resultSelector)
|
||||
{
|
||||
using (var e1 = s1.GetEnumerator())
|
||||
using (var e2 = s2.GetEnumerator())
|
||||
using (var e3 = s3.GetEnumerator())
|
||||
using (var e4 = s4.GetEnumerator())
|
||||
{
|
||||
while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext() && e4.MoveNext())
|
||||
yield return resultSelector(e1.Current, e2.Current, e3.Current, e4.Current);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static IEnumerable<int> MinMaxRange(int min, int hop, int max)
|
||||
{
|
||||
if (hop <= 0)
|
||||
throw new ArgumentException("hop counter should be positive.");
|
||||
|
||||
for (int i = min; i <= max; i += hop)
|
||||
yield return i;
|
||||
}
|
||||
|
||||
public static IEnumerable<int> MinMaxRange(int min, int max) => Enumerable.Range(min, max - min);
|
||||
|
||||
public static IEnumerable<string> HexRange(int start, int count)
|
||||
{
|
||||
foreach (var h in Enumerable.Range(start, count))
|
||||
{
|
||||
yield return $"{h:X}";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Enumerable 의 laziness 를 강제로 실행시켜 evaluation 시킴.
|
||||
/// </summary>
|
||||
public static IEnumerable<T> Realize<T>(this IEnumerable<T> seq)
|
||||
{
|
||||
//var count = seq.Count(); // count 만으로는, 즉석 evaluation 이 안되는 경우가 존재...???...
|
||||
var array = seq.ToArray();
|
||||
return array;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,771 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.IO;
|
||||
using System.IO.MemoryMappedFiles;
|
||||
using System.Threading;
|
||||
using System.Runtime.InteropServices;
|
||||
using SystemX.Net.BaseProtocol;
|
||||
using SystemX.Common.Serialization;
|
||||
using static SystemX.Net.Platform.Common.Util.LogMessage;
|
||||
|
||||
namespace SystemX.Net.Platform.SystemX.Common
|
||||
{
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1), Serializable]
|
||||
public struct InfoLogMappedPacket
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024, ArraySubType = UnmanagedType.Bool)]
|
||||
public bool[] bLogDataReady;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1), Serializable]
|
||||
public struct LogMappedPacket
|
||||
{
|
||||
//Use State
|
||||
[MarshalAs(UnmanagedType.Bool)]
|
||||
public bool bSectionUse;
|
||||
|
||||
//Host
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_16[] objLogType;
|
||||
|
||||
//This File Process Result 1
|
||||
[MarshalAs(UnmanagedType.Bool)]
|
||||
public bool bLogFileReadComplete;
|
||||
|
||||
//This File Process Result 2
|
||||
[MarshalAs(UnmanagedType.Bool)]
|
||||
public bool bLogFileProcessComplete;
|
||||
|
||||
//Number
|
||||
[MarshalAs(UnmanagedType.I4)]
|
||||
public int nNumber;
|
||||
|
||||
//Use Log Process Time
|
||||
[MarshalAs(UnmanagedType.Bool)]
|
||||
public bool bShowCpLogProcessTime;
|
||||
|
||||
//COMMAND 포트 번호
|
||||
[MarshalAs(UnmanagedType.I4)]
|
||||
public int nCommandPort;
|
||||
|
||||
//STREAM 포트 번호
|
||||
[MarshalAs(UnmanagedType.I4)]
|
||||
public int nStreamPort;
|
||||
|
||||
//Station ID
|
||||
[MarshalAs(UnmanagedType.I4)]
|
||||
public int nStationID;
|
||||
|
||||
//Host
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_64[] objHost;
|
||||
|
||||
//Section
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_64[] objSection;
|
||||
|
||||
//Option File Name
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_64[] objOptionFileName;
|
||||
|
||||
//Option File Name
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_16[] objOptionFileExtension;
|
||||
|
||||
//Station Name
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_64[] objStationName;
|
||||
|
||||
//Prod P
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_16[] objProdPNo;
|
||||
|
||||
//Prod C
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_16[] objProdCNo;
|
||||
|
||||
//Test Type
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_16[] objTestType;
|
||||
|
||||
//Test Code
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_16[] objTestCode;
|
||||
|
||||
//Version
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_16[] objVersion;
|
||||
|
||||
//Prod Code
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_16[] objProdCode;
|
||||
|
||||
//Test List Variant No
|
||||
[MarshalAs(UnmanagedType.I4)]
|
||||
public int nTestListVariantNo;
|
||||
|
||||
//Test List Load Cnt ID
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_256[] objResultTestListCntID;
|
||||
|
||||
public byte[] Data() { return ucLogData; }
|
||||
|
||||
//Test List Variant No
|
||||
[MarshalAs(UnmanagedType.I4)]
|
||||
public int nLogDataSize;
|
||||
|
||||
//Log File 1MB 까지
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024000, ArraySubType = UnmanagedType.U1)]
|
||||
public byte[] ucLogData;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
public class CMapParameter
|
||||
{
|
||||
public string strSetEnterMutexName;
|
||||
public string strSetAccessMutexName;
|
||||
public string strSetPath;
|
||||
public string strSetFileName;
|
||||
public string strSetMapName;
|
||||
}
|
||||
|
||||
public class SharedMemory
|
||||
{
|
||||
//Keep the mutex as static to prevent early garbage collection
|
||||
public const int nMaxStationSize = 8;
|
||||
|
||||
//Keep the mutex as static to prevent early garbage collection
|
||||
public const int nMaxInfoFullAccessSize = 1024;
|
||||
|
||||
protected byte[] ucCurrentArr;
|
||||
protected int nSize;
|
||||
|
||||
private bool bDisposed;
|
||||
|
||||
protected CMapParameter ParameterMap;
|
||||
|
||||
public SharedMemory(CMapParameter SetParameter)
|
||||
{
|
||||
bDisposed = false;
|
||||
|
||||
ParameterMap = new CMapParameter();
|
||||
ParameterMap.strSetEnterMutexName = SetParameter.strSetEnterMutexName;
|
||||
ParameterMap.strSetAccessMutexName = SetParameter.strSetAccessMutexName;
|
||||
ParameterMap.strSetPath = SetParameter.strSetPath;
|
||||
ParameterMap.strSetFileName = SetParameter.strSetFileName;
|
||||
ParameterMap.strSetMapName = SetParameter.strSetMapName;
|
||||
}
|
||||
|
||||
protected byte[] StructToByte(object obj)
|
||||
{
|
||||
int size = Marshal.SizeOf(obj);
|
||||
byte[] arr = new byte[size];
|
||||
IntPtr ptr = Marshal.AllocHGlobal(size);
|
||||
Marshal.StructureToPtr(obj, ptr, true);
|
||||
Marshal.Copy(ptr, arr, 0, size);
|
||||
Marshal.FreeHGlobal(ptr);
|
||||
|
||||
return arr;
|
||||
}
|
||||
|
||||
protected T ByteToStruct<T>(byte[] buffer) where T : struct
|
||||
{
|
||||
int size = Marshal.SizeOf(typeof(T));
|
||||
|
||||
if (size > buffer.Length)
|
||||
throw new Exception();
|
||||
|
||||
IntPtr ptr = Marshal.AllocHGlobal(size);
|
||||
Marshal.Copy(buffer, 0, ptr, size);
|
||||
T obj = (T)Marshal.PtrToStructure(ptr, typeof(T));
|
||||
Marshal.FreeHGlobal(ptr);
|
||||
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
public class LogSharedMemory : SharedMemory, IDisposable
|
||||
{
|
||||
//private static object _numLock;
|
||||
|
||||
//private static Mutex _mutex;
|
||||
private static Mutex _mutexSub;
|
||||
|
||||
private bool bDisposed;
|
||||
|
||||
public LogSharedMemory(CMapParameter SetParameter) : base(SetParameter)
|
||||
{
|
||||
bDisposed = false;
|
||||
}
|
||||
|
||||
static LogSharedMemory()
|
||||
{
|
||||
}
|
||||
|
||||
public void Set(int nPos, LogMappedPacket value)
|
||||
{
|
||||
bool bSubMutexResult = true;
|
||||
|
||||
try
|
||||
{
|
||||
if (!Mutex.TryOpenExisting(ParameterMap.strSetAccessMutexName + nPos.ToString("D03"), out _mutexSub))
|
||||
{
|
||||
_mutexSub = new Mutex(true, ParameterMap.strSetAccessMutexName + nPos.ToString("D03"));
|
||||
}
|
||||
else
|
||||
{
|
||||
bSubMutexResult = _mutexSub.WaitOne();
|
||||
|
||||
if (bSubMutexResult == false)
|
||||
throw new Exception("LogSharedMemory.Set failed Mutex WaitOne().");
|
||||
}
|
||||
//
|
||||
try
|
||||
{
|
||||
ucCurrentArr = StructToByte(value);
|
||||
nSize = ucCurrentArr.Count();
|
||||
|
||||
//access memory mapped file (need persistence)
|
||||
using (var memMapFile = MemoryMappedFile.CreateFromFile(
|
||||
@ParameterMap.strSetPath + ParameterMap.strSetFileName + nPos.ToString("D03"), //file location
|
||||
FileMode.OpenOrCreate, //create new file if not exist, open if exist
|
||||
ParameterMap.strSetMapName + nPos.ToString("D03"), //map name
|
||||
nSize * nMaxStationSize)) //size
|
||||
{
|
||||
//update the number to memory view
|
||||
using (var stream = memMapFile.CreateViewStream())
|
||||
using (var writer = new BinaryWriter(stream))
|
||||
{
|
||||
writer.Seek(value.nStationID * nSize, SeekOrigin.Begin);
|
||||
|
||||
writer.Write(ucCurrentArr);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + " [SystemX.Net.Platform.SystemX.Common : LogSharedMemory.Set[1]] " + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
finally
|
||||
{
|
||||
//release the mutex for other process to access the memory mapped file
|
||||
if (bSubMutexResult)
|
||||
{
|
||||
if (_mutexSub != null)
|
||||
_mutexSub.ReleaseMutex();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + " [SystemX.Net.Platform.SystemX.Common : LogSharedMemory.Set[2]] " + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
finally
|
||||
{
|
||||
//release the mutex for other process to access the memory mapped file
|
||||
//if (_mutex != null)
|
||||
// _mutex.ReleaseMutex();
|
||||
}
|
||||
}
|
||||
|
||||
public bool CheckFile(int nPos)
|
||||
{
|
||||
bool bCheckResult = false;
|
||||
|
||||
bool bSubMutexResult = true;
|
||||
|
||||
try
|
||||
{
|
||||
if (!Mutex.TryOpenExisting(ParameterMap.strSetAccessMutexName + nPos.ToString("D03"), out _mutexSub))
|
||||
{
|
||||
_mutexSub = new Mutex(true, ParameterMap.strSetAccessMutexName + nPos.ToString("D03"));
|
||||
}
|
||||
else
|
||||
{
|
||||
bSubMutexResult = _mutexSub.WaitOne(100);
|
||||
|
||||
if (bSubMutexResult == false)
|
||||
throw new Exception("LogSharedMemory.CheckFile failed Mutex WaitOne().");
|
||||
}
|
||||
//
|
||||
if (File.Exists(@ParameterMap.strSetPath + ParameterMap.strSetFileName + nPos.ToString("D03")))
|
||||
bCheckResult = true;
|
||||
else
|
||||
bCheckResult = false;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + " [SystemX.Net.Platform.SystemX.Common : LogSharedMemory.CheckFile] " + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
|
||||
bCheckResult = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
//release the mutex for other process to access the memory mapped file
|
||||
if (bSubMutexResult)
|
||||
{
|
||||
if (_mutexSub != null)
|
||||
_mutexSub.ReleaseMutex();
|
||||
}
|
||||
}
|
||||
|
||||
return bCheckResult;
|
||||
}
|
||||
public LogMappedPacket? Get(int nPos, int nStPos, out bool bFindProcessNeedLogResult, int nSetSize = int.MinValue)
|
||||
{
|
||||
LogMappedPacket? GetMappedFile = null;
|
||||
|
||||
bFindProcessNeedLogResult = false;
|
||||
|
||||
byte[] ucGetArr = null;
|
||||
|
||||
bool bSubMutexResult = true;
|
||||
|
||||
try
|
||||
{
|
||||
if (!Mutex.TryOpenExisting(ParameterMap.strSetAccessMutexName + nPos.ToString("D03"), out _mutexSub))
|
||||
{
|
||||
_mutexSub = new Mutex(true, ParameterMap.strSetAccessMutexName + nPos.ToString("D03"));
|
||||
}
|
||||
else
|
||||
{
|
||||
bSubMutexResult = _mutexSub.WaitOne();
|
||||
|
||||
if (bSubMutexResult == false)
|
||||
throw new Exception("LogSharedMemory.Get failed Mutex WaitOne().");
|
||||
}
|
||||
//
|
||||
try
|
||||
{
|
||||
if (nSetSize != int.MinValue)
|
||||
nSize = nSetSize;
|
||||
|
||||
//access memory mapped file (need persistence)
|
||||
using (var memMapFile = MemoryMappedFile.CreateFromFile(
|
||||
@ParameterMap.strSetPath + ParameterMap.strSetFileName + nPos.ToString("D03"), //file location
|
||||
FileMode.Open, //create new file if not exist, open if exist
|
||||
ParameterMap.strSetMapName + nPos.ToString("D03"), //map name
|
||||
nSize * nMaxStationSize)) //size
|
||||
{
|
||||
//get last number from memory view
|
||||
using (var stream = memMapFile.CreateViewStream())
|
||||
using (var reader = new BinaryReader(stream))
|
||||
{
|
||||
stream.Seek(nStPos * nSize, SeekOrigin.Begin);
|
||||
|
||||
ucGetArr = reader.ReadBytes(nSize);
|
||||
|
||||
GetMappedFile = ByteToStruct<LogMappedPacket>(ucGetArr);
|
||||
|
||||
if (GetMappedFile.Value.bSectionUse)
|
||||
{
|
||||
if (GetMappedFile.Value.bLogFileReadComplete == false)
|
||||
bFindProcessNeedLogResult = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + " [SystemX.Net.Platform.SystemX.Common : LogSharedMemory.Get[1]] " + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
finally
|
||||
{
|
||||
/*if (File.Exists(@"D:\CpServerXLogSharedMemoryMap" + nPos.ToString("D03")))
|
||||
File.Delete(@"D:\CpServerXLogSharedMemoryMap" + nPos.ToString("D03"));*/
|
||||
|
||||
//release the mutex for other process to access the memory mapped file
|
||||
if (bSubMutexResult)
|
||||
{
|
||||
if (_mutexSub != null)
|
||||
_mutexSub.ReleaseMutex();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + " [SystemX.Net.Platform.SystemX.Common : LogSharedMemory.Get[2]] " + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
finally
|
||||
{
|
||||
//release the mutex for other process to access the memory mapped file
|
||||
/*
|
||||
if (_mutex != null)
|
||||
_mutex.ReleaseMutex();
|
||||
*/
|
||||
}
|
||||
|
||||
return GetMappedFile;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!bDisposed)
|
||||
{
|
||||
//Manage
|
||||
|
||||
//Unmanage
|
||||
//
|
||||
if (_mutexSub != null)
|
||||
{
|
||||
_mutexSub.Dispose();
|
||||
_mutexSub = null;
|
||||
}
|
||||
|
||||
bDisposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
public class InfoLogSharedMemory : SharedMemory, IDisposable
|
||||
{
|
||||
private static Mutex _mutex;
|
||||
private static Mutex _mutexSub;
|
||||
|
||||
//private static object _numLock;
|
||||
|
||||
private bool bDisposed;
|
||||
|
||||
public InfoLogSharedMemory(CMapParameter SetParameter) : base(SetParameter)
|
||||
{
|
||||
bDisposed = false;
|
||||
}
|
||||
|
||||
static InfoLogSharedMemory()
|
||||
{
|
||||
}
|
||||
|
||||
public void Set(InfoLogMappedPacket value)
|
||||
{
|
||||
bool bSubMutexResult = true;
|
||||
|
||||
try
|
||||
{
|
||||
if (!Mutex.TryOpenExisting(ParameterMap.strSetAccessMutexName, out _mutexSub))
|
||||
{
|
||||
_mutexSub = new Mutex(true, ParameterMap.strSetAccessMutexName);
|
||||
}
|
||||
else
|
||||
{
|
||||
bSubMutexResult = _mutexSub.WaitOne();
|
||||
|
||||
if (bSubMutexResult == false)
|
||||
throw new Exception("InfoLogSharedMemory.Set failed Mutex WaitOne().");
|
||||
}
|
||||
//
|
||||
try
|
||||
{
|
||||
ucCurrentArr = StructToByte(value);
|
||||
nSize = ucCurrentArr.Count();
|
||||
|
||||
//access memory mapped file (need persistence)
|
||||
using (var memMapFile = MemoryMappedFile.CreateFromFile(
|
||||
@ParameterMap.strSetPath + ParameterMap.strSetFileName, //file location
|
||||
FileMode.OpenOrCreate, //create new file if not exist, open if exist
|
||||
ParameterMap.strSetMapName, //map name
|
||||
nSize)) //size
|
||||
{
|
||||
//update the number to memory view
|
||||
using (var stream = memMapFile.CreateViewStream())
|
||||
using (var writer = new BinaryWriter(stream))
|
||||
{
|
||||
writer.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
writer.Write(ucCurrentArr);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + " [SystemX.Net.Platform.SystemX.Common : InfoLogSharedMemory.Set InfoLogMappedPacket[1]] " + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
finally
|
||||
{
|
||||
//release the mutex for other process to access the memory mapped file
|
||||
if (bSubMutexResult)
|
||||
{
|
||||
if (_mutexSub != null)
|
||||
_mutexSub.ReleaseMutex();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + " [SystemX.Net.Platform.SystemX.Common : InfoLogSharedMemory.Set InfoLogMappedPacket[2]] " + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
finally
|
||||
{
|
||||
//release the mutex for other process to access the memory mapped file
|
||||
}
|
||||
}
|
||||
|
||||
public void Set(bool[] value)
|
||||
{
|
||||
bool bSubMutexResult = true;
|
||||
|
||||
try
|
||||
{
|
||||
if (!Mutex.TryOpenExisting(ParameterMap.strSetAccessMutexName, out _mutexSub))
|
||||
{
|
||||
_mutexSub = new Mutex(true, ParameterMap.strSetAccessMutexName);
|
||||
}
|
||||
else
|
||||
{
|
||||
bSubMutexResult = _mutexSub.WaitOne();
|
||||
|
||||
if (bSubMutexResult == false)
|
||||
throw new Exception("InfoLogSharedMemory.Set failed Mutex WaitOne().");
|
||||
}
|
||||
//
|
||||
try
|
||||
{
|
||||
InfoLogMappedPacket InfoLogMapFile = new InfoLogMappedPacket();
|
||||
int nSetSize = Marshal.SizeOf(InfoLogMapFile);
|
||||
byte[] ucSetLogArray = new byte[nSetSize];
|
||||
InfoLogMapFile = (InfoLogMappedPacket)SystemXNetSerialization.RawDeSerialize(ucSetLogArray, InfoLogMapFile.GetType());
|
||||
|
||||
Array.Copy(value, 0, InfoLogMapFile.bLogDataReady, 0, nMaxInfoFullAccessSize);
|
||||
|
||||
ucCurrentArr = StructToByte(InfoLogMapFile);
|
||||
nSize = ucCurrentArr.Count();
|
||||
|
||||
//access memory mapped file (need persistence)
|
||||
using (var memMapFile = MemoryMappedFile.CreateFromFile(
|
||||
@ParameterMap.strSetPath + ParameterMap.strSetFileName, //file location
|
||||
FileMode.OpenOrCreate, //create new file if not exist, open if exist
|
||||
ParameterMap.strSetMapName, //map name
|
||||
nSize)) //size
|
||||
{
|
||||
//update the number to memory view
|
||||
using (var stream = memMapFile.CreateViewStream())
|
||||
using (var writer = new BinaryWriter(stream))
|
||||
{
|
||||
writer.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
writer.Write(ucCurrentArr);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + " [SystemX.Net.Platform.SystemX.Common : InfoLogSharedMemory.Set bool[][1]] " + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
finally
|
||||
{
|
||||
//release the mutex for other process to access the memory mapped file
|
||||
if (bSubMutexResult)
|
||||
{
|
||||
if (_mutexSub != null)
|
||||
_mutexSub.ReleaseMutex();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + " [SystemX.Net.Platform.SystemX.Common : InfoLogSharedMemory.Set bool[][2]] " + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
finally
|
||||
{
|
||||
//release the mutex for other process to access the memory mapped file
|
||||
}
|
||||
}
|
||||
|
||||
public bool ForceCheckFile()
|
||||
{
|
||||
bool bCheckResult = false;
|
||||
|
||||
bool bSubMutexResult = true;
|
||||
|
||||
try
|
||||
{
|
||||
if (!Mutex.TryOpenExisting(ParameterMap.strSetAccessMutexName, out _mutexSub))
|
||||
{
|
||||
_mutexSub = new Mutex(true, ParameterMap.strSetAccessMutexName);
|
||||
}
|
||||
else
|
||||
{
|
||||
bSubMutexResult = _mutexSub.WaitOne();
|
||||
|
||||
if (bSubMutexResult == false)
|
||||
throw new Exception("InfoLogSharedMemory.CheckFile failed Mutex WaitOne().");
|
||||
}
|
||||
//
|
||||
if (File.Exists(@ParameterMap.strSetPath + ParameterMap.strSetFileName))
|
||||
bCheckResult = true;
|
||||
else
|
||||
bCheckResult = false;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + " [SystemX.Net.Platform.SystemX.Common : InfoLogSharedMemory.CheckFile] " + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
|
||||
bCheckResult = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
//release the mutex for other process to access the memory mapped file
|
||||
if (bSubMutexResult)
|
||||
{
|
||||
if (_mutexSub != null)
|
||||
_mutexSub.ReleaseMutex();
|
||||
}
|
||||
}
|
||||
|
||||
return bCheckResult;
|
||||
}
|
||||
|
||||
public bool CheckExistsInfoFile()
|
||||
{
|
||||
if (File.Exists(@ParameterMap.strSetPath + ParameterMap.strSetFileName))
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool CheckFile()
|
||||
{
|
||||
bool bCheckResult = false;
|
||||
|
||||
bool bSubMutexResult = true;
|
||||
|
||||
try
|
||||
{
|
||||
if (!Mutex.TryOpenExisting(ParameterMap.strSetAccessMutexName, out _mutexSub))
|
||||
{
|
||||
_mutexSub = new Mutex(true, ParameterMap.strSetAccessMutexName);
|
||||
}
|
||||
else
|
||||
{
|
||||
bSubMutexResult = _mutexSub.WaitOne(100);
|
||||
|
||||
if (bSubMutexResult == false)
|
||||
throw new Exception("InfoLogSharedMemory.CheckFile failed Mutex WaitOne().");
|
||||
}
|
||||
//
|
||||
if (File.Exists(@ParameterMap.strSetPath + ParameterMap.strSetFileName))
|
||||
bCheckResult = true;
|
||||
else
|
||||
bCheckResult = false;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + " [SystemX.Net.Platform.SystemX.Common : InfoLogSharedMemory.CheckFile] " + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
|
||||
bCheckResult = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
//release the mutex for other process to access the memory mapped file
|
||||
if (bSubMutexResult)
|
||||
{
|
||||
if (_mutexSub != null)
|
||||
_mutexSub.ReleaseMutex();
|
||||
}
|
||||
}
|
||||
|
||||
return bCheckResult;
|
||||
}
|
||||
|
||||
public bool[] Get(out bool bFindInfoLogResult, int nSetSize = int.MinValue)
|
||||
{
|
||||
bFindInfoLogResult = false;
|
||||
|
||||
bool[] bGetInfoLogStation = new bool[nMaxInfoFullAccessSize];
|
||||
|
||||
byte[] ucGetArr = null;
|
||||
|
||||
bool bSubMutexResult = true;
|
||||
|
||||
try
|
||||
{
|
||||
if (!Mutex.TryOpenExisting(ParameterMap.strSetAccessMutexName, out _mutexSub))
|
||||
{
|
||||
_mutexSub = new Mutex(true, ParameterMap.strSetAccessMutexName);
|
||||
}
|
||||
else
|
||||
{
|
||||
bSubMutexResult = _mutexSub.WaitOne();
|
||||
|
||||
if (bSubMutexResult == false)
|
||||
throw new Exception("InfoLogSharedMemory.Get failed Mutex WaitOne().");
|
||||
}
|
||||
//
|
||||
try
|
||||
{
|
||||
if (nSetSize != int.MinValue)
|
||||
nSize = nSetSize;
|
||||
|
||||
//access memory mapped file (need persistence)
|
||||
using (var memMapFile = MemoryMappedFile.CreateFromFile(
|
||||
@ParameterMap.strSetPath + ParameterMap.strSetFileName, //file location
|
||||
FileMode.Open, //create new file if not exist, open if exist
|
||||
ParameterMap.strSetMapName, //map name
|
||||
nSize)) //size
|
||||
{
|
||||
//get last number from memory view
|
||||
using (var stream = memMapFile.CreateViewStream())
|
||||
using (var reader = new BinaryReader(stream))
|
||||
{
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
ucGetArr = reader.ReadBytes(nSize);
|
||||
|
||||
InfoLogMappedPacket GetInfoMappedFile = ByteToStruct<InfoLogMappedPacket>(ucGetArr);
|
||||
|
||||
Array.Copy(GetInfoMappedFile.bLogDataReady, 0, bGetInfoLogStation, 0, nMaxInfoFullAccessSize);
|
||||
|
||||
bFindInfoLogResult = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + " [SystemX.Net.Platform.SystemX.Common : InfoLogSharedMemory.Get[1]] " + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
finally
|
||||
{
|
||||
/*if (File.Exists(@"D:\CpServerXLogSharedMemoryMap" + nPos.ToString("D03")))
|
||||
File.Delete(@"D:\CpServerXLogSharedMemoryMap" + nPos.ToString("D03"));*/
|
||||
|
||||
//release the mutex for other process to access the memory mapped file
|
||||
if (bSubMutexResult)
|
||||
{
|
||||
if (_mutexSub != null)
|
||||
_mutexSub.ReleaseMutex();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + " [SystemX.Net.Platform.SystemX.Common : InfoLogSharedMemory.Get[2]] " + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
finally
|
||||
{
|
||||
//release the mutex for other process to access the memory mapped file
|
||||
}
|
||||
|
||||
return bGetInfoLogStation;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!bDisposed)
|
||||
{
|
||||
//Manage
|
||||
//
|
||||
//Unmanag
|
||||
|
||||
if (_mutexSub != null)
|
||||
{
|
||||
_mutexSub.Dispose();
|
||||
_mutexSub = null;
|
||||
}
|
||||
|
||||
bDisposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -0,0 +1,216 @@
|
||||
using System;
|
||||
using System.CodeDom;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Remoting.Messaging;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Common.Archive;
|
||||
using SystemX.Common.Serialization;
|
||||
using SystemX.Net.BaseProtocol;
|
||||
using static SystemX.Net.Platform.Common.Util.LogMessage;
|
||||
|
||||
//STATIC 일반적으로 쓸 공용
|
||||
namespace SystemX.Common
|
||||
{
|
||||
public class ResultEventArgs : EventArgs
|
||||
{
|
||||
public bool bProcReuslt { get; set; }
|
||||
|
||||
public ResultEventArgs(bool bGetResult)
|
||||
{
|
||||
bProcReuslt = bGetResult;
|
||||
}
|
||||
~ResultEventArgs()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public class ScheduleEvent : EventArgs
|
||||
{
|
||||
public int CALL_NUMBER { get; set; }
|
||||
public bool PROCESS_RESULT { get; set; }
|
||||
public string STATE_MSG { get; set; }
|
||||
public byte nLABEL { get; set; }
|
||||
|
||||
public ScheduleEvent(int iCallNumer, bool bState, string strMsg, byte nLabel)
|
||||
{
|
||||
CALL_NUMBER = iCallNumer;
|
||||
|
||||
PROCESS_RESULT = bState;
|
||||
|
||||
STATE_MSG = strMsg;
|
||||
|
||||
nLABEL = nLabel;
|
||||
}
|
||||
|
||||
~ScheduleEvent()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public delegate void SendRecvCallEvent(byte[] sender, ScheduleEvent e);
|
||||
public delegate void SocketCallEvent(object sender, ScheduleEvent e);
|
||||
|
||||
//SystemXNetCommons
|
||||
public static partial class XCommons
|
||||
{
|
||||
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
|
||||
static extern int memcmp(byte[] b1, byte[] b2, long count);
|
||||
|
||||
public static bool ByteArrayCompare(byte[] ucArr1, byte[] ucArr2)
|
||||
{
|
||||
if (ucArr1 == null || ucArr2 == null)
|
||||
return false;
|
||||
if (ucArr1.Length != ucArr2.Length)
|
||||
return false;
|
||||
|
||||
// Validate buffers are the same length.
|
||||
// This also ensures that the count does not exceed the length of either buffer.
|
||||
return (memcmp(ucArr1, ucArr2, ucArr1.Length) == 0);
|
||||
}
|
||||
|
||||
|
||||
public const int PAD_SIZE = 12;
|
||||
private const int HEAD_SIZE = 8;
|
||||
private const int TAIL_SIZE = 4;
|
||||
|
||||
public static bool isHasRow(DataSet ds)
|
||||
{
|
||||
return (ds != null) ? ds.Tables.Cast<DataTable>().Any(table => table.Rows.Count != 0) : false;
|
||||
}
|
||||
|
||||
public static bool isHasRow(DataTable dt)
|
||||
{
|
||||
return (dt != null) ? dt.Rows.Count > 0 : false;
|
||||
}
|
||||
|
||||
//
|
||||
// 요약:
|
||||
// 패킷 압축 및 마샬링 패킷 마샬링 및 압축 해제시
|
||||
public class CommonPacketMarshalException : Exception
|
||||
{
|
||||
public CommonPacketMarshalException()
|
||||
{
|
||||
}
|
||||
|
||||
public CommonPacketMarshalException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public CommonPacketMarshalException(string message, Exception inner)
|
||||
: base(message, inner)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public static BASE_PROTOCOL GetHeaderProtocol(int iSize, byte[] CompressMarshalByteStream)
|
||||
{
|
||||
byte[] ucDecompressGetByte = new byte[1];
|
||||
byte[] getRowByte = new byte[iSize - PAD_SIZE];
|
||||
|
||||
BASE_PROTOCOL SET_PROTOCOL = new BASE_PROTOCOL();
|
||||
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
Array.Copy(CompressMarshalByteStream, HEAD_SIZE, getRowByte, 0, iSize - PAD_SIZE);
|
||||
|
||||
HEADER_PACKET GetHeaderPacket = new HEADER_PACKET();
|
||||
int iHeaderSize = Marshal.SizeOf(GetHeaderPacket);
|
||||
byte[] ucHeaderMake = new byte[iHeaderSize];
|
||||
GetHeaderPacket = (HEADER_PACKET)SystemXNetSerialization.RawDeSerialize(ucHeaderMake, GetHeaderPacket.GetType());
|
||||
int iHeadLeng = Marshal.SizeOf(GetHeaderPacket);
|
||||
|
||||
byte[] ucHeadBytes = new byte[iHeadLeng];
|
||||
|
||||
Array.Copy(getRowByte, 0, ucHeadBytes, 0, iHeadLeng);
|
||||
|
||||
GetHeaderPacket = (HEADER_PACKET)SystemXNetSerialization.RawDeSerialize(ucHeadBytes, GetHeaderPacket.GetType());
|
||||
|
||||
SET_PROTOCOL = (new BASE_PROTOCOL(GetHeaderPacket.usCommand, GetHeaderPacket.usSubCommand, GetHeaderPacket.uiOptionCommand));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//throw new CommonPacketMarshalException("General packet marshalling failed.[SystemX.Common : SystemXNetCommons.GetHeaderProtocol]");
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General packet marshalling failed.[SystemX.Common : SystemXNetCommons.GetHeaderProtocol]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
;//Until unused
|
||||
}
|
||||
|
||||
return SET_PROTOCOL;
|
||||
}
|
||||
public static HEADER_PACKET GetHeaderPacket(int iSize, byte[] CompressMarshalByteStream)
|
||||
{
|
||||
byte[] ucDecompressGetByte = new byte[1];
|
||||
byte[] getRowByte = new byte[iSize - PAD_SIZE];
|
||||
|
||||
HEADER_PACKET GetHeaderPacket = new HEADER_PACKET();
|
||||
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
Array.Copy(CompressMarshalByteStream, HEAD_SIZE, getRowByte, 0, iSize - PAD_SIZE);
|
||||
|
||||
GetHeaderPacket = new HEADER_PACKET();
|
||||
int iHeaderSize = Marshal.SizeOf(GetHeaderPacket);
|
||||
byte[] ucHeaderMake = new byte[iHeaderSize];
|
||||
GetHeaderPacket = (HEADER_PACKET)SystemXNetSerialization.RawDeSerialize(ucHeaderMake, GetHeaderPacket.GetType());
|
||||
int iHeadLeng = Marshal.SizeOf(GetHeaderPacket);
|
||||
|
||||
byte[] ucHeadBytes = new byte[iHeadLeng];
|
||||
|
||||
Array.Copy(getRowByte, 0, ucHeadBytes, 0, iHeadLeng);
|
||||
|
||||
GetHeaderPacket = (HEADER_PACKET)SystemXNetSerialization.RawDeSerialize(ucHeadBytes, GetHeaderPacket.GetType());
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//throw new CommonPacketMarshalException("General packet marshalling failed.[SystemX.Common : SystemXNetCommons.GetHeaderPacket]");
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General packet marshalling failed.[SystemX.Common : SystemXNetCommons.GetHeaderPacket]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
;//Until unused
|
||||
}
|
||||
|
||||
return GetHeaderPacket;
|
||||
}
|
||||
private static byte[] HeadTailMake(uint uiPacketSize, byte[] HeadBuff, byte[] BodyBuff)
|
||||
{
|
||||
byte[] ucSetStreamBytes = new byte[uiPacketSize + PAD_SIZE];
|
||||
|
||||
ucSetStreamBytes[0] = 0x0D;
|
||||
ucSetStreamBytes[1] = 0x02;
|
||||
ucSetStreamBytes[2] = (byte)(uiPacketSize >> 24);
|
||||
ucSetStreamBytes[3] = (byte)(uiPacketSize >> 16);
|
||||
ucSetStreamBytes[4] = (byte)(uiPacketSize >> 8);
|
||||
ucSetStreamBytes[5] = (byte)(uiPacketSize >> 0);
|
||||
ucSetStreamBytes[6] = 0x08;
|
||||
ucSetStreamBytes[7] = 0x0A;
|
||||
|
||||
Array.Copy(HeadBuff, 0, ucSetStreamBytes, 8, HeadBuff.Count());
|
||||
Array.Copy(BodyBuff, 0, ucSetStreamBytes, HeadBuff.Count() + HEAD_SIZE, BodyBuff.Count());
|
||||
|
||||
ucSetStreamBytes[ucSetStreamBytes.Length - 4] = 0x0D;
|
||||
ucSetStreamBytes[ucSetStreamBytes.Length - 3] = 0x02;
|
||||
ucSetStreamBytes[ucSetStreamBytes.Length - 2] = 0x08;
|
||||
ucSetStreamBytes[ucSetStreamBytes.Length - 1] = 0x0A;
|
||||
|
||||
return ucSetStreamBytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,271 @@
|
||||
using System;
|
||||
using System.CodeDom;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Remoting.Messaging;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Common.Archive;
|
||||
using SystemX.Common.Serialization;
|
||||
using SystemX.Net.BaseProtocol;
|
||||
using static SystemX.Net.Platform.Common.Util.LogMessage;
|
||||
|
||||
|
||||
namespace SystemX.Common
|
||||
{
|
||||
public static partial class XCommons
|
||||
{
|
||||
public static T ByteStreamToSpecialObject<T>(BASE_PROTOCOL.PROTOCOL_CODE GET_CODE, int iSize, byte[] MarshalByteStream)
|
||||
{
|
||||
byte[] getDataByte = new byte[1];
|
||||
byte[] getRawByte = new byte[iSize - PAD_SIZE];
|
||||
|
||||
int iRawDataSize;
|
||||
|
||||
object getObj = null;
|
||||
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
Array.Copy(MarshalByteStream, HEAD_SIZE, getRawByte, 0, iSize - PAD_SIZE);
|
||||
|
||||
HEADER_PACKET GetHeaderPacket = new HEADER_PACKET();
|
||||
int iHeadLeng = Marshal.SizeOf(GetHeaderPacket);
|
||||
byte[] ucHeadBytes = new byte[iHeadLeng];
|
||||
Array.Copy(getRawByte, 0, ucHeadBytes, 0, iHeadLeng);
|
||||
iRawDataSize = getRawByte.Count();
|
||||
GetHeaderPacket = (HEADER_PACKET)SystemXNetSerialization.RawDeSerialize(ucHeadBytes, GetHeaderPacket.GetType());
|
||||
|
||||
getDataByte = new byte[GetHeaderPacket.uiDataLength];
|
||||
|
||||
object getPacket = SystemXNetSerialization.SelectPacket(GetHeaderPacket.uiDataLength);
|
||||
if (getPacket == null) throw new Exception("SystemXNetSerialization.SelectPacket Failed.");
|
||||
int iBodySize = Marshal.SizeOf(getPacket);
|
||||
byte[] ucBodyArray = new byte[iBodySize];
|
||||
Array.Copy(getRawByte, iHeadLeng, ucBodyArray, 0, iBodySize); // iRawDataSize - iHeadLeng);
|
||||
|
||||
getPacket = Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucBodyArray, getPacket.GetType()), getPacket.GetType());
|
||||
getPacket = SystemXNetSerialization.RawDeSerialize(ucBodyArray, getPacket.GetType());
|
||||
|
||||
Array.Copy((byte[])getPacket.GetType().GetMethod("Data").Invoke(getPacket, null), getDataByte, GetHeaderPacket.uiDataLength);
|
||||
|
||||
byte[] ucSpecialObjArray = XDataArchive.DecompressDeflateByteToByte(getDataByte);
|
||||
|
||||
if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.CONNECT_STATE)
|
||||
{
|
||||
PING_PACKET PingPacket = new PING_PACKET();
|
||||
PingPacket = (PING_PACKET)Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, PingPacket.GetType()), PingPacket.GetType());
|
||||
PingPacket = (PING_PACKET)SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, PingPacket.GetType());
|
||||
|
||||
getObj = PingPacket;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.MIDDLEWARE_MESSAGE)
|
||||
{
|
||||
MESSAGE_PACKET MessagePacket = new MESSAGE_PACKET();
|
||||
MessagePacket = (MESSAGE_PACKET)Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, MessagePacket.GetType()), MessagePacket.GetType());
|
||||
MessagePacket = (MESSAGE_PACKET)SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, MessagePacket.GetType());
|
||||
|
||||
getObj = MessagePacket;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.HOST_INFO_CHECK)
|
||||
{
|
||||
SYSTEM_HOST_PACKET HostInfoPacket = new SYSTEM_HOST_PACKET();
|
||||
HostInfoPacket = (SYSTEM_HOST_PACKET)Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, HostInfoPacket.GetType()), HostInfoPacket.GetType());
|
||||
HostInfoPacket = (SYSTEM_HOST_PACKET)SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, HostInfoPacket.GetType());
|
||||
|
||||
getObj = HostInfoPacket;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.SYNC_TIME_SERVER)
|
||||
{
|
||||
TIME_PACKET timePacket = new TIME_PACKET();
|
||||
timePacket = (TIME_PACKET)Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, timePacket.GetType()), timePacket.GetType());
|
||||
timePacket = (TIME_PACKET)SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, timePacket.GetType());
|
||||
|
||||
getObj = timePacket;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.ETC)
|
||||
{
|
||||
USER_PACKET UserDataPacket = new USER_PACKET();
|
||||
UserDataPacket = (USER_PACKET)Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, UserDataPacket.GetType()), UserDataPacket.GetType());
|
||||
UserDataPacket = (USER_PACKET)SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, UserDataPacket.GetType());
|
||||
|
||||
getObj = UserDataPacket;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.PROCESS_QUERY)
|
||||
{
|
||||
PROCESS_PACKET ProcessDataPacket = new PROCESS_PACKET();
|
||||
ProcessDataPacket = (PROCESS_PACKET)Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, ProcessDataPacket.GetType()), ProcessDataPacket.GetType());
|
||||
ProcessDataPacket = (PROCESS_PACKET)SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, ProcessDataPacket.GetType());
|
||||
|
||||
getObj = ProcessDataPacket;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.SYSTEM_QUERY)
|
||||
{
|
||||
QUERY_PACKET SystemQueryPacket = new QUERY_PACKET();
|
||||
SystemQueryPacket = (QUERY_PACKET)Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, SystemQueryPacket.GetType()), SystemQueryPacket.GetType());
|
||||
SystemQueryPacket = (QUERY_PACKET)SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, SystemQueryPacket.GetType());
|
||||
|
||||
getObj = SystemQueryPacket;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.USER_QUERY)
|
||||
{
|
||||
QUERY_PACKET SystemQueryPacket = new QUERY_PACKET();
|
||||
SystemQueryPacket = (QUERY_PACKET)Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, SystemQueryPacket.GetType()), SystemQueryPacket.GetType());
|
||||
SystemQueryPacket = (QUERY_PACKET)SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, SystemQueryPacket.GetType());
|
||||
|
||||
getObj = SystemQueryPacket;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.TRANSFER_RESULT)
|
||||
{
|
||||
TRANSFER_PACKET TransferResult = new TRANSFER_PACKET();
|
||||
TransferResult = (TRANSFER_PACKET)Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, TransferResult.GetType()), TransferResult.GetType());
|
||||
TransferResult = (TRANSFER_PACKET)SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, TransferResult.GetType());
|
||||
|
||||
getObj = TransferResult;
|
||||
}
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.INITILALIZE_INFO)
|
||||
{
|
||||
COMM_INFO_PACKET CommInfoPacket = new COMM_INFO_PACKET();
|
||||
CommInfoPacket = (COMM_INFO_PACKET)Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, CommInfoPacket.GetType()), CommInfoPacket.GetType());
|
||||
CommInfoPacket = (COMM_INFO_PACKET)SystemXNetSerialization.RawDeSerialize(ucSpecialObjArray, CommInfoPacket.GetType());
|
||||
|
||||
getObj = CommInfoPacket;
|
||||
}
|
||||
else
|
||||
getObj = null;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//throw new CommonPacketMarshalException("General packet marshalling failed.[SystemX.Common : SystemXNetCommons.ByteStreamToUserObject]");
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General packet marshalling failed.[SystemX.Common : SystemXNetCommons.ByteStreamToUserObject]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
;//Until unused
|
||||
}
|
||||
|
||||
return (T)Convert.ChangeType(getObj, typeof(T));
|
||||
}
|
||||
|
||||
public static bool GetSimpleResponsResult(int iSize, byte[] CompressMarshalByteStream)
|
||||
{
|
||||
byte[] getDataByte = new byte[1];
|
||||
byte[] getRawByte = new byte[iSize - PAD_SIZE];
|
||||
|
||||
bool bResponsResult = false;
|
||||
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
Array.Copy(CompressMarshalByteStream, HEAD_SIZE, getRawByte, 0, iSize - PAD_SIZE);
|
||||
|
||||
HEADER_PACKET GetHeaderPacket = new HEADER_PACKET();
|
||||
int iHeaderSize = Marshal.SizeOf(GetHeaderPacket);
|
||||
byte[] ucHeaderMake = new byte[iHeaderSize];
|
||||
GetHeaderPacket = (HEADER_PACKET)SystemXNetSerialization.RawDeSerialize(ucHeaderMake, GetHeaderPacket.GetType());
|
||||
int iHeadLeng = Marshal.SizeOf(GetHeaderPacket);
|
||||
|
||||
byte[] ucHeadBytes = new byte[iHeadLeng];
|
||||
|
||||
Array.Copy(getRawByte, 0, ucHeadBytes, 0, iHeadLeng);
|
||||
|
||||
GetHeaderPacket = (HEADER_PACKET)SystemXNetSerialization.RawDeSerialize(ucHeadBytes, GetHeaderPacket.GetType());
|
||||
|
||||
getDataByte = new byte[GetHeaderPacket.uiDataLength];
|
||||
|
||||
object getPacket = SystemXNetSerialization.SelectPacket(GetHeaderPacket.uiDataLength);
|
||||
if (getPacket == null) throw new Exception("SystemXNetSerialization.SelectPacket Failed.");
|
||||
int iBodySize = Marshal.SizeOf(getPacket);
|
||||
byte[] ucBodyArray = new byte[iBodySize];
|
||||
Array.Copy(getRawByte, iHeadLeng, ucBodyArray, 0, iBodySize); // - iHeadLeng);
|
||||
|
||||
getPacket = Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucBodyArray, getPacket.GetType()), getPacket.GetType());
|
||||
getPacket = SystemXNetSerialization.RawDeSerialize(ucBodyArray, getPacket.GetType());
|
||||
|
||||
Array.Copy((byte[])getPacket.GetType().GetMethod("Data").Invoke(getPacket, null), getDataByte, GetHeaderPacket.uiDataLength);
|
||||
|
||||
bResponsResult = GetHeaderPacket.bResponsState;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//throw new CommonPacketMarshalException("General packet marshalling failed.[SystemX.Common : SystemXNetCommons.ByteStreamToObject]");
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General packet marshalling failed.[SystemX.Common : SystemXNetCommons.ByteStreamToObject]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
;//Until unused
|
||||
}
|
||||
|
||||
return bResponsResult;
|
||||
}
|
||||
|
||||
public static T ByteStreamToObject<T>(BASE_PROTOCOL.PROTOCOL_CODE GET_CODE, int iSize, byte[] CompressMarshalByteStream)
|
||||
{
|
||||
byte[] getDataByte = new byte[1];
|
||||
byte[] getRawByte = new byte[iSize - PAD_SIZE];
|
||||
|
||||
object getObj = null;
|
||||
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
Array.Copy(CompressMarshalByteStream, HEAD_SIZE, getRawByte, 0, iSize - PAD_SIZE);
|
||||
|
||||
HEADER_PACKET GetHeaderPacket = new HEADER_PACKET();
|
||||
int iHeaderSize = Marshal.SizeOf(GetHeaderPacket);
|
||||
byte[] ucHeaderMake = new byte[iHeaderSize];
|
||||
GetHeaderPacket = (HEADER_PACKET)SystemXNetSerialization.RawDeSerialize(ucHeaderMake, GetHeaderPacket.GetType());
|
||||
int iHeadLeng = Marshal.SizeOf(GetHeaderPacket);
|
||||
|
||||
byte[] ucHeadBytes = new byte[iHeadLeng];
|
||||
|
||||
Array.Copy(getRawByte, 0, ucHeadBytes, 0, iHeadLeng);
|
||||
|
||||
GetHeaderPacket = (HEADER_PACKET)SystemXNetSerialization.RawDeSerialize(ucHeadBytes, GetHeaderPacket.GetType());
|
||||
|
||||
getDataByte = new byte[GetHeaderPacket.uiDataLength];
|
||||
|
||||
object getPacket = SystemXNetSerialization.SelectPacket(GetHeaderPacket.uiDataLength);
|
||||
if (getPacket == null) throw new Exception("SystemXNetSerialization.SelectPacket Failed.");
|
||||
int iBodySize = Marshal.SizeOf(getPacket);
|
||||
byte[] ucBodyArray = new byte[iBodySize];
|
||||
Array.Copy(getRawByte, iHeadLeng, ucBodyArray, 0, iBodySize); // - iHeadLeng);
|
||||
|
||||
getPacket = Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucBodyArray, getPacket.GetType()), getPacket.GetType());
|
||||
getPacket = SystemXNetSerialization.RawDeSerialize(ucBodyArray, getPacket.GetType());
|
||||
|
||||
Array.Copy((byte[])getPacket.GetType().GetMethod("Data").Invoke(getPacket, null), getDataByte, GetHeaderPacket.uiDataLength);
|
||||
|
||||
if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.FILE_TRANSFER)
|
||||
getObj = getDataByte; //XDataArchive.DecompressDeflateByteToByte(getDataByte);
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.DATASET_TRANSEFER)
|
||||
getObj = XDataArchive.DecompressByteToDataset(getDataByte);
|
||||
else if (GET_CODE == BASE_PROTOCOL.PROTOCOL_CODE.RAW_SIZE)
|
||||
getObj = getDataByte;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//throw new CommonPacketMarshalException("General packet marshalling failed.[SystemX.Common : COMMON.ByteStreamToObject]");
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General packet marshalling failed.[SystemX.Common : COMMON.ByteStreamToObject]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
;//Until unused
|
||||
}
|
||||
|
||||
return (T)Convert.ChangeType(getObj, typeof(T));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,644 @@
|
||||
using System;
|
||||
using System.CodeDom;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Remoting.Messaging;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Common.Archive;
|
||||
using SystemX.Common.Serialization;
|
||||
using SystemX.Net.BaseProtocol;
|
||||
using static SystemX.Net.Platform.Common.Util.LogMessage;
|
||||
|
||||
namespace SystemX.Common
|
||||
{
|
||||
public static partial class XCommons
|
||||
{
|
||||
public static byte[] SpecialObjectToByteStream(BASE_PROTOCOL SET_PROTOCOL, object refObj)
|
||||
{
|
||||
byte[] ucGetStreamBytes = new byte[1];
|
||||
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
int iSize = Marshal.SizeOf(refObj);
|
||||
byte[] SendBuffer = SystemXNetSerialization.RawSerialize(refObj, Marshal.SizeOf(refObj));
|
||||
|
||||
var memoryStream = new MemoryStream(SendBuffer);
|
||||
byte[] getSendCompressFileByte = new byte[1];
|
||||
getSendCompressFileByte = XDataArchive.CompressDeflateByteToByte(SendBuffer);
|
||||
iSize = getSendCompressFileByte.Count();
|
||||
|
||||
HEADER_PACKET setHeader = new HEADER_PACKET();
|
||||
int iHeaderSize = Marshal.SizeOf(setHeader);
|
||||
byte[] ucHeaderMake = new byte[iHeaderSize];
|
||||
setHeader = (HEADER_PACKET)SystemXNetSerialization.RawDeSerialize(ucHeaderMake, setHeader.GetType());
|
||||
iHeaderSize = Marshal.SizeOf(setHeader);
|
||||
|
||||
setHeader.usCommand = SET_PROTOCOL.COMMAND;
|
||||
setHeader.usSubCommand = SET_PROTOCOL.SUB_COMMAND;
|
||||
setHeader.uiOptionCommand = SET_PROTOCOL.OPTION_COMMAND;
|
||||
|
||||
setHeader.uiHeaderLength = (uint)iHeaderSize;
|
||||
setHeader.uiDataLength = (uint)iSize;
|
||||
|
||||
setHeader.objOptionName[0].Data = "-";
|
||||
setHeader.objOptionExtension[0].Data = "-";
|
||||
|
||||
setHeader.uiSourDataNum = 0;
|
||||
setHeader.uiDestDataNum = 0;
|
||||
|
||||
byte[] SendHeadBuffer = SystemXNetSerialization.RawSerialize(setHeader, Marshal.SizeOf(setHeader));
|
||||
|
||||
object getPacket = SystemXNetSerialization.SelectPacket(setHeader.uiDataLength);
|
||||
if (getPacket == null) throw new Exception("SystemXNetSerialization.SelectPacket Failed.");
|
||||
int iBodySize = Marshal.SizeOf(getPacket);
|
||||
byte[] ucBodyArray = new byte[iBodySize];
|
||||
getPacket = Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucBodyArray, getPacket.GetType()), getPacket.GetType());
|
||||
Array.Copy(getSendCompressFileByte, (byte[])getPacket.GetType().GetMethod("Data").Invoke(getPacket, null), getSendCompressFileByte.Count());
|
||||
|
||||
setHeader.uiBodyLength = (uint)iBodySize;
|
||||
setHeader.uiPacketLength = (uint)(iHeaderSize + iBodySize);
|
||||
|
||||
byte[] SendBodyBuffer = SystemXNetSerialization.RawSerialize(getPacket, Marshal.SizeOf(getPacket));
|
||||
|
||||
ucGetStreamBytes = HeadTailMake(setHeader.uiPacketLength, SendHeadBuffer, SendBodyBuffer);
|
||||
|
||||
//string strMessage = Encoding.Unicode.GetString(ucGetFileBytes, 0, ucGetFileBytes.Length) + "\r\n";
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//throw new CommonPacketMarshalException("General packet marshalling failed.[SystemX.Common : SystemXNetCommons.UserObjectToByteStream]");
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General packet marshalling failed.[SystemX.Common : SystemXNetCommons.UserObjectToByteStream]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
;//Until unused
|
||||
}
|
||||
|
||||
return ucGetStreamBytes;
|
||||
}
|
||||
public static byte[] SetSimpleResponsPacket(BASE_PROTOCOL SET_PROTOCOL, bool bState)
|
||||
{
|
||||
byte[] ucGetStreamBytes = new byte[1];
|
||||
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
if (SET_PROTOCOL.GET_CURRENT_PROTOCOL == BASE_PROTOCOL.PROTOCOL_CODE.SIMPLE_RESPONSE)
|
||||
{
|
||||
;//
|
||||
}
|
||||
else if (SET_PROTOCOL.GET_CURRENT_PROTOCOL == BASE_PROTOCOL.PROTOCOL_CODE.RAW_END)
|
||||
{
|
||||
;//
|
||||
}
|
||||
else
|
||||
return null;
|
||||
|
||||
var bytes = new byte[1];
|
||||
|
||||
HEADER_PACKET setHeader = new HEADER_PACKET();
|
||||
int iHeaderSize = Marshal.SizeOf(setHeader);
|
||||
byte[] ucHeaderMake = new byte[iHeaderSize];
|
||||
setHeader = (HEADER_PACKET)SystemXNetSerialization.RawDeSerialize(ucHeaderMake, setHeader.GetType());
|
||||
iHeaderSize = Marshal.SizeOf(setHeader);
|
||||
|
||||
setHeader.usCommand = SET_PROTOCOL.COMMAND;
|
||||
setHeader.usSubCommand = SET_PROTOCOL.SUB_COMMAND;
|
||||
setHeader.uiOptionCommand = SET_PROTOCOL.OPTION_COMMAND;
|
||||
|
||||
setHeader.bResponsState = bState;
|
||||
setHeader.usHeader = 1;
|
||||
setHeader.uiHeaderLength = (uint)iHeaderSize;
|
||||
setHeader.uiDataLength = 512;
|
||||
|
||||
setHeader.objOptionName[0].Data = "-";
|
||||
setHeader.objOptionExtension[0].Data = "-";
|
||||
|
||||
setHeader.uiSourDataNum = 0;
|
||||
setHeader.uiDestDataNum = 0;
|
||||
|
||||
object getPacket = SystemXNetSerialization.SelectPacket(512);
|
||||
if (getPacket == null) throw new Exception("SystemXNetSerialization.SelectPacket Failed.");
|
||||
int iBodySize = Marshal.SizeOf(getPacket);
|
||||
byte[] ucBodyArray = new byte[iBodySize];
|
||||
getPacket = Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucBodyArray, getPacket.GetType()), getPacket.GetType());
|
||||
|
||||
setHeader.uiBodyLength = (uint)iBodySize;
|
||||
setHeader.uiPacketLength = (uint)(iHeaderSize + iBodySize);
|
||||
|
||||
byte[] SendHeadBuffer = SystemXNetSerialization.RawSerialize(setHeader, Marshal.SizeOf(setHeader));
|
||||
byte[] SendBodyBuffer = SystemXNetSerialization.RawSerialize(getPacket, Marshal.SizeOf(getPacket));
|
||||
|
||||
ucGetStreamBytes = HeadTailMake(setHeader.uiPacketLength, SendHeadBuffer, SendBodyBuffer);
|
||||
|
||||
//string strMessage = Encoding.Unicode.GetString(ucGetFileBytes, 0, ucGetFileBytes.Length) + "\r\n";
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//throw new CommonPacketMarshalException("General packet marshalling failed.[SystemX.Common : SystemXNetCommons.SimpleObjectToByteStream]");
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General packet marshalling failed.[SystemX.Common : SystemXNetCommons.SimpleObjectToByteStream]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
;//Until unused
|
||||
}
|
||||
|
||||
return ucGetStreamBytes;
|
||||
}
|
||||
public static byte[] ObjectToByteStream(BASE_PROTOCOL SET_PROTOCOL, object refObj, CP_PACKET? getCPPacket = null,
|
||||
ushort usPalletIndex = 0, int iRecordsAffected = 1, bool bHasRows = true, int iFieldCount = 1, params string[] strParameters)
|
||||
{
|
||||
byte[] ucGetStreamBytes = new byte[1];
|
||||
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
string refObjGetPos = string.Empty;
|
||||
|
||||
string strGetFileName = string.Empty;
|
||||
string strGetExtension = string.Empty;
|
||||
|
||||
MemoryStream ms = null;
|
||||
|
||||
//
|
||||
SqlDataReader sqlReader = null;
|
||||
|
||||
DataSet ds = new DataSet();
|
||||
DataTable dt = new DataTable();
|
||||
|
||||
bool bCheckPos = true;
|
||||
bool bResponsSetState = true;
|
||||
if (SET_PROTOCOL.GET_CURRENT_PROTOCOL == BASE_PROTOCOL.PROTOCOL_CODE.FILE_TRANSFER)
|
||||
{
|
||||
if (refObj is MemoryStream)
|
||||
{
|
||||
ms = (MemoryStream)refObj;
|
||||
|
||||
if (ms == null)
|
||||
{
|
||||
bCheckPos = false;
|
||||
|
||||
//throw new Exception("MemoryStream not initialize.. " + refObjGetPos);
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"MemoryStream not initialize." + refObjGetPos + " [SystemX.Common : SystemXNetCommons.ObjectToByteStream]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
refObjGetPos = (string)refObj;
|
||||
|
||||
if (File.Exists(@refObjGetPos) == false)
|
||||
{
|
||||
bCheckPos = false;
|
||||
|
||||
//throw new Exception("The file cannot be found. " + refObjGetPos);
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"The file cannot be found." + refObjGetPos + " [SystemX.Common : SystemXNetCommons.ObjectToByteStream]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
else
|
||||
{
|
||||
strGetFileName = Path.GetFileNameWithoutExtension(@refObjGetPos);
|
||||
strGetExtension = Path.GetExtension(@refObjGetPos);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (SET_PROTOCOL.GET_CURRENT_PROTOCOL == BASE_PROTOCOL.PROTOCOL_CODE.DATASET_TRANSEFER)
|
||||
{
|
||||
if (refObj is SqlDataReader)
|
||||
{
|
||||
sqlReader = (SqlDataReader)refObj;
|
||||
|
||||
bResponsSetState = false;
|
||||
|
||||
if (sqlReader != null)
|
||||
{
|
||||
if (sqlReader.RecordsAffected > 0)
|
||||
bResponsSetState = true;
|
||||
else if (sqlReader.HasRows == true)
|
||||
bResponsSetState = true;
|
||||
else if (sqlReader.FieldCount > 0)
|
||||
bResponsSetState = true;
|
||||
else
|
||||
bResponsSetState = false;
|
||||
|
||||
dt.Load(sqlReader);
|
||||
ds.Tables.Add(dt);
|
||||
}
|
||||
}
|
||||
else if (refObj is DataTable)
|
||||
{
|
||||
dt = (DataTable)refObj;
|
||||
|
||||
bResponsSetState = false;
|
||||
|
||||
if (dt != null)
|
||||
{
|
||||
if (iRecordsAffected > 0)
|
||||
bResponsSetState = true;
|
||||
else if (bHasRows == true)
|
||||
bResponsSetState = true;
|
||||
else if (iFieldCount > 0)
|
||||
bResponsSetState = true;
|
||||
else
|
||||
bResponsSetState = false;
|
||||
|
||||
ds.Tables.Add(dt);
|
||||
}
|
||||
}
|
||||
else if (refObj is DataSet)
|
||||
{
|
||||
ds = (DataSet)refObj;
|
||||
|
||||
bResponsSetState = false;
|
||||
|
||||
if (ds != null)
|
||||
{
|
||||
if (iRecordsAffected > 0)
|
||||
bResponsSetState = true;
|
||||
else if (bHasRows == true)
|
||||
bResponsSetState = true;
|
||||
else if (iFieldCount > 0)
|
||||
bResponsSetState = true;
|
||||
else
|
||||
bResponsSetState = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
;//
|
||||
}
|
||||
}
|
||||
if (bCheckPos)
|
||||
{
|
||||
var bytes = new byte[1];
|
||||
|
||||
if (SET_PROTOCOL.GET_CURRENT_PROTOCOL == BASE_PROTOCOL.PROTOCOL_CODE.FILE_TRANSFER)
|
||||
{
|
||||
if (ms != null)
|
||||
bytes = ms.ToArray();
|
||||
else
|
||||
bytes = File.ReadAllBytes(@refObjGetPos);
|
||||
}
|
||||
else if (SET_PROTOCOL.GET_CURRENT_PROTOCOL == BASE_PROTOCOL.PROTOCOL_CODE.DATASET_TRANSEFER)
|
||||
bytes = XDataArchive.CompressDatasetToByte(ds);
|
||||
|
||||
var memoryStream = new MemoryStream(bytes);
|
||||
byte[] getSendOrgFileByte = memoryStream.ToArray();
|
||||
byte[] getSendCompressFileByte = new byte[1];
|
||||
|
||||
if (SET_PROTOCOL.GET_CURRENT_PROTOCOL == BASE_PROTOCOL.PROTOCOL_CODE.FILE_TRANSFER)
|
||||
getSendCompressFileByte = XDataArchive.CompressDeflateByteToByte(getSendOrgFileByte);
|
||||
else if (SET_PROTOCOL.GET_CURRENT_PROTOCOL == BASE_PROTOCOL.PROTOCOL_CODE.DATASET_TRANSEFER)
|
||||
getSendCompressFileByte = memoryStream.ToArray();
|
||||
|
||||
HEADER_PACKET setHeader = new HEADER_PACKET();
|
||||
int iHeaderSize = Marshal.SizeOf(setHeader);
|
||||
byte[] ucHeaderMake = new byte[iHeaderSize];
|
||||
setHeader = (HEADER_PACKET)SystemXNetSerialization.RawDeSerialize(ucHeaderMake, setHeader.GetType());
|
||||
iHeaderSize = Marshal.SizeOf(setHeader);
|
||||
|
||||
//Various Parameter
|
||||
int nParamPos = 0;
|
||||
foreach (string strParam in strParameters)
|
||||
{
|
||||
switch (nParamPos)
|
||||
{
|
||||
case 0: setHeader.objVarParam1[0].Data = strParam; break;
|
||||
case 1: setHeader.objVarParam2[0].Data = strParam; break;
|
||||
case 2: setHeader.objVarParam3[0].Data = strParam; break;
|
||||
}
|
||||
|
||||
nParamPos++;
|
||||
}
|
||||
|
||||
setHeader.bResponsState = bResponsSetState;
|
||||
|
||||
setHeader.usPalletIndex = usPalletIndex;
|
||||
|
||||
setHeader.usCommand = SET_PROTOCOL.COMMAND;
|
||||
setHeader.usSubCommand = SET_PROTOCOL.SUB_COMMAND;
|
||||
setHeader.uiOptionCommand = SET_PROTOCOL.OPTION_COMMAND;
|
||||
|
||||
setHeader.uiHeaderLength = (uint)iHeaderSize;
|
||||
setHeader.uiDataLength = (uint)getSendCompressFileByte.Count();
|
||||
|
||||
setHeader.objOptionName[0].Data = "-";
|
||||
setHeader.objOptionExtension[0].Data = "-";
|
||||
|
||||
if (getCPPacket == null)
|
||||
{
|
||||
setHeader.objCP_Packet[0].objStationName[0].Data = "-";
|
||||
setHeader.objCP_Packet[0].objProdNo_P[0].Data = "-";
|
||||
setHeader.objCP_Packet[0].objProdNo_C[0].Data = "-";
|
||||
setHeader.objCP_Packet[0].objTestType[0].Data = "-";
|
||||
setHeader.objCP_Packet[0].objTestCode[0].Data = "-";
|
||||
setHeader.objCP_Packet[0].objVersion[0].Data = "-";
|
||||
setHeader.objCP_Packet[0].objProdCode[0].Data = "-";
|
||||
setHeader.objCP_Packet[0].uiTestListNo = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
setHeader.objCP_Packet[0].objStationName[0].Data = getCPPacket.Value.objStationName[0].Data;
|
||||
setHeader.objCP_Packet[0].objProdNo_P[0].Data = getCPPacket.Value.objProdNo_P[0].Data;
|
||||
setHeader.objCP_Packet[0].objProdNo_C[0].Data = getCPPacket.Value.objProdNo_C[0].Data;
|
||||
setHeader.objCP_Packet[0].objTestType[0].Data = getCPPacket.Value.objTestType[0].Data;
|
||||
setHeader.objCP_Packet[0].objTestCode[0].Data = getCPPacket.Value.objTestCode[0].Data;
|
||||
setHeader.objCP_Packet[0].objVersion[0].Data = getCPPacket.Value.objVersion[0].Data;
|
||||
setHeader.objCP_Packet[0].objProdCode[0].Data = getCPPacket.Value.objProdCode[0].Data;
|
||||
setHeader.objCP_Packet[0].uiTestListNo = getCPPacket.Value.uiTestListNo;
|
||||
}
|
||||
|
||||
if (SET_PROTOCOL.GET_CURRENT_PROTOCOL == BASE_PROTOCOL.PROTOCOL_CODE.FILE_TRANSFER)
|
||||
{
|
||||
if (strGetFileName != string.Empty)
|
||||
{
|
||||
setHeader.objOptionName[0].Data = strGetFileName;
|
||||
setHeader.objOptionExtension[0].Data = strGetExtension;
|
||||
}
|
||||
}
|
||||
|
||||
setHeader.uiSourDataNum = 0;
|
||||
setHeader.uiDestDataNum = 0;
|
||||
|
||||
object getPacket = SystemXNetSerialization.SelectPacket(setHeader.uiDataLength);
|
||||
if (getPacket == null) throw new Exception("SystemXNetSerialization.SelectPacket Failed.");
|
||||
int iBodySize = Marshal.SizeOf(getPacket);
|
||||
byte[] ucBodyArray = new byte[iBodySize];
|
||||
getPacket = Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucBodyArray, getPacket.GetType()), getPacket.GetType());
|
||||
Array.Copy(getSendCompressFileByte, (byte[])getPacket.GetType().GetMethod("Data").Invoke(getPacket, null), getSendCompressFileByte.Count());
|
||||
|
||||
setHeader.uiBodyLength = (uint)iBodySize;
|
||||
setHeader.uiPacketLength = (uint)(iHeaderSize + iBodySize);
|
||||
|
||||
byte[] SendHeadBuffer = SystemXNetSerialization.RawSerialize(setHeader, Marshal.SizeOf(setHeader));
|
||||
|
||||
byte[] SendBodyBuffer = SystemXNetSerialization.RawSerialize(getPacket, Marshal.SizeOf(getPacket));
|
||||
|
||||
ucGetStreamBytes = HeadTailMake(setHeader.uiPacketLength, SendHeadBuffer, SendBodyBuffer);
|
||||
|
||||
//string strMessage = Encoding.Unicode.GetString(ucGetFileBytes, 0, ucGetFileBytes.Length) + "\r\n";
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//throw new CommonPacketMarshalException("General packet marshalling failed.[SystemX.Common : SystemXNetCommons.ObjectToByteStream]");
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General packet marshalling failed.[SystemX.Common : SystemXNetCommons.ObjectToByteStream]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
;//Until unused
|
||||
}
|
||||
|
||||
return ucGetStreamBytes;
|
||||
}
|
||||
public static List<byte[]> ObjectToByteStreamList(BASE_PROTOCOL SET_PROTOCOL, object refObj, CP_PACKET? getCPPacket = null,
|
||||
ushort usPalletIdx = 0, params string[] strParameters)
|
||||
{
|
||||
List<byte[]> listStreamRawData = new List<byte[]>();
|
||||
|
||||
byte[] ucGetStreamBytes = new byte[1];
|
||||
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
string refObjGetPos = string.Empty;
|
||||
|
||||
string strGetFileName = string.Empty;
|
||||
string strGetExtension = string.Empty;
|
||||
|
||||
bool bCheckPos = true;
|
||||
|
||||
// 1 = File, 2 = DataSet
|
||||
int iSelectType = 0;
|
||||
if (refObj is string)
|
||||
{
|
||||
refObjGetPos = (string)refObj;
|
||||
|
||||
if (File.Exists(@refObjGetPos) == false)
|
||||
{
|
||||
bCheckPos = false;
|
||||
|
||||
//throw new Exception("The file cannot be found. " + refObjGetPos);
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"The file cannot be found. " + refObjGetPos + " [SystemX.Common : SystemXNetCommons.ObjectToByteStreamList]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
strGetFileName = Path.GetFileNameWithoutExtension(@refObjGetPos);
|
||||
strGetExtension = Path.GetExtension(@refObjGetPos);
|
||||
|
||||
iSelectType = 1;
|
||||
}
|
||||
}
|
||||
else if (refObj is DataSet)
|
||||
{
|
||||
strGetFileName = "";
|
||||
strGetExtension = "";
|
||||
|
||||
iSelectType = 2;
|
||||
}
|
||||
else
|
||||
bCheckPos = false;
|
||||
|
||||
if (bCheckPos)
|
||||
{
|
||||
var bytes = new byte[1];
|
||||
|
||||
switch (iSelectType)
|
||||
{
|
||||
case 1:
|
||||
bytes = File.ReadAllBytes(@refObjGetPos);
|
||||
break;
|
||||
case 2:
|
||||
bytes = XDataArchive.CompressDatasetToByte(refObj as DataSet);
|
||||
break;
|
||||
}
|
||||
/*
|
||||
try
|
||||
{
|
||||
Bitmap xBitmap = new Bitmap(@refObjGetPos);
|
||||
|
||||
using (var stream = new MemoryStream())
|
||||
{
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
xBitmap.Save(stream, xBitmap.RawFormat);
|
||||
bytes = stream.ToArray();
|
||||
}
|
||||
|
||||
//ImageConverter _imageConverter = new ImageConverter();
|
||||
//bytes = (byte[])_imageConverter.ConvertTo(xBitmap, typeof(byte[]));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bytes = File.ReadAllBytes(@refObjGetPos);
|
||||
}
|
||||
*/
|
||||
|
||||
var memoryStream = new MemoryStream(bytes);
|
||||
//moryStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
//byte[] getSendOrgFileByte = memoryStream.ToArray();
|
||||
//byte[] getSendCompressFileByte = new byte[1];
|
||||
//getSendCompressFileByte = XNetArchive.CompressGZipByteToByte(getSendOrgFileByte);
|
||||
//getSendCompressFileByte = bytes;
|
||||
|
||||
if (iSelectType == 1)
|
||||
{
|
||||
byte[] getSendCompressFileByte = XDataArchive.CompressGZipByteToByte(memoryStream.ToArray());
|
||||
memoryStream = new MemoryStream(getSendCompressFileByte);
|
||||
}
|
||||
|
||||
memoryStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
/*
|
||||
if (memoryStream.Length < SystemXNetSerialization.MAX_PACKET_SIZE)
|
||||
{
|
||||
//throw new Exception("The file use normal send mode. " + refObjGetPos);
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"The file use normal send mode. " + refObjGetPos + " [SystemX.Common : SystemXNetCommons.ObjectToByteStreamList]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
*/
|
||||
|
||||
int iFileSize = (int)memoryStream.Length;
|
||||
int iRemainSize = (int)memoryStream.Length;
|
||||
|
||||
uint uiMakeCnt = (uint)(Math.Ceiling((double)((double)iFileSize / (double)SystemXNetSerialization.MAX_PACKET_SIZE)));
|
||||
|
||||
int iSendPos = 0;
|
||||
|
||||
for (uint i = 0; i < uiMakeCnt; i++)
|
||||
{
|
||||
byte[] ucSendData = null;
|
||||
|
||||
if (iRemainSize >= SystemXNetSerialization.MAX_PACKET_SIZE)
|
||||
{
|
||||
ucSendData = new byte[SystemXNetSerialization.MAX_PACKET_SIZE];
|
||||
|
||||
int iRead = memoryStream.Read(ucSendData, 0, SystemXNetSerialization.MAX_PACKET_SIZE);
|
||||
|
||||
//Array.Copy(getSendCompressFileByte, iSendPos, ucSendData, 0, SystemXNetSerialization.MAX_PACKET_SIZE);
|
||||
|
||||
iSendPos += SystemXNetSerialization.MAX_PACKET_SIZE;
|
||||
iRemainSize -= SystemXNetSerialization.MAX_PACKET_SIZE;
|
||||
}
|
||||
else
|
||||
{
|
||||
ucSendData = new byte[iRemainSize];
|
||||
|
||||
int iRead = memoryStream.Read(ucSendData, 0, iRemainSize);
|
||||
|
||||
//Array.Copy(getSendCompressFileByte, iSendPos, ucSendData, 0, iRemainSize);
|
||||
|
||||
iSendPos += iRemainSize;
|
||||
iRemainSize -= iRemainSize;
|
||||
}
|
||||
|
||||
HEADER_PACKET setHeader = new HEADER_PACKET();
|
||||
int iHeaderSize = Marshal.SizeOf(setHeader);
|
||||
byte[] ucHeaderMake = new byte[iHeaderSize];
|
||||
setHeader = (HEADER_PACKET)SystemXNetSerialization.RawDeSerialize(ucHeaderMake, setHeader.GetType());
|
||||
iHeaderSize = Marshal.SizeOf(setHeader);
|
||||
|
||||
//Various Parameter
|
||||
int nParamPos = 0;
|
||||
foreach (string strParam in strParameters)
|
||||
{
|
||||
switch (nParamPos)
|
||||
{
|
||||
case 0: setHeader.objVarParam1[0].Data = strParam; break;
|
||||
case 1: setHeader.objVarParam2[0].Data = strParam; break;
|
||||
case 2: setHeader.objVarParam3[0].Data = strParam; break;
|
||||
}
|
||||
|
||||
nParamPos++;
|
||||
}
|
||||
|
||||
if (iSelectType == 1)
|
||||
setHeader.usPalletIndex = usPalletIdx;
|
||||
else if (iSelectType == 2)
|
||||
setHeader.usPalletIndex = ushort.MaxValue;
|
||||
|
||||
setHeader.usCommand = SET_PROTOCOL.COMMAND;
|
||||
setHeader.usSubCommand = SET_PROTOCOL.SUB_COMMAND;
|
||||
setHeader.uiOptionCommand = SET_PROTOCOL.OPTION_COMMAND;
|
||||
|
||||
setHeader.uiHeaderLength = (uint)iHeaderSize;
|
||||
setHeader.uiDataLength = (uint)ucSendData.Count();
|
||||
|
||||
if (getCPPacket == null)
|
||||
{
|
||||
setHeader.objCP_Packet[0].objStationName[0].Data = "-";
|
||||
setHeader.objCP_Packet[0].objProdNo_P[0].Data = "-";
|
||||
setHeader.objCP_Packet[0].objProdNo_C[0].Data = "-";
|
||||
setHeader.objCP_Packet[0].objTestType[0].Data = "-";
|
||||
setHeader.objCP_Packet[0].objTestCode[0].Data = "-";
|
||||
setHeader.objCP_Packet[0].objVersion[0].Data = "-";
|
||||
setHeader.objCP_Packet[0].objProdCode[0].Data = "-";
|
||||
setHeader.objCP_Packet[0].uiTestListNo = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
setHeader.objCP_Packet[0].objStationName[0].Data = getCPPacket.Value.objStationName[0].Data;
|
||||
setHeader.objCP_Packet[0].objProdNo_P[0].Data = getCPPacket.Value.objProdNo_P[0].Data;
|
||||
setHeader.objCP_Packet[0].objProdNo_C[0].Data = getCPPacket.Value.objProdNo_C[0].Data;
|
||||
setHeader.objCP_Packet[0].objTestType[0].Data = getCPPacket.Value.objTestType[0].Data;
|
||||
setHeader.objCP_Packet[0].objTestCode[0].Data = getCPPacket.Value.objTestCode[0].Data;
|
||||
setHeader.objCP_Packet[0].objVersion[0].Data = getCPPacket.Value.objVersion[0].Data;
|
||||
setHeader.objCP_Packet[0].objProdCode[0].Data = getCPPacket.Value.objProdCode[0].Data;
|
||||
setHeader.objCP_Packet[0].uiTestListNo = getCPPacket.Value.uiTestListNo;
|
||||
}
|
||||
|
||||
setHeader.objOptionName[0].Data = strGetFileName;
|
||||
setHeader.objOptionExtension[0].Data = strGetExtension;
|
||||
|
||||
setHeader.uiSourDataNum = i + 1;
|
||||
setHeader.uiDestDataNum = uiMakeCnt;
|
||||
|
||||
object getPacket = SystemXNetSerialization.SelectPacket(setHeader.uiDataLength);
|
||||
if (getPacket == null) throw new Exception("SystemXNetSerialization.SelectPacket Failed.");
|
||||
int iBodySize = Marshal.SizeOf(getPacket);
|
||||
byte[] ucBodyArray = new byte[iBodySize];
|
||||
getPacket = Convert.ChangeType(SystemXNetSerialization.RawDeSerialize(ucBodyArray, getPacket.GetType()), getPacket.GetType());
|
||||
Array.Copy(ucSendData, (byte[])getPacket.GetType().GetMethod("Data").Invoke(getPacket, null), ucSendData.Count());
|
||||
|
||||
setHeader.uiBodyLength = (uint)iBodySize;
|
||||
setHeader.uiPacketLength = (uint)(iHeaderSize + iBodySize);
|
||||
|
||||
byte[] SendHeadBuffer = SystemXNetSerialization.RawSerialize(setHeader, Marshal.SizeOf(setHeader));
|
||||
|
||||
byte[] SendBodyBuffer = SystemXNetSerialization.RawSerialize(getPacket, Marshal.SizeOf(getPacket));
|
||||
|
||||
ucGetStreamBytes = HeadTailMake(setHeader.uiPacketLength, SendHeadBuffer, SendBodyBuffer);
|
||||
|
||||
listStreamRawData.Add(ucGetStreamBytes);
|
||||
}
|
||||
//string strMessage = Encoding.Unicode.GetString(ucGetFileBytes, 0, ucGetFileBytes.Length) + "\r\n";
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//throw new CommonPacketMarshalException("General packet marshalling failed.[SystemX.Common : COMMON.ObjectToByteStreamList]");
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General packet marshalling failed.[SystemX.Common : COMMON.ObjectToByteStreamList]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
;//Until unused
|
||||
}
|
||||
|
||||
return listStreamRawData;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,465 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Serialization.Formatters.Binary;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Net.BaseProtocol;
|
||||
|
||||
//프로토콜 직렬화/역직렬화 기능
|
||||
//기본 프로토콜 정의 포함
|
||||
namespace SystemX.Common.Serialization
|
||||
{
|
||||
public static class SystemXNetSerialization
|
||||
{
|
||||
private const int MAX_STEP_PACKET_SIZE = 256000;
|
||||
|
||||
public const int MAX_PACKET_SIZE = 512000; //1024000 <- 256000 <- 65536;
|
||||
//public const int MAX_PACKET_SIZE = 256000; //1024000 <- 256000 <- 65536;
|
||||
|
||||
public const int PACKET_NUM = 251; // 250 <- 64;
|
||||
|
||||
public static object SelectPacket(uint uiDataSize)
|
||||
{
|
||||
object objPacket = null;
|
||||
|
||||
//uint uiLowBytes = 0;
|
||||
//uint uiHighBytes = 1024;
|
||||
//
|
||||
|
||||
/*
|
||||
FieldInfo field = typeof(StructureToMarshalFrom).GetField("_value1");
|
||||
object[] attributes = field.GetCustomAttributes(typeof(MarshalAsAttribute), false);
|
||||
MarshalAsAttribute marshal = (MarshalAsAttribute) attributes[0];
|
||||
int sizeConst = marshal.SizeConst
|
||||
*/
|
||||
|
||||
int iPacketPos = GetPacketPos(uiDataSize);
|
||||
objPacket = SetPacketObject(iPacketPos);
|
||||
|
||||
/*
|
||||
for (int i = 0; i < PACKET_NUM; i++)
|
||||
{
|
||||
uiLowBytes = (uint)(1024 * i);
|
||||
uiHighBytes = (uint)(1024 * (i + 1));
|
||||
|
||||
if (uiDataSize >= uiLowBytes && uiDataSize <= uiHighBytes)
|
||||
{
|
||||
objPacket = SetPacketObject(i);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
return objPacket;
|
||||
}
|
||||
public static int SelectPacketSize(PACKET_SIZE SET_SIZE)
|
||||
{
|
||||
object objPacket = null;
|
||||
int iSetSize = 0;
|
||||
|
||||
objPacket = SetPacketObject((int)SET_SIZE);
|
||||
|
||||
HEADER_PACKET HeaderPacket = new HEADER_PACKET();
|
||||
int iHeadSize = Marshal.SizeOf(HeaderPacket);
|
||||
int iPacketSize = 0;
|
||||
|
||||
if (objPacket != null)
|
||||
iPacketSize = Marshal.SizeOf(objPacket);
|
||||
|
||||
iSetSize = iHeadSize + iPacketSize;
|
||||
|
||||
return iSetSize;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
private static int GetPacketPos(uint uiDataSize)
|
||||
{
|
||||
int uiGetSizeMajor = -1;
|
||||
|
||||
/*uiGetSizeMajor = (int)(uiDataSize / 1024);
|
||||
int uiGetSizeMinor = (int)(uiDataSize % 1024);
|
||||
|
||||
if (uiGetSizeMajor == 0)
|
||||
uiGetSizeMajor = 0;
|
||||
|
||||
if (uiGetSizeMinor == 0)
|
||||
uiGetSizeMajor -= 1;*/
|
||||
|
||||
if (uiDataSize > MAX_STEP_PACKET_SIZE)
|
||||
{
|
||||
if (uiDataSize <= 512000) uiGetSizeMajor = 250;
|
||||
|
||||
/*
|
||||
else if (uiDataSize <= 1024000) uiGetSizeMajor = 251;
|
||||
else if (uiDataSize <= 2048000) uiGetSizeMajor = 252;
|
||||
else if (uiDataSize <= 3072000) uiGetSizeMajor = 253;
|
||||
else if (uiDataSize <= 4096000) uiGetSizeMajor = 254;
|
||||
else if (uiDataSize <= 5120000) uiGetSizeMajor = 255;
|
||||
else if (uiDataSize <= 6144000) uiGetSizeMajor = 256;
|
||||
else if (uiDataSize <= 7168000) uiGetSizeMajor = 257;
|
||||
else if (uiDataSize <= 8192000) uiGetSizeMajor = 258;
|
||||
else if (uiDataSize <= 9216000) uiGetSizeMajor = 259;
|
||||
else if (uiDataSize <= 10240000) uiGetSizeMajor = 260;
|
||||
*/
|
||||
}
|
||||
else
|
||||
{
|
||||
uiGetSizeMajor = (int)(uiDataSize / 1024);
|
||||
int uiGetSizeMinor = (int)(uiDataSize % 1024);
|
||||
|
||||
if (uiGetSizeMajor == 0)
|
||||
uiGetSizeMajor = 0;
|
||||
|
||||
if (uiGetSizeMinor == 0)
|
||||
uiGetSizeMajor -= 1;
|
||||
}
|
||||
|
||||
return uiGetSizeMajor;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
private static object SetPacketObject(int iSelectPos)
|
||||
{
|
||||
object objPacket = null;
|
||||
|
||||
switch (iSelectPos)
|
||||
{
|
||||
case 0: objPacket = new DATA_PACKET_1024(); break;
|
||||
case 1: objPacket = new DATA_PACKET_2048(); break;
|
||||
case 2: objPacket = new DATA_PACKET_3072(); break;
|
||||
case 3: objPacket = new DATA_PACKET_4096(); break;
|
||||
case 4: objPacket = new DATA_PACKET_5120(); break;
|
||||
case 5: objPacket = new DATA_PACKET_6144(); break;
|
||||
case 6: objPacket = new DATA_PACKET_7168(); break;
|
||||
case 7: objPacket = new DATA_PACKET_8192(); break;
|
||||
case 8: objPacket = new DATA_PACKET_9216(); break;
|
||||
case 9: objPacket = new DATA_PACKET_10240(); break;
|
||||
case 10: objPacket = new DATA_PACKET_11264(); break;
|
||||
case 11: objPacket = new DATA_PACKET_12288(); break;
|
||||
case 12: objPacket = new DATA_PACKET_13312(); break;
|
||||
case 13: objPacket = new DATA_PACKET_14336(); break;
|
||||
case 14: objPacket = new DATA_PACKET_15360(); break;
|
||||
case 15: objPacket = new DATA_PACKET_16384(); break;
|
||||
case 16: objPacket = new DATA_PACKET_17408(); break;
|
||||
case 17: objPacket = new DATA_PACKET_18432(); break;
|
||||
case 18: objPacket = new DATA_PACKET_19456(); break;
|
||||
case 19: objPacket = new DATA_PACKET_20480(); break;
|
||||
case 20: objPacket = new DATA_PACKET_21504(); break;
|
||||
case 21: objPacket = new DATA_PACKET_22528(); break;
|
||||
case 22: objPacket = new DATA_PACKET_23552(); break;
|
||||
case 23: objPacket = new DATA_PACKET_24576(); break;
|
||||
case 24: objPacket = new DATA_PACKET_25600(); break;
|
||||
case 25: objPacket = new DATA_PACKET_26624(); break;
|
||||
case 26: objPacket = new DATA_PACKET_27648(); break;
|
||||
case 27: objPacket = new DATA_PACKET_28672(); break;
|
||||
case 28: objPacket = new DATA_PACKET_29696(); break;
|
||||
case 29: objPacket = new DATA_PACKET_30720(); break;
|
||||
case 30: objPacket = new DATA_PACKET_31744(); break;
|
||||
case 31: objPacket = new DATA_PACKET_32768(); break;
|
||||
case 32: objPacket = new DATA_PACKET_33792(); break;
|
||||
case 33: objPacket = new DATA_PACKET_34816(); break;
|
||||
case 34: objPacket = new DATA_PACKET_35840(); break;
|
||||
case 35: objPacket = new DATA_PACKET_36864(); break;
|
||||
case 36: objPacket = new DATA_PACKET_37888(); break;
|
||||
case 37: objPacket = new DATA_PACKET_38912(); break;
|
||||
case 38: objPacket = new DATA_PACKET_39936(); break;
|
||||
case 39: objPacket = new DATA_PACKET_40960(); break;
|
||||
case 40: objPacket = new DATA_PACKET_41984(); break;
|
||||
case 41: objPacket = new DATA_PACKET_43008(); break;
|
||||
case 42: objPacket = new DATA_PACKET_44032(); break;
|
||||
case 43: objPacket = new DATA_PACKET_45056(); break;
|
||||
case 44: objPacket = new DATA_PACKET_46080(); break;
|
||||
case 45: objPacket = new DATA_PACKET_47104(); break;
|
||||
case 46: objPacket = new DATA_PACKET_48128(); break;
|
||||
case 47: objPacket = new DATA_PACKET_49152(); break;
|
||||
case 48: objPacket = new DATA_PACKET_50176(); break;
|
||||
case 49: objPacket = new DATA_PACKET_51200(); break;
|
||||
case 50: objPacket = new DATA_PACKET_52224(); break;
|
||||
case 51: objPacket = new DATA_PACKET_53248(); break;
|
||||
case 52: objPacket = new DATA_PACKET_54272(); break;
|
||||
case 53: objPacket = new DATA_PACKET_55296(); break;
|
||||
case 54: objPacket = new DATA_PACKET_56320(); break;
|
||||
case 55: objPacket = new DATA_PACKET_57344(); break;
|
||||
case 56: objPacket = new DATA_PACKET_58368(); break;
|
||||
case 57: objPacket = new DATA_PACKET_59392(); break;
|
||||
case 58: objPacket = new DATA_PACKET_60416(); break;
|
||||
case 59: objPacket = new DATA_PACKET_61440(); break;
|
||||
case 60: objPacket = new DATA_PACKET_62464(); break;
|
||||
case 61: objPacket = new DATA_PACKET_63488(); break;
|
||||
case 62: objPacket = new DATA_PACKET_64512(); break;
|
||||
case 63: objPacket = new DATA_PACKET_65536(); break;
|
||||
case 64: objPacket = new DATA_PACKET_66560(); break;
|
||||
case 65: objPacket = new DATA_PACKET_67584(); break;
|
||||
case 66: objPacket = new DATA_PACKET_68608(); break;
|
||||
case 67: objPacket = new DATA_PACKET_69632(); break;
|
||||
case 68: objPacket = new DATA_PACKET_70656(); break;
|
||||
case 69: objPacket = new DATA_PACKET_71680(); break;
|
||||
case 70: objPacket = new DATA_PACKET_72704(); break;
|
||||
case 71: objPacket = new DATA_PACKET_73728(); break;
|
||||
case 72: objPacket = new DATA_PACKET_74752(); break;
|
||||
case 73: objPacket = new DATA_PACKET_75776(); break;
|
||||
case 74: objPacket = new DATA_PACKET_76800(); break;
|
||||
case 75: objPacket = new DATA_PACKET_77824(); break;
|
||||
case 76: objPacket = new DATA_PACKET_78848(); break;
|
||||
case 77: objPacket = new DATA_PACKET_79872(); break;
|
||||
case 78: objPacket = new DATA_PACKET_80896(); break;
|
||||
case 79: objPacket = new DATA_PACKET_81920(); break;
|
||||
case 80: objPacket = new DATA_PACKET_82944(); break;
|
||||
case 81: objPacket = new DATA_PACKET_83968(); break;
|
||||
case 82: objPacket = new DATA_PACKET_84992(); break;
|
||||
case 83: objPacket = new DATA_PACKET_86016(); break;
|
||||
case 84: objPacket = new DATA_PACKET_87040(); break;
|
||||
case 85: objPacket = new DATA_PACKET_88064(); break;
|
||||
case 86: objPacket = new DATA_PACKET_89088(); break;
|
||||
case 87: objPacket = new DATA_PACKET_90112(); break;
|
||||
case 88: objPacket = new DATA_PACKET_91136(); break;
|
||||
case 89: objPacket = new DATA_PACKET_92160(); break;
|
||||
case 90: objPacket = new DATA_PACKET_93184(); break;
|
||||
case 91: objPacket = new DATA_PACKET_94208(); break;
|
||||
case 92: objPacket = new DATA_PACKET_95232(); break;
|
||||
case 93: objPacket = new DATA_PACKET_96256(); break;
|
||||
case 94: objPacket = new DATA_PACKET_97280(); break;
|
||||
case 95: objPacket = new DATA_PACKET_98304(); break;
|
||||
case 96: objPacket = new DATA_PACKET_99328(); break;
|
||||
case 97: objPacket = new DATA_PACKET_100352(); break;
|
||||
case 98: objPacket = new DATA_PACKET_101376(); break;
|
||||
case 99: objPacket = new DATA_PACKET_102400(); break;
|
||||
case 100: objPacket = new DATA_PACKET_103424(); break;
|
||||
case 101: objPacket = new DATA_PACKET_104448(); break;
|
||||
case 102: objPacket = new DATA_PACKET_105472(); break;
|
||||
case 103: objPacket = new DATA_PACKET_106496(); break;
|
||||
case 104: objPacket = new DATA_PACKET_107520(); break;
|
||||
case 105: objPacket = new DATA_PACKET_108544(); break;
|
||||
case 106: objPacket = new DATA_PACKET_109568(); break;
|
||||
case 107: objPacket = new DATA_PACKET_110592(); break;
|
||||
case 108: objPacket = new DATA_PACKET_111616(); break;
|
||||
case 109: objPacket = new DATA_PACKET_112640(); break;
|
||||
case 110: objPacket = new DATA_PACKET_113664(); break;
|
||||
case 111: objPacket = new DATA_PACKET_114688(); break;
|
||||
case 112: objPacket = new DATA_PACKET_115712(); break;
|
||||
case 113: objPacket = new DATA_PACKET_116736(); break;
|
||||
case 114: objPacket = new DATA_PACKET_117760(); break;
|
||||
case 115: objPacket = new DATA_PACKET_118784(); break;
|
||||
case 116: objPacket = new DATA_PACKET_119808(); break;
|
||||
case 117: objPacket = new DATA_PACKET_120832(); break;
|
||||
case 118: objPacket = new DATA_PACKET_121856(); break;
|
||||
case 119: objPacket = new DATA_PACKET_122880(); break;
|
||||
case 120: objPacket = new DATA_PACKET_123904(); break;
|
||||
case 121: objPacket = new DATA_PACKET_124928(); break;
|
||||
case 122: objPacket = new DATA_PACKET_125952(); break;
|
||||
case 123: objPacket = new DATA_PACKET_126976(); break;
|
||||
case 124: objPacket = new DATA_PACKET_128000(); break;
|
||||
case 125: objPacket = new DATA_PACKET_129024(); break;
|
||||
case 126: objPacket = new DATA_PACKET_130048(); break;
|
||||
case 127: objPacket = new DATA_PACKET_131072(); break;
|
||||
case 128: objPacket = new DATA_PACKET_132096(); break;
|
||||
case 129: objPacket = new DATA_PACKET_133120(); break;
|
||||
case 130: objPacket = new DATA_PACKET_134144(); break;
|
||||
case 131: objPacket = new DATA_PACKET_135168(); break;
|
||||
case 132: objPacket = new DATA_PACKET_136192(); break;
|
||||
case 133: objPacket = new DATA_PACKET_137216(); break;
|
||||
case 134: objPacket = new DATA_PACKET_138240(); break;
|
||||
case 135: objPacket = new DATA_PACKET_139264(); break;
|
||||
case 136: objPacket = new DATA_PACKET_140288(); break;
|
||||
case 137: objPacket = new DATA_PACKET_141312(); break;
|
||||
case 138: objPacket = new DATA_PACKET_142336(); break;
|
||||
case 139: objPacket = new DATA_PACKET_143360(); break;
|
||||
case 140: objPacket = new DATA_PACKET_144384(); break;
|
||||
case 141: objPacket = new DATA_PACKET_145408(); break;
|
||||
case 142: objPacket = new DATA_PACKET_146432(); break;
|
||||
case 143: objPacket = new DATA_PACKET_147456(); break;
|
||||
case 144: objPacket = new DATA_PACKET_148480(); break;
|
||||
case 145: objPacket = new DATA_PACKET_149504(); break;
|
||||
case 146: objPacket = new DATA_PACKET_150528(); break;
|
||||
case 147: objPacket = new DATA_PACKET_151552(); break;
|
||||
case 148: objPacket = new DATA_PACKET_152576(); break;
|
||||
case 149: objPacket = new DATA_PACKET_153600(); break;
|
||||
case 150: objPacket = new DATA_PACKET_154624(); break;
|
||||
case 151: objPacket = new DATA_PACKET_155648(); break;
|
||||
case 152: objPacket = new DATA_PACKET_156672(); break;
|
||||
case 153: objPacket = new DATA_PACKET_157696(); break;
|
||||
case 154: objPacket = new DATA_PACKET_158720(); break;
|
||||
case 155: objPacket = new DATA_PACKET_159744(); break;
|
||||
case 156: objPacket = new DATA_PACKET_160768(); break;
|
||||
case 157: objPacket = new DATA_PACKET_161792(); break;
|
||||
case 158: objPacket = new DATA_PACKET_162816(); break;
|
||||
case 159: objPacket = new DATA_PACKET_163840(); break;
|
||||
case 160: objPacket = new DATA_PACKET_164864(); break;
|
||||
case 161: objPacket = new DATA_PACKET_165888(); break;
|
||||
case 162: objPacket = new DATA_PACKET_166912(); break;
|
||||
case 163: objPacket = new DATA_PACKET_167936(); break;
|
||||
case 164: objPacket = new DATA_PACKET_168960(); break;
|
||||
case 165: objPacket = new DATA_PACKET_169984(); break;
|
||||
case 166: objPacket = new DATA_PACKET_171008(); break;
|
||||
case 167: objPacket = new DATA_PACKET_172032(); break;
|
||||
case 168: objPacket = new DATA_PACKET_173056(); break;
|
||||
case 169: objPacket = new DATA_PACKET_174080(); break;
|
||||
case 170: objPacket = new DATA_PACKET_175104(); break;
|
||||
case 171: objPacket = new DATA_PACKET_176128(); break;
|
||||
case 172: objPacket = new DATA_PACKET_177152(); break;
|
||||
case 173: objPacket = new DATA_PACKET_178176(); break;
|
||||
case 174: objPacket = new DATA_PACKET_179200(); break;
|
||||
case 175: objPacket = new DATA_PACKET_180224(); break;
|
||||
case 176: objPacket = new DATA_PACKET_181248(); break;
|
||||
case 177: objPacket = new DATA_PACKET_182272(); break;
|
||||
case 178: objPacket = new DATA_PACKET_183296(); break;
|
||||
case 179: objPacket = new DATA_PACKET_184320(); break;
|
||||
case 180: objPacket = new DATA_PACKET_185344(); break;
|
||||
case 181: objPacket = new DATA_PACKET_186368(); break;
|
||||
case 182: objPacket = new DATA_PACKET_187392(); break;
|
||||
case 183: objPacket = new DATA_PACKET_188416(); break;
|
||||
case 184: objPacket = new DATA_PACKET_189440(); break;
|
||||
case 185: objPacket = new DATA_PACKET_190464(); break;
|
||||
case 186: objPacket = new DATA_PACKET_191488(); break;
|
||||
case 187: objPacket = new DATA_PACKET_192512(); break;
|
||||
case 188: objPacket = new DATA_PACKET_193536(); break;
|
||||
case 189: objPacket = new DATA_PACKET_194560(); break;
|
||||
case 190: objPacket = new DATA_PACKET_195584(); break;
|
||||
case 191: objPacket = new DATA_PACKET_196608(); break;
|
||||
case 192: objPacket = new DATA_PACKET_197632(); break;
|
||||
case 193: objPacket = new DATA_PACKET_198656(); break;
|
||||
case 194: objPacket = new DATA_PACKET_199680(); break;
|
||||
case 195: objPacket = new DATA_PACKET_200704(); break;
|
||||
case 196: objPacket = new DATA_PACKET_201728(); break;
|
||||
case 197: objPacket = new DATA_PACKET_202752(); break;
|
||||
case 198: objPacket = new DATA_PACKET_203776(); break;
|
||||
case 199: objPacket = new DATA_PACKET_204800(); break;
|
||||
case 200: objPacket = new DATA_PACKET_205824(); break;
|
||||
case 201: objPacket = new DATA_PACKET_206848(); break;
|
||||
case 202: objPacket = new DATA_PACKET_207872(); break;
|
||||
case 203: objPacket = new DATA_PACKET_208896(); break;
|
||||
case 204: objPacket = new DATA_PACKET_209920(); break;
|
||||
case 205: objPacket = new DATA_PACKET_210944(); break;
|
||||
case 206: objPacket = new DATA_PACKET_211968(); break;
|
||||
case 207: objPacket = new DATA_PACKET_212992(); break;
|
||||
case 208: objPacket = new DATA_PACKET_214016(); break;
|
||||
case 209: objPacket = new DATA_PACKET_215040(); break;
|
||||
case 210: objPacket = new DATA_PACKET_216064(); break;
|
||||
case 211: objPacket = new DATA_PACKET_217088(); break;
|
||||
case 212: objPacket = new DATA_PACKET_218112(); break;
|
||||
case 213: objPacket = new DATA_PACKET_219136(); break;
|
||||
case 214: objPacket = new DATA_PACKET_220160(); break;
|
||||
case 215: objPacket = new DATA_PACKET_221184(); break;
|
||||
case 216: objPacket = new DATA_PACKET_222208(); break;
|
||||
case 217: objPacket = new DATA_PACKET_223232(); break;
|
||||
case 218: objPacket = new DATA_PACKET_224256(); break;
|
||||
case 219: objPacket = new DATA_PACKET_225280(); break;
|
||||
case 220: objPacket = new DATA_PACKET_226304(); break;
|
||||
case 221: objPacket = new DATA_PACKET_227328(); break;
|
||||
case 222: objPacket = new DATA_PACKET_228352(); break;
|
||||
case 223: objPacket = new DATA_PACKET_229376(); break;
|
||||
case 224: objPacket = new DATA_PACKET_230400(); break;
|
||||
case 225: objPacket = new DATA_PACKET_231424(); break;
|
||||
case 226: objPacket = new DATA_PACKET_232448(); break;
|
||||
case 227: objPacket = new DATA_PACKET_233472(); break;
|
||||
case 228: objPacket = new DATA_PACKET_234496(); break;
|
||||
case 229: objPacket = new DATA_PACKET_235520(); break;
|
||||
case 230: objPacket = new DATA_PACKET_236544(); break;
|
||||
case 231: objPacket = new DATA_PACKET_237568(); break;
|
||||
case 232: objPacket = new DATA_PACKET_238592(); break;
|
||||
case 233: objPacket = new DATA_PACKET_239616(); break;
|
||||
case 234: objPacket = new DATA_PACKET_240640(); break;
|
||||
case 235: objPacket = new DATA_PACKET_241664(); break;
|
||||
case 236: objPacket = new DATA_PACKET_242688(); break;
|
||||
case 237: objPacket = new DATA_PACKET_243712(); break;
|
||||
case 238: objPacket = new DATA_PACKET_244736(); break;
|
||||
case 239: objPacket = new DATA_PACKET_245760(); break;
|
||||
case 240: objPacket = new DATA_PACKET_246784(); break;
|
||||
case 241: objPacket = new DATA_PACKET_247808(); break;
|
||||
case 242: objPacket = new DATA_PACKET_248832(); break;
|
||||
case 243: objPacket = new DATA_PACKET_249856(); break;
|
||||
case 244: objPacket = new DATA_PACKET_250880(); break;
|
||||
case 245: objPacket = new DATA_PACKET_251904(); break;
|
||||
case 246: objPacket = new DATA_PACKET_252928(); break;
|
||||
case 247: objPacket = new DATA_PACKET_253952(); break;
|
||||
case 248: objPacket = new DATA_PACKET_254976(); break;
|
||||
case 249: objPacket = new DATA_PACKET_256000(); break;
|
||||
case 250: objPacket = new DATA_PACKET_512000(); break;
|
||||
|
||||
/*
|
||||
case 251: objPacket = new DATA_PACKET_1024000(); break;
|
||||
case 252: objPacket = new DATA_PACKET_2048000(); break;
|
||||
case 253: objPacket = new DATA_PACKET_3072000(); break;
|
||||
case 254: objPacket = new DATA_PACKET_4096000(); break;
|
||||
case 255: objPacket = new DATA_PACKET_5120000(); break;
|
||||
case 256: objPacket = new DATA_PACKET_6144000(); break;
|
||||
case 257: objPacket = new DATA_PACKET_7168000(); break;
|
||||
case 258: objPacket = new DATA_PACKET_8192000(); break;
|
||||
case 259: objPacket = new DATA_PACKET_9216000(); break;
|
||||
case 260: objPacket = new DATA_PACKET_10240000(); break;
|
||||
*/
|
||||
|
||||
default: objPacket = null; break;
|
||||
}
|
||||
|
||||
return objPacket;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
public static byte[] RawSerialize(object ShmStruct, int irsStructSize)
|
||||
{
|
||||
IntPtr buffer = Marshal.AllocHGlobal(irsStructSize);
|
||||
Marshal.StructureToPtr(ShmStruct, buffer, false);
|
||||
byte[] RawData = new byte[irsStructSize];
|
||||
Marshal.Copy(buffer, RawData, 0, irsStructSize);
|
||||
Marshal.FreeHGlobal(buffer);
|
||||
return RawData;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
public static object RawDeSerialize(byte[] RawData, Type typeData, int iOption = 0)
|
||||
{
|
||||
int RawSize = 0;
|
||||
|
||||
if (iOption == 0)
|
||||
RawSize = Marshal.SizeOf(typeData);
|
||||
else
|
||||
RawSize = iOption;
|
||||
|
||||
//Size Over
|
||||
if (RawSize > RawData.Length)
|
||||
return null;
|
||||
|
||||
IntPtr buffer = Marshal.AllocHGlobal(RawSize);
|
||||
Marshal.Copy(RawData, 0, buffer, RawSize);
|
||||
object retobj = Marshal.PtrToStructure(buffer, typeData);
|
||||
Marshal.FreeHGlobal(buffer);
|
||||
return retobj;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
public static byte[] ObjectToByteArray(object obj)
|
||||
{
|
||||
if (obj == null) return null;
|
||||
|
||||
BinaryFormatter bf = new BinaryFormatter();
|
||||
MemoryStream ms = new MemoryStream();
|
||||
bf.Serialize(ms, obj);
|
||||
return ms.ToArray();
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
public static object ByteArrayToObject(byte[] byteArr)
|
||||
{
|
||||
if (byteArr == null) return null;
|
||||
|
||||
MemoryStream ms = new MemoryStream();
|
||||
BinaryFormatter bf = new BinaryFormatter();
|
||||
ms.Write(byteArr, 0, byteArr.Length);
|
||||
ms.Seek(0, SeekOrigin.Begin);
|
||||
object obj = bf.Deserialize(ms);
|
||||
|
||||
return obj;
|
||||
}
|
||||
public static T ByteArrayToObject<T>(byte[] byteArr)
|
||||
{
|
||||
if (byteArr == null) return default(T);
|
||||
|
||||
MemoryStream ms = new MemoryStream();
|
||||
BinaryFormatter bf = new BinaryFormatter();
|
||||
ms.Write(byteArr, 0, byteArr.Length);
|
||||
ms.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
return (T)Convert.ChangeType(bf.Deserialize(ms), typeof(T));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
public static class AppWinControl
|
||||
{
|
||||
public enum eShowType
|
||||
{
|
||||
SW_HIDE = 0, //Hides the window and activates another window.
|
||||
SW_MAXIMIZE = 3, //Maximizes the specified window.
|
||||
SW_MINIMIZE = 6, //Minimizes the specified window and activates the next top-level window in the Z order.
|
||||
SW_RESTORE = 9, //Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window.
|
||||
SW_SHOW = 5, //Activates the window and displays it in its current size and position.
|
||||
SW_SHOWDEFAULT = 10, //Sets the show state based on the SW_ value specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application.
|
||||
SW_SHOWMAXIMIZED = 3, //Activates the window and displays it as a maximized window.
|
||||
SW_SHOWMINIMIZED = 2, //Activates the window and displays it as a minimized window.
|
||||
SW_SHOWMINNOACTIVE = 7, //Displays the window as a minimized window. This value is similar to SW_SHOWMINIMIZED, except the window is not activated.
|
||||
SW_SHOWNA = 8, //Displays the window in its current size and position. This value is similar to SW_SHOW, except that the window is not activated.
|
||||
SW_SHOWNOACTIVATE = 4, //Displays a window in its most recent size and position. This value is similar to SW_SHOWNORMAL, except that the window is not activated.
|
||||
SW_SHOWNORMAL = 1
|
||||
}
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern IntPtr ExtGetWindowRect(IntPtr hWnd, out Rect lpRect);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern bool ExtPrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern int ExtSetForegroundWindow(IntPtr hWnd);
|
||||
|
||||
private const int SW_RESTORE = 9;
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr ExtShowWindow(IntPtr hWnd, int nCmdShow);
|
||||
|
||||
public static IntPtr GetWindowRect(IntPtr hWnd, out Rect lpRect) { return ExtGetWindowRect(hWnd, out lpRect); }
|
||||
public static bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags) { return ExtPrintWindow(hWnd, hdcBlt, nFlags); }
|
||||
public static int SetForegroundWindow(IntPtr hWnd) { return ExtSetForegroundWindow(hWnd); }
|
||||
public static IntPtr ShowWindow(IntPtr hWnd, int nCmdShow) { return ExtShowWindow(hWnd, nCmdShow); }
|
||||
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,338 @@
|
||||
using System;
|
||||
|
||||
// http://www.codeproject.com/Articles/13756/Detecting-Application-Idleness
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
/// <summary>
|
||||
/// ApplicationIdleTimer provides a convenient way of
|
||||
/// processing events only during application dormancy.
|
||||
/// Why use this instead of the Application.Idle event?
|
||||
/// That event gets fired EVERY TIME the message stack
|
||||
/// is exhausted, which basically means it fires very
|
||||
/// frequently. With this, you only get events when
|
||||
/// the application is actually idle.
|
||||
/// </summary>
|
||||
public class ApplicationIdleTimer
|
||||
{
|
||||
|
||||
#region Static Members and Events
|
||||
|
||||
// private singleton
|
||||
private static ApplicationIdleTimer instance = null;
|
||||
|
||||
// Notes:
|
||||
// Could have utilized the System.Timers.ElapsedEventArgs, but that
|
||||
// only provides the time an event happend (even though it's called
|
||||
// "Elapsed" not "Timed" EventArgs). I figgure most listeners care
|
||||
// less *WHEN* the app went idle, but rather *HOW LONG* it has been
|
||||
// idle.
|
||||
|
||||
/// <summary>
|
||||
/// EventArgs for an ApplicationIdle event.
|
||||
/// </summary>
|
||||
public class ApplicationIdleEventArgs : EventArgs
|
||||
{
|
||||
// time of last idle
|
||||
private DateTime _idleSince;
|
||||
// duration of "idleness"
|
||||
private TimeSpan _idleTime;
|
||||
|
||||
/// <summary>
|
||||
/// Internal constructor
|
||||
/// </summary>
|
||||
/// <param name="idleSince">Time app was declared idle</param>
|
||||
internal ApplicationIdleEventArgs(DateTime idleSince) : base()
|
||||
{
|
||||
_idleSince = idleSince;
|
||||
_idleTime = new TimeSpan(DateTime.Now.Ticks - idleSince.Ticks);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Timestamp of the last time the application was "active".
|
||||
/// </summary>
|
||||
public DateTime IdleSince
|
||||
{
|
||||
get { return _idleSince; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Duration of time the application has been idle.
|
||||
/// </summary>
|
||||
public TimeSpan IdleDuration
|
||||
{
|
||||
get { return _idleTime; }
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// ApplicationIdle event handler.
|
||||
/// </summary>
|
||||
public delegate void ApplicationIdleEventHandler(ApplicationIdleEventArgs e);
|
||||
|
||||
/// <summary>
|
||||
/// Hook into the ApplicationIdle event to monitor inactivity.
|
||||
/// It will fire AT MOST once per second.
|
||||
/// </summary>
|
||||
public static event ApplicationIdleEventHandler ApplicationIdle;
|
||||
#endregion
|
||||
|
||||
#region Private Members
|
||||
// Timer used to guarentee perodic updates.
|
||||
private System.Timers.Timer _timer;
|
||||
|
||||
// Tracks idle state
|
||||
private bool isIdle;
|
||||
// Last time application was declared "idle"
|
||||
private System.DateTime lastAppIdleTime;
|
||||
// Last time we checked for GUI activity
|
||||
private long lastIdleCheckpoint;
|
||||
// Running count of Application.Idle events recorded since a checkpoint.
|
||||
// Expressed as a long (instead of int) for math.
|
||||
private long idlesSinceCheckpoint;
|
||||
// Number of ticks used by application process at last checkpoint
|
||||
private long cpuTime;
|
||||
// Last time we checked for cpu activity
|
||||
private long lastCpuCheckpoint;
|
||||
|
||||
// These values can be adjusted through the static properties:
|
||||
// Maximum "activity" (Application.Idle events per second) that will be considered "idle"
|
||||
// Here it is expressed as minimum ticks between idles.
|
||||
private long guiThreshold = TimeSpan.TicksPerMillisecond * 50L;
|
||||
// Maximum CPU use (percentage) that is considered "idle"
|
||||
private double cpuThreshold = 0.05;
|
||||
#endregion
|
||||
|
||||
#region Constructors
|
||||
/// <summary>
|
||||
/// Private constructor. One instance is plenty.
|
||||
/// </summary>
|
||||
private ApplicationIdleTimer()
|
||||
{
|
||||
// Initialize counters
|
||||
isIdle = false;
|
||||
lastAppIdleTime = DateTime.Now;
|
||||
lastIdleCheckpoint = lastCpuCheckpoint = DateTime.UtcNow.Ticks;
|
||||
idlesSinceCheckpoint = cpuTime = 0;
|
||||
|
||||
// Set up the timer and the counters
|
||||
_timer = new System.Timers.Timer(500); // every half-second.
|
||||
_timer.Enabled = true;
|
||||
_timer.Start();
|
||||
|
||||
// Hook into the events
|
||||
_timer.Elapsed += new System.Timers.ElapsedEventHandler(Heartbeat);
|
||||
System.Windows.Forms.Application.Idle += new EventHandler(Application_Idle);
|
||||
}
|
||||
/// <summary>
|
||||
/// Static initialization. Called once per AppDomain.
|
||||
/// </summary>
|
||||
static ApplicationIdleTimer()
|
||||
{
|
||||
// Create the singleton.
|
||||
if (instance == null)
|
||||
{
|
||||
instance = new ApplicationIdleTimer();
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Private Methods
|
||||
|
||||
private void Heartbeat(object sender, System.Timers.ElapsedEventArgs e)
|
||||
{
|
||||
// First we need to do here is compensate for the
|
||||
// "heartbeat", since it will result in an 'extra'
|
||||
// Idle firing .. just don't cause a divide by zero!
|
||||
if (idlesSinceCheckpoint > 1)
|
||||
idlesSinceCheckpoint--;
|
||||
|
||||
bool newIdle = isIdle;
|
||||
long delta = DateTime.UtcNow.Ticks - lastIdleCheckpoint;
|
||||
|
||||
// Determine average idle events per second. Done manually here
|
||||
// instead of using the ComputeGUIActivity() method to avoid the
|
||||
// unnecessary numeric conversion and use of a TimeSpan object.
|
||||
if (delta >= TimeSpan.TicksPerSecond)
|
||||
{
|
||||
// It's been over a second since last checkpoint,
|
||||
// so determine how "busy" the app has been over that timeframe.
|
||||
if (idlesSinceCheckpoint == 0 || delta / idlesSinceCheckpoint >= guiThreshold)
|
||||
{
|
||||
// Minimal gui activity. Check recent CPU activity.
|
||||
if (cpuThreshold < 1.0)
|
||||
newIdle = (ComputeCPUUsage(true) < cpuThreshold);
|
||||
else
|
||||
newIdle = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
newIdle = false;
|
||||
}
|
||||
|
||||
// Update counters if state changed.
|
||||
if (newIdle != isIdle)
|
||||
{
|
||||
isIdle = newIdle;
|
||||
if (newIdle)
|
||||
lastAppIdleTime = DateTime.Now.AddTicks(-1L * delta);
|
||||
}
|
||||
|
||||
// Reset checkpoint.
|
||||
lastIdleCheckpoint = DateTime.UtcNow.Ticks;
|
||||
idlesSinceCheckpoint = 0;
|
||||
|
||||
// Last but not least, if idle, raise the event.
|
||||
if (newIdle)
|
||||
OnApplicationIdle();
|
||||
}
|
||||
}
|
||||
private void Application_Idle(object sender, EventArgs e)
|
||||
{
|
||||
// Increment idle counter.
|
||||
idlesSinceCheckpoint++;
|
||||
}
|
||||
|
||||
internal double ComputeCPUUsage(bool resetCounters)
|
||||
{
|
||||
long delta = DateTime.UtcNow.Ticks - lastCpuCheckpoint;
|
||||
double pctUse = 0.0;
|
||||
try
|
||||
{
|
||||
// Get total time this process has used the cpu.
|
||||
long cpu = System.Diagnostics.Process.GetCurrentProcess().TotalProcessorTime.Ticks;
|
||||
|
||||
// Compute usage.
|
||||
if (delta > 0)
|
||||
pctUse = ((double)(cpu - cpuTime)) / (double)delta;
|
||||
else
|
||||
pctUse = ((cpu - cpuTime) == 0 ? 0.0 : 1.0);
|
||||
|
||||
// Update counter and checkpoint if told OR if delta is at least a quarter second.
|
||||
// This is to prevent inaccurate readings due to frequent OR infrequent calls.
|
||||
if (resetCounters || 4L * delta >= TimeSpan.TicksPerSecond)
|
||||
{
|
||||
lastCpuCheckpoint = DateTime.UtcNow.Ticks;
|
||||
cpuTime = cpu;
|
||||
|
||||
// Update idle status if above threshold.
|
||||
if (!resetCounters && isIdle && pctUse > cpuThreshold)
|
||||
isIdle = false;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// Probably a security thing. Just ignore.
|
||||
pctUse = double.NaN;
|
||||
}
|
||||
return pctUse;
|
||||
}
|
||||
|
||||
internal double ComputeGUIActivity()
|
||||
{
|
||||
if (idlesSinceCheckpoint <= 0) return 0.0;
|
||||
|
||||
TimeSpan delta = new TimeSpan(DateTime.UtcNow.Ticks - lastIdleCheckpoint);
|
||||
if (delta.Ticks == 0)
|
||||
{
|
||||
// Clock hasn't updated yet. Return a "real" value
|
||||
// based on counter (either 0 or twice the threshold).
|
||||
return (idlesSinceCheckpoint == 0 ? 0.0 : ((double)TimeSpan.TicksPerSecond / (double)instance.guiThreshold) * 2.0);
|
||||
}
|
||||
|
||||
// Expressed as activity (number of idles) per second.
|
||||
return ((double)idlesSinceCheckpoint / delta.TotalSeconds);
|
||||
|
||||
// Note that this method, unlike his CPU brother, does not reset any counters.
|
||||
// The gui activity counters are reset once a second by the Heartbeat.
|
||||
}
|
||||
private void OnApplicationIdle()
|
||||
{
|
||||
// Check to see if anyone cares.
|
||||
if (ApplicationIdle == null) return;
|
||||
|
||||
// Build the message
|
||||
ApplicationIdleEventArgs e = new ApplicationIdleEventArgs(this.lastAppIdleTime);
|
||||
|
||||
// Iterate over all listeners
|
||||
foreach (MulticastDelegate multicast in ApplicationIdle.GetInvocationList())
|
||||
{
|
||||
// Raise the event
|
||||
multicast.DynamicInvoke(new object[] { e });
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Static Properties
|
||||
/// <summary>
|
||||
/// Returns the percent CPU use for the current process (0.0-1.0).
|
||||
/// Will return double.NaN if indeterminate.
|
||||
/// </summary>
|
||||
public static double CurrentCPUUsage
|
||||
{
|
||||
get { return instance.ComputeCPUUsage(false); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns an "indication" of the gui activity, expressed as
|
||||
/// activity per second. 0 indicates no activity.
|
||||
/// GUI activity includes user interactions (typing,
|
||||
/// moving mouse) as well as events, paint operations, etc.
|
||||
/// </summary>
|
||||
public static double CurrentGUIActivity
|
||||
{
|
||||
get { return instance.ComputeGUIActivity(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the *last determined* idle state. Idle state is
|
||||
/// recomputed once per second. Both the gui and the cpu must
|
||||
/// be idle for this property to be true.
|
||||
/// </summary>
|
||||
public static bool IsIdle
|
||||
{
|
||||
get { return instance.isIdle; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The threshold (gui activity) for determining idleness.
|
||||
/// GUI activity below this level is considered "idle".
|
||||
/// </summary>
|
||||
public static double GUIActivityThreshold
|
||||
{
|
||||
get
|
||||
{
|
||||
return ((double)TimeSpan.TicksPerSecond / (double)instance.guiThreshold);
|
||||
}
|
||||
set
|
||||
{
|
||||
// validate value
|
||||
if (value <= 0.0)
|
||||
throw new ArgumentOutOfRangeException("GUIActivityThreshold", value, "GUIActivityThreshold must be greater than zero.");
|
||||
|
||||
instance.guiThreshold = (long)((double)TimeSpan.TicksPerSecond / value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The threshold (cpu usage) for determining idleness.
|
||||
/// CPU usage below this level is considered "idle".
|
||||
/// A value >= 1.0 will disable CPU idle checking.
|
||||
/// </summary>
|
||||
public static double CPUUsageThreshold
|
||||
{
|
||||
get { return instance.cpuThreshold; }
|
||||
set
|
||||
{
|
||||
if (value == instance.cpuThreshold)
|
||||
return;
|
||||
|
||||
// validate value
|
||||
if (value < 0.0)
|
||||
throw new ArgumentOutOfRangeException("CPUUsageThreshold", value, "Negative values are not allowed.");
|
||||
|
||||
instance.cpuThreshold = value;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,301 @@
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using static SystemX.Net.Platform.Common.Util.LogMessage;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
public static class ConsoleUtil
|
||||
{
|
||||
static bool ConsoleShowState = false;
|
||||
|
||||
const int SW_HIDE = 0;
|
||||
const int SW_SHOW = 5;
|
||||
|
||||
// STD_INPUT_HANDLE (DWORD): -10 is the standard input device.
|
||||
const int STD_INPUT_HANDLE = -10;
|
||||
|
||||
/// <summary>
|
||||
/// SC_CLOSE
|
||||
/// </summary>
|
||||
private const uint SC_CLOSE = 0xf060;
|
||||
|
||||
/// <summary>
|
||||
/// MF_ENABLED
|
||||
/// </summary>
|
||||
private const uint MF_ENABLED = 0x00000000;
|
||||
|
||||
/// <summary>
|
||||
/// MF_GRAYED
|
||||
/// </summary>
|
||||
private const uint MF_GRAYED = 0x00000001;
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
static extern IntPtr GetConsoleWindow();
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
static extern IntPtr GetStdHandle(int nStdHandle);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
|
||||
|
||||
#region 시스템 메뉴 구하기 - GetSystemMenu(windowHandle, revert)
|
||||
|
||||
/// <summary>
|
||||
/// 시스템 메뉴 구하기
|
||||
/// </summary>
|
||||
/// <param name="windowHandle">윈도우 핸들</param>
|
||||
/// <param name="revert">메뉴 복사 핸들 여부</param>
|
||||
/// <returns>시스템 메뉴 핸들</returns>
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetSystemMenu(IntPtr windowHandle, bool revert);
|
||||
|
||||
#endregion
|
||||
#region 메뉴 항목 이용 가능 여부 설정하기 - EnableMenuItem(menuHandle, menuItemID, enabled)
|
||||
|
||||
/// <summary>
|
||||
/// 메뉴 항목 이용 가능 여부 설정하기
|
||||
/// </summary>
|
||||
/// <param name="menuHandle">메뉴 핸들</param>
|
||||
/// <param name="menuItemID">메뉴 항목 ID</param>
|
||||
/// <param name="enabled">이용 가능 여부</param>
|
||||
/// <returns>처리 결과</returns>
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool EnableMenuItem(IntPtr menuHandle, uint menuItemID, uint enabled);
|
||||
#endregion
|
||||
|
||||
public static void ConsoleVisibleControl()
|
||||
{
|
||||
var handle = GetConsoleWindow();
|
||||
|
||||
if (ConsoleShowState)
|
||||
ConsoleHide(handle);
|
||||
else
|
||||
ConsoleShow(handle);
|
||||
}
|
||||
|
||||
public static void ConsoleHide()
|
||||
{
|
||||
var handle = GetConsoleWindow();
|
||||
var consoleHandle = GetStdHandle(STD_INPUT_HANDLE);
|
||||
|
||||
const uint ENABLE_QUICK_EDIT = 0x0040;
|
||||
const uint ENABLE_MOUSE_INPUT = 0x0010;
|
||||
|
||||
uint consoleMode = 0x0;
|
||||
|
||||
// get current console mode
|
||||
if (!GetConsoleMode(consoleHandle, out consoleMode))
|
||||
{
|
||||
// Error: Unable to get console mode.
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear the quick edit bit in the mode flags
|
||||
consoleMode &= ~ENABLE_QUICK_EDIT;
|
||||
consoleMode &= ~ENABLE_MOUSE_INPUT;
|
||||
|
||||
// set the new mode
|
||||
if (!SetConsoleMode(consoleHandle, consoleMode))
|
||||
{
|
||||
//ERROR: Unable to set console mode
|
||||
return;
|
||||
}
|
||||
|
||||
// Hide
|
||||
ShowWindow(handle, SW_HIDE);
|
||||
|
||||
ConsoleShowState = false;
|
||||
}
|
||||
|
||||
public static void ConsoleHide(IntPtr handle)
|
||||
{
|
||||
// Hide
|
||||
ShowWindow(handle, SW_HIDE);
|
||||
|
||||
ConsoleShowState = false;
|
||||
}
|
||||
|
||||
public static void ConsoleShow(IntPtr handle)
|
||||
{
|
||||
// Show
|
||||
SetCloseButtonEnabled(handle, false);
|
||||
|
||||
ShowWindow(handle, SW_SHOW);
|
||||
|
||||
ConsoleShowState = true;
|
||||
}
|
||||
|
||||
private static void SetCloseButtonEnabled(IntPtr windowHandle, bool enabled)
|
||||
{
|
||||
IntPtr systemMenuHandle = GetSystemMenu(windowHandle, false);
|
||||
|
||||
EnableMenuItem(systemMenuHandle, SC_CLOSE, (uint)(MF_ENABLED | (enabled ? MF_ENABLED : MF_GRAYED)));
|
||||
}
|
||||
}
|
||||
public static class CommonUtil
|
||||
{
|
||||
|
||||
public static string GetProfilePath(string programName = "", bool makeDirOnDemand = true)
|
||||
{
|
||||
var xProfilePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
var dir = String.Format(@"{0}\TESTApp\{1}", xProfilePath, programName);
|
||||
if (makeDirOnDemand && !Directory.Exists(dir))
|
||||
Directory.CreateDirectory(dir);
|
||||
|
||||
return dir;
|
||||
}
|
||||
|
||||
public static PropertyInfo GetProperty(object obj, string propName)
|
||||
{
|
||||
return obj.GetType().GetProperty(propName);
|
||||
}
|
||||
|
||||
public static void ClonePropertyValues<T>(T original, T clone)
|
||||
{
|
||||
foreach (_PropertyInfo info in original.GetType().GetProperties())
|
||||
SetPropertyValue(clone, info.Name, info.GetValue(original, null));
|
||||
}
|
||||
|
||||
public static T GetPropertyValue<T>(object obj, string propName)
|
||||
{
|
||||
return (T)obj.GetType().GetProperty(propName).GetValue(obj, null);
|
||||
}
|
||||
|
||||
public static void SetPropertyValue(object obj, string propName, object value)
|
||||
{
|
||||
obj.GetType().GetProperty(propName).SetValue(obj, value, null);
|
||||
}
|
||||
|
||||
public static Type GetType(string strType)
|
||||
{
|
||||
try
|
||||
{
|
||||
Type typeResult = Type.GetType("System." + strType, true, true);
|
||||
|
||||
return typeResult;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageOutput.ConsoleWrite("Type Recognition Error: " + ex.Message, ConsoleColor.Red, LogMessageLevel.FATAL);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Type GetType(Assembly assy, string strNameSpace, string strType)
|
||||
{
|
||||
try
|
||||
{
|
||||
string strFullName = $"{strNameSpace}." + strType;
|
||||
Type typeResult = Type.GetType(strFullName, true, true);
|
||||
|
||||
return typeResult;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageOutput.ConsoleWrite("Type Recognition Error: " + ex.Message, ConsoleColor.Red, LogMessageLevel.FATAL);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetStringFromASCII(int[] arrData, bool bReverseBit = false)
|
||||
{
|
||||
string sData = string.Empty;
|
||||
foreach (short s in arrData)
|
||||
{
|
||||
byte[] intBytes = BitConverter.GetBytes(s);
|
||||
|
||||
byte ucRever;
|
||||
if (bReverseBit)
|
||||
{
|
||||
ucRever = intBytes[0];
|
||||
intBytes[0] = intBytes[1];
|
||||
intBytes[1] = ucRever;
|
||||
}
|
||||
|
||||
foreach (byte b in intBytes)
|
||||
{
|
||||
if (b == 0)
|
||||
continue;
|
||||
|
||||
sData += ((Char)b).ToString(); // Ascii To Char
|
||||
}
|
||||
}
|
||||
return sData;
|
||||
}
|
||||
|
||||
public static short[] HexStringToBytes(string hexString)
|
||||
{
|
||||
if (hexString.Length % 2 != 0)
|
||||
hexString += "\0";
|
||||
|
||||
char[] result = hexString.ToCharArray();
|
||||
short[] arrShort = new short[hexString.Length / 2];
|
||||
byte[] bytes = new byte[hexString.Length];
|
||||
|
||||
for (int i = 0; i < result.Length; i++)
|
||||
bytes[i] = Convert.ToByte(result[i]);
|
||||
|
||||
for (int i = 0; i < bytes.Length; i += 2)
|
||||
arrShort[i / 2] = BitConverter.ToInt16(bytes, i);
|
||||
|
||||
return arrShort;
|
||||
}
|
||||
}
|
||||
|
||||
public partial class NativeMethods
|
||||
{
|
||||
[DllImportAttribute("kernel32.dll", SetLastError = true, EntryPoint = "CreateFile")]
|
||||
public static extern SafeFileHandle CreateFileW(
|
||||
[InAttribute()][MarshalAsAttribute(UnmanagedType.LPWStr)] string lpFileName,
|
||||
uint dwDesiredAccess,
|
||||
uint dwShareMode,
|
||||
[InAttribute()] System.IntPtr lpSecurityAttributes,
|
||||
uint dwCreationDisposition,
|
||||
uint dwFlagsAndAttributes,
|
||||
[InAttribute()] System.IntPtr hTemplateFile
|
||||
);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
|
||||
public static extern IntPtr CreateFile(
|
||||
[MarshalAs(UnmanagedType.LPTStr)] string filename,
|
||||
[MarshalAs(UnmanagedType.U4)] FileAccess access,
|
||||
[MarshalAs(UnmanagedType.U4)] FileShare share,
|
||||
IntPtr securityAttributes,
|
||||
[MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
|
||||
[MarshalAs(UnmanagedType.U4)] FileAttributes flagsAndAttributes,
|
||||
IntPtr templateFile);
|
||||
}
|
||||
|
||||
public partial class NativeConstants
|
||||
{
|
||||
|
||||
/// GENERIC_WRITE -> (0x40000000L)
|
||||
public const int GENERIC_WRITE = 1073741824;
|
||||
|
||||
public const uint GENERIC_READ = 2147483648;
|
||||
|
||||
/// FILE_SHARE_DELETE -> 0x00000004
|
||||
public const int FILE_SHARE_DELETE = 4;
|
||||
|
||||
/// FILE_SHARE_WRITE -> 0x00000002
|
||||
public const int FILE_SHARE_WRITE = 2;
|
||||
|
||||
/// FILE_SHARE_READ -> 0x00000001
|
||||
public const int FILE_SHARE_READ = 1;
|
||||
|
||||
/// OPEN_ALWAYS -> 4
|
||||
public const int OPEN_ALWAYS = 4;
|
||||
public const int CREATE_NEW = 1;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,34 @@
|
||||
using System;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
/// <summary>
|
||||
/// Subclass should have re-implemented the method by overriding, but it did not.
|
||||
/// </summary>
|
||||
public class NotReimplementedException : NotImplementedException
|
||||
{
|
||||
public NotReimplementedException() { }
|
||||
public NotReimplementedException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Subclass will not re-implemented. So you should not call this subclass method.
|
||||
/// </summary>
|
||||
public class WillNotBeReimplementedException : NotImplementedException
|
||||
{
|
||||
public WillNotBeReimplementedException() { }
|
||||
public WillNotBeReimplementedException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
public class UnexpectedCaseOccurredException : InvalidOperationException
|
||||
{
|
||||
public UnexpectedCaseOccurredException() { }
|
||||
public UnexpectedCaseOccurredException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
public class SampleException : Exception
|
||||
{
|
||||
public SampleException() { }
|
||||
public SampleException(string message) : base(message) { }
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,252 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
public static class FileSystemUtil
|
||||
{
|
||||
public static void DeleteFile(string strSourcePath)
|
||||
{
|
||||
if (!File.Exists(strSourcePath))
|
||||
return;
|
||||
|
||||
File.Delete(strSourcePath);
|
||||
}
|
||||
public static void CopyToDestination(string strSourcePath, string strDesitinationPath, bool bDeleteSrc, bool bOverwrite)
|
||||
{
|
||||
if (!Directory.Exists(Path.GetDirectoryName(strDesitinationPath)))
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(strDesitinationPath));
|
||||
|
||||
File.Copy(strSourcePath, strDesitinationPath, bOverwrite);
|
||||
|
||||
while(true)
|
||||
{
|
||||
FileInfo fileSrc = new FileInfo(strSourcePath);
|
||||
FileInfo fileDest = new FileInfo(strDesitinationPath);
|
||||
|
||||
if (fileSrc.Length == fileDest.Length)
|
||||
break;
|
||||
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
|
||||
if (bDeleteSrc)
|
||||
DeleteFile(strSourcePath);
|
||||
}
|
||||
|
||||
public static void Compress(DirectoryInfo directorySelected, string strFilePath)
|
||||
{
|
||||
using (var fileStream = new FileStream(strFilePath, FileMode.OpenOrCreate))
|
||||
{
|
||||
using (ZipArchive zip = new ZipArchive(fileStream, ZipArchiveMode.Create))
|
||||
{
|
||||
foreach (FileInfo file in directorySelected.GetFiles())
|
||||
{
|
||||
var entry = zip.CreateEntry(file.Name, CompressionLevel.Optimal);
|
||||
using (Stream s = entry.Open())
|
||||
{
|
||||
FileStream file2Comp = new FileStream(file.FullName, FileMode.Open);
|
||||
|
||||
byte[] data = new byte[file2Comp.Length];
|
||||
file2Comp.Read(data, 0, (int)file2Comp.Length);
|
||||
s.Write(data, 0, data.Length);
|
||||
|
||||
file2Comp.Close();
|
||||
s.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fileStream.Close();
|
||||
}
|
||||
}
|
||||
|
||||
public static void AddFile2CompFile(List<string> vstrTargetFilePath, string strCompFilePath)
|
||||
{
|
||||
using (var fileStream = new FileStream(strCompFilePath, FileMode.OpenOrCreate))
|
||||
{
|
||||
using (ZipArchive zip = new ZipArchive(fileStream, ZipArchiveMode.Create))
|
||||
{
|
||||
foreach (string strFilePath in vstrTargetFilePath)
|
||||
{
|
||||
string strTargetFileName = Path.GetFileName(strFilePath);
|
||||
var entry = zip.CreateEntry(strTargetFileName, CompressionLevel.Optimal);
|
||||
|
||||
using (Stream s = entry.Open())
|
||||
{
|
||||
FileStream file2Comp = new FileStream(strFilePath, FileMode.Open);
|
||||
|
||||
byte[] data = new byte[file2Comp.Length];
|
||||
file2Comp.Read(data, 0, (int)file2Comp.Length);
|
||||
s.Write(data, 0, data.Length);
|
||||
|
||||
file2Comp.Close();
|
||||
s.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fileStream.Close();
|
||||
}
|
||||
}
|
||||
|
||||
public static void CompressStream2CompFile(List<KeyValuePair<string, MemoryStream>> vPairTargetData, string strCompFilePath)
|
||||
{
|
||||
using (var fileStream = new FileStream(strCompFilePath, FileMode.OpenOrCreate))
|
||||
{
|
||||
using (ZipArchive zip = new ZipArchive(fileStream, ZipArchiveMode.Create))
|
||||
{
|
||||
foreach (KeyValuePair<string, MemoryStream> dataBinFile in vPairTargetData)
|
||||
{
|
||||
var entry = zip.CreateEntry(dataBinFile.Key, CompressionLevel.Optimal);
|
||||
|
||||
using (Stream s = entry.Open())
|
||||
{
|
||||
byte[] data = new byte[dataBinFile.Value.Length];
|
||||
s.Write(dataBinFile.Value.ToArray(), 0, data.Length);
|
||||
|
||||
s.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void Decompress(string strPathZip, string strPath)
|
||||
{
|
||||
if (!Directory.Exists(strPath))
|
||||
Directory.CreateDirectory(strPath);
|
||||
|
||||
using (ZipArchive archive = ZipFile.OpenRead(strPathZip))
|
||||
{
|
||||
foreach (ZipArchiveEntry entry in archive.Entries)
|
||||
{
|
||||
entry.ExtractToFile(Path.Combine(strPath, entry.FullName), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static List<string> GetFileList(string strPathZip)
|
||||
{
|
||||
List<string> vstrFileNames = new List<string>();
|
||||
|
||||
using (ZipArchive archive = ZipFile.OpenRead(strPathZip))
|
||||
{
|
||||
foreach (ZipArchiveEntry entry in archive.Entries)
|
||||
vstrFileNames.Add(entry.FullName);
|
||||
}
|
||||
|
||||
return vstrFileNames;
|
||||
}
|
||||
|
||||
public static bool IsFileExist(string strPathZip, string strFile)
|
||||
{
|
||||
using (ZipArchive archive = ZipFile.OpenRead(strPathZip))
|
||||
{
|
||||
ZipArchiveEntry entry = archive.Entries.Where(compFile => compFile.FullName == strFile).DefaultIfEmpty()?.First();
|
||||
|
||||
if (entry != null)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static MemoryStream OpenCompressWithoutUnzip(string strPathZip, string strFile)
|
||||
{
|
||||
Stream streamFile = null;
|
||||
|
||||
using (ZipArchive archive = ZipFile.OpenRead(strPathZip))
|
||||
{
|
||||
ZipArchiveEntry entry = archive.Entries.Where(compFile => compFile.FullName == strFile).DefaultIfEmpty()?.First();
|
||||
|
||||
if (entry != null)
|
||||
{
|
||||
streamFile = entry.Open();
|
||||
|
||||
return CopyToMemory(streamFile);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public static MemoryStream OpenCompressWithoutUnzip(Stream streamZip, string strFile)
|
||||
{
|
||||
Stream streamFile = null;
|
||||
|
||||
if (streamZip == null)
|
||||
return null;
|
||||
|
||||
using (ZipArchive archive = new ZipArchive(streamZip))
|
||||
{
|
||||
ZipArchiveEntry entry = archive.Entries.Where(compFile => compFile.FullName == strFile).DefaultIfEmpty()?.First();
|
||||
|
||||
if (entry != null)
|
||||
{
|
||||
streamFile = entry.Open();
|
||||
|
||||
return CopyToMemory(streamFile);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static MemoryStream CopyToMemory(Stream input)
|
||||
{
|
||||
// It won't matter if we throw an exception during this method;
|
||||
// we don't *really* need to dispose of the MemoryStream, and the
|
||||
// caller should dispose of the input stream
|
||||
MemoryStream ret = new MemoryStream();
|
||||
|
||||
byte[] buffer = new byte[8192];
|
||||
int bytesRead;
|
||||
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
|
||||
{
|
||||
ret.Write(buffer, 0, bytesRead);
|
||||
}
|
||||
// Rewind ready for reading (typical scenario)
|
||||
ret.Position = 0;
|
||||
return ret;
|
||||
}
|
||||
|
||||
static public void ClearDirectory(string strFolderPath)
|
||||
{
|
||||
if (Directory.Exists(strFolderPath))
|
||||
Directory.Delete(strFolderPath, true);
|
||||
}
|
||||
|
||||
static public void ClearFile(string strFilePath)
|
||||
{
|
||||
if (File.Exists(strFilePath))
|
||||
File.Delete(strFilePath);
|
||||
}
|
||||
|
||||
static public void MoveFile(string source, string destination)
|
||||
{
|
||||
if (!File.Exists(source))
|
||||
return;
|
||||
|
||||
if (!Directory.Exists(Path.GetDirectoryName(destination)))
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(destination));
|
||||
|
||||
// 2017.04.13 add M.S Ko
|
||||
if (File.Exists(destination))
|
||||
{
|
||||
File.Delete(destination);
|
||||
|
||||
LogMessage.MessageOutput.ConsoleWrite("File was deleted & moved name of " + destination, ConsoleColor.White);
|
||||
}
|
||||
|
||||
File.Move(source, destination);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,90 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
/// <summary>
|
||||
/// see http://www.thecoolestdolphin.be/?p=38
|
||||
/// TextBox 에서 invalid 문자를 filtering 함
|
||||
/// sister classes : Dsu.Common.Utilities.NumericTextBox
|
||||
/// </summary>
|
||||
public class FilterableTextBox : TextBox
|
||||
{
|
||||
/// <summary>
|
||||
/// 허용 문자 set.
|
||||
/// <para/> - empty 이면, ForbiddenCharacterSet 이외의 모든 문자 허용
|
||||
/// <para/> - empty 가 아니면 ForbiddenCharacterSet 는 의미가 없음
|
||||
/// </summary>
|
||||
public string AllowedCharacterSet { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 금칙 문자 set. AllowedCharacterSet 가 empty 인 경우에만 의미를 가짐
|
||||
/// </summary>
|
||||
public string ForbiddenCharacterSet { get; set; }
|
||||
|
||||
public bool ShowBalloonTips { get { return _showBalloonTips; } set { _showBalloonTips = value; }}
|
||||
private bool _showBalloonTips = true;
|
||||
private ToolTip _balloonTips;
|
||||
|
||||
public FilterableTextBox()
|
||||
{
|
||||
// default 는 alpha numeric 만 받음. 필요시 override.
|
||||
SetAlphaNumericFilter();
|
||||
|
||||
_balloonTips = new ToolTip()
|
||||
{
|
||||
ToolTipTitle = "Invalid character.",
|
||||
ToolTipIcon = ToolTipIcon.Warning,
|
||||
AutoPopDelay = 0,
|
||||
ShowAlways = false,
|
||||
};
|
||||
}
|
||||
protected override void OnKeyPress(KeyPressEventArgs e)
|
||||
{
|
||||
base.OnKeyPress(e);
|
||||
_balloonTips.Hide(this);
|
||||
|
||||
if ( Char.IsControl(e.KeyChar) || e.KeyChar == 46 ) // 8==backspace, 13=enter, 46=DEL
|
||||
return;
|
||||
|
||||
bool valid = true;
|
||||
if (String.IsNullOrEmpty(AllowedCharacterSet)) // 허용 문자를 지정하지 않은 경우. 금칙 문자에 포함되지 않으면 OK
|
||||
{
|
||||
if (!String.IsNullOrEmpty(ForbiddenCharacterSet) && ForbiddenCharacterSet.Contains(e.KeyChar))
|
||||
valid = false;
|
||||
}
|
||||
else // 허용 문자를 지정한 경우
|
||||
valid = AllowedCharacterSet.Contains(e.KeyChar);
|
||||
|
||||
|
||||
e.Handled = ! valid;
|
||||
|
||||
if ( ! valid && _showBalloonTips)
|
||||
_balloonTips.Show(String.Format("The character \"{0}\" is invalid.", e.KeyChar), this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Alpha-numeric 문자열 + addition 이 아니면 filtering 한다.
|
||||
/// </summary>
|
||||
/// <param name="addition"></param>
|
||||
public void SetAlphaNumericFilter(string addition="")
|
||||
{
|
||||
AllowedCharacterSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + addition;
|
||||
ForbiddenCharacterSet = String.Empty;
|
||||
}
|
||||
|
||||
public void SetFileNameFilter()
|
||||
{
|
||||
AllowedCharacterSet = String.Empty;
|
||||
ForbiddenCharacterSet = @"\/:*?""<>|";
|
||||
}
|
||||
|
||||
public void SetSymbolFilter(string addition="")
|
||||
{
|
||||
SetAlphaNumericFilter("@_?" + addition);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,25 @@
|
||||
using System;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
/// <summary>
|
||||
/// Generic event argument decorator class
|
||||
/// </summary>
|
||||
public class GenericEventArgs : EventArgs
|
||||
{
|
||||
private EventArgs _innerEventArgs;
|
||||
|
||||
public T Cast<T>() where T : EventArgs
|
||||
{
|
||||
if (_innerEventArgs is T)
|
||||
return (T)_innerEventArgs;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public GenericEventArgs(EventArgs args)
|
||||
{
|
||||
_innerEventArgs = args;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,61 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SystemX.Common.Util
|
||||
{
|
||||
public static class Gzip
|
||||
{
|
||||
#region Functions
|
||||
public static string Compress(string stringData)
|
||||
{
|
||||
var rowData = Encoding.UTF8.GetBytes(stringData);
|
||||
byte[] compressedData = null;
|
||||
using (var outStream = new MemoryStream())
|
||||
{
|
||||
using (var gStream = new GZipStream(outStream, CompressionMode.Compress))
|
||||
{
|
||||
gStream.Write(rowData, 0, rowData.Length);
|
||||
}
|
||||
compressedData = outStream.ToArray();
|
||||
}
|
||||
|
||||
return Convert.ToBase64String(compressedData);
|
||||
}
|
||||
|
||||
public static string Decompression(string compressedDataStr)
|
||||
{
|
||||
string output = null;
|
||||
byte[] compressedData = Convert.FromBase64String(compressedDataStr);
|
||||
using (var decompressStream = new MemoryStream(compressedData))
|
||||
{
|
||||
using (var gStream = new GZipStream(decompressStream, CompressionMode.Decompress))
|
||||
{
|
||||
using (var reader = new StreamReader(gStream))
|
||||
{
|
||||
output = reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region String Extension(확장메서드)
|
||||
public static string GzipCompress(this string stringData)
|
||||
{
|
||||
return Compress(stringData);
|
||||
}
|
||||
|
||||
public static string GzipDecompress(this string compressedDataStr)
|
||||
{
|
||||
return Decompression(compressedDataStr);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,124 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Windows.Forms;
|
||||
using log4net;
|
||||
using log4net.Appender;
|
||||
using SystemX.Net.Platform.Common.ExtensionMethods;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
public static class Log4NetWrapper
|
||||
{
|
||||
private static readonly LogProxy _dummyLogger = LogProxy.CreateLoggerProxy(MethodBase.GetCurrentMethod().DeclaringType);
|
||||
|
||||
private static ILog _logger = null;
|
||||
public static ILog Logger { get { return _logger ?? _dummyLogger.Logger; } set { _logger = value; } }
|
||||
|
||||
|
||||
#region Extension methods
|
||||
[Conditional("DEBUG")]
|
||||
public static void DEBUG(this ILog logger, object message, Exception exception)
|
||||
{
|
||||
if (logger.IsDebugEnabled) logger.Debug(message, exception);
|
||||
}
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
public static void DEBUG(this ILog logger, object message)
|
||||
{
|
||||
if (logger.IsDebugEnabled) logger.Debug(message);
|
||||
}
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
public static void DEBUGFORMAT(this ILog logger, string format, params object[] args)
|
||||
{
|
||||
if (logger.IsDebugEnabled) logger.DebugFormat(format, args);
|
||||
}
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
public static void DEBUGFORMAT(this ILog logger, string format, object arg0)
|
||||
{
|
||||
if (logger.IsDebugEnabled) logger.DebugFormat(format, arg0);
|
||||
}
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
public static void DEBUGFORMAT(this ILog logger, string format, object arg0, object arg1)
|
||||
{
|
||||
if (logger.IsDebugEnabled) logger.DebugFormat(format, arg0, arg1);
|
||||
}
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
public static void DEBUGFORMAT(this ILog logger, string format, object arg0, object arg1, object arg2)
|
||||
{
|
||||
if (logger.IsDebugEnabled) logger.DebugFormat(format, arg0, arg1, arg2);
|
||||
}
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
public static void DEBUGFORMAT(this ILog logger, IFormatProvider provider, string format, params object[] args)
|
||||
{
|
||||
if (logger.IsDebugEnabled) logger.DebugFormat(provider, format, args);
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="mainForm"></param>
|
||||
/// <param name="configFile">xml log configuration file</param>
|
||||
/// <param name="logFileName">real log file name to be generated.</param>
|
||||
public static void Install(IAppender mainForm, string configFile, string logFileName)
|
||||
{
|
||||
// http://stackoverflow.com/questions/2815940/where-will-log4net-create-this-log-file
|
||||
// see log4netXXXX.xml configuration file
|
||||
var appName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location);
|
||||
log4net.GlobalContext.Properties["LogFileName"] = logFileName.IsNullOrEmpty() ? Path.Combine(CommonUtil.GetProfilePath(), appName) : logFileName;
|
||||
|
||||
if ( File.Exists(configFile) )
|
||||
{
|
||||
log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(configFile));
|
||||
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.AddAppender(mainForm);
|
||||
}
|
||||
else
|
||||
MessageBox.Show(String.Format("Failed to load configuration file {0}.\r\nLog message will not be available.", configFile), appName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 분석 대상 assembly 의 type 을 검사하여, "logger" 라는 이름의 static 멤버를 찾고,
|
||||
/// 사전에 해당 객체를 생성해서 등록해 둔다.
|
||||
/// </summary>
|
||||
/// <param name="mainForm"></param>
|
||||
/// <param name="configFile">e.g "log4net.xml"</param>
|
||||
/// <param name="assemblies">Logger 를 포함하는 분석 대상 assemblies</param>
|
||||
/// <param name="logFileName">logFileName</param>
|
||||
/// <param name="staticLoggerMemberName">e.g "logger"</param>
|
||||
public static void Install(IAppender mainForm, string configFile, IEnumerable<Assembly> assemblies, string logFileName=null, string staticLoggerMemberName = "logger")
|
||||
{
|
||||
Install(mainForm, configFile, logFileName);
|
||||
|
||||
List<Type> types = new List<Type>();
|
||||
foreach (var assembly in assemblies)
|
||||
{
|
||||
foreach (Type t_ in assembly.GetTypes())
|
||||
{
|
||||
Type t = t_.DeclaringType ?? t_;
|
||||
MemberInfo[] mis = t.GetMember(staticLoggerMemberName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
|
||||
foreach (var mi in mis)
|
||||
{
|
||||
Type candidateType = mi.DeclaringType.DeclaringType ?? mi.DeclaringType;
|
||||
if (!types.Contains(candidateType))
|
||||
{
|
||||
types.Add(candidateType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var type in types)
|
||||
LogProxy.CreateLoggerProxy(type);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,73 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.Contracts;
|
||||
using log4net.Core;
|
||||
using SystemX.Net.Platform.Common.ExtensionMethods;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
public class LogEntryManager : IDisposable
|
||||
{
|
||||
private LoggingEvent[] _logEntries;
|
||||
public LoggingEvent[] LogEntries { get { return _logEntries; } }
|
||||
public int Capacity { get { return (int)_capacity; } set { _capacity = (ulong)value; } }
|
||||
private ulong _cursor = 0;
|
||||
private ulong _capacity = 0;
|
||||
|
||||
public int Count { get { return (int)Math.Min(_cursor, (ulong)Capacity); } }
|
||||
public LogEntryManager(int capacity)
|
||||
{
|
||||
Contract.Requires(capacity >= 0);
|
||||
Capacity = Math.Max(capacity, 1000);
|
||||
_logEntries = new LoggingEvent[Capacity];
|
||||
}
|
||||
|
||||
public void AddLogEntry(LoggingEvent logEntry)
|
||||
{
|
||||
_logEntries[_cursor++ % _capacity] = logEntry;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_logEntries = new LoggingEvent[Capacity];
|
||||
_cursor = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// logical index 를 physical index 로 변환해서 반환.
|
||||
/// e.g : capacity=1000, logical=1200 => physical=200
|
||||
/// </summary>
|
||||
/// <param name="n">logical index number</param>
|
||||
/// <returns>physical index number : capacity 적용하여 rolling 한 결과 값</returns>
|
||||
public int LogicalIndex2PhysicalIndex(int n)
|
||||
{
|
||||
Contract.Requires(n.InRange(0, Capacity - 1));
|
||||
|
||||
if (_cursor < _capacity)
|
||||
return n;
|
||||
|
||||
return (int)((_cursor + (ulong)n) % _capacity);
|
||||
}
|
||||
|
||||
public int PhysicalIndex2LogicalIndex(int n)
|
||||
{
|
||||
if (_cursor < _capacity)
|
||||
return n;
|
||||
|
||||
Debug.Assert((ulong)n < _cursor);
|
||||
|
||||
return (int)((ulong)n + (_cursor / _capacity) * _capacity);
|
||||
}
|
||||
|
||||
public LoggingEvent this[int n]
|
||||
{
|
||||
get { return _logEntries[LogicalIndex2PhysicalIndex(n)]; }
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_logEntries = null;
|
||||
_capacity = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,83 @@
|
||||
using log4net;
|
||||
using System;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
public class LogMessage
|
||||
{
|
||||
public enum LogMessageLevel
|
||||
{
|
||||
NONE = 0,
|
||||
FATAL,
|
||||
DEBUG,
|
||||
INFO,
|
||||
LAST
|
||||
};
|
||||
|
||||
public delegate void MessageEventHandlerOutput(string strMessage, ConsoleColor csColor = ConsoleColor.White, LogMessageLevel logLevel = LogMessageLevel.DEBUG);
|
||||
|
||||
static public class MessageOutput
|
||||
{
|
||||
private static ILog logger => Log4NetWrapper.Logger;
|
||||
static public LogMessageLevel PrintLogLevel { get; set; } = LogMessageLevel.DEBUG;
|
||||
static public MessageEventHandlerOutput UEventOutput;
|
||||
static public void ConsoleWrite(string strMessage, ConsoleColor csColor = ConsoleColor.White, LogMessageLevel logLevel = LogMessageLevel.DEBUG)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (PrintLogLevel >= logLevel)
|
||||
{
|
||||
Console.ForegroundColor = csColor;
|
||||
Console.WriteLine(strMessage);
|
||||
Console.ResetColor();
|
||||
UEventOutput?.Invoke(strMessage, csColor, logLevel);
|
||||
switch (logLevel)
|
||||
{
|
||||
case LogMessageLevel.FATAL:
|
||||
logger.Error(strMessage);
|
||||
|
||||
//WriteEventLogEntry(strMessage);
|
||||
break;
|
||||
case LogMessageLevel.DEBUG:
|
||||
logger.Debug(strMessage);
|
||||
break;
|
||||
default:
|
||||
logger.Info(strMessage);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (System.Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteEventLogEntry(string message)
|
||||
{
|
||||
// Create an instance of EventLog
|
||||
System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();
|
||||
|
||||
// Check if the event source exists. If not create it.
|
||||
if (!System.Diagnostics.EventLog.SourceExists("CP-ServerX"))
|
||||
{
|
||||
System.Diagnostics.EventLog.CreateEventSource("CP-ServerX", "SystemX");
|
||||
}
|
||||
|
||||
// Set the source name for writing log entries.
|
||||
eventLog.Source = "CP-ServerX";
|
||||
|
||||
// Create an event ID to add to the event log
|
||||
int eventID = 2051;
|
||||
|
||||
// Write an entry to the event log.
|
||||
eventLog.WriteEntry(message,
|
||||
System.Diagnostics.EventLogEntryType.Error,
|
||||
eventID);
|
||||
|
||||
// Close the Event Log
|
||||
eventLog.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,153 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using log4net;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
/// <summary>
|
||||
/// ILog 가 runtime 에 debug log 를 enable/disable 하는 기능을 지원하지 않으므로,
|
||||
/// proxy 를 통해서 enable/disable 한다.
|
||||
/// https://social.msdn.microsoft.com/forums/vstudio/en-US/0624de68-fe7f-45c0-9cd8-468d9dac844b/how-to-disable-log4net-debug-logging-during-runtime
|
||||
/// </summary>
|
||||
public class LogProxy
|
||||
{
|
||||
public ILog Logger { get; set; }
|
||||
public string Name { get { return Logger.Logger.Name; } }
|
||||
|
||||
public Type Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// runtime 에 debug 로그에 대한 enable/disable 여부
|
||||
/// </summary>
|
||||
public bool IsEnableDebug
|
||||
{
|
||||
get { return _isEnableDebug && Logger.IsDebugEnabled; }
|
||||
set
|
||||
{
|
||||
_isEnableDebug = value;
|
||||
Trace.WriteLine($"{Name}: IsEnableDebug={IsEnableDebug}");
|
||||
}
|
||||
}
|
||||
private bool _isEnableDebug = false;
|
||||
|
||||
public bool IsEnableInfo { get { return _isEnableInfo && Logger.IsInfoEnabled; } set { _isEnableInfo = value; } }
|
||||
private bool _isEnableInfo = false;
|
||||
|
||||
public bool IsEnableWarn { get { return _isEnableWarn && Logger.IsWarnEnabled; } set { _isEnableWarn = value; } }
|
||||
private bool _isEnableWarn = false;
|
||||
|
||||
/// <summary>
|
||||
/// 현재 등록된 logger 들 : var loggers = log4net.LogManager.GetCurrentLoggers(); 와 동일
|
||||
/// </summary>
|
||||
public static IEnumerable<LogProxy> CurrentLoggers { get { return _currentLoggers; } }
|
||||
private static List<LogProxy> _currentLoggers = new List<LogProxy>();
|
||||
|
||||
private LogProxy(Type type)
|
||||
{
|
||||
Type = type;
|
||||
Logger = log4net.LogManager.GetLogger(type);
|
||||
}
|
||||
|
||||
public static LogProxy GetLogProxy(Type t)
|
||||
{
|
||||
return CurrentLoggers.FirstOrDefault(l => l.Name == t.FullName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// proxy 된 logger 를 생성한다.
|
||||
/// </summary>
|
||||
/// <param name="t"></param>
|
||||
/// <param name="enableDebug"></param>
|
||||
/// <returns></returns>
|
||||
public static LogProxy CreateLoggerProxy(Type t, bool? enableDebug = null)
|
||||
{
|
||||
var proxy = GetLogProxy(t);
|
||||
if (proxy == null)
|
||||
{
|
||||
proxy = new LogProxy(t);
|
||||
_currentLoggers.Add(proxy);
|
||||
}
|
||||
|
||||
if (enableDebug.HasValue)
|
||||
proxy.IsEnableDebug = enableDebug.Value;
|
||||
|
||||
return proxy;
|
||||
}
|
||||
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
public void Debug(object message, Exception exception)
|
||||
{
|
||||
if (IsEnableDebug) Logger.Debug(message, exception);
|
||||
}
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
public void Debug(object message)
|
||||
{
|
||||
if (IsEnableDebug) Logger.Debug(message);
|
||||
}
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
public void DebugFormat(string format, params object[] args)
|
||||
{
|
||||
if (IsEnableDebug) Logger.DebugFormat(format, args);
|
||||
}
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
public void DebugFormat(string format, object arg0)
|
||||
{
|
||||
if (IsEnableDebug) Logger.DebugFormat(format, arg0);
|
||||
}
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
public void DebugFormat(string format, object arg0, object arg1)
|
||||
{
|
||||
if (IsEnableDebug) Logger.DebugFormat(format, arg0, arg1);
|
||||
}
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
public void DebugFormat(string format, object arg0, object arg1, object arg2)
|
||||
{
|
||||
if (IsEnableDebug) Logger.DebugFormat(format, arg0, arg1, arg2);
|
||||
}
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
public void DebugFormat(IFormatProvider provider, string format, params object[] args)
|
||||
{
|
||||
if (IsEnableDebug) Logger.DebugFormat(provider, format, args);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void Error(object message) { Logger.Error(message); }
|
||||
public void Error(object message, Exception exception) { Logger.Error(message, exception); }
|
||||
public void ErrorFormat(string format, object arg0) { Logger.ErrorFormat(format, arg0); }
|
||||
public void ErrorFormat(string format, params object[] args) { Logger.ErrorFormat(format, args); }
|
||||
public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { Logger.ErrorFormat(provider, format, args); }
|
||||
public void ErrorFormat(string format, object arg0, object arg1) { Logger.ErrorFormat(format, arg0, arg1); }
|
||||
public void ErrorFormat(string format, object arg0, object arg1, object arg2) { Logger.ErrorFormat(format, arg0, arg1, arg2); }
|
||||
public void Fatal(object message) { Logger.Fatal(message); }
|
||||
public void Fatal(object message, Exception exception) { Logger.Fatal(message, exception); }
|
||||
public void FatalFormat(string format, object arg0) { Logger.FatalFormat(format, arg0); }
|
||||
public void FatalFormat(string format, params object[] args) { Logger.FatalFormat(format, args); }
|
||||
public void FatalFormat(IFormatProvider provider, string format, params object[] args) { Logger.FatalFormat(provider, format, args); }
|
||||
public void FatalFormat(string format, object arg0, object arg1) { Logger.FatalFormat(format, arg0, arg1); }
|
||||
public void FatalFormat(string format, object arg0, object arg1, object arg2) { Logger.FatalFormat(format, arg0, arg1, arg2); }
|
||||
public void Info(object message) { if (IsEnableInfo) Logger.Info(message); }
|
||||
public void Info(object message, Exception exception) { if (IsEnableInfo) Logger.Info(message, exception); }
|
||||
public void InfoFormat(string format, object arg0) { if (IsEnableInfo) Logger.InfoFormat(format, arg0); }
|
||||
public void InfoFormat(string format, params object[] args) { if (IsEnableInfo) Logger.InfoFormat(format, args); }
|
||||
public void InfoFormat(IFormatProvider provider, string format, params object[] args) { if (IsEnableInfo) Logger.InfoFormat(provider, format, args); }
|
||||
public void InfoFormat(string format, object arg0, object arg1) { if (IsEnableInfo) Logger.InfoFormat(format, arg0, arg1); }
|
||||
public void InfoFormat(string format, object arg0, object arg1, object arg2) { if (IsEnableInfo) Logger.InfoFormat(format, arg0, arg1, arg2); }
|
||||
public void Warn(object message) { if (IsEnableWarn) Logger.Warn(message); }
|
||||
public void Warn(object message, Exception exception) { if (IsEnableWarn) Logger.Warn(message, exception); }
|
||||
public void WarnFormat(string format, object arg0) { if (IsEnableWarn) Logger.WarnFormat(format, arg0); }
|
||||
public void WarnFormat(string format, params object[] args) { if (IsEnableWarn) Logger.WarnFormat(format, args); }
|
||||
public void WarnFormat(IFormatProvider provider, string format, params object[] args) { if (IsEnableWarn) Logger.WarnFormat(provider, format, args); }
|
||||
public void WarnFormat(string format, object arg0, object arg1) { if (IsEnableWarn) Logger.WarnFormat(format, arg0, arg1); }
|
||||
public void WarnFormat(string format, object arg0, object arg1, object arg2) { if (IsEnableWarn) Logger.WarnFormat(format, arg0, arg1, arg2); }
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,81 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Windows.Forms;
|
||||
using log4net;
|
||||
using log4net.Core;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
public class LogRecord
|
||||
{
|
||||
[Browsable(false)]
|
||||
public LoggingEvent LogEntry { get; private set; }
|
||||
[DisplayName("Time")]
|
||||
public string TimeStamp { get { return LogEntry.TimeStamp.ToString("HH:mm:ss.ff"); } }
|
||||
public Level Level { get { return LogEntry.Level; } }
|
||||
[DisplayName("Sender")]
|
||||
public string LoggerName { get { return LogEntry.LoggerName; } }
|
||||
[DisplayName("Message")]
|
||||
public object MessageObject { get { return LogEntry.MessageObject; } }
|
||||
|
||||
[DisplayName("t-Id")]
|
||||
public string ThreadName { get { return LogEntry.ThreadName; } }
|
||||
|
||||
public LogRecord(LoggingEvent log)
|
||||
{
|
||||
LogEntry = log;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
|
||||
sb.Append(TimeStamp);
|
||||
sb.Append("\t");
|
||||
sb.Append(Level);
|
||||
sb.Append("\t");
|
||||
sb.Append(LoggerName);
|
||||
sb.Append("\t");
|
||||
sb.Append(MessageObject);
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[ComVisible(false)]
|
||||
public class LogRecordFiledWriter<T> : IDisposable
|
||||
{
|
||||
private bool _globalContext;
|
||||
private string _field;
|
||||
private T _valueBackup;
|
||||
|
||||
public LogRecordFiledWriter(string field, T value, bool globalContext=false)
|
||||
{
|
||||
_field = field;
|
||||
_globalContext = globalContext;
|
||||
|
||||
if (globalContext)
|
||||
{
|
||||
var backup = GlobalContext.Properties[field];
|
||||
_valueBackup = backup == null ? default(T) : (T)backup;
|
||||
GlobalContext.Properties[field] = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
var backup = ThreadContext.Properties[field];
|
||||
_valueBackup = backup == null ? default(T) : (T)backup;
|
||||
ThreadContext.Properties[field] = value;
|
||||
}
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
if (_globalContext)
|
||||
GlobalContext.Properties[_field] = _valueBackup;
|
||||
else
|
||||
ThreadContext.Properties[_field] = _valueBackup;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,432 @@
|
||||
//
|
||||
// http://www.mediafire.com/download/fidd3mm85dmq9tb/%281392.03.10%29+Numerical+TextBox+Sample.rar
|
||||
// 이거도 참고로 볼 것... 비슷하지만, 현재 것이 나아보임 http://www.codeproject.com/Articles/30812/Simple-Numeric-TextBox
|
||||
// http://www.thecoolestdolphin.be/?p=38 [Allow only specific characters in textBox in C#]
|
||||
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class NumericTextBox : TextBox
|
||||
{
|
||||
private bool _negative;
|
||||
private bool _dot;
|
||||
private bool _exponent;
|
||||
private int _decimalNumber;
|
||||
private int _cursorPositionPlus;
|
||||
private char _discriminant;
|
||||
private double _maxValue;
|
||||
private double _minValue;
|
||||
private bool _maxCheck;
|
||||
private bool _minCheck;
|
||||
private string _oldText;
|
||||
|
||||
public NumericTextBox()
|
||||
{
|
||||
_decimalNumber = 4;
|
||||
_negative = true;
|
||||
_dot = true;
|
||||
_exponent = true;
|
||||
_discriminant = ',';
|
||||
_maxValue = 0;
|
||||
_minValue = 0;
|
||||
_maxCheck = false;
|
||||
_minCheck = false;
|
||||
_oldText = string.Empty;
|
||||
|
||||
_balloonTips = new ToolTip()
|
||||
{
|
||||
ToolTipTitle = "Invalid character.",
|
||||
ToolTipIcon = ToolTipIcon.Warning,
|
||||
AutoPopDelay = 0,
|
||||
ShowAlways = false,
|
||||
};
|
||||
}
|
||||
public NumericTextBox(int decimalNumber)
|
||||
: this()
|
||||
{
|
||||
_decimalNumber = decimalNumber;
|
||||
}
|
||||
public NumericTextBox(char discriminant)
|
||||
: this(4)
|
||||
{
|
||||
if (discriminant == '\'' || discriminant == '/' || discriminant == '`')
|
||||
_discriminant = discriminant;
|
||||
else
|
||||
_discriminant = ',';
|
||||
}
|
||||
public NumericTextBox(int decimalNumber, char discriminant)
|
||||
: this(discriminant)
|
||||
{
|
||||
_decimalNumber = decimalNumber;
|
||||
}
|
||||
|
||||
[Description("1000 단위 comma 허용 여부")]
|
||||
public int DecimalNumber
|
||||
{
|
||||
get { return _decimalNumber; }
|
||||
set { _decimalNumber = value; OnTextChanged(new EventArgs()); }
|
||||
}
|
||||
|
||||
[Description("음수 허용 여부")]
|
||||
public bool Negative
|
||||
{
|
||||
get { return _negative; }
|
||||
set { _negative = value; OnTextChanged(new EventArgs()); }
|
||||
}
|
||||
[Description("Period 허용 여부")]
|
||||
public bool Dot
|
||||
{
|
||||
get { return _dot; }
|
||||
set { _dot = value; OnTextChanged(new EventArgs()); }
|
||||
}
|
||||
[Description("Scientific notation 허용 여부")]
|
||||
public bool Exponent
|
||||
{
|
||||
get { return _exponent; }
|
||||
set { _exponent = value; OnTextChanged(new EventArgs()); }
|
||||
}
|
||||
public char Discriminant
|
||||
{
|
||||
get { return _discriminant; }
|
||||
set
|
||||
{
|
||||
if (value == '\'' || value == '/' || value == '`')
|
||||
_discriminant = value;
|
||||
else
|
||||
_discriminant = ',';
|
||||
OnTextChanged(new EventArgs());
|
||||
}
|
||||
}
|
||||
public double MaxValue
|
||||
{
|
||||
get { return _maxValue; }
|
||||
set
|
||||
{
|
||||
_maxValue = (!MinCheck || value >= _minValue) ? value : _maxValue;
|
||||
if (_maxCheck && new NumericalString(this.Text) > _maxValue)
|
||||
this.Text = _maxValue.ToString();
|
||||
}
|
||||
}
|
||||
public double MinValue
|
||||
{
|
||||
get { return _minValue; }
|
||||
set
|
||||
{
|
||||
_minValue = (!MaxCheck || value <= _maxValue) ? value : _minValue;
|
||||
if (_minCheck && new NumericalString(this.Text) < _minValue)
|
||||
this.Text = _minValue.ToString();
|
||||
}
|
||||
}
|
||||
public bool MaxCheck
|
||||
{
|
||||
get { return _maxCheck; }
|
||||
set
|
||||
{
|
||||
_maxCheck = value;
|
||||
if (_maxCheck && new NumericalString(this.Text) > _maxValue)
|
||||
this.Text = _maxValue.ToString();
|
||||
}
|
||||
}
|
||||
public bool MinCheck
|
||||
{
|
||||
get { return _minCheck; }
|
||||
set
|
||||
{
|
||||
_minCheck = value;
|
||||
if (_minCheck && new NumericalString(this.Text) < _minValue)
|
||||
this.Text = _minValue.ToString();
|
||||
}
|
||||
}
|
||||
public NumericalString NumericalText
|
||||
{
|
||||
get { return new NumericalString(this.Text); }
|
||||
}
|
||||
|
||||
|
||||
public double GetDoubleValue()
|
||||
{
|
||||
double value;
|
||||
if (!Double.TryParse(NumericalText.Text, out value))
|
||||
return 0;
|
||||
return value;
|
||||
}
|
||||
public int GetIntValue()
|
||||
{
|
||||
int value;
|
||||
if (!Int32.TryParse(NumericalText.Text, out value))
|
||||
return 0;
|
||||
return value;
|
||||
}
|
||||
|
||||
|
||||
|
||||
#region Baloon Tips
|
||||
[Description("오류 문자 입력시 풍선 도움말 표시 여부")]
|
||||
public bool ShowBalloonTips { get { return _showBalloonTips; } set { _showBalloonTips = value; } }
|
||||
private bool _showBalloonTips = true;
|
||||
private ToolTip _balloonTips;
|
||||
#endregion
|
||||
|
||||
|
||||
protected override void OnTextChanged(EventArgs e)
|
||||
{
|
||||
_balloonTips.Hide(this);
|
||||
_cursorPositionPlus = 0;
|
||||
int SelectionStart = this.SelectionStart;
|
||||
int TextLength = this.Text.Length;
|
||||
int CursorPositionPlus;
|
||||
string Text = NormalTextToNumericString();
|
||||
CursorPositionPlus = _cursorPositionPlus;
|
||||
if ((!_maxCheck || new NumericalString(this.Text) <= _maxValue) && (!_minCheck || new NumericalString(this.Text) >= _minValue))
|
||||
{
|
||||
this.Text = Text;
|
||||
this.SelectionStart = SelectionStart + CursorPositionPlus;
|
||||
_oldText = this.Text;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Text = _oldText;
|
||||
this.SelectionStart = SelectionStart + _oldText.Length - TextLength;
|
||||
}
|
||||
base.OnTextChanged(e);
|
||||
}
|
||||
protected string NormalTextToNumericString()
|
||||
{
|
||||
string Text = this.Text;
|
||||
string TextTemp1 = string.Empty, TextTemp2 = string.Empty;
|
||||
#region Lowering Characters
|
||||
for (int i = 0; i < Text.Length; i++)
|
||||
TextTemp1 += char.ToLower(Text[i]);
|
||||
#endregion
|
||||
|
||||
|
||||
#region Remove Unknown Characters
|
||||
int FloatNumber = 0;
|
||||
for (int i = 0; i < TextTemp1.Length; i++)
|
||||
if (_negative && TextTemp1[i] == '-' && i == 0)
|
||||
TextTemp2 += TextTemp1[i];
|
||||
else if (TextTemp1[i] == '-' && TextTemp2.IndexOf('e') >= 0 && TextTemp2.Length == TextTemp2.IndexOf('e') + 1)
|
||||
TextTemp2 += TextTemp1[i];
|
||||
else if (char.IsDigit(TextTemp1[i]))
|
||||
{
|
||||
TextTemp2 += TextTemp1[i];
|
||||
if (TextTemp2.IndexOf('.') > -1 && TextTemp2.IndexOf('e') < 0 && i < this.SelectionStart)
|
||||
{
|
||||
FloatNumber++;
|
||||
if (FloatNumber > _decimalNumber && i < this.SelectionStart)
|
||||
_cursorPositionPlus--;
|
||||
}
|
||||
}
|
||||
else if (_dot && _decimalNumber > 0 && TextTemp1[i] == '.' && TextTemp2.IndexOf('.') < 0 && (TextTemp2.IndexOf('e') < 0 || TextTemp2.Length < TextTemp2.IndexOf('e')))
|
||||
TextTemp2 += TextTemp1[i];
|
||||
else if (_exponent && TextTemp1[i] == 'e' && TextTemp2.IndexOf('e') < 0 && TextTemp2.Length >= TextTemp2.IndexOf('.') + 1)
|
||||
TextTemp2 += TextTemp1[i];
|
||||
else if (i < this.SelectionStart)
|
||||
{
|
||||
bool skip = _decimalNumber != 0 && TextTemp1[i] == ',';
|
||||
if ( ! skip && ShowBalloonTips )
|
||||
_balloonTips.Show(String.Format("The character \"{0}\" is invalid.", TextTemp1[i]), this);
|
||||
|
||||
_cursorPositionPlus--;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#region Get Integer Number
|
||||
string INTEGER = string.Empty;
|
||||
int IntegerIndex = (TextTemp2.IndexOf('.') >= 0) ? TextTemp2.IndexOf('.') : (TextTemp2.IndexOf('e') >= 0) ? TextTemp2.IndexOf('e') : TextTemp2.Length;
|
||||
for (int i = 0; i < IntegerIndex; i++)
|
||||
if (char.IsDigit(TextTemp2[i]) || TextTemp2[i] == '-' && INTEGER.IndexOf('-') < 0)
|
||||
INTEGER += TextTemp2[i];
|
||||
#endregion
|
||||
#region Get Float Number
|
||||
string FLOAT = string.Empty;
|
||||
if (TextTemp2.IndexOf('.') >= 0)
|
||||
for (int i = TextTemp2.IndexOf('.') + 1; i < ((TextTemp2.IndexOf('e') >= 0) ? TextTemp2.IndexOf('e') : TextTemp2.Length); i++)
|
||||
if (char.IsDigit(TextTemp2[i]))
|
||||
FLOAT += TextTemp2[i];
|
||||
#endregion
|
||||
#region Put '/' Character in Integer Number
|
||||
string T = string.Empty;
|
||||
int n = 0;
|
||||
for (int i = INTEGER.Length - 1; i >= 0; i--)
|
||||
{
|
||||
T += INTEGER[i];
|
||||
n++;
|
||||
if (n == 3 && i > 0 && INTEGER[i - 1] != '-')
|
||||
{
|
||||
if (i - _cursorPositionPlus < this.SelectionStart)
|
||||
_cursorPositionPlus++;
|
||||
T += _discriminant.ToString();
|
||||
n = 0;
|
||||
}
|
||||
}
|
||||
char[] charArray = T.ToCharArray();
|
||||
Array.Reverse(charArray);
|
||||
T = new string(charArray);
|
||||
#endregion
|
||||
#region Put '.' Character
|
||||
if (TextTemp2.IndexOf('.') >= 0)
|
||||
{
|
||||
T += ('.').ToString();
|
||||
for (int i = 0; i < DecimalNumber && i < FLOAT.Length; i++)
|
||||
T += FLOAT[i];
|
||||
}
|
||||
#endregion
|
||||
#region Put 'e' Character
|
||||
if (TextTemp2.IndexOf('e') >= 0)
|
||||
{
|
||||
T += ('e').ToString();
|
||||
for (int i = TextTemp2.IndexOf('e') + 1; i < TextTemp2.Length; i++)
|
||||
T += TextTemp2[i];
|
||||
}
|
||||
#endregion
|
||||
return T;
|
||||
}
|
||||
}
|
||||
public class NumericalString
|
||||
{
|
||||
private string _text;
|
||||
public string Text
|
||||
{
|
||||
get { return _text; }
|
||||
set { _text = value; }
|
||||
}
|
||||
public NumericalString()
|
||||
{
|
||||
_text = string.Empty;
|
||||
}
|
||||
public NumericalString(string Text)
|
||||
{
|
||||
string Temp = string.Empty;
|
||||
for (int i = 0; i < Text.Length; i++)
|
||||
if (char.IsDigit(Text[i]) || Text[i] == '-' || Text[i] == '.' || Text[i] == 'e')
|
||||
Temp += Text[i];
|
||||
_text = Temp;
|
||||
}
|
||||
public override string ToString()
|
||||
{
|
||||
return (this.Text == string.Empty) ? "0" : this.Text;
|
||||
}
|
||||
public static implicit operator NumericalString(string Text)
|
||||
{
|
||||
return new NumericalString(Text);
|
||||
}
|
||||
public static explicit operator string(NumericalString Text)
|
||||
{
|
||||
return (Text.Text == "") ? "0" : Text.Text;
|
||||
}
|
||||
public static implicit operator double(NumericalString Text)
|
||||
{
|
||||
double value;
|
||||
if (Text.Text == "")
|
||||
return 0;
|
||||
if (Text.Text == "-")
|
||||
return 0;
|
||||
if (Text.Text == "-.")
|
||||
return 0;
|
||||
if (Text.Text.StartsWith("-e"))
|
||||
return 0;
|
||||
if (Text.Text.StartsWith("e"))
|
||||
return 0;
|
||||
if (Text.Text.EndsWith("e") || Text.Text.EndsWith("e-"))
|
||||
return Convert.ToDouble(Text.Text.Substring(0, Text.Text.IndexOf('e')));
|
||||
if (!Double.TryParse(Text.Text, out value))
|
||||
return Convert.ToDouble(Regex.Replace(Text.Text, @"\D", ""));
|
||||
|
||||
return Convert.ToDouble(Text.Text);
|
||||
}
|
||||
public static string operator +(NumericalString Text1, NumericalString Text2)
|
||||
{
|
||||
return Text1.Text + Text2.Text;
|
||||
}
|
||||
public static string operator +(NumericalString Text1, string Text2)
|
||||
{
|
||||
return Text1.Text + Text2;
|
||||
}
|
||||
public static string operator +(NumericalString Text1, char ch)
|
||||
{
|
||||
return Text1.Text + ch.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
|
||||
public partial class Form1 : Form
|
||||
{
|
||||
public Form1()
|
||||
{
|
||||
InitializeComponent();
|
||||
numericalTextBox.DecimalNumber = (int)DecimalNumberNumericUpDown.Value;
|
||||
numericalTextBox.Negative = NegativeSignCheckBox.Checked;
|
||||
numericalTextBox.Dot = DotCheckBox.Checked;
|
||||
numericalTextBox.Exponent = ExponentCheckBox.Checked;
|
||||
numericalTextBox.MaxValue = System.Convert.ToDouble(MaximumTextBox.Text);
|
||||
numericalTextBox.MinValue = System.Convert.ToDouble(MinimumTextBox.Text);
|
||||
numericalTextBox.MaxCheck = MaximumCheckBox.Checked;
|
||||
numericalTextBox.MinCheck = MinimumCheckBox.Checked;
|
||||
numericalTextBox.Discriminant = ',';
|
||||
}
|
||||
private void DecimalNumberNumericUpDown_ValueChanged(object sender, EventArgs e)
|
||||
{
|
||||
numericalTextBox.DecimalNumber = (int)DecimalNumberNumericUpDown.Value;
|
||||
}
|
||||
private void NegativeSignCheckBox_CheckedChanged(object sender, EventArgs e)
|
||||
{
|
||||
numericalTextBox.Negative = NegativeSignCheckBox.Checked;
|
||||
}
|
||||
private void DotCheckBox_CheckedChanged(object sender, EventArgs e)
|
||||
{
|
||||
numericalTextBox.Dot = DotCheckBox.Checked;
|
||||
}
|
||||
private void ExponentCheckBox_CheckedChanged(object sender, EventArgs e)
|
||||
{
|
||||
numericalTextBox.Exponent = ExponentCheckBox.Checked;
|
||||
}
|
||||
private void MaximumTextBox_TextChanged(object sender, EventArgs e)
|
||||
{
|
||||
numericalTextBox.MaxValue = MaximumTextBox.NumericalText;
|
||||
}
|
||||
private void MinimumTextBox_TextChanged(object sender, EventArgs e)
|
||||
{
|
||||
numericalTextBox.MinValue = MinimumTextBox.NumericalText;
|
||||
}
|
||||
private void MaximumCheckBox_CheckedChanged(object sender, EventArgs e)
|
||||
{
|
||||
numericalTextBox.MaxCheck = MaximumCheckBox.Checked;
|
||||
MaximumTextBox.Enabled = MaximumCheckBox.Checked;
|
||||
}
|
||||
private void MinimumCheckBox_CheckedChanged(object sender, EventArgs e)
|
||||
{
|
||||
numericalTextBox.MinCheck = MinimumCheckBox.Checked;
|
||||
MinimumTextBox.Enabled = MinimumCheckBox.Checked;
|
||||
}
|
||||
private void GroupSeparatorCharacterTextBox_TextChanged(object sender, EventArgs e)
|
||||
{
|
||||
if (GroupSeparatorCharacterTextBox.Text != "" && GroupSeparatorCharacterTextBox.Text.Length == 1)
|
||||
numericalTextBox.Discriminant = System.Convert.ToChar(GroupSeparatorCharacterTextBox.Text);
|
||||
else
|
||||
numericalTextBox.Discriminant = ',';
|
||||
}
|
||||
private void numericalTextBox_TextChanged(object sender, EventArgs e)
|
||||
{
|
||||
NumericalString NS = "Reza";
|
||||
string s = numericalTextBox.NumericalText.ToString();
|
||||
TextTextBox.Text = (string)numericalTextBox.NumericalText + " Reza";
|
||||
DoubleTextBox.Text = (numericalTextBox.NumericalText + 3).ToString();
|
||||
ConditionTextBox.Text = (numericalTextBox.NumericalText < 100) ? (string)numericalTextBox.NumericalText : "Over 100";
|
||||
}
|
||||
}
|
||||
*/
|
||||
@ -0,0 +1,16 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
/// <summary>
|
||||
/// Rx: System.Reactive.Subjects.Subject 에 대한 base interface
|
||||
/// </summary>
|
||||
[ComVisible(false)]
|
||||
public interface IObservableEvent
|
||||
{
|
||||
}
|
||||
|
||||
public interface IObservableUIEvent : IObservableEvent { }
|
||||
|
||||
}
|
||||
@ -0,0 +1,45 @@
|
||||
using System.Globalization;
|
||||
using System.Threading;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
public enum SupportedCultures
|
||||
{
|
||||
English,
|
||||
Korean,
|
||||
}
|
||||
|
||||
public static class CultrureConverter
|
||||
{
|
||||
public static string ConvertToString(this SupportedCultures culture)
|
||||
{
|
||||
switch (culture)
|
||||
{
|
||||
case SupportedCultures.English:
|
||||
return "en-US";
|
||||
case SupportedCultures.Korean:
|
||||
return "ko-KR";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static CultureInfo ConvertToCultureInfo(this SupportedCultures culture)
|
||||
{
|
||||
return new CultureInfo(culture.ConvertToString());
|
||||
}
|
||||
|
||||
public static void Apply(this SupportedCultures culture)
|
||||
{
|
||||
var ci = culture.ConvertToCultureInfo();
|
||||
ci.Apply();
|
||||
}
|
||||
|
||||
public static void Apply(this CultureInfo ci)
|
||||
{
|
||||
Thread.CurrentThread.CurrentCulture = ci;
|
||||
Thread.CurrentThread.CurrentUICulture = ci;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.IO;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
public class CwdChanger : IDisposable
|
||||
{
|
||||
protected string m_strBackupDirectory = null;
|
||||
|
||||
public CwdChanger() : this(null) { }
|
||||
public CwdChanger(string strTargetDirectory/*=null*/)
|
||||
{
|
||||
m_strBackupDirectory = Directory.GetCurrentDirectory();
|
||||
if (!String.IsNullOrEmpty(strTargetDirectory))
|
||||
Directory.SetCurrentDirectory(strTargetDirectory);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Directory.SetCurrentDirectory(m_strBackupDirectory);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,55 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace SystemX.Net.Platform.Common.Util
|
||||
{
|
||||
public static class XMLControl
|
||||
{
|
||||
public static XDocument OpenXMLDocument(string strXmlPath)
|
||||
{
|
||||
XDocument xDoc = XDocument.Load(strXmlPath);
|
||||
|
||||
return xDoc;
|
||||
}
|
||||
|
||||
public static XElement OpenXMLDocument(string strXmlPath, string strRootElemName)
|
||||
{
|
||||
XDocument xDoc = XDocument.Load(strXmlPath);
|
||||
|
||||
var xElement = xDoc.Element(strRootElemName);
|
||||
|
||||
if (xElement == null) return null;
|
||||
|
||||
return xElement;
|
||||
}
|
||||
|
||||
public static XElement OpenXMLElement(XElement xRootElem, string strChildName)
|
||||
{
|
||||
var xElement = xRootElem.Element(strChildName);
|
||||
|
||||
if (xElement == null) return null;
|
||||
|
||||
return xElement;
|
||||
}
|
||||
|
||||
public static void LoadXMLAttributes(object objOwner, Type typAttributes, XElement xelem)
|
||||
{
|
||||
foreach (string strAttrb in Enum.GetNames(typAttributes))
|
||||
{
|
||||
string strData = xelem.Attribute(strAttrb).Value;
|
||||
|
||||
PropertyInfo propInfo = CommonUtil.GetProperty(objOwner, strAttrb);
|
||||
|
||||
if (propInfo.PropertyType == typeof(int))
|
||||
CommonUtil.SetPropertyValue(objOwner, strAttrb, Convert.ToInt32(strData));
|
||||
else if (propInfo.PropertyType == typeof(string))
|
||||
CommonUtil.SetPropertyValue(objOwner, strAttrb, strData);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,173 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{9E024203-A0D4-4A08-8041-9D31248B6F7B}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>SystemX.Net.Platform</RootNamespace>
|
||||
<AssemblyName>SystemX.Net.Platform</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<Deterministic>true</Deterministic>
|
||||
<TargetFrameworkProfile />
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>..\..\Output.SystemX\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>..\..\Output.SystemX\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\x64\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<DebugType>full</DebugType>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<LangVersion>7.3</LangVersion>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
|
||||
<OutputPath>..\..\Output.SystemX\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<LangVersion>7.3</LangVersion>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="log4net">
|
||||
<HintPath>..\..\References\log4net.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="Remotion.Linq, Version=2.1.0.0, Culture=neutral, PublicKeyToken=fee00910d6e5f53b, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Remotion.Linq.2.1.1\lib\net45\Remotion.Linq.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Collections.Immutable, Version=1.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\System.Collections.Immutable.1.3.0\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.ComponentModel.Composition" />
|
||||
<Reference Include="System.ComponentModel.DataAnnotations" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Diagnostics.DiagnosticSource, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\System.Diagnostics.DiagnosticSource.4.3.1\lib\portable-net45+win8+wpa81\System.Diagnostics.DiagnosticSource.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Drawing" />
|
||||
<Reference Include="System.Interactive.Async, Version=3.0.0.0, Culture=neutral, PublicKeyToken=94bc3704cddfc263, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\System.Interactive.Async.3.0.0\lib\net45\System.Interactive.Async.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.IO.Compression" />
|
||||
<Reference Include="System.IO.Compression.FileSystem" />
|
||||
<Reference Include="System.Numerics" />
|
||||
<Reference Include="System.Reactive.Core">
|
||||
<HintPath>..\..\References\System.Reactive.Core.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Reactive.Interfaces">
|
||||
<HintPath>..\..\References\System.Reactive.Interfaces.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Reactive.Linq">
|
||||
<HintPath>..\..\References\System.Reactive.Linq.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.4.3.0\lib\netstandard1.0\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Transactions" />
|
||||
<Reference Include="System.Windows" />
|
||||
<Reference Include="System.Windows.Forms" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Xml" />
|
||||
<Reference Include="WindowsBase" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="SystemX.Common.Protocol\CommonCustomMakeProtocol.cs" />
|
||||
<Compile Include="SystemX.Common.Protocol\LSU Trimming 4th\CustomMakeProtocol_LSU.cs" />
|
||||
<Compile Include="SystemX.Common.Protocol\Smart Inhibitor 1th\CustomMakeProtocol_SIA.cs" />
|
||||
<Compile Include="SystemX.Common\DataTableQuery.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="SystemX.Common.Protocol\AsyncEventProcess.cs" />
|
||||
<Compile Include="SystemX.Common\Archive.cs" />
|
||||
<Compile Include="SystemX.Common\MemoryMappedFileControl.cs" />
|
||||
<Compile Include="SystemX.Common\PacketControl\Common.cs" />
|
||||
<Compile Include="SystemX.Common\Event\EventBase.cs" />
|
||||
<Compile Include="SystemX.Common\Event\FuncEventHandler.cs" />
|
||||
<Compile Include="SystemX.Common\Event\PauseToken.cs" />
|
||||
<Compile Include="SystemX.Common\Extension\EmAsync.cs" />
|
||||
<Compile Include="SystemX.Common\Extension\EmBitmap.cs" />
|
||||
<Compile Include="SystemX.Common\Extension\EmComparable.cs" />
|
||||
<Compile Include="SystemX.Common\Extension\EmControl.cs" />
|
||||
<Compile Include="SystemX.Common\Extension\EmEventHandler.cs" />
|
||||
<Compile Include="SystemX.Common\Extension\EmGeneral.cs" />
|
||||
<Compile Include="SystemX.Common\Extension\EmLinq.cs" />
|
||||
<Compile Include="SystemX.Common\PacketControl\PacketMakeFrom.cs" />
|
||||
<Compile Include="SystemX.Common\PacketControl\PacketMakeTo.cs" />
|
||||
<Compile Include="SystemX.Common\Serialization.cs" />
|
||||
<Compile Include="SystemX.Common\Util\ApplicationIdleTimer.cs" />
|
||||
<Compile Include="SystemX.Common\Util\AppWinControl.cs" />
|
||||
<Compile Include="SystemX.Common\Util\CommonUtil.cs" />
|
||||
<Compile Include="SystemX.Common\Util\CustomExceptions.cs" />
|
||||
<Compile Include="SystemX.Common\Util\FileSystemUtil.cs" />
|
||||
<Compile Include="SystemX.Common\Util\FilterableTextBox.cs">
|
||||
<SubType>Component</SubType>
|
||||
</Compile>
|
||||
<Compile Include="SystemX.Common\Util\GenericEventArgs.cs" />
|
||||
<Compile Include="SystemX.Common\Util\Gzip.cs" />
|
||||
<Compile Include="SystemX.Common\Util\Log4NetWrapper.cs" />
|
||||
<Compile Include="SystemX.Common\Util\LogEntryManager.cs" />
|
||||
<Compile Include="SystemX.Common\Util\LogMessage.cs" />
|
||||
<Compile Include="SystemX.Common\Util\LogProxy.cs" />
|
||||
<Compile Include="SystemX.Common\Util\LogRecord.cs" />
|
||||
<Compile Include="SystemX.Common\Util\NumericTextBox.cs">
|
||||
<SubType>Component</SubType>
|
||||
</Compile>
|
||||
<Compile Include="SystemX.Common\Util\ObservableEvent.cs" />
|
||||
<Compile Include="SystemX.Common\Util\SupportedCultures.cs" />
|
||||
<Compile Include="SystemX.Common\Util\Utilities.cs" />
|
||||
<Compile Include="SystemX.Common\Util\XMLControl.cs" />
|
||||
<Compile Include="SystemX.Net.Comm\AsyncComClientSocket.cs" />
|
||||
<Compile Include="SystemX.Net.Comm\AsyncClientSocket.cs" />
|
||||
<Compile Include="SystemX.Net.Comm\AsyncServerSocket.cs" />
|
||||
<Compile Include="SystemX.Net.Comm\Comm.cs" />
|
||||
<Compile Include="SystemX.Net.Comm\IIS FTP\CommonsFTP.cs" />
|
||||
<Compile Include="SystemX.Net.Comm\IIS FTP\ManagerFTP.cs" />
|
||||
<Compile Include="SystemX.Net.Comm\IIS FTP\CtrlFTP.cs" />
|
||||
<Compile Include="SystemX.Net.DB\ConnInfo.cs" />
|
||||
<Compile Include="SystemX.Net.DB\ConnManager.cs" />
|
||||
<Compile Include="SystemX.Net.DB\DBType\DBTMSSQL - Query.cs" />
|
||||
<Compile Include="SystemX.Net.DB\DBType\DBTMSSQL.cs" />
|
||||
<Compile Include="SystemX.Net.DB\DBType\IDBControl.cs" />
|
||||
<Compile Include="SystemX.Net.DB\DBType\MariaDB.cs" />
|
||||
<Compile Include="SystemX.Net.Schedule\PacketFlowControl.cs" />
|
||||
<Compile Include="SystemX.Net.Schedule\Schedule.cs" />
|
||||
<Compile Include="SystemX.Net\BaseContainer.cs" />
|
||||
<Compile Include="SystemX.Net\Base.cs" />
|
||||
<Compile Include="SystemX.Net\Protocol\BasePacket.cs" />
|
||||
<Compile Include="SystemX.Net\Protocol\BaseProtocol.cs" />
|
||||
<Compile Include="SystemX.Net\Info.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup />
|
||||
<ItemGroup>
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
</Project>
|
||||
@ -0,0 +1,940 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Common;
|
||||
using SystemX.Common.Serialization;
|
||||
using SystemX.Net.Comm;
|
||||
using static SystemX.Net.Platform.Common.Util.LogMessage;
|
||||
|
||||
namespace SystemX.Net.Comm
|
||||
{
|
||||
public class AsyncClientSocket : SystemXSocket, IDisposable
|
||||
{
|
||||
private Socket ClientSock; /* client Socket */
|
||||
private Socket cbClientSock; /* client Async Callback Socket */
|
||||
|
||||
private byte[] recvBuffer;
|
||||
//private String recvText;
|
||||
|
||||
private byte[] recvStoreBuffer;
|
||||
private int iStoreCnt;
|
||||
private int iCheckRetryCnt;
|
||||
|
||||
private const int MAX_CHECK_COUNT = 100; /* 256000 / 4096 <- 65526 / 4096 */
|
||||
private const int USER_MAX_SIZE = 819200; /* 256000 <- 1000000 65536 */
|
||||
private const int MAXSIZE = 8192; /* 8192 <- 4096 */
|
||||
private const int MAX_PACKET_COUNT = 1024;
|
||||
|
||||
private string m_strGetIp;
|
||||
private int m_iGetPort;
|
||||
|
||||
private bool m_bConnected;
|
||||
private string m_strGetText;
|
||||
private bool m_bGetRecv;
|
||||
|
||||
private bool bDisposed;
|
||||
|
||||
private bool bReadySocket;
|
||||
|
||||
public override event SocketCallEvent Comm_Connect_Event;
|
||||
public override event SocketCallEvent Socket_Error_Event;
|
||||
|
||||
public override event SendRecvCallEvent Comm_Send_Event;
|
||||
public override event SendRecvCallEvent Comm_Recv_Event;
|
||||
|
||||
public override event EventHandler<ScheduleEvent> AwaitSendEvent;
|
||||
public override event EventHandler<ScheduleEvent> AwaitRecvEvent;
|
||||
|
||||
private Queue<CPacketDataInfo> QPacketAllData;
|
||||
private Queue<CPacketDataInfo> QPacketRemainData;
|
||||
|
||||
private bool bQueuePacketClearOn;
|
||||
|
||||
public override void SetRefSocketPacketClear()
|
||||
{
|
||||
bQueuePacketClearOn = true;
|
||||
}
|
||||
|
||||
/*
|
||||
private Task taskPacketCaclQueue;
|
||||
private bool m_bThreadPCQBlock;
|
||||
//
|
||||
private CancellationTokenSource CTS;
|
||||
private CancellationToken CT;
|
||||
//
|
||||
private async void WatchPacketCaclQueue()
|
||||
{
|
||||
await Task.Delay(250).ConfigureAwait(false);
|
||||
|
||||
while (!m_bThreadPCQBlock)
|
||||
{
|
||||
try
|
||||
{
|
||||
CT.ThrowIfCancellationRequested();
|
||||
}
|
||||
catch (OperationCanceledException CancelEx)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" Work Canceled. [SystemX.Net.Comm : AsyncClientSocket.WatchPacketCaclQueue]\r\n" + CancelEx.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
|
||||
break;
|
||||
}
|
||||
//
|
||||
try
|
||||
{
|
||||
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General Queue Schedule failed. [SystemX.Net.Comm : AsyncClientSocket.WatchPacketCaclQueue]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
await Task.Delay(1).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
public bool CONNECT
|
||||
{
|
||||
get { return this.m_bConnected; }
|
||||
}
|
||||
|
||||
public string MSG
|
||||
{
|
||||
set { this.m_strGetText = value; }
|
||||
get { return this.m_strGetText; }
|
||||
}
|
||||
|
||||
public bool RECV_STATE
|
||||
{
|
||||
set { this.m_bGetRecv = value; }
|
||||
get { return this.m_bGetRecv; }
|
||||
}
|
||||
|
||||
public bool READY_STATE
|
||||
{
|
||||
set { this.bReadySocket = value; }
|
||||
get { return this.bReadySocket; }
|
||||
}
|
||||
|
||||
public string strGetLocalAddress { set; get; }
|
||||
public string strGetLocalPort { set; get; }
|
||||
|
||||
public AsyncClientSocket(SOCKET_TYPE SOCK_TYPE, IPEndPoint SetRemote) : base(SOCKET_RULE.CLIENT, SOCK_TYPE)
|
||||
{
|
||||
nSocketNumber = 100;
|
||||
|
||||
bDisposed = false;
|
||||
|
||||
QPacketAllData = new Queue<CPacketDataInfo>();
|
||||
QPacketRemainData = new Queue<CPacketDataInfo>();
|
||||
|
||||
bQueuePacketClearOn = false;
|
||||
|
||||
bReadySocket = false;
|
||||
|
||||
m_strGetIp = SetRemote.Address.ToString();
|
||||
m_iGetPort = SetRemote.Port;
|
||||
|
||||
ClientSock = null;
|
||||
cbClientSock = null;
|
||||
|
||||
//recvText = string.Empty;
|
||||
recvStoreBuffer = new byte[USER_MAX_SIZE];
|
||||
iStoreCnt = 0;
|
||||
iCheckRetryCnt = 0;
|
||||
|
||||
recvBuffer = new byte[MAXSIZE];
|
||||
//
|
||||
m_bGetRecv = false;
|
||||
m_bConnected = false;
|
||||
|
||||
AwaitSendEvent += SendCompleteEvent;
|
||||
|
||||
/*
|
||||
taskSendQueue = null;
|
||||
m_bThreadSendBlock = false;
|
||||
|
||||
taskSendQueue = new Task(new Action(WatchSendQueue));
|
||||
taskSendQueue.Start();
|
||||
*/
|
||||
|
||||
bReadySocket = DoReady();
|
||||
/*
|
||||
//
|
||||
CTS = new CancellationTokenSource();
|
||||
CT = CTS.Token;
|
||||
//
|
||||
m_bThreadPCQBlock = false;
|
||||
taskPacketCaclQueue = new Task(new Action(WatchPacketCaclQueue), CT);
|
||||
taskPacketCaclQueue.Start();
|
||||
//
|
||||
*/
|
||||
}
|
||||
|
||||
private async void WatchSendQueue()
|
||||
{
|
||||
/*
|
||||
while (!m_bThreadSendBlock)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(qSendData.Count > 0)
|
||||
{
|
||||
byte[] ucGetData;
|
||||
|
||||
if(qSendData.TryDequeue(out ucGetData))
|
||||
{
|
||||
cbClientSock.BeginSend(ucGetData, 0, ucGetData.Length, SocketFlags.None, new AsyncCallback(SendCallBack), ucGetData);
|
||||
|
||||
stopWaitHandle.WaitOne();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ErrorEventProcess(new CommonSocketException("Send error.[SystemX.Net.Comm : AsyncClientSocket|WatchSendQueue]"));
|
||||
}
|
||||
|
||||
await Task.Delay(1);
|
||||
}
|
||||
*/
|
||||
|
||||
await Task.Delay(1);
|
||||
}
|
||||
|
||||
public void ClearEventConnectCall()
|
||||
{
|
||||
if (Comm_Connect_Event != null)
|
||||
{
|
||||
foreach (Delegate d in Comm_Connect_Event.GetInvocationList())
|
||||
Comm_Connect_Event -= (SocketCallEvent)d;
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearEventErrorCall()
|
||||
{
|
||||
if (Socket_Error_Event != null)
|
||||
{
|
||||
foreach (Delegate d in Socket_Error_Event.GetInvocationList())
|
||||
Socket_Error_Event -= (SocketCallEvent)d;
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearEventSendCall()
|
||||
{
|
||||
if (Comm_Send_Event != null)
|
||||
{
|
||||
foreach (Delegate d in Comm_Send_Event.GetInvocationList())
|
||||
Comm_Send_Event -= (SendRecvCallEvent)d;
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearEventRecvCall()
|
||||
{
|
||||
if (Comm_Recv_Event != null)
|
||||
{
|
||||
foreach (Delegate d in Comm_Recv_Event.GetInvocationList())
|
||||
Comm_Recv_Event -= (SendRecvCallEvent)d;
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearEventAsyncSendCall()
|
||||
{
|
||||
if (AwaitSendEvent != null)
|
||||
{
|
||||
foreach (Delegate d in AwaitSendEvent.GetInvocationList())
|
||||
AwaitSendEvent -= (EventHandler<ScheduleEvent>)d;
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearEventAsyncRecvCall()
|
||||
{
|
||||
if (AwaitRecvEvent != null)
|
||||
{
|
||||
foreach (Delegate d in AwaitRecvEvent.GetInvocationList())
|
||||
AwaitRecvEvent -= (EventHandler<ScheduleEvent>)d;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (!bDisposed)
|
||||
{
|
||||
try
|
||||
{
|
||||
/*
|
||||
if (taskSendQueue != null)
|
||||
{
|
||||
m_bThreadSendBlock = true;
|
||||
|
||||
taskSendQueue.Wait();
|
||||
}
|
||||
*/
|
||||
|
||||
// dispose managed resource (종결자를 가진 객체의 자원 해제)
|
||||
/*
|
||||
if (cbClientSock != null)
|
||||
{
|
||||
if (cbClientSock.Connected)
|
||||
{
|
||||
cbClientSock.Disconnect(false);
|
||||
cbClientSock.Shutdown(SocketShutdown.Both);
|
||||
cbClientSock.Close();
|
||||
cbClientSock = null;
|
||||
}
|
||||
|
||||
cbClientSock = null;
|
||||
}
|
||||
*/
|
||||
|
||||
if (ClientSock != null)
|
||||
{
|
||||
if (ClientSock.Connected)
|
||||
{
|
||||
ClientSock.Disconnect(false);
|
||||
ClientSock.Shutdown(SocketShutdown.Both);
|
||||
}
|
||||
|
||||
ClientSock.Close();
|
||||
ClientSock = null;
|
||||
}
|
||||
|
||||
/*if(cbClientSock != null)
|
||||
cbClientSock.Close();*/
|
||||
|
||||
cbClientSock = null;
|
||||
|
||||
m_bConnected = false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
cbClientSock = null;
|
||||
ClientSock = null;
|
||||
|
||||
m_bConnected = false;
|
||||
|
||||
ErrorEventProcess(new Exception("Dispose failed. [SystemX.Net.Comm : AsyncClientSocket.Dispose]"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
ClearEventAsyncSendCall();
|
||||
ClearEventAsyncRecvCall();
|
||||
|
||||
ClearEventSendCall();
|
||||
ClearEventRecvCall();
|
||||
|
||||
/*
|
||||
ClearEventConnectCall();
|
||||
ClearEventErrorCall();
|
||||
*/
|
||||
}
|
||||
|
||||
if (disposing)
|
||||
{
|
||||
//Manage
|
||||
}
|
||||
|
||||
//Unmanage
|
||||
recvStoreBuffer = null;
|
||||
recvBuffer = null;
|
||||
|
||||
bDisposed = true;
|
||||
}
|
||||
|
||||
//Base Dispose
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private void ErrorEventProcess(Exception e, bool ConnectStateOff = false)
|
||||
{
|
||||
//if (e.SocketErrorCode == SocketError.NotConnected)
|
||||
|
||||
m_bConnected = ConnectStateOff;
|
||||
|
||||
Socket_Error_Event?.Invoke(e, new ScheduleEvent(nSocketNumber, false, "Error", 0));
|
||||
}
|
||||
|
||||
private bool DoReady()
|
||||
{
|
||||
bool bDoState = true;
|
||||
|
||||
try
|
||||
{
|
||||
if (base.SOCK_TYPE == SOCKET_TYPE.TCP)
|
||||
ClientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
else if (base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
ClientSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
|
||||
|
||||
if (base.SOCK_TYPE == SOCKET_TYPE.TCP)
|
||||
{
|
||||
LingerOption SetLinger = new LingerOption(true, 1);
|
||||
ClientSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, SetLinger);
|
||||
//ClientSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
|
||||
|
||||
var option = new TcpKeepAlive
|
||||
{
|
||||
OnOff = 1,
|
||||
KeepAliveTime = 90000,
|
||||
KeepAliveInterval = 3000
|
||||
};
|
||||
|
||||
int iState = ClientSock.IOControl(IOControlCode.KeepAliveValues, option.GetBytes(), null);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bDoState = false;
|
||||
|
||||
/* 접속 실패 */
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
;//
|
||||
}
|
||||
|
||||
return bDoState;
|
||||
}
|
||||
|
||||
public void Connect()
|
||||
{
|
||||
if (bReadySocket)
|
||||
BeginConnect();
|
||||
}
|
||||
|
||||
private void BeginConnect()
|
||||
{
|
||||
try
|
||||
{
|
||||
/* 접속 대기중 */
|
||||
ClientSock.BeginConnect(m_strGetIp, m_iGetPort, new AsyncCallback(ConnectCallBack), ClientSock);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
/* 접속 실패 */
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
}
|
||||
private void ConnectCallBack(IAsyncResult IAR)
|
||||
{
|
||||
try
|
||||
{
|
||||
//보류중인 연결을 완성
|
||||
Socket tempSock = (Socket)IAR.AsyncState;
|
||||
|
||||
IPEndPoint svrEP = (IPEndPoint)tempSock.RemoteEndPoint;
|
||||
IPEndPoint connEP = (IPEndPoint)tempSock.LocalEndPoint;
|
||||
|
||||
string strLocalAddress = connEP.Address.ToString();
|
||||
string strLocalPort = connEP.Port.ToString();
|
||||
|
||||
strGetLocalAddress = strLocalAddress;
|
||||
strGetLocalPort = strLocalPort;
|
||||
|
||||
tempSock.EndConnect(IAR);
|
||||
|
||||
//AsyncSocketObject objScoket = new AsyncSocketObject(MAXSIZE);
|
||||
//objScoket.WorkSocket = tempSock;
|
||||
cbClientSock = tempSock;// objScoket.WorkSocket;
|
||||
|
||||
/*
|
||||
LingerOption SetLinger = new LingerOption(true, 1);
|
||||
cbClientSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, SetLinger);
|
||||
cbClientSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
|
||||
|
||||
var option = new TcpKeepAlive
|
||||
{
|
||||
OnOff = 1,
|
||||
KeepAliveTime = 53000,
|
||||
KeepAliveInterval = 2000
|
||||
};
|
||||
int iState = cbClientSock.IOControl(IOControlCode.KeepAliveValues, option.GetBytes(), null);
|
||||
*/
|
||||
|
||||
//데이터 받을 이벤트 함수 등록
|
||||
cbClientSock.BeginReceive(recvBuffer, 0, MAXSIZE, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), ClientSock);
|
||||
|
||||
m_bConnected = true;
|
||||
|
||||
Comm_Connect_Event?.BeginInvoke(ClientSock, new ScheduleEvent(nSocketNumber, true, "Connect", 0), InvokeCallback, null);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
/* 접속 실패 */
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void InvokeCallback(object obj)
|
||||
{
|
||||
}
|
||||
|
||||
public override bool BeginSend(byte[] ucDatas)
|
||||
{
|
||||
bool bState = true;
|
||||
|
||||
if (cbClientSock == null)
|
||||
return false;
|
||||
|
||||
//qSendData.Enqueue(ucDatas);
|
||||
|
||||
try
|
||||
{
|
||||
//연결 성공시
|
||||
if (cbClientSock.Connected || base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
{
|
||||
cbClientSock.BeginSend(ucDatas, 0, ucDatas.Length, SocketFlags.None, new AsyncCallback(SendCallBack), ucDatas);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bState = false;
|
||||
|
||||
//전송 에러
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
|
||||
return bState;
|
||||
}
|
||||
|
||||
|
||||
public override bool BeginSend(Socket SetSock, byte[] ucDatas)
|
||||
{
|
||||
bool bState = true;
|
||||
|
||||
if (cbClientSock == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
//연결 성공시
|
||||
if (SetSock.Connected || base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
{
|
||||
SetSock.BeginSend(ucDatas, 0, ucDatas.Length, SocketFlags.None, new AsyncCallback(SendCallBack), ucDatas);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bState = false;
|
||||
|
||||
//전송 에러
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
|
||||
return bState;
|
||||
}
|
||||
|
||||
|
||||
public override bool BeginSend(string strMessage)
|
||||
{
|
||||
bool bState = true;
|
||||
|
||||
if (cbClientSock == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
//연결 성공시
|
||||
if (cbClientSock.Connected || base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
{
|
||||
byte[] buffer = new UnicodeEncoding().GetBytes(strMessage);
|
||||
|
||||
cbClientSock.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), strMessage);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bState = false;
|
||||
|
||||
//전송 에러
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
|
||||
return bState;
|
||||
}
|
||||
|
||||
|
||||
private void SendCallBack(IAsyncResult IAR)
|
||||
{
|
||||
//전송 완료
|
||||
byte[] getData = null;
|
||||
ScheduleEvent se = new ScheduleEvent(nSocketNumber, false, "Send Fail", 0);
|
||||
|
||||
if (cbClientSock == null)
|
||||
return;
|
||||
|
||||
bool bResult = true;
|
||||
try
|
||||
{
|
||||
getData = (byte[])IAR.AsyncState;
|
||||
|
||||
if (getData != null)
|
||||
se = new ScheduleEvent(nSocketNumber, true, "Send Success", 0);
|
||||
else
|
||||
se = new ScheduleEvent(nSocketNumber, false, "Send Fail", 0);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bResult = false;
|
||||
|
||||
//Callback Error
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (bResult)
|
||||
{
|
||||
Comm_Send_Event?.BeginInvoke(getData, se, null, null);
|
||||
AwaitSendEvent?.BeginInvoke(getData, se, null, null);
|
||||
|
||||
//Comm_Send_Event?.Invoke(getData, se);
|
||||
//AwaitSendEvent?.Invoke(getData, se);
|
||||
}
|
||||
}
|
||||
//
|
||||
try
|
||||
{
|
||||
int iSendCnt = cbClientSock.EndSend(IAR);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bResult = false;
|
||||
|
||||
//Callback Error
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void SendCompleteEvent(object senderData, ScheduleEvent e)
|
||||
{
|
||||
}
|
||||
|
||||
private void Receive()
|
||||
{
|
||||
if (cbClientSock == null)
|
||||
return;
|
||||
|
||||
//받기
|
||||
try
|
||||
{
|
||||
if (cbClientSock.Connected || base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
cbClientSock.BeginReceive(recvBuffer, 0, MAXSIZE, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), cbClientSock);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnReceiveCallBack(IAsyncResult IAR)
|
||||
{
|
||||
bool bReceiveState = true;
|
||||
int nReadSize = 0;
|
||||
|
||||
Socket ClientSideSock = null;
|
||||
//AsyncSocketObject objScoket = null;
|
||||
|
||||
try
|
||||
{
|
||||
//수신
|
||||
ClientSideSock = (Socket)IAR.AsyncState;
|
||||
//objScoket = (AsyncSocketObject)IAR.AsyncState;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.Dispose(true);
|
||||
|
||||
//수신 실패
|
||||
ErrorEventProcess(new CommonSocketException("Middleware server side connection lost.[SystemX.Net.Comm : AsyncClientSocket|OnReceiveCallBack]"));
|
||||
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (ClientSideSock.Connected)
|
||||
nReadSize = ClientSideSock.EndReceive(IAR);
|
||||
else
|
||||
{
|
||||
if (base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
nReadSize = ClientSideSock.EndReceive(IAR);
|
||||
else
|
||||
bReceiveState = false;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bReceiveState = false;
|
||||
}
|
||||
//
|
||||
if (bReceiveState)
|
||||
{
|
||||
if (nReadSize != 0)
|
||||
{
|
||||
byte[] ucFindData = new byte[1];
|
||||
//byte[] ucSetClearArray;
|
||||
|
||||
int iFindDataCnt = 0;
|
||||
|
||||
//bool bSegmentFind = false;
|
||||
bool bDataFind = false;
|
||||
|
||||
byte ucGetLabel = 0;
|
||||
|
||||
try
|
||||
{
|
||||
/*
|
||||
Array.Copy(recvBuffer, 0, recvStoreBuffer, iStoreCnt, nReadSize);
|
||||
|
||||
iStoreCnt += nReadSize;
|
||||
*/
|
||||
|
||||
if (bQueuePacketClearOn)
|
||||
{
|
||||
bQueuePacketClearOn = false;
|
||||
|
||||
QPacketAllData.Clear();
|
||||
}
|
||||
//
|
||||
QPacketAllData.Enqueue(new CPacketDataInfo(DateTime.Now, recvBuffer, nReadSize));
|
||||
|
||||
foreach (var n in QPacketAllData.ToList())
|
||||
{
|
||||
TimeSpan dsInterval = DateTime.Now - n.dtPacket;
|
||||
|
||||
//오랜된 패킷 소거
|
||||
if (dsInterval.TotalSeconds >= 20.0)
|
||||
QPacketAllData.Dequeue();
|
||||
else
|
||||
QPacketRemainData.Enqueue(new CPacketDataInfo(n.ID, n.dtPacket, n.ucData, n.nDataSize));
|
||||
}
|
||||
//
|
||||
iStoreCnt = 0;
|
||||
Array.Clear(recvStoreBuffer, 0, USER_MAX_SIZE);
|
||||
|
||||
Guid[] guidUsePacketID = new Guid[QPacketRemainData.Count];
|
||||
int nPacketPos = 0;
|
||||
|
||||
//남은 패킷중 연산 시도
|
||||
foreach (var n in QPacketRemainData.ToList())
|
||||
{
|
||||
Array.Copy(n.ucData, 0, recvStoreBuffer, iStoreCnt, n.nDataSize);
|
||||
|
||||
iStoreCnt += n.nDataSize;
|
||||
|
||||
guidUsePacketID[nPacketPos++] = n.ID;
|
||||
|
||||
for (int j = 0; j < iStoreCnt; j++)
|
||||
{
|
||||
if (recvStoreBuffer[j] == 0x0D &&
|
||||
recvStoreBuffer[j + 1] == 0x02 &&
|
||||
recvStoreBuffer[j + 6] == 0x08 &&
|
||||
recvStoreBuffer[j + 7] == 0x0A)
|
||||
{
|
||||
ucGetLabel = recvStoreBuffer[j - 1];
|
||||
|
||||
uint uiGetPacketSize = 0x0;
|
||||
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[j + 2] << 24);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[j + 3] << 16);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[j + 4] << 8);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[j + 5] << 0);
|
||||
|
||||
int iGetSize = (int)uiGetPacketSize;
|
||||
|
||||
iGetSize += XCommons.PAD_SIZE;
|
||||
|
||||
if (recvStoreBuffer[j + iGetSize - 4] == 0x0D &&
|
||||
recvStoreBuffer[j + iGetSize - 3] == 0x02 &&
|
||||
recvStoreBuffer[j + iGetSize - 2] == 0x08 &&
|
||||
recvStoreBuffer[j + iGetSize - 1] == 0x0A)
|
||||
{
|
||||
iFindDataCnt = iGetSize;
|
||||
|
||||
ucFindData = new byte[iFindDataCnt];
|
||||
Array.Copy(recvStoreBuffer, j, ucFindData, 0, iFindDataCnt);
|
||||
|
||||
bDataFind = true;
|
||||
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
bDataFind = false;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
//
|
||||
if(bDataFind)
|
||||
{
|
||||
//성공한 패킷이 있을경우 해당 패킷 제거
|
||||
foreach (var m in QPacketAllData.ToList())
|
||||
{
|
||||
for (int i = 0; i < guidUsePacketID.Count(); i++)
|
||||
{
|
||||
if (m.ID == guidUsePacketID[i])
|
||||
{
|
||||
QPacketAllData.Dequeue();
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
QPacketRemainData.Clear();
|
||||
|
||||
//recvText += Encoding.Unicode.GetString(recvBuffer, 0, nReadSize);
|
||||
|
||||
/*
|
||||
for (int i = 0; i < iStoreCnt; i++)
|
||||
{
|
||||
if (recvStoreBuffer[i] == 0x0D &&
|
||||
recvStoreBuffer[i + 1] == 0x02 &&
|
||||
recvStoreBuffer[i + 6] == 0x08 &&
|
||||
recvStoreBuffer[i + 7] == 0x0A)
|
||||
{
|
||||
ucGetLabel = recvStoreBuffer[i - 1];
|
||||
|
||||
uint uiGetPacketSize = 0x0;
|
||||
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[i + 2] << 24);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[i + 3] << 16);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[i + 4] << 8);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[i + 5] << 0);
|
||||
|
||||
int iGetSize = (int)uiGetPacketSize;
|
||||
|
||||
iGetSize += XCommons.PAD_SIZE;
|
||||
|
||||
if (recvStoreBuffer[i + iGetSize - 4] == 0x0D &&
|
||||
recvStoreBuffer[i + iGetSize - 3] == 0x02 &&
|
||||
recvStoreBuffer[i + iGetSize - 2] == 0x08 &&
|
||||
recvStoreBuffer[i + iGetSize - 1] == 0x0A)
|
||||
{
|
||||
iFindDataCnt = iGetSize;
|
||||
|
||||
bSegmentFind = true;
|
||||
}
|
||||
if (bSegmentFind)
|
||||
{
|
||||
iCheckRetryCnt = 0;
|
||||
|
||||
ucFindData = new byte[iFindDataCnt];
|
||||
ucSetClearArray = new byte[(iFindDataCnt + 1)];
|
||||
|
||||
Array.Clear(ucSetClearArray, 0, (iFindDataCnt + 1));
|
||||
Array.Copy(recvStoreBuffer, i, ucFindData, 0, iFindDataCnt);
|
||||
|
||||
iStoreCnt -= (iFindDataCnt + 1);
|
||||
|
||||
Buffer.BlockCopy(ucSetClearArray, 0, recvStoreBuffer, 0, (iFindDataCnt + 1));
|
||||
Buffer.BlockCopy(recvStoreBuffer, iStoreCnt, recvStoreBuffer, 0, USER_MAX_SIZE - iStoreCnt);
|
||||
|
||||
bDataFind = true;
|
||||
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
iCheckRetryCnt++;
|
||||
|
||||
if (iCheckRetryCnt > MAX_CHECK_COUNT)
|
||||
{
|
||||
iCheckRetryCnt = 0;
|
||||
|
||||
ucSetClearArray = new byte[iFindDataCnt];
|
||||
Array.Clear(ucSetClearArray, 0, iFindDataCnt);
|
||||
|
||||
iStoreCnt -= iFindDataCnt;
|
||||
|
||||
Buffer.BlockCopy(ucSetClearArray, 0, recvStoreBuffer, 0, iFindDataCnt);
|
||||
Buffer.BlockCopy(recvStoreBuffer, iStoreCnt, recvStoreBuffer, 0, USER_MAX_SIZE - iStoreCnt);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bDataFind = false;
|
||||
|
||||
/*
|
||||
iStoreCnt = 0;
|
||||
|
||||
if(recvStoreBuffer != null) Array.Clear(recvStoreBuffer, 0, recvStoreBuffer.Count());
|
||||
*/
|
||||
}
|
||||
|
||||
if (bDataFind)
|
||||
{
|
||||
bool bDataControl = true;
|
||||
byte[] ucGetInfp = null;
|
||||
|
||||
try
|
||||
{
|
||||
ucGetInfp = new byte[iFindDataCnt];
|
||||
|
||||
Array.Copy(ucFindData, ucGetInfp, iFindDataCnt);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bDataControl = false;
|
||||
}
|
||||
|
||||
ScheduleEvent se = null;
|
||||
|
||||
m_bGetRecv = true;
|
||||
|
||||
//recvText = string.Empty;
|
||||
|
||||
if (bDataControl)
|
||||
{
|
||||
se = new ScheduleEvent(nSocketNumber, true, "Recv Success", ucGetLabel);
|
||||
}
|
||||
else
|
||||
{
|
||||
se = new ScheduleEvent(nSocketNumber, false, "Recv Fail", ucGetLabel);
|
||||
}
|
||||
|
||||
Comm_Recv_Event?.BeginInvoke(ucGetInfp, se, null, null);
|
||||
AwaitRecvEvent?.BeginInvoke(ucGetInfp, se, null, null);
|
||||
|
||||
//Comm_Recv_Event?.Invoke(ucGetInfp, se);
|
||||
//AwaitRecvEvent?.Invoke(ucGetInfp, se);
|
||||
}
|
||||
|
||||
this.Receive();
|
||||
//objScoket.WorkSocket.BeginReceive(objScoket.recvBuffer, 0, MAXSIZE, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), objScoket);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Dispose(true);
|
||||
|
||||
ErrorEventProcess(new CommonSocketException("Middleware server side connection lost.[SystemX.Net.Comm : AsyncClientSocket|OnReceiveCallBack]"));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Dispose(true);
|
||||
|
||||
ErrorEventProcess(new CommonSocketException("Middleware server side connection lost.[SystemX.Net.Comm : AsyncClientSocket|OnReceiveCallBack]"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,871 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Common;
|
||||
using SystemX.Common.Serialization;
|
||||
using SystemX.Net.Comm;
|
||||
|
||||
namespace SystemX.Net.Comm
|
||||
{
|
||||
public class AsyncComClientSocket : SystemXSocket, IDisposable
|
||||
{
|
||||
private Socket ClientSock; /* client Socket */
|
||||
private Socket cbClientSock; /* client Async Callback Socket */
|
||||
|
||||
private byte[] recvBuffer;
|
||||
//private String recvText;
|
||||
|
||||
private byte[] recvStoreBuffer;
|
||||
private int iStoreCnt;
|
||||
private int iCheckRetryCnt;
|
||||
|
||||
private const int MAX_CHECK_COUNT = 100; /* 256000 / 4096 <- 65526 / 4096 */
|
||||
private const int USER_MAX_SIZE = 819200; /* 256000 <- 1000000 65536 */
|
||||
private const int MAXSIZE = 8192; /* 8192 <- 4096 */
|
||||
|
||||
private string m_strGetIp;
|
||||
private int m_iGetPort;
|
||||
|
||||
private bool m_bConnected;
|
||||
private string m_strGetText;
|
||||
private bool m_bGetRecv;
|
||||
|
||||
private bool bDisposed;
|
||||
|
||||
public override event SocketCallEvent Comm_Connect_Event;
|
||||
public override event SocketCallEvent Socket_Error_Event;
|
||||
|
||||
public override event SendRecvCallEvent Comm_Send_Event;
|
||||
public override event SendRecvCallEvent Comm_Recv_Event;
|
||||
|
||||
public override event EventHandler<ScheduleEvent> AwaitSendEvent;
|
||||
public override event EventHandler<ScheduleEvent> AwaitRecvEvent;
|
||||
|
||||
private Queue<CPacketDataInfo> QPacketAllData;
|
||||
private Queue<CPacketDataInfo> QPacketRemainData;
|
||||
|
||||
private bool bQueuePacketClearOn;
|
||||
|
||||
public override void SetRefSocketPacketClear()
|
||||
{
|
||||
bQueuePacketClearOn = true;
|
||||
}
|
||||
|
||||
/*
|
||||
private Task taskSendQueue;
|
||||
private bool m_bThreadSendBlock;
|
||||
private ConcurrentQueue<byte[]> qSendData = new ConcurrentQueue<byte[]>();
|
||||
|
||||
AutoResetEvent stopWaitHandle = new AutoResetEvent(false);
|
||||
*/
|
||||
|
||||
public bool CONNECT
|
||||
{
|
||||
get { return this.m_bConnected; }
|
||||
}
|
||||
public string MSG
|
||||
{
|
||||
set { this.m_strGetText = value; }
|
||||
get { return this.m_strGetText; }
|
||||
}
|
||||
public bool RECV_STATE
|
||||
{
|
||||
set { this.m_bGetRecv = value; }
|
||||
get { return this.m_bGetRecv; }
|
||||
}
|
||||
|
||||
public string strGetLocalAddress { set; get; }
|
||||
public string strGetLocalPort { set; get; }
|
||||
|
||||
public AsyncComClientSocket(SOCKET_TYPE SOCK_TYPE, IPEndPoint SetRemote) : base(SOCKET_RULE.CLIENT, SOCK_TYPE)
|
||||
{
|
||||
nSocketNumber = 100;
|
||||
|
||||
bDisposed = false;
|
||||
|
||||
QPacketAllData = new Queue<CPacketDataInfo>();
|
||||
QPacketRemainData = new Queue<CPacketDataInfo>();
|
||||
|
||||
bQueuePacketClearOn = false;
|
||||
|
||||
m_strGetIp = SetRemote.Address.ToString();
|
||||
m_iGetPort = SetRemote.Port;
|
||||
|
||||
ClientSock = null;
|
||||
cbClientSock = null;
|
||||
|
||||
//recvText = string.Empty;
|
||||
recvStoreBuffer = new byte[USER_MAX_SIZE];
|
||||
iStoreCnt = 0;
|
||||
iCheckRetryCnt = 0;
|
||||
|
||||
recvBuffer = new byte[MAXSIZE];
|
||||
//
|
||||
m_bGetRecv = false;
|
||||
m_bConnected = false;
|
||||
|
||||
AwaitSendEvent += SendCompleteEvent;
|
||||
|
||||
/*
|
||||
taskSendQueue = null;
|
||||
m_bThreadSendBlock = false;
|
||||
|
||||
taskSendQueue = new Task(new Action(WatchSendQueue));
|
||||
taskSendQueue.Start();
|
||||
*/
|
||||
|
||||
this.DoInit();
|
||||
}
|
||||
|
||||
private async void WatchSendQueue()
|
||||
{
|
||||
/*
|
||||
while (!m_bThreadSendBlock)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(qSendData.Count > 0)
|
||||
{
|
||||
byte[] ucGetData;
|
||||
|
||||
if(qSendData.TryDequeue(out ucGetData))
|
||||
{
|
||||
cbClientSock.BeginSend(ucGetData, 0, ucGetData.Length, SocketFlags.None, new AsyncCallback(SendCallBack), ucGetData);
|
||||
|
||||
stopWaitHandle.WaitOne();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ErrorEventProcess(new CommonSocketException("Send error.[SystemX.Net.Comm : AsyncClientSocket|WatchSendQueue]"));
|
||||
}
|
||||
|
||||
await Task.Delay(1);
|
||||
}
|
||||
*/
|
||||
|
||||
await Task.Delay(1);
|
||||
}
|
||||
|
||||
|
||||
public void ClearEventConnectCall()
|
||||
{
|
||||
if (Comm_Connect_Event != null)
|
||||
{
|
||||
foreach (Delegate d in Comm_Connect_Event.GetInvocationList())
|
||||
Comm_Connect_Event -= (SocketCallEvent)d;
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearEventErrorCall()
|
||||
{
|
||||
if (Socket_Error_Event != null)
|
||||
{
|
||||
foreach (Delegate d in Socket_Error_Event.GetInvocationList())
|
||||
Socket_Error_Event -= (SocketCallEvent)d;
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearEventSendCall()
|
||||
{
|
||||
if (Comm_Send_Event != null)
|
||||
{
|
||||
foreach (Delegate d in Comm_Send_Event.GetInvocationList())
|
||||
Comm_Send_Event -= (SendRecvCallEvent)d;
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearEventRecvCall()
|
||||
{
|
||||
if (Comm_Recv_Event != null)
|
||||
{
|
||||
foreach (Delegate d in Comm_Recv_Event.GetInvocationList())
|
||||
Comm_Recv_Event -= (SendRecvCallEvent)d;
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearEventAsyncSendCall()
|
||||
{
|
||||
if (AwaitSendEvent != null)
|
||||
{
|
||||
foreach (Delegate d in AwaitSendEvent.GetInvocationList())
|
||||
AwaitSendEvent -= (EventHandler<ScheduleEvent>)d;
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearEventAsyncRecvCall()
|
||||
{
|
||||
if (AwaitRecvEvent != null)
|
||||
{
|
||||
foreach (Delegate d in AwaitRecvEvent.GetInvocationList())
|
||||
AwaitRecvEvent -= (EventHandler<ScheduleEvent>)d;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (!bDisposed)
|
||||
{
|
||||
AwaitSendEvent -= SendCompleteEvent;
|
||||
|
||||
try
|
||||
{
|
||||
/*
|
||||
if (taskSendQueue != null)
|
||||
{
|
||||
m_bThreadSendBlock = true;
|
||||
|
||||
taskSendQueue.Wait();
|
||||
}
|
||||
*/
|
||||
|
||||
// dispose managed resource (종결자를 가진 객체의 자원 해제)
|
||||
/*
|
||||
if (cbClientSock != null)
|
||||
{
|
||||
if (cbClientSock.Connected)
|
||||
{
|
||||
cbClientSock.Disconnect(false);
|
||||
cbClientSock.Shutdown(SocketShutdown.Both);
|
||||
cbClientSock.Close();
|
||||
cbClientSock = null;
|
||||
}
|
||||
|
||||
cbClientSock = null;
|
||||
}
|
||||
*/
|
||||
|
||||
if (ClientSock != null)
|
||||
{
|
||||
if (ClientSock.Connected)
|
||||
{
|
||||
ClientSock.Disconnect(false);
|
||||
ClientSock.Shutdown(SocketShutdown.Both);
|
||||
ClientSock.Close();
|
||||
ClientSock = null;
|
||||
}
|
||||
|
||||
ClientSock = null;
|
||||
}
|
||||
|
||||
/*if(cbClientSock != null)
|
||||
cbClientSock.Close();*/
|
||||
|
||||
cbClientSock = null;
|
||||
|
||||
m_bConnected = false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
cbClientSock = null;
|
||||
ClientSock = null;
|
||||
|
||||
m_bConnected = false;
|
||||
|
||||
ErrorEventProcess(new Exception("Dispose failed. [SystemX.Net.Comm : AsyncComClientSocket.Dispose]"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
ClearEventAsyncSendCall();
|
||||
ClearEventAsyncRecvCall();
|
||||
|
||||
ClearEventSendCall();
|
||||
ClearEventRecvCall();
|
||||
|
||||
/*
|
||||
ClearEventConnectCall();
|
||||
ClearEventErrorCall();
|
||||
*/
|
||||
}
|
||||
|
||||
if (disposing)
|
||||
{
|
||||
//Manage
|
||||
}
|
||||
|
||||
//Unmanage
|
||||
recvStoreBuffer = null;
|
||||
recvBuffer = null;
|
||||
|
||||
bDisposed = true;
|
||||
}
|
||||
|
||||
//Base Dispose
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private void ErrorEventProcess(Exception e, bool ConnectStateOff = false)
|
||||
{
|
||||
//if (e.SocketErrorCode == SocketError.NotConnected)
|
||||
|
||||
m_bConnected = ConnectStateOff;
|
||||
|
||||
Socket_Error_Event?.Invoke(e, new ScheduleEvent(nSocketNumber, false, "Error", 0));
|
||||
}
|
||||
|
||||
private void DoInit()
|
||||
{
|
||||
bool bDoState = true;
|
||||
|
||||
try
|
||||
{
|
||||
if (base.SOCK_TYPE == SOCKET_TYPE.TCP)
|
||||
ClientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
else if (base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
ClientSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
|
||||
|
||||
if (base.SOCK_TYPE == SOCKET_TYPE.TCP)
|
||||
{
|
||||
LingerOption SetLinger = new LingerOption(true, 1);
|
||||
ClientSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, SetLinger);
|
||||
//ClientSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
|
||||
|
||||
var option = new TcpKeepAlive
|
||||
{
|
||||
OnOff = 1,
|
||||
KeepAliveTime = 90000,
|
||||
KeepAliveInterval = 3000
|
||||
};
|
||||
|
||||
int iState = ClientSock.IOControl(IOControlCode.KeepAliveValues, option.GetBytes(), null);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bDoState = false;
|
||||
|
||||
/* 접속 실패 */
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (bDoState)
|
||||
this.BeginConnect();
|
||||
}
|
||||
}
|
||||
private void BeginConnect()
|
||||
{
|
||||
try
|
||||
{
|
||||
/* 접속 대기중 */
|
||||
ClientSock.BeginConnect(m_strGetIp, m_iGetPort, new AsyncCallback(ConnectCallBack), ClientSock);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
/* 접속 실패 */
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
}
|
||||
private void ConnectCallBack(IAsyncResult IAR)
|
||||
{
|
||||
try
|
||||
{
|
||||
//보류중인 연결을 완성
|
||||
Socket tempSock = (Socket)IAR.AsyncState;
|
||||
|
||||
IPEndPoint svrEP = (IPEndPoint)tempSock.RemoteEndPoint;
|
||||
IPEndPoint connEP = (IPEndPoint)tempSock.LocalEndPoint;
|
||||
|
||||
string strLocalAddress = connEP.Address.ToString();
|
||||
string strLocalPort = connEP.Port.ToString();
|
||||
|
||||
strGetLocalAddress = strLocalAddress;
|
||||
strGetLocalPort = strLocalPort;
|
||||
|
||||
tempSock.EndConnect(IAR);
|
||||
|
||||
//AsyncSocketObject objScoket = new AsyncSocketObject(MAXSIZE);
|
||||
//objScoket.WorkSocket = tempSock;
|
||||
cbClientSock = tempSock;
|
||||
|
||||
/*
|
||||
LingerOption SetLinger = new LingerOption(true, 1);
|
||||
cbClientSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, SetLinger);
|
||||
cbClientSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
|
||||
|
||||
var option = new TcpKeepAlive
|
||||
{
|
||||
OnOff = 1,
|
||||
KeepAliveTime = 53000,
|
||||
KeepAliveInterval = 2000
|
||||
};
|
||||
int iState = cbClientSock.IOControl(IOControlCode.KeepAliveValues, option.GetBytes(), null);
|
||||
*/
|
||||
|
||||
//데이터 받을 이벤트 함수 등록
|
||||
cbClientSock.BeginReceive(recvBuffer, 0, MAXSIZE, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), ClientSock);
|
||||
|
||||
m_bConnected = true;
|
||||
|
||||
Comm_Connect_Event?.BeginInvoke(ClientSock, new ScheduleEvent(nSocketNumber, true, "Connect", 0), InvokeCallback, null);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
/* 접속 실패 */
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
}
|
||||
private void InvokeCallback(object obj)
|
||||
{
|
||||
}
|
||||
public override bool BeginSend(byte[] ucDatas)
|
||||
{
|
||||
bool bState = true;
|
||||
|
||||
if (cbClientSock == null)
|
||||
return false;
|
||||
|
||||
//qSendData.Enqueue(ucDatas);
|
||||
|
||||
try
|
||||
{
|
||||
//연결 성공시
|
||||
if (cbClientSock.Connected || base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
{
|
||||
cbClientSock.BeginSend(ucDatas, 0, ucDatas.Length, SocketFlags.None, new AsyncCallback(SendCallBack), ucDatas);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bState = false;
|
||||
|
||||
//전송 에러
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
|
||||
return bState;
|
||||
}
|
||||
public override bool BeginSend(Socket SetSock, byte[] ucDatas)
|
||||
{
|
||||
bool bState = true;
|
||||
|
||||
if (cbClientSock == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
//연결 성공시
|
||||
if (SetSock.Connected || base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
{
|
||||
SetSock.BeginSend(ucDatas, 0, ucDatas.Length, SocketFlags.None, new AsyncCallback(SendCallBack), ucDatas);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bState = false;
|
||||
|
||||
//전송 에러
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
|
||||
return bState;
|
||||
}
|
||||
public override bool BeginSend(string strMessage)
|
||||
{
|
||||
bool bState = true;
|
||||
|
||||
if (cbClientSock == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
//연결 성공시
|
||||
if (cbClientSock.Connected || base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
{
|
||||
byte[] buffer = new UnicodeEncoding().GetBytes(strMessage);
|
||||
|
||||
cbClientSock.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), strMessage);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bState = false;
|
||||
|
||||
//전송 에러
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
|
||||
return bState;
|
||||
}
|
||||
private void SendCallBack(IAsyncResult IAR)
|
||||
{
|
||||
//전송 완료
|
||||
byte[] getData = null;
|
||||
ScheduleEvent se = new ScheduleEvent(nSocketNumber, false, "Send Fail", 0);
|
||||
|
||||
if (cbClientSock == null)
|
||||
return;
|
||||
|
||||
bool bResult = true;
|
||||
try
|
||||
{
|
||||
getData = (byte[])IAR.AsyncState;
|
||||
|
||||
if (getData != null)
|
||||
se = new ScheduleEvent(nSocketNumber, true, "Send Success", 0);
|
||||
else
|
||||
se = new ScheduleEvent(nSocketNumber, false, "Send Fail", 0);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bResult = false;
|
||||
|
||||
//Callback Error
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (bResult)
|
||||
{
|
||||
Comm_Send_Event?.BeginInvoke(getData, se, null, null);
|
||||
AwaitSendEvent?.BeginInvoke(getData, se, null, null);
|
||||
|
||||
//Comm_Send_Event?.Invoke(getData, se);
|
||||
//AwaitSendEvent?.Invoke(getData, se);
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
int iSendCnt = cbClientSock.EndSend(IAR);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bResult = false;
|
||||
|
||||
//Callback Error
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
}
|
||||
private void SendCompleteEvent(object senderData, ScheduleEvent e)
|
||||
{
|
||||
}
|
||||
private void Receive()
|
||||
{
|
||||
if (cbClientSock == null)
|
||||
return;
|
||||
|
||||
//받기
|
||||
try
|
||||
{
|
||||
if (cbClientSock.Connected || base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
cbClientSock.BeginReceive(recvBuffer, 0, MAXSIZE, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), ClientSock);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
}
|
||||
private void OnReceiveCallBack(IAsyncResult IAR)
|
||||
{
|
||||
bool bReceiveState = true;
|
||||
int nReadSize = 0;
|
||||
|
||||
Socket ClientSideSock = null;
|
||||
//AsyncSocketObject objScoket = null;
|
||||
|
||||
try
|
||||
{
|
||||
//수신
|
||||
ClientSideSock = (Socket)IAR.AsyncState;
|
||||
//objScoket = (AsyncSocketObject)IAR.AsyncState;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.Dispose(true);
|
||||
|
||||
//수신 실패
|
||||
ErrorEventProcess(new CommonSocketException("Middleware server side connection lost.[SystemX.Net.Comm : AsyncClientSocket|OnReceiveCallBack]"));
|
||||
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (ClientSideSock.Connected)
|
||||
nReadSize = ClientSideSock.EndReceive(IAR);
|
||||
else
|
||||
{
|
||||
if (base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
nReadSize = ClientSideSock.EndReceive(IAR);
|
||||
else
|
||||
bReceiveState = false;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bReceiveState = false;
|
||||
}
|
||||
//
|
||||
if (bReceiveState)
|
||||
{
|
||||
if (nReadSize != 0)
|
||||
{
|
||||
byte[] ucFindData = new byte[1];
|
||||
//byte[] ucSetClearArray;
|
||||
|
||||
int iFindDataCnt = 0;
|
||||
|
||||
//bool bSegmentFind = false;
|
||||
bool bDataFind = false;
|
||||
|
||||
byte ucGetLabel = 0;
|
||||
|
||||
try
|
||||
{
|
||||
/*
|
||||
Array.Copy(recvBuffer, 0, recvStoreBuffer, iStoreCnt, nReadSize);
|
||||
|
||||
iStoreCnt += nReadSize;
|
||||
*/
|
||||
|
||||
if (bQueuePacketClearOn)
|
||||
{
|
||||
bQueuePacketClearOn = false;
|
||||
|
||||
QPacketAllData.Clear();
|
||||
}
|
||||
|
||||
QPacketAllData.Enqueue(new CPacketDataInfo(DateTime.Now, recvBuffer, nReadSize));
|
||||
|
||||
foreach (var n in QPacketAllData.ToList())
|
||||
{
|
||||
TimeSpan dsInterval = DateTime.Now - n.dtPacket;
|
||||
|
||||
//오랜된 패킷 소거
|
||||
if (dsInterval.TotalSeconds >= 20.0)
|
||||
QPacketAllData.Dequeue();
|
||||
else
|
||||
QPacketRemainData.Enqueue(new CPacketDataInfo(n.ID, n.dtPacket, n.ucData, n.nDataSize));
|
||||
}
|
||||
//
|
||||
iStoreCnt = 0;
|
||||
Array.Clear(recvStoreBuffer, 0, USER_MAX_SIZE);
|
||||
|
||||
Guid[] guidUsePacketID = new Guid[QPacketRemainData.Count];
|
||||
int nPacketPos = 0;
|
||||
|
||||
//남은 패킷중 연산 시도
|
||||
foreach (var n in QPacketRemainData.ToList())
|
||||
{
|
||||
Array.Copy(n.ucData, 0, recvStoreBuffer, iStoreCnt, n.nDataSize);
|
||||
|
||||
iStoreCnt += n.nDataSize;
|
||||
|
||||
guidUsePacketID[nPacketPos++] = n.ID;
|
||||
|
||||
for (int j = 0; j < iStoreCnt; j++)
|
||||
{
|
||||
if (recvStoreBuffer[j] == 0x0D &&
|
||||
recvStoreBuffer[j + 1] == 0x02 &&
|
||||
recvStoreBuffer[j + 6] == 0x08 &&
|
||||
recvStoreBuffer[j + 7] == 0x0A)
|
||||
{
|
||||
ucGetLabel = recvStoreBuffer[j - 1];
|
||||
|
||||
uint uiGetPacketSize = 0x0;
|
||||
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[j + 2] << 24);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[j + 3] << 16);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[j + 4] << 8);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[j + 5] << 0);
|
||||
|
||||
int iGetSize = (int)uiGetPacketSize;
|
||||
|
||||
iGetSize += XCommons.PAD_SIZE;
|
||||
|
||||
if (recvStoreBuffer[j + iGetSize - 4] == 0x0D &&
|
||||
recvStoreBuffer[j + iGetSize - 3] == 0x02 &&
|
||||
recvStoreBuffer[j + iGetSize - 2] == 0x08 &&
|
||||
recvStoreBuffer[j + iGetSize - 1] == 0x0A)
|
||||
{
|
||||
iFindDataCnt = iGetSize;
|
||||
|
||||
ucFindData = new byte[iFindDataCnt];
|
||||
Array.Copy(recvStoreBuffer, j, ucFindData, 0, iFindDataCnt);
|
||||
|
||||
bDataFind = true;
|
||||
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
bDataFind = false;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
//
|
||||
if (bDataFind)
|
||||
{
|
||||
//성공한 패킷이 있을경우 해당 패킷 제거
|
||||
foreach (var m in QPacketAllData.ToList())
|
||||
{
|
||||
for (int i = 0; i < guidUsePacketID.Count(); i++)
|
||||
{
|
||||
if (m.ID == guidUsePacketID[i])
|
||||
{
|
||||
QPacketAllData.Dequeue();
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
QPacketRemainData.Clear();
|
||||
|
||||
//recvText += Encoding.Unicode.GetString(recvBuffer, 0, nReadSize);
|
||||
|
||||
/*
|
||||
for (int i = 0; i < iStoreCnt; i++)
|
||||
{
|
||||
if (recvStoreBuffer[i] == 0x0D &&
|
||||
recvStoreBuffer[i + 1] == 0x02 &&
|
||||
recvStoreBuffer[i + 6] == 0x08 &&
|
||||
recvStoreBuffer[i + 7] == 0x0A)
|
||||
{
|
||||
ucGetLabel = recvStoreBuffer[i - 1];
|
||||
|
||||
uint uiGetPacketSize = 0x0;
|
||||
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[i + 2] << 24);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[i + 3] << 16);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[i + 4] << 8);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[i + 5] << 0);
|
||||
|
||||
int iGetSize = (int)uiGetPacketSize;
|
||||
|
||||
iGetSize += XCommons.PAD_SIZE;
|
||||
|
||||
if (recvStoreBuffer[i + iGetSize - 4] == 0x0D &&
|
||||
recvStoreBuffer[i + iGetSize - 3] == 0x02 &&
|
||||
recvStoreBuffer[i + iGetSize - 2] == 0x08 &&
|
||||
recvStoreBuffer[i + iGetSize - 1] == 0x0A)
|
||||
{
|
||||
iFindDataCnt = iGetSize;
|
||||
|
||||
bSegmentFind = true;
|
||||
}
|
||||
if (bSegmentFind)
|
||||
{
|
||||
iCheckRetryCnt = 0;
|
||||
|
||||
ucFindData = new byte[iFindDataCnt];
|
||||
ucSetClearArray = new byte[(iFindDataCnt + 1)];
|
||||
|
||||
Array.Clear(ucSetClearArray, 0, (iFindDataCnt + 1));
|
||||
Array.Copy(recvStoreBuffer, i, ucFindData, 0, iFindDataCnt);
|
||||
|
||||
iStoreCnt -= (iFindDataCnt + 1);
|
||||
|
||||
Buffer.BlockCopy(ucSetClearArray, 0, recvStoreBuffer, 0, (iFindDataCnt + 1));
|
||||
Buffer.BlockCopy(recvStoreBuffer, iStoreCnt, recvStoreBuffer, 0, USER_MAX_SIZE - iStoreCnt);
|
||||
|
||||
bDataFind = true;
|
||||
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
iCheckRetryCnt++;
|
||||
|
||||
if (iCheckRetryCnt > MAX_CHECK_COUNT)
|
||||
{
|
||||
iCheckRetryCnt = 0;
|
||||
|
||||
ucSetClearArray = new byte[iFindDataCnt];
|
||||
Array.Clear(ucSetClearArray, 0, iFindDataCnt);
|
||||
|
||||
iStoreCnt -= iFindDataCnt;
|
||||
|
||||
Buffer.BlockCopy(ucSetClearArray, 0, recvStoreBuffer, 0, iFindDataCnt);
|
||||
Buffer.BlockCopy(recvStoreBuffer, iStoreCnt, recvStoreBuffer, 0, USER_MAX_SIZE - iStoreCnt);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bDataFind = false;
|
||||
|
||||
/*
|
||||
iStoreCnt = 0;
|
||||
|
||||
if (recvStoreBuffer != null) Array.Clear(recvStoreBuffer, 0, recvStoreBuffer.Count());
|
||||
*/
|
||||
}
|
||||
|
||||
if (bDataFind)
|
||||
{
|
||||
bool bDataControl = true;
|
||||
byte[] ucGetInfp = null;
|
||||
|
||||
try
|
||||
{
|
||||
ucGetInfp = new byte[iFindDataCnt];
|
||||
|
||||
Array.Copy(ucFindData, ucGetInfp, iFindDataCnt);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bDataControl = false;
|
||||
}
|
||||
|
||||
ScheduleEvent se = null;
|
||||
|
||||
m_bGetRecv = true;
|
||||
|
||||
//recvText = string.Empty;
|
||||
|
||||
if (bDataControl)
|
||||
{
|
||||
se = new ScheduleEvent(nSocketNumber, true, "Recv Success", ucGetLabel);
|
||||
}
|
||||
else
|
||||
{
|
||||
se = new ScheduleEvent(nSocketNumber, false, "Recv Fail", ucGetLabel);
|
||||
}
|
||||
|
||||
Comm_Recv_Event?.BeginInvoke(ucGetInfp, se, null, null);
|
||||
AwaitRecvEvent?.BeginInvoke(ucGetInfp, se, null, null);
|
||||
|
||||
//Comm_Recv_Event?.Invoke(ucGetInfp, se);
|
||||
//AwaitRecvEvent?.Invoke(ucGetInfp, se);
|
||||
}
|
||||
|
||||
this.Receive();
|
||||
//objScoket.WorkSocket.BeginReceive(objScoket.recvBuffer, 0, MAXSIZE, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), objScoket);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Dispose(true);
|
||||
|
||||
ErrorEventProcess(new CommonSocketException("Middleware server side connection lost.[SystemX.Net.Comm : AsyncClientSocket|OnReceiveCallBack]"));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Dispose(true);
|
||||
|
||||
ErrorEventProcess(new CommonSocketException("Middleware server side connection lost.[SystemX.Net.Comm : AsyncClientSocket|OnReceiveCallBack]"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,977 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Common;
|
||||
using SystemX.Common.Serialization;
|
||||
using SystemX.Net.Comm;
|
||||
|
||||
//using static SystemX.Net.Platform.Common.Util.LogMessage;
|
||||
|
||||
namespace SystemX.Net.Comm
|
||||
{
|
||||
public class AsyncServerSocket : SystemXSocket, IDisposable
|
||||
{
|
||||
private Socket ServerSock;
|
||||
|
||||
private IPAddress SetAddress;
|
||||
|
||||
//Unused
|
||||
private Socket ClientSock; /* client Socket */
|
||||
//private Socket cbClientSock; /* client Async Callback Socket */
|
||||
|
||||
private byte[] recvBuffer;
|
||||
//private String recvText;
|
||||
|
||||
private byte[] recvStoreBuffer;
|
||||
private int iStoreCnt;
|
||||
private int iCheckRetryCnt;
|
||||
|
||||
private const int MAX_CHECK_COUNT = 100; /* 256000 / 4096 <- 65526 / 4096 */
|
||||
private const int USER_MAX_SIZE = 819200; /* 256000 <- 1000000 65536 */
|
||||
private const int MAXSIZE = 8192; /* 8192 <- 4096 */
|
||||
|
||||
private string m_strGetIp;
|
||||
private int m_iGetPort;
|
||||
|
||||
private bool m_bOpen;
|
||||
private bool m_bConnected;
|
||||
|
||||
private string m_strGetText;
|
||||
private bool m_bGetRecv;
|
||||
|
||||
public override event SocketCallEvent Comm_Connect_Event;
|
||||
public override event SocketCallEvent Socket_Error_Event;
|
||||
|
||||
public override event SendRecvCallEvent Comm_Send_Event;
|
||||
public override event SendRecvCallEvent Comm_Recv_Event;
|
||||
|
||||
private Queue<CPacketDataInfo> QPacketAllData;
|
||||
private Queue<CPacketDataInfo> QPacketRemainData;
|
||||
|
||||
private bool bQueuePacketClearOn;
|
||||
|
||||
public override void SetRefSocketPacketClear()
|
||||
{
|
||||
bQueuePacketClearOn = true;
|
||||
}
|
||||
|
||||
private bool bDisposed;
|
||||
|
||||
//
|
||||
//private bool bHaveHostinfo;
|
||||
//private DataTable dtHostInfo;
|
||||
|
||||
public bool STATE
|
||||
{
|
||||
get { return this.m_bOpen; }
|
||||
}
|
||||
public bool CLIENT_CONNECT
|
||||
{
|
||||
get { return this.m_bConnected; }
|
||||
}
|
||||
public string MSG
|
||||
{
|
||||
set { this.m_strGetText = value; }
|
||||
get { return this.m_strGetText; }
|
||||
}
|
||||
public bool RECV_STATE
|
||||
{
|
||||
set { this.m_bGetRecv = value; }
|
||||
get { return this.m_bGetRecv; }
|
||||
}
|
||||
|
||||
public string strSetRemoteAddress { set; get; }
|
||||
public string strSetRemotePort { set; get; }
|
||||
|
||||
/*
|
||||
public bool HAVE_HOST_INFO
|
||||
{
|
||||
set { this.bHaveHostinfo = value; }
|
||||
get { return this.bHaveHostinfo; }
|
||||
}
|
||||
*/
|
||||
|
||||
public AsyncServerSocket(SOCKET_TYPE SOCK_TYPE, int iCreatePosition, IPEndPoint SetRemote) : base(SOCKET_RULE.SERVER, SOCK_TYPE)
|
||||
{
|
||||
bDisposed = false;
|
||||
|
||||
QPacketAllData = new Queue<CPacketDataInfo>();
|
||||
QPacketRemainData = new Queue<CPacketDataInfo>();
|
||||
|
||||
bQueuePacketClearOn = false;
|
||||
|
||||
strSetRemoteAddress = string.Empty;
|
||||
strSetRemotePort = string.Empty;
|
||||
|
||||
SetAddress = SetRemote.Address;
|
||||
|
||||
nSocketNumber = iCreatePosition;
|
||||
|
||||
m_strGetIp = SetRemote.Address.ToString();
|
||||
m_iGetPort = SetRemote.Port;
|
||||
|
||||
ServerSock = null;
|
||||
|
||||
ClientSock = null;
|
||||
//cbClientSock = null;
|
||||
|
||||
//recvText = string.Empty;
|
||||
recvStoreBuffer = new byte[USER_MAX_SIZE];
|
||||
iStoreCnt = 0;
|
||||
iCheckRetryCnt = 0;
|
||||
|
||||
recvBuffer = new byte[MAXSIZE];
|
||||
//
|
||||
m_bGetRecv = false;
|
||||
|
||||
m_bOpen = false;
|
||||
m_bConnected = false;
|
||||
|
||||
SetSocketListen();
|
||||
}
|
||||
|
||||
public AsyncServerSocket(SOCKET_TYPE SOCK_TYPE, int iCreatePosition, IPEndPoint SetRemote, DataTable dtHostInfomation) : base(SOCKET_RULE.SERVER, SOCK_TYPE)
|
||||
{
|
||||
bDisposed = false;
|
||||
|
||||
strSetRemoteAddress = string.Empty;
|
||||
strSetRemotePort = string.Empty;
|
||||
|
||||
SetAddress = SetRemote.Address;
|
||||
|
||||
nSocketNumber = iCreatePosition;
|
||||
|
||||
m_strGetIp = SetRemote.Address.ToString();
|
||||
m_iGetPort = SetRemote.Port;
|
||||
|
||||
ServerSock = null;
|
||||
ClientSock = null;
|
||||
//cbClientSock = null;
|
||||
|
||||
//recvText = string.Empty;
|
||||
recvStoreBuffer = new byte[USER_MAX_SIZE];
|
||||
iStoreCnt = 0;
|
||||
iCheckRetryCnt = 0;
|
||||
|
||||
recvBuffer = new byte[MAXSIZE];
|
||||
//
|
||||
m_bGetRecv = false;
|
||||
|
||||
m_bOpen = false;
|
||||
m_bConnected = false;
|
||||
|
||||
SetSocketListen();
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (!bDisposed)
|
||||
{
|
||||
ConnectTokken.SetTokenState((ConnectTokken.Connect_Token)nSocketNumber, false);
|
||||
|
||||
try
|
||||
{
|
||||
if (ServerSock != null)
|
||||
{
|
||||
if (ServerSock.Connected)
|
||||
ServerSock.Shutdown(SocketShutdown.Both);
|
||||
|
||||
ServerSock.Close();
|
||||
//ServerSock.Dispose();
|
||||
ServerSock = null;
|
||||
}
|
||||
|
||||
m_bOpen = false;
|
||||
|
||||
ClientSock = null;
|
||||
|
||||
m_bConnected = false;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ClientSock = null;
|
||||
|
||||
ServerSock = null;
|
||||
|
||||
m_bOpen = false;
|
||||
|
||||
m_bConnected = false;
|
||||
|
||||
ErrorEventProcess(new Exception("Dispose failed. [SystemX.Net.Comm : AsyncServerSocket.Dispose]"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
/*
|
||||
ClearEventConnectCall();
|
||||
ClearEventErrorCall();
|
||||
*/
|
||||
|
||||
ClearEventSendCall();
|
||||
ClearEventRecvCall();
|
||||
}
|
||||
|
||||
if (disposing)
|
||||
{
|
||||
//Manage
|
||||
}
|
||||
|
||||
//Unmanage
|
||||
recvStoreBuffer = null;
|
||||
recvBuffer = null;
|
||||
|
||||
bDisposed = true;
|
||||
}
|
||||
|
||||
//Base Dispose
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
public void ClearEventConnectCall()
|
||||
{
|
||||
if (Comm_Connect_Event != null)
|
||||
{
|
||||
foreach (Delegate d in Comm_Connect_Event.GetInvocationList())
|
||||
Comm_Connect_Event -= (SocketCallEvent)d;
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearEventErrorCall()
|
||||
{
|
||||
if (Socket_Error_Event != null)
|
||||
{
|
||||
foreach (Delegate d in Socket_Error_Event.GetInvocationList())
|
||||
Socket_Error_Event -= (SocketCallEvent)d;
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearEventSendCall()
|
||||
{
|
||||
if (Comm_Send_Event != null)
|
||||
{
|
||||
foreach (Delegate d in Comm_Send_Event.GetInvocationList())
|
||||
Comm_Send_Event -= (SendRecvCallEvent)d;
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearEventRecvCall()
|
||||
{
|
||||
if (Comm_Recv_Event != null)
|
||||
{
|
||||
foreach (Delegate d in Comm_Recv_Event.GetInvocationList())
|
||||
Comm_Recv_Event -= (SendRecvCallEvent)d;
|
||||
}
|
||||
}
|
||||
|
||||
public void ServerSocketAllClearToken()
|
||||
{
|
||||
ConnectTokken.AllClearToken((ConnectTokken.Connect_Token)nSocketNumber);
|
||||
}
|
||||
|
||||
public bool ServerTokenPosCheck(int iGet)
|
||||
{
|
||||
return ConnectTokken.GetTokenPosState((ConnectTokken.Connect_Token)nSocketNumber, iGet);
|
||||
}
|
||||
|
||||
public void ServerSocketUnknownError(bool bCallEvent = true)
|
||||
{
|
||||
ConnectTokken.SetTokenState((ConnectTokken.Connect_Token)nSocketNumber, false);
|
||||
|
||||
try
|
||||
{
|
||||
if (ClientSock != null)
|
||||
{
|
||||
if (ClientSock.Connected)
|
||||
{
|
||||
ClientSock.Disconnect(false);
|
||||
ClientSock.Shutdown(SocketShutdown.Both);
|
||||
|
||||
ClientSock.Close();
|
||||
ClientSock = null;
|
||||
}
|
||||
|
||||
ClientSock = null;
|
||||
}
|
||||
|
||||
//m_bOpen = false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ClientSock = null;
|
||||
|
||||
//MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"Client socket release error.[SystemX.Net.Net.Comm.AsyncServerSocket] " + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
m_bConnected = false;
|
||||
|
||||
if (bCallEvent)
|
||||
Socket_Error_Event?.Invoke(null, new ScheduleEvent(nSocketNumber, false, "Error", 0));
|
||||
}
|
||||
private void ErrorEventProcess(Exception e, bool ConnectStateOff = false, bool bServerSock = false)
|
||||
{
|
||||
//if (e.SocketErrorCode == SocketError.NotConnected)
|
||||
ConnectTokken.SetTokenState((ConnectTokken.Connect_Token)nSocketNumber, false);
|
||||
|
||||
if (bServerSock == false)
|
||||
m_bConnected = ConnectStateOff;
|
||||
else
|
||||
m_bOpen = ConnectStateOff;
|
||||
|
||||
Socket_Error_Event?.Invoke(e, new ScheduleEvent(nSocketNumber, false, "Error", 0));
|
||||
}
|
||||
private void AcceptCallback(IAsyncResult ar)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (m_bOpen)
|
||||
{
|
||||
Socket SockListen = null;
|
||||
|
||||
try
|
||||
{
|
||||
SockListen = (Socket)ar?.AsyncState;
|
||||
|
||||
int nGetAvailable = SockListen.Available;
|
||||
}
|
||||
catch (ObjectDisposedException dispose)
|
||||
{
|
||||
SockListen = null;
|
||||
|
||||
throw new Exception();
|
||||
}
|
||||
|
||||
if (SockListen != null)
|
||||
{
|
||||
IPEndPoint GetIPInfo = (IPEndPoint)SockListen.LocalEndPoint;
|
||||
|
||||
if (ConnectTokken.GetTokenState((ConnectTokken.Connect_Token)nSocketNumber) == false)
|
||||
{
|
||||
ConnectTokken.SetTokenState((ConnectTokken.Connect_Token)nSocketNumber, true);
|
||||
|
||||
//AsyncSocketObject objScoket = new AsyncSocketObject(MAXSIZE);
|
||||
|
||||
Socket sockClient = SockListen.EndAccept(ar);
|
||||
|
||||
//objScoket.WorkSocket = sockClient;
|
||||
ClientSock = sockClient; // objScoket.WorkSocket;
|
||||
|
||||
m_bConnected = true;
|
||||
|
||||
sockClient.BeginReceive(recvBuffer, 0, MAXSIZE, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), ClientSock);
|
||||
|
||||
Comm_Connect_Event?.BeginInvoke(ClientSock, new ScheduleEvent(nSocketNumber, true, "Connect", 0), InvokeCallback, null);
|
||||
}
|
||||
|
||||
//클라이언트의 연결 요청 대기
|
||||
SockListen.BeginAccept(AcceptCallback, SockListen);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//종료 또는 Accept 실패.
|
||||
ErrorEventProcess(new CommonSocketException("Middleware server side connection lost.[SystemX.Net.Comm : AsyncServerSocket|AcceptCallback]"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void InvokeCallback(object obj)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
private void SetSocketListen()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (base.SOCK_TYPE == SOCKET_TYPE.TCP)
|
||||
{
|
||||
ServerSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
|
||||
|
||||
LingerOption SetLinger = new LingerOption(true, 0);
|
||||
ServerSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, SetLinger);
|
||||
//ServerSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
|
||||
|
||||
var option = new TcpKeepAlive
|
||||
{
|
||||
OnOff = 1,
|
||||
KeepAliveTime = 90000,
|
||||
KeepAliveInterval = 3000
|
||||
};
|
||||
|
||||
int iState = ServerSock.IOControl(IOControlCode.KeepAliveValues, option.GetBytes(), null);
|
||||
|
||||
// 서버에서 클라이언트의 연결 요청을 대기하기 위해 소켓을 열어둔다.
|
||||
IPEndPoint mkServerEP;
|
||||
mkServerEP = new IPEndPoint(SetAddress, m_iGetPort);
|
||||
|
||||
ServerSock.Bind(mkServerEP);
|
||||
ServerSock.Listen(1024);
|
||||
|
||||
SetSocketBeginReady();
|
||||
}
|
||||
else if (base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
{
|
||||
ServerSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
|
||||
|
||||
// 서버에서 클라이언트의 연결 요청을 대기하기 위해 소켓을 열어둔다.
|
||||
IPEndPoint mkServerEP;
|
||||
mkServerEP = new IPEndPoint(SetAddress, m_iGetPort);
|
||||
|
||||
EndPoint ServerEP;
|
||||
ServerEP = new IPEndPoint(SetAddress, m_iGetPort);
|
||||
|
||||
ServerSock.Bind(mkServerEP);
|
||||
|
||||
//ServerSock.BeginReceiveFrom(recvBuffer, 0, MAXSIZE, SocketFlags.None, ref ServerEP, new AsyncCallback(OnReceiveCallBack), ServerSock);
|
||||
|
||||
ServerSock.BeginReceive(recvBuffer, 0, MAXSIZE, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), ServerSock);
|
||||
}
|
||||
|
||||
m_bOpen = true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//종료 또는 Accept 실패.
|
||||
ErrorEventProcess(new CommonSocketException("Server socket open-ready fail.[SystemX.Net.Comm : AsyncServerSocket|DoInit]"), false, true);
|
||||
}
|
||||
}
|
||||
|
||||
private void SetSocketBeginReady()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (ServerSock != null)
|
||||
// 비동기적으로 클라이언트의 연결 요청을 받는다.
|
||||
ServerSock.BeginAccept(AcceptCallback, ServerSock);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//종료 또는 Accept 실패.
|
||||
ErrorEventProcess(new CommonSocketException("Server socket BeginAccept() fail. [SystemX.Net.Comm : AsyncServerSocket|SetSocketListen]"), false, true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public override bool BeginSend(byte[] ucDatas)
|
||||
{
|
||||
bool bState = true;
|
||||
|
||||
if (ClientSock == null)
|
||||
{
|
||||
if (base.SOCK_TYPE != SOCKET_TYPE.UDP)
|
||||
return false;
|
||||
else
|
||||
{
|
||||
if (ServerSock == null)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (base.SOCK_TYPE == SOCKET_TYPE.TCP)
|
||||
{
|
||||
/* 연결 성공시 */
|
||||
if (ClientSock.Connected) ClientSock.BeginSend(ucDatas, 0, ucDatas.Length, SocketFlags.None, new AsyncCallback(SendCallBack), ucDatas);
|
||||
}
|
||||
else if (base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
{
|
||||
if (strSetRemoteAddress.Length > 0 && strSetRemotePort.Length > 0)
|
||||
{
|
||||
EndPoint setRemote = new IPEndPoint(IPAddress.Parse(strSetRemoteAddress), int.Parse(strSetRemotePort));
|
||||
ServerSock.BeginSendTo(ucDatas, 0, ucDatas.Length, SocketFlags.None, setRemote, new AsyncCallback(SendCallBack), ucDatas);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bState = false;
|
||||
|
||||
//전송 에러
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
|
||||
return bState;
|
||||
}
|
||||
public override bool BeginSend(Socket SetSock, byte[] ucDatas)
|
||||
{
|
||||
bool bState = true;
|
||||
|
||||
if (SetSock == null)
|
||||
{
|
||||
if (base.SOCK_TYPE != SOCKET_TYPE.UDP)
|
||||
return false;
|
||||
else
|
||||
{
|
||||
if (ServerSock == null)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
/* 연결 성공시 */
|
||||
if (base.SOCK_TYPE == SOCKET_TYPE.TCP)
|
||||
{
|
||||
if (SetSock.Connected) SetSock.BeginSend(ucDatas, 0, ucDatas.Length, SocketFlags.None, new AsyncCallback(SendCallBack), ucDatas);
|
||||
}
|
||||
else if (base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
{
|
||||
if (strSetRemoteAddress.Length > 0 && strSetRemotePort.Length > 0)
|
||||
{
|
||||
EndPoint setRemote = new IPEndPoint(IPAddress.Parse(strSetRemoteAddress), int.Parse(strSetRemotePort));
|
||||
ServerSock.BeginSendTo(ucDatas, 0, ucDatas.Length, SocketFlags.None, setRemote, new AsyncCallback(SendCallBack), ucDatas);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bState = false;
|
||||
|
||||
//전송 에러
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
|
||||
return bState;
|
||||
}
|
||||
public override bool BeginSend(string strMessage)
|
||||
{
|
||||
bool bState = true;
|
||||
|
||||
if (ClientSock == null)
|
||||
{
|
||||
if (base.SOCK_TYPE != SOCKET_TYPE.UDP)
|
||||
return false;
|
||||
else
|
||||
{
|
||||
if (ServerSock == null)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
byte[] buffer = new UnicodeEncoding().GetBytes(strMessage);
|
||||
|
||||
/* 연결 성공시 */
|
||||
if (base.SOCK_TYPE == SOCKET_TYPE.TCP)
|
||||
{
|
||||
if (ClientSock.Connected) ClientSock.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), strMessage);
|
||||
}
|
||||
else if (base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
{
|
||||
if (strSetRemoteAddress.Length > 0 && strSetRemotePort.Length > 0)
|
||||
{
|
||||
EndPoint setRemote = new IPEndPoint(IPAddress.Parse(strSetRemoteAddress), int.Parse(strSetRemotePort));
|
||||
ServerSock.BeginSendTo(buffer, 0, buffer.Length, SocketFlags.None, setRemote, new AsyncCallback(SendCallBack), strMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bState = false;
|
||||
|
||||
//전송 에러
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
|
||||
return bState;
|
||||
}
|
||||
private void SendCallBack(IAsyncResult IAR)
|
||||
{
|
||||
//전송 완료
|
||||
byte[] getData = null;
|
||||
ScheduleEvent se = new ScheduleEvent(nSocketNumber, false, "Send Fail", 0);
|
||||
|
||||
if (ClientSock == null)
|
||||
{
|
||||
if (base.SOCK_TYPE != SOCKET_TYPE.UDP)
|
||||
return;
|
||||
else
|
||||
{
|
||||
if (ServerSock == null)
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
bool bResult = true;
|
||||
try
|
||||
{
|
||||
getData = (byte[])IAR.AsyncState;
|
||||
|
||||
if (getData != null)
|
||||
se = new ScheduleEvent(nSocketNumber, true, "Send Success", 0);
|
||||
else
|
||||
se = new ScheduleEvent(nSocketNumber, false, "Send Fail", 0);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bResult = false;
|
||||
|
||||
//Callback Error
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (bResult)
|
||||
{
|
||||
Comm_Send_Event?.BeginInvoke(getData, se, null, null);
|
||||
}
|
||||
}
|
||||
//
|
||||
try
|
||||
{
|
||||
int iSendCnt = 0;
|
||||
|
||||
if (base.SOCK_TYPE != SOCKET_TYPE.UDP)
|
||||
iSendCnt = ClientSock.EndSend(IAR);
|
||||
else
|
||||
iSendCnt = ServerSock.EndSend(IAR);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bResult = false;
|
||||
|
||||
//Callback Error
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void Receive()
|
||||
{
|
||||
if (ClientSock == null)
|
||||
{
|
||||
if (base.SOCK_TYPE != SOCKET_TYPE.UDP)
|
||||
return;
|
||||
else
|
||||
{
|
||||
if (ServerSock == null)
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
//받기
|
||||
try
|
||||
{
|
||||
if (base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
ServerSock.BeginReceive(recvBuffer, 0, MAXSIZE, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), ServerSock);
|
||||
else
|
||||
{
|
||||
if (ClientSock.Connected)
|
||||
ClientSock.BeginReceive(recvBuffer, 0, MAXSIZE, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), ClientSock);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ErrorEventProcess(e);
|
||||
}
|
||||
}
|
||||
private void OnReceiveCallBack(IAsyncResult IAR)
|
||||
{
|
||||
bool bReceiveState = true;
|
||||
int nReadSize = 0;
|
||||
|
||||
Socket ClientSideSock;
|
||||
//AsyncSocketObject objScoket = null;
|
||||
|
||||
try
|
||||
{
|
||||
//수신
|
||||
ClientSideSock = (Socket)IAR.AsyncState;
|
||||
//objScoket = (AsyncSocketObject)IAR.AsyncState;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.Dispose();
|
||||
|
||||
//수신 실패
|
||||
ErrorEventProcess(new CommonSocketException("Middleware server side connection lost.[SystemX.Net.Comm : AsyncServerSocket|OnReceiveCallBack]"));
|
||||
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (ClientSideSock.Connected)
|
||||
nReadSize = ClientSideSock.EndReceive(IAR);
|
||||
else
|
||||
{
|
||||
if (base.SOCK_TYPE == SOCKET_TYPE.UDP)
|
||||
nReadSize = ClientSideSock.EndReceive(IAR);
|
||||
else
|
||||
bReceiveState = false;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bReceiveState = false;
|
||||
}
|
||||
//
|
||||
if (bReceiveState)
|
||||
{
|
||||
if (nReadSize != 0)
|
||||
{
|
||||
byte[] ucFindData = new byte[1];
|
||||
byte[] ucSetClearArray;
|
||||
|
||||
int iFindDataCnt = 0;
|
||||
|
||||
bool bSegmentFind = false;
|
||||
bool bDataFind = false;
|
||||
|
||||
byte ucGetLabel = 0;
|
||||
|
||||
try
|
||||
{
|
||||
/*
|
||||
Array.Copy(recvBuffer, 0, recvStoreBuffer, iStoreCnt, nReadSize);
|
||||
|
||||
iStoreCnt += nReadSize;
|
||||
*/
|
||||
|
||||
if(bQueuePacketClearOn)
|
||||
{
|
||||
bQueuePacketClearOn = false;
|
||||
|
||||
QPacketAllData.Clear();
|
||||
}
|
||||
|
||||
QPacketAllData.Enqueue(new CPacketDataInfo(DateTime.Now, recvBuffer, nReadSize));
|
||||
|
||||
foreach (var n in QPacketAllData.ToList())
|
||||
{
|
||||
TimeSpan dsInterval = DateTime.Now - n.dtPacket;
|
||||
|
||||
//오랜된 패킷 소거
|
||||
if (dsInterval.TotalSeconds >= 20.0)
|
||||
QPacketAllData.Dequeue();
|
||||
else
|
||||
QPacketRemainData.Enqueue(new CPacketDataInfo(n.ID, n.dtPacket, n.ucData, n.nDataSize));
|
||||
}
|
||||
//
|
||||
iStoreCnt = 0;
|
||||
Array.Clear(recvStoreBuffer, 0, USER_MAX_SIZE);
|
||||
|
||||
Guid[] guidUsePacketID = new Guid[QPacketRemainData.Count];
|
||||
int nPacketPos = 0;
|
||||
|
||||
//남은 패킷중 연산 시도
|
||||
foreach (var n in QPacketRemainData.ToList())
|
||||
{
|
||||
Array.Copy(n.ucData, 0, recvStoreBuffer, iStoreCnt, n.nDataSize);
|
||||
|
||||
iStoreCnt += n.nDataSize;
|
||||
|
||||
guidUsePacketID[nPacketPos++] = n.ID;
|
||||
|
||||
for (int j = 0; j < iStoreCnt; j++)
|
||||
{
|
||||
if (recvStoreBuffer[j] == 0x0D &&
|
||||
recvStoreBuffer[j + 1] == 0x02 &&
|
||||
recvStoreBuffer[j + 6] == 0x08 &&
|
||||
recvStoreBuffer[j + 7] == 0x0A)
|
||||
{
|
||||
ucGetLabel = recvStoreBuffer[j - 1];
|
||||
|
||||
uint uiGetPacketSize = 0x0;
|
||||
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[j + 2] << 24);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[j + 3] << 16);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[j + 4] << 8);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[j + 5] << 0);
|
||||
|
||||
int iGetSize = (int)uiGetPacketSize;
|
||||
|
||||
iGetSize += XCommons.PAD_SIZE;
|
||||
|
||||
if (recvStoreBuffer[j + iGetSize - 4] == 0x0D &&
|
||||
recvStoreBuffer[j + iGetSize - 3] == 0x02 &&
|
||||
recvStoreBuffer[j + iGetSize - 2] == 0x08 &&
|
||||
recvStoreBuffer[j + iGetSize - 1] == 0x0A)
|
||||
{
|
||||
iFindDataCnt = iGetSize;
|
||||
|
||||
ucFindData = new byte[iFindDataCnt];
|
||||
Array.Copy(recvStoreBuffer, j, ucFindData, 0, iFindDataCnt);
|
||||
|
||||
bDataFind = true;
|
||||
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
bDataFind = false;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
//
|
||||
if (bDataFind)
|
||||
{
|
||||
//성공한 패킷이 있을경우 해당 패킷 제거
|
||||
foreach (var m in QPacketAllData.ToList())
|
||||
{
|
||||
for (int i = 0; i < guidUsePacketID.Count(); i++)
|
||||
{
|
||||
if (m.ID == guidUsePacketID[i])
|
||||
{
|
||||
QPacketAllData.Dequeue();
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
QPacketRemainData.Clear();
|
||||
|
||||
//recvText += Encoding.Unicode.GetString(recvBuffer, 0, nReadSize);
|
||||
|
||||
/*
|
||||
for (int i = 0; i < iStoreCnt; i++)
|
||||
{
|
||||
if (recvStoreBuffer[i] == 0x0D &&
|
||||
recvStoreBuffer[i + 1] == 0x02 &&
|
||||
recvStoreBuffer[i + 6] == 0x08 &&
|
||||
recvStoreBuffer[i + 7] == 0x0A)
|
||||
{
|
||||
ucGetLabel = recvStoreBuffer[i - 1];
|
||||
|
||||
uint uiGetPacketSize = 0x0;
|
||||
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[i + 2] << 24);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[i + 3] << 16);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[i + 4] << 8);
|
||||
uiGetPacketSize |= (uint)(recvStoreBuffer[i + 5] << 0);
|
||||
|
||||
int iGetSize = (int)uiGetPacketSize;
|
||||
|
||||
iGetSize += XCommons.PAD_SIZE;
|
||||
|
||||
if (recvStoreBuffer[i + iGetSize - 4] == 0x0D &&
|
||||
recvStoreBuffer[i + iGetSize - 3] == 0x02 &&
|
||||
recvStoreBuffer[i + iGetSize - 2] == 0x08 &&
|
||||
recvStoreBuffer[i + iGetSize - 1] == 0x0A)
|
||||
{
|
||||
iFindDataCnt = iGetSize;
|
||||
|
||||
bSegmentFind = true;
|
||||
}
|
||||
if (bSegmentFind)
|
||||
{
|
||||
iCheckRetryCnt = 0;
|
||||
|
||||
ucFindData = new byte[iFindDataCnt];
|
||||
ucSetClearArray = new byte[(iFindDataCnt + 1)];
|
||||
|
||||
Array.Clear(ucSetClearArray, 0, (iFindDataCnt + 1));
|
||||
Array.Copy(recvStoreBuffer, i, ucFindData, 0, iFindDataCnt);
|
||||
|
||||
iStoreCnt -= (iFindDataCnt + 1);
|
||||
|
||||
Buffer.BlockCopy(ucSetClearArray, 0, recvStoreBuffer, 0, (iFindDataCnt + 1));
|
||||
Buffer.BlockCopy(recvStoreBuffer, iStoreCnt, recvStoreBuffer, 0, USER_MAX_SIZE - iStoreCnt);
|
||||
|
||||
bDataFind = true;
|
||||
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
iCheckRetryCnt++;
|
||||
|
||||
if (iCheckRetryCnt > MAX_CHECK_COUNT)
|
||||
{
|
||||
iCheckRetryCnt = 0;
|
||||
|
||||
ucSetClearArray = new byte[iFindDataCnt];
|
||||
Array.Clear(ucSetClearArray, 0, iFindDataCnt);
|
||||
|
||||
iStoreCnt -= iFindDataCnt;
|
||||
|
||||
Buffer.BlockCopy(ucSetClearArray, 0, recvStoreBuffer, 0, iFindDataCnt);
|
||||
Buffer.BlockCopy(recvStoreBuffer, iStoreCnt, recvStoreBuffer, 0, USER_MAX_SIZE - iStoreCnt);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bDataFind = false;
|
||||
|
||||
/*
|
||||
iStoreCnt = 0;
|
||||
|
||||
if (recvStoreBuffer != null) Array.Clear(recvStoreBuffer, 0, recvStoreBuffer.Count());
|
||||
*/
|
||||
}
|
||||
//
|
||||
if (bDataFind)
|
||||
{
|
||||
bool bDataControl = true;
|
||||
|
||||
byte[] ucGetInfp = null;
|
||||
|
||||
try
|
||||
{
|
||||
ucGetInfp = new byte[iFindDataCnt];
|
||||
|
||||
Array.Copy(ucFindData, ucGetInfp, iFindDataCnt);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bDataControl = false;
|
||||
}
|
||||
|
||||
ScheduleEvent se = null;
|
||||
|
||||
m_bGetRecv = true;
|
||||
|
||||
//recvText = string.Empty;
|
||||
|
||||
if (bDataControl)
|
||||
{
|
||||
se = new ScheduleEvent(nSocketNumber, true, "Recv Success", ucGetLabel);
|
||||
}
|
||||
else
|
||||
{
|
||||
se = new ScheduleEvent(nSocketNumber, false, "Recv Fail", ucGetLabel);
|
||||
}
|
||||
|
||||
|
||||
Comm_Recv_Event?.BeginInvoke(ucGetInfp, se, null, null);
|
||||
}
|
||||
|
||||
this.Receive();
|
||||
//objScoket.WorkSocket.BeginReceive(objScoket.recvBuffer, 0, MAXSIZE, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), objScoket);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Dispose();
|
||||
|
||||
ErrorEventProcess(new Exception("Middleware server side connection lost.[SystemX.Net.Comm : AsyncServerSocket.OnReceiveCallBack]"));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Dispose();
|
||||
|
||||
ErrorEventProcess(new Exception("Middleware server side connection lost.[SystemX.Net.Comm : AsyncServerSocket.OnReceiveCallBack]"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,383 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Common;
|
||||
using SystemX.Common.Serialization;
|
||||
|
||||
namespace SystemX.Net.Comm
|
||||
{
|
||||
//
|
||||
// 요약:
|
||||
// Socket error information
|
||||
public class CommonSocketException : Exception
|
||||
{
|
||||
public CommonSocketException()
|
||||
{
|
||||
}
|
||||
|
||||
public CommonSocketException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public CommonSocketException(string message, Exception inner)
|
||||
: base(message, inner)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public enum SOCKET_RULE
|
||||
{
|
||||
NONE = -1,
|
||||
SERVER = 0,
|
||||
CLIENT = 1
|
||||
}
|
||||
|
||||
public enum SOCKET_TYPE
|
||||
{
|
||||
NONE = -1,
|
||||
TCP = 0,
|
||||
UDP = 1
|
||||
}
|
||||
|
||||
public class SystemXSocket : IDisposable
|
||||
{
|
||||
public virtual event SocketCallEvent Comm_Connect_Event;
|
||||
public virtual event SocketCallEvent Socket_Error_Event;
|
||||
|
||||
public virtual event SendRecvCallEvent Comm_Send_Event;
|
||||
public virtual event SendRecvCallEvent Comm_Recv_Event;
|
||||
|
||||
public virtual event EventHandler<ScheduleEvent> AwaitSendEvent;
|
||||
public virtual event EventHandler<ScheduleEvent> AwaitRecvEvent;
|
||||
|
||||
public int nSocketNumber;
|
||||
|
||||
private bool bDisposed;
|
||||
|
||||
public SOCKET_RULE SOCK_RULE { set; get; }
|
||||
|
||||
public SOCKET_TYPE SOCK_TYPE { set; get; }
|
||||
|
||||
|
||||
public SystemXSocket(SOCKET_RULE GET_SOCK_RULE, SOCKET_TYPE GET_SOCK_TYPE) {
|
||||
SOCK_RULE = GET_SOCK_RULE;
|
||||
|
||||
SOCK_TYPE = GET_SOCK_TYPE;
|
||||
|
||||
bDisposed = false;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool bDisposing)
|
||||
{
|
||||
if(bDisposed == false)
|
||||
{
|
||||
if(bDisposing)
|
||||
{
|
||||
//Manage
|
||||
}
|
||||
|
||||
//Unmanage
|
||||
|
||||
bDisposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
~SystemXSocket()
|
||||
{
|
||||
Dispose(false);
|
||||
}
|
||||
|
||||
public virtual bool BeginSend(byte[] ucDatas) { return true; }
|
||||
public virtual bool BeginSend(Socket SetSock, byte[] ucDatas) { return true; }
|
||||
public virtual bool BeginSend(string strMessage) { return true; }
|
||||
|
||||
public virtual void SetRefSocketPacketClear() { return; }
|
||||
}
|
||||
|
||||
public class CPacketDataInfo
|
||||
{
|
||||
public Guid ID;
|
||||
public DateTime dtPacket;
|
||||
public byte[] ucData;
|
||||
public int nDataSize;
|
||||
|
||||
public CPacketDataInfo(DateTime dateTime, byte[] ucGetData, int nGetSize)
|
||||
{
|
||||
if (ID == default(Guid))
|
||||
ID = Guid.NewGuid();
|
||||
|
||||
dtPacket = dateTime;
|
||||
|
||||
nDataSize = nGetSize;
|
||||
|
||||
ucData = new byte[nGetSize];
|
||||
|
||||
Buffer.BlockCopy(ucGetData, 0, ucData, 0, nGetSize);
|
||||
}
|
||||
public CPacketDataInfo(Guid SetID, DateTime dateTime, byte[] ucGetData, int nGetSize)
|
||||
{
|
||||
ID = SetID;
|
||||
|
||||
dtPacket = dateTime;
|
||||
|
||||
nDataSize = nGetSize;
|
||||
|
||||
ucData = new byte[nGetSize];
|
||||
|
||||
Buffer.BlockCopy(ucGetData, 0, ucData, 0, nGetSize);
|
||||
}
|
||||
}
|
||||
|
||||
public class AsyncSocketObject
|
||||
{
|
||||
public byte[] recvBuffer;
|
||||
public Socket WorkSocket;
|
||||
public readonly int iBufferSize;
|
||||
|
||||
public AsyncSocketObject(int ibufferSize)
|
||||
{
|
||||
iBufferSize = ibufferSize;
|
||||
|
||||
recvBuffer = new byte[iBufferSize];
|
||||
}
|
||||
|
||||
public void ClearBuffer()
|
||||
{
|
||||
Array.Clear(recvBuffer, 0, iBufferSize);
|
||||
}
|
||||
}
|
||||
|
||||
public class TcpKeepAlive
|
||||
{
|
||||
public uint OnOff { get; set; }
|
||||
public uint KeepAliveTime { get; set; }
|
||||
public uint KeepAliveInterval { get; set; }
|
||||
|
||||
public byte[] GetBytes()
|
||||
{
|
||||
return BitConverter.GetBytes(OnOff).Concat(BitConverter.GetBytes(KeepAliveTime)).Concat(BitConverter.GetBytes(KeepAliveInterval)).ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
public static class ConnectTokken
|
||||
{
|
||||
public enum Connect_Token
|
||||
{
|
||||
T010 = 0,
|
||||
T020 = 1,
|
||||
T030 = 2,
|
||||
T040 = 3,
|
||||
T050 = 4,
|
||||
T060 = 5,
|
||||
T070 = 6,
|
||||
T080 = 7,
|
||||
T090 = 8,
|
||||
T100 = 9,
|
||||
T110 = 10,
|
||||
T120 = 11,
|
||||
T130 = 12,
|
||||
T140 = 13,
|
||||
T150 = 14,
|
||||
T160 = 15,
|
||||
T170 = 16,
|
||||
T180 = 17,
|
||||
T190 = 18,
|
||||
T200 = 19,
|
||||
T210 = 20,
|
||||
T220 = 21,
|
||||
T230 = 22,
|
||||
T240 = 23,
|
||||
T250 = 24,
|
||||
T260 = 25,
|
||||
T270 = 26,
|
||||
T280 = 27,
|
||||
T290 = 28,
|
||||
T300 = 29,
|
||||
T310 = 30,
|
||||
T320 = 31,
|
||||
T330 = 32,
|
||||
T340 = 33,
|
||||
T350 = 34,
|
||||
T360 = 35,
|
||||
T370 = 36,
|
||||
T380 = 37,
|
||||
T390 = 38,
|
||||
T400 = 39,
|
||||
T410 = 40,
|
||||
T420 = 41,
|
||||
T430 = 42,
|
||||
T440 = 43,
|
||||
T450 = 44,
|
||||
T460 = 45,
|
||||
T470 = 46,
|
||||
T480 = 47,
|
||||
T490 = 48,
|
||||
T500 = 49,
|
||||
T510 = 50,
|
||||
T520 = 51,
|
||||
T530 = 52,
|
||||
T540 = 53,
|
||||
T550 = 54,
|
||||
T560 = 55,
|
||||
T570 = 56,
|
||||
T580 = 57,
|
||||
T590 = 58,
|
||||
T600 = 59,
|
||||
T610 = 60,
|
||||
T620 = 61,
|
||||
T630 = 62,
|
||||
T640 = 63,
|
||||
T650 = 64,
|
||||
T660 = 65,
|
||||
T670 = 66,
|
||||
T680 = 67,
|
||||
T690 = 68,
|
||||
T700 = 69,
|
||||
T710 = 70,
|
||||
T720 = 71,
|
||||
T730 = 72,
|
||||
T740 = 73,
|
||||
T750 = 74,
|
||||
T760 = 75,
|
||||
T770 = 76,
|
||||
T780 = 77,
|
||||
T790 = 78,
|
||||
T800 = 79,
|
||||
T810 = 80,
|
||||
T820 = 81,
|
||||
T830 = 82,
|
||||
T840 = 83,
|
||||
T850 = 84,
|
||||
T860 = 85,
|
||||
T870 = 86,
|
||||
T880 = 87,
|
||||
T890 = 88,
|
||||
T900 = 89,
|
||||
T910 = 90,
|
||||
T920 = 91,
|
||||
T930 = 92,
|
||||
T940 = 93,
|
||||
T950 = 94,
|
||||
T960 = 95,
|
||||
T970 = 96,
|
||||
T980 = 97,
|
||||
T990 = 98,
|
||||
T1000 = 99,
|
||||
T1010 = 100,
|
||||
T1020 = 101,
|
||||
T1030 = 102,
|
||||
T1040 = 103,
|
||||
T1050 = 104,
|
||||
T1060 = 105,
|
||||
T1070 = 106,
|
||||
T1080 = 107,
|
||||
T1090 = 108,
|
||||
T1100 = 109,
|
||||
T1110 = 110,
|
||||
T1120 = 111,
|
||||
T1130 = 112,
|
||||
T1140 = 113,
|
||||
T1150 = 114,
|
||||
T1160 = 115,
|
||||
T1170 = 116,
|
||||
T1180 = 117,
|
||||
T1190 = 118,
|
||||
T1200 = 119,
|
||||
T1210 = 120,
|
||||
T1220 = 121,
|
||||
T1230 = 122,
|
||||
T1240 = 123,
|
||||
T1250 = 124,
|
||||
T1260 = 125,
|
||||
T1270 = 126,
|
||||
T1280 = 127
|
||||
}
|
||||
|
||||
public const int MAX_PROCESS_NUM = 128;
|
||||
|
||||
public const int MAX_TOKEN_NUM = 128;
|
||||
|
||||
public static bool[,] m_bTokenUseState = new bool[MAX_PROCESS_NUM, MAX_TOKEN_NUM];
|
||||
|
||||
private static object objWait = new object();
|
||||
|
||||
public static int GET_MAX_PROCESS
|
||||
{
|
||||
get { return MAX_PROCESS_NUM; }
|
||||
}
|
||||
|
||||
public static void AllClearToken(Connect_Token thisToken)
|
||||
{
|
||||
lock (objWait)
|
||||
{
|
||||
for (int i = 0; i < MAX_TOKEN_NUM; i++)
|
||||
m_bTokenUseState[(int)thisToken, i] = false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool GetTokenPosState(Connect_Token thisToken, int iPos)
|
||||
{
|
||||
bool bValue = false;
|
||||
|
||||
if (iPos >= 0 && iPos < MAX_TOKEN_NUM)
|
||||
bValue = m_bTokenUseState[(int)thisToken, iPos];
|
||||
|
||||
return bValue;
|
||||
}
|
||||
|
||||
public static void SetTokenState(Connect_Token thisToken, bool bValue)
|
||||
{
|
||||
lock (objWait)
|
||||
{
|
||||
for (int i = 0; i < MAX_TOKEN_NUM; i++)
|
||||
{
|
||||
if (m_bTokenUseState[(int)thisToken, i] == !bValue)
|
||||
{
|
||||
m_bTokenUseState[(int)thisToken, i] = bValue;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//사용 불가능 true 가능 false
|
||||
public static bool GetTokenState(Connect_Token thisToken)
|
||||
{
|
||||
bool bUnused = true;
|
||||
|
||||
for (int i = 0; i < MAX_TOKEN_NUM; i++)
|
||||
{
|
||||
if (m_bTokenUseState[(int)thisToken, i] == false)
|
||||
{
|
||||
//사용 가능
|
||||
bUnused = false;
|
||||
|
||||
return bUnused;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//사용 불가능
|
||||
bUnused = true;
|
||||
|
||||
return bUnused;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SystemX.Net.Comm.IIS_FTP
|
||||
{
|
||||
public enum eFTPServiceStatus
|
||||
{
|
||||
None = 0,
|
||||
Unused,
|
||||
Connected,
|
||||
Disconnected
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,578 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SystemX.Net.Comm.IIS_FTP
|
||||
{
|
||||
public class CtrlFTP : ManagerInfoFTP
|
||||
{
|
||||
public CtrlFTP(bool bUseService, IPAddress SetIpAddress, int nSetPort, string strSetUserName, string strSetUserPassword)
|
||||
: base (bUseService, SetIpAddress, nSetPort, strSetUserName, strSetUserPassword)
|
||||
{
|
||||
/*
|
||||
"14.33.116.123", "2121"
|
||||
"ALISFTP", "Kefico!@34"
|
||||
*/
|
||||
|
||||
if (Connect())
|
||||
FTPConnState = true;
|
||||
else
|
||||
FTPConnState = false;
|
||||
|
||||
string strGetLastCommandState = LastestCommandDebugInformation();
|
||||
}
|
||||
|
||||
public override string GetLastestCommandStatusDescriptionText()
|
||||
{
|
||||
return LastestCommandStatusDescription;
|
||||
}
|
||||
|
||||
public override FtpStatusCode GetLastestCommandStatusCodeText()
|
||||
{
|
||||
return LastestCommandStatusCode;
|
||||
}
|
||||
|
||||
public override string GetLastestExceptionText()
|
||||
{
|
||||
return LastestCommandException.Message;
|
||||
}
|
||||
|
||||
public override Exception GetLastestException()
|
||||
{
|
||||
return LastestCommandException;
|
||||
}
|
||||
|
||||
public bool Connect()
|
||||
{
|
||||
LastestCommandException = null;
|
||||
|
||||
bool bCommandResult = true;
|
||||
|
||||
string url = string.Format(@"FTP://{0}:{1}/", UseInfo.InfoIPAddress.ToString(), UseInfo.InfoPort.ToString());
|
||||
|
||||
FtpWebRequest fwr = (FtpWebRequest)WebRequest.Create(url);
|
||||
fwr.KeepAlive = false;
|
||||
//fwr.UseBinary = true;
|
||||
fwr.UsePassive = true;
|
||||
|
||||
fwr.Method = WebRequestMethods.Ftp.ListDirectory;
|
||||
fwr.Credentials = new NetworkCredential(UseInfo.InfoUseUserAccount, UseInfo.InfoUseUserPassword);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
FtpWebResponse wr = null;
|
||||
try
|
||||
{
|
||||
using (wr = (FtpWebResponse)fwr.GetResponse())
|
||||
{
|
||||
LastestCommandStatusDescription = wr.StatusDescription;
|
||||
LastestCommandStatusCode = wr.StatusCode;
|
||||
}
|
||||
}
|
||||
catch(Exception FtpException)
|
||||
{
|
||||
bCommandResult = false;
|
||||
|
||||
LastestCommandException = FtpException;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if(wr != null)
|
||||
{
|
||||
wr.Close();
|
||||
wr = null;
|
||||
}
|
||||
}
|
||||
|
||||
return bCommandResult;
|
||||
}
|
||||
|
||||
private List<string> CheckList(StringBuilder sb, bool bFolderCheck = false, string strFolderPath = "")
|
||||
{
|
||||
List<string> lstInfo = new List<string>();
|
||||
string[] directorys = sb.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string strList in directorys)
|
||||
{
|
||||
string[] strGetItems = new string[4];
|
||||
|
||||
int[] nSplitPos = new int[3];
|
||||
string strCopyText = strList;
|
||||
for (int n = 0; n < 3; n++)
|
||||
{
|
||||
int nPos = strCopyText.IndexOf(' ');
|
||||
int nOriginPosition = nPos;
|
||||
int nCnt = 0;
|
||||
while (strCopyText[nPos] == ' ')
|
||||
{
|
||||
nPos++;
|
||||
nCnt++;
|
||||
}
|
||||
|
||||
string strTempText = strCopyText.Substring(0, nOriginPosition);
|
||||
strCopyText = strCopyText.Remove(0, nOriginPosition + nCnt);
|
||||
|
||||
strGetItems[n] = strTempText;
|
||||
}
|
||||
|
||||
strGetItems[3] = strCopyText;
|
||||
|
||||
//string[] strGetItems = strList.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
if (strGetItems.Length != 4)
|
||||
continue;
|
||||
if (bFolderCheck)
|
||||
{
|
||||
if (strGetItems[2] != "<DIR>")
|
||||
continue;
|
||||
|
||||
if (strFolderPath.Length == 0)
|
||||
lstInfo.Add(strGetItems[3]);
|
||||
else
|
||||
{
|
||||
if (strFolderPath.CompareTo(strGetItems[3]) == 0)
|
||||
{
|
||||
lstInfo.Add(strGetItems[3]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (strGetItems[2] == "<DIR>")
|
||||
continue;
|
||||
|
||||
DateTime dt = new DateTime();
|
||||
|
||||
if (DateTime.TryParse(strGetItems[0] + " " + strGetItems[1], CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.None, out dt))
|
||||
{
|
||||
TimeSpan ts = DateTime.Now - dt;
|
||||
|
||||
if (ts.TotalSeconds >= ManagerInfoFTP.dDiffScanCheckFileTime)
|
||||
lstInfo.Add(strGetItems[3]);
|
||||
|
||||
// TODO : FTP Download file list chekc limit 2048
|
||||
if (lstInfo.Count >= 2048)
|
||||
break;
|
||||
}
|
||||
else //Parsing failed!
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return lstInfo;
|
||||
}
|
||||
|
||||
public List<string> PositionRootCheckList(bool bFolderCheck = false, string strFolderPath = "")
|
||||
{
|
||||
LastestCommandException = null;
|
||||
|
||||
bool bCommandResult = true;
|
||||
|
||||
List<string> lstInfo = new List<string>();
|
||||
string url = string.Format(@"FTP://{0}:{1}/", UseInfo.InfoIPAddress.ToString(), UseInfo.InfoPort.ToString());
|
||||
|
||||
FtpWebRequest fwr = (FtpWebRequest)WebRequest.Create(url);
|
||||
fwr.KeepAlive = false;
|
||||
//fwr.UseBinary = true;
|
||||
fwr.UsePassive = true;
|
||||
|
||||
fwr.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
|
||||
fwr.Credentials = new NetworkCredential(UseInfo.InfoUseUserAccount, UseInfo.InfoUseUserPassword);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
FtpWebResponse wr = null;
|
||||
try
|
||||
{
|
||||
using (wr = (FtpWebResponse)fwr.GetResponse())
|
||||
{
|
||||
LastestCommandStatusDescription = wr.StatusDescription;
|
||||
LastestCommandStatusCode = wr.StatusCode;
|
||||
|
||||
StreamReader streamReader = new StreamReader(wr.GetResponseStream(), Encoding.Default);
|
||||
sb.Append(streamReader.ReadToEnd());
|
||||
}
|
||||
}
|
||||
catch (Exception FtpException)
|
||||
{
|
||||
LastestCommandException = FtpException;
|
||||
|
||||
bCommandResult = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (wr != null)
|
||||
{
|
||||
wr.Close();
|
||||
wr = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (bCommandResult)
|
||||
lstInfo = CheckList(sb, bFolderCheck, strFolderPath);
|
||||
|
||||
return lstInfo;
|
||||
}
|
||||
|
||||
public List<string> PositionSubCheckList(string strSubPath, bool bFolderCheck = false, string strFolderPath = "")
|
||||
{
|
||||
LastestCommandException = null;
|
||||
|
||||
bool bCommandResult = true;
|
||||
|
||||
List<string> lstInfo = new List<string>();
|
||||
string url = string.Format(@"FTP://{0}:{1}/" + strSubPath + @"/", UseInfo.InfoIPAddress.ToString(), UseInfo.InfoPort.ToString());
|
||||
|
||||
FtpWebRequest fwr = (FtpWebRequest)WebRequest.Create(url);
|
||||
fwr.KeepAlive = false;
|
||||
//fwr.UseBinary = true;
|
||||
fwr.UsePassive = true;
|
||||
|
||||
fwr.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
|
||||
fwr.Credentials = new NetworkCredential(UseInfo.InfoUseUserAccount, UseInfo.InfoUseUserPassword);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
FtpWebResponse wr = null;
|
||||
try
|
||||
{
|
||||
using (wr = (FtpWebResponse)fwr.GetResponse())
|
||||
{
|
||||
LastestCommandStatusDescription = wr.StatusDescription;
|
||||
LastestCommandStatusCode = wr.StatusCode;
|
||||
|
||||
StreamReader streamReader = new StreamReader(wr.GetResponseStream(), Encoding.Default);
|
||||
sb.Append(streamReader.ReadToEnd());
|
||||
}
|
||||
}
|
||||
catch (Exception FtpException)
|
||||
{
|
||||
LastestCommandException = FtpException;
|
||||
|
||||
bCommandResult = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (wr != null)
|
||||
{
|
||||
wr.Close();
|
||||
wr = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (bCommandResult)
|
||||
lstInfo = CheckList(sb, bFolderCheck, strFolderPath);
|
||||
|
||||
return lstInfo;
|
||||
}
|
||||
|
||||
public bool MakeDirectory(string strDirectoryPath)
|
||||
{
|
||||
LastestCommandException = null;
|
||||
|
||||
bool bCommandResult = true;
|
||||
|
||||
string url = string.Format(@"FTP://{0}:{1}/" + strDirectoryPath + @"/", UseInfo.InfoIPAddress.ToString(), UseInfo.InfoPort.ToString());
|
||||
|
||||
FtpWebRequest fwr = null;
|
||||
FtpWebResponse wr = null;
|
||||
|
||||
try
|
||||
{
|
||||
fwr = (FtpWebRequest)WebRequest.Create(url);
|
||||
fwr.KeepAlive = false;
|
||||
//fwr.UseBinary = true;
|
||||
fwr.UsePassive = true;
|
||||
|
||||
fwr.Method = WebRequestMethods.Ftp.MakeDirectory;
|
||||
fwr.Credentials = new NetworkCredential("ALISFTP", "Kefico!@34");
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
using (wr = (FtpWebResponse)fwr.GetResponse())
|
||||
{
|
||||
// FTP 결과 스트림
|
||||
LastestCommandStatusDescription = wr.StatusDescription;
|
||||
LastestCommandStatusCode = wr.StatusCode;
|
||||
|
||||
if (LastestCommandStatusCode != System.Net.FtpStatusCode.PathnameCreated)
|
||||
bCommandResult = false;
|
||||
}
|
||||
}
|
||||
catch (Exception FtpException)
|
||||
{
|
||||
LastestCommandException = FtpException;
|
||||
|
||||
bCommandResult = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (wr != null)
|
||||
{
|
||||
wr.Close();
|
||||
wr = null;
|
||||
}
|
||||
}
|
||||
|
||||
return bCommandResult;
|
||||
}
|
||||
|
||||
public bool FileExist(string strFileName)
|
||||
{
|
||||
LastestCommandException = null;
|
||||
|
||||
bool bCommandResult = true;
|
||||
|
||||
string url = string.Format(@"FTP://{0}:{1}/" + strFileName, UseInfo.InfoIPAddress.ToString(), UseInfo.InfoPort.ToString());
|
||||
|
||||
FtpWebRequest fwr = null;
|
||||
FtpWebResponse wr = null;
|
||||
|
||||
try
|
||||
{
|
||||
fwr = (FtpWebRequest)WebRequest.Create(url);
|
||||
fwr.KeepAlive = false;
|
||||
//fwr.UseBinary = true;
|
||||
fwr.UsePassive = true;
|
||||
fwr.Method = WebRequestMethods.Ftp.GetFileSize;
|
||||
fwr.Credentials = new NetworkCredential(UseInfo.InfoUseUserAccount, UseInfo.InfoUseUserPassword);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
using (wr = (FtpWebResponse)fwr.GetResponse())
|
||||
{
|
||||
LastestCommandStatusDescription = wr.StatusDescription;
|
||||
LastestCommandStatusCode = wr.StatusCode;
|
||||
|
||||
if (LastestCommandStatusCode == System.Net.FtpStatusCode.ActionNotTakenFileUnavailable)
|
||||
bCommandResult = false;
|
||||
}
|
||||
}
|
||||
catch (Exception FtpException)
|
||||
{
|
||||
LastestCommandException = FtpException;
|
||||
|
||||
bCommandResult = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (wr != null)
|
||||
{
|
||||
wr.Close();
|
||||
wr = null;
|
||||
}
|
||||
}
|
||||
|
||||
return bCommandResult;
|
||||
}
|
||||
|
||||
public bool DeleteFile(string strFileName)
|
||||
{
|
||||
LastestCommandException = null;
|
||||
|
||||
bool bCommandResult = true;
|
||||
|
||||
string url = string.Format(@"FTP://{0}:{1}/" + strFileName, UseInfo.InfoIPAddress.ToString(), UseInfo.InfoPort.ToString());
|
||||
|
||||
FtpWebRequest fwr = null;
|
||||
FtpWebResponse wr = null;
|
||||
|
||||
try
|
||||
{
|
||||
fwr = (FtpWebRequest)WebRequest.Create(url);
|
||||
fwr.KeepAlive = false;
|
||||
//fwr.UseBinary = true;
|
||||
fwr.UsePassive = true;
|
||||
fwr.Method = WebRequestMethods.Ftp.DeleteFile;
|
||||
fwr.Credentials = new NetworkCredential(UseInfo.InfoUseUserAccount, UseInfo.InfoUseUserPassword);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
using (wr = (FtpWebResponse)fwr.GetResponse())
|
||||
{
|
||||
LastestCommandStatusDescription = wr.StatusDescription;
|
||||
LastestCommandStatusCode = wr.StatusCode;
|
||||
|
||||
if (LastestCommandStatusCode != System.Net.FtpStatusCode.FileActionOK)
|
||||
bCommandResult = false;
|
||||
else
|
||||
{
|
||||
if (LastestCommandStatusDescription.IndexOf("DELE command successful") < 0)
|
||||
bCommandResult = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception FtpException)
|
||||
{
|
||||
LastestCommandException = FtpException;
|
||||
|
||||
bCommandResult = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (wr != null)
|
||||
{
|
||||
wr.Close();
|
||||
wr = null;
|
||||
}
|
||||
}
|
||||
|
||||
return bCommandResult;
|
||||
}
|
||||
|
||||
public bool FileUpload(string strFilePos)
|
||||
{
|
||||
string strFileName = Path.GetFileName(strFilePos);
|
||||
|
||||
string url = string.Format(@"FTP://{0}:{1}/" + strFileName, UseInfo.InfoIPAddress.ToString(), UseInfo.InfoPort.ToString());
|
||||
|
||||
LastestCommandException = null;
|
||||
|
||||
bool bCommandResult = true;
|
||||
|
||||
FtpWebRequest fwr = null;
|
||||
FtpWebResponse wr = null;
|
||||
|
||||
try
|
||||
{
|
||||
fwr = (FtpWebRequest)WebRequest.Create(url);
|
||||
fwr.KeepAlive = false;
|
||||
fwr.UseBinary = true;
|
||||
fwr.UsePassive = true;
|
||||
fwr.Method = WebRequestMethods.Ftp.UploadFile;
|
||||
fwr.Credentials = new NetworkCredential(UseInfo.InfoUseUserAccount, UseInfo.InfoUseUserPassword);
|
||||
|
||||
// 입력파일을 바이트 배열로 읽음
|
||||
byte[] ucReadData;
|
||||
using (FileStream reader = new FileStream(strFilePos, FileMode.Open, FileAccess.Read))
|
||||
{
|
||||
ucReadData = new byte[reader.Length];
|
||||
reader.Read(ucReadData, 0, (int)reader.Length);
|
||||
}
|
||||
|
||||
// RequestStream에 데이타를 쓴다
|
||||
fwr.ContentLength = ucReadData.Length;
|
||||
using (Stream reqStream = fwr.GetRequestStream())
|
||||
{
|
||||
reqStream.Write(ucReadData, 0, ucReadData.Length);
|
||||
}
|
||||
|
||||
// FTP Upload 실행
|
||||
using (wr = (FtpWebResponse)fwr.GetResponse())
|
||||
{
|
||||
// FTP 결과 상태 출력
|
||||
//Console.WriteLine("Upload: {0}", wr.StatusDescription);
|
||||
LastestCommandStatusDescription = wr.StatusDescription;
|
||||
LastestCommandStatusCode = wr.StatusCode;
|
||||
|
||||
if (LastestCommandStatusDescription.IndexOf("Transfer complete") >= 0)
|
||||
bCommandResult = true;
|
||||
}
|
||||
}
|
||||
catch (Exception FtpException)
|
||||
{
|
||||
LastestCommandException = FtpException;
|
||||
|
||||
bCommandResult = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (wr != null)
|
||||
{
|
||||
wr.Close();
|
||||
wr = null;
|
||||
}
|
||||
}
|
||||
|
||||
return bCommandResult;
|
||||
}
|
||||
|
||||
public async Task<string> FileDownload(string strDownloadFileName, string strCreateFilePath)
|
||||
{
|
||||
string url = string.Format(@"FTP://{0}:{1}/" + strDownloadFileName, UseInfo.InfoIPAddress.ToString(), UseInfo.InfoPort.ToString());
|
||||
|
||||
LastestCommandException = null;
|
||||
|
||||
bool bCommandResult = true;
|
||||
|
||||
FtpWebRequest fwr = null;
|
||||
FtpWebResponse wr = null;
|
||||
|
||||
try
|
||||
{
|
||||
fwr = (FtpWebRequest)WebRequest.Create(url);
|
||||
fwr.KeepAlive = false;
|
||||
fwr.UseBinary = true;
|
||||
fwr.UsePassive = true;
|
||||
fwr.Method = WebRequestMethods.Ftp.DownloadFile;
|
||||
fwr.Credentials = new NetworkCredential(UseInfo.InfoUseUserAccount, UseInfo.InfoUseUserPassword);
|
||||
|
||||
// FTP Request 결과를 가져온다.
|
||||
using (wr = (FtpWebResponse)fwr.GetResponseAsync().ConfigureAwait(false).GetAwaiter().GetResult())
|
||||
{
|
||||
// FTP 결과 스트림
|
||||
LastestCommandStatusDescription = wr.StatusDescription;
|
||||
LastestCommandStatusCode = wr.StatusCode;
|
||||
|
||||
Stopwatch stWaitTime = new Stopwatch();
|
||||
stWaitTime.Start();
|
||||
while (true)
|
||||
{
|
||||
LastestCommandStatusDescription = wr.StatusDescription;
|
||||
LastestCommandStatusCode = wr.StatusCode;
|
||||
|
||||
if (stWaitTime.ElapsedMilliseconds >= 10000)
|
||||
throw new Exception("Can't FtpStatusCode.DataAlreadyOpen|FtpStatusCode.ClosingData");
|
||||
|
||||
if (LastestCommandStatusCode == System.Net.FtpStatusCode.DataAlreadyOpen ||
|
||||
LastestCommandStatusCode == System.Net.FtpStatusCode.ClosingData)
|
||||
break;
|
||||
|
||||
await Task.Delay(0);
|
||||
}
|
||||
|
||||
Stream stream = wr.GetResponseStream();
|
||||
FileStream fileStream = new FileStream(strCreateFilePath + strDownloadFileName, FileMode.Create);
|
||||
|
||||
byte[] ucBuffer = new byte[4096];
|
||||
int nBytesRead;
|
||||
while (true)
|
||||
{
|
||||
nBytesRead = stream.Read(ucBuffer, 0, ucBuffer.Length);
|
||||
|
||||
if (nBytesRead == 0)
|
||||
break;
|
||||
|
||||
fileStream.Write(ucBuffer, 0, nBytesRead);
|
||||
}
|
||||
fileStream.Close();
|
||||
}
|
||||
}
|
||||
catch (Exception FtpException)
|
||||
{
|
||||
LastestCommandException = FtpException;
|
||||
|
||||
bCommandResult = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (wr != null)
|
||||
{
|
||||
wr.Close();
|
||||
wr = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (bCommandResult)
|
||||
return strCreateFilePath + strDownloadFileName;
|
||||
else
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,77 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SystemX.Net.Comm.IIS_FTP
|
||||
{
|
||||
public class ManagerInfoFTP
|
||||
{
|
||||
protected static double dDiffScanCheckFileTime = 60.0;
|
||||
|
||||
public sealed class ConnectFTPInformation
|
||||
{
|
||||
public bool UseFTPService { set; get; }
|
||||
|
||||
public IPAddress InfoIPAddress { set; get; }
|
||||
|
||||
public int InfoPort { set; get; }
|
||||
|
||||
public string InfoUseUserAccount { set; get; }
|
||||
|
||||
public string InfoUseUserPassword { set; get; }
|
||||
}
|
||||
|
||||
protected ConnectFTPInformation UseInfo { set; get; }
|
||||
|
||||
protected string LastestCommandStatusDescription { set; get; }
|
||||
protected FtpStatusCode LastestCommandStatusCode { set; get; }
|
||||
protected Exception LastestCommandException { set; get; }
|
||||
|
||||
public virtual string GetLastestCommandStatusDescriptionText()
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
public virtual FtpStatusCode GetLastestCommandStatusCodeText()
|
||||
{
|
||||
return FtpStatusCode.Undefined;
|
||||
}
|
||||
|
||||
public virtual string GetLastestExceptionText()
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
public virtual Exception GetLastestException()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public string LastestCommandDebugInformation()
|
||||
{
|
||||
string strMakeMessage = string.Format("{0}@{1}", LastestCommandStatusDescription, LastestCommandStatusCode.ToString());
|
||||
|
||||
if (LastestCommandException != null)
|
||||
strMakeMessage += "@" + LastestCommandException.Message;
|
||||
|
||||
return strMakeMessage;
|
||||
}
|
||||
|
||||
public ManagerInfoFTP(bool bUseService, IPAddress SetIpAddress, int nSetPort, string strSetUserName, string strSetUserPassword)
|
||||
{
|
||||
UseInfo = new ConnectFTPInformation();
|
||||
|
||||
UseInfo.UseFTPService = bUseService;
|
||||
|
||||
UseInfo.InfoIPAddress = SetIpAddress;
|
||||
UseInfo.InfoPort = nSetPort;
|
||||
UseInfo.InfoUseUserAccount = strSetUserName;
|
||||
UseInfo.InfoUseUserPassword = strSetUserPassword;
|
||||
}
|
||||
|
||||
public bool FTPConnState { set; get; }
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,271 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Xml;
|
||||
using SystemX.Common;
|
||||
using SystemX.Common.Serialization;
|
||||
using static SystemX.Net.DB.XDBConnManager;
|
||||
|
||||
namespace SystemX.Net.DB
|
||||
{
|
||||
public class CMainConnInfo
|
||||
{
|
||||
public string Type { get; set; }
|
||||
public string IP { get; set; }
|
||||
public string Port { get; set; }
|
||||
public string ID { get; set; }
|
||||
public string PW { get; set; }
|
||||
public string SCHEMA { get; set; }
|
||||
public string MAC_ADDR { get; set; }
|
||||
public string SSPI { get; set; }
|
||||
|
||||
public CMainConnInfo()
|
||||
{
|
||||
Type = string.Empty;
|
||||
IP = string.Empty;
|
||||
Port = string.Empty;
|
||||
ID = string.Empty;
|
||||
PW = string.Empty;
|
||||
SCHEMA = string.Empty;
|
||||
MAC_ADDR = string.Empty;
|
||||
SSPI = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public class CShortTermConnInfo
|
||||
{
|
||||
public string Type { get; set; }
|
||||
public string IP { get; set; }
|
||||
public string Port { get; set; }
|
||||
public string ID { get; set; }
|
||||
public string PW { get; set; }
|
||||
public string SCHEMA { get; set; }
|
||||
public string MAC_ADDR { get; set; }
|
||||
public string SSPI { get; set; }
|
||||
|
||||
public CShortTermConnInfo()
|
||||
{
|
||||
Type = string.Empty;
|
||||
IP = string.Empty;
|
||||
Port = string.Empty;
|
||||
ID = string.Empty;
|
||||
PW = string.Empty;
|
||||
SCHEMA = string.Empty;
|
||||
MAC_ADDR = string.Empty;
|
||||
SSPI = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class CLongTermConnInfo
|
||||
{
|
||||
public string Type { get; set; }
|
||||
public string IP { get; set; }
|
||||
public string Port { get; set; }
|
||||
public string ID { get; set; }
|
||||
public string PW { get; set; }
|
||||
public string SCHEMA { get; set; }
|
||||
public string MAC_ADDR { get; set; }
|
||||
public string SSPI { get; set; }
|
||||
|
||||
public CLongTermConnInfo()
|
||||
{
|
||||
Type = string.Empty;
|
||||
IP = string.Empty;
|
||||
Port = string.Empty;
|
||||
ID = string.Empty;
|
||||
PW = string.Empty;
|
||||
SCHEMA = string.Empty;
|
||||
MAC_ADDR = string.Empty;
|
||||
SSPI = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public class XDBConnInfo
|
||||
{
|
||||
public enum INFO_STRUCTURE
|
||||
{
|
||||
DBConnInfo,
|
||||
IP,
|
||||
Port,
|
||||
ID,
|
||||
PW,
|
||||
DB_CONN,
|
||||
MAC_ADDR,
|
||||
SSPI
|
||||
}
|
||||
|
||||
public CMainConnInfo ConnMain;
|
||||
|
||||
public CShortTermConnInfo ConnShortTerm;
|
||||
|
||||
public CLongTermConnInfo ConnLongTerm;
|
||||
|
||||
public XDBConnInfo()
|
||||
{
|
||||
ConnMain = new CMainConnInfo();
|
||||
ConnShortTerm = new CShortTermConnInfo();
|
||||
ConnLongTerm = new CLongTermConnInfo();
|
||||
}
|
||||
|
||||
public bool ReadConfig(string strPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.Read);
|
||||
|
||||
XmlDocument xmldoc = new XmlDocument();
|
||||
XmlNodeList nodeList;
|
||||
|
||||
Type InfoType = typeof(XDBConnInfo);
|
||||
|
||||
xmldoc.Load(fs);
|
||||
|
||||
nodeList = xmldoc.GetElementsByTagName(INFO_STRUCTURE.DBConnInfo.ToString());
|
||||
|
||||
XmlNode topNode = nodeList.Item(0);
|
||||
|
||||
foreach (XmlNode node in topNode.ChildNodes)
|
||||
{
|
||||
string strNodeName = node.Name;
|
||||
|
||||
if (strNodeName.CompareTo("MainConnInfo") == 0)
|
||||
{
|
||||
if (node.HasChildNodes == false)
|
||||
throw new Exception("[MainConnInfo] Has no entries.");
|
||||
if (node.ChildNodes.Count != 8)
|
||||
throw new Exception("[MainConnInfo] Entries do not match.");
|
||||
|
||||
ConnMain.Type = node.ChildNodes[0].InnerText;
|
||||
ConnMain.IP = node.ChildNodes[1].InnerText;
|
||||
ConnMain.Port = node.ChildNodes[2].InnerText;
|
||||
ConnMain.ID = node.ChildNodes[3].InnerText;
|
||||
ConnMain.PW = node.ChildNodes[4].InnerText;
|
||||
ConnMain.SCHEMA = node.ChildNodes[5].InnerText;
|
||||
ConnMain.MAC_ADDR = node.ChildNodes[6].InnerText;
|
||||
ConnMain.SSPI = node.ChildNodes[7].InnerText;
|
||||
}
|
||||
else if (strNodeName.CompareTo("ShortTermInfo") == 0)
|
||||
{
|
||||
if (node.HasChildNodes == false)
|
||||
throw new Exception("[ShortTermInfo] Has no entries.");
|
||||
if (node.ChildNodes.Count != 8)
|
||||
throw new Exception("[ShortTermInfo] Entries do not match.");
|
||||
|
||||
ConnShortTerm.Type = node.ChildNodes[0].InnerText;
|
||||
ConnShortTerm.IP = node.ChildNodes[1].InnerText;
|
||||
ConnShortTerm.Port = node.ChildNodes[2].InnerText;
|
||||
ConnShortTerm.ID = node.ChildNodes[3].InnerText;
|
||||
ConnShortTerm.PW = node.ChildNodes[4].InnerText;
|
||||
ConnShortTerm.SCHEMA = node.ChildNodes[5].InnerText;
|
||||
ConnShortTerm.MAC_ADDR = node.ChildNodes[6].InnerText;
|
||||
ConnShortTerm.SSPI = node.ChildNodes[7].InnerText;
|
||||
}
|
||||
else if(strNodeName.CompareTo("LongTermInfo") == 0)
|
||||
{
|
||||
if (node.HasChildNodes == false)
|
||||
throw new Exception("[LongTermInfo] Has no entries.");
|
||||
if (node.ChildNodes.Count != 8)
|
||||
throw new Exception("[LongTermInfo] Entries do not match.");
|
||||
|
||||
ConnLongTerm.Type = node.ChildNodes[0].InnerText;
|
||||
ConnLongTerm.IP = node.ChildNodes[1].InnerText;
|
||||
ConnLongTerm.Port = node.ChildNodes[2].InnerText;
|
||||
ConnLongTerm.ID = node.ChildNodes[3].InnerText;
|
||||
ConnLongTerm.PW = node.ChildNodes[4].InnerText;
|
||||
ConnLongTerm.SCHEMA = node.ChildNodes[5].InnerText;
|
||||
ConnLongTerm.MAC_ADDR = node.ChildNodes[6].InnerText;
|
||||
ConnLongTerm.SSPI = node.ChildNodes[7].InnerText;
|
||||
}
|
||||
/*
|
||||
else
|
||||
{
|
||||
PropertyInfo propFound = InfoType.GetProperty(strNodeName);
|
||||
|
||||
if (propFound != null)
|
||||
propFound.SetValue(this, node.InnerText);
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
fs.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"DB Connection Info. Reading Error : {ex.Message}");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public string GetConnectionStatement(eDbType eType, eConnCategory eConn)
|
||||
{
|
||||
string strStatement = string.Empty;
|
||||
|
||||
bool bSSPI = true;
|
||||
|
||||
string IP_ADDRESS = string.Empty;
|
||||
string PORT_NUMBER = string.Empty;
|
||||
string CONN_SCHEMA = string.Empty;
|
||||
string IDENTIFIER = string.Empty;
|
||||
string PASSWORD = string.Empty;
|
||||
|
||||
switch (eConn)
|
||||
{
|
||||
case eConnCategory.Main:
|
||||
{
|
||||
if (ConnMain.SSPI.IndexOf("False") >= 0) bSSPI = false;
|
||||
|
||||
IP_ADDRESS = ConnMain.IP;
|
||||
PORT_NUMBER = ConnMain.Port;
|
||||
CONN_SCHEMA = ConnMain.SCHEMA;
|
||||
IDENTIFIER = ConnMain.ID;
|
||||
PASSWORD = ConnMain.PW;
|
||||
}
|
||||
break;
|
||||
case eConnCategory.ShortTerm:
|
||||
{
|
||||
if (ConnShortTerm.SSPI.IndexOf("False") >= 0) bSSPI = false;
|
||||
|
||||
IP_ADDRESS = ConnShortTerm.IP;
|
||||
PORT_NUMBER = ConnShortTerm.Port;
|
||||
CONN_SCHEMA = ConnShortTerm.SCHEMA;
|
||||
IDENTIFIER = ConnShortTerm.ID;
|
||||
PASSWORD = ConnShortTerm.PW;
|
||||
}
|
||||
break;
|
||||
case eConnCategory.LongTerm:
|
||||
{
|
||||
if (ConnLongTerm.SSPI.IndexOf("False") >= 0) bSSPI = false;
|
||||
|
||||
IP_ADDRESS = ConnLongTerm.IP;
|
||||
PORT_NUMBER = ConnLongTerm.Port;
|
||||
CONN_SCHEMA = ConnLongTerm.SCHEMA;
|
||||
IDENTIFIER = ConnLongTerm.ID;
|
||||
PASSWORD = ConnLongTerm.PW;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
switch (eType)
|
||||
{
|
||||
case eDbType.MS_SQL:
|
||||
if (bSSPI == false)
|
||||
strStatement = $"Data Source = {IP_ADDRESS},{PORT_NUMBER}; Initial Catalog = {CONN_SCHEMA}; User ID = {IDENTIFIER}; Password = {PASSWORD}; MultipleActiveResultSets=True;";
|
||||
else
|
||||
strStatement = $"Data Source = localhost; Initial Catalog = {CONN_SCHEMA}; Integrated Security = SSPI; MultipleActiveResultSets=True;";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return strStatement;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,420 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Net.DB.DBType;
|
||||
using SystemX.Common;
|
||||
using SystemX.Common.Serialization;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using static SystemX.Net.Platform.Common.Util.LogMessage;
|
||||
using System.Diagnostics;
|
||||
using log4net.Config;
|
||||
|
||||
namespace SystemX.Net.DB
|
||||
{
|
||||
public class XDBConnManager
|
||||
{
|
||||
public enum eDbType
|
||||
{
|
||||
Unknown,
|
||||
MS_SQL
|
||||
}
|
||||
|
||||
public enum eConnCategory
|
||||
{
|
||||
Main,
|
||||
ShortTerm,
|
||||
LongTerm
|
||||
}
|
||||
|
||||
private Stopwatch stMainDBAccessTime;
|
||||
|
||||
private Stopwatch stShortTermDBAccessTime;
|
||||
|
||||
private Stopwatch stLongTermDBAccessTime;
|
||||
|
||||
private bool MAIN_CONNECT_STATE { set; get; }
|
||||
|
||||
private bool SHORTTERM_CONNECT_STATE { set; get; }
|
||||
|
||||
private bool LONGTERM_CONNECT_STATE { set; get; }
|
||||
|
||||
public bool CONNECT_STATE
|
||||
{
|
||||
get { return MAIN_CONNECT_STATE && SHORTTERM_CONNECT_STATE && LONGTERM_CONNECT_STATE; }
|
||||
}
|
||||
|
||||
protected void SET_CONNECT_STATE(eConnCategory eConn, bool bValue)
|
||||
{
|
||||
switch (eConn)
|
||||
{
|
||||
case eConnCategory.Main:
|
||||
MAIN_CONNECT_STATE = bValue;
|
||||
break;
|
||||
case eConnCategory.ShortTerm:
|
||||
SHORTTERM_CONNECT_STATE = bValue;
|
||||
break;
|
||||
case eConnCategory.LongTerm:
|
||||
LONGTERM_CONNECT_STATE = bValue;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
protected bool GET_CONNECT_STATE(eConnCategory eConn)
|
||||
{
|
||||
switch (eConn)
|
||||
{
|
||||
case eConnCategory.Main:
|
||||
return MAIN_CONNECT_STATE;
|
||||
case eConnCategory.ShortTerm:
|
||||
return SHORTTERM_CONNECT_STATE;
|
||||
case eConnCategory.LongTerm:
|
||||
return LONGTERM_CONNECT_STATE;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public string ConfigPath { get; set; }
|
||||
|
||||
public XDBConnInfo InfoConnection { get; set; } = new XDBConnInfo();
|
||||
|
||||
private IDBControl MgrMainConnection { set; get; }
|
||||
|
||||
private IDBControl MgrShortTermConnection { set; get; }
|
||||
|
||||
private IDBControl MgrLongTermConnection { set; get; }
|
||||
|
||||
public XDBConnManager()
|
||||
{
|
||||
stMainDBAccessTime = new Stopwatch();
|
||||
stMainDBAccessTime.Start();
|
||||
|
||||
stShortTermDBAccessTime = new Stopwatch();
|
||||
stShortTermDBAccessTime.Start();
|
||||
|
||||
stLongTermDBAccessTime = new Stopwatch();
|
||||
stLongTermDBAccessTime.Start();
|
||||
|
||||
MAIN_CONNECT_STATE = false;
|
||||
SHORTTERM_CONNECT_STATE = false;
|
||||
LONGTERM_CONNECT_STATE = false;
|
||||
}
|
||||
|
||||
public long GetMainDBAccessTime()
|
||||
{
|
||||
if (stMainDBAccessTime != null)
|
||||
return stMainDBAccessTime.ElapsedMilliseconds;
|
||||
else
|
||||
return long.MinValue;
|
||||
}
|
||||
|
||||
public void SetMainDBAccessTime()
|
||||
{
|
||||
if (stMainDBAccessTime != null)
|
||||
stMainDBAccessTime.Restart();
|
||||
}
|
||||
|
||||
public long GetShortTermDBAccessTime()
|
||||
{
|
||||
if (stShortTermDBAccessTime != null)
|
||||
return stShortTermDBAccessTime.ElapsedMilliseconds;
|
||||
else
|
||||
return long.MinValue;
|
||||
}
|
||||
|
||||
public void SetShortTermDBAccessTime()
|
||||
{
|
||||
if (stShortTermDBAccessTime != null)
|
||||
stShortTermDBAccessTime.Restart();
|
||||
}
|
||||
|
||||
public long GetLongTermDBAccessTime()
|
||||
{
|
||||
if (stLongTermDBAccessTime != null)
|
||||
return stLongTermDBAccessTime.ElapsedMilliseconds;
|
||||
else
|
||||
return long.MinValue;
|
||||
}
|
||||
|
||||
public void SetLongTermDBAccessTime()
|
||||
{
|
||||
if (stLongTermDBAccessTime != null)
|
||||
stLongTermDBAccessTime.Restart();
|
||||
}
|
||||
|
||||
public IDBControl CurrentConnection(eConnCategory eConn)
|
||||
{
|
||||
if (GET_CONNECT_STATE(eConn))
|
||||
{
|
||||
switch (eConn)
|
||||
{
|
||||
case eConnCategory.Main:
|
||||
{
|
||||
if (stMainDBAccessTime != null)
|
||||
stMainDBAccessTime.Restart();
|
||||
}
|
||||
return MgrMainConnection;
|
||||
case eConnCategory.ShortTerm:
|
||||
{
|
||||
if (stShortTermDBAccessTime != null)
|
||||
stShortTermDBAccessTime.Restart();
|
||||
}
|
||||
return MgrShortTermConnection;
|
||||
case eConnCategory.LongTerm:
|
||||
{
|
||||
if (stLongTermDBAccessTime != null)
|
||||
stLongTermDBAccessTime.Restart();
|
||||
}
|
||||
return MgrLongTermConnection;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
private bool ReadyForConnection(eConnCategory eConn)
|
||||
{
|
||||
bool bResult = true;
|
||||
|
||||
try
|
||||
{
|
||||
string strSetType = string.Empty;
|
||||
|
||||
eDbType eType = eDbType.Unknown;
|
||||
|
||||
switch (eConn)
|
||||
{
|
||||
case eConnCategory.Main:
|
||||
strSetType = InfoConnection.ConnMain.Type;
|
||||
break;
|
||||
case eConnCategory.ShortTerm:
|
||||
strSetType = InfoConnection.ConnShortTerm.Type;
|
||||
break;
|
||||
case eConnCategory.LongTerm:
|
||||
strSetType = InfoConnection.ConnLongTerm.Type;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!Enum.TryParse(strSetType, out eType))
|
||||
throw new Exception("Failed Database type check.");
|
||||
|
||||
switch (eConn)
|
||||
{
|
||||
case eConnCategory.Main:
|
||||
MgrMainConnection = CreateDBConnMgr(eType);
|
||||
MgrMainConnection.ConnectionText = InfoConnection.GetConnectionStatement(eType, eConn);
|
||||
break;
|
||||
case eConnCategory.ShortTerm:
|
||||
MgrShortTermConnection = CreateDBConnMgr(eType);
|
||||
MgrShortTermConnection.ConnectionText = InfoConnection.GetConnectionStatement(eType, eConn);
|
||||
break;
|
||||
case eConnCategory.LongTerm:
|
||||
MgrLongTermConnection = CreateDBConnMgr(eType);
|
||||
MgrLongTermConnection.ConnectionText = InfoConnection.GetConnectionStatement(eType, eConn);
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bResult = false;
|
||||
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"Failed make connection.[SystemX.Net.DB : XDBConnManager.MakeConnection]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
return bResult;
|
||||
}
|
||||
|
||||
private bool MakeConnection(eConnCategory eConn)
|
||||
{
|
||||
bool bResult = true;
|
||||
|
||||
try
|
||||
{
|
||||
bResult = ReadyForConnection(eConn);
|
||||
|
||||
if(bResult)
|
||||
{
|
||||
switch (eConn)
|
||||
{
|
||||
case eConnCategory.Main:
|
||||
if (!MgrMainConnection.OpenConnection())
|
||||
throw new Exception("Failed [Main] IDBControl.OpenConnection()");
|
||||
break;
|
||||
case eConnCategory.ShortTerm:
|
||||
if (!MgrShortTermConnection.OpenConnection())
|
||||
throw new Exception("Failed [ShortTerm] IDBControl.OpenConnection()");
|
||||
break;
|
||||
case eConnCategory.LongTerm:
|
||||
if (!MgrLongTermConnection.OpenConnection())
|
||||
throw new Exception("Failed [LongTerm] IDBControl.OpenConnection()");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bResult = false;
|
||||
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"Failed make connection.[SystemX.Net.DB : XDBConnManager.MakeConnection]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
return bResult;
|
||||
}
|
||||
|
||||
|
||||
private bool MakeConnection(eConnCategory eConn, bool bUseHostInfo, string strHostTableName, string strUserTableName)
|
||||
{
|
||||
bool bResult = true;
|
||||
|
||||
try
|
||||
{
|
||||
bResult = ReadyForConnection(eConn);
|
||||
|
||||
if (bResult)
|
||||
{
|
||||
switch (eConn)
|
||||
{
|
||||
case eConnCategory.Main:
|
||||
if (!MgrMainConnection.OpenConnection(bUseHostInfo, strHostTableName, strUserTableName))
|
||||
throw new Exception("Failed [Main] IDBControl.OpenConnection()");
|
||||
break;
|
||||
case eConnCategory.ShortTerm:
|
||||
if (!MgrShortTermConnection.OpenConnection(bUseHostInfo, strHostTableName, strUserTableName))
|
||||
throw new Exception("Failed [ShortTerm] IDBControl.OpenConnection()");
|
||||
break;
|
||||
case eConnCategory.LongTerm:
|
||||
if (!MgrLongTermConnection.OpenConnection(bUseHostInfo, strHostTableName, strUserTableName))
|
||||
throw new Exception("Failed [LongTerm] IDBControl.OpenConnection()");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bResult = false;
|
||||
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"Failed make connection.[SystemX.Net.DB : XDBConnManager.MakeConnection]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
return bResult;
|
||||
}
|
||||
|
||||
public bool OpenConnection(bool bReadCfgFile = true)
|
||||
{
|
||||
return CONNECT_STATE;
|
||||
}
|
||||
public bool OpenConnection(bool bUseHostInfo, string strHostTableName, string strUserTableName, bool bReadCfgFile = true)
|
||||
{
|
||||
SET_CONNECT_STATE(eConnCategory.Main, true);
|
||||
SET_CONNECT_STATE(eConnCategory.ShortTerm, true);
|
||||
SET_CONNECT_STATE(eConnCategory.LongTerm, true);
|
||||
|
||||
try
|
||||
{
|
||||
if (bReadCfgFile)
|
||||
{
|
||||
if (InfoConnection.ReadConfig(ConfigPath) == false)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"Fail read DB info file.[SystemX.Net.DB : XDBConnManager.OpenConnection]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
|
||||
throw new Exception("Failed ReadConfig()");
|
||||
}
|
||||
}
|
||||
|
||||
SET_CONNECT_STATE(eConnCategory.Main, MakeConnection(eConnCategory.Main, bUseHostInfo, strHostTableName, strUserTableName));
|
||||
SET_CONNECT_STATE(eConnCategory.ShortTerm, MakeConnection(eConnCategory.ShortTerm));
|
||||
SET_CONNECT_STATE(eConnCategory.LongTerm, MakeConnection(eConnCategory.LongTerm));
|
||||
|
||||
if (GET_CONNECT_STATE(eConnCategory.Main) == false ||
|
||||
GET_CONNECT_STATE(eConnCategory.ShortTerm) == false ||
|
||||
GET_CONNECT_STATE(eConnCategory.LongTerm) == false)
|
||||
throw new Exception();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"Fail db connect.[SystemX.Net.DB : XDBConnManager.OpenConnection - Parameter Type]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
return CONNECT_STATE;
|
||||
}
|
||||
|
||||
IDBControl CreateDBConnMgr(eDbType eType)
|
||||
{
|
||||
switch (eType)
|
||||
{
|
||||
case eDbType.MS_SQL:
|
||||
return new XDBTMSSQL();
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public SqlDataReader QueryDatabase(eConnCategory eConn, string strStmt)
|
||||
{
|
||||
IDBControl ctrlDB = null;
|
||||
|
||||
switch (eConn)
|
||||
{
|
||||
case eConnCategory.Main:
|
||||
ctrlDB = MgrMainConnection;
|
||||
break;
|
||||
case eConnCategory.ShortTerm:
|
||||
ctrlDB = MgrShortTermConnection;
|
||||
break;
|
||||
case eConnCategory.LongTerm:
|
||||
ctrlDB = MgrLongTermConnection;
|
||||
break;
|
||||
}
|
||||
|
||||
SqlDataReader drResult = ctrlDB.QueryDatabase(strStmt);
|
||||
|
||||
return drResult;
|
||||
}
|
||||
public DataTable QueryDatabaseInTable(eConnCategory eConn, string strStmt)
|
||||
{
|
||||
IDBControl ctrlDB = null;
|
||||
|
||||
switch (eConn)
|
||||
{
|
||||
case eConnCategory.Main:
|
||||
ctrlDB = MgrMainConnection;
|
||||
break;
|
||||
case eConnCategory.ShortTerm:
|
||||
ctrlDB = MgrShortTermConnection;
|
||||
break;
|
||||
case eConnCategory.LongTerm:
|
||||
ctrlDB = MgrLongTermConnection;
|
||||
break;
|
||||
}
|
||||
|
||||
DataTable dtResult = ctrlDB.QueryDataTable(strStmt);
|
||||
|
||||
return dtResult;
|
||||
}
|
||||
public DataSet QueryDatabaseInSet(eConnCategory eConn, string strStmt)
|
||||
{
|
||||
IDBControl ctrlDB = null;
|
||||
|
||||
switch (eConn)
|
||||
{
|
||||
case eConnCategory.Main:
|
||||
ctrlDB = MgrMainConnection;
|
||||
break;
|
||||
case eConnCategory.ShortTerm:
|
||||
ctrlDB = MgrShortTermConnection;
|
||||
break;
|
||||
case eConnCategory.LongTerm:
|
||||
ctrlDB = MgrLongTermConnection;
|
||||
break;
|
||||
}
|
||||
|
||||
DataSet dsResult = ctrlDB.QueryDataSet(strStmt);
|
||||
|
||||
return dsResult;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,447 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Common;
|
||||
using SystemX.Common.Serialization;
|
||||
using static SystemX.Net.Platform.Common.Util.LogMessage;
|
||||
|
||||
namespace SystemX.Net.DB.DBType
|
||||
{
|
||||
public partial class XDBTMSSQL : IDBControl, IDisposable
|
||||
{
|
||||
public bool ExecuteNonQuery(SqlCommand cmd)
|
||||
{
|
||||
bool bStatus = true;
|
||||
int iRecordsAffected = 0;
|
||||
|
||||
if (cmd == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
if (cmd.Connection == null)
|
||||
cmd.Connection = dbConnection;
|
||||
|
||||
iRecordsAffected = cmd.ExecuteNonQuery();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
|
||||
iRecordsAffected = 0;
|
||||
|
||||
bStatus = false;
|
||||
|
||||
string strErrorMsg = e.Message;
|
||||
string strSetData = DateTime.Now.ToString("yyyy -MM-dd HH:mm:ss>>");
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Message [" + strErrorMsg + "] ExecuteNonQuery command failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Command [" + cmd.CommandText + "] ExecuteNonQuery command failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
if (iRecordsAffected > 0)
|
||||
bStatus = true;
|
||||
else
|
||||
bStatus = false;
|
||||
|
||||
return bStatus;
|
||||
}
|
||||
|
||||
public bool ExecuteNonCommandQuery(SqlCommand cmd)
|
||||
{
|
||||
bool bStatus = true;
|
||||
int iRecordsAffected = 0;
|
||||
|
||||
if (cmd == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
if (cmd.Connection == null)
|
||||
cmd.Connection = dbConnection;
|
||||
|
||||
iRecordsAffected = cmd.ExecuteNonQuery();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
string strErrorMsg = e.Message;
|
||||
|
||||
iRecordsAffected = 0;
|
||||
|
||||
bStatus = false;
|
||||
|
||||
string strSetData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>");
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Message [" + strErrorMsg + "] ExecuteNonQuery command failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Command [" + cmd.CommandText + "] ExecuteNonQuery command failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
if (iRecordsAffected > 0)
|
||||
bStatus = true;
|
||||
else
|
||||
bStatus = false;
|
||||
|
||||
return bStatus;
|
||||
}
|
||||
|
||||
public bool ExecuteNonStreamQuery(SqlCommand cmd)
|
||||
{
|
||||
bool bStatus = true;
|
||||
int iRecordsAffected = 0;
|
||||
|
||||
if (cmd == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
if (cmd.Connection == null)
|
||||
cmd.Connection = dbConnection;
|
||||
|
||||
iRecordsAffected = cmd.ExecuteNonQuery();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
string strErrorMsg = e.Message;
|
||||
|
||||
iRecordsAffected = 0;
|
||||
|
||||
bStatus = false;
|
||||
|
||||
string strSetData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>");
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Message [" + strErrorMsg + "] ExecuteNonQuery command failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Command [" + cmd.CommandText + "] ExecuteNonQuery command failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
if (iRecordsAffected > 0)
|
||||
bStatus = true;
|
||||
else
|
||||
bStatus = false;
|
||||
|
||||
return bStatus;
|
||||
}
|
||||
|
||||
public SqlDataReader QueryDatabase(string strSQL)
|
||||
{
|
||||
bool bHasRow = false;
|
||||
int nCnt = 0;
|
||||
|
||||
SqlDataReader QueryReader = null;
|
||||
|
||||
try
|
||||
{
|
||||
using (var dbExcuteCommand = new SqlCommand(strSQL, dbConnection))
|
||||
{
|
||||
QueryReader = dbExcuteCommand.ExecuteReader();
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (QueryReader != null)
|
||||
QueryReader.Close();
|
||||
|
||||
QueryReader = null;
|
||||
|
||||
string strErrorMsg = e.Message;
|
||||
string strSetData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>");
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Message [" + strErrorMsg + "] QueryDatabase failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Command [" + strSQL + "] QueryDatabase failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (QueryReader != null)
|
||||
{
|
||||
bHasRow = QueryReader.HasRows;
|
||||
nCnt = QueryReader.RecordsAffected;
|
||||
}
|
||||
}
|
||||
|
||||
return QueryReader;
|
||||
}
|
||||
|
||||
public SqlDataReader QueryDatabaseSub(string strSQL)
|
||||
{
|
||||
bool bHasRow = false;
|
||||
int nCnt = 0;
|
||||
|
||||
SqlDataReader QueryReader = null;
|
||||
|
||||
try
|
||||
{
|
||||
using (var dbExcuteCommand = new SqlCommand(strSQL, dbConnection))
|
||||
{
|
||||
QueryReader = dbExcuteCommand.ExecuteReader();
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (QueryReader != null)
|
||||
QueryReader.Close();
|
||||
|
||||
QueryReader = null;
|
||||
|
||||
string strErrorMsg = e.Message;
|
||||
string strSetData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>");
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Message [" + strErrorMsg + "] QueryDatabaseSub failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Command [" + strSQL + "] QueryDatabaseSub failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (QueryReader != null)
|
||||
{
|
||||
bHasRow = QueryReader.HasRows;
|
||||
nCnt = QueryReader.RecordsAffected;
|
||||
}
|
||||
}
|
||||
|
||||
return QueryReader;
|
||||
}
|
||||
|
||||
public SqlDataReader QueryStreamDatabase(string strSQL)
|
||||
{
|
||||
bool bHasRow = false;
|
||||
int nCnt = 0;
|
||||
|
||||
SqlDataReader QueryReader = null;
|
||||
|
||||
try
|
||||
{
|
||||
using (var dbExcuteCommand = new SqlCommand(strSQL, dbConnection))
|
||||
{
|
||||
QueryReader = dbExcuteCommand.ExecuteReader();
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (QueryReader != null)
|
||||
QueryReader.Close();
|
||||
|
||||
QueryReader = null;
|
||||
|
||||
string strErrorMsg = e.Message;
|
||||
string strSetData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>");
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Message [" + strErrorMsg + "] QueryStreamDatabase failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Command [" + strSQL + "] QueryStreamDatabase failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (QueryReader != null)
|
||||
{
|
||||
bHasRow = QueryReader.HasRows;
|
||||
nCnt = QueryReader.RecordsAffected;
|
||||
}
|
||||
}
|
||||
|
||||
return QueryReader;
|
||||
}
|
||||
|
||||
public SqlDataReader QueryCommandDatabase(string strSQL, bool bUseTransaction = false)
|
||||
{
|
||||
bool bHasRow = false;
|
||||
int nCnt = 0;
|
||||
|
||||
SqlDataReader QueryReader = null;
|
||||
|
||||
try
|
||||
{
|
||||
if (bUseTransaction)
|
||||
{
|
||||
// Start a local transaction.
|
||||
SqlTransaction sqlTran = dbConnection.BeginTransaction();
|
||||
|
||||
// Enlist a command in the current transaction.
|
||||
SqlCommand command = dbConnection.CreateCommand();
|
||||
command.Transaction = sqlTran;
|
||||
|
||||
try
|
||||
{
|
||||
// Execute two separate commands.
|
||||
command.CommandText = strSQL;
|
||||
QueryReader = command.ExecuteReader();
|
||||
|
||||
// Commit the transaction.
|
||||
sqlTran.Commit();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Handle the exception if the transaction fails to commit.
|
||||
string strErrorMsg = ex.Message;
|
||||
string strSetData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>");
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Message [" + strErrorMsg + "] QueryCommandDatabase Transaction failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Command [" + strSQL + "] QueryCommandDatabase Transaction failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
|
||||
try
|
||||
{
|
||||
// Attempt to roll back the transaction.
|
||||
sqlTran.Rollback();
|
||||
}
|
||||
catch (Exception exRollback)
|
||||
{
|
||||
// Throws an InvalidOperationException if the connection
|
||||
// is closed or the transaction has already been rolled
|
||||
// back on the server.
|
||||
strErrorMsg = exRollback.Message;
|
||||
strSetData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>");
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Message [" + strErrorMsg + "] QueryCommandDatabase Transaction-Rollback failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
using (var dbExcuteCommand = new SqlCommand(strSQL, dbConnection))
|
||||
{
|
||||
QueryReader = dbExcuteCommand.ExecuteReader();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (QueryReader != null)
|
||||
QueryReader.Close();
|
||||
|
||||
QueryReader = null;
|
||||
|
||||
string strErrorMsg = e.Message;
|
||||
string strSetData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>");
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Message [" + strErrorMsg + "] QueryCommandDatabase failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Command [" + strSQL + "] QueryCommandDatabase failed. [SystemX.Net.DB.DBType : XDBTMSSQL.ExecuteNonQuery]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (QueryReader != null)
|
||||
{
|
||||
bHasRow = QueryReader.HasRows;
|
||||
nCnt = QueryReader.RecordsAffected;
|
||||
}
|
||||
}
|
||||
|
||||
return QueryReader;
|
||||
}
|
||||
|
||||
public DataTable QueryDataTable(string strSQL)
|
||||
{
|
||||
SqlDataReader Sqldr = null;
|
||||
|
||||
try
|
||||
{
|
||||
Sqldr = QueryDatabase(strSQL);
|
||||
|
||||
queryDataTable = new DataTable();
|
||||
queryDataTable.Load(Sqldr);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
;//
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Sqldr != null)
|
||||
Sqldr.Close();
|
||||
}
|
||||
|
||||
return queryDataTable;
|
||||
|
||||
//return null;
|
||||
}
|
||||
|
||||
public DataTable QueryDataTable(string strSQL, out bool bHasRows)
|
||||
{
|
||||
bHasRows = false;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public DataTable QueryDataTable(string strSQL, out int iRecordsAffected)
|
||||
{
|
||||
iRecordsAffected = 0;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public DataTable QueryDataTable(string strSQL, out bool bHasRows, out int iRecordsAffected)
|
||||
{
|
||||
bHasRows = false;
|
||||
iRecordsAffected = 0;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public DataSet QueryDataSet(string strSQL)
|
||||
{
|
||||
SqlDataReader Sqldr = null;
|
||||
|
||||
try
|
||||
{
|
||||
Sqldr = QueryDatabase(strSQL);
|
||||
|
||||
queryDataTable = new DataTable();
|
||||
queryDataTable.Load(Sqldr);
|
||||
|
||||
queryDataSet = new DataSet();
|
||||
queryDataSet.Tables.Add(queryDataTable);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
;//
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Sqldr != null)
|
||||
Sqldr.Close();
|
||||
}
|
||||
|
||||
return queryDataSet;
|
||||
}
|
||||
|
||||
public DataSet QueryDataSet(string strSQL, out bool bHasRows)
|
||||
{
|
||||
bHasRows = false;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public DataSet QueryDataSet(string strSQL, out int iRecordsAffected)
|
||||
{
|
||||
iRecordsAffected = 0;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public DataSet QueryDataSet(string strSQL, out bool bHasRows, out int iRecordsAffected)
|
||||
{
|
||||
bHasRows = false;
|
||||
iRecordsAffected = 0;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/*
|
||||
public DataSet Query(string strSetCommand, out int iRecordsAffect)
|
||||
{
|
||||
iRecordsAffect = 0;
|
||||
|
||||
queryDataSet = null;
|
||||
|
||||
try
|
||||
{
|
||||
dbCommand.CommandText = strSetCommand;
|
||||
queryDataReader = dbCommand.ExecuteReader();
|
||||
|
||||
queryDataTable = new DataTable();
|
||||
queryDataTable.Load(queryDataReader);
|
||||
|
||||
queryDataSet = new DataSet();
|
||||
queryDataSet.Tables.Add(queryDataTable);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//throw new CommonQueryException("Execution failed for the statement.[SystemX.Net.DB : MSSQL|COMMON.Query]");
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General packet marshalling failed.[SystemX.Common : COMMON.GetHeaderProtocol]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
return queryDataSet;
|
||||
}
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,468 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Common;
|
||||
using SystemX.Common.Serialization;
|
||||
using static SystemX.Net.Platform.Common.Util.LogMessage;
|
||||
|
||||
namespace SystemX.Net.DB.DBType
|
||||
{
|
||||
public partial class XDBTMSSQL : IDBControl, IDisposable
|
||||
{
|
||||
private SqlConnection dbConnection;
|
||||
private SqlCommand dbCommand;
|
||||
private SqlDataReader queryDataReader;
|
||||
|
||||
private DataSet queryDataSet;
|
||||
private DataTable queryDataTable;
|
||||
|
||||
private byte[] ucCollectSerializationSchema;
|
||||
private XTableInfo XSchemaTables;
|
||||
|
||||
private DataTable HostList;
|
||||
private DataTable UserList;
|
||||
|
||||
public string ConnectionText { get; set; }
|
||||
|
||||
public bool IsConnected { get; set; }
|
||||
|
||||
private string strSetHostTableName;
|
||||
private string strSetUserTableName;
|
||||
|
||||
public byte[] GetCollectSerializationSchemaInfo()
|
||||
{
|
||||
return ucCollectSerializationSchema;
|
||||
}
|
||||
|
||||
public XTableInfo GetCollectSchemaInfo()
|
||||
{
|
||||
return XSchemaTables;
|
||||
}
|
||||
|
||||
public DataTable GetHostList(bool bDBQueryCheck = false)
|
||||
{
|
||||
if(bDBQueryCheck == false)
|
||||
return HostList;
|
||||
else
|
||||
{
|
||||
if (QueryHostList(strSetHostTableName))
|
||||
return HostList;
|
||||
else
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public DataTable GetUserList(bool bDBQueryCheck = false)
|
||||
{
|
||||
if (bDBQueryCheck == false)
|
||||
return UserList;
|
||||
else
|
||||
{
|
||||
if (QueryUserList(strSetUserTableName))
|
||||
return UserList;
|
||||
else
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public XDBTMSSQL()
|
||||
{
|
||||
HostList = null;
|
||||
}
|
||||
~XDBTMSSQL()
|
||||
{
|
||||
Dispose(false);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool bDisposing)
|
||||
{
|
||||
if (bDisposing)
|
||||
ChkCloseConnect();
|
||||
|
||||
// do releasing unmanaged resource (종결자가 없는 객체의 자원 해제)
|
||||
// i.e. close file handle of operating systems
|
||||
|
||||
// suppress calling of Finalizer
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
public bool InitConnection()
|
||||
{
|
||||
try
|
||||
{
|
||||
ChkCloseConnect();
|
||||
|
||||
dbConnection = null;
|
||||
dbCommand = null;
|
||||
queryDataReader = null;
|
||||
queryDataSet = null;
|
||||
queryDataTable = null;
|
||||
|
||||
IsConnected = false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"SystemX Database Initialization is Failed. Error: {ex.Message}");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public void ChkCloseConnect()
|
||||
{
|
||||
if (IsConnected)
|
||||
{
|
||||
if (dbConnection != null)
|
||||
{
|
||||
dbConnection.Close();
|
||||
dbConnection.Dispose();
|
||||
dbConnection = null;
|
||||
}
|
||||
|
||||
IsConnected = false;
|
||||
}
|
||||
}
|
||||
|
||||
public bool OpenConnection()
|
||||
{
|
||||
ChkCloseConnect();
|
||||
|
||||
try
|
||||
{
|
||||
dbCommand = new SqlCommand();
|
||||
dbConnection = new SqlConnection(ConnectionText);
|
||||
dbConnection.Open();
|
||||
|
||||
dbCommand.Connection = dbConnection;
|
||||
|
||||
if (CollectSchemaInfomation())
|
||||
IsConnected = true;
|
||||
else
|
||||
Console.WriteLine($"SystemX Database CollectSchemaInfomation() is Failed.");
|
||||
}
|
||||
catch (SqlException exsql)
|
||||
{
|
||||
Console.WriteLine($"SystemX Database Connection Open is Failed. Error: {exsql.Message}");
|
||||
|
||||
IsConnected = false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"SystemX Database Connection Open is Failed. Error: {ex.Message}");
|
||||
|
||||
IsConnected = false;
|
||||
}
|
||||
|
||||
return IsConnected;
|
||||
}
|
||||
public bool OpenConnection(bool bUseHostInfo, string strHostTableName, string strUserTableName)
|
||||
{
|
||||
ChkCloseConnect();
|
||||
|
||||
strSetHostTableName = string.Empty;
|
||||
strSetUserTableName = string.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
dbCommand = new SqlCommand();
|
||||
dbConnection = new SqlConnection(ConnectionText);
|
||||
dbConnection.Open();
|
||||
|
||||
dbCommand.Connection = dbConnection;
|
||||
|
||||
if (CollectSchemaInfomation())
|
||||
{
|
||||
if (bUseHostInfo)
|
||||
{
|
||||
strSetHostTableName = strHostTableName;
|
||||
strSetUserTableName = strUserTableName;
|
||||
|
||||
if (QueryHostList(strSetHostTableName) &&
|
||||
QueryUserList(strSetUserTableName))
|
||||
IsConnected = true;
|
||||
else
|
||||
Console.WriteLine($"SystemX Database QueryHostList() is Failed.");
|
||||
}
|
||||
else
|
||||
IsConnected = true;
|
||||
}
|
||||
else
|
||||
Console.WriteLine($"SystemX Database CollectSchemaInfomation() is Failed.");
|
||||
}
|
||||
catch (SqlException exsql)
|
||||
{
|
||||
Console.WriteLine($"SystemX Database Connection Open is Failed. Error: {exsql.Message}");
|
||||
|
||||
IsConnected = false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"SystemX Database Connection Open is Failed. Error: {ex.Message}");
|
||||
|
||||
IsConnected = false;
|
||||
}
|
||||
|
||||
return IsConnected;
|
||||
}
|
||||
|
||||
public bool CloseConnection()
|
||||
{
|
||||
try
|
||||
{
|
||||
ChkCloseConnect();
|
||||
}
|
||||
catch (SqlException exsql)
|
||||
{
|
||||
Console.WriteLine($"SystemX Database Connection Open is Failed. Error: {exsql.Message}");
|
||||
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"SystemX Database Connection Open is Failed. Error: {ex.Message}");
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public SqlConnection getConnection()
|
||||
{
|
||||
return dbConnection;
|
||||
}
|
||||
|
||||
public string MakeTableInfoQuery(string strTableName)
|
||||
{
|
||||
//--컬럼 정보 가져오기
|
||||
string strTableColInfoCommand = "SELECT A.TABLE_CATALOG" +
|
||||
",A.TABLE_NAME" +
|
||||
",A.ORDINAL_POSITION" +
|
||||
",A.COLUMN_NAME" +
|
||||
",A.DATA_TYPE" +
|
||||
",ISNULL(A.CHARACTER_MAXIMUM_LENGTH, '') CHARACTER_LENGTH" +
|
||||
",ISNULL(A.NUMERIC_PRECISION, '') NUMBERIC_LENGTH" +
|
||||
",A.IS_NULLABLE" +
|
||||
",ISNULL(A.COLUMN_DEFAULT, '')" +
|
||||
",ISNULL(B.CONSTRAINT_NAME, '')" +
|
||||
",ISNULL(A.CHARACTER_SET_NAME, '')" +
|
||||
",ISNULL(A.COLLATION_NAME, '')" +
|
||||
",CASE WHEN ISNULL(C.NAME, '') = '' THEN '' ELSE 'Identity' END AUTO" +
|
||||
" FROM INFORMATION_SCHEMA.COLUMNS A LEFT OUTER JOIN" +
|
||||
" INFORMATION_SCHEMA.KEY_COLUMN_USAGE B" +
|
||||
" ON A.TABLE_NAME = B.TABLE_NAME" +
|
||||
" AND A.COLUMN_NAME = B.COLUMN_NAME" +
|
||||
" LEFT OUTER JOIN" +
|
||||
" syscolumns C" +
|
||||
" ON C.ID = object_id(A.TABLE_NAME) AND A.COLUMN_NAME = C.NAME AND C.COLSTAT & 1 = 1 WHERE A.TABLE_NAME = " +
|
||||
"'" + strTableName + "'" +
|
||||
" ORDER BY A.ORDINAL_POSITION";
|
||||
|
||||
return strTableColInfoCommand;
|
||||
}
|
||||
|
||||
public bool CollectSchemaInfomation()
|
||||
{
|
||||
bool bInfoCollectResult = true;
|
||||
|
||||
try
|
||||
{
|
||||
dbCommand.CommandText = "SELECT * FROM INFORMATION_SCHEMA.TABLES A ORDER BY A.TABLE_NAME;";
|
||||
|
||||
queryDataReader = dbCommand.ExecuteReader();
|
||||
DataTable dtQueryTable = new DataTable();
|
||||
dtQueryTable.Load(queryDataReader);
|
||||
|
||||
List<string> listTableInfo = new List<string>();
|
||||
|
||||
if (dtQueryTable.Columns.Contains("TABLE_NAME"))
|
||||
{
|
||||
int iColPos = dtQueryTable.Columns.IndexOf("TABLE_NAME");
|
||||
|
||||
for (int i = 0; i < dtQueryTable.Columns[0].Table.Rows.Count; i++)
|
||||
{
|
||||
object[] objRows = dtQueryTable.Columns[0].Table.Rows[i].ItemArray;
|
||||
|
||||
string strGetTableName = objRows[iColPos] as string;
|
||||
|
||||
if (strGetTableName.IndexOf("sysdiagrams") < 0)
|
||||
listTableInfo.Add(objRows[iColPos] as string);
|
||||
}
|
||||
}
|
||||
|
||||
int iNamePos = 0, iTypePos = 0, iCharLengPos = 0, iNumLengPos = 0, iIsNullAblePos = 0, iAutoPos = 0;
|
||||
|
||||
int iPosition = 0;
|
||||
XTable[] listTable = new XTable[listTableInfo.Count];
|
||||
|
||||
foreach (string strTbName in listTableInfo)
|
||||
{
|
||||
dbCommand.CommandText = MakeTableInfoQuery(strTbName);
|
||||
queryDataReader = dbCommand.ExecuteReader();
|
||||
dtQueryTable = new DataTable();
|
||||
dtQueryTable.Load(queryDataReader);
|
||||
|
||||
if (dtQueryTable.Columns.Contains("COLUMN_NAME"))
|
||||
iNamePos = dtQueryTable.Columns.IndexOf("COLUMN_NAME");
|
||||
if (dtQueryTable.Columns.Contains("DATA_TYPE"))
|
||||
iTypePos = dtQueryTable.Columns.IndexOf("DATA_TYPE");
|
||||
if (dtQueryTable.Columns.Contains("CHARACTER_LENGTH"))
|
||||
iCharLengPos = dtQueryTable.Columns.IndexOf("CHARACTER_LENGTH");
|
||||
if (dtQueryTable.Columns.Contains("NUMBERIC_LENGTH"))
|
||||
iNumLengPos = dtQueryTable.Columns.IndexOf("NUMBERIC_LENGTH");
|
||||
if (dtQueryTable.Columns.Contains("IS_NULLABLE"))
|
||||
iIsNullAblePos = dtQueryTable.Columns.IndexOf("IS_NULLABLE");
|
||||
if (dtQueryTable.Columns.Contains("AUTO"))
|
||||
iAutoPos = dtQueryTable.Columns.IndexOf("AUTO");
|
||||
|
||||
listTable[iPosition] = new XTable(strTbName);
|
||||
for (int i = 0; i < dtQueryTable.Rows[0].Table.Rows.Count; i++)
|
||||
{
|
||||
object[] objRows = dtQueryTable.Columns[0].Table.Rows[i].ItemArray;
|
||||
|
||||
string strGetName = objRows[iNamePos] as string;
|
||||
string strGetTypeName = objRows[iTypePos] as string;
|
||||
int iGetTypeCharLeng = Convert.ToInt32(objRows[iCharLengPos]);
|
||||
int iGetTypeNumLeng = Convert.ToInt32(objRows[iNumLengPos]);
|
||||
string strGetNullState = objRows[iIsNullAblePos] as string;
|
||||
string strGetAuto = objRows[iAutoPos] as string;
|
||||
|
||||
bool bGetIsNullAble = false;
|
||||
|
||||
if (strGetNullState.IndexOf("YES") >= 0)
|
||||
bGetIsNullAble = true;
|
||||
else if (strGetNullState.IndexOf("NO") >= 0)
|
||||
bGetIsNullAble = false;
|
||||
|
||||
Type SetThisType = null;
|
||||
switch (strGetTypeName)
|
||||
{
|
||||
case "bit":
|
||||
//SET_CODE = TypeCode.Boolean;
|
||||
SetThisType = typeof(Boolean);
|
||||
break;
|
||||
case "tinyint":
|
||||
//SET_CODE = TypeCode.Int64;
|
||||
SetThisType = typeof(Byte);
|
||||
break;
|
||||
case "int":
|
||||
//SET_CODE = TypeCode.Int32;
|
||||
SetThisType = typeof(Int32);
|
||||
break;
|
||||
case "bigint":
|
||||
//SET_CODE = TypeCode.Int64;
|
||||
SetThisType = typeof(Int64);
|
||||
break;
|
||||
case "float":
|
||||
//SET_CODE = TypeCode.Double;
|
||||
SetThisType = typeof(Double);
|
||||
break;
|
||||
case "nvarchar":
|
||||
//SET_CODE = TypeCode.String;
|
||||
SetThisType = typeof(String);
|
||||
break;
|
||||
case "nchar":
|
||||
//SET_CODE = TypeCode.String;
|
||||
SetThisType = typeof(String);
|
||||
break;
|
||||
case "datetime":
|
||||
//SET_CODE = TypeCode.DateTime;
|
||||
SetThisType = typeof(DateTime);
|
||||
break;
|
||||
}
|
||||
|
||||
listTable[iPosition].XTableAdd(i, strGetName, SetThisType, iGetTypeCharLeng, bGetIsNullAble);
|
||||
}
|
||||
|
||||
iPosition++;
|
||||
}
|
||||
|
||||
XSchemaTables = new XTableInfo(listTable);
|
||||
|
||||
ucCollectSerializationSchema = SystemXNetSerialization.ObjectToByteArray(XSchemaTables);
|
||||
XTableInfo XTablesReturn = (XTableInfo)SystemXNetSerialization.ByteArrayToObject(ucCollectSerializationSchema);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bInfoCollectResult = false;
|
||||
|
||||
//throw new Exception("Collect Schema infomation fail!");
|
||||
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"Collect Schema infomation fail![SystemX.Net.DB.DBType : XDBTMSSQL.CollectSchemaInfomation]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (queryDataReader != null)
|
||||
queryDataReader.Close();
|
||||
}
|
||||
|
||||
return bInfoCollectResult;
|
||||
}
|
||||
public bool QueryHostList(string strTableName)
|
||||
{
|
||||
bool bReuslt = true;
|
||||
|
||||
try
|
||||
{
|
||||
dbCommand.CommandText = "SELECT * FROM " + $"{strTableName} WITH(NOLOCK) ORDER BY NO ASC;";
|
||||
|
||||
queryDataReader = dbCommand.ExecuteReader();
|
||||
HostList = new DataTable();
|
||||
HostList.Load(queryDataReader);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
HostList = null;
|
||||
|
||||
bReuslt = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (queryDataReader != null)
|
||||
queryDataReader.Close();
|
||||
}
|
||||
|
||||
return bReuslt;
|
||||
}
|
||||
|
||||
public bool QueryUserList(string strTableName)
|
||||
{
|
||||
bool bReuslt = true;
|
||||
|
||||
try
|
||||
{
|
||||
dbCommand.CommandText = "SELECT * FROM " + $"{strTableName} WITH(NOLOCK) ORDER BY NO ASC;";
|
||||
|
||||
queryDataReader = dbCommand.ExecuteReader();
|
||||
UserList = new DataTable();
|
||||
UserList.Load(queryDataReader);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
UserList = null;
|
||||
|
||||
bReuslt = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (queryDataReader != null)
|
||||
queryDataReader.Close();
|
||||
}
|
||||
|
||||
return bReuslt;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SystemX.Net.DB.DBType
|
||||
{
|
||||
public interface IDBControl
|
||||
{
|
||||
string ConnectionText { get; set; }
|
||||
bool IsConnected { get; set; }
|
||||
|
||||
bool InitConnection();
|
||||
bool OpenConnection();
|
||||
bool OpenConnection(bool bUseHostInfo, string strHostTableName, string strUserTableName);
|
||||
|
||||
bool CloseConnection();
|
||||
|
||||
SqlConnection getConnection();
|
||||
|
||||
string MakeTableInfoQuery(string strTableName);
|
||||
bool CollectSchemaInfomation();
|
||||
|
||||
byte[] GetCollectSerializationSchemaInfo();
|
||||
|
||||
XTableInfo GetCollectSchemaInfo();
|
||||
DataTable GetHostList(bool bDBQueryCheck = false);
|
||||
DataTable GetUserList(bool bDBQueryCheck = false);
|
||||
|
||||
bool ExecuteNonQuery(SqlCommand cmd);
|
||||
bool ExecuteNonCommandQuery(SqlCommand cmd);
|
||||
bool ExecuteNonStreamQuery(SqlCommand cmd);
|
||||
|
||||
SqlDataReader QueryDatabase(string strSQL);
|
||||
SqlDataReader QueryDatabaseSub(string strSQL);
|
||||
SqlDataReader QueryCommandDatabase(string strSQL, bool bUseTransaction = false);
|
||||
SqlDataReader QueryStreamDatabase(string strSQL);
|
||||
|
||||
DataTable QueryDataTable(string strSQL);
|
||||
DataTable QueryDataTable(string strSQL, out bool bHasRows);
|
||||
DataTable QueryDataTable(string strSQL, out int iRecordsAffected);
|
||||
DataTable QueryDataTable(string strSQL, out bool bHasRows, out int iRecordsAffected);
|
||||
DataSet QueryDataSet(string strSQL);
|
||||
DataSet QueryDataSet(string strSQL, out bool bHasRows);
|
||||
DataSet QueryDataSet(string strSQL, out int iRecordsAffected);
|
||||
DataSet QueryDataSet(string strSQL, out bool bHasRows, out int iRecordsAffected);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,112 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using static SystemX.Net.Platform.Common.Util.LogMessage;
|
||||
//using MySql.Data.MySqlClient;
|
||||
|
||||
namespace SystemX.Net.DB.DBType
|
||||
{
|
||||
public class MariaXDB
|
||||
{
|
||||
//private MySqlConnection sqlConnection;
|
||||
//private MySqlCommand sqlCommand;
|
||||
//private MySqlDataReader sqlDataReader;
|
||||
private DataSet sqlDataSet;
|
||||
private DataTable sqlDataTable;
|
||||
|
||||
private string m_strConnectionText;
|
||||
|
||||
private bool m_bConnect;
|
||||
|
||||
public bool CONNECT { get { return m_bConnect; } }
|
||||
|
||||
public MariaXDB(string strSetConnectionInfo)
|
||||
{
|
||||
//sqlConnection = null;
|
||||
//sqlCommand = null;
|
||||
//sqlDataReader = null;
|
||||
sqlDataSet = null;
|
||||
sqlDataTable = null;
|
||||
|
||||
m_strConnectionText = strSetConnectionInfo;
|
||||
|
||||
m_bConnect = false;
|
||||
}
|
||||
~MariaXDB()
|
||||
{
|
||||
ChkCloseConnect();
|
||||
}
|
||||
public void ChkCloseConnect()
|
||||
{
|
||||
if (m_bConnect)
|
||||
{
|
||||
m_bConnect = false;
|
||||
|
||||
/*
|
||||
if (sqlConnection != null)
|
||||
{
|
||||
sqlConnection.Close();
|
||||
sqlConnection.Dispose();
|
||||
sqlConnection = null;
|
||||
}
|
||||
*/
|
||||
}
|
||||
}
|
||||
public bool ConnectDatabase()
|
||||
{
|
||||
ChkCloseConnect();
|
||||
|
||||
try
|
||||
{
|
||||
//sqlConnection = new MySqlConnection(m_strConnectionText);
|
||||
//sqlCommand.Connection = sqlConnection;
|
||||
|
||||
m_bConnect = true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
m_bConnect = false;
|
||||
|
||||
string strErrorMsg = e.Message;
|
||||
string strSetData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>");
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Message [" + strErrorMsg + "] ConnectDatabase failed. [SystemX.Net.DB.DBType : MariaXDB.ConnectDatabase]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
return m_bConnect;
|
||||
}
|
||||
public DataSet Query(string strSetCommand, out int iRecordsAffect)
|
||||
{
|
||||
iRecordsAffect = 0;
|
||||
|
||||
sqlDataSet = null;
|
||||
|
||||
try
|
||||
{
|
||||
//sqlCommand.CommandText = strSetCommand;
|
||||
//sqlDataReader = sqlCommand.ExecuteReader();
|
||||
|
||||
//iRecordsAffect = sqlDataReader.RecordsAffected;
|
||||
|
||||
sqlDataTable = new DataTable();
|
||||
//sqlDataTable.Load(sqlDataReader);
|
||||
|
||||
sqlDataSet = new DataSet();
|
||||
sqlDataSet.Tables.Add(sqlDataTable);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
;// throw new XDBCommonQueryException("Execution failed for the statement.[SystemX.Net.DB : MariaDB|COMMON.Query]");
|
||||
|
||||
string strErrorMsg = e.Message;
|
||||
string strSetData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>");
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Message [" + strErrorMsg + "] Query failed. [SystemX.Net.DB.DBType : MariaXDB.Query]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
MessageOutput.ConsoleWrite(strSetData + @"! Command [" + strSetCommand + "] Query failed. [SystemX.Net.DB.DBType : MariaXDB.Query]", ConsoleColor.Red, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
return sqlDataSet;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,225 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Common;
|
||||
using SystemX.Common.Archive;
|
||||
using SystemX.Common.Serialization;
|
||||
using SystemX.Net.BaseProtocol;
|
||||
|
||||
namespace SystemX.Net.Schedule
|
||||
{
|
||||
public class ScheduleLabelManage
|
||||
{
|
||||
private byte ucLabelSize = 128;
|
||||
|
||||
// 해당 위치 토큰 사용 여부
|
||||
private bool[] bLabelUse;
|
||||
// 해당 위치 처리 여부
|
||||
private bool[] bLabelComplete;
|
||||
|
||||
private XData[] XLabelData;
|
||||
|
||||
public byte GetLabelSize()
|
||||
{
|
||||
return ucLabelSize;
|
||||
}
|
||||
|
||||
public void SetManageLabel()
|
||||
{
|
||||
bLabelUse = new bool[ucLabelSize];
|
||||
bLabelComplete = new bool[ucLabelSize];
|
||||
|
||||
XLabelData = new XData[ucLabelSize];
|
||||
|
||||
bLabelUse.ToArray().Initialize();
|
||||
bLabelComplete.ToArray().Initialize();
|
||||
}
|
||||
|
||||
public byte GetLabel(int nLabelPos = -1)
|
||||
{
|
||||
byte ucLabelPos = 0;
|
||||
|
||||
if (nLabelPos == -1)
|
||||
{
|
||||
for (int i = 1; i < ucLabelSize - 1; i++)
|
||||
{
|
||||
if (bLabelUse[i] == false)
|
||||
{
|
||||
ucLabelPos = (byte)i;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
ucLabelPos = (byte)nLabelPos;
|
||||
|
||||
if (ucLabelPos != 0)
|
||||
{
|
||||
bLabelComplete[ucLabelPos] = false;
|
||||
bLabelUse[ucLabelPos] = true;
|
||||
}
|
||||
|
||||
return ucLabelPos;
|
||||
}
|
||||
|
||||
public bool SetLabel(byte ucCheckLabelPos, XData setXLabelData)
|
||||
{
|
||||
if (ucCheckLabelPos < 0 || ucCheckLabelPos >= ucLabelSize)
|
||||
return false;
|
||||
|
||||
if (bLabelUse[ucCheckLabelPos])
|
||||
{
|
||||
XLabelData[ucCheckLabelPos] = setXLabelData;
|
||||
|
||||
bLabelComplete[ucCheckLabelPos] = true;
|
||||
}
|
||||
|
||||
return bLabelComplete[ucCheckLabelPos];
|
||||
}
|
||||
|
||||
public bool ClearLabel(byte ucCheckLabelPos)
|
||||
{
|
||||
if (ucCheckLabelPos < 0 || ucCheckLabelPos >= ucLabelSize)
|
||||
return false;
|
||||
|
||||
if (bLabelUse[ucCheckLabelPos])
|
||||
{
|
||||
bLabelUse[ucCheckLabelPos] = false;
|
||||
|
||||
bLabelComplete[ucCheckLabelPos] = false;
|
||||
}
|
||||
|
||||
return bLabelUse[ucCheckLabelPos];
|
||||
}
|
||||
|
||||
public XData CheckLabel(byte ucCheckLabelPos, ref bool bLabelProcessResult)
|
||||
{
|
||||
if (ucCheckLabelPos < 0 || ucCheckLabelPos >= ucLabelSize)
|
||||
return null;
|
||||
|
||||
if (bLabelComplete[ucCheckLabelPos])
|
||||
{
|
||||
bLabelComplete[ucCheckLabelPos] = false;
|
||||
bLabelUse[ucCheckLabelPos] = false;
|
||||
|
||||
bLabelProcessResult = true;
|
||||
|
||||
return XLabelData[ucCheckLabelPos];
|
||||
}
|
||||
else
|
||||
{
|
||||
bLabelProcessResult = false;
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Packet Time, Retrty Num, Replay Packet, Packet Data, Packet Event, Label
|
||||
/// </summary>
|
||||
|
||||
/// <summary>
|
||||
/// Data Time, Data Replay Result, Packet Protocol Info, Packet Header Info, Result Data Object, Label
|
||||
/// </summary>
|
||||
public class XPacket
|
||||
{
|
||||
public DateTime dtPacketTime;
|
||||
public int iRetryNum;
|
||||
public bool bReplayPacket;
|
||||
public byte[] ucPacketBytes;
|
||||
public SendRecvCallEvent deleCallEvt;
|
||||
public byte nLabel;
|
||||
}
|
||||
public class XData
|
||||
{
|
||||
public DateTime dtTime;
|
||||
public bool bReplayResult;
|
||||
public BASE_PROTOCOL BaseProtocol;
|
||||
public HEADER_PACKET HeaderPacket;
|
||||
public object objData;
|
||||
public byte nLabel;
|
||||
}
|
||||
|
||||
public enum FlowControlType
|
||||
{
|
||||
Commnad = 0,
|
||||
Stream,
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class XDataSchedule
|
||||
{
|
||||
public List<byte[]> SendQueue;
|
||||
public List<byte[]> ReplySendQueue;
|
||||
public List<byte[]> SendRawSetQueue;
|
||||
|
||||
public List<byte[]> RecvQueue;
|
||||
|
||||
public XDataSchedule()
|
||||
{
|
||||
SendQueue = new List<byte[]>();
|
||||
ReplySendQueue = new List<byte[]>();
|
||||
SendRawSetQueue = new List<byte[]>();
|
||||
|
||||
RecvQueue = new List<byte[]>();
|
||||
}
|
||||
}
|
||||
[Serializable]
|
||||
public class XSchedule
|
||||
{
|
||||
public ConcurrentQueue<XPacket> SendQueue { get; }
|
||||
public ConcurrentQueue<XPacket> ReplySendQueue { get; }
|
||||
public ConcurrentQueue<XPacket> SendRawSetQueue { get; }
|
||||
|
||||
public ConcurrentQueue<XPacket> RecvQueue { get; }
|
||||
//
|
||||
public ConcurrentQueue<XData> RecvResultData { get; }
|
||||
|
||||
public XSchedule()
|
||||
{
|
||||
SendQueue = new ConcurrentQueue<XPacket>();
|
||||
ReplySendQueue = new ConcurrentQueue<XPacket>();
|
||||
SendRawSetQueue = new ConcurrentQueue<XPacket>();
|
||||
|
||||
RecvQueue = new ConcurrentQueue<XPacket>();
|
||||
RecvResultData = new ConcurrentQueue<XData>();
|
||||
}
|
||||
}
|
||||
public class EventAwaiter<TEventArgs>
|
||||
{
|
||||
private readonly TaskCompletionSource<TEventArgs> _eventArrived = new TaskCompletionSource<TEventArgs>();
|
||||
|
||||
private readonly Action<EventHandler<TEventArgs>> _unsubscribe;
|
||||
|
||||
public EventAwaiter(Action<EventHandler<TEventArgs>> subscribe, Action<EventHandler<TEventArgs>> unsubscribe)
|
||||
{
|
||||
subscribe(Subscription);
|
||||
_unsubscribe = unsubscribe;
|
||||
}
|
||||
|
||||
public Task<TEventArgs> Task => _eventArrived.Task;
|
||||
|
||||
private EventHandler<TEventArgs> Subscription => (s, e) =>
|
||||
{
|
||||
_eventArrived.TrySetResult(e);
|
||||
_unsubscribe(Subscription);
|
||||
};
|
||||
|
||||
/*
|
||||
var valueChangedEventAwaiter = new EventAwaiter<YourEventArgs>(
|
||||
h => example.YourEvent += h,
|
||||
h => example.YourEvent -= h);
|
||||
await valueChangedEventAwaiter.Task;
|
||||
*/
|
||||
}
|
||||
}
|
||||
155
SystemX.Net.CP.Platform/SystemX.Net.Platform/SystemX.Net/Base.cs
Normal file
155
SystemX.Net.CP.Platform/SystemX.Net.Platform/SystemX.Net/Base.cs
Normal file
@ -0,0 +1,155 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SystemX.Net
|
||||
{
|
||||
public static class Base
|
||||
{
|
||||
public static bool CheckPath(string strPath)
|
||||
{
|
||||
Regex r = new Regex(@"^(([a-zA-Z]\:)|(\\))(\\{1}|((\\{1})[^\\]([^/:*?<>""|]*))+)$");
|
||||
return r.IsMatch(strPath);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//Table Info(Serializatiopn) object.
|
||||
[Serializable]
|
||||
public class XTable
|
||||
{
|
||||
public string tableName;
|
||||
|
||||
public List<int> lstIndex;
|
||||
public List<string> lstName;
|
||||
public List<Type> lstType;
|
||||
public List<int> lstCharSize;
|
||||
public List<bool> lstNullAble;
|
||||
|
||||
public XTable(string fName)
|
||||
{
|
||||
this.tableName = fName;
|
||||
|
||||
lstIndex = new List<int>();
|
||||
lstName = new List<string>();
|
||||
lstType = new List<Type>();
|
||||
lstCharSize = new List<int>();
|
||||
lstNullAble = new List<bool>();
|
||||
}
|
||||
public void XTableAdd(int iIndex, string strName, Type SetType, int iCharSize, bool bNullable)
|
||||
{
|
||||
lstIndex.Add(iIndex);
|
||||
lstName.Add(strName);
|
||||
lstType.Add(SetType);
|
||||
lstCharSize.Add(iCharSize);
|
||||
lstNullAble.Add(bNullable);
|
||||
}
|
||||
}
|
||||
public enum eLogDataType
|
||||
{
|
||||
None = -1,
|
||||
|
||||
//CpLog
|
||||
Normal = 0,
|
||||
|
||||
//Leak
|
||||
CSV_Type0 = 1,
|
||||
|
||||
//Laser Trimming Vision
|
||||
CSV_Type1 = 2,
|
||||
|
||||
//Pin Vision
|
||||
CSV_Type2 = 3
|
||||
}
|
||||
public enum eLogAccessType
|
||||
{
|
||||
None = -1,
|
||||
|
||||
//File
|
||||
FileData = 0,
|
||||
|
||||
//VarBinary
|
||||
VarBinaryData = 1,
|
||||
}
|
||||
|
||||
// implements IEnumerable so that it can be used
|
||||
[Serializable]
|
||||
public class XTableInfo : IEnumerable
|
||||
{
|
||||
public XTable[] _table;
|
||||
public XTableInfo(XTable[] pArrayTable)
|
||||
{
|
||||
_table = new XTable[pArrayTable.Length];
|
||||
|
||||
for (int i = 0; i < pArrayTable.Length; i++)
|
||||
{
|
||||
_table[i] = pArrayTable[i];
|
||||
}
|
||||
}
|
||||
|
||||
// Implementation for the GetEnumerator method.
|
||||
IEnumerator IEnumerable.GetEnumerator()
|
||||
{
|
||||
return (IEnumerator)GetEnumerator();
|
||||
}
|
||||
|
||||
public TableEnum GetEnumerator()
|
||||
{
|
||||
return new TableEnum(_table);
|
||||
}
|
||||
}
|
||||
|
||||
//implement IEnumerable, implement IEnumerator.
|
||||
[Serializable]
|
||||
public class TableEnum : IEnumerator
|
||||
{
|
||||
public XTable[] _table;
|
||||
|
||||
// Enumerators are positioned before the first element
|
||||
// until the first MoveNext() call.
|
||||
int position = -1;
|
||||
|
||||
public TableEnum(XTable[] list)
|
||||
{
|
||||
_table = list;
|
||||
}
|
||||
|
||||
public bool MoveNext()
|
||||
{
|
||||
position++;
|
||||
return (position < _table.Length);
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
position = -1;
|
||||
}
|
||||
|
||||
object IEnumerator.Current
|
||||
{
|
||||
get
|
||||
{
|
||||
return Current;
|
||||
}
|
||||
}
|
||||
|
||||
public XTable Current
|
||||
{
|
||||
get
|
||||
{
|
||||
try
|
||||
{
|
||||
return _table[position];
|
||||
}
|
||||
catch (IndexOutOfRangeException)
|
||||
{
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using SystemX.Common;
|
||||
using SystemX.Net.BaseProtocol;
|
||||
|
||||
namespace SystemX.Net
|
||||
{
|
||||
}
|
||||
551
SystemX.Net.CP.Platform/SystemX.Net.Platform/SystemX.Net/Info.cs
Normal file
551
SystemX.Net.CP.Platform/SystemX.Net.Platform/SystemX.Net/Info.cs
Normal file
@ -0,0 +1,551 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using System.Xml.Linq;
|
||||
using SystemX.Net.BaseProtocol;
|
||||
|
||||
namespace SystemX.Net
|
||||
{
|
||||
/// <summary>
|
||||
/// Num, Command Port, Stream Port, Use, ProcessCode, TestID, ProcessName, PLCCOnfilgFileName, PLCUseType
|
||||
/// </summary>
|
||||
//using PLC_DEVICE_BASE_CONFIG = Tuple<int, int, int, bool, int, string, string, Tuple<string, string>>;
|
||||
|
||||
using static SystemX.Net.Platform.Common.Util.LogMessage;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class PLCDeviceBaseConfig {
|
||||
public int nNum;
|
||||
public int nCommandPort;
|
||||
public int nStreamPort;
|
||||
public bool bUse;
|
||||
public int nProcessCode;
|
||||
public string strTestID;
|
||||
public string strProcessName;
|
||||
public string strPLCCOnfilgFileName;
|
||||
public string strPLCUseType;
|
||||
}
|
||||
|
||||
public class ServerInfo {
|
||||
public bool READ_INFO_STATE { set; get; }
|
||||
|
||||
private string strInfoFilePos;
|
||||
|
||||
private int MAX_PROCESS_NUM;
|
||||
|
||||
public string SERVER_IP;
|
||||
public bool LOOP_BACK;
|
||||
|
||||
public string TITLE;
|
||||
|
||||
public int[] nListenCommandPort;
|
||||
public int[] nListenStreamPort;
|
||||
|
||||
public int nListenCommandPortNum;
|
||||
public int nListenCommandStartPort;
|
||||
public int nListenCommandEndPort;
|
||||
|
||||
public int nListenStreamPortNum;
|
||||
public int nListenStreamStartPort;
|
||||
public int nListenStreamEndPort;
|
||||
|
||||
public int nDistributionCommandPortNum;
|
||||
public int nDistributionCommandStartPort;
|
||||
public int nDistributionCommandEndPort;
|
||||
|
||||
public int nDistributionStreamPortNum;
|
||||
public int nDistributionStreamStartPort;
|
||||
public int nDistributionStreamEndPort;
|
||||
|
||||
public bool USE_HOST_INFO;
|
||||
public string HOST_TABLE_NAME;
|
||||
public string USER_TABLE_NAME;
|
||||
|
||||
public string DISK_MONITOR_POS1;
|
||||
public string DISK_MONITOR_POS2;
|
||||
|
||||
public string SERVER_SAVE_POS;
|
||||
public string MES_SAVE_POS;
|
||||
|
||||
public string SyncTimeServerAddress;
|
||||
public int SyncTimeServerPort;
|
||||
public int TimeServerSyncTimeHour;
|
||||
public int TimeServerSyncTimeMinute;
|
||||
public int TimeServerSyncTimeSecond;
|
||||
|
||||
public ServerInfo(string strGetInfoPath, int iMaxProcessNum)
|
||||
{
|
||||
strInfoFilePos = strGetInfoPath;
|
||||
|
||||
MAX_PROCESS_NUM = iMaxProcessNum;
|
||||
}
|
||||
public bool Load()
|
||||
{
|
||||
READ_INFO_STATE = true;
|
||||
|
||||
try
|
||||
{
|
||||
XDocument xDoc = XDocument.Load(strInfoFilePos);
|
||||
var xElement = xDoc.Element("ROOT");
|
||||
|
||||
int iPort = 0;
|
||||
if (xElement != null)
|
||||
{
|
||||
var xGetElement = xElement.Element("Configure");
|
||||
|
||||
SERVER_IP = xGetElement.Element("UseIP").Value;
|
||||
iPort = Convert.ToInt32((xGetElement.Element("Port").Value.IndexOf("-") >= 0) ? "0" : xGetElement.Element("Port").Value);
|
||||
LOOP_BACK = Convert.ToBoolean(xGetElement.Element("Loopback").Value);
|
||||
|
||||
TITLE = xGetElement.Element("Title").Value;
|
||||
|
||||
nListenCommandStartPort = Convert.ToInt32(xGetElement.Element("ListenCommandPort").Attribute("Start").Value);
|
||||
nListenCommandEndPort = Convert.ToInt32(xGetElement.Element("ListenCommandPort").Attribute("End").Value);
|
||||
|
||||
nListenCommandPortNum = nListenCommandEndPort - nListenCommandStartPort;
|
||||
|
||||
nListenStreamStartPort = Convert.ToInt32(xGetElement.Element("ListenStreamPort").Attribute("Start").Value);
|
||||
nListenStreamEndPort = Convert.ToInt32(xGetElement.Element("ListenStreamPort").Attribute("End").Value);
|
||||
|
||||
nListenStreamPortNum = nListenStreamEndPort - nListenStreamStartPort;
|
||||
|
||||
nListenCommandPort = new int[nListenCommandPortNum];
|
||||
nListenStreamPort = new int[nListenStreamPortNum];
|
||||
|
||||
for (int i = 0; i < nListenCommandPortNum; i++)
|
||||
nListenCommandPort[i] = nListenCommandStartPort + i;
|
||||
|
||||
for (int i = 0; i < nListenStreamPortNum; i++)
|
||||
nListenStreamPort[i] = nListenStreamStartPort + i;
|
||||
|
||||
nDistributionCommandStartPort = Convert.ToInt32(xGetElement.Element("DistributionCommandPort").Attribute("Start").Value);
|
||||
nDistributionCommandEndPort = Convert.ToInt32(xGetElement.Element("DistributionCommandPort").Attribute("End").Value);
|
||||
|
||||
nDistributionCommandPortNum = nDistributionCommandEndPort - nDistributionCommandStartPort;
|
||||
|
||||
nDistributionStreamStartPort = Convert.ToInt32(xGetElement.Element("DistributionStreamPort").Attribute("Start").Value);
|
||||
nDistributionStreamEndPort = Convert.ToInt32(xGetElement.Element("DistributionStreamPort").Attribute("End").Value);
|
||||
|
||||
nDistributionStreamPortNum = nDistributionStreamEndPort - nDistributionStreamStartPort;
|
||||
|
||||
SERVER_SAVE_POS = @xGetElement.Element("LogFileSavePos").Value;
|
||||
MES_SAVE_POS = @xGetElement.Element("MESFileSavePos").Value;
|
||||
|
||||
USE_HOST_INFO = Convert.ToBoolean(xGetElement.Element("UseHostInfo").Value);
|
||||
HOST_TABLE_NAME = @xGetElement.Element("HostInfoTableName").Value;
|
||||
USER_TABLE_NAME = @xGetElement.Element("UserInfoTableName").Value;
|
||||
|
||||
DISK_MONITOR_POS1 = xGetElement.Element("DiskMonitor1").Value;
|
||||
DISK_MONITOR_POS2 = xGetElement.Element("DiskMonitor2").Value;
|
||||
|
||||
if (DISK_MONITOR_POS1.Length <= 0)
|
||||
DISK_MONITOR_POS1 = @"C:\";
|
||||
if (DISK_MONITOR_POS2.Length <= 0)
|
||||
DISK_MONITOR_POS2 = @"D:\";
|
||||
|
||||
SyncTimeServerAddress = xGetElement.Element("SyncTimeServerAddress").Attribute("Address").Value;
|
||||
|
||||
SyncTimeServerPort = int.MinValue;
|
||||
|
||||
if (int.TryParse(xGetElement.Element("SyncTimePort").Attribute("Port").Value, out SyncTimeServerPort) == false)
|
||||
SyncTimeServerPort = int.MinValue;
|
||||
|
||||
TimeServerSyncTimeHour = 24;
|
||||
TimeServerSyncTimeMinute = 0;
|
||||
TimeServerSyncTimeSecond = 0;
|
||||
|
||||
if (int.TryParse(xGetElement.Element("TimeServer-SyncTime").Attribute("H").Value, out TimeServerSyncTimeHour) == false)
|
||||
TimeServerSyncTimeHour = 24;
|
||||
if (int.TryParse(xGetElement.Element("TimeServer-SyncTime").Attribute("M").Value, out TimeServerSyncTimeMinute) == false)
|
||||
TimeServerSyncTimeMinute = 0;
|
||||
if (int.TryParse(xGetElement.Element("TimeServer-SyncTime").Attribute("S").Value, out TimeServerSyncTimeSecond) == false)
|
||||
TimeServerSyncTimeSecond = 0;
|
||||
|
||||
if (Base.CheckPath(SERVER_SAVE_POS)) {
|
||||
if (Directory.Exists(SERVER_SAVE_POS) == false)
|
||||
Directory.CreateDirectory(SERVER_SAVE_POS);
|
||||
}
|
||||
else {
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"ServerInfo read failed.(SERVER SAVE POS - Folder name error)[SystemX.Common : SystemX.Net.ServerInfo]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
|
||||
throw new Exception();
|
||||
}
|
||||
|
||||
if (Base.CheckPath(MES_SAVE_POS)) {
|
||||
if (Directory.Exists(MES_SAVE_POS) == false) {
|
||||
Directory.CreateDirectory(MES_SAVE_POS);
|
||||
|
||||
/*MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"ServerInfo read failed.(MES SAVE POS - Folder exist error)[SystemX.Common : SystemX.Net.ServerInfo]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
|
||||
throw new Exception();*/
|
||||
}
|
||||
}
|
||||
else {
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"ServerInfo read failed.(MES SAVE POS - Folder name error)[SystemX.Common : SystemX.Net.ServerInfo]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
|
||||
throw new Exception();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
READ_INFO_STATE = false;
|
||||
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"ServerInfo read failed.[SystemX.Common : SystemX.Net.ServerInfo]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
return READ_INFO_STATE;
|
||||
}
|
||||
}
|
||||
|
||||
public class MapLogOption
|
||||
{
|
||||
public bool bReadInfoState { set; get; }
|
||||
|
||||
private string strInfoFilePos;
|
||||
|
||||
public bool bUseMapLog;
|
||||
public string strMapLogEnterMutexName;
|
||||
public string strMapLogAccessMutexName;
|
||||
public string strMapLogPath;
|
||||
public string strMapLogFileName;
|
||||
public string strMapLogName;
|
||||
|
||||
public string strMapInfoLogEnterMutexName;
|
||||
public string strMapInfoLogAccessMutexName;
|
||||
public string strMapInfoLogPath;
|
||||
public string strMapInfoLogFileName;
|
||||
public string strMapInfoLogName;
|
||||
|
||||
public MapLogOption(string strGetInfoPath)
|
||||
{
|
||||
strInfoFilePos = strGetInfoPath;
|
||||
}
|
||||
public bool Load()
|
||||
{
|
||||
bReadInfoState = true;
|
||||
|
||||
try
|
||||
{
|
||||
XDocument xDoc = XDocument.Load(strInfoFilePos);
|
||||
var xElement = xDoc.Element("ROOT");
|
||||
|
||||
if (xElement != null)
|
||||
{
|
||||
var xGetElement = xElement.Element("Configure");
|
||||
|
||||
XElement xEle = xGetElement.Element("UseMapLog");
|
||||
|
||||
if (xEle?.IsEmpty == false)
|
||||
bUseMapLog = Convert.ToBoolean(xGetElement.Element("UseMapLog").Value);
|
||||
else
|
||||
bUseMapLog = false;
|
||||
|
||||
strMapLogEnterMutexName = xGetElement.Element("MapLogEnterMutexName").Value;
|
||||
strMapLogAccessMutexName = xGetElement.Element("MapLogAccessMutexName").Value;
|
||||
strMapLogPath = @xGetElement.Element("MapLogFilePath").Value;
|
||||
strMapLogFileName = xGetElement.Element("MapLogFileName").Value;
|
||||
strMapLogName = xGetElement.Element("MapLogName").Value;
|
||||
|
||||
strMapInfoLogEnterMutexName = xGetElement.Element("MapInfoLogEnterMutexName").Value;
|
||||
strMapInfoLogAccessMutexName = xGetElement.Element("MapInfoLogAccessMutexName").Value;
|
||||
strMapInfoLogPath = @xGetElement.Element("MapInfoLogFilePath").Value;
|
||||
strMapInfoLogFileName = xGetElement.Element("MapInfoLogFileName").Value;
|
||||
strMapInfoLogName = xGetElement.Element("MapInfoLogName").Value;
|
||||
|
||||
if (Base.CheckPath(strMapLogPath))
|
||||
{
|
||||
if (Directory.Exists(strMapLogPath) == false)
|
||||
Directory.CreateDirectory(strMapLogPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"MapLogOption read failed. (Map Log Path - Folder name error)[SystemX.Common : SystemX.Net.MapLogOption]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
|
||||
throw new Exception();
|
||||
}
|
||||
|
||||
if (Base.CheckPath(strMapInfoLogPath))
|
||||
{
|
||||
if (Directory.Exists(strMapInfoLogPath) == false)
|
||||
Directory.CreateDirectory(strMapInfoLogPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"MapLogOption read failed. (Map Info Log Path - Folder name error)[SystemX.Common : SystemX.Net.MapLogOption]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
|
||||
throw new Exception();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
bReadInfoState = false;
|
||||
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"MapLogOption read failed. [SystemX.Common : SystemX.Net.MapLogOption]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
return bReadInfoState;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PLC Device Base Infomation
|
||||
/// </summary>
|
||||
/// <param name="index"> Num, Port, Use, ProcessCode, TestID, ProcessName, PLCCOnfilgFileName </param>
|
||||
public class PLCBaseInfo {
|
||||
public bool READ_INFO_STATE { set; get; }
|
||||
private string strInfoFilePos;
|
||||
private int MAX_DEVICE_NUM;
|
||||
|
||||
public string SERVER_IP;
|
||||
public bool LOOP_BACK;
|
||||
|
||||
public PLCDeviceBaseConfig[] BaseInfo;
|
||||
|
||||
public PLCBaseInfo(string strGetInfoPath, int iMaxDeviceNum) {
|
||||
strInfoFilePos = strGetInfoPath;
|
||||
|
||||
MAX_DEVICE_NUM = iMaxDeviceNum;
|
||||
|
||||
BaseInfo = new PLCDeviceBaseConfig[MAX_DEVICE_NUM];
|
||||
}
|
||||
public bool Load() {
|
||||
READ_INFO_STATE = true;
|
||||
|
||||
try
|
||||
{
|
||||
XDocument xDoc = XDocument.Load(strInfoFilePos);
|
||||
var xElement = xDoc.Element("ROOT");
|
||||
|
||||
int iPort = 0;
|
||||
if (xElement != null) {
|
||||
var xGetElement = xElement.Element("Configure");
|
||||
|
||||
SERVER_IP = xGetElement.Element("UseIP").Value;
|
||||
LOOP_BACK = Convert.ToBoolean(xGetElement.Element("Loopback").Value);
|
||||
|
||||
var ListGetElement = xElement.Elements("MiddlewareConnect").ToList();
|
||||
|
||||
foreach (var getXElement in ListGetElement) {
|
||||
if (getXElement.Attribute("INFO")?.Value.CompareTo("COMMON") == 0) {
|
||||
for (int i = 0; i < MAX_DEVICE_NUM; i++) {
|
||||
BaseInfo[i] = new PLCDeviceBaseConfig();
|
||||
BaseInfo[i].nNum = i;
|
||||
BaseInfo[i].nCommandPort = Convert.ToInt32(getXElement.Element("Device" + (i + 1).ToString()).Attribute("Command_PortNumber").Value);
|
||||
BaseInfo[i].nStreamPort = Convert.ToInt32(getXElement.Element("Device" + (i + 1).ToString()).Attribute("Stream_PortNumber").Value);
|
||||
BaseInfo[i].bUse = Convert.ToBoolean(getXElement.Element("Device" + (i + 1).ToString()).Attribute("Use").Value);
|
||||
BaseInfo[i].nProcessCode = Convert.ToInt32(getXElement.Element("Device" + (i + 1).ToString()).Attribute("ProcessCode").Value);
|
||||
BaseInfo[i].strTestID = getXElement.Element("Device" + (i + 1).ToString()).Attribute("TestID").Value;
|
||||
BaseInfo[i].strProcessName = getXElement.Element("Device" + (i + 1).ToString()).Attribute("ProcessName").Value;
|
||||
BaseInfo[i].strPLCCOnfilgFileName = getXElement.Element("Device" + (i + 1).ToString()).Attribute("PLCConfigFileName").Value;
|
||||
BaseInfo[i].strPLCUseType = getXElement.Element("Device" + (i + 1).ToString()).Attribute("PLCUseType").Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
READ_INFO_STATE = false;
|
||||
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"PLCBaseInfo read failed.[SystemX.Common : SystemX.Net.PLCBaseInfo]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
return READ_INFO_STATE;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// PC Client Base Infomation
|
||||
/// </summary>
|
||||
public class ClientInfo {
|
||||
public bool READ_INFO_STATE { set; get; }
|
||||
private string strInfoFilePos;
|
||||
|
||||
public string CONNECT_IP;
|
||||
|
||||
public int COMMAND_PORT;
|
||||
public int STREAM_PORT;
|
||||
|
||||
public bool LOOP_BACK;
|
||||
|
||||
public string HOST_ID;
|
||||
public string SECTION;
|
||||
public string TEST_CODE;
|
||||
|
||||
/* TODO : UIM Mode 및 기존 코드 정리 필요 */
|
||||
//SIMPLE_LOOKUP_OPTION
|
||||
//ISSUE_WORKER_WAIT_TIME_ms
|
||||
//SESSION_TIMEOUT_TIME_S
|
||||
//UIM
|
||||
public bool SIMPLE_LOOKUP_OPTION;
|
||||
public double ISSUE_WORKER_WAIT_TIME_ms;
|
||||
public double SESSION_TIMEOUT_TIME_S;
|
||||
|
||||
//TODO : Client ALIS FTP
|
||||
public bool FTP_Use;
|
||||
|
||||
public string FTP_IPAddress;
|
||||
public string FTP_Port;
|
||||
public string FTP_Account;
|
||||
public string FTP_Password;
|
||||
|
||||
public ClientInfo() {
|
||||
strInfoFilePos = "";
|
||||
}
|
||||
public ClientInfo(string strGetInfoPath) {
|
||||
strInfoFilePos = strGetInfoPath;
|
||||
}
|
||||
public bool Load() {
|
||||
READ_INFO_STATE = true;
|
||||
|
||||
SIMPLE_LOOKUP_OPTION = false;
|
||||
|
||||
ISSUE_WORKER_WAIT_TIME_ms = 3000.0;
|
||||
SESSION_TIMEOUT_TIME_S = 300.0;
|
||||
|
||||
TEST_CODE = string.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
XDocument xDoc = XDocument.Load(strInfoFilePos);
|
||||
var xElement = xDoc.Element("ROOT");
|
||||
|
||||
if (xElement != null) {
|
||||
var xGetElement = xElement.Element("Configure");
|
||||
|
||||
CONNECT_IP = xGetElement.Element("UseIP").Value;
|
||||
|
||||
COMMAND_PORT = Convert.ToInt32((xGetElement.Element("CommandPort").Value.IndexOf("-") >= 0) ? "0" : xGetElement.Element("CommandPort").Value);
|
||||
STREAM_PORT = Convert.ToInt32((xGetElement.Element("StreamPort").Value.IndexOf("-") >= 0) ? "0" : xGetElement.Element("StreamPort").Value);
|
||||
|
||||
LOOP_BACK = Convert.ToBoolean(xGetElement.Element("Loopback").Value);
|
||||
|
||||
HOST_ID = @xGetElement.Element("HostID").Value;
|
||||
SECTION = @xGetElement.Element("Section").Value;
|
||||
|
||||
XElement xEle = xGetElement.Element("TestCode");
|
||||
|
||||
if (xEle?.IsEmpty == false)
|
||||
TEST_CODE = @xGetElement.Element("TestCode").Value;
|
||||
|
||||
/*SCAN_LOG_FOLDER = Convert.ToBoolean(xGetElement.Element("LogFileScan").Value);
|
||||
SCAN_LOG_FOLDER_POS = xGetElement.Element("LogFileScanPos").Value;
|
||||
|
||||
if (SCAN_LOG_FOLDER) {
|
||||
if (Base.CheckPath(SCAN_LOG_FOLDER_POS)) {
|
||||
if (Directory.Exists(SCAN_LOG_FOLDER_POS) == false) {
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"ClientInfo read failed.(Scan log folder not exist)[SystemX.Common : SystemX.Net.ClientInfo]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
|
||||
throw new Exception();
|
||||
}
|
||||
}
|
||||
else {
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"ClientInfo read failed.(Scan log folder name error)[SystemX.Common : SystemX.Net.ClientInfo]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
|
||||
throw new Exception();
|
||||
}
|
||||
}
|
||||
|
||||
SCAN_DEVICE_FOLDER = Convert.ToBoolean(xGetElement.Element("DeviceFileScan").Value);
|
||||
SCAN_DEVICE_FOLDER_TYPE = xGetElement.Element("DeviceFileScanType").Value;
|
||||
SCAN_DEVICE_FOLDER_POS = xGetElement.Element("DeviceFileScanPos").Value;
|
||||
|
||||
if (SCAN_DEVICE_FOLDER) {
|
||||
if (Base.CheckPath(SCAN_DEVICE_FOLDER_POS)) {
|
||||
if (Directory.Exists(SCAN_DEVICE_FOLDER_POS) == false) {
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"ClientInfo read failed.(Scan device folder not exist)[SystemX.Common : SystemX.Net.ClientInfo]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
|
||||
throw new Exception();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"ClientInfo read failed.(Scan device folder name error)[SystemX.Common : SystemX.Net.ClientInfo]", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
|
||||
throw new Exception();
|
||||
}
|
||||
}*/
|
||||
|
||||
xEle = xGetElement.Element("SimpleLookUpOption");
|
||||
|
||||
bool bValue = false;
|
||||
//string strValue;
|
||||
|
||||
if (xEle?.IsEmpty == false) {
|
||||
if (bool.TryParse(xEle.Value, out bValue))
|
||||
SIMPLE_LOOKUP_OPTION = Convert.ToBoolean(xEle.Value);
|
||||
}
|
||||
|
||||
xEle = xGetElement.Element("IssueWorkerWaitTime_ms");
|
||||
|
||||
double dValue = double.NaN;
|
||||
|
||||
if (xEle?.IsEmpty == false) {
|
||||
if(double.TryParse(xEle.Value, out dValue))
|
||||
ISSUE_WORKER_WAIT_TIME_ms = Convert.ToDouble(xEle.Value);
|
||||
}
|
||||
|
||||
xEle = xGetElement.Element("SessionTimeout_s");
|
||||
|
||||
if (xGetElement.Element("SessionTimeout_s")?.IsEmpty == false) {
|
||||
dValue = double.NaN;
|
||||
if (double.TryParse(xEle.Value, out dValue))
|
||||
SESSION_TIMEOUT_TIME_S = Convert.ToDouble(xEle.Value);
|
||||
}
|
||||
|
||||
//TODO : Client ALIS FTP
|
||||
xEle = xGetElement.Element("UseFTP");
|
||||
|
||||
if (xEle?.IsEmpty == false)
|
||||
{
|
||||
if (bool.TryParse(xEle.Value, out bValue))
|
||||
FTP_Use = bValue;
|
||||
}
|
||||
else
|
||||
FTP_Use = false;
|
||||
|
||||
xEle = xGetElement.Element("IPAddressFTP");
|
||||
|
||||
if (xEle?.IsEmpty == false)
|
||||
FTP_IPAddress = xEle.Value;
|
||||
else
|
||||
FTP_IPAddress = "0.0.0.0";
|
||||
|
||||
xEle = xGetElement.Element("PortFTP");
|
||||
|
||||
if (xEle?.IsEmpty == false)
|
||||
FTP_Port = xEle.Value;
|
||||
else
|
||||
FTP_Port = "21";
|
||||
|
||||
xEle = xGetElement.Element("AccountFTP");
|
||||
|
||||
if (xEle?.IsEmpty == false)
|
||||
FTP_Account = xEle.Value;
|
||||
else
|
||||
FTP_Account = "";
|
||||
|
||||
xEle = xGetElement.Element("PasswordFTP");
|
||||
|
||||
if (xEle?.IsEmpty == false)
|
||||
FTP_Password = xEle.Value;
|
||||
else
|
||||
FTP_Password = "";
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
READ_INFO_STATE = false;
|
||||
|
||||
MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"ClientInfo read failed.[SystemX.Common : SystemX.Net.ClientInfo]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
|
||||
}
|
||||
|
||||
return READ_INFO_STATE;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,672 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SystemX.Net.BaseProtocol
|
||||
{
|
||||
[Serializable]
|
||||
public enum PROCESS_TYPE
|
||||
{
|
||||
NONE = -1,
|
||||
SYSTEM = 0,
|
||||
PLC = 1,
|
||||
PC = 2,
|
||||
DEVICE = 3,
|
||||
UIM = 4,
|
||||
UIM_SERVER = 5,
|
||||
PC_PORT_SERVER = 6
|
||||
}
|
||||
|
||||
/*
|
||||
* Adaptor
|
||||
*/
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode), Serializable]
|
||||
public struct STRING_4
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)]
|
||||
public string Data;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode), Serializable]
|
||||
public struct STRING_8
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
|
||||
public string Data;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode), Serializable]
|
||||
public struct STRING_16
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
|
||||
public string Data;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode), Serializable]
|
||||
public struct STRING_32
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
|
||||
public string Data;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode), Serializable]
|
||||
public struct STRING_64
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
|
||||
public string Data;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode), Serializable]
|
||||
public struct STRING_128
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
|
||||
public string Data;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode), Serializable]
|
||||
public struct STRING_256
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
|
||||
public string Data;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode), Serializable]
|
||||
public struct STRING_512
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
|
||||
public string Data;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode), Serializable]
|
||||
public struct STRING_1024
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
|
||||
public string Data;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode), Serializable]
|
||||
public struct STRING_2048
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2048)]
|
||||
public string Data;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode), Serializable]
|
||||
public struct STRING_4096
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4096)]
|
||||
public string Data;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
/*
|
||||
* System Query
|
||||
*/
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode), Serializable]
|
||||
public struct QUERY_STRING
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2048)]
|
||||
public string Data;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1), Serializable]
|
||||
public struct SYSTEMTIME
|
||||
{
|
||||
public short wYear;
|
||||
public short wMonth;
|
||||
public short wDayOfWeek;
|
||||
public short wDay;
|
||||
public short wHour;
|
||||
public short wMinute;
|
||||
public short wSecond;
|
||||
public short wMilliseconds;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
/*
|
||||
* Initialize Comm Body
|
||||
*/
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1), Serializable]
|
||||
public struct COMM_INFO_PACKET
|
||||
{
|
||||
//Use Port Distribution
|
||||
[MarshalAs(UnmanagedType.Bool)]
|
||||
public bool bPortDistribution;
|
||||
|
||||
//COMMAND 포트 번호
|
||||
[MarshalAs(UnmanagedType.U2)]
|
||||
public ushort usPortCommandNumber;
|
||||
|
||||
//STREAM 포트 번호
|
||||
[MarshalAs(UnmanagedType.U2)]
|
||||
public ushort usPortStreamNumber;
|
||||
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_32[] objConnLocalAddress;
|
||||
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_32[] objConnLocalPort;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
/*
|
||||
* Initialize Comm Body
|
||||
*/
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1), Serializable]
|
||||
public struct PING_PACKET
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_8[] objCheckMsg;
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1), Serializable]
|
||||
public struct TIME_PACKET
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_32[] objMsg;
|
||||
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public SYSTEMTIME[] objTime;
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1), Serializable]
|
||||
public struct MESSAGE_PACKET
|
||||
{
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_512[] objMessage;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1), Serializable]
|
||||
public struct TRANSFER_PACKET
|
||||
{
|
||||
//수신 결과
|
||||
[MarshalAs(UnmanagedType.Bool)]
|
||||
public bool bRecvResult;
|
||||
|
||||
//처리 결과
|
||||
[MarshalAs(UnmanagedType.Bool)]
|
||||
public bool bProcessResult;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
|
||||
//------------------------------------------------------------------------------------------
|
||||
/*
|
||||
* Packet Header
|
||||
*/
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1), Serializable]
|
||||
public struct HEADER_PACKET
|
||||
{
|
||||
[MarshalAs(UnmanagedType.U2)]
|
||||
public ushort usHeader;
|
||||
|
||||
//응답 결과
|
||||
[MarshalAs(UnmanagedType.Bool)]
|
||||
public bool bResponsState;
|
||||
|
||||
//네트워크 번호
|
||||
[MarshalAs(UnmanagedType.U1)]
|
||||
public byte ucNetworkNo;
|
||||
|
||||
//데이터베이스 ID
|
||||
[MarshalAs(UnmanagedType.U1)]
|
||||
public byte ucDatabaseID;
|
||||
|
||||
//테이블 ID
|
||||
[MarshalAs(UnmanagedType.U2)]
|
||||
public ushort usTableID;
|
||||
|
||||
//Pallet Number
|
||||
[MarshalAs(UnmanagedType.U1)]
|
||||
public byte ucPalletNumber;
|
||||
|
||||
//Pallet Index
|
||||
[MarshalAs(UnmanagedType.U2)]
|
||||
public ushort usPalletIndex;
|
||||
|
||||
//해당 헤더 크기
|
||||
[MarshalAs(UnmanagedType.U4)]
|
||||
public uint uiHeaderLength;
|
||||
|
||||
//선택된 바디 패킷 길이
|
||||
[MarshalAs(UnmanagedType.U4)]
|
||||
public uint uiBodyLength;
|
||||
|
||||
//전체 패킷 크기
|
||||
[MarshalAs(UnmanagedType.U4)]
|
||||
public uint uiPacketLength;
|
||||
|
||||
//실제 데이터 크기
|
||||
[MarshalAs(UnmanagedType.U4)]
|
||||
public uint uiDataLength;
|
||||
|
||||
//로그 파일 전송시 이름
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_128[] objOptionName;
|
||||
|
||||
//최종 변환 확장자 명
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_8[] objOptionExtension;
|
||||
|
||||
//연속 패킷(대용량) 현재 번호 Default 0 Else 1 ~
|
||||
[MarshalAs(UnmanagedType.U4)]
|
||||
public uint uiSourDataNum;
|
||||
|
||||
//연속 패킷(대용량) 최종 번호 Default 0 Else 1 ~
|
||||
[MarshalAs(UnmanagedType.U4)]
|
||||
public uint uiDestDataNum;
|
||||
|
||||
//주 명령
|
||||
[MarshalAs(UnmanagedType.U2)]
|
||||
public ushort usCommand;
|
||||
|
||||
//서브 명령
|
||||
[MarshalAs(UnmanagedType.U2)]
|
||||
public ushort usSubCommand;
|
||||
|
||||
//옵션 명령
|
||||
[MarshalAs(UnmanagedType.U4)]
|
||||
public uint uiOptionCommand;
|
||||
|
||||
//다목적 사용 파라미터1
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_64[] objVarParam1;
|
||||
|
||||
//다목적 사용 파라미터2
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_128[] objVarParam2;
|
||||
|
||||
//다목적 사용 파라미터3
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_256[] objVarParam3;
|
||||
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public CP_PACKET[] objCP_Packet;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
|
||||
/*
|
||||
* CP Info Header
|
||||
*/
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1), Serializable]
|
||||
public struct CP_PACKET
|
||||
{
|
||||
//CP ALIS StationName
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_64[] objStationName;
|
||||
|
||||
//CP ALIS ProdP
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_16[] objProdNo_P;
|
||||
|
||||
//CP ALIS ProdC
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_16[] objProdNo_C;
|
||||
|
||||
//CP ALIS TestType
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_8[] objTestType;
|
||||
|
||||
//CP ALIS TestCode
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_16[] objTestCode;
|
||||
|
||||
//CP ALIS Version
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_4[] objVersion;
|
||||
|
||||
//CP ALIS ProdCode
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_4[] objProdCode;
|
||||
|
||||
//CP ALIS TestListNo
|
||||
[MarshalAs(UnmanagedType.U4)]
|
||||
public uint uiTestListNo;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
|
||||
/*
|
||||
* PLC Adaptor 지원
|
||||
*/
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1), Serializable]
|
||||
public struct USER_PACKET
|
||||
{
|
||||
//파레트 정보 및 제품 아이디 및 품번
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public PROCESS_PACKET[] objProcessInfo;
|
||||
|
||||
//명령 INSERT, UPDATE, DELETE SELECT 등 현재는 INSERT 만.
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_16[] objTableCommand;
|
||||
|
||||
//테이블 명칭
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_64[] objTableName;
|
||||
|
||||
//컬럼 길이
|
||||
[MarshalAs(UnmanagedType.U4)]
|
||||
public uint uiSubLength;
|
||||
|
||||
//0 부터 해당 컬럼 명
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_512[] objNames;
|
||||
|
||||
//0 부터 해당 컬럼 데이터
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_512[] objDatas;
|
||||
|
||||
//처리 결과
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_16[] objCommandResult;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
/*
|
||||
* SYSTEM 지원
|
||||
*/
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1), Serializable]
|
||||
public struct QUERY_PACKET
|
||||
{
|
||||
//QUERY 문
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public QUERY_STRING[] objQueryText;
|
||||
//다목적 파라미터1
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_64[] objVarParam1;
|
||||
//다목적 파라미터2
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_128[] objVarParam2;
|
||||
//다목적 파라미터3
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_256[] objVarParam3;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
/*
|
||||
* HOST LOGIN
|
||||
*/
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1), Serializable]
|
||||
public struct SYSTEM_HOST_PACKET
|
||||
{
|
||||
//UIM Use
|
||||
[MarshalAs(UnmanagedType.Bool)]
|
||||
public bool bUseUIM;
|
||||
//UIM Use
|
||||
[MarshalAs(UnmanagedType.Bool)]
|
||||
public bool bUseSimpleLookupOption;
|
||||
//HOST ID
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_64[] objHostID;
|
||||
//SECTION
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_64[] objSection;
|
||||
//TEST CODE
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_64[] objTestCode;
|
||||
//MESSAGE
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_512[] objMessage;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
/*
|
||||
* PROCESS QUERY(PC, PLC Adaptor) 지원
|
||||
*/
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1), Serializable]
|
||||
public struct PROCESS_PACKET
|
||||
{
|
||||
//Station ID
|
||||
[MarshalAs(UnmanagedType.U4)]
|
||||
public uint nStationID;
|
||||
|
||||
//ProdC
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_16[] objProdNo_C;
|
||||
|
||||
//TestType
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_8[] objTestType;
|
||||
|
||||
//TestCode
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_16[] objTestCode;
|
||||
|
||||
//FileVersion
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_4[] objTestListFileVersion;
|
||||
|
||||
//ProductionCode
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_4[] objProductionCode;
|
||||
|
||||
//Product ID
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public STRING_64[] objProductID;
|
||||
}
|
||||
//------------------------------------------------------------------------------------------
|
||||
public class BASE_PROTOCOL
|
||||
{
|
||||
//BASE PROTOCOL Main Command 0 - Private
|
||||
public enum PROTOCOL_CODE
|
||||
{
|
||||
NONE = -1,
|
||||
//PC Adaptor File Save
|
||||
FILE_TRANSFER = 0,
|
||||
DATASET_TRANSEFER = 1,
|
||||
//Just reply
|
||||
SIMPLE_RESPONSE = 2,
|
||||
//PLC Adaptor
|
||||
ETC = 3,
|
||||
RAW_SIZE = 4,
|
||||
RAW_END = 5,
|
||||
//System Program
|
||||
SYSTEM_QUERY = 6,
|
||||
INITILALIZE_INFO = 7,
|
||||
PROCESS_QUERY = 8,
|
||||
USER_QUERY = 9,
|
||||
TRANSFER_RESULT = 10,
|
||||
|
||||
//Time Server Sync Request
|
||||
SYNC_TIME_SERVER = 128,
|
||||
//Host Info Check
|
||||
HOST_INFO_CHECK = 256,
|
||||
//Middleware send message
|
||||
MIDDLEWARE_MESSAGE = 512,
|
||||
//Ping
|
||||
CONNECT_STATE = 1024
|
||||
}
|
||||
[Flags]
|
||||
public enum OPTION_CODE
|
||||
{
|
||||
NONE = 0x00000000,
|
||||
QUERY_TESTLIST = 0x00000001,
|
||||
GET_ISSUANCE_MACADDRESS = 0x00000002,
|
||||
CHECK_VAILD_TESTLIST = 0x00000004,
|
||||
}
|
||||
public OPTION_CODE GetOptionCode()
|
||||
{
|
||||
return (OPTION_CODE)uiOptionCommand;
|
||||
}
|
||||
public void SetOptionCode(OPTION_CODE SET_OPTION)
|
||||
{
|
||||
uiOptionCommand = (uint)SET_OPTION;
|
||||
}
|
||||
//
|
||||
private ushort usCommand;
|
||||
private ushort usSubCommand;
|
||||
private uint uiOptionCommand;
|
||||
|
||||
public PROTOCOL_CODE GET_CURRENT_PROTOCOL
|
||||
{
|
||||
get { return ProtocolDecoder(); }
|
||||
}
|
||||
public ushort COMMAND
|
||||
{
|
||||
get { return usCommand; }
|
||||
}
|
||||
public ushort SUB_COMMAND
|
||||
{
|
||||
get { return usSubCommand; }
|
||||
}
|
||||
public uint OPTION_COMMAND
|
||||
{
|
||||
get { return uiOptionCommand; }
|
||||
}
|
||||
|
||||
public PROTOCOL_CODE ProtocolDecoder()
|
||||
{
|
||||
PROTOCOL_CODE SET_CODE = new PROTOCOL_CODE();
|
||||
SET_CODE = PROTOCOL_CODE.NONE;
|
||||
|
||||
string TextCode = usCommand.ToString("D3") + "_" + usSubCommand.ToString("D3");
|
||||
|
||||
if (TextCode.CompareTo("000_001") == 0)
|
||||
SET_CODE = PROTOCOL_CODE.FILE_TRANSFER;
|
||||
else if (TextCode.CompareTo("000_002") == 0)
|
||||
SET_CODE = PROTOCOL_CODE.DATASET_TRANSEFER;
|
||||
else if (TextCode.CompareTo("000_003") == 0)
|
||||
SET_CODE = PROTOCOL_CODE.SIMPLE_RESPONSE;
|
||||
else if (TextCode.CompareTo("000_004") == 0)
|
||||
SET_CODE = PROTOCOL_CODE.RAW_SIZE;
|
||||
else if (TextCode.CompareTo("000_005") == 0)
|
||||
SET_CODE = PROTOCOL_CODE.RAW_END;
|
||||
else if (TextCode.CompareTo("000_006") == 0)
|
||||
SET_CODE = PROTOCOL_CODE.SYSTEM_QUERY;
|
||||
else if (TextCode.CompareTo("000_007") == 0)
|
||||
SET_CODE = PROTOCOL_CODE.INITILALIZE_INFO;
|
||||
else if (TextCode.CompareTo("000_009") == 0)
|
||||
SET_CODE = PROTOCOL_CODE.USER_QUERY;
|
||||
else if (TextCode.CompareTo("000_010") == 0)
|
||||
SET_CODE = PROTOCOL_CODE.TRANSFER_RESULT;
|
||||
|
||||
else if (TextCode.CompareTo("001_000") == 0)
|
||||
SET_CODE = PROTOCOL_CODE.ETC;
|
||||
|
||||
else if (TextCode.CompareTo("002_001") == 0)
|
||||
SET_CODE = PROTOCOL_CODE.PROCESS_QUERY;
|
||||
|
||||
else if (TextCode.CompareTo("999_004") == 0)
|
||||
SET_CODE = PROTOCOL_CODE.SYNC_TIME_SERVER;
|
||||
|
||||
else if (TextCode.CompareTo("999_003") == 0)
|
||||
SET_CODE = PROTOCOL_CODE.HOST_INFO_CHECK;
|
||||
|
||||
else if (TextCode.CompareTo("999_002") == 0)
|
||||
SET_CODE = PROTOCOL_CODE.MIDDLEWARE_MESSAGE;
|
||||
|
||||
else if (TextCode.CompareTo("999_001") == 0)
|
||||
SET_CODE = PROTOCOL_CODE.CONNECT_STATE;
|
||||
|
||||
else
|
||||
SET_CODE = PROTOCOL_CODE.NONE;
|
||||
|
||||
return SET_CODE;
|
||||
}
|
||||
public BASE_PROTOCOL()
|
||||
{
|
||||
}
|
||||
public BASE_PROTOCOL(ushort usGetCommnad, ushort usGetSubCommand, uint uiGetOptionCommand = 0)
|
||||
{
|
||||
usCommand = usGetCommnad;
|
||||
usSubCommand = usGetSubCommand;
|
||||
//
|
||||
uiOptionCommand = uiGetOptionCommand;
|
||||
}
|
||||
/*
|
||||
public void PROTOCOL_CHANGE(PROTOCOL_CODE SET_CODE, OPTION_CODE SET_OPTION = OPTION_CODE.NONE)
|
||||
{
|
||||
new BASE_PROTOCOL(SET_CODE, SET_OPTION);
|
||||
}
|
||||
*/
|
||||
public BASE_PROTOCOL(PROTOCOL_CODE SET_CODE, OPTION_CODE SET_OPTION = OPTION_CODE.NONE)
|
||||
{
|
||||
uiOptionCommand = (uint)SET_OPTION;
|
||||
|
||||
if (SET_CODE == PROTOCOL_CODE.NONE)
|
||||
{
|
||||
usCommand = 0;
|
||||
usSubCommand = 0;
|
||||
}
|
||||
else if (SET_CODE == PROTOCOL_CODE.FILE_TRANSFER)
|
||||
{
|
||||
usCommand = 0;
|
||||
usSubCommand = 1;
|
||||
}
|
||||
else if (SET_CODE == PROTOCOL_CODE.DATASET_TRANSEFER)
|
||||
{
|
||||
usCommand = 0;
|
||||
usSubCommand = 2;
|
||||
}
|
||||
else if (SET_CODE == PROTOCOL_CODE.SIMPLE_RESPONSE)
|
||||
{
|
||||
usCommand = 0;
|
||||
usSubCommand = 3;
|
||||
}
|
||||
else if (SET_CODE == PROTOCOL_CODE.RAW_SIZE)
|
||||
{
|
||||
usCommand = 0;
|
||||
usSubCommand = 4;
|
||||
}
|
||||
else if (SET_CODE == PROTOCOL_CODE.RAW_END)
|
||||
{
|
||||
usCommand = 0;
|
||||
usSubCommand = 5;
|
||||
}
|
||||
else if (SET_CODE == PROTOCOL_CODE.SYSTEM_QUERY)
|
||||
{
|
||||
usCommand = 0;
|
||||
usSubCommand = 6;
|
||||
}
|
||||
else if (SET_CODE == PROTOCOL_CODE.INITILALIZE_INFO)
|
||||
{
|
||||
usCommand = 0;
|
||||
usSubCommand = 7;
|
||||
}
|
||||
else if (SET_CODE == PROTOCOL_CODE.USER_QUERY)
|
||||
{
|
||||
usCommand = 0;
|
||||
usSubCommand = 9;
|
||||
}
|
||||
else if (SET_CODE == PROTOCOL_CODE.TRANSFER_RESULT)
|
||||
{
|
||||
usCommand = 0;
|
||||
usSubCommand = 10;
|
||||
}
|
||||
//
|
||||
else if (SET_CODE == PROTOCOL_CODE.ETC)
|
||||
{
|
||||
usCommand = 1;
|
||||
usSubCommand = 0;
|
||||
}
|
||||
|
||||
else if (SET_CODE == PROTOCOL_CODE.PROCESS_QUERY)
|
||||
{
|
||||
usCommand = 2;
|
||||
usSubCommand = 1;
|
||||
}
|
||||
|
||||
else if (SET_CODE == PROTOCOL_CODE.SYNC_TIME_SERVER)
|
||||
{
|
||||
usCommand = 999;
|
||||
usSubCommand = 4;
|
||||
}
|
||||
|
||||
else if (SET_CODE == PROTOCOL_CODE.HOST_INFO_CHECK)
|
||||
{
|
||||
usCommand = 999;
|
||||
usSubCommand = 3;
|
||||
}
|
||||
|
||||
else if (SET_CODE == PROTOCOL_CODE.MIDDLEWARE_MESSAGE)
|
||||
{
|
||||
usCommand = 999;
|
||||
usSubCommand = 2;
|
||||
}
|
||||
|
||||
else if (SET_CODE == PROTOCOL_CODE.CONNECT_STATE)
|
||||
{
|
||||
usCommand = 999;
|
||||
usSubCommand = 1;
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
usCommand = 0;
|
||||
usSubCommand = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
42
SystemX.Net.CP.Platform/SystemX.Net.Platform/packages.config
Normal file
42
SystemX.Net.CP.Platform/SystemX.Net.Platform/packages.config
Normal file
@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Microsoft.NETCore.Platforms" version="1.1.0" targetFramework="net452" />
|
||||
<package id="NETStandard.Library" version="1.6.1" targetFramework="net452" />
|
||||
<package id="Remotion.Linq" version="2.1.1" targetFramework="net452" />
|
||||
<package id="System.Collections" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Collections.Concurrent" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Collections.Immutable" version="1.3.0" targetFramework="net452" />
|
||||
<package id="System.ComponentModel" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Diagnostics.DiagnosticSource" version="4.3.1" targetFramework="net452" />
|
||||
<package id="System.Diagnostics.Tools" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Diagnostics.Tracing" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Globalization" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Interactive.Async" version="3.0.0" targetFramework="net452" />
|
||||
<package id="System.IO" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.IO.Compression" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Linq" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Linq.Expressions" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Linq.Queryable" version="4.0.1" targetFramework="net452" />
|
||||
<package id="System.Net.Http" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Net.Primitives" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.ObjectModel" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Reflection" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Reflection.Extensions" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Reflection.Primitives" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Runtime" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Runtime.CompilerServices.Unsafe" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Runtime.Extensions" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Runtime.InteropServices" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Runtime.Numerics" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Text.Encoding" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Text.Encoding.Extensions" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Text.RegularExpressions" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Threading" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Threading.Tasks" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Threading.Timer" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Xml.ReaderWriter" version="4.3.0" targetFramework="net452" />
|
||||
<package id="System.Xml.XDocument" version="4.3.0" targetFramework="net452" />
|
||||
</packages>
|
||||
Reference in New Issue
Block a user