Exemplo n.º 1
0
 public TopshelfExitCode Run()
 {
     try
     {
         _log.Debug("Starting application.");
         _exitCode = TopshelfExitCode.Ok;
         if (_serviceHandle.Start(this) == false)
         {
             throw new TopshelfException("The application failed to start (return false).");
         }
         _log.InfoFormat("The {0} application is now running.", _settings.ServiceName);
     }
     catch (Exception ex)
     {
         var exceptionCallback = _settings.ExceptionCallback;
         if (exceptionCallback != null)
         {
             Exception exception = ex;
             exceptionCallback(exception);
         }
         _log.Error("An exception occurred", ex);
         HostLogger.Shutdown();
         return(TopshelfExitCode.AbnormalExit);
     }
     return(_exitCode);
 }
Exemplo n.º 2
0
        void StopService()
        {
            try
            {
                if (_hasCancelled == false)
                {
                    _log.InfoFormat("Stopping the {0} service", _settings.ServiceName);

                    if (!_serviceHandle.Stop(this))
                    {
                        throw new TopshelfException("The service failed to stop (returned false).");
                    }
                }
            }
            catch (Exception ex)
            {
                _settings.ExceptionCallback?.Invoke(ex);

                _log.Error("The service did not shut down gracefully", ex);
                _exitCode = TopshelfExitCode.ServiceControlRequestFailed;
            }
            finally
            {
                _serviceHandle.Dispose();

                _log.InfoFormat("The {0} service has stopped.", _settings.ServiceName);
            }
        }
Exemplo n.º 3
0
        static int Main(string[] args)
        {
            int syncInterval = Convert.ToInt16(ConfigurationManager.AppSettings["SyncInterval"]);

            var rc = HostFactory.New(x =>
            {
                x.Service <SyncingJobService>(sc =>
                {
                    sc.ConstructUsing(s => new SyncingJobService());
                    sc.WhenStarted((s, hostControl) => s.Start(hostControl));
                    sc.WhenStopped((s, hostControl) => s.Stop(hostControl));
                });

                x.RunAsLocalSystem()
                .DependsOnEventLog()
                .StartAutomatically()
                .EnableServiceRecovery(src => src.RestartService(1));

                x.SetServiceName("KL2 Files sync service");
                x.SetDisplayName("KL2 Files sync service");
                x.SetDescription("KL2 Files syncing job service");
            });

            TopshelfExitCode exitCode = TopshelfExitCode.AbnormalExit;

            try
            {
                exitCode = rc.Run();
            }
            catch (Exception e)
            {
                //Trace.TraceError(e, "ERROR on service starting.");
            }
            return((int)exitCode);
        }
Exemplo n.º 4
0
        public static void Main(string[] args)
        {
            StandardKernel kernel = new StandardKernel();

            kernel.Load("StanBot.*.dll");

            TopshelfExitCode topshelfExitCode = HostFactory.Run(x =>
            {
                x.Service <ServiceManager>(s =>
                {
                    s.ConstructUsing(name => kernel.Get <ServiceManager>());
                    s.WhenStarted(tc => AsyncContext.Run(tc.Start));
                    s.WhenStopped(tc => tc.Stop());
                });
                x.RunAsLocalSystem();

                x.UnhandledExceptionPolicy = UnhandledExceptionPolicyCode.LogErrorOnly;
                x.OnException(HandleException);

                x.SetDescription("Discord bot for the STAIR discord to authenticate students from HSLU. May include more features but I don't really know now so this is for everything else that may be integrated and not mentioned here. Bad Heineken!");
                x.SetDisplayName("STAIR Discord Bot");
                x.SetServiceName("STAIR Discord Bot");
            });

            int exitCode = (int)Convert.ChangeType(topshelfExitCode, topshelfExitCode.GetTypeCode());

            Environment.ExitCode = exitCode;
        }
