예제 #1
0
        private static (Attempt <SingleGlobalInstance> Instance, bool Error) MainLowLevel()
        {
            try
            {
                // Only one program instance
                var attempt = Attempt.Get(() => new SingleGlobalInstance());
                if (attempt.Failed)
                {
                    SingleInstanceHelper.ProcessFailedSingleInstance(attempt);
                    return(null, true);
                }

                var currentAssembly = typeof(Program).Assembly;

                // Init app internal registry
                Bootstrap.Instance.GetExtendedRegistry(currentAssembly);

                // Add all assemblies in our scope of interest
                AssemblyCollector.Instance.AddAssembly(currentAssembly, AssemblyInProject.View);
                AssemblyCollector.Instance.AddAssembly(typeof(Main).Assembly, AssemblyInProject.Core);


                return(attempt, false);
            }
            catch (Exception e)
            {
                _log.Error(e);
                _log.Error(e.Message);
            }

            return(null, true);
        }
예제 #2
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // Parse the command line arguments and store them in the current configuration
            CommandLineManager.Parse();

            // If we have restart our application... wait until it has finished
            if (CommandLineManager.Current.RestartPid != 0)
            {
                Process[] processList = Process.GetProcesses();

                Process process = processList.FirstOrDefault(x => x.Id == CommandLineManager.Current.RestartPid);

                if (process != null)
                {
                    process.WaitForExit();
                }
            }

            // Detect the current configuration
            ConfigurationManager.Detect();

            // Get assembly informations
            AssemblyManager.Load();

            // Load application settings (profiles/sessions/clients are loaded when needed)
            SettingsManager.Load();

            // Load localization (requires settings to be loaded first)
            LocalizationManager.Load();

            if (CommandLineManager.Current.Help)
            {
                StartupUri = new Uri("/Views/Help/HelpCommandLineWindow.xaml", UriKind.Relative);
                return;
            }

            // Create mutex
            _mutex = new Mutex(true, "{" + Guid + "}");
            bool mutexIsAcquired = _mutex.WaitOne(TimeSpan.Zero, true);

            // Release mutex
            if (mutexIsAcquired)
            {
                _mutex.ReleaseMutex();
            }

            if (SettingsManager.Current.Window_MultipleInstances || mutexIsAcquired)
            {
                StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
            }
            else
            {
                // Bring the already running application into the foreground
                SingleInstanceHelper.PostMessage((IntPtr)SingleInstanceHelper.HWND_BROADCAST, SingleInstanceHelper.WM_SHOWME, IntPtr.Zero, IntPtr.Zero);

                _singleInstanceClose = true;
                Shutdown();
            }
        }
예제 #3
0
        static void Main(string[] args)
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

            // send log to console
            log4net.Config.BasicConfigurator.Configure();

            bool onlyInstance = false;

            mutex = new Mutex(true, "SuperPutty", out onlyInstance);

            Log.InfoFormat(
                "IsFirstRun={0}, SingleInstanceMode={1}, onlyInstance={2}",
                SuperPuTTY.IsFirstRun, SuperPuTTY.Settings.SingleInstanceMode, onlyInstance);
            if ((EnforceSingleInstance || SuperPuTTY.Settings.SingleInstanceMode) && !SuperPuTTY.IsFirstRun && !onlyInstance)
            {
                SingleInstanceHelper.LaunchInExistingInstance(args);
                Log.InfoFormat("Sent Command to Existing Instance: [{0}]", String.Join(" ", args));
                Environment.Exit(0);
            }

            // open full file
            log4net.Config.XmlConfigurator.Configure();

#if DEBUG
            Logger.OnLog += delegate(string logMessage)
            {
                //Console.WriteLine(logMessage);
                Log.Info(logMessage);
            };
#endif

            try
            {
                Log.Info("Starting");
                SuperPuTTY.Initialize(args);

                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                frmSuperPutty mainForm = new frmSuperPutty();
                SetDefaultIcon(mainForm);
                Application.Run(SuperPuTTY.MainForm = mainForm);
                SuperPuTTY.Shutdown();
            }
            catch (Exception ex)
            {
                Log.Error("Error in Main", ex);
            }
            finally
            {
                Log.Info("Shutdown");
            }
        }
