Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Working with Windows Service Using Visual Studio 2005

Posted by Ravi Varma Thumati on October 6, 2009

In this article we will discuss how to implement, setup, install, and debug Windows Services with the help of snap-shots.

Article Contents:

  • Introduction
  • Building a Windows Service
  • Building a Setup for the Windows Service
  • Installing Windows Service using IDE
  • Starting the installed Windows Service
  • Debugging the running Windows Service (process)
  • Conclusion

Introduction

  1. A windows service is a program which runs continuously in the background of an Operating System. It was formerly known as NT services. Window service internally uses the Service Control Manager (SCM) of the operating system. A service must be installed in a SCM database before it can be launched. SCM controls the entire lifetime of each installed service.
  2.  Implementing windows services has become the choice of the current era of business as it requires minimum human intervention after deployment and gives long running functionality. We also say window service application works as an Engine; once started it will keep running until the machine shutdowns or gets some abnormal error.

Building a Windows Service

Create a Windows Service project in Visual Studio 2005 as given below:

File >> New >> Project

It will open the New Project window. Choose the following settings:

  • Project types: Visual Basic >> Windows
  • Visual Studio installed templates: Windows Service
  • Name: AuthorLogService

Specify the location for the solution and let the solution name be AuthorLogService. Select the check box for “create directory for solution.”

Figure 1 – Creating new windows service project using Visual Studio 2005 IDE

ws1

Click OK to create the solution and project. The IDE will automatically add a Service1.vb class file in the project AuthorLogService; rename Service1.vb into AuthorLog.vb. Switch to the code view of AuthorLog.vb and open the OnStart function of the AuthorLog class. Add the following codes in the OnStart function.

Listing 1 – Function OnStart in class AuthorLog.vb project

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.
        Const iTIME_INTERVAL As Integer = 60000      ' 60 seconds.
        Dim oTimer As System.Threading.Timer
        System.IO.File.AppendAllText("C:\AuthorLog.txt",
            "AuthorLogService has been started at " & Now.ToString())
 
        Dim tDelegate As Threading.TimerCallback = AddressOf EventAction
        oTimer = New System.Threading.Timer(tDelegate, Me, 0, iTIME_INTERVAL)
 
    End Sub

Next, implement EventAction procedure in the AuthorLog class. Note that the EventAction is the procedure which is to be fired/called at each timer interval of 60 seconds raised by Timer implemented in OnStart function above. For a simple example, we will implement to write the current time in a text file AuthorLog.txt in C drive. Add the following code in the AuthorLog class for EventAction procedure.

Listing 2 – Implementation of sample procedure EventAction in class AuthorLog.vb

Public Sub EventAction(ByVal sender As Object)
        System.IO.File.AppendAllText("C:\AuthorLog.txt",
            "AuthorLogService fires EventAction at " & Now.ToString())
    End Sub

Now we need to add installer components in the service project to set service setup properties. Installer components provided in Visual Studio automatically create Operating System environment objects like registry keys, Windows services control manager event handlers, executables for installation utilities when installing a service application, SCM initialization, etc.

To add installer in the windows service

Open the AuthorLog.vb file in design view. Right click on the form and choose Add Installer in the pop up menu.

Figure 2 – Add Installer in windows service project

ws2

This will add a new file ProjectInstaller.vb with two controls, ServiceProcessInstaller1 and ServiceInstaller1, in the project. Select ServiceProcessInstaller1 and press F4 to open its properties window. Set the Account type to LocalSystem.

Figure 3 – Setting Account type for the windows service

ws3

Now select the ServiceInstaller1 control and press F4 to go to its properties window. Set the ServiceName as “AuthorLogService” and StartType as “Automatic.” Setting StartType to automatic will automatically start the service (after installation) whenever the computer restarts.

Figure 4 – Setting service name and start type using service installer component

ws4

Build the AuthorLogService project. If the build is successful then we are ready with the service. Now to install this service in the system we need an installer/setup file. So we will create and add a setup project for the service in the current solution through which we can install/uninstall the service.

Building a Setup for the Windows Service

In the solution “AuthorLogService,” follow the steps given below to create a setup project.

File >> Add >> New Project

It will open the Add New Project window. Choose the following settings:

  • Project types: Other Project Types >> Setup and Deployment
  • Visual Studio Installed Templates: Setup Project
  • Project Name: AuthorLogServiceSetup
  • Click OK to create the project. The setup project AuthorLogServiceSetup will be added in the solution and IDE will show you the file system window for the setup.

Figure 5 – Setup project structure in visual studio 2005

ws5

Right click on the project AuthorLogServiceSetup and choose View >> Custom Actions from the pop up menu. It will open the Custom Actions settings window for the setup deployment. Right click on the Custom Actions Node and choose “Add Custom Actions.”

Figure 6 – Show custom actions setting in setup project