Exemplo n.º 5
0
        public static int Main(string[] args)
        {
            // .\Syringe.Service.exe [verb] [-option:value] [-switch]
            // run Runs the service from the command line (default)
            // help or –help Displays help
            // install Installs the service

            var container = IoC.Initialize();

            TopshelfExitCode exitCode = HostFactory.Run(host =>
            {
                host.ApplyCommandLine();

                host.Service <Startup>(service =>
                {
                    service.ConstructUsing(() => container.GetInstance <Startup>());
                    service.WhenStarted(x => x.Start());
                    service.WhenStopped(x => x.Stop());
                });

                host.SetServiceName("Syringe");
                host.SetDisplayName("Syringe");
                host.SetDescription("Syringe RESTful API service");
            });

            return((int)exitCode);
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure(new FileInfo(Path.Combine(path, "log4net.config")));
            TopshelfExitCode returnCode = HostFactory.Run(app =>
            {
                app.UseLog4Net();
                app.Service <Worker>(service =>
                {
                    string dvsaConfig = File.ReadAllText(Path.Combine(path, "config.json"));
                    service.ConstructUsing(name => new Worker(connection, appSettings, dvsaConfig));
                    service.WhenStarted(worker => worker.Start());
                    service.WhenStopped(worker => worker.Stop());
                });
                app.StartAutomatically();
                app.RunAsLocalService();
                app.SetServiceName("DVSA Service");
                app.SetDescription("Checks vehicles against the DVSA MOT History API");

                app.EnableServiceRecovery(recovery =>
                {
                    recovery.RestartService(5);
                });
            });

            int exitCode = (int)Convert.ChangeType(returnCode, returnCode.GetTypeCode());

            Environment.ExitCode = exitCode;
        }
