Net windows service host

Creating a Windows Service with C#/.NET5

February 10th, 2021

Windows Services

Windows Services have been a foundation of Windows since Windows NT. They help users, or system admins, manage long-running programs that execute in their own Windows sessions. It is fairly trivial to set them up and start whenever the computer boots, for example. Since they can be completely UI-less, they provide an interesting approach for tasks that don’t require user interaction, such as looking for directory or file updates, pooling a service, or logging data. Windows itself uses services for many common task that an operating system should do, like Windows Defender , and Windows Update .

This blog post will demonstrate how to build a system file watcher as a Windows service that runs in the background, and classifies images using the WinML model we’ve previously set in my previous blog post.

ASP.NET similarities

If you ever created an ASP.NET Core project, you probably noticed that the default templates create a Program.cs file. This file contains the worldly famous Main method. Actually, most templates create this method, aside from class libraries, which don’t necessarily provide a starting point for your code to execute.

In my last blog post we created a small program that parses the arguments passed down to it and processes one image file, using WinML. For a Windows Service, which must not end its execution straight away, we need to halt the termination of our process until the Windows Service manually is terminated, not only after a single image is processed. We don’t want the Start -> Process -> End flow to exist. To achieve this, instead of using the command line argument to inform a single image file path, we will change our software to expect a Directory path, which we will listen for file changes. Then, whenever a new file is created inside this folder we are watching, we will run our WinML code to move the file to a folder named after its category, recognized by our WinML model.

ASP.NET is the most common framework to provide a web service using .NET , but unlike a web service, a Windows Service is not necessarily accessed through the network. It is, still, quite simple to setup a Windows Service that hosts a web service. Since this is a possible scenario, Microsoft provides a NuGet package named Microsoft.Extensions.Hosting.WindowsServices that let us host our .NET process, with or without ASP.NET , as a Windows Service. It automatically provides logging capabilities to the Windows Events, the default output where Windows Services should log information to, as well as automatically logging life-cycle events, such as Started , Stopping and Stopped events. It also provides a helpful method to detect if your process is running as a windows service or not.

Coding, coding, coding!

With this NuGet installed inside our project, we can change our Main method to initialize a Host, which will initialize it as a Windows Service and run it. We’ll move all the WinML related code to a new Worker class, which will act as a hosted service without our host process. The code itself is simpler than it sounds:

As you can see, we are still using the CommandLineParser NuGet package that we’ve used on the last blog post, since we still want to make this software act based on the parameters that we invoked it with. You’ll notice that the CreateHostBuilder method has both the string array parameter, as well as our already parsed and valid CommandLineOptions . We need both, since we want the parsed one and due to the fact that the Host.CreateDefaultBuilder method allows you to pass parameters from the command line to configure it, so we need to pass down the original string array to it.

We start by creating this default builder. We then configure its logging to filter only if the log level is Information or higher, and then we add our hosted service. We also create a singleton with our parsed CommandLineOptions , which allows us to use it inside the ImageClassifierWorker class that is initialized for us by the default builder. We will expect a CommandLineOptions parameter in the constructor of our ImageClassifierWorker which will be automatically injected for us. We are also configuring our EventLogSettings with a LogName and a SourceName . These parameters let us choose where the Events from our logs will be stored. Last, but not least, we are initializing this host as a Windows Service. This last step is as easy as calling the UseWindowsService() method, which configures the host to use the logging properties we just set, as well as setting up automatic logging for the Windows Service lifetime events.

Читайте также:  Виджет часы календарь для windows 10

Since this new code will listen to new files in the directory we specify, we need a way to filter the file extensions we want to allow processing. We could hard-code this, but lets simply add a parameter to our CommandLineOptions class, which will easily handle all the parsing for us:

See how easy it is to support our list of extensions? Since these are the most commons ones, we support png , jpg , and jpeg , and all the classes we use to load our image handle these extensions, so we are safe with them. We’ve also updated the HelpText of the Path argument, to better reflect what it actually means.

Now that you understand the structure of our Program.cs , and we’ve updated our arguments, lets look at our new ImageClassifierWorker class, which inherits from BackgroundService :

This is the class that will run our WinML code. The ExecuteAsync method is going to be called automatically for us, so we need a mechanism to keep it from returning, to keep our process from ending. There are many ways to achieve that, specially since we need to return a Task . I’ve chosen a simple one that can be achieved in only 3 lines of code:

