示例#1
0
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            // in addition to the arguments that the service has been registered with,
            // each service start may add additional startup parameters.
            // To test this: Open services console, open service details, enter startup arguments and press start.
            _logger.Info("Windows service starting");
            try
            {
                string[] combinedArguments;
                if (startupArguments.Length > 0)
                {
                    combinedArguments = new string[commandLineArguments.Length + startupArguments.Length];
                    Array.Copy(commandLineArguments, combinedArguments, commandLineArguments.Length);
                    Array.Copy(startupArguments, 0, combinedArguments, commandLineArguments.Length, startupArguments.Length);
                }
                else
                {
                    combinedArguments = commandLineArguments;
                }


                OnStart?.Invoke(this, new StringsEventArgs(combinedArguments));
            }
            catch (Exception ex)
            {
                _logger.Fatal("Service start failure: " + ex.ToString());
                throw;
            }
        }
示例#2
0
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            //Task.Delay(20000).Wait();
            _logger.LogInformation("-----------------------------Start  All In One Service-----------------------------");
            _logger.LogInformation("-----------------------------Run ForwardAlarmLogTask-----------------------------");
            MyMigration.Migrate();

            //启动报警上传检测
            ForwardAlarmLogTask.Instance.Run();

            //启动预案任务
            PlanTaskScheduler.Instance.Start();

            //启动查勤包生成线程
            DutyCheckPackageRunner.Instance.Start();

            WebHost = new WebHostBuilder().UseKestrel()
                      .UseUrls("http://*:5001")
                      .UseStartup <Startup>()
                      .Build();

            WebHost
            .Services
            .GetRequiredService <IApplicationLifetime>()
            .ApplicationStopped
            .Register(() =>
            {
                if (StopRequestedByWindows == false)
                {
                    serviceStoppedCallback();
                }
            });
            _logger.LogInformation("-----------------------------Run WebHostBuilder-----------------------------");
            WebHost.Start(); //注意:以服务的方式启动不要用扩展方法Run(),避免服务不能完全启动。(可能是阻塞导致)
        }
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            const string staging = "staging";

            if (!Directory.Exists(staging))
            {
                Logger.Info($"Creating staging directory: {Path.GetFullPath(staging)}");
                Directory.CreateDirectory(staging);
            }
            else
            {
                Logger.Info($"Since staging directory already exists at {Path.GetFullPath(staging)}, not creating it");
            }
            const string filter = "cafe-*.zip";

            Logger.Info($"Setting up file watcher to watch for {filter}");
            _watcher = new FileSystemWatcher(staging)
            {
                Filter = filter
            };
            _watcher.Created += WatcherOnCreated;
            _watcher.Deleted += WatcherOnDeleted;

            Logger.Debug("Watching for files");
            _watcher.EnableRaisingEvents = true;
        }
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            // in addition to the arguments that the service has been registered with,
            // each service start may add additional startup parameters.
            // To test this: Open services console, open service details, enter startup arguments and press start.
            string[] combinedArguments;
            if (startupArguments.Length > 0)
            {
                combinedArguments = new string[commandLineArguments.Length + startupArguments.Length];
                Array.Copy(commandLineArguments, combinedArguments, commandLineArguments.Length);
                Array.Copy(startupArguments, 0, combinedArguments, commandLineArguments.Length, startupArguments.Length);
            }
            else
            {
                combinedArguments = commandLineArguments;
            }

            webHost = Program.BuildWebHost(combinedArguments);

            // Make sure the windows service is stopped if the
            // ASP.NET Core stack stops for any reason
            webHost
            .Services
            .GetRequiredService <IApplicationLifetime>()
            .ApplicationStopped
            .Register(() =>
            {
                if (stopRequestedByWindows == false)
                {
                    serviceStoppedCallback();
                }
            });

            webHost.Start();
        }
