private static void RegisterService() { var remainingArgs = Environment.GetCommandLineArgs() .Where(arg => arg != RegisterServiceFlag) .Select(EscapeArgs).ToList(); remainingArgs.Add(RunAsServiceFlag); var host = Process.GetCurrentProcess().MainModule.FileName; if (!host.EndsWith("dotnet.exe", StringComparison.OrdinalIgnoreCase)) { // For self-contained apps, skip the dll path remainingArgs = remainingArgs.Skip(1).ToList(); } var fullServiceCommand = host + " " + string.Join(" ", remainingArgs); // Do not use LocalSystem in production, but this is good for demos as LocalSystem will have access to some random git-clone path // Note that when the service is already registered and running, it will be reconfigured but not restarted var serviceDefinition = new ServiceDefinitionBuilder(ServiceName) .WithDisplayName(ServiceDisplayName) .WithDescription(ServiceDescription) .WithBinaryPath(fullServiceCommand) .WithCredentials(Win32ServiceCredentials.LocalSystem) .WithAutoStart(true) .Build(); new Win32ServiceManager().CreateOrUpdateService(serviceDefinition, startImmediately: true); Console.WriteLine($@"Successfully registered and started service ""{ServiceDisplayName}"" (""{ServiceDescription}"")"); }
private static void RegisterService() { // Environment.GetCommandLineArgs() includes the current DLL from a "dotnet my.dll --register-service" call, which is not passed to Main() var remainingArgs = Environment.GetCommandLineArgs() .Where(arg => arg != RegisterServiceFlag) .Select(EscapeCommandLineArgument) .Append(RunAsServiceFlag); var host = Process.GetCurrentProcess().MainModule.FileName; if (!host.EndsWith("dotnet.exe", StringComparison.OrdinalIgnoreCase)) { remainingArgs = remainingArgs.Skip(1); } var fullServiceCommand = host + " " + string.Join(" ", remainingArgs); var serviceDefinition = new ServiceDefinitionBuilder(ServiceName) .WithDisplayName(ServiceDisplayName) .WithDescription(ServiceDescription) .WithBinaryPath(fullServiceCommand) .WithCredentials(Win32ServiceCredentials.LocalSystem) .WithAutoStart(true) .Build(); new Win32ServiceManager().CreateOrUpdateService(serviceDefinition, true); Console.WriteLine( $@"Successfully registered and started service ""{ServiceDisplayName}"" (""{ServiceDescription}"")"); }
private static string GetGeneratedCodeFromXmlDefinition(string xml) { ////var serializer = new XmlSerializer(typeof(ApisRoot)); ////var reader = new StringReader(xml); ////var root = (ApisRoot)serializer.Deserialize(reader); MemoryStream stream = new MemoryStream(); StreamWriter writer = new System.IO.StreamWriter(stream); var generator = new CSharpGenerator(writer); var xmlStream = new MemoryStream(); var xmlWriter = new StreamWriter(xmlStream); xmlWriter.Write(xml); xmlWriter.Flush(); xmlStream.Seek(0L, SeekOrigin.Begin); var builder = new ServiceDefinitionBuilder(); ////builder.AppendServiceDefinition(new ServiceDefinition(root)); builder.AppendServiceDefinition(xmlStream); generator.Run(builder.Definition); stream.Seek(0L, SeekOrigin.Begin); var result = new StreamReader(stream).ReadToEnd(); return(result); }
public void ImplicitSubReturnTypes2() { var xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <Root> <ApiGroup Name=""group""> <ReturnType Name=""person"" ClassName=""Person""> <Field Name=""location:(name)"" /> <Field Name=""location:(country:(code))"" /> </ReturnType> </ApiGroup> </Root>"; var serializer = new XmlSerializer(typeof(ApisRoot)); var reader = new StringReader(xml); var root = (ApisRoot)serializer.Deserialize(reader); var stream = new System.IO.MemoryStream(); var writer = new System.IO.StreamWriter(stream); var generator = new CSharpGenerator(writer); var builder = new ServiceDefinitionBuilder(); builder.AppendServiceDefinition(new ServiceDefinition(root)); generator.Run(builder.Definition); writer.Flush(); stream.Seek(0L, System.IO.SeekOrigin.Begin); var result = new StreamReader(stream).ReadToEnd(); Assert.IsFalse(string.IsNullOrEmpty(result)); }
private static void RegisterService() { Logger.Log(LogLevel.Info, "Program registering as service"); // Environment.GetCommandLineArgs() includes the current DLL from a "dotnet my.dll --register-service" call, which is not passed to Main() var remainingArgs = Environment.GetCommandLineArgs().Where(arg => arg != RegisterServiceFlag) .Select(EscapeCommandLineArgument).Append(RunAsServiceFlag); var host = Process.GetCurrentProcess().MainModule.FileName; if (!host.EndsWith("dotnet.exe", StringComparison.OrdinalIgnoreCase)) { remainingArgs = remainingArgs.Skip(1); } var fullServiceCommand = host + " " + string.Join(" ", remainingArgs); // Do not use LocalSystem in production.. but this is good for demos as LocalSystem will have access to some random git-clone path // Note that when the service is already registered and running, it will be reconfigured but not restarted var serviceDefinition = new ServiceDefinitionBuilder(ServiceName).WithDisplayName(ServiceDisplayName) .WithDescription(ServiceDescription).WithBinaryPath(fullServiceCommand) .WithCredentials(Win32ServiceCredentials.LocalSystem).WithAutoStart(true).Build(); Console.WriteLine(ServiceName); Console.WriteLine(ServiceDisplayName); Console.WriteLine(ServiceDescription); Console.WriteLine(fullServiceCommand); new Win32ServiceManager().CreateOrUpdateService(serviceDefinition, true); Console.WriteLine( $@"Successfully registered and started service ""{ServiceDisplayName}"" (""{ServiceDescription}"")"); }
public static ServiceDefinition BuildNonValidating(this ServiceDefinitionBuilder builder) { return(new ServiceDefinition(builder.ServiceName, builder.BinaryPath) { DisplayName = builder.DisplayName, Description = builder.Description, Credentials = builder.Credentials, FailureActions = builder.FailureActions, FailureActionsOnNonCrashFailures = builder.FailureActionsOnNonCrashFailures, AutoStart = builder.AutoStart, ErrorSeverity = builder.ErrorSeverity }); }
public void ImplicitSubReturnTypes() { var stream = new System.IO.MemoryStream(); var writer = new System.IO.StreamWriter(stream); var generator = new CSharpGenerator(writer); var root = new ApisRoot { ApiGroups = new List <ApiGroup>() { new ApiGroup { Name = "g", Methods = new List <ApiMethod>(), ReturnTypes = new List <ReturnType>() { new ReturnType { Name = "r1", Fields = new List <Field>() { new Field { Name = "f1", }, new Field { Name = "f2:(r2:(name))", }, }, }, }, }, }, }; var builder = new ServiceDefinitionBuilder(); builder.AppendServiceDefinition(new ServiceDefinition(root)); generator.Run(builder.Definition); writer.Flush(); stream.Seek(0L, System.IO.SeekOrigin.Begin); var result = new StreamReader(stream).ReadToEnd(); Assert.IsFalse(string.IsNullOrEmpty(result)); Assert.IsTrue(result.Contains("public class R1")); Assert.IsTrue(result.Contains("public class F2")); Assert.IsTrue(result.Contains("public string F1")); Assert.IsTrue(result.Contains("public F2 F2")); Assert.IsTrue(result.Contains("public string Name")); }
public void Register(Action <ServiceMessage> error) { try { var cmd = $"{Process.GetCurrentProcess().MainModule.FileName} {RunAsServiceHostFlag}"; var serviceDefinition = new ServiceDefinitionBuilder(ServiceName) .WithDisplayName(ServiceName) .WithDescription(ServiceDescription) .WithBinaryPath(cmd) .WithCredentials(Win32ServiceCredentials.NetworkService) .WithAutoStart(true) .Build(); this.Manager.CreateOrUpdateService(serviceDefinition, startImmediately: true); } catch (Exception e) { ServiceMessage.Send(error, $"Register: {e.Message}"); } }
public void MyTestMethod() { var stream = new System.IO.MemoryStream(); var writer = new System.IO.StreamWriter(stream); var generator = new CSharpGenerator(writer); var root = new ApisRoot { ApiGroups = new List <ApiGroup>() { new ApiGroup { Name = "g", Methods = new List <ApiMethod>() { new ApiMethod { Path = "/v1/test1", MethodName = "mtd1", }, new ApiMethod { Path = "/v1/test1/{UserId}", MethodName = "mtd2", }, }, ReturnTypes = new List <ReturnType>(), }, }, }; var builder = new ServiceDefinitionBuilder(); builder.AppendServiceDefinition(new ServiceDefinition(root)); generator.Run(builder.Definition); writer.Flush(); stream.Seek(0L, System.IO.SeekOrigin.Begin); var result = new StreamReader(stream).ReadToEnd(); Assert.IsFalse(string.IsNullOrEmpty(result)); Assert.IsTrue(result.Contains("public void mtd1(")); Assert.IsTrue(result.Contains("public void mtd2(")); Assert.IsTrue(result.Contains("string userId")); }
private static void RegisterService() { // Environment.GetCommandLineArgs() includes the current DLL from a "dotnet my.dll --register-service" call, which is not passed to Main() var commandLineArgs = Environment.GetCommandLineArgs(); var serviceArgs = commandLineArgs .Where(arg => arg != RegisterServiceFlag && arg != PreserveWorkingDirectoryFlag) .Select(EscapeCommandLineArgument) .Append(RunAsServiceFlag); var host = Process.GetCurrentProcess().MainModule.FileName; if (!host.EndsWith("dotnet.exe", StringComparison.OrdinalIgnoreCase)) { // For self-contained apps, skip the dll path serviceArgs = serviceArgs.Skip(1); } if (commandLineArgs.Contains(PreserveWorkingDirectoryFlag)) { serviceArgs = serviceArgs .Append(ServiceWorkingDirectoryFlag) .Append(EscapeCommandLineArgument(Directory.GetCurrentDirectory())); } var fullServiceCommand = host + " " + string.Join(" ", serviceArgs); // Do not use LocalSystem in production.. but this is good for demos as LocalSystem will have access to some random git-clone path // When the service is already registered and running, it will be reconfigured but not restarted var serviceDefinition = new ServiceDefinitionBuilder(ServiceName) .WithDisplayName(ServiceDisplayName) .WithDescription(ServiceDescription) .WithBinaryPath(fullServiceCommand) .WithCredentials(Win32ServiceCredentials.LocalSystem) .WithAutoStart(true) .Build(); new Win32ServiceManager().CreateOrUpdateService(serviceDefinition, startImmediately: true); WriteLine($@"Successfully registered and started service ""{ServiceDisplayName}"" (""{ServiceDescription}"")"); }
private static void Install(IService service) { var failureAction = new ScAction { Type = ScActionType.ScActionRestart, Delay = TimeSpan.FromMinutes(1) }; var serviceDefinition = new ServiceDefinitionBuilder(service.ServiceName) .WithDisplayName(service.DisplayName) .WithDescription(service.Description) .WithBinaryPath(Process.GetCurrentProcess().MainModule.FileName + " run-as-service") .WithAutoStart(true) .WithFailureActions(new ServiceFailureActions(TimeSpan.FromMinutes(1), "", "", new[] { failureAction, failureAction, failureAction })) .WithCredentials(Win32ServiceCredentials.LocalSystem) .Build(); new Win32ServiceManager().CreateOrUpdateService(serviceDefinition); Console.WriteLine($"service {service.ServiceName} installed successfully."); }
public void ImplicitAndExplicitReturnTypes() { var xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <Root> <ApiGroup Name=""group""> <ApiMethod MethodName=""ftw"" ReturnType=""Person"" Path=""/ftw"" /> <ReturnType Name=""person"" ClassName=""Person""> <Field Name=""location"" Type=""PersonLocation"" /> </ReturnType> <ReturnType Name=""location"" ClassName=""PersonLocation""> <Field Name=""name"" /> </ReturnType> </ApiGroup> </Root>"; var serializer = new XmlSerializer(typeof(ApisRoot)); var reader = new StringReader(xml); var root = (ApisRoot)serializer.Deserialize(reader); var stream = new System.IO.MemoryStream(); var writer = new System.IO.StreamWriter(stream); var generator = new CSharpGenerator(writer); var builder = new ServiceDefinitionBuilder(); builder.AppendServiceDefinition(new ServiceDefinition(root)); generator.Run(builder.Definition); writer.Flush(); stream.Seek(0L, System.IO.SeekOrigin.Begin); var result = new StreamReader(stream).ReadToEnd(); Assert.IsFalse(string.IsNullOrEmpty(result)); Assert.IsFalse(string.IsNullOrEmpty(result)); Assert.IsTrue(result.Contains("public class Person")); Assert.IsTrue(result.Contains("public class PersonLocation")); Assert.IsTrue(result.Contains("public PersonLocation Location")); Assert.IsFalse(result.Contains("public class Location")); Assert.IsTrue(result.Contains("public string Name")); }
public static void RegisterService(string registerFlag, string runFlag) { var remainingArgs = Environment.GetCommandLineArgs() .Where(arg => arg != registerFlag) .Select(arg => { arg = Regex.Replace(arg, @"(\\*)" + "\"", @"$1$1\" + "\""); arg = "\"" + Regex.Replace(arg, @"(\\+)$", @"$1$1") + "\""; return(arg); }) .Append(runFlag); var host = Process.GetCurrentProcess().MainModule.FileName; if (!host.EndsWith("dotnet.exe", StringComparison.OrdinalIgnoreCase)) { // For self-contained apps, skip the dll path remainingArgs = remainingArgs.Skip(1); } var fullServiceCommand = host + " " + string.Join(" ", remainingArgs); // Do not use LocalSystem in production.. but this is good for demos as LocalSystem will have access to some random git-clone path // Note that when the service is already registered and running, it will be reconfigured but not restarted var serviceDefinition = new ServiceDefinitionBuilder("Simpbot.Cli.Service") .WithDisplayName("Simpbot.Cli.Service") .WithDescription("Simple bot built with Discrod.NET") .WithBinaryPath(fullServiceCommand) .WithCredentials(Win32ServiceCredentials.LocalSystem) .WithAutoStart(true) .Build(); new Win32ServiceManager().CreateOrUpdateService(serviceDefinition, true); Console.WriteLine($@"Successfully registered and started service Simpbot.Cli"); }
public void ValidateAndExecuteService() { var iSendFireService = GetServiceSingleton(); try { //File.Create("C:\\GotThere.FactoryBaseValidateAndExecute.txt"); iSendFireService.Init(ServiceProvider); var status = iSendFireService.ValidateConfiguration(); DisplayStartup(iSendFireService, status); switch (status) { case BaseCommandArgumentSelected.DisplayHelp: Environment.ExitCode = 1; Thread.Sleep(500); // Allow NLog Console Logging. break; case BaseCommandArgumentSelected.ExecuteProgramAsConsole: Console.Title = iSendFireService.ApplicationName; iSendFireService.Start(); Console.WriteLine($"Running {iSendFireService.ServiceName} in Console Mode."); Console.WriteLine("Hit any Key to Stop..."); Console.ReadKey(); Console.WriteLine("Key Registered, Stopping..."); iSendFireService.Stop(); Thread.Sleep(500); // Allow NLog Console Logging. break; case BaseCommandArgumentSelected.ExecuteProgramAsService: //File.Create("C:\\GotThere.FactoryBaseValidateAndExecute.ExecuteProgramAsService.txt"); var serviceHost = new Win32ServiceHost(iSendFireService); serviceHost.Run(); break; case BaseCommandArgumentSelected.RegisterService: var rebuiltArguments = Environment.GetCommandLineArgs() .Where(arg => !arg.EndsWith(BaseCommandArguments.RegisterService, StringComparison.OrdinalIgnoreCase)) .Select(EscapeCommandLineArgument); var host = Process.GetCurrentProcess().MainModule.FileName; if (!host.EndsWith("dotnet.exe", StringComparison.OrdinalIgnoreCase)) { // For self-contained apps, skip the dll path rebuiltArguments = rebuiltArguments.Skip(1); } var fullServiceCommand = host + " " + string.Join(" ", rebuiltArguments); // Note that when the service is already registered and running, it will be reconfigured but not restarted var serviceDefinition = new ServiceDefinitionBuilder(iSendFireService.ServiceName) .WithDisplayName(iSendFireService.GetServiceDisplayName()) .WithDescription(iSendFireService.GetServiceDescription()) .WithBinaryPath(fullServiceCommand) // TODO: Support more than LocalSystem in the future .WithCredentials(Win32ServiceCredentials.LocalSystem) // TODO: Support more than autostart in the future .WithAutoStart(true) .Build(); ServiceProvider.GetService <Win32ServiceManager>().CreateOrUpdateService(serviceDefinition, true); Console.WriteLine($@"Successfully registered and started service ""{iSendFireService.ServiceName}"" (""{iSendFireService.GetHelpDescription()}"")"); break; case BaseCommandArgumentSelected.UninstallService: ServiceProvider.GetService <Win32ServiceManager>().DeleteService(iSendFireService.ServiceName); break; } } catch (Exception ex) { var errorTitle = $"{iSendFireService.ApplicationName} Startup Exception!"; //File.WriteAllText(".\\SendFireServiceFactoryBase.err", ex.Message + Environment.NewLine + ex.StackTrace); // Catastrophic failure of DI and configuration building, display exception and shut down. if (Logger != null) { DisplayStartup(iSendFireService, BaseCommandArgumentSelected.DisplayHelp); // TODO: Need a better logger than the base logger. Logger.LogCritical(errorTitle, ex); Logger.LogCritical(ex.Message); Thread.Sleep(500); // Allow Console / Other Logging if its on a background thread. } else { Console.WriteLine(errorTitle); Console.WriteLine(ex.Message); } } }