Windows Services in .NET

If you want to write application that constantly monitors some files, creates a log file, or anything else which runs constantly in the background while the machine is busy doing something else, the best way to this used to be to run a windows application continuously or at a regular interval with the use of Windows scheduler. There was one big disadvantage to this — someone had to log into the system to start the application. This sort of activity has been long put behind us thanks to Windows services.

A Windows Service is a process that runs unattended and without a user interface. Windows Services are available only in Windows NT, Windows 2000, Windows XP, and Windows Server 2003. Windows Services run in their own process space and can be configured to start up during the OS boot process. Other desktop applications can interact with them, if you configure them that way.

Let’s start creating a sample Windows Service in VB.NET
=======================================================

Start by creating a Windows Service project. Select File | New Project, then select the Windows Service template and give its name as MyService.Some versions of Visual Studio .NET (VS.NET) provide a Windows Service application template that creates the skeleton of your application. Note that Visual Basic Standard Edition and Visual C# Standard Edition do not include the Windows Service application template, so you’ll have to start from scratch.
Now VS.NET creates a new project with a single VB.NET file called MyService.vb. Double-click on this file to bring up a designer view

You can set several properties for the service project. For example, you can tell Windows that this service will respond to shutdown, pause, and continue, and other events. You can also tell Windows to log service events such as stop and start in the Windows Event Log by setting the AutoLog property to True.

Now take a look at the code for the service by clicking on the "click here to switch to code view" link. The first thing you’ll notice is that the Service1 class inherits from the System.ServiceProcess.ServiceBase class. The .NET Framework’s System.ServiceProcess.ServiceBase class encapsulates essentially all of the "plumbing" required to create and control service applications. By basing your application on this class, most of the difficult work is already done for you.

This class contains the following subset of events that interact with the Windows Service Control Manager (SCM):

* OnContinue: Fires when a continue command is sent to the service by the SCM. It specifies actions to take when a service resumes normal functioning after being paused.
* OnPause: Fires when a pause command is sent to the service by the SCM. It specifies actions to take when a service pauses.
* OnPowerEvent: Fires when the computer’s power status has changed. This applies to laptop computers when they go into suspended mode, which isn’t the same as a system shutdown.
* OnShutdown: Fires when the system is shutting down. It specifies what should happen immediately prior to the system shutting down.
* OnStart: Fires when a start command is sent to the service by the SCM or when the operating system starts (for a service that starts automatically). It specifies actions to take when the service starts. An array of String objects is the event’s lone parameter.
* OnStop: Fires when a stop command is sent to the service by the SCM. It specifies actions to take when a service stops running.

The point where most of the developers are cofused is Starting a service and running a service. Note that these two are entirely different. Running a service makes it available but does not start it. Once available, a service can be started or stopped either automatically, manually, or programmatically. Depending on the setting of the ServiceBase object’s CanPauseAndContinue property, a service may also be able to pause and continue.

imports System.Diagnostics
Imports System.ServiceProcess
Public Class MyService
Inherits System.ServiceProcess.ServiceBase
Private log As EventLog
Public Sub New()
MyBase.New()
InitializeComponent()
End Sub
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If (disposing) Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
log.WriteEntry("Service dispose", EventLogEntryType.Information)
log.Close()
MyBase.Dispose(disposing)
End Sub
<MTAThread()> _
Shared Sub Main()
Dim ServicesToRun() As System.ServiceProcess.ServiceBase
ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1}
System.ServiceProcess.ServiceBase.Run(ServicesToRun)
End Sub
Private components As System.ComponentModel.IContainer
Private Sub InitializeComponent()
components = New System.ComponentModel.Container
Me.ServiceName = "Service1"
End Sub
Protected Overrides Sub OnStart(ByVal args() As String)
log = New EventLog("Builder.com")
log.WriteEntry("Service Starting", EventLogEntryType.Information)
End Sub
Protected Overrides Sub OnStop()
log.WriteEntry("Service Stopping", EventLogEntryType.Information)
End Sub
End Class

Service Installation
====================
To install a service you must compile the service project into an exe file, and then run the utility program InstallUtil.exe (installed with the .NET Framework). At a command prompt enter the command:

   installutil servicename.exe
 

You must provide the complete path to the service’s exe file. The InstallUtil application installs the specified service. will be installed. After installing the new service, you can find it in the Services window of the Computer Management applet. (You can use the InstallUtil program to uninstall a service as well.)

Windows services are an often overlooked type of application. They are relatively specialized, but for certain type of tasks, usually in the administrative category, they fit the bill perfectly. The .NET Framework provides classes designed specifically for creating and controlling Windows service applications. Given that the required programming is relatively simple, you should take advantage of Windows services

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s