forked from dasMulli/dotnet-win32-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
129 lines (114 loc) · 5.19 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
using System;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using DasMulli.Win32.ServiceUtils;
namespace TestService
{
public class Program
{
private const string RunAsServiceFlag = "--run-as-service";
private const string RegisterServiceFlag = "--register-service";
private const string UnregisterServiceFlag = "--unregister-service";
private const string InteractiveFlag = "--interactive";
private const string ServiceName = "DemoService";
private const string ServiceDisplayName = "Demo .NET Core Service";
private const string ServiceDescription = "Demo ASP.NET Core Service running on .NET Core";
public static void Main(string[] args)
{
try
{
if (args.Contains(RunAsServiceFlag))
{
RunAsService(args);
}
else if (args.Contains(RegisterServiceFlag))
{
RegisterService();
}
else if (args.Contains(UnregisterServiceFlag))
{
UnregisterService();
}
else if (args.Contains(InteractiveFlag))
{
RunInteractive(args);
}
else
{
DisplayHelp();
}
}
catch (Exception ex)
{
Console.WriteLine($"An error ocurred: {ex.Message}");
}
}
private static void RunAsService(string[] args)
{
var testService = new TestWin32Service(args.Where(a => a != RunAsServiceFlag).ToArray());
var serviceHost = new Win32ServiceHost(testService);
serviceHost.Run();
}
private static void RunInteractive(string[] args)
{
var testService = new TestWin32Service(args.Where(a => a != InteractiveFlag).ToArray());
testService.Start(new string[0], () => { });
Console.WriteLine("Running interactively, press enter to stop.");
Console.ReadLine();
testService.Stop();
}
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))
{
// 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
new Win32ServiceManager()
.CreateOrUpdateService(
ServiceName,
ServiceDisplayName,
ServiceDescription,
fullServiceCommand,
Win32ServiceCredentials.LocalSystem,
autoStart: true,
startImmediately: true,
errorSeverity: ErrorSeverity.Normal
);
Console.WriteLine($@"Successfully registered and started service ""{ServiceDisplayName}"" (""{ServiceDescription}"")");
}
private static void UnregisterService()
{
new Win32ServiceManager()
.DeleteService(ServiceName);
Console.WriteLine($@"Successfully unregistered service ""{ServiceDisplayName}"" (""{ServiceDescription}"")");
}
private static void DisplayHelp()
{
Console.WriteLine(ServiceDescription);
Console.WriteLine();
Console.WriteLine("This demo application is intened to be run as windows service. Use one of the following options:");
Console.WriteLine(" --register-service Registers and starts this program as a windows service named \"" + ServiceDisplayName + "\"");
Console.WriteLine(" All additional arguments will be passed to ASP.NET Core's WebHostBuilder.");
Console.WriteLine(" --unregister-service Removes the windows service creatd by --register-service.");
Console.WriteLine(" --interactive Runs the underlying asp.net core app. Useful to test arguments.");
}
private static string EscapeCommandLineArgument(string arg)
{
// http://stackoverflow.com/a/6040946/784387
arg = Regex.Replace(arg, @"(\\*)" + "\"", @"$1$1\" + "\"");
arg = "\"" + Regex.Replace(arg, @"(\\+)$", @"$1$1") + "\"";
return arg;
}
}
}