예제 #4
0
 protected override void OnStartup(StartupEventArgs e)
 {
     if (SingleInstanceHelper.IsFirstInsance())
     {
         base.OnStartup(e);
     }
     else
     {
         MessageBox.Show(Acadon.Client.Connector.Properties.Resources.OnlyOncePerSession, Consts.AppName);
         Environment.Exit(0);
     }
 }
예제 #5
0
        private void OnStartup(object sender, StartupEventArgs e)
        {
            Console.Out.WriteLine("Render Tier: {0}", Tier);

            SingleInstanceHelper.Make();

            var sb = new StringBuilder();

            sb.AppendLine();
            sb.AppendFormat("Запущена касса версии {0}", Assembly.GetExecutingAssembly().GetName().Version);
            Log.Info(sb);

            Loader(StaticHelper.IoCcontainer);
            var o = ObserveWrapperHelper.GetInstance();
            var relationsViewToViewModel = new Dictionary <Type, Type>
            {
                { o.GetWrappedType <LoginViewModel>(true), typeof(LoginView) },
                { o.GetWrappedType <MainViewModel>(true), typeof(MainView) },
                { o.GetWrappedType <PaymentViewModel>(true), typeof(PaymentView) },
                { o.GetWrappedType <RollInfoViewModel>(true), typeof(RollInfoView) },
                { o.GetWrappedType <InformationViewModel>(true), typeof(InformationView) },
                { o.GetWrappedType <SettingsViewModel>(true), typeof(SettingsView) },
                { o.GetWrappedType <TicketWriteOffViewModel>(true), typeof(TicketWriteOffView) },
                { o.GetWrappedType <ReversalTicketViewModel>(true), typeof(ReversalTicketView) }
            };

            ViewManager.RegisterViewViewModelRelations(relationsViewToViewModel);
            ViewModelManager.ActiveViewModels.CollectionChanged += ViewManager.OnViewModelsCoolectionChanged;

            #if LOGIN_DEBUG && PRINT_DEBUG
            Log.Warn("Запущено в режиме полной отладки!");
            #elif LOGIN_DEBUG
            Log.Warn("Запущено в режиме отладки авторизации!");
            #elif PRINT_DEBUG
            Log.Warn("Запущено в режиме отладки печати!");
            #elif DEBUG
            Log.Warn("Запущено в режиме отладки!");
            #else
            Log.Info("Запущено в продуктивном режиме.");
            #endif

            #if DEBUG && !LOGIN_DEBUG
            var startupWindowSeed = o.Resolve <MainViewModel>();
            startupWindowSeed.OpenSession();
            #else
            var startupWindowSeed = o.Resolve <LoginViewModel>();
            startupWindowSeed.Show();
            #endif
        }
예제 #6
0
 static bool LoadFilesInPreviousInstance(string[] fileList)
 {
     try {
         foreach (string file in fileList)
         {
             if (ProjectService.HasProjectLoader(file))
             {
                 return(false);
             }
         }
         return(SingleInstanceHelper.OpenFilesInPreviousInstance(fileList));
     } catch (Exception ex) {
         LoggingService.Error(ex);
         return(false);
     }
 }
예제 #7
0
 static bool LoadFilesInPreviousInstance(string[] fileList)
 {
     try {
         foreach (string file in fileList)
         {
             if (SD.ProjectService.IsSolutionOrProjectFile(FileName.Create(file)))
             {
                 return(false);
             }
         }
         return(SingleInstanceHelper.OpenFilesInPreviousInstance(fileList));
     } catch (Exception ex) {
         LoggingService.Error(ex);
         return(false);
     }
 }
 public void RestartAppIfInvalid()
 {
     try
     {
         bool arg_0B_0 = this._settings.AppFirstRun;
     }
     catch (ConfigurationException arg_0E_0)
     {
         ConfigurationErrorsException expr_18 = arg_0E_0.InnerException as ConfigurationErrorsException;
         if (expr_18 == null)
         {
             throw;
         }
         File.Delete(expr_18.Filename);
         SingleInstanceHelper.ReleaseSingleInstanceLock();
         Process.Start(Application.ResourceAssembly.Location);
         Environment.Exit(0);
     }
 }
 public void Load()
 {
     try
     {
         this._decorated.Load();
     }
     catch (ConfigurationException arg_0D_0)
     {
         ConfigurationErrorsException ex;
         if ((ex = (arg_0D_0.InnerException as ConfigurationErrorsException)) == null || string.IsNullOrEmpty(ex.Filename))
         {
             throw;
         }
         File.Delete(ex.Filename);
         SingleInstanceHelper.ReleaseSingleInstanceLock();
         Process.Start(Application.ResourceAssembly.Location);
         Environment.Exit(0);
     }
 }