示例#5
0
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            string[] withArgs;
            if (startupArguments.Length > 0)
            {
                withArgs = new string[args.Length + startupArguments.Length];
                Array.Copy(args, withArgs, args.Length);
                Array.Copy(startupArguments, 0, withArgs, args.Length, startupArguments.Length);
            }
            else
            {
                withArgs = args;
            }

            //start web browser
            browser = new Browser();

            //start WCF TCP Service Host
            var baseAddress = "http://localhost:7077/Browser";

            host = new BrowserServiceHost(browser, new Uri(baseAddress));
            //host.AddServiceEndpoint(typeof(Browser), new BasicHttpBinding(), "");
            host.Open();
            Console.WriteLine("WCF host opened at " + baseAddress);
        }
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            Logger.Info("Starting service");
            var config = new ConfigurationBuilder()
                         // .AddCommandLine(args)
                         .AddEnvironmentVariables(prefix: "ASPNETCORE_")
                         .Build();

            _webHost = new WebHostBuilder()
                       .UseUrls($"http://*:{ServerSettings.Instance.Port}/")
                       .UseConfiguration(config)
                       .UseKestrel()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseIISIntegration()
                       .UseStartup <Startup>()
                       .Build();

            _webHost.Services.GetRequiredService <IApplicationLifetime>()
            .ApplicationStopped
            .Register(() =>
            {
                if (!_stopRequestedByWindows)
                {
                    serviceStoppedCallback();
                }
            });

            Initialize();

            ReactToChangesToServerConfiguration();
            ReactToChangesToChefClientRunning();

            _webHost.Start();
        }
示例#7
0
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            var responder = new KestrelResponder();

            _listener = new DistributingKestrelServer(8080);
            _listener.AddResponder(responder);
            _listener.Start();
        }
示例#8
0
 public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
 {
     System.IO.File.AppendAllText(logPath, $"{Environment.NewLine}{DateTime.Now} start");
     IsRunning      = true;
     timer          = new Timer();
     timer.Interval = 5000;
     timer.Elapsed += new ElapsedEventHandler(DoWork);
     timer.Enabled  = true;
 }
示例#9
0
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            _host = new WebHostBuilder()
                    .UseKestrel()
                    .UseUrls("http://*:5001")
                    .UseStartup <Startup>()
                    .Build();

            _host.Start();
        }
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            Logger.Log(LogLevel.Info, "Service Starting.");

            string url = null;
            string dynamoDbConfigJson = null;

            var builder = new ConfigurationBuilder();

            builder.AddCommandLine(startupArguments);

            if (!this.StartupConfig.IsTest)
            {
                // No need to spend time checking dynamo db if in test mode
                dynamoDbConfigJson = DynamoDbConfigurationProviderFactory.Create().GetJson();

                if (!string.IsNullOrWhiteSpace(dynamoDbConfigJson))
                {
                    var dynamoAppSettingsFileName = "appsettings.dynamodb.json";
                    var provider = new InMemoryFileProvider();
                    provider.Directory.AddFile("/", new StringFileInfo(dynamoDbConfigJson, dynamoAppSettingsFileName));
                    provider.EnsureFile($"/{dynamoAppSettingsFileName}");

                    builder.AddJsonFile(provider, $"/{dynamoAppSettingsFileName}", false, false);
                }
            }

            var config = builder.Build();

            url = config.GetValue <string>("SurveillanceApiUrl");

            if (string.IsNullOrWhiteSpace(url))
            {
                url = "https://localhost:8888";
            }

            this._webHost = CreateWebHostBuilder(startupArguments, dynamoDbConfigJson, url, this.StartupConfig).Build();

            // Make sure the windows service is stopped if the
            // ASP.NET Core stack stops for any reason
            this._webHost.Services.GetRequiredService <IHostApplicationLifetime>().ApplicationStopped.Register(
                () =>
            {
                if (this._stopRequestedByWindows == false)
                {
                    serviceStoppedCallback();
                }
            });

            Logger.Log(LogLevel.Info, "WebHost Starting.");
            this._webHost.Start();
            Logger.Log(LogLevel.Info, "WebHost Started.");

            Logger.Log(LogLevel.Info, "Service Started.");
        }