This should be at the very end of our ExecuteAsync method. The stoppingToken is passed down to our ExecuteAsync method, and it is an instance of CancellationToken which will be cancelled when our service is requested to stop. See how we are using the _logger object that we stored in our constructor? That is a handy helper that lets us log whatever we want/need. Remember that this code is headless (no user interface at all), so we need a way to know what our code is executing, and that is done through logs.

At the start of our method, we should load our WinML model, pretty much the same way we were doing before:

The interesting code that we are adding here is this:

This creates a FileSystemWatcher instance that will hook up to some Windows events for us, and automatically raise the Created event whenever there is a new file created on the folder we are watching. Notice that we are adding Filters to it, which are mapping to the extension filters coming from our new command line argument.

We are waiting 1000 milliseconds (1 second), before we process the file. The FileSystemWatcher is attached to the Windows events, and is so fast that it will raise the Created event even before the file is closed by whichever process is still creating it. If we didn’t add a Delay, our ProcessFileAsync method would throw an exception:

We could have created a retry logic if we caught this specific exception but, again, this solution is a simplification, and will keep our code simple for this sample.

The ProcessFileAsync method expects a full path to an image file and a confidence float, just like we had before. I’ve just extracted it to its own method. Also, I’ve changed the logic at the end to, instead of just printing the classification to the Console, to move the file to its correct folder:

Notice that the folderName argument passed in our MoveFileToFolder method is the label with highest confidence, returned by our WinML classification model for that one specific image. Therefore, we are moving that file inside a folder with its category name. The whole process is so fast that if you copy and paste an image file into the folder we are watching, it barely stays inside the folder, almost instantaneously being moved to a newly (or existing) folder.

Where is the service?

The next step is to (1) deploy this somewhere, (2) register our Windows Service, and (3) start it!

Читайте также:  Порт сканер для linux

The deployment step is very straight forward. Right-click in our ImageClassifier project, inside Visual Studio, and select Publish . This will let you select where you want to publish it, and since this is a simple .NET5 console application, we can choose between a variety of places. Lets select a simple Folder .

On the next step, just select Folder again and click Next . On the last step, we need to select a path. I’ve chosen a simple folder inside my Desktop, but this could be anywhere you need it to, as long as the user you select to run the service have the proper permissions to execute it.

Click on Finish to create the publish profile, and then on Publish to build our code and deploy it!

You will see that all the files that we need are properly deployed in that folder, so we can now configure our service!

Another way to publish your project is using the dotnet publish command.

Service Controller

Windows Services are managed through a tool called Service Controller, a.k.a. SC . We’ll use one simple command to create a windows service, and we’ll start it manually through the services tab. Remember that you need admin privileges to create a service on Windows, so run an elevated command line to run these commands.

All we need is a name for our service, and which command should be executed (the binary path).

Notice that we are passing the binPath argument in quotes. We are passing our arguments to the executable right after the path, still inside the quotes, which will be handled by our implementation of the CommandLineParser .

Running this command should return a simple message, if successful:

This means our service is created, but not yet running. To run it, lets call the SC command again, but now with different parameters:

This will log some properties on the console, and you will probably read START_PENDING in the STATE , since the SC command will return immediately. The simplest way to check the state of your service is at Windows’s Task Manager . If you never noticed, there is a Services tab:

This means that our service is running! Lets see if it works!

Code in Action!

Since I’ve added the C:\Users\alzollin\Desktop\ImageClassification\Images path parameter when I created the service, it will be listening to new files created at that folder. Here is the folder before I do anything:

And I’m going to copy all these files at the same time inside this empty folder:

The instant I copy these files over to the Images folder, there will be an intentional one second delay, followed by a refresh of explorer showing all the images already classified:

Notice that some files were not moved, and that is due to our logic that moves them only if the WinML model classified them with a 90% confidence. But how do we know how these files were classified? The answer is the Windows Events.

Event Viewer

The Windows Event Viewer is a tool that helps you read the Windows Logs. Just search on Windows’ start menu for Event Viewer , and the Windows search will show find it. There is also a neat shortcut that I often use: Windows Key + X then V .

When you open the Event Viewer you will see a tree view on the left side, that categorizes the events. Remember when we configured our LogName , during our process initialization? This is where the log will be, inside the Applications and Services Logs :

