Click here to Skip to main content
15,885,366 members
Articles / Programming Languages / C#

Working with Windows Service Using VS 2005

Rate me:
Please Sign up or sign in to vote.
2.25/5 (4 votes)
16 Jun 2009CPOL5 min read 27.6K   12   5
Written in C# for beginners who want to learn

Abstract

In this article, I will describe how to implement, setup, install Windows Services with the help of snapshots.

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 an 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 shuts down 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: C# >> Windows
  • Visual Studio installed templates: Windows Service
  • Name: MyService

Specify the location for the solution and let the solution name be MyService. 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.cs class file in the project MyService; rename Service1.cs into MyService.cs. Switch to the code view of MyService.cs and open the OnStart function of the MyService class. Add the following codes in the OnStart function:

C#
protected override void OnStart(string[] args) 
{
    // TODO: Add code here to start your service. 
    const Int32 iTimer_Interval = 60000;
    Timer oTimer; 
    System.IO.File.AppendAllText("C:\\MyLog.txt", "MyService has been started at " +
        DateTime.Now.ToShortTimeString()); 
    System.Threading.TimerCallback tDelegate = EventAction; 
    oTimer = new System.Threading.Timer(tDelegate, this, 0, iTimer_Interval);
}

Next, implement EventAction procedure in the MyService 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 MyLog.txt in C drive. Add the following code in the MyService class for EventAction procedure:

C#
public void EventAction(object sender) 
{ 
    System.IO.File.AppendAllText("C:\\MyLog.txt", "MyService fires EventAction at " +
        DateTime.Now.ToShortTimeString());
}

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 MyService.cs file in design view. Right click on the form and choose Add Installer in the pop up menu:

This will add a new file ProjectInstaller.cs 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.

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

Build the MyService 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 "MyService," 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: MyServiceSetup
  • Click OK to create the project. The setup project MyServiceSetup will be added in the solution and IDE will show you the file system window for the setup.

Right click on the project MyServiceSetup 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."

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

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.

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

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

Installing Windows Service using IDE

You can use setup file MyServiceSetup.msi to install/uninstall the service MyService 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 MyService using Visual Studio 2005 IDE, right click on the MyServiceSetup project in the solution explorer and choose Install in the pop-up menu.

It will open the window 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 MyService in the list. Right click on it and choose Start to start the service.

Now the service MyWinService 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:\MyLog.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 MyLog.txt at each interval of 60 seconds. If it is so, then we are sure that service is performing as per the implementation.

History

  • 16th June, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Divyalok Suman has done B.E in Computer Science from bangalore ,Karnataka, India . Past 6 years he is working on web-based and windows based solutions in Asp.net MVC 1.0/2.0/3.0/4.0, ASP.NET 2.0/3.5/4.0, C# 2.0/3.5/4.0, AJAX, Web Services, MS SQL Server 2005/2008,Win Forms, Window services. He is also an MCP and MCTS . He has good knowledge of Object Oriented Programming, 3-Tier Architecture and Designing.

Comments and Discussions

 
Questionerror code 2869 Pin
arti881-Apr-13 18:27
arti881-Apr-13 18:27 
GeneralProblems with TimeCallback Pin
robinson oliva16-Jun-09 17:35
robinson oliva16-Jun-09 17:35 
AnswerRe: Problems with TimeCallback Pin
divyaloksuman17-Jun-09 7:53
divyaloksuman17-Jun-09 7:53 
GeneralBeginners beware! Pin
PIEBALDconsult16-Jun-09 5:34
mvePIEBALDconsult16-Jun-09 5:34 
AnswerRe: Beginners beware! Pin
divyaloksuman17-Jun-09 7:41
divyaloksuman17-Jun-09 7:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.