ws6

After clicking on “Add Custom Actions” a window will appear to select the item for the deployment.

Figure 7 – Choosing application folder to add files for setup

ws7

Double click on the “Application Folder.” The “Add Output” button will be enabled now. Click on it to open the “Add Project Output Group” window.

Figure 8 – Setting primary output of windows service project for setup

 ws8

In this window choose the “Primary Output” under AuthorLogService and Click the “OK” button. You will see that a new entry Primary output from AuthorLogService (Active) in the parent “Select Item in Project” window. Click OK to complete the custom settings.

Now Build the AuthorLogServiceSetup project. If the build is successful then you can find AuthorLogServiceSetup.msi file in …\AuthorLogServiceSetup\Debug folder.

Installing Windows Service using IDE

You can use setup file AuthorLogServiceSetup.msi to install/uninstall the service AuthorLogService on any computer. Also you can use Visual Studio 2005 IDE to install the service using setup project. I prefer to use IDE to install/uninstall services as it is convenient during implementation and debugging.

To install AuthorLogService using Visual Studio 2005 IDE, right click on the AuthorLogServiceSetup project in the solution explorer and choose Install in the pop-up menu.

Figure 9 – Install and uninstall options through IDE in setup project

ws9

It will open the windows installer wizard. Click Next button and specify the installation folder location in the folder location text box. Click Next button. It will show you the confirmation window. Click Next to start the installation. It will show you the installing status and then completion message window. Now the service should be installed in the machine. Let us find and start the service as given in the next section.

Starting the installed Windows Service

Reach the installed Services following any of the methods given below.

Open Service Control Manager: Control Panel >> Administrative Tools >> Services.

OR right click on My Computer, choose Manage. It will open the Computer Management window. In the tree view open Services and Applications and click Services.

OR In the Visual Studio 2005 IDE, open Server Explorer by pressing CTRL+ALT+S and choose node Services under the machine name of Servers tag.

Find the AuthorLogService in the list. Right click on it and choose Start to start the service.

Figure 10 – Starting the service from Service Control Manager

ws10

Now the service AuthorLogService has been started and its status should be changed to “Started” in the list. Remember that this sample service is implemented to write log time in a text file “C:\AuthorLog.txt.” For the confirmation of the accuracy of service you can verify the existence of file. The service should write the current time in the file AuthorLog.txt at each interval of 60 seconds. If it is so then we are sure that service is performing as per the implementation.

However, in the real world of computation we use service to process very complex logic and operations where we cannot determine the accuracy of service functionality just by verifying the output or log file of the service. The service should be diagnosed properly to have minimum processing overhead. It needs proper debugging to prevent any infinite looping or crashes. Improper implementation of service may cause unexpected halt of service, unnecessary memory consumption, overhead on machine, etc.

Hence, to get the optimal performance from the service, we need to step into the code of the service and debug the process line by line. In the next section we will see how to step into the windows service code for debugging with the help of sample AuthorLogService project source. Note that the AuthorLogService service is installed and running.

Note: Windows Service must be installed and started to perform debugging.

Debugging the running Windows Service (process)

Set breakpoint in the service application code

In the solution explorer choose the project AuthorLogService and open AuthorLog.vb in code view. Go to the definition of EvenAction procedure. Remember that we had implemented EventAction procedure in the service such that it will be called by the timer periodically at each 60 seconds. Therefore, we will put a breakpoint in this procedure.

Figure 11 – Setting breakpoint in the code

ws11

Attach debugger to the running service process

Go to the Debug menu and choose “Attach to Process.” It will show the list of all available processes for different types of codes. We need to find the service process under managed code. Enable the option for “Show processes from all users.” Now the “AuthorLogService.exe” should be available in process list as shown below.

Figure 12 – Attaching the debugger on windows service process

ws12

Click Attach button to attach the debugger for the service and to start the project AuthorLogService debugging.

As we have set the timer period to 60 second, the breakpoint set over EventAction procedure must hit within 60 seconds. When the breakpoint is hit then you can use F9 or F10 to debug the code line by line.

Figure 13

ws13

Remember that as per the implementation in this sample, each timer call generates a new thread for EventAction. Each thread will wait for the previous thread to finish by making a FIFO (first in first out) queue. However, we can implement thread management as desired.

Conclusion

In this example the procedure EventAction contains few lines of code to execute. But if the service is to be implemented for complex operations (e.g. to read/monitor the incoming mails on a network port, to transfer the data continuously from one end to other end by implementing remote programming in services etc.), then we must debug the service properly to manage the threads, to fix run time errors and for proper use of resources, etc. A bad thread management or programming in windows service may cause abnormal stop of service, hang of service process, operating system overhead, etc. Hence, we need to debug the service implementations minutely before releasing the service in production.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

 
%d bloggers like this: