Ejemplo n.º 1
0
        protected override void Configure()
        {
            this.options = this.Container.Get <CommandLineOptionsParser>();
            if (!this.options.Parse(this.Args))
            {
                Environment.Exit(0);
            }

            var pathTransformer = this.Container.Get <IPathTransformer>();

            // Have to set the log path before anything else
            var pathConfiguration = AppSettings.Instance.PathConfiguration;

            GlobalDiagnosticsContext.Set("LogFilePath", pathTransformer.MakeAbsolute(pathConfiguration.LogFilePath));

            AppDomain.CurrentDomain.UnhandledException += (o, e) => OnAppDomainUnhandledException(e);

            var logger   = LogManager.GetCurrentClassLogger();
            var assembly = this.Container.Get <IAssemblyProvider>();

            logger.Info("SyncTrazor version {0} ({1}) started at {2} (.NET version: {3})", assembly.FullVersion, assembly.ProcessorArchitecture, assembly.Location, DotNetVersionFinder.FindDotNetVersion());

            // This needs to happen before anything which might cause the unhandled exception stuff to be shown, as that wants to know
            // where to find the log file.
            this.Container.Get <IApplicationPathsProvider>().Initialize(pathConfiguration);

            var client = this.Container.Get <IIpcCommsClientFactory>().TryCreateClient();

            if (client != null)
            {
                try
                {
                    if (this.options.StartSyncthing || this.options.StopSyncthing)
                    {
                        if (this.options.StartSyncthing)
                        {
                            client.StartSyncthing();
                        }
                        else if (this.options.StopSyncthing)
                        {
                            client.StopSyncthing();
                        }
                        if (!this.options.StartMinimized)
                        {
                            client.ShowMainWindow();
                        }
                        Environment.Exit(0);
                    }

                    if (AppSettings.Instance.EnforceSingleProcessPerUser)
                    {
                        if (!this.options.StartMinimized)
                        {
                            client.ShowMainWindow();
                        }
                        Environment.Exit(0);
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e, $"Failed to talk to {client}: {e.Message}. Pretending that it doesn't exist...");
                }
            }

            var configurationProvider = this.Container.Get <IConfigurationProvider>();

            configurationProvider.Initialize(AppSettings.Instance.DefaultUserConfiguration);
            var configuration = this.Container.Get <IConfigurationProvider>().Load();

            if (AppSettings.Instance.EnforceSingleProcessPerUser)
            {
                this.Container.Get <IIpcCommsServer>().StartServer();
            }

            // Has to be done before the VMs are fetched from the container
            var languageArg = this.Args.FirstOrDefault(x => x.StartsWith("-culture="));

            if (languageArg != null)
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(languageArg.Substring("-culture=".Length));
            }
            else if (!configuration.UseComputerCulture)
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
            }

            // WPF ignores the current culture by default - so we have to force it
            FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.IetfLanguageTag)));

            var autostartProvider = this.Container.Get <IAutostartProvider>();

#if DEBUG
            autostartProvider.IsEnabled = false;
#endif

            // If it's not in portable mode, and if we had to create config (i.e. it's the first start ever), then enable autostart
            if (autostartProvider.CanWrite && AppSettings.Instance.EnableAutostartOnFirstStart && configurationProvider.HadToCreateConfiguration)
            {
                autostartProvider.SetAutoStart(new AutostartConfiguration()
                {
                    AutoStart = true, StartMinimized = true
                });
            }

            // Needs to be done before ConfigurationApplicator is run
            this.Container.Get <IApplicationWindowState>().Setup(this.RootViewModel);

            this.Container.Get <ConfigurationApplicator>().ApplyConfiguration();

            this.Container.Get <MemoryUsageLogger>().Enabled = true;

            // Handles Restart Manager requests - sent by the installer. We need to shutdown syncthing in this case
            this.Application.SessionEnding += (o, e) =>
            {
                LogManager.GetCurrentClassLogger().Info("Shutting down: {0}", e.ReasonSessionEnding);
                var manager = this.Container.Get <ISyncthingManager>();
                manager.StopAndWaitAsync().Wait(2000);
                manager.Kill();
            };

            MessageBoxViewModel.ButtonLabels = new Dictionary <MessageBoxResult, string>()
            {
                { MessageBoxResult.Cancel, Resources.Generic_Dialog_Cancel },
                { MessageBoxResult.No, Resources.Generic_Dialog_No },
                { MessageBoxResult.OK, Resources.Generic_Dialog_OK },
                { MessageBoxResult.Yes, Resources.Generic_Dialog_Yes },
            };

            MessageBoxViewModel.DefaultFlowDirection = Localizer.FlowDirection;

            RecycleBinDeleter.Logger = s => LogManager.GetLogger(typeof(RecycleBinDeleter).FullName).Error(s);
        }
