App.xaml.cs 16 KB

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