Selecting our Image Classifier Service will show all the events that your service logged under that category, with the Level, Date/Time, and much more:

You can quickly see that the Cat2.jpg file was not moved around since its highest ranked classification was at only about 44% (0.44842827) of confidence, as a “tabby, tabby cat”. Since our default confidence is 90%, the file wasn’t moved. You can easily play around with this service, for example, by dragging images from the browser to that folder to see the logs of how they were classified. Just remember to refresh by pressing F5.

Conclusion

As we were able to show with our fun sample, Windows Services are not extremely complex, if used properly. They allow developers to implement complex scenario with a simple lifecycle management, and C#/.NET5 is a great technology to create them.

Читайте также:  Приложение для установки windows 10 mobile

Don’t forget to check out the full sample source here.

I hope you enjoyed this 3-part series. You can read the other 2 blog posts here:

Service Host

The service host is the runtime environment for hosting a service within a process.

A service can configure one or more endpoints inside a service host.

Creating a service host

Before creating a service host, a service needs to define its endpoints. An endpoint in service host is specified in the WS_SERVICE_ENDPOINT structure and it is defined by the following information:

  • An address, which is the physical URI on which the service will be hosted.
  • A WS_CHANNEL_TYPE structure that specifies the type of the underlying channel for the endpoint.
  • A WS_CHANNEL_BINDING structure that specifies the binding of the channel.
  • A WS_SECURITY_DESCRIPTION structure that contains the security description for the endpoint.
  • A WS_SERVICE_CONTRACT structure that represents the service contract for the endpoint.
  • A WS_SERVICE_SECURITY_CALLBACK structure that specifies an authorization callback function for the endpoint.
  • A WS_SERVICE_ENDPOINT_PROPERTY structure that contains an array of service endpoint properties.

Only one-way contracts are supported for SOAP over UDP, represented by WS_UDP_CHANNEL_BINDING in the WS_CHANNEL_BINDING enumeration.

After an endpoint is defined, it can be passed to the WsCreateServiceHost function, which takes an array of pointers to WS_SERVICE_ENDPOINT structures.

An application can optionally provide an array of service properties to WsCreateServiceHost to configure custom settings on the service host.

An application opens the service host to start accepting client requests.

After opening the service host, the application can close it if there are no more operations that require it. Note that this does not release its resources, and that it can be reopened with a subsequent call to WsResetServiceHost.

After closing the service host, an application may reset the service host for reuse.

When the application is done with the service host it can free the resources associated with the service host by calling the WsFreeServiceHost function. Note that WsCloseServiceHost must be called before calling this function.

For information on attaching a custom state to the service host, see User Host State

For information on authorization in a service host for a given endpoint, see Service Authorization.

For iinformation on implementing service operations and service contracts for a service, see the service operations and service contracttopics.

Security

An application can use the followin properties to control the amount of resources the service host allocates on behalf of the application:

Secure defaults are chosen for each of these properties, an application must be careful if it wishes to modify these properties. Beyond the above-mentioned properties, channel, listener and message specific properties can also be modified by the application. Refer to the security considerations of these components before modifying any of these settings.

In addition, the following application design considerations should be carefully evaluated when using WWSAPI service host API:

  • When using MEX, applications should be careful not to disclose any sensitive data. As a mitigation, if the nature of the data being exposed through MEX is sensitive, applications may choose to configure the MEX endpoint with a secure binding requiring authentication at the very least and implement authorization as part of the endpoint using the WS_SERVICE_SECURITY_CALLBACK.
  • By default rich error information through faults is disabled on service host by WS_SERVICE_PROPERTY_FAULT_DISCLOSURE property. It is upon the discretion of the application to send rich error information as part of the fault. However, this can result in information disclosure and thus it is recommended that this setting is only changed for debugging scenarios.
  • Beyond validation performed for Basic Profile 2.0 and XML serialization, service host performs no validation on the data content received as part of service operation parameters. It is the responsibility of the application to perform all parameter validations on its own.
  • Authorization is not implemented as part of service host. However, applications can implement their own authorization scheme using WS_SECURITY_DESCRIPTION and the WS_SERVICE_SECURITY_CALLBACK.
  • It is the responsibility of the application to use secure bindings on its endpoint. Service host does not provide any security beyond what is configured on the endpoint.

The following API elements are used with the service host.

Оцените статью