123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356 |
- using System;
- using System.Diagnostics;
- using System.IO;
- using System.Windows;
- using System.Windows.Threading;
- using vStation.Module.Login;
- using vStation.Module.Status;
- using vStation.Module.SystemSetting;
- using vStation.Module.Workstation;
- using System.Runtime.InteropServices;
- using vStation.Infrastructure;
- using vStation.Utilities.Report;
- using Vinno.IUS.Common.Utilities;
- using System.Threading.Tasks;
- using vStation.PipeLine;
- using vStation.URMStationRelevant;
- using Newtonsoft.Json;
- using System.Collections.Generic;
- using URMServiceConfig;
- using JsonRpcLite.Rpc;
- using JsonRpcLite.Network;
- using WingInterfaceLibrary.Interface;
- using JsonRpcLite.Services;
- using NPOI.SS.Formula.Functions;
- using System.Threading;
- namespace vStation
- {
- /// <summary>
- /// App.xaml 的交互逻辑
- /// </summary>
- public partial class App : Application
- {
- /// <summary>
- /// 该函数将创建指定窗口的线程设置到前台,并且激活该窗口。键盘输入转向该窗口,并为用户改各种可视的记号。系统给创建前台窗口的线程分配的权限稍高于其他线程。
- /// </summary>
- /// <param name="hWnd">将被激活并被调入前台的窗口句柄。</param>
- /// <returns>如果窗口设入了前台,返回值为非零;如果窗口未被设入前台,返回值为零。</returns>
- [DllImport("User32.dll")]
- private static extern bool SetForegroundWindow(IntPtr hWnd);
- [DllImport("User32.dll")]
- private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
- private DefaultLogEngine _defaultLogEngine;
- private UserLogEngine _userLogEngine;
- protected override void OnStartup(StartupEventArgs e)
- {
- CheckedOpenRepeatedly(e.Args);
- //NetworkException.RegisterConverter(new NetworkExceptionConverter());
- XmlHelper.RegisterXmlEngine(new XmlEngine());
- InitializeLanguage();
- IoHelper.RegisterEngine(new IoEngine(AppDomain.CurrentDomain.BaseDirectory));
- _defaultLogEngine = new DefaultLogEngine();
- _userLogEngine = new UserLogEngine();
- UserLogger.RegisterEngine(_userLogEngine);
- Logger.RegisterEngine(_defaultLogEngine);
- AppDomain.CurrentDomain.UnhandledException += OnDomainOnUnhandledException;
- Current.DispatcherUnhandledException += OnDispatcherUnhandledException;
- Current.Exit += OnExit;
-
- AppManager.Instance.RegisterFunction(typeof(IDbService), new DbService());
- AppManager.Instance.RegisterFunction(typeof(Module.Login.ILoginService), new LoginService());
- AppManager.Instance.RegisterFunction(typeof(ISystemSettingManager), new SystemSettingManager());
- AppManager.Instance.RegisterFunction(typeof(ISystemSettingExamPointFee), new SystemSettingExamPointFee());
- Config.IsURMStation = true;
- if (Config.IsURMStation)
- {
- IntiURMStation();
- }
- base.OnStartup(e);
- }
- private void IntiURMStation()
- {
- // "E:\\FISShellRev\\fis\\fis\\fis\\bin\\Debug\\net6.0";
- URMConfig.URMWorkingDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "URMWorkStation") ;
- if (!Directory.Exists(URMConfig.StorageDirectory))
- {
- Directory.CreateDirectory(URMConfig.StorageDirectory);
- }
- RootObject root=null;
- var isSingle= URMConfig.GetIsSingleMode();
- if (File.Exists(URMConfig.ConfigPath))
- {
- try
- {
- var data = File.ReadAllText(URMConfig.ConfigPath);
- root = JsonConvert.DeserializeObject<RootObject>(data);
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"Error happened while init urm station{ex}");
- }
- }
- else {
- if (root == null)
- {
- root = new RootObject();
- root.flyinsonoServers = new List<string>();
- root.flyinsonoServers.Add("https://bj.flyinsono.com");
- root.common = new Common();
- root.server = new URMServiceConfig.Server();
- root.common.dateTimeFormat = "yyyy-MM-dd HH:mm";
- root.server.current = "http://127.0.0.1:8303";
- root.server.optionSource = new List<string>();
- root.server.optionSource.Add("http://127.0.0.1:8303");
- }
- }
- URMConfig.RPCAddress = root.server.current;
- if (isSingle)
- {
- root.server.current = "http://127.0.0.1:8303";
- var txt = JsonConvert.SerializeObject(root);
- URMConfig.ServerStatusChanged += OnServerStatusChanged;
- URMConfig.ServerStatus = ServerStatus.NeedStartServer;
- File.WriteAllText(URMConfig.ConfigPath, txt);
- }
- }
- private void OnServerStatusChanged(object sender, ServerStatus e)
- {
- if (e == ServerStatus.NeedStartServer)
- {
- GetServerState(URMConfig.RPCAddress);
- return;
- }
- if (e == ServerStatus.Starting)
- {
- ControlServer(true);
- return;
- }
- Logger.WriteLineVerbose($"Server starting result is:--- {e}");
- }
- private void ControlServer(bool isOpen, bool isRestart = false)
- {
- Logger.WriteLineInfo($"Server start batch file not exist!");
- var targetPath = isOpen ? URMConfig.StartServerBatchFile : URMConfig.CloseServerBatchFile;
- if (!File.Exists(targetPath))
- {
- Logger.WriteLineError($"Server start batch file not exist!");
- return;
- }
- ProcessStartInfo processInfo2 = new ProcessStartInfo(targetPath)
- {
- CreateNoWindow = true,
- UseShellExecute = false,
- RedirectStandardError = true,
- RedirectStandardOutput = true,
- Verb = "runas",
- // 不使用操作系统外壳程序启动进程
- };
- Process.Start(processInfo2);
-
- Task.Run
- (() =>
- {
- if (isOpen)
- {
- int count = 0;
- while (URMConfig.ServerStatus==ServerStatus.Starting)
- {
- count++;
- Thread.Sleep(2000);
- GetServerState(URMConfig.RPCAddress);
- if (count == 30)
- {
- URMConfig.ServerStatus = ServerStatus.StartingTimeout;
- break;
- }
- }
- }
-
- });
- }
- private void GetServerState(string address)
- {
- Task.Run(async () => {
- var isConnected = await ValidateServerAddress(address);
- if (isConnected)
- {
- URMConfig.ServerStatus = ServerStatus.Started;
- }
- else
- {
- URMConfig.ServerStatus=ServerStatus.Starting;
- }
- });
- }
- private async Task<bool> ValidateServerAddress(string address)
- {
- try
- {
- var client = new JsonRpcClient();
- var clientEngine = new JsonRpcHttpClientEngine(address);
- clientEngine.Timeout = 1000;
- client.UseEngine(clientEngine);
- var loginService = client?.CreateProxy<WingInterfaceLibrary.Interface.ILoginService>();
- if (loginService == null)
- {
- return false;
- }
-
- var result = await loginService.CommonLoginAsync(new WingInterfaceLibrary.Request.User.CommonLoginRequest()
- {
- });
- if (result == null)
- {
- return false;
- }
- if (result.LoginState == WingInterfaceLibrary.Enum.LoginStateEnum.SignOrLoginFail ||
- result.LoginState == WingInterfaceLibrary.Enum.LoginStateEnum.PasswordIncorrect
- )
- {
- return true;
- }
- }
- catch (RpcException ex)
- {
- return true;
- }
- catch (Exception ex)
- {
-
- return false;
- }
- finally
- {
- }
- return true;
- }
- /// <summary>
- /// 判断是否重复打开
- /// </summary>
- /// <param name="checkedIndex">判断次数,每次间隔1秒,判断结束,窗口依旧存在,则取消此次运行</param>
- private void CheckedOpenRepeatedly(string[] Args = null)
- {
- var thisProcess = Process.GetCurrentProcess();
- foreach (var item in Process.GetProcessesByName(thisProcess.ProcessName))
- {
- if (thisProcess.Id != item.Id)
- {
- if ((Args != null && Args.Length > 0 && Args[0] == "RestoreData")||string.IsNullOrEmpty(item.MainWindowTitle))
- {
- item.Close();
- }
- else
- {
- ShowWindow(item.MainWindowHandle, 9);
- SetForegroundWindow(item.MainWindowHandle);
- Current.Shutdown();
- }
- }
- }
- }
- private void OnExit(object sender, ExitEventArgs e)
- {
- _defaultLogEngine.Dispose();
- _userLogEngine.Dispose();
- var thisProcess = Process.GetCurrentProcess();
- thisProcess.Kill();
- }
-
- private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
- {
- Logger.WriteLineError($"Unhandled exception:{e.Exception}");
- e.Handled = true;
- ShowExceptionWindow(e.Exception.Message);
- }
- private void OnDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
- {
- Logger.WriteLineError($"Unhandled exception:{e.ExceptionObject}");
- var exception = e.ExceptionObject as Exception;
- if (exception == null)
- {
- ShowExceptionWindow(e.ExceptionObject.ToString());
- }
- else
- {
- ShowExceptionWindow(exception.ToString());
- }
- }
- private void ShowExceptionWindow(string exceptionMessage)
- {
- var statusService = AppManager.Instance.GetFunction<IStatusService>();
- var popupInfo = new PopupInfo(TranslateHelper.Translate("Error"), exceptionMessage, PopupIconType.Error);
- statusService?.ShowPopup(popupInfo);
- }
- private void InitializeLanguage()
- {
- var assemblyName = GetType().Assembly.GetName().Name;
- foreach (var supportedLanguage in TranslateHelper.SupportedLanguages)
- {
- var resourceName = $"{assemblyName}.Languages.{supportedLanguage}.json";
- using (var languageStream = GetType().Assembly.GetManifestResourceStream(resourceName))
- {
- if (languageStream != null)
- {
- var reader = new StreamReader(languageStream);
- var content = reader.ReadToEnd();
- TranslateHelper.AddLanguageResource(supportedLanguage, content);
- }
- }
- }
- }
- }
- public class RootObject
- {
- public Common common { get; set; }
- public URMServiceConfig.Server server { get; set; }
- public List<string> flyinsonoServers { get; set; }
- }
- public class Common
- {
- public string dateTimeFormat { get; set; }
- }
- }
- namespace URMServiceConfig
- {
- public class Server
- {
- public string current { get; set; }
- public List<string> optionSource { get; set; }
- }
- }
|