BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Programming
.NET 1.1+

Creating a Windows Service

Windows services are background processes that usually have no direct interaction with the user interface. This article explains how to create a windows service with an example that monitors the file system for changes using a FileSystemWatcher object.

Adding the Logging Methods

OnStart creates a new FileSystemWatcher object and connects five of its events to three methods. These methods will use the information from the event arguments passed to them to create event log entries for file changes or to log buffer overflow errors. To define these methods, add the following to the class:

void LogFileSystemChanges(object sender, FileSystemEventArgs e)
{
    string log = string.Format("{0} | {1}", e.FullPath, e.ChangeType);
    LogEvent(log);
}

void LogFileSystemRenaming(object sender, RenamedEventArgs e)
{
    string log = string.Format("{0} | Renamed from {1}", e.FullPath, e.OldName);
    LogEvent(log);
}

void LogBufferError(object sender, ErrorEventArgs e)
{
    LogEvent("Buffer limit exceeded");
}

Adding the OnStop Method

When a service is stopped, the OnStop method is called. We will use this method to disable and dispose of the FileSystemWatcher object, freeing its resources. We will also log a message. To do so, change the OnStop method as follows:

protected override void OnStop()
{
    _watcher.EnableRaisingEvents = false;
    _watcher.Dispose();
    
    LogEvent("Monitoring Stopped");
}

Adding OnPause and OnContinue Methods

Often Windows Services have the ability to be paused and resumed. This is useful if the start-up process for a service is slow or uses many resources. Although this is not true for our example, we will add pause and continue functionality for demonstration purposes.

When a new service is created, it does not support pausing and resuming by default. These options must be configured within the project before compiling. The simplest method to achieve this is to return to the designer for the service and set its properties.

Double-click the Monitor.cs file in the Solution Explorer to view the designer surface. If you cannot see its properties, right-click the designer surface and choose Properties from the menu that appears. You should see a set of properties that determine which actions the service can use. To enable pausing and resuming, set the value of the CanPauseAndContinue property to True.

You should also see a property named, AutoLog. When set to True, this property indicates that standard messages should be logged in response to service events, such as starting and stopping. As we are logging our own messages for these activities, set the AutoLog property value to False. We can also set a friendlier name for the service by changing the ServiceName property to "File Monitor".

We can now add the code to handle pausing and resuming of the service by overriding methods from the ServiceBase class. Add the following to the Monitor class:

protected override void OnPause()
{
    _watcher.EnableRaisingEvents = false;
    LogEvent("Monitoring Paused");
}

protected override void OnContinue()
{
    _watcher.EnableRaisingEvents = true;
    LogEvent("Monitoring Resumed");
}

Other Events

Windows services can react to two additional events, each with its own enabling property and overridable method. The OnShutdown method is called when the computer is being shut down completely. The OnPowerEvent method captures changes to the computer's power status, such as the machine being suspended. For the example service we will not implement these methods.

Adding an Installer

The basic code for the service is now complete. At the moment it will not be possible to install the service so that it can be configured using the Microsoft Management Console. To permit this, we need to add installer components.

Double-click the Monitor.cs file to redisplay the designer. Right-click the grey background and select "Add Installer..." from the pop-up menu. This will add two components to the designer; a ServiceInstaller and a ServiceProcessInstaller.

The two components allow configuration of the service. We will start by changing the service process installer. Click the component named "serviceProcessInstaller1" to select it and view its properties. The important property is Account. This allows you to define the default account used by the service when it is running. This can be a user account or a system account. If a user account is selected, a password will be required during installation. In this case we want the service to run with limited privileges so select "LocalService" from the drop-down list.

The service installer component can be used to set general information relating to the service. This information is registered on installation and appears in the Services window of the MMC.

Select the serviceInstaller1 component. Change the DisplayName property to "File Monitor Demonstration Service".

10 September 2008