[성현모] CPXV2 Init

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

View File

@ -0,0 +1,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);
}
}
}
}
}

View File

@ -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;
}
}
}

View File

@ -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 { }
}

View File

@ -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);
}
}
}

View File

@ -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;
}
}
}

View File

@ -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);
}
}
}

View File

@ -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
}
}

View File

@ -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));
}
}
}

View File

@ -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;
}
}
}

View File

@ -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);
}
}
}

View File

@ -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});
}
}
}

View File

@ -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;
}
}
}

View File

@ -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;
}
}
}
}

View File

@ -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;
}
}
}

View File

@ -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));
}
}
}

View File

@ -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;
}
}
}

View File

@ -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));
}
}
}

View File

@ -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); }
}
}

View File

@ -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
}
}

View File

@ -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;
}
}

View File

@ -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) { }
}
}

View File

@ -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);
}
}
}

View File

@ -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);
}
}
}

View File

@ -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;
}
}
}

View File

@ -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
}
}

View File

@ -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);
}
}
}

View File

@ -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;
}
}
}

View File

@ -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();
}
}
}

View File

@ -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); }
}
}

View File

@ -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;
}
}
}

View File

@ -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";
}
}
*/

View File

@ -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 { }
}

View File

@ -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;
}
}
}

View File

@ -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);
}
}
}

View File

@ -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);
}
}
}
}