Blame view

HHECS.DAQClient/App.xaml.cs 5.57 KB
唐召明 authored
1
2
3
4
using FreeSql;
using HHECS.DAQClient.Common;
using HHECS.DAQClient.Services;
using HHECS.DAQClient.ViewModel;
唐召明 authored
5
using HHECS.DAQClient.ViewModel.CommunicationVM;
唐召明 authored
6
using HHECS.DAQClient.ViewModel.EquipmentPropVM;
唐召明 authored
7
using HHECS.DAQClient.ViewModel.EquipmentVM;
唐召明 authored
8
9
10
11
12
13
14
15
16
using Microsoft.Extensions.DependencyInjection;
using NLog;
using System.Configuration;
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using System.Windows.Threading;
using MessageBox = HandyControl.Controls.MessageBox;
唐召明 authored
17
namespace HHECS.DAQClient
唐召明 authored
18
19
20
21
22
23
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
唐召明 authored
24
25
        private static Mutex mutex;
唐召明 authored
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
        private readonly Logger _log = LogManager.GetCurrentClassLogger();

        public App()
        {
            Services = ConfigureServices();
            InitializeComponent();
        }

        /// <summary>
        /// Gets the current <see cref="App"/> instance in use
        /// </summary>
        public new static App Current => (App)Application.Current;

        /// <summary>
        /// Gets the <see cref="IServiceProvider"/> instance to resolve application services.
        /// </summary>
        public IServiceProvider Services { get; }

        /// <summary>
        /// Configures the services for the application.
        /// </summary>
47
        private static ServiceProvider ConfigureServices()
唐召明 authored
48
49
        {
            var services = new ServiceCollection();
唐召明 authored
50
            var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
唐召明 authored
51
52
53
            IFreeSql fsql = new FreeSqlBuilder()
                .UseConnectionString(DataType.Sqlite, connectionString)
                //.UseMonitorCommand(cmd => Console.WriteLine($"Sql:{cmd.CommandText}"))//监听SQL语句
54
                .UseAutoSyncStructure(false) //自动同步实体结构到数据库,FreeSql不会扫描程序集,只有CRUD时才会生成表。
唐召明 authored
55
                .Build();
唐召明 authored
56
唐召明 authored
57
            services.AddSingleton(fsql);
唐召明 authored
58
唐召明 authored
59
60
61
            services.AddHttpClient<HttpService>().ConfigureHttpClient(client =>
            {
                _ = bool.TryParse(ConfigurationManager.AppSettings["IsProductionEnvironment"], out var isProductionEnvironment);
62
                var clientId = ConfigurationManager.AppSettings["ClientId"];
唐召明 authored
63
64
65
66
                var urlConfig = ConfigurationManager.AppSettings[isProductionEnvironment ? "ProductionAPI" : "TestAPI"]!;
                client.BaseAddress = new Uri(urlConfig);
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("User-Agent", "HHECS.DAQClient");
67
                client.DefaultRequestHeaders.Add("ClientId", clientId);
唐召明 authored
68
            });
唐召明 authored
69
70
71
72
73
74
75
            services.AddSingleton<CenterService>();

            // DataAnalysis
            //services.AddScoped<IAnalysis, FanucAnalysis>();

            // Viewmodels
            services.AddTransient<MainVM>();
唐召明 authored
76
            services.AddTransient<EquipmentVM>();
77
            services.AddTransient<EquipmentAddOrEditVM>();
唐召明 authored
78
唐召明 authored
79
80
            services.AddTransient<EquipmentPropMonitorVM>();
唐召明 authored
81
            services.AddTransient<CommunicationVM>();
82
            services.AddTransient<CommunicationAddOrEditVM>();
唐召明 authored
83
84

            services.AddTransient<EquipmentDataQueueVM>();
85
            services.AddTransient<PrivacyInfoVM>();
唐召明 authored
86
唐召明 authored
87
88
89
90
91
92
            return services.BuildServiceProvider();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            //UI线程未捕获异常处理事件(UI主线程)
唐召明 authored
93
            DispatcherUnhandledException += App_DispatcherUnhandledException;
唐召明 authored
94
95
96
97
98
99
            //UI线程未捕获异常处理事件(例如自己创建的一个子线程)
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            //Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            var process = Process.GetProcessesByName($"{Assembly.GetExecutingAssembly().GetName().Name}");
唐召明 authored
100
            _ = bool.TryParse(ConfigurationManager.AppSettings["IsProductionEnvironment"], out var isProductionEnvironment);
唐召明 authored
101
            mutex = new Mutex(false, $"{process}_{ConfigurationManager.AppSettings["ClientId"]}_{isProductionEnvironment}");
唐召明 authored
102
103

            if (!mutex.WaitOne(TimeSpan.Zero, true))
唐召明 authored
104
            {
唐召明 authored
105
106
107
                MessageBox.Warning("应用程序已在运行!");
                Shutdown();
                return;
唐召明 authored
108
            }
唐召明 authored
109
110
111
112
113
114

            Application.Current.Exit += (s, args) =>
            {
                mutex.ReleaseMutex();
                mutex.Close();
            };
唐召明 authored
115
116
        }
唐召明 authored
117
        private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
唐召明 authored
118
119
120
        {
            Exception ex = e.Exception;
            _log.Debug($"UI线程异常{ex}");
121
            e.SetObserved();
唐召明 authored
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is Exception ex)
            {
                _log.Debug($"非UI线程异常{ex}", LogType.Debug);
            }
        }

        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            Exception ex = e.Exception;
            string msg = string.Format("{0}\n\n{1}", ex.Message, ex.StackTrace);//异常信息  调用堆栈信息
            MessageBox.Error("UI线程异常", msg);
            _log.Debug($"UI线程异常{ex}");
            e.Handled = true;//表示异常已处理,可以继续运行
        }
    }
}