Esempio n. 1
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());
        }
Esempio n. 2
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;
        }
Esempio n. 3
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;
        }
Esempio n. 4
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();
            }
        }
        /// <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
            });
        }
Esempio n. 6
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;
        }
Esempio n. 7
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;
        }
Esempio n. 8
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;
        }
Esempio n. 9
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;
        }
        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();
            }
        }
Esempio n. 11
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;
        }
Esempio n. 12
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;
        }
Esempio n. 13
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());
        }
Esempio n. 14
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;
        }
Esempio n. 15
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;
        }
Esempio n. 16
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;
        }
Esempio n. 17
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 driveTimeConfig = File.ReadAllText(Path.Combine(path, "config.json"));
                    JObject json           = JObject.Parse(driveTimeConfig);

                    Template template = Template.Parse(json["apiKey"].ToString());
                    string apiKey     = template.Render(new
                    {
                        ApiKey = appSettings["ApiKey"]
                    });
                    json["apiKey"]  = apiKey;
                    driveTimeConfig = json.ToString();

                    service.ConstructUsing(name => new Worker(connection, appSettings, driveTimeConfig));
                    service.WhenStarted(worker => worker.Start());
                    service.WhenStopped(worker => worker.Stop());
                });
                app.StartAutomatically();
                app.RunAsLocalService();
                app.SetServiceName("DriveTime Service");
                app.SetDescription("Checks against the Google Distance Matrix API");

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

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

            Environment.ExitCode = exitCode;
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            ILogger errorLogger = null;

            try
            {
                _container = new WindsorContainer();
                _container.RegisterAll();

                _container.Register(Component.For <ILogger>().UsingFactoryMethod(() =>
                                                                                 _container.Resolve <LoggerFactory>()
                                                                                 .WriteToConsole()
                                                                                 .WriteToFile()
                                                                                 .CreateErrorLogger())
                                    .Named("Error")
                                    .LifestyleSingleton());

                _container.Register(Component.For <ILogger>().UsingFactoryMethod(() => _container.Resolve <LoggerFactory>()
                                                                                 .WriteToFile("SyncService")
                                                                                 .WriteToConsole()
                                                                                 .CreateApplicationLogger())
                                    .Named("SyncService")
                                    .LifestyleSingleton());

                _container.Register(Component.For <ILogger>().UsingFactoryMethod(() => _container.Resolve <LoggerFactory>()
                                                                                 .WriteToFile("Workflow")
                                                                                 .WriteToConsole()
                                                                                 .CreateApplicationLogger())
                                    .Named("Workflow")
                                    .LifestyleSingleton());

                errorLogger = _container.Resolve <ILogger>("Error");
                Log.Logger  = _container.Resolve <LoggerFactory>()
                              .WriteToFile("Topshelf")
                              .WriteToConsole()
                              .CreateApplicationLogger();


                /**
                 * Service can be installed via command line:
                 *  - {Service Folder}\FastSQL.Service.exe install -servicename test1 -displayname test1 -description test1
                 * Service can be remove via command line:
                 *  - {Service Folder}\FastSQL.Service.exe uninstall -servicename test1
                 **/
                TopshelfExitCode rc = HostFactory.Run(x =>
                {
                    x.Service <SyncService>(service =>
                    {
                        service.ConstructUsing(s => {
                            var svc = _container.Resolve <SyncService>();
                            return(svc);
                        });
                        service.WhenStarted(s => s.Start());
                        service.WhenStopped(s =>
                        {
                            try
                            {
                                s.Stop();
                            }
                            finally
                            {
                                _container.Release(s);
                            }
                        });
                    });
                    x.StartAutomatically();
                    x.UseSerilog();
                });

                var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());
                Environment.ExitCode = exitCode;
            }
            catch (Exception ex)
            {
                errorLogger?.Error(ex, "An error has occurred!!!");
                if (errorLogger == null) // this could be happend when ioc failed to register items
                {
                    Console.WriteLine(ex.ToString());
                }

                Console.ReadKey();
            }
        }