示例#11
0
        private void GivenTheServiceHasBeenStarted()
        {
            A.CallTo(() => serviceImplmentation.Start(null, null))
            .WithAnyArguments()
            .Invokes((string[] args, ServiceStoppedCallback stoppedCallback) =>
            {
                serviceStoppedCallbackPassedToImplementation = stoppedCallback;
            });

            sut.OnStart(TestStartupArguments, statusReportCallback);
        }
示例#12
0
 public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
 {
     _simpbotClient.StopCallback = () =>
     {
         if (_stopRequestedByWindows)
         {
             serviceStoppedCallback.Invoke();
         }
     };
     _simpbotClient.StartAsync().GetAwaiter();
 }
示例#13
0
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            ImportSettings();
            singularity = Singularity.Instance;
            var job = new SimpleJob((scheduledTime) =>
                                    GetAndCompareCommits());
            var schedule     = new EveryXTimeSchedule(TimeSpan.FromSeconds(12));
            var scheduledJob = singularity.ScheduleJob(schedule, job, true);

            singularity.Start();
        }
示例#14
0
 public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
 {
     GlobalConfiguration.Configuration.ConfigureAppEndpoints();
     GlobalConfiguration.Configuration.UseRabbitMQHost(new RabbitMQHostOptions()
     {
         HostName            = Configuration.Current["AccessData:RabbitMQ:HostName"],
         UserName            = Configuration.Current["AccessData:RabbitMQ:UserName"],
         Password            = Configuration.Current["AccessData:RabbitMQ:Password"],
         MessageQueue        = Configuration.Current["AccessData:RabbitMQ:MessageQueue"],
         InvalidMessageQueue = Configuration.Current["AccessData:RabbitMQ:InvalidMessageQueue"]
     });
 }
示例#15
0
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            Console.WriteLine("Starting Bladr as a Windows Service");

            if (string.IsNullOrWhiteSpace(this.ContentRootPath))
            {
                throw new ArgumentNullException("ContentRootPath", "Path is missing.");
            }

            this.WebHost = Host.ServiceBuildHost(this.ContentRootPath, this.StopRequestedByWindows, serviceStoppedCallback);
            this.WebHost.Start();
        }
示例#16
0
 public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
 {
     try
     {
         onStart();
     }
     catch (Exception)
     {
         onStopped();
         serviceStoppedCallback();
     }
 }
示例#17
0
 public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
 {
     try
     {
         _onStart?.Invoke();
     }
     catch (Exception)
     {
         _onStopped?.Invoke();
         serviceStoppedCallback?.Invoke();
     }
 }
示例#18
0
 // Windows Service start.
 public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
 {
     log.Info("Scheduler start");
     try
     {
         //Start the job
         scheduler.Start().ConfigureAwait(false).GetAwaiter().GetResult();
     }
     catch (Exception e)
     {
         log.Error($"Eerror when starting the job{System.Environment.NewLine}{e.Message}");
     }
 }
示例#19
0
        public void Start(string[] startupAruments, ServiceStoppedCallback serviceStoppedCallback)
        {
            try {
                // Register an IPC channel
                IpcServerChannel = new IpcServerChannel(IpcChannelName);
                ChannelServices.RegisterChannel(IpcServerChannel, false);

                // Expose an object
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(ServiceDocker), "docker", WellKnownObjectMode.Singleton);
            } catch (Exception) {
                serviceStoppedCallback();
            }
        }