예제 #10
0
        protected override async void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

#if DEBUG
            //LogManager.AddDebugListener();
#endif

            var serviceLocator = this.GetServiceLocator();

            try
            {
                bool singleInstance = SingleInstanceHelper.EnsureSingleInstance(AppInfo.Id);
                if (!singleInstance)
                {
                    return;
                }

                Register(serviceLocator);

                Logger = serviceLocator.ResolveType <ILoggingService>();
                var visualizer      = serviceLocator.ResolveType <IUIVisualizerService>();
                var settingsService = serviceLocator.ResolveType <ISettingsService>();

                Logger.Info($"App started ({AppInfo.Version})");

                settingsService.Load();

                var mainViewModel = MainViewModel.Create();
                await visualizer.ShowDialogAsync(mainViewModel);

                Logger.Info("App gonna close");
            }
            catch (Exception ex)
            {
                ProcessUnhandledException(ex);
            }
            finally
            {
                Shutdown();
            }
        }
예제 #11
0
        protected override void OnStartup(StartupEventArgs e)
        {
#if DEBUG
            //while (!Debugger.IsAttached) Thread.Sleep(100);
#endif

            _singleHelper = new SingleInstanceHelper();

            if (_singleHelper.IsNewInstance)
            {
                Current.DispatcherUnhandledException += Application_DispatcherUnhandledException;
                SetupMagnetLinkHandler();
                StartApplication(e);
            }
            else
            {
                _singleHelper.InformExistingInstance(e.Args);
                Current.Shutdown();
            }
        }
예제 #12
0
        static void Main(string [] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Form applicationMainWindow = new frmMainWindow();

            ApplicationSettings.ApplicationMainForm = applicationMainWindow;

            if (Debugger.IsAttached)
            {
                LogWriter = new DebugLogger();
                LogWriter.Log("DebugLogger wurde aktiviert!");
            }
            else
            {
                LogWriter = new LoggerMock();
            }

            SingleInstanceHelper.RegisterRemotingService();

            if (ApplicationSettings.RuninSingleInstanceMode)
            {
                bool  onlyInstance = false;
                Mutex mutex        = new Mutex(true, "PuttyServerManager", out onlyInstance);

                LogWriter.Log("Running in single instance mode - is first instance: {0}", onlyInstance);
                if (!onlyInstance)
                {
                    SingleInstanceHelper.LaunchInExistingInstance(args);
                    Environment.Exit(0);
                }
            }



            Application.Run(applicationMainWindow);
        }
예제 #13
0
        public static void Initialize(string[] args)
        {
            Log.InfoFormat(
                "Initializing.  Version={0}, UserSettings={1}, SettingsFolder={2}",
                Version, Settings.SettingsFilePath, Settings.SettingsFolder);

            if (!SuperPuTTY.IsFirstRun)
            {
                // parse command line args
                CommandLine = new CommandLineOptions(args);

                // display help if --help specified
                if (CommandLine.Help)
                {
                    if (DialogResult.Cancel == MessageBox.Show(CommandLineOptions.Usage(), "SuperPutty CLI Help", MessageBoxButtons.OKCancel))
                    {
                        Environment.Exit(0);
                    }
                }

                // load data
                LoadLayouts();
                LoadSessions();
                Images = LoadImageList("default");

                // determine starting layout, if any.  CLI has priority
                if (CommandLine.IsValid)
                {
                    if (CommandLine.Layout != null)
                    {
                        StartingLayout = FindLayout(CommandLine.Layout);
                        if (StartingLayout != null)
                        {
                            Log.InfoFormat("Starting with layout from command line, {0}", CommandLine.Layout);
                        }
                    }
                    else
                    {
                        // ad-hoc session specified
                        SessionDataStartInfo sessionStartInfo = CommandLine.ToSessionStartInfo();
                        if (sessionStartInfo != null)
                        {
                            StartingSession = sessionStartInfo;
                            Log.InfoFormat("Starting adhoc Session from command line, {0}", StartingSession.Session.SessionId);
                        }
                    }
                }

                // if nothing specified, then try the default layout
                if (StartingLayout == null && StartingSession == null)
                {
                    StartingLayout = FindLayout(Settings.DefaultLayoutName);
                    if (StartingLayout != null)
                    {
                        Log.InfoFormat("Starting with default layout, {0}", Settings.DefaultLayoutName);
                    }
                }
            }

            // Register IpcChanncel for single instance support
            SingleInstanceHelper.RegisterRemotingService();

            Log.Info("Initialized");
        }
