protected HostFactoryTest() { _globalSettings = Vim.GlobalSettings; _protectedOperations = new TestableProtectedOperations(); _mockFactory = new MockRepository(MockBehavior.Strict); _synchronizer = _mockFactory.Create<IEditorToSettingsSynchronizer>(MockBehavior.Strict); _vsEditorAdaptersFactoryService = _mockFactory.Create<IVsEditorAdaptersFactoryService>(); _vimApplicationSettings = _mockFactory.Create<IVimApplicationSettings>(MockBehavior.Loose); var vsAdapter = _mockFactory.Create<IVsAdapter>(); vsAdapter.SetupGet(x => x.EditorAdapter).Returns(_vsEditorAdaptersFactoryService.Object); _hostFactory = new HostFactory( Vim, _vsEditorAdaptersFactoryService.Object, _mockFactory.Create<IDisplayWindowBrokerFactoryService>(MockBehavior.Loose).Object, _mockFactory.Create<ITextManager>(MockBehavior.Loose).Object, vsAdapter.Object, _protectedOperations, new VimBufferCoordinatorFactory(Vim), _mockFactory.Create<IKeyUtil>(MockBehavior.Loose).Object, _synchronizer.Object, _vimApplicationSettings.Object, new Lazy<ICommandTargetFactory, IOrderable>[] { }); }
static void Main(string[] args) { LogManager.LogFactory = new NLogFactory(); var hostFactory = new HostFactory(); var host = hostFactory.Create(); host.Init(); host.Start(Platform.ServerUri); Console.ReadKey(); }
protected HostFactoryTest() { _protectedOperations = new TestableProtectedOperations(); _mockFactory = new MockRepository(MockBehavior.Strict); _synchronizer = _mockFactory.Create<IEditorToSettingsSynchronizer>(MockBehavior.Strict); _vsEditorAdaptersFactoryService = _mockFactory.Create<IVsEditorAdaptersFactoryService>(); var vsAdapter = _mockFactory.Create<IVsAdapter>(); vsAdapter.SetupGet(x => x.EditorAdapter).Returns(_vsEditorAdaptersFactoryService.Object); _hostFactory = new HostFactory( Vim, _vsEditorAdaptersFactoryService.Object, _mockFactory.Create<IResharperUtil>().Object, _mockFactory.Create<IDisplayWindowBrokerFactoryService>(MockBehavior.Loose).Object, _mockFactory.Create<ITextManager>(MockBehavior.Loose).Object, vsAdapter.Object, _protectedOperations, new VimBufferCoordinatorFactory(), _mockFactory.Create<IKeyUtil>(MockBehavior.Loose).Object, _synchronizer.Object); }
static void Main(string[] args) { var retry = new StdRetry(); string simpleRuleName = "SimpleRepeatRetryRule"; string customRuleName = "CustomIntervalRetryRule"; //声明并注册重试规则 var simpleRepeatRule = new SimpleRepeatRetryRule(simpleRuleName, 50, TimeSpan.FromSeconds(2)); var customIntervalRule = new CustomIntervalRetryRule(customRuleName, Enumerable.Range(1, 6).Select(r => TimeSpan.FromSeconds(r)).ToArray()); retry.RuleManager.AddRule(simpleRepeatRule); retry.RuleManager.AddRule(customIntervalRule); var tasks = new Task <bool>[] { //注册Job //retry.RegisterJob<AlawaysSuccessJob>(new RetryJobRegisterInfo{ UsedRuleName= simpleRuleName, StartAt= DateTimeOffset.UtcNow.AddSeconds(3)}), retry.RegisterJob <AlawaysFailJob>(new RetryJobRegisterInfo { UsedRuleName = simpleRuleName, /*EndAt =DateTimeOffset.Now.AddSeconds(2),*/ StartAt = DateTimeOffset.Now.AddSeconds(3) }), //retry.RegisterJob<MaybeFailJob>(new RetryJobRegisterInfo{ JobMap=new Dictionary<string,object>{ {"Id",1 } } , UsedRuleName= customRuleName}), //retry.RegisterJob<MaybeFailJob>(new RetryJobRegisterInfo{ JobMap=new Dictionary<string,object>{ {"Id",2 } } ,UsedRuleName= customRuleName}), //retry.RegisterJob<MaybeFailJob>(new RetryJobRegisterInfo{ JobMap=new Dictionary<string,object>{ {"Id",3 } } ,UsedRuleName= customRuleName}), //retry.RegisterJob<MaybeFailJob>(new RetryJobRegisterInfo{ JobMap=new Dictionary<string,object>{ {"Id",4 } } ,UsedRuleName= customRuleName}), //retry.RegisterJob<MaybeFailJob>(new RetryJobRegisterInfo{ JobMap=new Dictionary<string,object>{ {"Id",5 } } ,UsedRuleName= "NotSetRule"}), }; Task.WaitAll(tasks); for (var i = 0; i < tasks.Length; i++) { Logger.Info("RegisterJob {0} {1}", i, tasks[i].Result ? "Success" : "Fail"); } retry.ContinueWith <AlawaysSuccessJob, MaybeFailJob>(i => new RetryJobRegisterInfo { JobMap = new Dictionary <string, object> { { "Id", DateTime.Now.Ticks % int.MaxValue } } }); //注册执行完时的通知事件 retry.RegisterEvent <AlawaysSuccessJob>(e => { Logger.Info("AlawaysSuccessJob Result:{0}", JsonConvert.SerializeObject(e)); }); retry.RegisterEvent <AlawaysFailJob>(e => { Logger.Info("AlawaysFailJob Result:{0}", JsonConvert.SerializeObject(e)); }); retry.RegisterEvent <MaybeFailJob>(e => { Logger.Info("MaybeFailJob Result:{0}", JsonConvert.SerializeObject(e)); }); var host = HostFactory.New(x => { x.Service <StdRetry>(s => { s.ConstructUsing(settings => retry); s.WhenStarted(service => service.Start()); s.WhenStopped(service => service.Stop()); }); }); host.Run(); }
static int Main(string[] args) { return((int)HostFactory.Run(x => x.Service <AttendantService>())); }
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(); } }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Main entry-point for this application. </summary> /// /// <param name="args"> An array of command-line argument strings. </param> //////////////////////////////////////////////////////////////////////////////////////////////////// static void Main(string[] args) { var builder = new ContainerBuilder(); // Service itself builder.RegisterType <SchedulingMicroService>() .AsImplementedInterfaces() .AsSelf() ?.InstancePerLifetimeScope(); builder.RegisterType <Logger>().SingleInstance(); var container = builder.Build(); XmlConfigurator.ConfigureAndWatch(new FileInfo(@".\log4net.config")); HostFactory.Run(c => { c?.UseAutofacContainer(container); c?.UseLog4Net(); c?.ApplyCommandLineWithDebuggerSupport(); c?.EnablePauseAndContinue(); c?.EnableShutdown(); c?.OnException(ex => { Console.WriteLine(ex.Message); }); c.ScheduleQuartzJobAsService(q => q.WithJob(() => JobBuilder.Create <SampleJob>().Build()) .AddTrigger(() => TriggerBuilder.Create().WithSimpleSchedule( build => build.WithIntervalInSeconds(30).RepeatForever()).Build()) ).StartAutomatically(); c?.Service <SchedulingMicroService>(s => { s.ConstructUsingAutofacContainer <SchedulingMicroService>(); s?.ConstructUsing(settings => { var service = AutofacHostBuilderConfigurator.LifetimeScope.Resolve <SchedulingMicroService>(); return(service); }); s?.ConstructUsing(name => new SchedulingMicroService()); s?.WhenStarted((SchedulingMicroService server, HostControl host) => server.OnStart(host)); s?.WhenPaused(server => server.OnPause()); s?.WhenContinued(server => server.OnResume()); s?.WhenStopped(server => server.OnStop()); s?.WhenShutdown(server => server.OnShutdown()); }); c?.RunAsNetworkService(); c?.StartAutomaticallyDelayed(); c?.SetDescription(string.Intern("Scheduling Microservice Sample")); c?.SetDisplayName(string.Intern("SchedulingMicroService")); c?.SetServiceName(string.Intern("SchedulingMicroService")); c?.EnableServiceRecovery(r => { r?.OnCrashOnly(); r?.RestartService(1); //first r?.RestartService(1); //second r?.RestartService(1); //subsequents r?.SetResetPeriod(0); }); }); }
public void NormalAndInitialFileSystemChangeEventMultipleConfiguratorsTest() { //Arrange Mock <IDelegateMock> onChanged = new Mock <IDelegateMock>(); CreateFile(_testDir + "initialFile.Test3"); CreateFile(_testDir + "initialFile.Test2"); CreateFile(_testDir + "initialFile.Test"); //Act var exitCode = HostFactory.Run(config => { config.UseTestHost(); config.Service <TopshelfFileSystemWatcherTest>(s => { s.ConstructUsing(() => new TopshelfFileSystemWatcherTest()); s.WhenStarted((service, host) => { CreateFile(_testDir + "testFile.Test3"); CreateFile(_testDir + "testFile.Test2"); CreateFile(_testDir + "testFile.Test"); File.Delete(TestContext.CurrentContext.WorkDirectory + _testDir + "testFile.Test"); File.Delete(TestContext.CurrentContext.WorkDirectory + _testDir + "testFile.Test2"); File.Delete(TestContext.CurrentContext.WorkDirectory + _testDir + "testFile.Test3"); return(true); }); s.WhenStopped((service, host) => true); s.WhenFileSystemChanged(configurator => { configurator.AddDirectory(dir => { dir.Path = TestContext.CurrentContext.WorkDirectory + _testDir; dir.CreateDir = true; dir.FileFilter = "*.Test2"; dir.NotifyFilters = NotifyFilters.FileName; dir.GetInitialStateEvent = true; }); configurator.AddDirectory(dir => { dir.Path = TestContext.CurrentContext.WorkDirectory + _testDir; dir.CreateDir = true; dir.FileFilter = "*.Test3"; dir.NotifyFilters = NotifyFilters.FileName; dir.GetInitialStateEvent = true; }); configurator.AddDirectory(dir => { dir.Path = TestContext.CurrentContext.WorkDirectory + _testDir; dir.CreateDir = true; dir.FileFilter = "*.Test"; dir.NotifyFilters = NotifyFilters.FileName; dir.GetInitialStateEvent = false; }); }, onChanged.Object.FileSystemChanged, onChanged.Object.FileSystemCreated, onChanged.Object.FileSystemRenamed, onChanged.Object.FileSystemDeleted, onChanged.Object.FileSystemInitial); }); }); //Assert onChanged.Verify(mock => mock.FileSystemChanged(It.IsAny <TopshelfFileSystemEventArgs>()), Times.Exactly(0)); onChanged.Verify(mock => mock.FileSystemCreated(It.IsAny <TopshelfFileSystemEventArgs>()), Times.Exactly(3)); onChanged.Verify(mock => mock.FileSystemDeleted(It.IsAny <TopshelfFileSystemEventArgs>()), Times.Exactly(3)); onChanged.Verify(mock => mock.FileSystemInitial(It.IsAny <TopshelfFileSystemEventArgs>()), Times.Exactly(2)); onChanged.Verify(mock => mock.FileSystemRenamed(It.IsAny <TopshelfFileSystemEventArgs>()), Times.Never); Assert.AreEqual(TopshelfExitCode.Ok, exitCode); }
static void Main() { var settings = new Settings(); ILifetimeScope container = null; Log.Logger = new LoggerConfiguration() .ReadFrom.AppSettings() .Enrich.WithExceptionDetails() .WriteTo.Console() .CreateLogger(); var builder = new ContainerBuilder(); var easyNetQLogger = new SerilogLogger(Log.Logger); builder.Register(t => settings).AsSelf(); builder.Register(c => RabbitHutch.CreateBus(register => register.Register <IEasyNetQLogger>(l => easyNetQLogger)).Advanced).As <IAdvancedBus>(); builder.Register(c => new HttpMessageHandlerClient( () => new HttpClientHandler(), settings.ApiEndpoint, null, new DelegatedDeserializer(JsonConvert.DeserializeObject), new DelegatedSerializer(JsonConvert.SerializeObject), string.Empty) ).As <IRestClient>(); builder.RegisterType <ApiService>().AsImplementedInterfaces(); builder.RegisterType <Service>().AsSelf(); container = builder.Build(); HostFactory.Run(c => { c.Service <Service>((s) => { s.ConstructUsing(name => container.Resolve <Service>()); s.WhenStarted(service => service.Start()); s.WhenStopped(service => service.Stop()); }); c.RunAsLocalSystem(); c.SetServiceName(settings.ServiceName); c.SetDisplayName(settings.ServiceName); c.SetDescription("Сервис отправки готовой продукции"); c.DependsOnEventLog(); c.StartAutomatically(); c.UseSerilog(); c.EnableServiceRecovery(configurator => { configurator.RestartService(1); }); }); }
public static void Main(string[] args) { try { var container = new Container(); var config = new Settings("configuration"); container.RegisterSingleton <IConfiguration>(() => { return(config); }); container.RegisterSingleton <ILogger>(() => { return(LogManager.GetLogger(typeof(Program).Namespace)); }); container.RegisterSingleton(() => { var scheduler = Async.Execute(() => StdSchedulerFactory.GetDefaultScheduler()); scheduler.JobFactory = new JobFactory(container); return(scheduler); }); container.RegisterSingleton <IMiddlewareContext>(() => new MiddlewareContext(config.Bus.Url)); container.RegisterSingleton <IMiddleware, RabbitMiddleware>(); container.RegisterSingleton <IDatabaseContext>(() => new DatabaseContext(config.Database.Url)); container.RegisterSingleton <IApplicationRepository, ApplicationRepository>(); container.RegisterSingleton <IHealthRepository, HealthRepository>(); container.RegisterSingleton <IConfigurationRepository, ConfigurationRepository>(); container.RegisterSingleton <IServiceContext>(() => new ServiceContext()); container.RegisterSingleton <IHealthService, HealthService>(); container.RegisterSingleton <IApplicationService, ApplicationService>(); container.RegisterSingleton <IConfigurationService, ConfigurationService>(); container.RegisterSingleton <Pulse>(); if (config.Web.Enabled) { container.RegisterSingleton <INancyBootstrapper, Bootstrapper>(); } container.Register <IHost, Host>(); container.Verify(); HostFactory.Run(host => { host.UseSimpleInjector(container); host.OnException((Exception e) => { container.GetInstance <ILogger>().Error(e, e.ToString()); }); host.Service <IHost>(server => { server.ConstructUsingSimpleInjector(); server.WhenStarted(async i => await i.Start()); server.WhenStopped(async i => await i.Stop()); if (config.Web.Enabled) { server.WithNancyEndpoint(host, web => { web.AddHost(config.Web.Scheme, config.Web.Server, config.Web.Port, "/"); web.Bootstrapper = container.GetInstance <INancyBootstrapper>(); }); } }); host.UseNLog(); host.RunAsNetworkService(); host.SetDescription("Matrix Platform Configuration"); host.SetDisplayName("Matrix Configuration"); host.SetServiceName("Matrix.Configuration"); }); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
public static void Main(string[] args) { HostFactory.Run(x => { var startType = UserSettings.Default.StartType; if (startType == "TodayAt") { x.Service <OutlookAppointmentService>(s => { s.ConstructUsing(() => new OutlookAppointmentService()); s.WhenStarted((tc, hostControl) => tc.Start(hostControl)); s.WhenStopped((tc, hostControl) => tc.Stop(hostControl)); s.ScheduleQuartzJob(q => q.WithJob(() => JobBuilder.Create <OutlookBooking>().Build()) .AddTrigger(() => TriggerBuilder.Create() .StartAt(DateBuilder.TodayAt (UserSettings.Default.ScheduleStartTime.Hours, UserSettings.Default.ScheduleStartTime.Minutes, UserSettings.Default.ScheduleStartTime.Seconds)) .WithSimpleSchedule(builder => builder .WithIntervalInHours(UserSettings.Default.ScheduleIntervalInHours) // Every x hours from then on. (App config) .RepeatForever()) .Build()) ); }); } else if (startType == "StartNow") { x.Service <OutlookAppointmentService>(s => { s.ConstructUsing(() => new OutlookAppointmentService()); s.WhenStarted((tc, hostControl) => tc.Start(hostControl)); s.WhenStopped((tc, hostControl) => tc.Stop(hostControl)); s.ScheduleQuartzJob(q => q.WithJob(() => JobBuilder.Create <OutlookBooking>().Build()) .AddTrigger(() => TriggerBuilder.Create() .StartNow() // Test trigger - Starts immediately. .WithSimpleSchedule(builder => builder .WithIntervalInHours(24) // Every x hours from then on. (App config) .RepeatForever()) .Build()) ); }); } else { throw new System.Exception("Invalid UserSettings.StartType: Argument not recognised."); } x.RunAsLocalSystem() .DependsOnEventLog() .StartAutomatically() .EnableServiceRecovery(rc => rc.RestartService(1)); x.SetServiceName("OutlookAppointmentScheduler"); x.SetDisplayName("OutlookAppointmentScheduler"); x.SetDescription("OutlookAppointmentScheduler - Scheduled Outlook Appointment bookings to be sent at specified times."); }); }
static void Main(string[] args) { string appVerStr = System.Diagnostics.Process.GetCurrentProcess().ProcessName; System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); appVerStr += "." + System.Reflection.AssemblyName.GetAssemblyName(assembly.Location).Version.ToString(); bool createdNew; InstanceMutex = new Mutex(true, string.Format(@"Global\{0}", appVerStr.Replace(" ", "")), out createdNew); if (createdNew) { var exitCode = HostFactory.Run(x => { x.Service <Sentinel>(s => { s.ConstructUsing(name => new Sentinel()); s.WhenStarted((guardian, hostCtl) => guardian.Start()); s.WhenStopped((guardian, hostCtl) => guardian.Stop()); s.WhenShutdown((guardian, hostCtl) => { hostCtl.RequestAdditionalTime(TimeSpan.FromSeconds(30)); guardian.Shutdown(ExitCodes.ShutdownWithSafeguards); }); }); x.EnableShutdown(); x.SetDescription("Content Filtering Enforcement Service"); x.SetDisplayName(nameof(Sentinel)); x.SetServiceName(nameof(Sentinel)); x.StartAutomatically(); x.RunAsLocalSystem(); // We don't need recovery options, because there will be multiple // services all watching eachother that will all record eachother // in the event of a failure or forced termination. /* * //http://docs.topshelf-project.com/en/latest/configuration/config_api.html#id1 * x.EnableServiceRecovery(rc => * { * rc.OnCrashOnly(); * rc.RestartService(0); * rc.RestartService(0); * rc.RestartService(0); * }); */ }); } else { Console.WriteLine("Service already running. Exiting."); // We have to exit with a safe code so that if another // monitor is running, it won't see this process end // and then panic and try to restart it when it's already // running! Environment.Exit((int)ExitCodes.ShutdownWithSafeguards); } }
static int Main() { Log4NetLogWriterFactory.Use("log4net.config"); Log4NetLogger.Use(); string username = "******"; string password = "******"; var serviceBusUri = new Uri("rabbitmq://localhost/stress_service"); ushort heartbeat = 3; int iterations = 1000; int instances = 10; int requestsPerInstance = 1; int messageSize = 128; int prefetchCount = 10; int consumerLimit = 10; string test = "stress"; bool cleanup = true; bool mixed = false; string debug = null; int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); ThreadPool.SetMinThreads(Math.Max(workerThreads, 100), completionPortThreads); return((int)HostFactory.Run(x => { x.SetDescription("Generates a stressful load on RabbitMQ using MassTransit"); x.SetDisplayName("MassTransit RabbitMQ Stress Console"); x.SetServiceName("MassTransitStressConsole"); x.AddCommandLineDefinition("rmqusername", v => username = v); x.AddCommandLineDefinition("rmqpassword", v => password = v); x.AddCommandLineDefinition("uri", v => serviceBusUri = new Uri(v)); x.AddCommandLineDefinition("heartbeat", v => heartbeat = ushort.Parse(v)); x.AddCommandLineDefinition("iterations", v => iterations = int.Parse(v)); x.AddCommandLineDefinition("instances", v => instances = int.Parse(v)); x.AddCommandLineDefinition("prefetch", v => prefetchCount = int.Parse(v)); x.AddCommandLineDefinition("threads", v => consumerLimit = int.Parse(v)); x.AddCommandLineDefinition("requests", v => requestsPerInstance = int.Parse(v)); x.AddCommandLineDefinition("test", v => test = v); x.AddCommandLineDefinition("size", v => messageSize = int.Parse(v)); x.AddCommandLineDefinition("cleanup", v => cleanup = bool.Parse(v)); x.AddCommandLineDefinition("mixed", v => mixed = bool.Parse(v)); x.AddCommandLineDefinition("debug", v => debug = v); x.ApplyCommandLine(); x.Service(hostSettings => { if (!string.IsNullOrWhiteSpace(debug)) { EnableDebug(debug); } if (test == "ingest") { return new SelectService(new StressIngestService(serviceBusUri, username, password, heartbeat, iterations, instances, messageSize, cleanup, mixed, prefetchCount, consumerLimit)); } return new SelectService(new StressService(serviceBusUri, username, password, heartbeat, iterations, instances, messageSize, cleanup, mixed, prefetchCount, consumerLimit, requestsPerInstance)); }); })); }
private static void CreateStartService() { try { HostFactory.New(x => { if (!String.IsNullOrEmpty(tsd.Name)) { x.SetServiceName(tsd.Name); } if (!String.IsNullOrEmpty(tsd.Description)) { x.SetDescription(tsd.Description); } if (!String.IsNullOrEmpty(tsd.DisplayName)) { x.SetDisplayName(tsd.DisplayName); } if (!String.IsNullOrEmpty(tsd.InstanceName)) { x.SetInstanceName(tsd.InstanceName); } #region Start Modes switch (tsd.StartMode) { case 1: x.StartAutomatically(); break; case 2: x.StartAutomaticallyDelayed(); break; case 3: x.StartManually(); break; default: break; } #endregion Start Modes #region Service Recovery if (tsd.EnableServiceRecovery) { x.EnableServiceRecovery(rc => { rc.RestartService(tsd.ServiceRecoveryOptions.RestartServiceDelay); rc.RunProgram(tsd.ServiceRecoveryOptions.RunProgramDelay, tsd.ServiceRecoveryOptions.RunProgramName); rc.SetResetPeriod(tsd.ServiceRecoveryOptions.ResetPeriod); }); } #endregion Service Recovery #region Service Identity string username = string.Empty; string password = string.Empty; switch (tsd.Identity) { case 1: Console.WriteLine(); Console.WriteLine("#### Please enter a username: ####"); username = Console.ReadLine(); Console.WriteLine("#### Please enter a password: ####"); password = Console.ReadLine(); if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password)) { x.RunAs(username, password); } break; case 2: x.RunAsPrompt(); break; case 3: x.RunAsNetworkService(); break; case 4: x.RunAsLocalSystem(); break; case 5: x.RunAsLocalService(); break; } #endregion Service Identity #region Another Dependency if (tsd.AnotherDependency && !String.IsNullOrEmpty(tsd.AnotherDependencyName)) { x.DependsOn(tsd.AnotherDependencyName); } #endregion Another Dependency #region Built In Dependency if (tsd.BuiltInDependency) { switch (tsd.Dependency) { case 1: x.DependsOnEventLog(); break; case 2: x.DependsOnIis(); break; case 3: x.DependsOnMsmq(); break; case 4: x.DependsOnMsSql(); break; } } #endregion Built In Dependency #region Pause And Continue if (tsd.EnablePauseAndContinue) { x.EnablePauseAndContinue(); } #endregion Pause And Continue #region Shutdown if (tsd.Shutdown) { x.EnableShutdown(); } #endregion Shutdown }); } catch (Exception ex) { WriteError(ex.Message); } }
static void Main(string[] args) { try { logger.Trace("Performing Host Init"); AppDomain.MonitoringIsEnabled = true; var tempPath = Path.Combine(pluginPath, "_temp"); if (Directory.Exists(tempPath)) { if (Directory.GetFiles(tempPath).Any()) { foreach (var file in Directory.GetFiles(tempPath)) { File.Move(file, Path.Combine(basePath, "plugins", Path.GetFileName(file))); } } Directory.Delete(tempPath, true); } if (!File.Exists(Path.Combine(pluginPath, "Tether.Plugins.dll"))) { Directory.CreateDirectory(Path.Combine(pluginPath)); File.Copy(Path.Combine(basePath, "Tether.Plugins.dll"), Path.Combine(pluginPath, "Tether.Plugins.dll")); File.Copy(Path.Combine(basePath, "Tether.Plugins.pdb"), Path.Combine(pluginPath, "Tether.Plugins.pdb")); } Host host = HostFactory.New(x => { x.UseNLog(); x.Service <Service>(service => { service.ConstructUsing(f => new Service()); service.WhenStarted((a, control) => a.Start(control)); service.WhenStopped((a, control) => a.Stop(control)); service.ScheduleQuartzJob(b => b.WithJob(() => JobBuilder.Create <ManifestRegularCheck>().Build()) .AddTrigger(() => TriggerBuilder.Create() .WithSimpleSchedule(builder => builder.WithMisfireHandlingInstructionFireNow() .WithIntervalInSeconds(Config.ConfigurationSingleton.Instance.Config.ManifestCheckInterval) .RepeatForever()) .Build())); if (!Config.ConfigurationSingleton.Instance.Config.DisableResending) { service.ScheduleQuartzJob(b => b.WithJob(() => JobBuilder.Create <ResenderJob>().Build()) .AddTrigger(() => TriggerBuilder.Create() .WithSimpleSchedule(builder => builder.WithMisfireHandlingInstructionFireNow() .WithIntervalInSeconds(Config.ConfigurationSingleton.Instance.Config.RetriesResendInterval) .RepeatForever()) .Build())); } }); x.RunAsLocalSystem(); x.StartAutomatically(); x.SetDescription("Tether"); x.SetDisplayName("Tether"); x.SetServiceName("Tether"); x.EnableServiceRecovery( r => { r.RestartService(0); }); }); host.Run(); } catch (Exception ex) { logger.Fatal(ex, "Problem when trying to run host"); } }
static void Main(string[] args) { ServicePointManager.DefaultConnectionLimit = 1000; HostFactory.Run(x => { x.AddCommandLineDefinition("deploymentId", did => _deploymentId = did); x.AddCommandLineDefinition("updateDomain", upd => _updateDomain = upd); x.AddCommandLineDefinition("storageAccount", sacc => _storageAccount = sacc); x.AddCommandLineDefinition("storageKey", skey => _storageKey = skey); x.AddCommandLineDefinition("updateFrequency", uf => _updateFrequencyInSeconds = Convert.ToInt32(uf)); x.AddCommandLineDefinition("applicationRestartCount", arc => _applicationRestartCount = Convert.ToInt32(arc)); x.ApplyCommandLine(); x.Service <IYamsService>(s => { s.ConstructUsing(name => { if (string.IsNullOrWhiteSpace(_storageKey)) { throw new ArgumentNullException(nameof(_storageKey)); } if (string.IsNullOrWhiteSpace(_storageAccount)) { throw new ArgumentNullException(nameof(_storageAccount)); } if (string.IsNullOrWhiteSpace(_deploymentId)) { throw new ArgumentNullException(nameof(_deploymentId)); } if (string.IsNullOrWhiteSpace(_updateDomain)) { throw new ArgumentNullException(nameof(_updateDomain)); } string blobStorageConnectionString = $"DefaultEndpointsProtocol=https;AccountName={_storageAccount};AccountKey={_storageKey}"; YamsConfig yamsConfig = new YamsConfigBuilder( // mandatory configs _deploymentId, _updateDomain, Environment.MachineName, Environment.CurrentDirectory + "\\LocalStore") // optional configs .SetCheckForUpdatesPeriodInSeconds(_updateFrequencyInSeconds) .SetApplicationRestartCount(_applicationRestartCount) .Build(); return(YamsServiceFactory.Create(yamsConfig, deploymentRepositoryStorageConnectionString: blobStorageConnectionString, updateSessionStorageConnectionString: blobStorageConnectionString)); }); s.WhenStarted(yep => yep.Start().Wait()); s.WhenStopped(yep => yep.Stop().Wait()); }); x.RunAsLocalSystem(); x.SetDescription("Yams Service Host"); x.SetDisplayName("Yams Service"); x.SetServiceName("Yams"); x.StartAutomatically(); }); }
internal void RunService() { var exitCode = HostFactory.Run(Configure); Environment.ExitCode = (int)exitCode; }
static void Main(string[] args) { var builder = new ContainerBuilder(); // Service itself builder.RegisterType <MLMicroService>().AsImplementedInterfaces() .AsSelf() ?.InstancePerLifetimeScope(); builder.RegisterType <Logger>().SingleInstance(); var container = builder.Build(); XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(@".log4net.config")); HostFactory.Run(c => { c?.UseAutofacContainer(container); c?.UseLog4Net(); c?.ApplyCommandLineWithDebuggerSupport(); c?.EnablePauseAndContinue(); c?.EnableShutdown(); c?.OnException(ex => { Console.WriteLine(ex.Message); }); c?.UseWindowsHostEnvironmentWithDebugSupport(); c?.Service <MLMicroService>(s => { s.ConstructUsingAutofacContainer <MLMicroService>(); s?.ConstructUsing(settings => { var service = AutofacHostBuilderConfigurator.LifetimeScope.Resolve <MLMicroService>(); return(service); }); s?.ConstructUsing(name => new MLMicroService()); s?.WhenStartedAsLeader(b => { b.WhenStarted(async(service, token) => { await service.Start(token); }); b.Lease(lcb => lcb.RenewLeaseEvery(TimeSpan.FromSeconds(2)) .AquireLeaseEvery(TimeSpan.FromSeconds(5)) .LeaseLength(TimeSpan.FromDays(1)) .WithLeaseManager(new MLMicroService())); b.WithHeartBeat(TimeSpan.FromSeconds(30), (isLeader, token) => Task.CompletedTask); b.Build(); }); s?.WhenStarted((MLMicroService server, HostControl host) => server.OnStart(host)); s?.WhenPaused(server => server.OnPause()); s?.WhenContinued(server => server.OnResume()); s?.WhenStopped(server => server.OnStop()); s?.WhenShutdown(server => server.OnShutdown()); }); c?.RunAsNetworkService(); c?.StartAutomaticallyDelayed(); c?.SetDescription(string.Intern("Machine Learning Microservice Sample")); c?.SetDisplayName(string.Intern("MachineLearningMicroservice")); c?.SetServiceName(string.Intern("MachineLearningMicroservice")); c?.EnableServiceRecovery(r => { r?.OnCrashOnly(); r?.RestartService(1); // first r?.RestartService(1); // second r?.RestartService(1); // subsequents r?.SetResetPeriod(0); }); }); }
static void Main(string[] args) { #region 启动消息处理器 var QueenBasePath = ConfigurationManager.AppSettings["MessageQueueServer"]; foreach (var t in Queens) { try { //创建实例 var QueenInstance = Activator.CreateInstance(t) as IQueue; if (!QueenInstance.Enable) { continue; } //新建消息循环队列或连接到已有的消息队列 var path = QueenBasePath + QueenInstance.Path; MessageQueue mq; if (MessageQueue.Exists(path)) { mq = new MessageQueue(path); } else { mq = MessageQueue.Create(path); } mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); //mq.Formatter = new JsonFormater(); mq.ReceiveCompleted += (sender, e) => { var m = mq.EndReceive(e.AsyncResult); String body = String.Empty; try { body = m.Body.ToString(); } catch { body = String.Empty; } try { QueenInstance.ReceiveCompleted(body); mq.BeginReceive(); } catch (Exception ex) { Console.WriteLine(ex.Message); } }; mq.BeginReceive(); } catch (Exception ex) { new Log().Add(t.Name, JsonConvert.SerializeObject(ex), EventLogEntryType.Error); Console.WriteLine(ex.Message); } Thread.Sleep(1); } #endregion Console.ForegroundColor = ConsoleColor.Green; String ServiceName = ConfigurationManager.AppSettings["ServiceName"]; if (String.IsNullOrEmpty(ServiceName)) { ServiceName = "yueyaCms.Service"; } Host host = HostFactory.New((config) => { config.Service <Engine>(); //服务的描述 config.SetDescription("玥雅CMS核心服务。"); //服务的显示名称 config.SetDisplayName(ServiceName); //服务名称 config.SetServiceName(ServiceName); //以本地服务方式运行 config.RunAsLocalService(); }); host.Run(); Console.ReadLine(); }
public static void HostDaemon <T>(string updateUrl, string serviceName, string serviceDescription, string serviceDisplayName, ILogger logger = null) where T : class, IAppDaemonService, new() { logger?.Information("Hosting Daemon..."); logger?.Information("Hosting Daemon Update URL: {UpdateUrl}", updateUrl); // Configure unhandled exception logging if (logger != null) { AppDomain.CurrentDomain.UnhandledException += (sender, args) => logger.Fatal(args.ExceptionObject as Exception, "AppDomain Unhandled Exception"); } // Configure update manager UpdateManager updateManager = null; IUpdater updater = null; try { updateManager = new UpdateManager(updateUrl, serviceName); } catch { logger?.Information("Updater not configured. Some features may be unavailable because the app is running without Update.exe"); } // Updater config if (updateManager != null) { var updatePeriod = TimeSpan.FromSeconds(30); updater = new RepeatedTimeUpdater(updateManager).SetCheckUpdatePeriod(updatePeriod); updater.Start(); logger?.Information("Daemon auto-update period set to: {AutoUpdatePeriod} minutes", updatePeriod.TotalMinutes); } else { logger?.Warning("Daemon auto-updates are disabled."); } // Configuration var con = new Action <HostConfigurator>(config => { config.SetServiceName(serviceName); config.SetDescription(serviceDescription); config.SetDisplayName(serviceDisplayName); config.RunAsLocalSystem(); config.StartAutomatically(); config.EnableShutdown(); config.Service <T>(service => { service.ConstructUsing(_ => new T { Logger = logger, Identifier = serviceName }); service.WhenStarted(instance => instance.Start()); service.WhenStopped(instance => instance.Stop()); }); if (logger != null) { config.UseSerilog(logger); } }); // Run the service if (updater != null) { logger?.Information("Starting service with updater..."); var service = new T { Logger = logger, Identifier = serviceName }; var x = new SquirreledHost(service, Assembly.GetExecutingAssembly(), updater); x.ConfigureAndRun(new SquirreledHost.ConfigureExt(con)); } else { logger?.Information("Starting service without updater..."); HostFactory.Run(con); } }
public App() { host = HostFactory.Create(); ServiceProvider = host.Services; }
private static int Main() { Type launcherType = Type.GetType(ConfigurationManager.AppSettings["launcherType"]); if (launcherType == null) { throw new Exception("The launcher type setting must be defined."); } TopshelfExitCode exitCode = HostFactory.Run(hostConfigurator => { WebApplicationConfig config = WebApplicationConfig.TryLoadOrNewWebRunnerConfig(); hostConfigurator.AddCommandLineDefinition("useSSL", useSSLArgument => { config.UseSSL = bool.Parse(useSSLArgument); }); hostConfigurator.AddCommandLineDefinition("isLocalMode", isLocalModeArgument => { config.IsLocalMode = bool.Parse(isLocalModeArgument); }); hostConfigurator.AddCommandLineDefinition("port", portArgument => { config.Port = int.Parse(portArgument); }); hostConfigurator.ApplyCommandLine(); hostConfigurator.Service <WebApplicationLauncherAdapter>(s => { s.ConstructUsing(hostSettings => new WebApplicationLauncherAdapter(launcherType)); s.WhenStarted(o => o.Start(config)); s.WhenStopped(o => o.Stop()); s.AfterStartingService(() => { if (!config.OpenBrowser) { return; } Process.Start(new ProcessStartInfo("cmd", $"/c start {config.GetUrl()}") { CreateNoWindow = true }); }); }); hostConfigurator.RunAsNetworkService(); hostConfigurator.StartAutomatically(); hostConfigurator.SetServiceName("ContentTransformer"); hostConfigurator.SetDescription($"Content Transformer Service (v{Assembly.GetExecutingAssembly().GetName().Version})"); hostConfigurator.SetDisplayName($"Content Transformer - {config.GetUrl()}"); hostConfigurator.OnException(exception => { Console.ForegroundColor = ConsoleColor.Red; while (true) { if (exception == null) { break; } Console.WriteLine(exception.Message); exception = exception.InnerException; } Console.ResetColor(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }); }); return((int)exitCode); }
private static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .ReadFrom.AppSettings() .CreateLogger(); Log.Logger.Verbose("Logger configured"); var appSettings = new AppSettingsProvider() .GetAppSettings(); try { HostFactory.Run(x => //1 { try { x.Service <Worker>(s => //2 { try { s.ConstructUsing(name => new Worker()); //3 s.WhenStarted(tc => { Log.Logger.Information("Starting service."); tc.Start(); Log.Logger.Information("Service started."); }); //4 s.WhenStopped(tc => { Log.Logger.Information("Stopping service."); tc.Stop(); Log.Logger.Information("Service stopped."); }); //5 s.WhenPaused(tc => { Log.Logger.Information("Pausing service."); tc.Stop(); Log.Logger.Information("Service paused."); }); //5 s.WhenContinued(tc => { Log.Logger.Information("Continuing service."); tc.Start(); Log.Logger.Information("Service continued."); }); //5 s.WhenSessionChanged((w, sca) => { Log.Logger.Information("Session changed: " + w); Log.Logger.Information("Session changed: " + sca); }); } catch (Exception ex) { Log.Logger.Error(ex, "Fra program"); throw; } }); x.RunAsLocalService(); //6 x.SetDescription(appSettings.Description); //7 x.SetDisplayName(appSettings.DisplayName); //8 x.SetServiceName(appSettings.ServiceName); //9 x.OnException(e => { Log.Logger.Error(e, "Exception"); }); } catch (Exception e) { Console.WriteLine(e); throw; } }); //10 } } catch (Exception ex) { Log.Logger.Error(ex, "Yderste"); throw; } }
static int Main() { return((int)HostFactory.Run(new Program().Configure)); }
static void Main(string[] args) { //初始化 Startup.Configuration(); HostFactory.Run(x => { x.RunAsLocalSystem(); //x.SetServiceName(ScheduleSettings.Instance.ServiceName); //x.SetDisplayName(ScheduleSettings.Instance.ServiceDisplayName); //x.SetDescription(ScheduleSettings.Instance.ServiceDescription); x.SetServiceName("TestJob服务名称"); x.SetDisplayName("TestJob服务显示名称"); x.SetDescription("TestJob服务描述"); x.Service <Bootstrapper>(s => { s.ConstructUsing(name => new Bootstrapper()); s.WhenStarted(w => w.Start()); s.WhenStopped(w => w.Stop()); }); //x.SetStartTimeout(TimeSpan.FromMinutes(5)); //x.SetStopTimeout(TimeSpan.FromMinutes(35)); //x.EnableServiceRecovery(r => { r.RestartService(1); }); x.OnException((ex) => { WriteExceptionLog(ex); Console.WriteLine(ex.ToString() ?? ex.InnerException.ToString()); Console.WriteLine(ex.StackTrace ?? ex.InnerException?.StackTrace); }); }); //try //{ // // Grab the Scheduler instance from the Factory // IScheduler scheduler = AsyncHelper.RunSync( () => StdSchedulerFactory.GetDefaultScheduler()); // // and start it off // scheduler.Start(); // // define the job and tie it to our HelloJob class // IJobDetail job = JobBuilder.Create<CheckoffAutoAcpSendEmailJob>() // .WithIdentity("job1", "group1") // .Build(); // // Trigger the job to run now, and then repeat every 10 seconds // ITrigger trigger = TriggerBuilder.Create() // .WithIdentity("trigger1", "group1") // .StartNow() // .WithSimpleSchedule(x => x // .WithIntervalInSeconds(10) // .RepeatForever()) // .Build(); // // Tell quartz to schedule the job using our trigger // scheduler.ScheduleJob(job, trigger); // // some sleep to show what's happening // Thread.Sleep(TimeSpan.FromSeconds(60)); // // and last shut down the scheduler when you are ready to close your program // scheduler.Shutdown(); //} //catch (SchedulerException se) //{ // Console.WriteLine(se); //} //Console.WriteLine("Press any key to close the application"); //Console.ReadKey(); //Console.ReadKey(); }
public static void Main() { // Run Visual Studio as Administrator or the ports will not be opened. XmlConfigurator.ConfigureAndWatch(new FileInfo(@"./log4net.config")); var host = HostFactory.New(hostConfiguration => { hostConfiguration.UseLog4Net(); hostConfiguration.Service <NancySelfHost>(serviceFactoryBuilder => { serviceFactoryBuilder.ScheduleQuartzJob( quartzConfigurator => quartzConfigurator.WithJob(() => JobBuilder.Create <MainJob>().Build()) .AddTrigger( () => TriggerBuilder.Create().WithSimpleSchedule( builder => builder.WithIntervalInSeconds(5).RepeatForever() ).Build() ) ); serviceFactoryBuilder.WithNancyEndpoint(hostConfiguration, nancyConfigurator => { nancyConfigurator.AddHost(scheme: NancySelfHost.DomainSchema, domain: NancySelfHost.LocalhostDomainName, port: NancySelfHost.LocalhostDomainPortNumber); nancyConfigurator.AddHost(scheme: NancySelfHost.DomainSchema, domain: NancySelfHost.MachineDomainName, port: NancySelfHost.MachineDomainPortNumber); nancyConfigurator.CreateUrlReservationsOnInstall(); nancyConfigurator.DeleteReservationsOnUnInstall(); nancyConfigurator.OpenFirewallPortsOnInstall(firewallRuleName: ApplicationName + "." + "FirewallRule"); }); serviceFactoryBuilder.ConstructUsing(hostSettings => new NancySelfHost()); serviceFactoryBuilder.BeforeStartingService(webService => { }); serviceFactoryBuilder.AfterStartingService(webService => { }); serviceFactoryBuilder.BeforeStoppingService(webService => { }); serviceFactoryBuilder.AfterStoppingService(webService => { }); serviceFactoryBuilder.WhenStarted(webService => webService.Start()); serviceFactoryBuilder.WhenStopped(webService => webService.Stop()); serviceFactoryBuilder.WhenPaused(webService => webService.Pause()); serviceFactoryBuilder.WhenContinued(webService => webService.Continue()); serviceFactoryBuilder.WhenShutdown(webService => webService.Shutdown()); }); hostConfiguration.EnableServiceRecovery(serviceRecovers => { serviceRecovers.RestartService(3); serviceRecovers.RestartComputer(5, "Restarting " + ApplicationName); serviceRecovers.SetResetPeriod(2); }); hostConfiguration.SetDescription("Description of " + ApplicationName); hostConfiguration.SetDisplayName(ApplicationName); hostConfiguration.SetServiceName(ApplicationName); hostConfiguration.EnablePauseAndContinue(); hostConfiguration.EnableShutdown(); hostConfiguration.UseAssemblyInfoForServiceInfo(); hostConfiguration.RunAsLocalSystem(); hostConfiguration.StartAutomatically(); }); if (Environment.UserInteractive) { Process.Start(NancySelfHost.DomainSchema + "://" + NancySelfHost.LocalhostDomainName + ":" + NancySelfHost.LocalhostDomainPortNumber); } host.Run(); }
static void Main(string[] args) { try { Service?service = ParseCommandLine(Environment.CommandLine); if (service == null) { Trace.Write("Failed to load service configuration from container"); return; } string ravenInstanceId = Environment.GetEnvironmentVariable("raveninstanceid"); if (ravenInstanceId.IsNullOrEmpty()) { Trace.Write("No raven instance set, defaulting to instance #1"); ravenInstanceId = "1"; } Trace.Write("Attempting to start Errordite.Services${0} for RavenInstanceId:={1}".FormatWith(service, ravenInstanceId)); var configuration = ObjectFactory.GetObject <ServiceConfiguration>(service.ToString()); //indicates this is the active configuration for this service configuration.IsActive = true; Trace.Write("Loaded configuration, Service:={0}".FormatWith(configuration.ServiceName)); ObjectFactory.Container.Install(new ServicesMasterInstaller(service.Value)); HostFactory.Run(c => { c.StartAutomatically(); c.SetServiceName(configuration.ServiceName); c.SetDisplayName(configuration.ServiceDisplayName); c.SetDescription(configuration.ServiceDiscription); c.DependsOnEventLog(); c.UseLog4Net(@"config\log4net.config"); if (configuration.Username.IsNullOrEmpty()) { c.RunAsPrompt(); } else { c.RunAs(@"{0}\{1}".FormatWith(Environment.MachineName, configuration.Username), configuration.Password); } c.Service <IErrorditeService>(s => { s.ConstructUsing(builder => ObjectFactory.GetObject <IErrorditeService>()); s.WhenStarted(svc => { svc.Configure(); svc.Start(ravenInstanceId); }); s.WhenStopped(svc => svc.Stop()); }); }); } catch (Exception e) { Trace.Write(e.ToString()); } }
public static void Main(string[] args) { var configuration = (EventStoreServiceConfiguration)ConfigurationManager.GetSection("eventStore"); var address = NetworkHelpers.GetIPAddress(); if (args.Contains("--console", StringComparer.CurrentCultureIgnoreCase)) { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget { Layout = "${message}" }; config.AddTarget("console", consoleTarget); var rule = new LoggingRule("*", LogLevel.Debug, consoleTarget); config.LoggingRules.Add(rule); LogManager.Configuration = config; } if (args.Length == 1 && args[0] == "--test") { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget { Layout = "${message}" }; config.AddTarget("console", consoleTarget); var rule = new LoggingRule("*", LogLevel.Debug, consoleTarget); config.LoggingRules.Add(rule); LogManager.Configuration = config; var logger = LogManager.GetLogger("config"); // ReSharper disable once ObjectCreationAsStatement new EventStoreService(address, configuration, logger); return; } HostFactory.Run( hc => { hc.RunAsLocalSystem(); hc.StartAutomatically(); hc.EnableShutdown(); hc.EnableServiceRecovery(c => c.RestartService(1)); hc.Service <EventStoreService>( s => { s.ConstructUsing(name => new EventStoreService(address, configuration, LogManager.GetLogger("eventstorehost"))); s.WhenStarted(tc => tc.Start()); s.WhenStopped(tc => tc.Stop()); }); hc.SetDescription("EventStore OSS Cluster Host Service"); hc.SetDisplayName("EventStore Host"); hc.SetServiceName("EventStoreHost"); }); Console.ReadLine(); }
static void Main(string[] args) { try { log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config")); HostFactory.Run(c => { c.UseLog4Net(); c.Service <ServiceRunner>(s => { s.ConstructUsing(name => new ServiceRunner()); s.WhenStarted((service, control) => service.Start(null)); s.WhenStopped((service, control) => service.Stop(null)); //同步商品池和商品sku s.ScheduleQuartzJob <ServiceRunner>(q => q.WithJob(() => JobBuilder.Create <InsertToProductSkuDetailJob>().Build()) .AddTrigger(() => TriggerBuilder.Create() .WithSimpleSchedule(builder => builder .WithIntervalInHours(5) .RepeatForever()) .Build()) ); }); }); //var a = service.Get(token).GetAwaiter().GetResult(); //var b = service.Del(token,1525817600).GetAwaiter().GetResult(); //var request = new SubmitOrderRequestDto //{ // token = token, // thirdOrder = "ABC0001", // sku = new List<SkuObject> // { // new SkuObject // { // skuId = 3153365, // num = 1, // bNeedAnnex = true, // bNeedGift = false, // //yanbao = new List<long> { 1618482 } // }, // }, // name = "hahah", // province = 1, //北京 // city = 2810, // 大兴区 // county = 6501, //五环至六环之间 // town = 0, // address = "中航技广场B座3层", // mobile = "13811931624", // email = "*****@*****.**", // invoiceState = 2, // invoiceType = 1, // selectedInvoiceTitle = 5, // companyName = "门财科技", // invoiceContent = 22, // paymentType = 4, // isUseBalance = 1, // submitState = 1, // doOrderPriceMode = 1, // orderPriceSnap = new List<OrderPriceSnap> // { // new OrderPriceSnap // { // skuId = 3153365, // price = 7699.00M // } // }, //}; //var jsonRequest = StringHelper.ToJson(request); //var result = service.SubmitOrder(request).GetAwaiter().GetResult(); } catch (Exception e) { throw e; } Console.Read(); }
public static void Main(string[] args) { XmlConfigurator.Configure(); HostFactory.Run(ConfigureHost); }
static void Main(string[] args) { // MassTransit to use Log4Net Log4NetLogger.Use(); HostFactory.Run(cfg => cfg.Service(x => new UserService())); }
static int Main(string[] args) { return((int)HostFactory.Run(cfg => cfg.Service(x => new EventConsumerService()))); }
public static void Main() { bool isTest = false; try { Log.Logger = new LoggerConfiguration() .WriteTo.Console() .WriteTo.EventLog(AppName, manageEventSource: true) .CreateLogger(); } catch (SecurityException) { Log.Logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); Log.Warning("Unable to access Windows Event Log. Logging console only"); } var rc = HostFactory.Run(x => { Type t = typeof(Program); Assembly assembly = t.Assembly; x.Service <Service>(hostSettings => new Service(isTest)); x.RunAsLocalSystem(); x.UseSerilog(); x.SetServiceName(assembly.GetName().Name); x.SetDisplayName(assembly.GetCustomAttribute <AssemblyTitleAttribute>().Title); x.SetDescription(assembly.GetCustomAttribute <AssemblyDescriptionAttribute>().Description); x.AddCommandLineDefinition("test", v => { isTest = true; }); x.AddCommandLineDefinition("config", v => { isTest = true; //configure custom file if (!string.IsNullOrEmpty(v)) { Config.SetConfigFile(v); } Config.ConfigureAppSettings(); }); x.AddCommandLineDefinition("installAndConfigureService", v => { isTest = true; Config.ConfigureAppSettings(); Config.InstallService(); }); x.AddCommandLineDefinition("uninstallService", v => Config.UninstallService(v)); x.AddCommandLineDefinition("installAndConfigureInstance", v => { isTest = true; if (string.IsNullOrEmpty(v)) { Log.Logger.Error("Instance name must be provided"); } else { Config.ConfigureFromFile(); Config.ConfigureAppSettings(); Config.InstallService(v); } }); x.AddCommandLineDefinition("loglevel", v => { var loggerConfig = new LoggerConfiguration(); try { switch (v) { case "information": loggerConfig = loggerConfig.MinimumLevel.Information(); break; case "warning": loggerConfig = loggerConfig.MinimumLevel.Warning(); break; case "debug": loggerConfig = loggerConfig.MinimumLevel.Debug(); break; case "error": loggerConfig = loggerConfig.MinimumLevel.Error(); break; case "verbose": loggerConfig = loggerConfig.MinimumLevel.Verbose(); break; } Log.Logger = loggerConfig.WriteTo.Console() .WriteTo.EventLog(AppName, manageEventSource: true) .CreateLogger(); } catch (SecurityException) { Log.Logger = loggerConfig.WriteTo.Console().CreateLogger(); Log.Warning("Unable to access Windows Event Log. Logging console only"); } }); x.EnableStartParameters(); x.WithStartParameter("ConfigFile", f => { Config.SetConfigFile(f); }); x.SetHelpTextPrefix(BuildHelpDoc()); }); var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode()); Environment.ExitCode = exitCode; }