示例#20
0
 public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
 {
     //File.Create("C:\\GotThere.ServiceBase.txt");
     try
     {
         Start();
     }
     catch (Exception exception)
     {
         Logger.LogCritical($"{ServiceName} Start threw an exception.", exception);
         serviceStoppedCallback.Invoke();
     }
 }
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            try
            {
                var binaryPath = Process.GetCurrentProcess().MainModule.FileName;
                var args       = binaryPath.EndsWith("dotnet.exe", StringComparison.OrdinalIgnoreCase)
                    ? $"\"{Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, PlatformServices.Default.Application.ApplicationName + ".dll")}\" {string.Join(" ", Service.Args)}"
                    : $"{string.Join(" ", Service.Args)}";

                HostProcess = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName              = binaryPath;
                startInfo.Arguments             = args;
                startInfo.UseShellExecute       = false;
                startInfo.CreateNoWindow        = true;
                startInfo.WorkingDirectory      = PlatformServices.Default.Application.ApplicationBasePath;
                HostProcess.StartInfo           = startInfo;
                HostProcess.EnableRaisingEvents = true;
                HostProcess.Exited             += (s, _e) => { Stop(); serviceStoppedCallback(); };

                if (Service.WriteLog)
                {
                    startInfo.RedirectStandardOutput = true;
                    startInfo.RedirectStandardError  = true;
                    HostProcess.OutputDataReceived  += (s, _e) => WriteLog(_e.Data);
                    HostProcess.ErrorDataReceived   += (s, _e) => WriteLog(_e.Data);
                }

                HostProcess.Start();

                if (Service.WriteLog)
                {
                    HostProcess.BeginOutputReadLine();
                    HostProcess.BeginErrorReadLine();
                }

                if (Service.WriteLog)
                {
                    WriteLog($"{ServiceName} Started");
                }
            }
            catch (Exception ex)
            {
                if (Service.WriteLog)
                {
                    WriteLog($"{ServiceName} {ex.Message}");
                }
                Stop();
                serviceStoppedCallback();
            }
        }
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            // in addition to the arguments that the service has been registered with,
            // each service start may add additional startup parameters.
            // To test this: Open services console, open service details, enter startup arguments and press start.
            string[] combinedArguments;
            if (startupArguments.Length > 0)
            {
                combinedArguments = new string[commandLineArguments.Length + startupArguments.Length];
                Array.Copy(commandLineArguments, combinedArguments, commandLineArguments.Length);
                Array.Copy(startupArguments, 0, combinedArguments, commandLineArguments.Length, startupArguments.Length);
            }
            else
            {
                combinedArguments = commandLineArguments;
            }

            var config = new ConfigurationBuilder()
                         .AddCommandLine(combinedArguments)
                         .Build();

            webHost = new WebHostBuilder()
                      .UseKestrel()
                      .UseStartup <Startup>()
                      .UseConfiguration(config)
                      .Build();

            // Make sure the windows service is stopped if the
            // ASP.NET Core stack stops for any reason
            webHost
            .Services
            .GetRequiredService <IApplicationLifetime>()
            .ApplicationStopped
            .Register(() =>
            {
                if (stopRequestedByWindows == false)
                {
                    serviceStoppedCallback();
                }
            });

            webHost.Start();
            var serviceScopeFactory = webHost.Services.GetRequiredService <IServiceScopeFactory>();

            using (var scope = serviceScopeFactory.CreateScope())
            {
                var processor = scope.ServiceProvider.GetService <IDownloadingService>();
                processor.Start();
            }
        }
示例#23
0
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            try
            {
                _logger.Information("Starting Seed Hangfire Host Service");

                _server = new BackgroundJobServer();

                _logger.Information("Started Seed Hangfire Host Service");
            }
            catch (Exception ex)
            {
                _logger.Fatal(ex, "Failed to start Seed Hangfire Host Service");
                throw;
            }
        }
示例#24
0
        /// <inheritdoc />
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            host
            .Services
            .GetRequiredService <IApplicationLifetime>()
            .ApplicationStopped
            .Register(() =>
            {
                if (stopRequestedByWindows == false)
                {
                    serviceStoppedCallback();
                }
            });

            host.Start();
        }