Ejemplo n.º 2
0
        protected override void Configure()
        {
            // GitHub uses Tls 1.2 only, and it isn't enabled by default before .NET 4.6. Since we target an earlier
            // .NET version, we have to enable this ourselves.
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            this.options = this.Container.Get <CommandLineOptionsParser>();
            if (!this.options.Parse(this.Args))
            {
                Environment.Exit(0);
            }

            var pathTransformer = this.Container.Get <IPathTransformer>();

            // Have to set the log path before anything else
            var pathConfiguration = AppSettings.Instance.PathConfiguration;

            GlobalDiagnosticsContext.Set("LogFilePath", pathTransformer.MakeAbsolute(pathConfiguration.LogFilePath));

            AppDomain.CurrentDomain.UnhandledException += (o, e) => OnAppDomainUnhandledException(e);

            var logger   = LogManager.GetCurrentClassLogger();
            var assembly = this.Container.Get <IAssemblyProvider>();

            logger.Info("SyncTrazor version {0} ({1}) started at {2} (.NET version: {3})", assembly.FullVersion, assembly.ProcessorArchitecture, assembly.Location, DotNetVersionFinder.FindDotNetVersion());

            // This needs to happen before anything which might cause the unhandled exception stuff to be shown, as that wants to know
            // where to find the log file.
            this.Container.Get <IApplicationPathsProvider>().Initialize(pathConfiguration);

            var client = this.Container.Get <IIpcCommsClientFactory>().TryCreateClient();

            if (client != null)
            {
                try
                {
                    if (this.options.Shutdown)
                    {
                        client.Shutdown();
                        // Give it some time to shut down
                        var elapsed = Stopwatch.StartNew();
                        while (elapsed.Elapsed < TimeSpan.FromSeconds(10) &&
                               this.Container.Get <IIpcCommsClientFactory>().TryCreateClient() != null)
                        {
                            Thread.Sleep(100);
                        }
                        // Wait another half-second -- it seems it can take the browser process a little longer to exit
                        Thread.Sleep(500);
                        Environment.Exit(0);
                    }

                    if (this.options.StartSyncthing || this.options.StopSyncthing)
                    {
                        if (this.options.StartSyncthing)
                        {
                            client.StartSyncthing();
                        }
                        else if (this.options.StopSyncthing)
                        {
                            client.StopSyncthing();
                        }
                        if (!this.options.StartMinimized)
                        {
                            client.ShowMainWindow();
                        }
                        Environment.Exit(0);
                    }

                    if (AppSettings.Instance.EnforceSingleProcessPerUser)
                    {
                        if (!this.options.StartMinimized)
                        {
                            client.ShowMainWindow();
                        }
                        Environment.Exit(0);
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e, $"Failed to talk to {client}: {e.Message}. Pretending that it doesn't exist...");
                }
            }

            // If we got this far, there probably isn't another instance running, and we should just shut down
            if (this.options.Shutdown)
            {
                Environment.Exit(0);
            }

            var configurationProvider = this.Container.Get <IConfigurationProvider>();

            configurationProvider.Initialize(AppSettings.Instance.DefaultUserConfiguration);
            var configuration = this.Container.Get <IConfigurationProvider>().Load();

            if (AppSettings.Instance.EnforceSingleProcessPerUser)
            {
                this.Container.Get <IIpcCommsServer>().StartServer();
            }

            // Has to be done before the VMs are fetched from the container
            if (this.options.Culture != null)
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(this.options.Culture);
            }
            else if (!configuration.UseComputerCulture)
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
            }

            // WPF ignores the current culture by default - so we have to force it
            FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.IetfLanguageTag)));

            var autostartProvider = this.Container.Get <IAutostartProvider>();

#if DEBUG
            autostartProvider.IsEnabled = false;
#endif

            // If it's not in portable mode, and if we had to create config (i.e. it's the first start ever), then enable autostart
            if (autostartProvider.CanWrite && AppSettings.Instance.EnableAutostartOnFirstStart && configurationProvider.HadToCreateConfiguration)
            {
                autostartProvider.SetAutoStart(new AutostartConfiguration()
                {
                    AutoStart = true, StartMinimized = true
                });
            }

            // Needs to be done before ConfigurationApplicator is run
            this.Container.Get <IApplicationWindowState>().Setup(this.RootViewModel);

            this.Container.Get <ConfigurationApplicator>().ApplyConfiguration();

            this.Container.Get <MemoryUsageLogger>().Enabled = true;

            // Handles Restart Manager requests - sent by the installer. We need to shutdown syncthing in this case
            this.Application.SessionEnding += (o, e) =>
            {
                LogManager.GetCurrentClassLogger().Info("Shutting down: {0}", e.ReasonSessionEnding);
                var manager = this.Container.Get <ISyncthingManager>();
                manager.StopAndWaitAsync().Wait(2000);
                manager.Kill();
            };

            MessageBoxViewModel.ButtonLabels = new Dictionary <MessageBoxResult, string>()
            {
                { MessageBoxResult.Cancel, Resources.Generic_Dialog_Cancel },
                { MessageBoxResult.No, Resources.Generic_Dialog_No },
                { MessageBoxResult.OK, Resources.Generic_Dialog_OK },
                { MessageBoxResult.Yes, Resources.Generic_Dialog_Yes },
            };

            MessageBoxViewModel.DefaultFlowDirection = Localizer.FlowDirection;

            RecycleBinDeleter.Logger = s => LogManager.GetLogger(typeof(RecycleBinDeleter).FullName).Error(s);

            // Workaround for Intel Xe processors, which mess up CefSharp unless we disable hardware
            // rendering for WPF. See #606.
            if (configuration.DisableHardwareRendering)
            {
                RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
            }
        }