Exemplo n.º 7
0
        void CatchUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            _settings.ExceptionCallback?.Invoke((Exception)e.ExceptionObject);

            _log.Fatal("The service threw an unhandled exception", (Exception)e.ExceptionObject);

            HostLogger.Shutdown();

            if (e.IsTerminating)
            {
                _exitCode = TopshelfExitCode.UnhandledServiceException;
                _exit.Set();

#if !NET35
                // it isn't likely that a TPL thread should land here, but if it does let's no block it
                if (Task.CurrentId.HasValue)
                {
                    return;
                }
#endif

                // this is evil, but perhaps a good thing to let us clean up properly.
                int deadThreadId = Interlocked.Increment(ref _deadThread);
                Thread.CurrentThread.IsBackground = true;
                Thread.CurrentThread.Name         = "Unhandled Exception " + deadThreadId.ToString();
                while (true)
                {
                    Thread.Sleep(TimeSpan.FromHours(1));
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="cancelRunner"></param>
        /// <param name="companyConfig"></param>
        /// <param name="runnerProgress"></param>
        /// <returns></returns>
        private ServiceTaskResult RunWindowsService(CancellationToken cancelRunner, CompanyConfig companyConfig,
                                                    ServiceProgressInfo runnerProgress)
        {
            // NOTE: In order to get the initial code delivered, I am reusing the code, or parts of it at least,
            //		 from the original MakoRunner project that uses the Topshelf library. This is not ideal since
            //		 we lose a great deal of control over our services. However, we know the code works for one
            //		 company ID at a time, which is why I'm reusing here, in the Sequential portion of the IF clause.

            //
            TopshelfExitCode retCode = HostFactory.Run(x =>
            {
                x.Service <TopshelfWindowsService>(sc =>
                {
                    sc.ConstructUsing(name => new TopshelfWindowsService(companyConfig, runnerProgress));
                    sc.WhenStarted((s, hostControl) => s.Start(hostControl));
                    sc.WhenShutdown(s => s.Shutdown());
                    sc.WhenStopped((s, hostControl) => s.Stop(hostControl));
                });
                //
                x.SetServiceName($"CommRunner {companyConfig.CompanyName + companyConfig.CompanyId}");
                x.SetDescription($"Mako Commission Runner for CompanyID ({companyConfig.CompanyId})");
                x.SetDisplayName($"Mako Commission Runner {companyConfig.CompanyId}");
                //
                //x.StartAutomaticallyDelayed();
            });
            //
            int exitCode = (int)Convert.ChangeType(retCode, retCode.GetTypeCode());

            // Create and return a ServiceTaskResult.
            // TODO: Add properties to the ServiceTaskResult and populate based on service exit code, etc.
            return(new ServiceTaskResult()
            {
                ServiceReturnCode = exitCode
            });
        }
Exemplo n.º 9
0
        private void CatchUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            _logWriter.Fatal(string.Format(Resources.UnhandledException, _settings.ServiceName), (Exception)e.ExceptionObject);

            HostLogger.Shutdown();

            if (e.IsTerminating)
            {
                _exitCode = TopshelfExitCode.UnhandledServiceException;

                SetStopSignal();

                // Author Topshelf: it isn't likely that a TPL thread should land here, but if it does let's no block it
                if (!Task.CurrentId.HasValue)
                {
                    // Author Topshelf: this is evil, but perhaps a good thing to let us clean up properly

                    var deadThreadId = Interlocked.Increment(ref _deadThread);

                    Thread.CurrentThread.IsBackground = true;
                    Thread.CurrentThread.Name         = "Unhandled Exception " + deadThreadId;

                    while (true)
                    {
                        Thread.Sleep(TimeSpan.FromHours(1));
                    }
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            TopshelfExitCode exitcode = HostFactory.Run(x =>
            {
                x.RunAsLocalSystem();
                x.SetDescription("Open Account Windows Service");
                x.SetDisplayName("Open Account Service");
                x.SetServiceName("OpenAccountService");

                x.Service <OAService>(service =>
                {
                    service.ConstructUsing(name => new OAService());

                    service.WhenStarted(tc =>
                    {
                        tc.Start();
                        x.StartAutomatically();
                    });

                    service.WhenStopped(tc =>
                    {
                        tc.Stop();
                    });
                });
            });
        }
Exemplo n.º 11
0
        public static int Main(string[] args)
        {
            ITraceManager traceManager = new Log4netTraceManager(new Log4netWrapper());

            var rc = HostFactory.New(x =>
            {
                x.Service <ApiService>(sc =>
                {
                    sc.ConstructUsing(s => new ApiService());
                    sc.WhenStarted((s, hostControl) => s.Start(hostControl));
                    sc.WhenStopped((s, hostControl) => s.Stop(hostControl));
                });

                x.RunAsLocalSystem();
                x.SetDescription(ApiService.Description);
                x.SetDisplayName(ApiService.DisplayName);
                x.SetServiceName(ApiService.ServiceName);

                x.EnableServiceRecovery(recoveryOption => recoveryOption.RestartService(0));
                x.StartAutomaticallyDelayed();
            });

            TopshelfExitCode exitCode = TopshelfExitCode.AbnormalExit;

            try
            {
                exitCode = rc.Run();
            }
            catch (Exception e)
            {
                traceManager.TraceError(e, "ERROR on service starting.");
            }
            return((int)exitCode);
        }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            TopshelfExitCode rc = HostFactory.Run(X =>
            {
                X.RunAsLocalSystem();//服务使用NETWORK_SERVICE内置帐户运行。
                //身份标识,有好几种方式,如:X.RunAs("username", "password"); X.RunAsPrompt(); X.RunAsNetworkService(); 等

                X.SetDisplayName("自动服务");//显示名称
                X.SetDescription("任务调度系统的服务");//安装服务后,服务的描述
                X.SetServiceName("自动服务");//服务名称

                X.UseOwin(baseAddress: "http://localhost:9000/");

                X.SetStartTimeout(TimeSpan.FromMinutes(5));//设置超时之前等待服务启动的时间。 默认值为10秒。
                X.SetStopTimeout(TimeSpan.FromMinutes(35));//设置超时之前等待服务停止的时间。 默认值为10秒。

                //设置服务失败后的操作
                X.EnableServiceRecovery(r =>
                {
                    r.RestartService(1); //等待延迟时间(分钟)后重新启动服务
                });
            });
            Environment.ExitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());

            RecurringJob.AddOrUpdate<SampleService>("TestSimpleJob", X => X.SimpleJob(null), Cron.Minutely(), TimeZoneInfo.Local);

            using (var server = new BackgroundJobServer())
            {
                Console.ReadLine();
            }
        }
Exemplo n.º 13
0
        private static int Main(string[] args)
        {
            IWindsorContainer container = CreateContainer();

            TopshelfExitCode exitCode = HostFactory.Run(
                config =>
            {
                config.Service <TimesheetProcessingService>(
                    s =>
                {
                    s.ConstructUsing(f => container.Resolve <TimesheetProcessingService>());

                    s.WhenStarted(f => f.Start());
                    s.WhenStopped(f => f.Stop());

                    s.WhenShutdown((service, host) => container.Release(service));
                });


                config.RunAsLocalSystem();
                config.SetServiceName(ConfigurationManager.AppSettings["TopShelf.Service.Name"]);
                config.SetDisplayName(ConfigurationManager.AppSettings["TopShelf.Service.DisplayName"]);
                config.SetDescription(ConfigurationManager.AppSettings["TopShelf.Service.Description"]);
            });

            return((int)exitCode);
        }
Exemplo n.º 14
0
        private static TopshelfExitCode RunServiceNormally <TService>(Action <HostConfigurator, TService> options)
            where TService : IService, new()
        {
            TopshelfExitCode code = HostFactory.Run(x =>
            {
                options(x, (TService)_serviceProxy.Service);
                VersionLogger.LogVersions();

                x.Service <ServiceProxy>(s =>
                {
                    s.ConstructUsing(name => _serviceProxy);
                    s.WhenStarted(StartService);
                    s.WhenStopped(tc => tc.Stop());
                    s.WhenShutdown(tc => tc.Stop());
                });

                x.EnableShutdown();
                x.EnableServiceRecovery(ConfigureRecovery);
                x.RunAsLocalSystem();

                Assembly serviceAssembly = Assembly.GetEntryAssembly();
                string serviceName       = GetServiceName(serviceAssembly);
                x.SetServiceName(serviceName);
                x.SetDisplayName(serviceName.Replace('.', ' '));
                x.SetDescription(GetServiceDescription(serviceAssembly));
            });

            return(code);
        }
Exemplo n.º 15
0
        private void RunService(ServiceController <IGaiaService> serviceController)
        {
            _topshelfExitCode = HostFactory.Run(x =>
            {
                //x.UseLinuxIfAvailable();
                x.ApplyCommandLine();

                x.StartAutomatically();
                x.RunAsNetworkService();
                x.EnableShutdown();
                x.EnableServiceRecovery(r => r.RestartService(2));
                x.EnablePauseAndContinue();

                x.SetDescription(Description);
                x.SetDisplayName(DisplayName);
                x.SetServiceName(ServiceName);
                x.Service(
                    s => serviceController,
                    e => {
                    e.AfterStoppingService(() => serviceController.Dispose());
                });
            });

            Environment.ExitCode = (int)Convert.ChangeType(_topshelfExitCode, _topshelfExitCode.GetTypeCode());
        }
Exemplo n.º 16
0
        private Program Run()
        {
            _logger.Information("Starting TopShelf host...");

            _exitCode =
                HostFactory.Run(
                    hostConfig =>
            {
                hostConfig.Service <PlayLogger>(
                    serviceConfig =>
                {
                    serviceConfig.ConstructUsing(() => _container.GetInstance <PlayLogger>());
                    serviceConfig.WhenStarted(x => x.Start());
                    serviceConfig.WhenStopped(x => x.Stop());
                });
                hostConfig.RunAsLocalSystem();

                hostConfig.SetServiceName(ServiceName);
                hostConfig.SetDisplayName(ServiceDisplayName);
                hostConfig.SetDescription(ServiceDescription);
            });

            _logger.Information("TopShelf host completed");
            return(this);
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            if (args.Length == 0 && Environment.UserInteractive)
            {
                IsConsoleMode = true;
                InstanceProvider.GetServiceLogger().AppendLine("BedrockService startup detected in Console mode.");;
            }
            Host host = HostFactory.New(x =>
            {
                x.SetStartTimeout(TimeSpan.FromSeconds(10));
                x.SetStopTimeout(TimeSpan.FromSeconds(10));
                //x.UseLog4Net();
                x.UseAssemblyInfoForServiceInfo();
                x.Service(settings => InstanceProvider.GetBedrockService(), s =>
                {
                    s.BeforeStartingService(_ => InstanceProvider.GetServiceLogger().AppendLine("Starting service..."));
                    s.BeforeStoppingService(_ => InstanceProvider.GetServiceLogger().AppendLine("Stopping service..."));
                });


                x.RunAsLocalSystem();
                x.SetDescription("Windows Service Wrapper for Windows Bedrock Server");
                x.SetDisplayName("BedrockService");
                x.SetServiceName("BedrockService");
                x.UnhandledExceptionPolicy = UnhandledExceptionPolicyCode.LogErrorOnly;

                x.EnableServiceRecovery(src =>
                {
                    src.RestartService(delayInMinutes: 0);
                    src.RestartService(delayInMinutes: 1);
                    src.SetResetPeriod(days: 1);
                });

                x.OnException((ex) =>
                {
                    InstanceProvider.GetServiceLogger().AppendLine("Exception occured Main : " + ex.ToString());
                });
            });

            TopshelfExitCode rc = host.Run();
            var exitCode        = (int)Convert.ChangeType(rc, rc.GetTypeCode());

            if (DebugModeEnabled)
            {
                Console.Write("Program is force-quitting. Press any key to exit.");
                Console.Out.Flush();
                Console.ReadLine();
            }
            Environment.ExitCode = exitCode;
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            var mode            = ConfigurationManager.AppSettings["MPE.Pinger.Mode"]?.ToLowerInvariant();
            TopshelfExitCode rc = TopshelfExitCode.Ok;

            switch (mode)
            {
            case "server":
                rc = HostFactory.Run(x =>
                {
                    x.Service <ServerStartup>(s =>
                    {
                        s.ConstructUsing(name => new ServerStartup());
                        s.WhenStarted(tc => tc.Start());
                        s.WhenStopped(tc => tc.Stop());
                    });
                    x.RunAsLocalSystem();

                    x.SetDescription("Server to receive metric results");
                    x.SetDisplayName("MPE_Pinger_Server");
                    x.SetServiceName("MPE_Pinger_Server");
                });
                break;

            case "client":
                rc = HostFactory.Run(x =>
                {
                    x.Service <ClientStartup>(s =>
                    {
                        s.ConstructUsing(name => new ClientStartup());
                        s.WhenStarted(tc => tc.Start());
                        s.WhenStopped(tc => tc.Stop());
                    });
                    x.RunAsLocalSystem();

                    x.SetDescription("Service to call different endpoint to check for life");
                    x.SetDisplayName("MPE_Pinger");
                    x.SetServiceName("MPE_Pinger");
                });
                break;
            }

            Console.ReadLine();

            var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());

            Environment.ExitCode = exitCode;
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            TopshelfExitCode exitCode = TopshelfExitCode.Ok;

            try
            {
                // https://github.com/serilog/serilog/wiki/AppSettings
                Log.Logger = new LoggerConfiguration()
                             .ReadFrom.AppSettings()
                             .CreateLogger();

                Log.Information("*** Begin Application. ***");

                exitCode = HostFactory.Run(x =>
                {
                    var settings = new LoggerJsonSettings().Load();
                    Log.Information("Loaded settings at {0}", settings.DefaultPath);
                    x.Service <LoggerService>(s =>
                    {
                        s.ConstructUsing(name => new LoggerService(settings));
                        s.WhenStarted(tc => tc.Start());
                        s.WhenStopped(tc => tc.Stop());
                    });

                    x.EnableServiceRecovery(r =>
                    {
                        r.OnCrashOnly();
                        r.RestartService(1); //first
                        r.RestartService(1); //second
                        r.RestartService(1); //subsequents
                    });
                    //Windowsサービスの設定
                    x.RunAs(settings.LoggerSettings.ServiceUserName, settings.LoggerSettings.ServicePassword);

                    x.SetDescription(loggerConstants.ServiceDescription);
                    x.SetDisplayName(loggerConstants.ServiceDsiplayName);
                    x.SetServiceName(loggerConstants.ServiceServiceName);
                    x.StartAutomaticallyDelayed();
                });
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Topshelf down?");
            }
            finally
            {
                Log.Information("*** Topshelf exit code is {0} ***", exitCode);
                Log.CloseAndFlush();
            }
        }
