App.xaml.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. using Microsoft.Win32;
  2. using SWRIS.Core;
  3. using SWRIS.Extensions;
  4. using SWRIS.Models;
  5. using SWRIS.Properties;
  6. using SWRIS.Services;
  7. using System;
  8. using System.Diagnostics;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Threading.Tasks;
  12. using System.Web.Http;
  13. using System.Web.Http.SelfHost;
  14. using System.Windows;
  15. using System.Windows.Threading;
  16. namespace SWRIS
  17. {
  18. /// <summary>
  19. /// App.xaml 的交互逻辑
  20. /// </summary>
  21. public partial class App : Application
  22. {
  23. public static ConfigModel Config { get; set; }
  24. public static TcpServerFrame TcpServer { get; set; }
  25. public static CalibrationCore Calibration { get; set; }
  26. public static DataCenterModel DataCenter { get; set; }
  27. public static HistoryCleanupService HistoryCleanup { get; set; }
  28. public App()
  29. {
  30. //首先注册开始和退出事件
  31. if (!Settings.Default.IsDebug)
  32. {
  33. Startup += new StartupEventHandler(App_Startup);
  34. if (!HslCommunication.Authorization.SetAuthorizationCode("946778b1-967c-4e05-beab-7f47bb248b71"))
  35. {
  36. LogHelper.Info("HSL授权失败");
  37. return;
  38. }
  39. }
  40. //PDF初始化配置
  41. QuestPDF.Settings.License = QuestPDF.Infrastructure.LicenseType.Community;
  42. QuestPDF.Settings.CheckIfAllTextGlyphsAreAvailable = false;
  43. }
  44. private void InitSoftAuthorize()
  45. {
  46. if (!SoftAuth.IsAuthorizeSuccess())
  47. {
  48. SoftAuthDialog authDialog = new SoftAuthDialog();
  49. var result = authDialog.ShowDialog();
  50. if (result != true)
  51. {
  52. Environment.Exit(0);
  53. }
  54. }
  55. }
  56. private static SingleInstanceManager _singleInstanceManager;
  57. public static void SwitchToExistingInstance(string processName)
  58. {
  59. _singleInstanceManager?.SwitchToExistingInstance(processName);
  60. }
  61. protected override void OnStartup(StartupEventArgs e)
  62. {
  63. #region 阻止系统睡眠,阻止屏幕关闭。
  64. SystemSleep.PreventForCurrentThread();
  65. #endregion
  66. #region 避免程序多次启动
  67. _singleInstanceManager = new SingleInstanceManager("SWRIS");
  68. // 检查是否已有实例运行
  69. if (_singleInstanceManager.IsAlreadyRunning())
  70. {
  71. // 切换到已有实例
  72. _singleInstanceManager.SwitchToExistingInstance();
  73. Shutdown();
  74. return;
  75. }
  76. #endregion
  77. Config = ConfigHelper.Read();
  78. if (Config == null)
  79. {
  80. LogHelper.Error("读取配置文件失败");
  81. Environment.Exit(0);
  82. }
  83. if (!Tools.CheckIpAddressExists(Config.IpAddress))
  84. {
  85. MessageBox.Show($"当前在用网卡的IP地址中没有发现[{Config.IpAddress}],请检查网络配置", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
  86. Environment.Exit(0);
  87. }
  88. if (Tools.CheckPortInUse(Config.Port))
  89. {
  90. MessageBox.Show("当前配置的端口已被占用,请更换端口或关闭占用该端口的程序", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
  91. Environment.Exit(0);
  92. }
  93. if (Settings.Default.IsDebug)
  94. {
  95. SetAutoStart(false);
  96. }
  97. else
  98. {
  99. InitSoftAuthorize();
  100. SetAutoStart(true);
  101. // 创建桌面快捷方式
  102. Tools.CreateShortcut(Assembly.GetExecutingAssembly().Location, Config.AppName);
  103. }
  104. // 显示启动画面
  105. var splashScreen = new SplashScreen("Resources/loading.png");
  106. splashScreen.Show(false, true);
  107. Task.Run(async () =>
  108. {
  109. SqLiteBaseRepository.CreateDatabase();
  110. //初始化TcpServer
  111. TcpServer = new TcpServerFrame(Config.IpAddress, Config.Port);
  112. //初始化标定模块
  113. Calibration = new CalibrationCore(Config.Calibration);
  114. //初始化数据中心能模块
  115. DataCenter = new DataCenterModel(Config.Equipments, Config.Calibration.Limits);
  116. //初始化清理计划模块
  117. HistoryCleanup = new HistoryCleanupService();
  118. HistoryCleanup.StartScheduledCleanup();
  119. // 数据加载完成后,在UI线程更新
  120. await Current.Dispatcher.InvokeAsync(() =>
  121. {
  122. splashScreen.Close(TimeSpan.FromMilliseconds(200));
  123. var mainWindow = new MainWindow
  124. {
  125. Height = SystemParameters.PrimaryScreenHeight,
  126. Width = SystemParameters.PrimaryScreenWidth
  127. };
  128. mainWindow.Activate();
  129. mainWindow.Show();
  130. });
  131. });
  132. base.OnStartup(e);
  133. }
  134. public static bool UpdateEquipment(EquipmentModel equipment)
  135. {
  136. if (equipment == null) return false;
  137. var existingEquipment = Config.Equipments.FirstOrDefault(e => e.IpAddress == equipment.IpAddress);
  138. if (existingEquipment == null) return false;
  139. // 更新设备信息
  140. Mapping.AssignFrom(existingEquipment, equipment);
  141. return true;
  142. }
  143. private void StartHttpServer()
  144. {
  145. //添加防火墙8002端口允许出站规则
  146. FirewallHelper.CreateTCPOutRule(Assembly.GetEntryAssembly().Location, remotePorts: "8002");
  147. var config = new HttpSelfHostConfiguration($"http://{Tools.GetIpAddress()}:{8002}");
  148. config.MapHttpAttributeRoutes();
  149. config.Routes.MapHttpRoute(name: "DefaultApi",
  150. routeTemplate: "api/{controller}/{action}",
  151. defaults: new { id = RouteParameter.Optional });
  152. new HttpSelfHostServer(config).OpenAsync();
  153. }
  154. private void App_Startup(object sender, StartupEventArgs e)
  155. {
  156. //UI线程未捕获异常处理事件
  157. DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
  158. //Task线程内未捕获异常处理事件
  159. TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
  160. //非UI线程未捕获异常处理事件
  161. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
  162. }
  163. void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
  164. {
  165. try
  166. {
  167. LogHelper.Error("UI线程异常:" + e.Exception.Message, e.Exception);
  168. }
  169. catch (Exception ex)
  170. {
  171. LogHelper.Error("UI线程异常trycatch:" + ex.Message, ex);
  172. }
  173. finally
  174. {
  175. e.Handled = true;
  176. }
  177. }
  178. void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  179. {
  180. try
  181. {
  182. var exception = e.ExceptionObject as Exception;
  183. if (exception != null)
  184. {
  185. LogHelper.Error("非UI线程发生致命错误", exception);
  186. }
  187. }
  188. catch (Exception ex)
  189. {
  190. LogHelper.Error("非UI线程发生致命错误trycatch", ex);
  191. }
  192. finally
  193. {
  194. //此时程序出现严重异常,将强制结束退出
  195. Current.Shutdown();
  196. Process.Start(ResourceAssembly.Location);//重启软件
  197. }
  198. }
  199. void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
  200. {
  201. try
  202. {
  203. var exception = e.Exception as Exception;
  204. if (exception != null)
  205. {
  206. LogHelper.Error("Task线程异常:" + exception.Message, exception);
  207. }
  208. }
  209. catch (Exception ex)
  210. {
  211. LogHelper.Error("Task线程异常trycatch:" + ex.Message, ex);
  212. }
  213. finally
  214. {
  215. e.SetObserved();
  216. }
  217. }
  218. /// <summary>
  219. /// 修改程序在注册表中的键值
  220. /// </summary>
  221. /// <param name="isAuto">true:开机启动,false:不开机自启</param>
  222. public static void SetAutoStart(bool isAuto, bool showInfo = true)
  223. {
  224. string appName = Config.AppName;
  225. try
  226. {
  227. using (RegistryKey rLocal = Registry.CurrentUser)
  228. using (RegistryKey rRun = rLocal.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true))
  229. {
  230. if (rRun == null) return;
  231. if (isAuto)
  232. {
  233. string currentPath = Process.GetCurrentProcess().MainModule.FileName;
  234. object existingValue = rRun.GetValue(appName);
  235. // 只有当值不存在或路径不同时才更新
  236. if (existingValue == null || !currentPath.Equals(existingValue.ToString(), StringComparison.OrdinalIgnoreCase))
  237. {
  238. rRun.SetValue(appName, currentPath);
  239. }
  240. }
  241. else
  242. {
  243. // 如果存在则删除
  244. if (rRun.GetValue(appName) != null)
  245. {
  246. rRun.DeleteValue(appName, false);
  247. }
  248. }
  249. }
  250. }
  251. catch (UnauthorizedAccessException)
  252. {
  253. if (showInfo)
  254. {
  255. MessageBox.Show("需要管理员权限才能修改开机启动设置", "权限不足");
  256. }
  257. }
  258. catch (Exception ex)
  259. {
  260. if (showInfo)
  261. {
  262. MessageBox.Show($"修改开机启动设置时出错: {ex.Message}", "错误");
  263. }
  264. }
  265. }
  266. public static void RestartApplication()
  267. {
  268. _singleInstanceManager?.Dispose();
  269. // 获取当前进程的可执行文件路径
  270. string currentExecutablePath = Process.GetCurrentProcess().MainModule.FileName;
  271. // 启动新的进程实例
  272. Process.Start(currentExecutablePath);
  273. // 关闭当前应用程序
  274. Current.Shutdown();
  275. }
  276. protected override void OnExit(ExitEventArgs e)
  277. {
  278. TcpServer?.Dispose();
  279. Calibration?.Dispose();
  280. HistoryCleanup?.Dispose();
  281. _singleInstanceManager?.Dispose();
  282. // 恢复此线程曾经阻止的系统休眠和屏幕关闭。
  283. SystemSleep.RestoreForCurrentThread();
  284. base.OnExit(e);
  285. }
  286. }
  287. }