电子药箱通讯服务端
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

App.xaml.cs 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. using Microsoft.EntityFrameworkCore;
  2. using Microsoft.Extensions.Configuration;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using Prism.Ioc;
  5. using Prism.Modularity;
  6. using Prism.Unity;
  7. using Rdh.ElectronicMedicineKit.EntityFrameworkCore;
  8. using Rdh.SocketServer.Client.BLL;
  9. using Rdh.SocketServer.Client.Models;
  10. using Rdh.SocketServer.Client.MQ;
  11. using Rdh.SocketServer.Client.Views;
  12. using Serilog;
  13. using Serilog.Formatting.Compact;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Diagnostics;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Text;
  20. using System.Threading.Tasks;
  21. using System.Windows;
  22. using TouchSocket.Core.Config;
  23. using TouchSocket.Core.Dependency;
  24. using TouchSocket.Core.Plugins;
  25. using TouchSocket.Sockets;
  26. using Unity;
  27. using Unity.Microsoft.DependencyInjection;
  28. namespace Rdh.SocketServer.Client
  29. {
  30. /// <summary>
  31. /// Interaction logic for App.xaml
  32. /// </summary>
  33. public partial class App : PrismApplication
  34. {
  35. public App()
  36. {
  37. }
  38. protected override void OnStartup(StartupEventArgs e)
  39. {
  40. //限制程序单实例运行
  41. if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
  42. {
  43. Application.Current.Shutdown();
  44. return;
  45. }
  46. RegisterEvents();
  47. base.OnStartup(e);
  48. }
  49. protected override Window CreateShell()
  50. {
  51. return Container.Resolve<MainWindowView>();
  52. }
  53. protected override void OnInitialized()
  54. {
  55. base.OnInitialized();
  56. }
  57. protected override void RegisterTypes(IContainerRegistry containerRegistry)
  58. {
  59. //containerRegistry.RegisterForNavigation<MainWindowView>();
  60. }
  61. protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
  62. {
  63. }
  64. protected override IContainerExtension CreateContainerExtension()
  65. {
  66. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  67. // 配置日志文件
  68. Log.Logger = new LoggerConfiguration()
  69. .MinimumLevel.Debug()
  70. .Enrich.FromLogContext()
  71. .WriteTo.Async(c => c.File(
  72. new CompactJsonFormatter(),
  73. path: Environment.GetEnvironmentVariable("RDH_LOG_PATH") ?? "logs//Log.txt",
  74. rollingInterval: RollingInterval.Day,
  75. retainedFileCountLimit: 60))
  76. #if DEBUG
  77. .WriteTo.Console()
  78. #endif
  79. .CreateLogger();
  80. Log.Information("Starting Rdh.SocketServer Client.");
  81. // 实例化Services集合
  82. var services = new ServiceCollection();
  83. // 加载配置文件
  84. var config = new ConfigurationBuilder()
  85. .SetBasePath(Directory.GetCurrentDirectory())
  86. .AddJsonFile("appsettings.json", false, true)
  87. .Build();
  88. // 注册配置文件服务
  89. services.AddSingleton<IConfiguration>(config);
  90. //注册日志文件服务
  91. services.AddLogging(option => option.AddSerilog());
  92. var connectionStrings = config.GetSection("DataBaseConnectStrings").Get<List<DataBaseConnectString>>();
  93. services.AddDbContext<ApplicationDbContext>(options =>
  94. {
  95. options.UseSqlite(connectionStrings.First(x => x.DbType == DbTypes.Sqlite).ConnectionString, b => b.MigrationsAssembly("Rdh.SocketServer.Client"));
  96. options.UseLazyLoadingProxies();
  97. options.EnableSensitiveDataLogging();
  98. });
  99. ShouShuShiUtility.ConnectionString = connectionStrings.FirstOrDefault(x => x.Name == "ShouShuShi")?.ConnectionString;
  100. Serilog.Log.Debug("设置手术室数据库:" + ShouShuShiUtility.ConnectionString);
  101. MQService.Singleton.EleMedKitCabinetNodeName = config.GetSection("EleMedKitCabinetMQNodeName")?.Value;
  102. String? state = MQService.Singleton.Init();
  103. Log.Information("初始化MQservice:" + (state == null ? "ok" : state));
  104. #region MyRegion
  105. //connectionStrings.ForEach(conn =>
  106. //{
  107. // switch (conn.Name)
  108. // {
  109. // default:
  110. // services.AddDbContext<ApplicationDbContext>(options =>
  111. // {
  112. // switch (conn.DbType)
  113. // {
  114. // case DbTypes.Oracle:
  115. // break;
  116. // case DbTypes.Mysql:
  117. // //options.UseMySQL(conn.ConnectionString/*, b => b.MigrationsAssembly("Rdh.HempCart.WebApi")*/);
  118. // break;
  119. // case DbTypes.SQLServer:
  120. // break;
  121. // case DbTypes.Sqlite:
  122. // break;
  123. // default:
  124. // break;
  125. // }
  126. // });
  127. // break;
  128. // }
  129. //});
  130. #endregion
  131. // 读取TcpService服务列表 并注册配置相应服务
  132. var tcpServices = config.GetSection("TcpServers").Get<List<TcpServiceInfo>>();
  133. if (tcpServices.Any())
  134. {
  135. tcpServices.ForEach(info =>
  136. {
  137. var service = new TcpService();
  138. service.Setup(new TouchSocketConfig()//载入配置
  139. .SetListenIPHosts(new IPHost[] { new IPHost(info.Port) })
  140. .SetMaxCount(10000)
  141. .SetThreadCount(10)
  142. .SetServerName(info.ServerName)
  143. .ConfigurePlugins(a => a.UseReconnection(5, true, 1000)))
  144. .Start();
  145. if (info.ServerName == "ElectronicMedicineKit")
  146. service.Config.SetDataHandlingAdapter(() => new EleMedKitServerAdapter());
  147. services.AddSingleton<ITcpService>(service);
  148. });
  149. }
  150. // 实例化Unity Ioc容器
  151. var container = new UnityContainer();
  152. // 将服务集合注册进容器
  153. container.BuildServiceProvider(services);
  154. return new UnityContainerExtension(container);
  155. }
  156. #region 日志相关
  157. private void RegisterEvents()
  158. {
  159. TaskScheduler.UnobservedTaskException += this.TaskScheduler_UnobservedTaskException;
  160. DispatcherUnhandledException += App_DispatcherUnhandledException;
  161. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  162. }
  163. /// <summary>
  164. /// Task线程内未捕获异常处理事件
  165. /// </summary>
  166. /// <param name="sender"></param>
  167. /// <param name="e"></param>
  168. private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
  169. {
  170. try
  171. {
  172. if (e.Exception is Exception exception)
  173. {
  174. HandleException(exception);
  175. }
  176. }
  177. catch (Exception ex)
  178. {
  179. HandleException(ex);
  180. }
  181. finally
  182. {
  183. e.SetObserved();
  184. }
  185. }
  186. /// <summary>
  187. /// 非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
  188. /// </summary>
  189. /// <param name="sender"></param>
  190. /// <param name="e"></param>
  191. private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  192. {
  193. try
  194. {
  195. if (e.ExceptionObject is Exception exception)
  196. {
  197. HandleException(exception);
  198. }
  199. }
  200. catch (Exception ex)
  201. {
  202. HandleException(ex);
  203. }
  204. finally
  205. {
  206. //ignore
  207. }
  208. }
  209. /// <summary>
  210. /// UI线程未捕获异常处理事件(UI主线程)
  211. /// </summary>
  212. /// <param name="sender"></param>
  213. /// <param name="e"></param>
  214. private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
  215. {
  216. try
  217. {
  218. HandleException(e.Exception);
  219. }
  220. catch (Exception ex)
  221. {
  222. HandleException(ex);
  223. }
  224. finally
  225. {
  226. e.Handled = true;
  227. }
  228. }
  229. /// <summary>
  230. /// 日志记录
  231. /// </summary>
  232. /// <param name="ex"></param>
  233. private void HandleException(Exception ex)
  234. {
  235. Log.Error(ex, ex.Message);
  236. }
  237. #endregion
  238. }
  239. }