Exemplo n.º 20
0
        static void Main()
        {
            TopshelfExitCode topshelfExitCode = HostFactory.Run(configure =>
            {
                configure.Service <ObsOverwatchService>();
                configure.RunAsLocalSystem();
                configure.SetServiceName("OBS Overwatch");
                configure.SetDisplayName("OBS Overwatch");
                configure.SetDescription("Service that controls OBS program and manages automatic recovery from failure.");
            });

            int exitCode = (int)Convert.ChangeType(topshelfExitCode, topshelfExitCode.GetTypeCode());

            Environment.ExitCode = exitCode;
        }
Exemplo n.º 21
0
        public static int Service <TService>()
            where TService : IService, new()
        {
            Type serviceType = typeof(TService);

            _serviceProxy = new ServiceProxy(serviceType);

            ProcessCustomCommand();

            if (!_startService)
            {
                return(0);
            }

            TopshelfExitCode code = RunServiceNormally <TService>(serviceType);

            HostLogger.Shutdown();
            return((int)code);
        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            TopshelfExitCode TSExitCode = HostFactory.Run(x =>
            {
                x.Service <Observer>(s =>
                {
                    s.ConstructUsing(Observer => new Observer());
                    s.WhenStarted(Observer => Observer.Start());
                    s.WhenStopped(Observer => Observer.Stop());
                });
                x.RunAsLocalSystem();
                x.StartAutomatically();
                x.SetDisplayName("ProccessObserverLocal");
                x.SetDescription("Observes all starting services and writes their names in a log file");
            });
            int exitCode = (int)Convert.ChangeType(TSExitCode, TSExitCode.GetTypeCode());

            Environment.ExitCode = exitCode;
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            try
            {
                Type       service_type     = Type.GetType($"Service_Project.Services.{SERVICE_NAME}");
                MethodInfo get_host_factory = service_type.GetMethod(
                    "GetHostFactory", BindingFlags.Static | BindingFlags.Public);

                TopshelfExitCode exit_code = (TopshelfExitCode)get_host_factory.Invoke(null, null);

                int exit_code_value = (int)Convert.ChangeType(exit_code, exit_code.GetTypeCode());
                Environment.ExitCode = exit_code_value;
            }
            catch (Exception exception)
            {
                Console.WriteLine($"{exception.GetType()}: {exception.Message}");
                Console.ReadKey();
            }
        }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                                               .AddJsonFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Constants.AppSettingsFileName))
                                               .Build();

            IServiceCollection services = new ServiceCollection()
                                          .AddLogging()
                                          .EnableTraceLogging()
                                          .AddCloudFtpBridgeCore(configuration.GetSection(Constants.CloudFtpBridgeConfigSectionName))
                                          .AddCloudFtpBridgeService();

            IServiceProvider serviceProvider = services.BuildServiceProvider();
            ILoggerFactory   loggerFactory   = serviceProvider.GetService <ILoggerFactory>();

            loggerFactory.AddPsgLogging(configuration.GetSection(Constants.LoggingConfigSectionName));

            TopshelfExitCode topshelfExitCode = HostFactory.Run(topshelf =>
            {
                topshelf.EnableServiceRecovery(x =>
                {
                    x.RestartService(1).RestartService(2).RestartService(4);
                });

                topshelf.Service <PollingService>(service =>
                {
                    service.ConstructUsing(() => serviceProvider.GetService <PollingService>());
                    service.WhenStarted(x => x.Start());
                    service.WhenStopped(x => x.Stop());
                });

                topshelf.RunAsLocalService();
                topshelf.SetDescription(_ServiceDescription);
                topshelf.SetDisplayName(_ServiceDisplayName);
                topshelf.SetServiceName(_ServiceName);
                topshelf.StartAutomatically();
            });

            int exitCode = (int)Convert.ChangeType(topshelfExitCode, topshelfExitCode.GetTypeCode());

            Environment.ExitCode = exitCode;
        }
