App.xaml.cs 16 KB

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