using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Windows.Forms; using GalaSoft.MvvmLight.Threading; using Muchinfo.MTPClient.CustomException; using Muchinfo.MTPClient.Infrastructure.Helpers; using Muchinfo.MTPClient.Infrastructure.LinkProxy; using Muchinfo.MTPClient.Infrastructure.MessageBox; using Muchinfo.MTPClient.Infrastructure.Utilities; using Muchinfo.MTPClient.Resources; using Muchinfo.MTPClient.UI; using Muchinfo.MTPClient.UI.Utilities; using Muchinfo.MTPClient.UI.Views; using Muchinfo.PC.Common.Extensions; using Muchinfo.PC.Common.Helpers; using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Windows; using Microsoft.Win32; using Muchinfo.MTPClient.Adapter.Utilities; using Muchinfo.MTPClient.Data.Enums; using Muchinfo.MTPClient.Data.Model.Account; using Application = System.Windows.Application; namespace Muchinfo.MTPClient { /// /// App.xaml 的交互逻辑 /// public partial class App : Application { #region Fields private System.Threading.Mutex _mutexApplication; #endregion /// /// Initializes static members of the class. /// static App() { CopyLibsByOS(); DispatcherHelper.Initialize(); ViewModelLocator.Initialize(); } /// /// Initializes a new instance of the class. /// public App() { this.DispatcherUnhandledException += App_DispatcherUnhandledException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; ////初始化CEF浏览器 //InitialCEF(); //注册账号变更,修改MessageHead的AccountID MessengerHelper.DefaultRegister(this, MessengerTokens.UpdateTradeAccount, (account) => { ProtoBufHelper.Head.AccountID = UserManager.CurrentTradeAccount.FundsAccountId; }); } /// /// 引发 事件。 /// /// 一个包含事件数据的 。 protected override void OnStartup(StartupEventArgs e) { //EntrustOrderFrame entrust = new EntrustOrderFrame(); //entrust.ShowDialog(); //读取系统配置 ApplicationParameter.InitializeSystemConfig(); // 风管云平台服务地址 ApplicationParameter.UpdateErmcpParamete(); base.OnStartup(e); ApplicationParameter.LoginGuid = System.Guid.NewGuid().ToString(); ApplicationParameter.ShowChart = 1; var lastLoginUser = UserManager.GetLastLoginUser(); ////加载资源 //Client_Resource.Resource(new MuchInfoResourceManager()); //ErrorResources.Resource(new ErrorResourceManager()); this.ShutdownMode = ShutdownMode.OnMainWindowClose; /// RegChartComModules(); bool runApplication; if (e.Args.Contains(WindowHelper.restratCommand)) { runApplication = true; } else { _mutexApplication = new System.Threading.Mutex(true, Process.GetCurrentProcess().MainModule.FileName.Replace("\\", string.Empty), out runApplication); } //允许多实例 runApplication = true; if (runApplication) { #region MyRegion try { MuchinfoException.InitErrorResx(); ///初始化错误资源 ConstResxManager.InitConstResx(UserManager.UserDataFolder); ///常量资源 ConfigParamResxManager.InitConfigParamResx(UserManager.UserDataFolder); MarketResxManager.InitMarketResx(UserManager.UserDataFolder); MenuResxManager.InitMenuResx(UserManager.UserDataFolder); GoodsResxManager.InitGoodsResx(UserManager.UserDataFolder); DeliveryResxManager.InitDeliveryResx(UserManager.UserDataFolder); RiskMsgResxManager.InitRiskMsgResx(UserManager.UserDataFolder); TradeDateResxManager.InitTradeDateResx(UserManager.UserDataFolder); LastUpdateTimeManager.InitLastUpdateTimeType(); ///初始化最后更新时间列表 } catch (Exception ex) { LogHelper.WriteError(typeof(App), ex.ToString()); } #endregion var login = new LoginView_1(); // new LoginNewView(); this.MainWindow = login; login.Show(); if (!IsRun() && !string.IsNullOrWhiteSpace(ApplicationParameter.UpdateAddress)) { //todo: 开发期间注释升级 string fileName = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "Client.Update.exe"); var arguments = string.Format("{0},{1}", ApplicationParameter.UpdateAddress, lastLoginUser == null ? string.Empty : lastLoginUser.MemberId); Process.Start(fileName, arguments); } } else { //同一安装目录的程序只允许运行单个实例! MessageBoxHelper.ShowInfo(null, Client_Resource.APP_OnlySingleExe, Client_Resource.APP_Tips, true); WindowHelper.RerunApplication(false); } } /// /// 引发 事件。 /// /// 一个包含事件数据的 。 protected override void OnExit(ExitEventArgs e) { try { if (_mutexApplication != null) { _mutexApplication.ReleaseMutex(); } ViewModelLocator.Cleanup(); //释放链路对象 LinkManager.Instance.Dispose(); } catch (Exception ex) { } finally { ////关闭CEF浏览器 //CefRuntime.Shutdown(); base.OnExit(e); Environment.Exit(0); } } #region Exception Handle /// /// 处理Domain异常 /// /// The source of the event. /// The instance containing the event data. private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { try { var muchinfoEx = e.ExceptionObject as MuchinfoException; if (muchinfoEx != null) { HandleException(muchinfoEx); } else if (e.ExceptionObject is Exception) { HandleException(e.ExceptionObject as Exception); } } catch (Exception ex) { HandleException(ex); } } /// /// 处理Dispatcher线程异常 /// /// The source of the event. /// The instance containing the event data. private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { try { var muchinfoEx = e.Exception as MuchinfoException; if (muchinfoEx == null) { HandleException(e.Exception); } else { HandleException(muchinfoEx); } e.Handled = true; } catch (Exception ex) { HandleException(new MuchinfoException(ExceptionManager.UnknownClientErrorCode, ex)); } } /// /// 显示预期的错误 /// /// private void HandleException(MuchinfoException e) { MessageBoxHelper.ShowInfo(e.Message, Client_Resource.Bank_ErrotTips); } /// /// Handles the exception. /// /// The e. private void HandleException(Exception e) { #region 暂时不显示错误内容 //MessageBoxSend mbs = new MessageBoxSend() // { // WindowStartupLocation = WindowStartupLocation.CenterScreen, // }; //mbs.DataContext = new MessageBoxSendViewModel(e.ToString()); //var viewModel = mbs.DataContext as MessageBoxSendViewModel; //mbs.ShowDialog(); //if (mbs.DialogResult == true && viewModel != null) //{ // string Error = ""; // if ( // !MailSendHelper.MailSend(ApplicationParameter.ToAddress, "ClientErrorReport@163.com", "1qazxsw2", // "smtp.163.com", 25, ApplicationParameter.TradeSystemName, // ApplicationParameter.ExchangeName + ApplicationParameter.Version, // e.ToString() + Environment.NewLine + viewModel.UserInfo, string.Empty, out Error)) ; //} ////写错误日志 //LogHelper.WriteError(typeof(App), e.ToString()); #endregion // string Error = ""; try { //MailSendHelper.MailSend(ApplicationParameter.ToAddress, "ClientErrorReport@163.com", "1qazxsw2", // "smtp.163.com", 25, ApplicationParameter.TradeSystemName, // ApplicationParameter.ExchangeName + ApplicationParameter.Version, // e.ToString() + Environment.NewLine, string.Empty, out Error); LogHelper.WriteError(typeof(App), e.ToString()); } catch (Exception ex) { LogHelper.WriteError(typeof(App), ex.ToString()); } } #endregion #region 更新 private readonly bool isUpdate = false; /// /// 更新程序是否正在运行 /// /// private bool IsRun() { bool bo = false; var process = Process.GetProcessesByName("Muchinfo.MTPClient.Update"); if (process.Length > 0) { bo = true; } return bo; } #endregion #region Copy Sqlite vc++库 /// /// 根据操作系统COPY依赖库 /// private static void CopyLibsByOS() { try { //// 项目编译成anycpu,按操作系统类型COPY //// sqliteFilePath = Path.Combine(sqliteFilePath, is64 ? "x64" : "x86"); //// 项目编译成x86,只COPY x86目录文件 var is64 = Environment.Is64BitOperatingSystem; var sqliteFilePath = AppDomain.CurrentDomain.BaseDirectory; //sqliteFilePath = Path.Combine(sqliteFilePath, is64 ? "x64" : "x86"); sqliteFilePath = Path.Combine(sqliteFilePath, is64 ? "x86" : "x86"); var dirInfo = new DirectoryInfo(sqliteFilePath); if (dirInfo.Exists) { var fileInfos = dirInfo.GetFiles("*.dll", SearchOption.TopDirectoryOnly); if (!fileInfos.Any()) return; foreach (var fileInfo in fileInfos) { fileInfo.CopyTo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileInfo.Name), true); } } } catch { } } #endregion private void RegChartComModules() { //try //{ // var financeChart = new PriceChartClass(); // financeChart.Destory(); //} //catch (COMException ex) //{ // try // { // var directory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "COM"); // //MessageBoxHelper.ShowInfo(Path.Combine(directory, "FinancePrice.dll"), "提示"); // var fileFullName = Path.Combine(directory, "FinancePrice.dll"); // if (File.Exists(fileFullName)) // { // System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo( // "Regsvr32 ", " /s \"" + fileFullName + "\""); // startInfo.WorkingDirectory = directory; // startInfo.WindowStyle = ProcessWindowStyle.Hidden; // startInfo.UseShellExecute = false; // startInfo.CreateNoWindow = true; // Process process = Process.Start(startInfo); // process.WaitForExit(7000); // Application.Current.Dispatcher.BeginInvoke(new Action(() => // { // MessageBoxHelper.ShowInfo(Client_Resource.AppChartReg_Error_Tips, Client_Resource.APP_Tips); // })); // WindowHelper.RerunApplication(); // } // } // catch (Exception e) // { // LogHelper.WriteError(typeof (App), ex.ToString()); // } //} } ///// ///// Initails the cef. ///// //private static void InitialCEF() //{ // try // { // var path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cef"); // CefRuntime.Load(path); // var mainArgs = new CefMainArgs(new string[] { }); // var cefApp = new SampleCefApp(); // var exitCode = CefRuntime.ExecuteProcess(mainArgs, cefApp); // if (exitCode != -1) // { // return; // } // var cefSettings = new CefSettings // { // // BrowserSubprocessPath = browserSubprocessPath, // SingleProcess = false, // WindowlessRenderingEnabled = true, // MultiThreadedMessageLoop = true, // LogSeverity = CefLogSeverity.Error, //CefLogSeverity.Verbose, // LogFile = "cef.log", // }; // CefRuntime.Initialize(mainArgs, cefSettings, cefApp); // } // catch (Exception e) // { // throw e; // } //} } //internal sealed class SampleCefApp : CefApp //{ // public SampleCefApp() // { // } //} }