Exemplo n.º 25
0
        /// <summary>
        /// Main
        /// </summary>
        /// <param name="args"></param>
        /// <returns>Returns void.</returns>
        public static void Main(string[] args)
        {
            bool result = BootLoader();

            if (!result)
            {
                return;
            }

            SCHostLoader Hostloader = new SCHostLoader();

            TopshelfExitCode rc = HostFactory.Run(x =>
            {
                x.Service <SCLoader>(sc =>
                {
                    sc.ConstructUsing(name => new SCLoader());

                    sc.WhenStarted(tc => tc.WhenStart());
                    sc.WhenStopped(tc => tc.WhenStop());
                    sc.WhenPaused(tc => tc.WhenPause());
                    sc.WhenContinued(tc => tc.WhenContinue());
                    sc.WhenShutdown(tc => tc.WhenShutdown());
                });

                x.RunAsLocalSystem();

                x.SetServiceName(DeployServer.ServiceName);
                x.SetDisplayName(DeployServer.ServiceDisplayName);
                x.SetInstanceName(DeployServer.ServiceInstanceName);
                x.SetDescription(DeployServer.ServiceDescription);

                x.BeforeInstall(settings => Hostloader.BeforeInstall());
                x.BeforeUninstall(() => Hostloader.BeforeUninstall());

                x.AfterInstall(settings => Hostloader.AfterInstall());
                x.AfterUninstall(() => Hostloader.AfterUninstall());
            });

            int exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode(), CultureInfo.InvariantCulture);

            Environment.ExitCode = exitCode;
        }
Exemplo n.º 26
0
        static void Main()
        {
            TopshelfExitCode returnCode = HostFactory.Run(x =>
            {
                x.Service <WebService>(s =>
                {
                    s.ConstructUsing(name => new WebService());
                    s.WhenStarted(ws => ws.Start());
                    s.WhenStopped(ws => ws.Stop());
                });

                x.RunAsLocalService();

                x.SetDescription("SVB-Ticker service for live results.");
                x.SetDisplayName("SVB-Ticker");
                x.SetServiceName("SVB-Ticker");
            });

            Environment.ExitCode = (int)Convert.ChangeType(returnCode, returnCode.GetTypeCode());
        }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            TopshelfExitCode exitCode = HostFactory.Run(x =>
            {
                x.Service <GooseBotService>(s =>
                {
                    s.ConstructUsing(gooseBot => new GooseBotService());
                    s.WhenStarted(gooseBot => gooseBot.Start());
                    s.WhenStopped(gooseBot => gooseBot.Stop());
                });

                x.RunAsLocalSystem();
                x.SetServiceName("GooseBot");
                x.SetDisplayName("Goose Bot");
                x.SetDescription("My first Discord bot. Honk!");
            });

            int exitCodeValue = (int)Convert.ChangeType(exitCode, exitCode.GetTypeCode());

            Environment.ExitCode = exitCodeValue;
        }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            TopshelfExitCode exitCode = HostFactory.Run(x =>
            {
                x.Service <HeartBeat>(s =>
                {
                    s.ConstructUsing(heartbeat => new HeartBeat());
                    s.WhenStarted(heartbeat => heartbeat.Start());
                    s.WhenStopped(heartbeat => heartbeat.Stop());
                });

                x.RunAsLocalSystem();
                x.SetServiceName("HeartBeatService");
                x.SetDisplayName("HeartBeat Service");
                x.SetDescription("Test service");
            });

            int exitCodeValue = (int)Convert.ChangeType(exitCode, exitCode.GetTypeCode());

            Environment.ExitCode = exitCodeValue;
        }
