Beispiel #1
0
        /// <summary>
        /// Mains the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        static void Main(string[] args)
        {
            XmlConfigurator.Configure();
            try
            {
                Log.InfoFormat("##########   Starting service '{0}', V '{1}'   ##########",
                               AssemblyHelper.AssemblyTitle,
                               AssemblyHelper.AssemblyVersion);

                // Add the event handler for handling unhandled  exceptions to the event.
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

                // Start Service Updater
                IUpdater      selfupdater = null;
                ServiceHosted service     = new ServiceHosted();

                IUpdateManager updateManager = null;
                try
                {
                    Log.Info("Updater Initialisation");
                    updateManager = new UpdateManager(_urlNugetRepositories, AssemblyHelper.AssemblyTitle);
                    selfupdater   = new RepeatedTimeUpdater(updateManager).SetCheckUpdatePeriod(TimeSpan.FromMinutes(30));
                    selfupdater.Start();
                }
                catch (Exception exx)
                {
                    Log.WarnFormat("'{0}' is not installed via Squirrel. Install program first.", AssemblyHelper.AssemblyTitle);
                    Log.Warn(exx);
                }

                // Start TopShelf
                var x = new SquirreledHost(service, AssemblyHelper.CurrentAssembly, selfupdater, true, RunAS.LocalSystem);

                // If RunAS.RunSpecificUser set login / password
                //x.SetCredentials("", "");

                x.ConfigureAndRun(HostConfig =>
                {
                    HostConfig.Service <ServiceHosted>(s =>
                    {
                        s.ConstructUsing(name => new ServiceHosted());
                        s.WhenStarted(tc => tc.Start());
                        s.WhenStopped(tc => tc.Stop());
                        s.WhenPaused(tc => { });
                        s.WhenContinued(tc => { });
                    });
                    HostConfig.EnableServiceRecovery(rc => rc.RestartService(1));
                    HostConfig.EnableSessionChanged();
                    HostConfig.UseLog4Net();
                    HostConfig.StartAutomatically();
                });
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
            finally
            {
                Log.InfoFormat("##########   Stoppping service '{0}', V '{1}'   ##########",
                               AssemblyHelper.AssemblyTitle,
                               AssemblyHelper.AssemblyVersion);
            }
        }
Beispiel #2
0
        public static void HostDaemon <T>(string updateUrl, string serviceName, string serviceDescription, string serviceDisplayName, ILogger logger = null)
            where T : class, IAppDaemonService, new()
        {
            logger?.Information("Hosting Daemon...");
            logger?.Information("Hosting Daemon Update URL: {UpdateUrl}", updateUrl);

            // Configure unhandled exception logging
            if (logger != null)
            {
                AppDomain.CurrentDomain.UnhandledException +=
                    (sender, args) => logger.Fatal(args.ExceptionObject as Exception, "AppDomain Unhandled Exception");
            }

            // Configure update manager
            UpdateManager updateManager = null;
            IUpdater      updater       = null;

            try
            {
                updateManager = new UpdateManager(updateUrl, serviceName);
            }
            catch
            {
                logger?.Information("Updater not configured. Some features may be unavailable because the app is running without Update.exe");
            }

            // Updater config
            if (updateManager != null)
            {
                var updatePeriod = TimeSpan.FromSeconds(30);
                updater = new RepeatedTimeUpdater(updateManager).SetCheckUpdatePeriod(updatePeriod);
                updater.Start();

                logger?.Information("Daemon auto-update period set to: {AutoUpdatePeriod} minutes", updatePeriod.TotalMinutes);
            }
            else
            {
                logger?.Warning("Daemon auto-updates are disabled.");
            }

            // Configuration
            var con = new Action <HostConfigurator>(config =>
            {
                config.SetServiceName(serviceName);
                config.SetDescription(serviceDescription);
                config.SetDisplayName(serviceDisplayName);
                config.RunAsLocalSystem();
                config.StartAutomatically();
                config.EnableShutdown();

                config.Service <T>(service =>
                {
                    service.ConstructUsing(_ => new T
                    {
                        Logger     = logger,
                        Identifier = serviceName
                    });
                    service.WhenStarted(instance => instance.Start());
                    service.WhenStopped(instance => instance.Stop());
                });

                if (logger != null)
                {
                    config.UseSerilog(logger);
                }
            });


            // Run the service
            if (updater != null)
            {
                logger?.Information("Starting service with updater...");

                var service = new T
                {
                    Logger     = logger,
                    Identifier = serviceName
                };
                var x = new SquirreledHost(service, Assembly.GetExecutingAssembly(), updater);
                x.ConfigureAndRun(new SquirreledHost.ConfigureExt(con));
            }
            else
            {
                logger?.Information("Starting service without updater...");

                HostFactory.Run(con);
            }
        }