123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465 |
- using DBModel;
- using DBNames;
- using log4net;
- using SCADA.CommonLib;
- using SCADA.CommonLib.Helper;
- using SCADA.CommonLib.License;
- using SCADA_DAQ.Plugin.Core;
- using SCADA_DAQ.Plugin.Core.License;
- using SCADA_DAQ.Plugin.CoreUI;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows;
- namespace SCADA_DAQ
- {
- internal class SystemControl
- {
- /// <summary>
- ///
- /// </summary>
- bool isShutDown = false;
- ILog Log { get; set; } = null;
- private EventWaitHandle evh;
- public App App { get; private set; }
- private static SystemControl systemControl;
- private static readonly object syncObj = new object();
- private readonly List<AdvanceTimer> Timers = new List<AdvanceTimer>();
- private readonly Task initTask;
- private readonly Task initServer;
- public string UidVersion { get; }
- private string SoftWareId { get; set; }
- private SystemControl(App app)
- {
- App = app;
- PowerOnTime = DateTime.Now;
- SoftWareId = MD5Helper.GetFileMD5(GetType().Assembly.Location);
- UidVersion = $"{ApplicationHelper.GetAppVersion()}.{Convert.ToUInt16(SoftWareId.Substring(0, 3), 16):D4}";
- app.RuntimeInfo.UidVersion = UidVersion;
- initTask = Task.Factory.StartNew(() =>
- {
- bool createdNew = true;
- if (app.SystemConfig.SingleModel == true)
- {
- evh = new EventWaitHandle(false, EventResetMode.AutoReset, App.RuntimeInfo.ProductId, out createdNew);
- var currentProcess = Process.GetCurrentProcess();
- var ps = Process.GetProcessesByName(
- Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().ManifestModule.Name))
- .Where(t => t.Id != currentProcess.Id);
- if (createdNew) //信号锁创建成功,且是单例模式
- {
- foreach (Process p in ps)
- {
- p.Kill();
- }
- }
- else
- {
- if (ps.Count() == 1 && ps.First().MainWindowHandle != IntPtr.Zero)
- {
- evh?.Set();
- app.Dispatcher.Invoke(new Action(() =>
- {
- isShutDown = true;
- App.Shutdown(1);
- }));
- return;
- }
- else
- {
- foreach (Process p in ps) //单例模式下如果主界面没有出现,或者有多个进程,直接全部kill掉
- {
- p.Kill();
- }
- }
- }
- }
- Console.WriteLine($"开始获取电脑ID {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
- LicenseManage.GenerateID(App.RuntimeInfo.ProductId, out var str);
- Console.WriteLine($"检查释放系统组件 {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
- ReleaseRunTime();
- try
- {
- var dtClass = DataTableHelper.DtToList<App_Classes>(Env.DAL.App_Classes.GetData($"{T_Col_Name.App_Classes.ClassType_Int}=2"));
- if (dtClass != null)
- {
- Env.Schedual.Classes.Clear();
- foreach (var appClassese in dtClass)
- {
- var startTime = TimeSpan.Parse(appClassese.StartTime_Str);
- var endTime = TimeSpan.Parse(appClassese.EndTime_Str);
- Env.Schedual.Classes.Add(new WorkShift(startTime,
- endTime, appClassese.ClassesName_Str));
- }
- }
- }
- catch (Exception)
- {
- Env.Schedual.Classes.Add(new WorkShift(new TimeSpan(7, 30, 0), new TimeSpan(19, 30, 0), "白班"));
- Env.Schedual.Classes.Add(new WorkShift(new TimeSpan(19, 30, 0), new TimeSpan(7, 30, 0), "夜班"));
- }
- CreateBackGroundTask(ReportOnLine, 10 * 1000 * 60, 10 * 1000, true, "ReportAppInfo");
- var systemStatics = Plugin.CoreUI.SystemApp.SystemStatictics.Create();
- systemStatics.AppRuntime = App;
- systemStatics.Start();
- });
- initServer = Task.Factory.StartNew(() =>
- {
- });
- }
- private DateTime PowerOnTime { get; set; }
- public static SystemControl Create(App app)
- {
- lock (syncObj)
- {
- if (systemControl == null)
- {
- systemControl = new SystemControl(app);
- }
- }
- return systemControl;
- }
- public static SystemControl GetInstance()
- {
- return systemControl;
- }
- public void SystemInit()
- {
- App.DispatcherUnhandledException += Application_DispatcherUnhandledException;
- AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
- TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
- Task.Factory.StartNew(() =>
- {
- Task.WaitAll(initTask);
- if (isShutDown) return;
- var st = new Stopwatch();
- st.Start();
- EicpCoreManage.AppRuntime = App;
- try
- {
- App.RuntimeInfo.StartTime = DateTime.Now;
- Log = SCADA.CommonLib.LoggerHelper.Logger.CreateLogger(typeof(App));
- Dictionary<SCADA.CommonLib.LoggerHelper.LogLevel, log4net.Core.Level> logLevel =
- new Dictionary<SCADA.CommonLib.LoggerHelper.LogLevel, log4net.Core.Level>()
- {
- { SCADA.CommonLib.LoggerHelper.LogLevel.All,log4net.Core.Level.All},
- { SCADA.CommonLib.LoggerHelper.LogLevel.Debug,log4net.Core.Level.Debug},
- { SCADA.CommonLib.LoggerHelper.LogLevel.Info,log4net.Core.Level.Info},
- { SCADA.CommonLib.LoggerHelper.LogLevel.Warn,log4net.Core.Level.Warn},
- { SCADA.CommonLib.LoggerHelper.LogLevel.Error,log4net.Core.Level.Error},
- { SCADA.CommonLib.LoggerHelper.LogLevel.Fatal,log4net.Core.Level.Fatal},
- { SCADA.CommonLib.LoggerHelper.LogLevel.None,log4net.Core.Level.Off},
- };
- LogManager.GetRepository().Threshold = logLevel[App.SystemConfig.LogLevel];
- Log.Info($"App {App.RuntimeInfo.ProductId} ({UidVersion}) [{App.SystemConfig.ComputerTag}] is starting ……");
- Task.WaitAll(initServer);
- Console.WriteLine($"系统初始化完成 {DateTime.Now:yyyy-MM-dd HH:mm:ss,fff}");
- Func<bool> action = null;
- LoadLicense();
- App.RuntimeInfo.ComputerId = App.RuntimeInfo.LicenseInfo.Computer.ComputerId;
- var host = ServiceHost.Instance;
- App.ServiceHost = host;
- host.Start(App);
- App.Dispatcher.Invoke(new Action(() =>
- {
- if (App.MainWindow is MainWindow window)
- {
- action = window.GetLicense;
- }
- }));
- if (!LicenseManage.CheckID(App as IApp, out var str, action))
- {
- App.Dispatcher.Invoke(new Action(() =>
- {
- isShutDown = true;
- App.Shutdown(100);
- }));
- return;
- }
- else
- {
- App.RuntimeInfo.LicenseInfo = LicenseManage.GetLicenseInfo(App.RuntimeInfo.ProductId);
- }
- App.Dispatcher.Invoke(new Action(() =>
- {
- if (App.MainWindow is MainWindow window)
- {
- window.LicenseInfo = App.RuntimeInfo.LicenseInfo;
- Log.Debug($"系统初始化完成,即将开启");
- Env.SetLanguage();
- window.SystemInited();
- Env.SetTheme();
- Env.SetFont();
- }
- }));
- }
- catch (Exception ex)
- {
- FalatReport(ex);
- Log.Error(ex);
- }
- new Thread(() =>
- {
- while (!isShutDown && evh != null)
- {
- if (evh.WaitOne(-1))
- {
- if (isShutDown)
- {
- return;
- }
- App.Dispatcher.Invoke(new Action(() =>
- {
- App.MainWindow.Topmost = true;
- App.MainWindow.WindowState = WindowState.Maximized;
- App.MainWindow.Topmost = false;
- }));
- }
- }
- }).Start();
- });
- }
- /// <summary>
- /// 重新加载授权文件
- /// </summary>
- internal void LoadLicense()
- {
- App.RuntimeInfo.LicenseInfo = LicenseManage.GetLicenseInfo(App.RuntimeInfo.ProductId);
- if (isShutDown || App.RuntimeInfo.LicenseInfo == null) return;
- if (!App.Dispatcher.HasShutdownStarted)
- {
- App.Dispatcher.Invoke(new Action(() =>
- {
- if (App.MainWindow is MainWindow window)
- {
- window.MainWindowViewModel.CopyRightInfo = $"{App.SystemConfig.AuthorInfo}({App.RuntimeInfo.LicenseInfo.LicenseType})";
- }
- }));
- ReportAppInfo(true);
- }
- }
- private DateTime lastReportSuccessTime = DateTime.MinValue;
- private void ReportOnLine()
- {
- if ((DateTime.Now - lastReportSuccessTime).TotalSeconds > 590)
- {
- ReportAppInfo(true);
- }
- }
- private void ReportAppInfo(bool isOnline = true)
- {
- var license = App.RuntimeInfo.LicenseInfo;
- if (license != null && (license.LicenseType == LicenseType.TempLicense || license.LicenseType == LicenseType.Permanentlicense))
- {
- var reportInfo = new
- {
- SessionID = App.RuntimeInfo.SessionId,
- AppName = license?.AppName,
- Version = UidVersion,
- CustomerTag = App.SystemConfig.ComputerTag,
- ComputerId = license?.Computer.ComputerId,
- LicenseId = license?.LicenseId,
- LicenseType = license?.LicenseType.ToString(),
- ActiveTime = license?.ActiveTime,
- ExpireDate = license?.ActiveTime.AddDays(license.ExpireDays),
- TotalOutputPcs = Env.TotalOutputPcs.Value,
- TotalOutputQty = Env.TotalOutputQty.Value,
- IsOnline = isOnline
- };
- if (EicpCoreManage.ReportAppInfo(reportInfo, out var appName))
- {
- lastReportSuccessTime = DateTime.Now;
- App.SystemConfig.ComputerTag = appName;
- }
- }
- }
- private void FalatReport(Exception exception)
- {
- if (isShutDown) return;
- var license = App.RuntimeInfo.LicenseInfo;
- if (license != null && (license.LicenseType == LicenseType.TempLicense || license.LicenseType == LicenseType.Permanentlicense))
- {
- try
- {
- EicpCoreManage.FalatReport(new
- {
- SessionID = App.RuntimeInfo.SessionId,
- AppName = license?.AppName,
- Version = UidVersion,
- ComputerId = license?.Computer?.ComputerId,
- SoftwareID = SoftWareId,
- Customer = System.Windows.Forms.Application.CompanyName,
- Message = exception.Message,
- PowerOnTime = PowerOnTime,
- RunTime = DateTime.Now - PowerOnTime,
- Exception = exception?.ToString()
- });
- }
- catch (Exception ex)
- {
- Log?.Error(ex);
- }
- }
- }
- public bool RestartHost()
- {
- return App.ServiceHost.Restart();
- }
- private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
- {
- Log?.Error(e.Exception);
- e.Handled = true;
- if (!isShutDown)
- {
- FalatReport(e.Exception);
- }
- }
- private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
- {
- FalatReport(e.ExceptionObject as Exception);
- Log?.Fatal(e.ExceptionObject);
- LogManager.Flush(10);
- ExitHandler(e.ExceptionObject.ToString());
- App?.Dispatcher.BeginInvoke(new Action(() =>
- {
- MessageBox.Show(e.ExceptionObject.ToString());
- }));
- }
- /// <summary>
- /// 释放运行时压缩包
- /// </summary>
- private void ReleaseRunTime()
- {
- var runTimeLibDic = new Dictionary<string, string>()
- {
- {"Content.zip","Content" },
- {"EicpWeb.zip","Content" },
- {"EicpCustomer.zip","Content" },
- {"HCNETSDKLib.zip",null },
- {"RunTime.zip",null },
- {"SyntecLib_v4.zip",null},
- {"Fwlib.zip",AppDomain.CurrentDomain.BaseDirectory },
- {"DeviceCfg.zip",null},
- {"x86_x64.zip",null },
- };
- foreach (var item in runTimeLibDic)
- {
- try
- {
- if (System.IO.File.Exists(item.Key))
- {
- ZipHelper.UnZip(item.Key, item.Value);
- FileHelper.DeleteFile(item.Key);
- }
- }
- catch (Exception ex)
- {
- Log.Error(ex);
- }
- }
- }
- private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
- {
- Log?.Fatal(e.Exception);
- FalatReport(e.Exception);
- ExitHandler(e.Exception.Message);
- }
- private void ExitHandler(string exitMsg)
- {
- Plugin.CoreUI.SystemApp.SystemStatictics.Create().AppExit(exitMsg);
- ReportAppInfo(false);
- }
- public void ApplicationExit(int exitCode)
- {
- isShutDown = true;
- evh?.Set();
- evh?.Dispose();
- }
- public void ApplicationDispose(int exitCode)
- {
- isShutDown = true;
- App.ServiceHost?.Stop();
- foreach (var item in Timers)
- {
- item.Dispose();
- }
- var exitReason = "";
- if (ExitCode.ContainsKey(exitCode))
- {
- exitReason = ExitCode[exitCode];
- }
- ExitHandler(exitReason);
- if (Log != null)
- {
- Log.Info($"{App.RuntimeInfo.ProductId}({UidVersion}) is shutdown by {exitReason}");
- SCADA.CommonLib.LoggerHelper.Logger.Dispose();
- }
- }
- public void ApplicationSessionEnding(object sender, SessionEndingCancelEventArgs e)
- {
- Log.Error($"计算机已注销或关闭,原因:{e.ReasonSessionEnding}");
- }
- /// <summary>
- /// 创建一个后台任务
- /// </summary>
- /// <param name="task"></param>
- /// <param name="cycleTime">重复执行间隔 毫秒</param>
- /// <param name="delayTime">延迟时间</param>
- /// <param name="backgroundContinue">当转到后台时继续执行</param>
- /// <param name="taskName"></param>
- public void CreateBackGroundTask(ThreadStart task, int cycleTime, int delayTime = 0, bool backgroundContinue = false, string taskName = null)
- {
- Timers.Add(new AdvanceTimer(task, taskName, cycleTime, delayTime)
- {
- IsBackground = backgroundContinue,
- IsActived = true,
- TimerName = taskName
- });
- }
- private readonly Dictionary<int, string> ExitCode = new Dictionary<int, string>()
- {
- {0,"User Exit"},
- {100,"invalid license"},
- };
- }
- }
|