Exemplo n.º 29
0
        internal static TopshelfExitCode Configure( )
        {
            TopshelfExitCode exitCode = TopshelfExitCode.Ok;

            try
            {
                var containerBuilder = new ContainerBuilder();
                containerBuilder.RegisterType <RealWork>().As <IAmDoingRealWork>();
                containerBuilder.RegisterType <MyService>();

                var container = containerBuilder.Build();

                exitCode = HostFactory.Run(x =>
                {
                    x.UseAutofacContainer(container);

                    x.Service <MyService>(hostSettings =>
                    {
                        hostSettings.ConstructUsing(() => container.Resolve <MyService>());

                        hostSettings.WhenStarted(s => s.StartService());
                        hostSettings.WhenStopped(s => s.StopService());
                    });

                    x.RunAsLocalSystem();
                    x.StartAutomatically();

                    x.SetServiceName("TopshelfTemplateService");
                    x.SetDisplayName("TopshelfTemplateService");
                    x.SetDescription("TopshelfTemplateService");
                });
            }
            catch (Exception ex)
            {
                Log.Information(ex, "Error in ConfigureService.Configure()");
                throw;
            }

            return(exitCode);
        }
Exemplo n.º 30
0
        static void Main(string[] args)
        {
            TopshelfExitCode rc = HostFactory.Run(x =>
            {
                x.Service <GenericRestService>(s =>
                {
                    s.ConstructUsing(name => new GenericRestService());
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc => tc.Stop());
                });

                x.RunAsLocalSystem();

                x.SetDescription("Generic POS Rest Service");
                x.SetDisplayName("Generic POS Rest Service");
                x.SetServiceName("GenericPOSRestService");
            });

            int exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());

            Environment.ExitCode = exitCode;
        }
