AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1316&pId=-1
Working with Windows Service Using Visual Studio 2005
page
by Abhishek Kumar Singh
Feedback
Average Rating: 
Views (Total / Last 10 Days): 52707/ 130

Introduction

·         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.

·         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

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

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

 

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

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

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

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

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

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

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

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

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

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

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.

Downloads
Questions with Answers based on Window Services

Read these questions and think of possible answers. Compare your thoughts with the answers given in the "Answers" section.

Questions

1.     Can we debug windows service without installing it on the computer?

2.     Can we debug the OnStart method of windows service?

3.     Is there any alternative for windows service application?

4.     How to start, pause, continue and stop the service using command line?

5.     How to set permissions on windows service?

6.     Can we share the process among multiple windows services?

7.     Is there way to create installer other than by using Setup project template of Visual Studio?

Answers

1.  No, we cannot debug windows service without installing and starting it. However, we can debug the functional part by creating separate assemblies using console or windows application and then use the debugged assembly in windows service project. This is not possible in all cases, especially when we need to debug run time issues.

2.  As the service must be started to attach its process to debugger, we need the service to be started in advance. Hence, normally we cannot debug the OnStart method of service.

However, we can make an extra dummy windows service which should internally start the actual service. By attaching debugger to the process of dummy service we can step into the OnStart method of actual service to debug it.

3. Probably, we can use Windows Operating System’s Schedule Tasks as an alternative of windows service. We can implement required functionalities in a valid program and then configure it with Schedule Tasks.

4.  To start, pause, continue and stop the service through command line use net start ServiceName, net pause ServiceName, net continue ServiceName and net stop ServiceName, respectively.

5.  Permissions for windows service depend upon the account type (Local Service/Network Service/Local System/User) set for the service. If service is set to use particular user account then permissions set for specified user becomes the permission for the service.

6.  Yes, windows services could be implemented like other exe applications if they do not need GUI. One major difference is that windows service is managed by SCM (Service Control Manager) which provides options to implement many settings and events. Internally the Main method of the service application issues the Run command and then Run method loads the service in SCM.

7.  We can create installer using command-line utility Installutil.exe by passing the path of service's executables.

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.

If you have better answers or any suggestions, please write your comments in the feedback. It will help me as well as all viewers.

Abhishek Kumar Singh

Mindfire Solutions

 



©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-05-18 10:00:52 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search