Saturday 24 April 2021

Writing Windows Services - Creating a Windows Service

Introduction

Windows Services are the Microsoft Windows' implementation of the computer science daemon.

Creating the service

In Visual Studio go to File/New/Project.

On the dialogue select Windows Service (.NET Framework).

Name the project and click Create.

Rename the Service1.cs file. VS will offer to rename the references as well, agree to it.

In the Design Tab, select Properties from the short cut menu.

Name the service. This is at the bottom of the properties and is easy to overlook (the error starts "service name contains invalid characters").

Add an Event Log object.

View Code to see the code.

Add a custom event log.

        public MyService()
        {
            InitializeComponent();
            eventLog1 = new System.Diagnostics.EventLog();
            if (!System.Diagnostics.EventLog.SourceExists("MySource"))
            {
                System.Diagnostics.EventLog.CreateEventSource(
                    "MySource", "MyNewLog");
            }
            eventLog1.Source = "MySource";
            eventLog1.Log = "MyNewLog";
        }

Add polling to the OnStart.

Add method called by timer.

        protected override void OnStart(string[] args)
        {
            eventLog1.WriteEntry("In OnStart.");
            ServiceStatus serviceStatus = new ServiceStatus();
            serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;
            serviceStatus.dwWaitHint = 100000;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);            // Set up a timer that triggers every minute.
            Timer timer = new Timer();
            timer.Interval = 60000; // 60 seconds
            timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
            timer.Start();
            // Update the service state to Running.
            serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);
        }

If the start (and/or) stop process is expected to take some time, it is possible to add additional service status information.

Creating the installer

Select the Service code file in Solution Explorer and choose View Designer.

In the Design View select the background and Add Installer.

This will add ProjectInstaller.cs to the project.

Click on the serviceInstaller1 and select Properties

Ensure the service name is correct, add a description and a display name.

Set the StartType to Automatic.

Right click on serviceProcessInstaller1 and select Properties. Set the Account property to LocalSystem.



Build the service

In the Solution Explorer select the service project and right click and select properties.

On the Application tab select the service program as the Startup object.

Build the project via Build/Build on the menu.

Installing the Service

Open the Developer Command Prompt for Visual Studio as Administrator from the Windows Start menu.

Change Directory to the location of the service executable.

Enter the command: installutil "My First Service.exe"

Checking your work

In the search box on the task bar type "services" and select the "Services" app.

Check for your new service.

Again in the search box on the task bar type "event" and select the Event Viewer.

Expand the Applications and Services Logs and look for your new log. Refresh the log to see each new log entry as the timer triggers.

Updating your Service

Now your service is n place and running, but you need to update it. Now you can uninstall the service (see later), rebuild it and re-install it.

Alternatively, you can just stop the service (using the Services app), rebuild it, and restart the service.

Cleaning Up

Open the Developer Command Prompt for Visual Studio as Administrator.

Change the Directory to where the executable is located.

Enter the command

installutil /u "My First Service.exe"

To uninstall the service.

References

https://en.wikipedia.org/wiki/Windows_service

https://en.wikipedia.org/wiki/Daemon_(computing)

https://docs.microsoft.com/en-us/dotnet/framework/windows-services/walkthrough-creating-a-windows-service-application-in-the-component-designer

https://docs.microsoft.com/en-us/visualstudio/deployment/deploying-applications-services-and-components#create-an-installer-package-windows-desktop

https://docs.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicecontroller

https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.eventloginstaller