Exemplo n.º 31
0
        public TopshelfExitCode Run()
        {
            AppDomain.CurrentDomain.UnhandledException += CatchUnhandledException;
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            _exitCode = TopshelfExitCode.Ok;

            _signalListener.Listen();

            var started = false;

            try
            {
                StartService();
                started = true;

                WaitStopSignal();
            }
            catch (Exception error)
            {
                _logWriter.Fatal(error);

                _exitCode = TopshelfExitCode.AbnormalExit;
            }
            finally
            {
                if (started)
                {
                    StopService();
                }

                HostLogger.Shutdown();
            }

            return _exitCode;
        }
Exemplo n.º 32
0
        void CatchUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            _settings.ExceptionCallback?.Invoke((Exception)e.ExceptionObject);

            _log.Fatal("The service threw an unhandled exception", (Exception)e.ExceptionObject);

            HostLogger.Shutdown();

            if (e.IsTerminating)
            {
                _exitCode = TopshelfExitCode.UnhandledServiceException;
                _exit.Set();

            #if !NET35
                // it isn't likely that a TPL thread should land here, but if it does let's no block it
                if (Task.CurrentId.HasValue)
                {
                    return;
                }
            #endif

                // this is evil, but perhaps a good thing to let us clean up properly.
                int deadThreadId = Interlocked.Increment(ref _deadThread);
                Thread.CurrentThread.IsBackground = true;
                Thread.CurrentThread.Name = "Unhandled Exception " + deadThreadId.ToString();
                while (true)
                    Thread.Sleep(TimeSpan.FromHours(1));
            }
        }
Exemplo n.º 33
0
        private void CatchUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            _logWriter.Fatal(string.Format(Resources.UnhandledException, _settings.ServiceName), (Exception)e.ExceptionObject);

            HostLogger.Shutdown();

            if (e.IsTerminating)
            {
                _exitCode = TopshelfExitCode.UnhandledServiceException;

                SetStopSignal();

                // Author Topshelf: it isn't likely that a TPL thread should land here, but if it does let's no block it
                if (!Task.CurrentId.HasValue)
                {
                    // Author Topshelf: this is evil, but perhaps a good thing to let us clean up properly

                    var deadThreadId = Interlocked.Increment(ref _deadThread);

                    Thread.CurrentThread.IsBackground = true;
                    Thread.CurrentThread.Name = "Unhandled Exception " + deadThreadId;

                    while (true)
                    {
                        Thread.Sleep(TimeSpan.FromHours(1));
                    }
                }
            }
        }
Exemplo n.º 34
0
        public TopshelfExitCode Run()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            AppDomain.CurrentDomain.UnhandledException += CatchUnhandledException;

            if (_environment.IsServiceInstalled(_settings.ServiceName))
            {
                if (!_environment.IsServiceStopped(_settings.ServiceName))
                {
                    _log.ErrorFormat("The {0} service is running and must be stopped before running via the console",
                        _settings.ServiceName);

                    return TopshelfExitCode.ServiceAlreadyRunning;
                }
            }

            bool started = false;
            try
            {
                _log.Debug("Starting up as a console application");

                _exit = new ManualResetEvent(false);
                _exitCode = TopshelfExitCode.Ok;

                Console.Title = _settings.DisplayName;
                Console.CancelKeyPress += HandleCancelKeyPress;

                if (!_serviceHandle.Start(this))
                    throw new TopshelfException("The service failed to start (return false).");

                started = true;

                _log.InfoFormat("The {0} service is now running, press Control+C to exit.", _settings.ServiceName);

                _exit.WaitOne();
            }
            catch (Exception ex)
            {
                _settings.ExceptionCallback?.Invoke(ex);

                _log.Error("An exception occurred", ex);

                return TopshelfExitCode.AbnormalExit;
            }
            finally
            {
                if (started)
                    StopService();

                _exit.Close();
                (_exit as IDisposable).Dispose();

                HostLogger.Shutdown();
            }

            return _exitCode;
        }