示例#25
0
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            var optionsParserResult = Parser.Default.ParseArguments <Options>(startupArguments);

            if (optionsParserResult.Tag == ParserResultType.NotParsed)
            {
                throw new ArgumentException("Invalid arguments");
            }
            var options = ((Parsed <Options>)optionsParserResult).Value;

            options.RunAsService = false;
            options.ServiceName  = ServiceName;
            var applicationJsonPath = ConsoleRunner.GetApplicationJsonPath(options);

            using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(options.StartTimeout)))
            {
                _stoppable = ConsoleRunner.StartAsync(applicationJsonPath, cts.Token).Result;
            }
        }
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            this._logger.LogInformation("Service Starting.");

            this._structureMapServiceProviderFactory = new StructureMapServiceProviderFactory(StructureMapContainer.Instance);
            this._host = Host.CreateDefaultBuilder(startupArguments)
                         .UseServiceProviderFactory(this._structureMapServiceProviderFactory)
                         .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder
                .UseStartup <Startup>()
                .UseUrls("http://*:9065/");
            })
                         .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(LogLevel.Trace);
            })
                         .UseNLog()
                         .Build();

            // Make sure the windows service is stopped if the
            // ASP.NET Core stack stops for any reason
            this._host
            .Services
            .GetRequiredService <IHostApplicationLifetime>()
            .ApplicationStopped
            .Register(() =>
            {
                if (this._stopRequestedByWindows == false)
                {
                    serviceStoppedCallback();
                }
            });

            this._logger.LogInformation("WebHost Starting.");
            this._host.Start();
            this._logger.LogInformation("WebHost Started.");

            this._logger.LogInformation("Service Started.");
        }
示例#27
0
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            this._logger.LogInformation("Service Starting.");

            _structureMapServiceProviderFactory = new StructureMapServiceProviderFactory(StructureMapContainer.Instance);
            this._host = Host.CreateDefaultBuilder(startupArguments)
                         .UseServiceProviderFactory(_structureMapServiceProviderFactory)
                         .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(LogLevel.Trace);
            })
                         .UseNLog()
                         .Build();

            this._logger.LogInformation("Host Starting.");
            this._host.Start();
            this._logger.LogInformation("Host Started.");

            this._logger.LogInformation("Service Started.");
        }
示例#28
0
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            string[] combinedArguments;
            if (startupArguments.Length > 0)
            {
                combinedArguments = new string[_commandLineArguments.Length + startupArguments.Length];
                Array.Copy(_commandLineArguments, combinedArguments, _commandLineArguments.Length);
                Array.Copy(startupArguments, 0, combinedArguments, _commandLineArguments.Length, startupArguments.Length);
            }
            else
            {
                combinedArguments = _commandLineArguments;
            }

            var config = new ConfigurationBuilder()
                         .AddCommandLine(combinedArguments)
                         .Build();

            _webHost = new WebHostBuilder()
                       .UseUrls("http://*:5084")
                       .UseKestrel()
                       .UseStartup <Startup>()
                       .UseConfiguration(config)
                       .Build();

            _webHost
            .Services
            .GetRequiredService <IApplicationLifetime>()
            .ApplicationStopped
            .Register(() =>
            {
                if (_stopRequestedByWindows == false)
                {
                    serviceStoppedCallback();
                }
            });

            _webHost.Start();
        }
示例#29
0
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            if (Logger.IsInfoEnabled)
            {
                Logger.Info($"Starting RavenDB Windows Service: {ServiceName}.");
            }

            _serviceStoppedCallback = serviceStoppedCallback;

            try
            {
                _ravenServer.OpenPipes();
            }
            catch (Exception e)
            {
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info("Unable to OpenPipe. Admin Channel will not be available to the user", e);
                }

                throw;
            }

            try
            {
                _ravenServer.Initialize();
            }
            catch (Exception e)
            {
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info("Error initializing the server", e);
                }

                throw;
            }
        }
 public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
 {
 }