Tuesday, March 17, 2009

Creating Services with Visual Studio 2008

A Windows service is an aplication that runs in the background. Here's an example on how to make one. It's for Visual Studio 2008, but it would work with Visual Studio 2005 as well.

Create the Service


From Visual Studio Start Page, choose create project... Select Windows Service and give a name of NewService.


First we will do is add a timer to the Service. DO NOT USE THE TIMER IN THE TOOLBOX. The Timer for Windows Forms won't work for Services. We will have to the System.Timers.Timer component by right clicking on the Toolbox, and Choose Items.

Find the one that matches below:

Click OK. This will put the Timer into the Printing section of the Toolbar for some reason.

From The Service1 designer. Click on Timer1, and set the interval to 10000 (10 seconds). Then Double-click to open Code View for Timer1_Elapsed.

Add the Following Code to the Timer1_Elapsed:

Dim MyLog As New EventLog()
' Create a new event log
' Check if the Event Log Exists
If Not MyLog.SourceExists("NewService") Then
MyLog.CreateEventSource("NewService", "NewService_Log") ' Create Log
End If

MyLog.Source = "NewService" ' Write to the Log
MyLog.WriteEntry("NewService_Log", "Service is running", EventLogEntryType.Information)

End Sub

And for OnStart():

Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.

Timer1.Enabled = True

End Sub

Now is normally where you would hit Run to start and debug your App. This is not the case with Windows Services. We have to add a few thing called Installers to make them work correctly.

We will discuss it in the next part of this tutorial.