App.xaml.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. using System.Runtime.InteropServices;
  2. using System.Threading.Tasks;
  3. using System.Windows.Forms;
  4. using GalaSoft.MvvmLight.Threading;
  5. using Muchinfo.MTPClient.CustomException;
  6. using Muchinfo.MTPClient.Infrastructure.Helpers;
  7. using Muchinfo.MTPClient.Infrastructure.LinkProxy;
  8. using Muchinfo.MTPClient.Infrastructure.MessageBox;
  9. using Muchinfo.MTPClient.Infrastructure.Utilities;
  10. using Muchinfo.MTPClient.Resources;
  11. using Muchinfo.MTPClient.UI;
  12. using Muchinfo.MTPClient.UI.Utilities;
  13. using Muchinfo.MTPClient.UI.Views;
  14. using Muchinfo.PC.Common.Extensions;
  15. using Muchinfo.PC.Common.Helpers;
  16. using System;
  17. using System.Diagnostics;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Windows;
  21. using Microsoft.Win32;
  22. using Muchinfo.MTPClient.Adapter.Utilities;
  23. using Muchinfo.MTPClient.Data.Enums;
  24. using Muchinfo.MTPClient.Data.Model.Account;
  25. using Application = System.Windows.Application;
  26. namespace Muchinfo.MTPClient
  27. {
  28. /// <summary>
  29. /// App.xaml 的交互逻辑
  30. /// </summary>
  31. public partial class App : Application
  32. {
  33. #region Fields
  34. private System.Threading.Mutex _mutexApplication;
  35. #endregion
  36. /// <summary>
  37. /// Initializes static members of the <see cref="App"/> class.
  38. /// </summary>
  39. static App()
  40. {
  41. CopyLibsByOS();
  42. DispatcherHelper.Initialize();
  43. ViewModelLocator.Initialize();
  44. }
  45. /// <summary>
  46. /// Initializes a new instance of the <see cref="App"/> class.
  47. /// </summary>
  48. public App()
  49. {
  50. this.DispatcherUnhandledException += App_DispatcherUnhandledException;
  51. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  52. ////初始化CEF浏览器
  53. //InitialCEF();
  54. //注册账号变更,修改MessageHead的AccountID
  55. MessengerHelper.DefaultRegister<TradeAccount>(this, MessengerTokens.UpdateTradeAccount, (account) =>
  56. {
  57. ProtoBufHelper.Head.AccountID = UserManager.CurrentTradeAccount.FundsAccountId;
  58. });
  59. }
  60. /// <summary>
  61. /// 引发 <see cref="E:System.Windows.Application.Startup" /> 事件。
  62. /// </summary>
  63. /// <param name="e">一个包含事件数据的 <see cref="T:System.Windows.StartupEventArgs" />。</param>
  64. protected override void OnStartup(StartupEventArgs e)
  65. {
  66. //EntrustOrderFrame entrust = new EntrustOrderFrame();
  67. //entrust.ShowDialog();
  68. //读取系统配置
  69. ApplicationParameter.InitializeSystemConfig();
  70. // 风管云平台服务地址
  71. ApplicationParameter.UpdateErmcpParamete();
  72. base.OnStartup(e);
  73. ApplicationParameter.LoginGuid = System.Guid.NewGuid().ToString();
  74. ApplicationParameter.ShowChart = 1;
  75. var lastLoginUser = UserManager.GetLastLoginUser();
  76. ////加载资源
  77. //Client_Resource.Resource(new MuchInfoResourceManager());
  78. //ErrorResources.Resource(new ErrorResourceManager());
  79. this.ShutdownMode = ShutdownMode.OnMainWindowClose;
  80. /// RegChartComModules();
  81. bool runApplication;
  82. if (e.Args.Contains(WindowHelper.restratCommand))
  83. {
  84. runApplication = true;
  85. }
  86. else
  87. {
  88. _mutexApplication = new System.Threading.Mutex(true,
  89. Process.GetCurrentProcess().MainModule.FileName.Replace("\\", string.Empty), out runApplication);
  90. }
  91. //允许多实例
  92. runApplication = true;
  93. if (runApplication)
  94. {
  95. #region MyRegion
  96. try
  97. {
  98. MuchinfoException.InitErrorResx(); ///初始化错误资源
  99. ConstResxManager.InitConstResx(UserManager.UserDataFolder); ///常量资源
  100. ConfigParamResxManager.InitConfigParamResx(UserManager.UserDataFolder);
  101. MarketResxManager.InitMarketResx(UserManager.UserDataFolder);
  102. MenuResxManager.InitMenuResx(UserManager.UserDataFolder);
  103. GoodsResxManager.InitGoodsResx(UserManager.UserDataFolder);
  104. DeliveryResxManager.InitDeliveryResx(UserManager.UserDataFolder);
  105. RiskMsgResxManager.InitRiskMsgResx(UserManager.UserDataFolder);
  106. TradeDateResxManager.InitTradeDateResx(UserManager.UserDataFolder);
  107. LastUpdateTimeManager.InitLastUpdateTimeType(); ///初始化最后更新时间列表
  108. }
  109. catch (Exception ex)
  110. {
  111. LogHelper.WriteError(typeof(App), ex.ToString());
  112. }
  113. #endregion
  114. var login = new LoginView_1(); // new LoginNewView();
  115. this.MainWindow = login;
  116. login.Show();
  117. if (!IsRun() && !string.IsNullOrWhiteSpace(ApplicationParameter.UpdateAddress))
  118. {
  119. //todo: 开发期间注释升级
  120. string fileName = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory,
  121. "Client.Update.exe");
  122. var arguments = string.Format("{0},{1}", ApplicationParameter.UpdateAddress,
  123. lastLoginUser == null ? string.Empty : lastLoginUser.MemberId);
  124. Process.Start(fileName, arguments);
  125. }
  126. }
  127. else
  128. { //同一安装目录的程序只允许运行单个实例!
  129. MessageBoxHelper.ShowInfo(null, Client_Resource.APP_OnlySingleExe, Client_Resource.APP_Tips, true);
  130. WindowHelper.RerunApplication(false);
  131. }
  132. }
  133. /// <summary>
  134. /// 引发 <see cref="E:System.Windows.Application.Exit" /> 事件。
  135. /// </summary>
  136. /// <param name="e">一个包含事件数据的 <see cref="T:System.Windows.ExitEventArgs" />。</param>
  137. protected override void OnExit(ExitEventArgs e)
  138. {
  139. try
  140. {
  141. if (_mutexApplication != null)
  142. {
  143. _mutexApplication.ReleaseMutex();
  144. }
  145. ViewModelLocator.Cleanup();
  146. //释放链路对象
  147. LinkManager.Instance.Dispose();
  148. }
  149. catch (Exception ex)
  150. {
  151. }
  152. finally
  153. {
  154. ////关闭CEF浏览器
  155. //CefRuntime.Shutdown();
  156. base.OnExit(e);
  157. Environment.Exit(0);
  158. }
  159. }
  160. #region Exception Handle
  161. /// <summary>
  162. /// 处理Domain异常
  163. /// </summary>
  164. /// <param name="sender">The source of the event.</param>
  165. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  166. private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  167. {
  168. try
  169. {
  170. var muchinfoEx = e.ExceptionObject as MuchinfoException;
  171. if (muchinfoEx != null)
  172. {
  173. HandleException(muchinfoEx);
  174. }
  175. else if (e.ExceptionObject is Exception)
  176. {
  177. HandleException(e.ExceptionObject as Exception);
  178. }
  179. }
  180. catch (Exception ex)
  181. {
  182. HandleException(ex);
  183. }
  184. }
  185. /// <summary>
  186. /// 处理Dispatcher线程异常
  187. /// </summary>
  188. /// <param name="sender">The source of the event.</param>
  189. /// <param name="e">The <see cref="System.Windows.Threading.DispatcherUnhandledExceptionEventArgs"/> instance containing the event data.</param>
  190. private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
  191. {
  192. try
  193. {
  194. var muchinfoEx = e.Exception as MuchinfoException;
  195. if (muchinfoEx == null)
  196. {
  197. HandleException(e.Exception);
  198. }
  199. else
  200. {
  201. HandleException(muchinfoEx);
  202. }
  203. e.Handled = true;
  204. }
  205. catch (Exception ex)
  206. {
  207. HandleException(new MuchinfoException(ExceptionManager.UnknownClientErrorCode, ex));
  208. }
  209. }
  210. /// <summary>
  211. /// 显示预期的错误
  212. /// </summary>
  213. /// <param name="e"></param>
  214. private void HandleException(MuchinfoException e)
  215. {
  216. MessageBoxHelper.ShowInfo(e.Message, Client_Resource.Bank_ErrotTips);
  217. }
  218. /// <summary>
  219. /// Handles the exception.
  220. /// </summary>
  221. /// <param name="e">The e.</param>
  222. private void HandleException(Exception e)
  223. {
  224. #region 暂时不显示错误内容
  225. //MessageBoxSend mbs = new MessageBoxSend()
  226. // {
  227. // WindowStartupLocation = WindowStartupLocation.CenterScreen,
  228. // };
  229. //mbs.DataContext = new MessageBoxSendViewModel(e.ToString());
  230. //var viewModel = mbs.DataContext as MessageBoxSendViewModel;
  231. //mbs.ShowDialog();
  232. //if (mbs.DialogResult == true && viewModel != null)
  233. //{
  234. // string Error = "";
  235. // if (
  236. // !MailSendHelper.MailSend(ApplicationParameter.ToAddress, "ClientErrorReport@163.com", "1qazxsw2",
  237. // "smtp.163.com", 25, ApplicationParameter.TradeSystemName,
  238. // ApplicationParameter.ExchangeName + ApplicationParameter.Version,
  239. // e.ToString() + Environment.NewLine + viewModel.UserInfo, string.Empty, out Error)) ;
  240. //}
  241. ////写错误日志
  242. //LogHelper.WriteError(typeof(App), e.ToString());
  243. #endregion
  244. // string Error = "";
  245. try
  246. {
  247. //MailSendHelper.MailSend(ApplicationParameter.ToAddress, "ClientErrorReport@163.com", "1qazxsw2",
  248. // "smtp.163.com", 25, ApplicationParameter.TradeSystemName,
  249. // ApplicationParameter.ExchangeName + ApplicationParameter.Version,
  250. // e.ToString() + Environment.NewLine, string.Empty, out Error);
  251. LogHelper.WriteError(typeof(App), e.ToString());
  252. }
  253. catch (Exception ex)
  254. {
  255. LogHelper.WriteError(typeof(App), ex.ToString());
  256. }
  257. }
  258. #endregion
  259. #region 更新
  260. private readonly bool isUpdate = false;
  261. /// <summary>
  262. /// 更新程序是否正在运行
  263. /// </summary>
  264. /// <returns></returns>
  265. private bool IsRun()
  266. {
  267. bool bo = false;
  268. var process = Process.GetProcessesByName("Muchinfo.MTPClient.Update");
  269. if (process.Length > 0)
  270. {
  271. bo = true;
  272. }
  273. return bo;
  274. }
  275. #endregion
  276. #region Copy Sqlite vc++库
  277. /// <summary>
  278. /// 根据操作系统COPY依赖库
  279. /// </summary>
  280. private static void CopyLibsByOS()
  281. {
  282. try
  283. {
  284. //// 项目编译成anycpu,按操作系统类型COPY
  285. //// sqliteFilePath = Path.Combine(sqliteFilePath, is64 ? "x64" : "x86");
  286. //// 项目编译成x86,只COPY x86目录文件
  287. var is64 = Environment.Is64BitOperatingSystem;
  288. var sqliteFilePath = AppDomain.CurrentDomain.BaseDirectory;
  289. //sqliteFilePath = Path.Combine(sqliteFilePath, is64 ? "x64" : "x86");
  290. sqliteFilePath = Path.Combine(sqliteFilePath, is64 ? "x86" : "x86");
  291. var dirInfo = new DirectoryInfo(sqliteFilePath);
  292. if (dirInfo.Exists)
  293. {
  294. var fileInfos = dirInfo.GetFiles("*.dll", SearchOption.TopDirectoryOnly);
  295. if (!fileInfos.Any()) return;
  296. foreach (var fileInfo in fileInfos)
  297. {
  298. fileInfo.CopyTo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileInfo.Name), true);
  299. }
  300. }
  301. }
  302. catch { }
  303. }
  304. #endregion
  305. private void RegChartComModules()
  306. {
  307. //try
  308. //{
  309. // var financeChart = new PriceChartClass();
  310. // financeChart.Destory();
  311. //}
  312. //catch (COMException ex)
  313. //{
  314. // try
  315. // {
  316. // var directory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "COM");
  317. // //MessageBoxHelper.ShowInfo(Path.Combine(directory, "FinancePrice.dll"), "提示");
  318. // var fileFullName = Path.Combine(directory, "FinancePrice.dll");
  319. // if (File.Exists(fileFullName))
  320. // {
  321. // System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(
  322. // "Regsvr32 ", " /s \"" + fileFullName + "\"");
  323. // startInfo.WorkingDirectory = directory;
  324. // startInfo.WindowStyle = ProcessWindowStyle.Hidden;
  325. // startInfo.UseShellExecute = false;
  326. // startInfo.CreateNoWindow = true;
  327. // Process process = Process.Start(startInfo);
  328. // process.WaitForExit(7000);
  329. // Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  330. // {
  331. // MessageBoxHelper.ShowInfo(Client_Resource.AppChartReg_Error_Tips, Client_Resource.APP_Tips);
  332. // }));
  333. // WindowHelper.RerunApplication();
  334. // }
  335. // }
  336. // catch (Exception e)
  337. // {
  338. // LogHelper.WriteError(typeof (App), ex.ToString());
  339. // }
  340. //}
  341. }
  342. ///// <summary>
  343. ///// Initails the cef.
  344. ///// </summary>
  345. //private static void InitialCEF()
  346. //{
  347. // try
  348. // {
  349. // var path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cef");
  350. // CefRuntime.Load(path);
  351. // var mainArgs = new CefMainArgs(new string[] { });
  352. // var cefApp = new SampleCefApp();
  353. // var exitCode = CefRuntime.ExecuteProcess(mainArgs, cefApp);
  354. // if (exitCode != -1)
  355. // {
  356. // return;
  357. // }
  358. // var cefSettings = new CefSettings
  359. // {
  360. // // BrowserSubprocessPath = browserSubprocessPath,
  361. // SingleProcess = false,
  362. // WindowlessRenderingEnabled = true,
  363. // MultiThreadedMessageLoop = true,
  364. // LogSeverity = CefLogSeverity.Error, //CefLogSeverity.Verbose,
  365. // LogFile = "cef.log",
  366. // };
  367. // CefRuntime.Initialize(mainArgs, cefSettings, cefApp);
  368. // }
  369. // catch (Exception e)
  370. // {
  371. // throw e;
  372. // }
  373. //}
  374. }
  375. //internal sealed class SampleCefApp : CefApp
  376. //{
  377. // public SampleCefApp()
  378. // {
  379. // }
  380. //}
  381. }