예제 #14
0
        /// <summary>
        /// Either shows the application's main window or inits the application in the system tray.
        /// </summary>
        private void OnStartup(object sender, StartupEventArgs args)
        {
            Thread.CurrentThread.Name = "Main";
            Thread.CurrentThread.SetApartmentState(ApartmentState.STA);

            // Parse command line options
            var mpOptions = new CommandLineOptions();
            var parser    = new CommandLine.Parser(with => with.HelpWriter = Console.Out);

            parser.ParseArgumentsStrict(args.Args, mpOptions, () => Environment.Exit(1));

            // Check if another instance is already running
            // If new instance was created by UacHelper previous one, assume that previous one is already closed.
            if (SingleInstanceHelper.IsAlreadyRunning(MUTEX_ID, out _mutex))
            {
                _mutex = null;
                // Set focus on previously running app
                SingleInstanceHelper.SwitchToCurrentInstance(SingleInstanceHelper.SHOW_MP2_SERVICEMONITOR_MESSAGE);
                // Stop current instance
                Console.Out.WriteLine("Application already running.");
                Environment.Exit(2);
            }

            // Make sure we're properly handling exceptions
            DispatcherUnhandledException += OnUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += LauncherExceptionHandling.CurrentDomain_UnhandledException;

            var systemStateService = new SystemStateService();

            ServiceRegistration.Set <ISystemStateService>(systemStateService);
            systemStateService.SwitchSystemState(SystemState.Initializing, false);

#if !DEBUG
            string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Team MediaPortal\MP2-ServiceMonitor\Log");
#endif

            try
            {
                ILogger logger = null;
                try
                {
                    ApplicationCore.RegisterVitalCoreServices(true);
                    ApplicationCore.RegisterCoreServices();
                    logger = ServiceRegistration.Get <ILogger>();

                    logger.Debug("Starting Localization");
                    Localization localization = new Localization();
                    ServiceRegistration.Set <ILocalization>(localization);
                    localization.Startup();

                    //ApplicationCore.StartCoreServices();

                    logger.Debug("UiExtension: Registering ISystemResolver service");
                    ServiceRegistration.Set <ISystemResolver>(new SystemResolver());

                    logger.Debug("UiExtension: Registering IServerConnectionManager service");
                    ServiceRegistration.Set <IServerConnectionManager>(new ServerConnectionManager());

#if !DEBUG
                    logPath = ServiceRegistration.Get <IPathManager>().GetPath("<LOG>");
#endif
                }
                catch (Exception e)
                {
                    if (logger != null)
                    {
                        logger.Critical("Error starting application", e);
                    }

                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;

                    ApplicationCore.DisposeCoreServices();

                    throw;
                }

                InitIpc();

                var appController = new AppController();
                ServiceRegistration.Set <IAppController>(appController);

                // Start the application
                logger.Debug("Starting application");
                try
                {
                    ServiceRegistration.Get <IServerConnectionManager>().Startup();
                    appController.StartUp(mpOptions);
                }
                catch (Exception e)
                {
                    logger.Critical("Error executing application", e);
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                var log = new ConsoleLogger(LogLevel.All, false);
                log.Error(ex);
#else
                ServerCrashLogger crash = new ServerCrashLogger(logPath);
                crash.CreateLog(ex);
#endif
                systemStateService.SwitchSystemState(SystemState.Ending, false);
                Current.Shutdown();
            }
        }
예제 #15
0
        /// <summary>
        /// The main entry point for the MP2 client application.
        /// </summary>
        private static void Main(params string[] args)
        {
            Thread.CurrentThread.Name = "Main";

            // Parse command line options
            var mpOptions = new CommandLineOptions();
            var parser    = new CommandLine.Parser(with => with.HelpWriter = Console.Out);

            parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

            // Check if another instance is already running
            if (SingleInstanceHelper.IsAlreadyRunning(MUTEX_ID, out _mutex))
            {
                _mutex = null;
                // Set focus on previously running app
                SingleInstanceHelper.SwitchToCurrentInstance(SingleInstanceHelper.SHOW_MP2_CLIENT_MESSAGE);
                // Stop current instance
                Console.Out.WriteLine("Application already running.");
                Environment.Exit(2);
            }

#if !DEBUG
            string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Team MediaPortal\MP2-Client\Log");
#endif

            Application.ThreadException += LauncherExceptionHandling.Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += LauncherExceptionHandling.CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException      += LauncherExceptionHandling.TaskScheduler_UnobservedTaskException;

            SystemStateService systemStateService = new SystemStateService();
            ServiceRegistration.Set <ISystemStateService>(systemStateService);
            systemStateService.SwitchSystemState(SystemState.Initializing, false);

            try
            {
#if !DEBUG
                SplashScreen splashScreen = null;
#endif
                ILogger logger = null;
                try
                {
                    // Check if user wants to override the default Application Data location.
                    ApplicationCore.RegisterVitalCoreServices(true, mpOptions.DataDirectory);

#if !DEBUG
                    splashScreen = CreateSplashScreen();
                    splashScreen.ShowSplashScreen();
#endif

                    ApplicationCore.RegisterCoreServices();

                    logger = ServiceRegistration.Get <ILogger>();

#if !DEBUG
                    IPathManager pathManager = ServiceRegistration.Get <IPathManager>();
                    logPath = pathManager.GetPath("<LOG>");
#endif

                    UiExtension.RegisterUiServices();
                }
                catch (Exception e)
                {
                    if (logger != null)
                    {
                        logger.Critical("Error starting application", e);
                    }
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;

                    UiExtension.DisposeUiServices();
                    ApplicationCore.DisposeCoreServices();

                    throw;
                }

                // Start the core
                logger.Debug("ApplicationLauncher: Starting application");

                try
                {
                    IPluginManager pluginManager = ServiceRegistration.Get <IPluginManager>();
                    pluginManager.Initialize();
                    pluginManager.Startup(false);
                    ApplicationCore.StartCoreServices();

                    ISkinEngine            skinEngine            = ServiceRegistration.Get <ISkinEngine>();
                    IWorkflowManager       workflowManager       = ServiceRegistration.Get <IWorkflowManager>();
                    IMediaAccessor         mediaAccessor         = ServiceRegistration.Get <IMediaAccessor>();
                    ILocalSharesManagement localSharesManagement = ServiceRegistration.Get <ILocalSharesManagement>();

                    // We have to handle some dependencies here in the start order:
                    // 1) After all plugins are loaded, the SkinEngine can initialize (=load all skin resources)
                    // 2) After the skin resources are loaded, the workflow manager can initialize (=load its states and actions)
                    // 3) Before the main window is shown, the splash screen should be hidden
                    // 4) After the workflow states and actions are loaded, the main window can be shown
                    // 5) After the skinengine triggers the first workflow state/startup screen, the default shortcuts can be registered
                    mediaAccessor.Initialize();         // Independent from other services
                    localSharesManagement.Initialize(); // After media accessor was initialized
                    skinEngine.Initialize();            // 1)
                    workflowManager.Initialize();       // 2)

#if !DEBUG
                    splashScreen.CloseSplashScreen(); // 3)
#endif

                    skinEngine.Startup();                                         // 4)
                    UiExtension.Startup();                                        // 5)

                    ApplicationCore.RegisterDefaultMediaItemAspectTypes().Wait(); // To be done after UI services are running

                    _ipcServer = new IpcServer("Client");
                    _ipcServer.CustomShutdownCallback = () =>
                    {
                        ServiceRegistration.Get <IScreenControl>().Shutdown();
                        return(true);
                    };
                    try
                    {
                        _ipcServer.Open();
                    }
                    catch (Exception ipcEx)
                    {
                        logger.Error(ipcEx);
                    }
                    systemStateService.SwitchSystemState(SystemState.Running, true);

                    if (mpOptions.AutoStart)
                    {
                        StartFocusKeeper();
                    }

                    Application.Run();
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true; // Block ServiceRegistration from trying to load new services in shutdown phase

                    // 1) Stop UI extensions (Releases all active players, must be done before shutting down SE)
                    // 2) Shutdown SkinEngine (Closes all screens, uninstalls background manager, stops render thread)
                    // 3) Shutdown WorkflowManager (Disposes all models)
                    // 4) Shutdown ImporterWorker
                    // 5) Shutdown PluginManager (Shuts down all plugins)
                    // 6) Remove all services
                    UiExtension.StopUiServices();
                    skinEngine.Shutdown();
                    workflowManager.Shutdown();
                    ServiceRegistration.Get <IImporterWorker>().Shutdown();
                    pluginManager.Shutdown();
                    mediaAccessor.Shutdown();
                    localSharesManagement.Shutdown();
                    ApplicationCore.StopCoreServices();
                }
                catch (Exception e)
                {
                    logger.Critical("Error executing application", e);
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;
                }
                finally
                {
                    if (_ipcServer != null)
                    {
                        _ipcServer.Close();
                    }
                    UiExtension.DisposeUiServices();
                    ApplicationCore.DisposeCoreServices();

                    systemStateService.SwitchSystemState(SystemState.Ending, false);
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ConsoleLogger log = new ConsoleLogger(LogLevel.All, false);
                log.Error(ex);
#else
                UiCrashLogger crash = new UiCrashLogger(logPath);
                crash.CreateLog(ex);
#endif
                systemStateService.SwitchSystemState(SystemState.Ending, false);

                // Release mutex for single instance
                if (_mutex != null)
                {
                    _mutex.ReleaseMutex();
                }

                Application.Exit();
            }
        }
예제 #16
0
        /// <summary>
        /// The main entry point for the MP2-ClientLauncher application.
        /// </summary>
        private static void Main(params string[] args)
        {
            Thread.CurrentThread.Name = "Main";

            // Parse command line options
            var mpOptions = new CommandLineOptions();
            var parser    = new CommandLine.Parser(with => with.HelpWriter = Console.Out);

            parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

            // Check if another instance is already running
            if (SingleInstanceHelper.IsAlreadyRunning(MUTEX_ID, out _mutex))
            {
                _mutex = null;
                // Stop current instance
                Console.Out.WriteLine("Application already running.");
                Environment.Exit(2);
            }

#if !DEBUG
            string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                                          @"Team MediaPortal", "MP2-Client", "Log");
#endif

            //// todo: Make sure we're properly handling exceptions
            //DispatcherUnhandledException += OnUnhandledException;
            //AppDomain.CurrentDomain.UnhandledException += LauncherExceptionHandling.CurrentDomain_UnhandledException;

            // Start core services
            ILogger logger = null;
            try
            {
                // Check if user wants to override the default Application Data location.
                ApplicationCore.RegisterVitalCoreServices(mpOptions.DataDirectory);

                logger = ServiceRegistration.Get <ILogger>();

#if !DEBUG
                logPath = ServiceRegistration.Get <IPathManager>().GetPath("<LOG>");
#endif
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger.Critical("Error starting application", e);
                }

                ApplicationCore.DisposeCoreServices();

                throw;
            }

            // Start application
            logger.Info("Starting application");

            try
            {
                if (TerminateProcess("ehtray"))
                {
                    logger.Info("Terminating running instance(s) of ehtray.exe");
                }

                Remote.Transceivers.AddRange(GetTransceiverList());
                Remote.Click         += OnClick;
                Device.DeviceArrival += OnDeviceArrival;
                Device.DeviceRemoval += OnDeviceRemoval;

                if (!mpOptions.NoIcon)
                {
                    InitTrayIcon();
                }

                Application.Run();
            }
            catch (Exception e)
            {
                logger.Critical("Error executing application", e);
            }

            logger.Info("Exiting...");



            // Release mutex for single instance
            if (_mutex != null)
            {
                _mutex.ReleaseMutex();
            }

            Application.Exit();
        }
예제 #17
0
 internal void <EnsureServiceHealthy> b__3_0(bool cancelled)
 {
     SingleInstanceHelper.ReleaseSingleInstanceLock();
     Environment.Exit(0);
 }