Click here to Skip to main content
Licence CPOL
First Posted 16 Feb 2004
Views 147,650
Bookmarked 41 times

Developing a Windows SERVICE Application using .NET Framework with C#.

By | 16 Feb 2004 | Article
An Introduction to Windows SERVICE Application using .NET Framework

Introduction

This article will take you through the step-by-step procedure to develop a SERVICE to run windows based Operating System. Developing a SERVICE based application in .NET Framework is pretty straightforward which it does by confining to very few classes. Before we could move on to the development part of the application a bit of theory on Service application should be of use.

          Windows Services is previously called as NT Service. The Idea of creating a windows service application is two fold one is to create a long running application and the other is service applications are the application that run directly in the windows session itself (This can be verified by accessing the current or home directory of the service application which default to .winnt\system32). One more advantage of the Windows Service Application, which makes it more useful, compared to other application is that, Service application can be made to run in the security context of a specific user account.

There are basically two types of Services that can be created in .NET Framework. Services that are only service in a process are assigned the type Win32OwnProcess.Services that share a process with another service are assigned the type Win32ShareProcess.The type of the service can be queried. There are other types of services which are occasionally used they are mostly for hardware,Kernel,FileSystem.

          Lifecycle of the Service Application. In a typical application the Main method is the entry point and for what ever instantiation has to happen will happen here matters. In Case of Service, the Main method remains to the entry module by the actual functionality of the service application start only in the Main method by  triggering a overridden method called OnStart() which actually starts the SERVICE. Prior to OnStart() method another significant variance is compared to the other application is service should be  installed onto the system on which it will run. This process executes the installers for the service project and loads the service into the Services Control Manager for that computer. The Services Control Manager is the central utility provided by Windows to administer services following which the main and Onstart is followed to fall in line.

            A Service application can be in any one of the states listed they are viz., Running, Paused or Stopped. The Services also has the capability to queue the commands and also remain in those states. Such statuses can be queried, some of the significant states are like Continue Pending, which means  continue command is in queue and yet to get executed.Similarily StartPending,StopPending,PausePending.

        Window SERVICE application development can be divided to two phases. One is the development of Service functionality and the last phases is about the development. The 3 Main classes involved in Service development are

  •        System.ServiceProcess.ServiceBase 

  •        System.ServiceProcess.ServiceProcessInstaller

  •        ServiceController

System.ServiceProcess.ServiceBase  ,is the class in which we override the methods for implementation ,Some the method which gives us the behaviour of this are as follows.

Method Override to
OnStart Indicate what actions should be taken when your service starts running. You must write code in this procedure for your service to perform useful work.
OnPause Indicate what should happen when your service is paused.
OnStop Indicate what should happen when your service stops running.
OnContinue Indicate what should happen when your service resumes normal functioning after being paused.
OnShutDown Indicate what should happen just prior to your system shutting down, if your service is running at that time.
OnCustomCommand Indicate what should happen when your service receives a custom command. For more information on custom commands, see MSDN online.
OnPowerEvent Indicate how the service should respond when a power management event is received, such as a low battery or suspended operation.
Run  The main entry point for the service, u sally in the Main method
[Src :MSDN]

Some Of the properties of Interest are as follows

ServiceName 

CanStop

CanPauseAndContinue

AutoLog 

 

Structure Of a Service Program

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Diagnostics;

using System.ServiceProcess;

using System.Configuration.Install;

namespace WindowsService

{

/// <summary>

/// This is the class for my Service

/// </summary>

public class MyService : System.ServiceProcess.ServiceBase

{

public MyService()

{

InitializeComponents();

// TODO: Add any further initialization code

}

private void InitializeComponents()

{

this.ServiceName = "MyService";

}

 

/// <summary>

/// This method starts the service.

/// </summary>

public static void Main()

{

System.ServiceProcess.ServiceBase.Run(new System.ServiceProcess.ServiceBase[] {

new MyService() // To run more than one service you have to add them here

});

}

/// <summary>

/// Clean up any resources being used.

/// </summary>

protected override void Dispose(bool disposing)

{

// TODO: Add cleanup code here (if required)

base.Dispose(disposing);

}

/// <summary>

/// Start this service.

/// </summary>

protected override void OnStart(string[] args)

{

// TODO: Add start code here (if required)

// to start your service.

}

 

/// <summary>

/// Stop this service.

/// </summary>

protected override void OnStop()

{

// TODO: Add tear-down code here (if required)

// to stop your service.

}

}

}

[RunInstaller(true)]

public class ProjectInstaller : Installer

{

public ProjectInstaller()

{

ServiceProcessInstaller spi = new ServiceProcessInstaller();

spi.Account = ServiceAccount.LocalSystem;

 

ServiceInstaller si = new ServiceInstaller();

si.ServiceName = "Hello Service Template";

si.StartType = ServiceStartMode.Automatic;

Installers.AddRange(new Installer[] {spi, si});

}

}

[Note: This Code is generated using Sharp Develop Version 0.98,Build 1.1]

 

Service Installation Procedure:

To install your service manually

  1. Access the directory in which your project's compiled executable file is located.
  2. Run InstallUtil.exe from the command line with your project's output as a parameter. Enter the following code on the command line:
    <FONT face=Verdana size=2><SNIPPET>
    :- installutil myservices.exe</SNIPPET>
    </FONT>

To uninstall your service manually

  • Run InstallUtil.exe from the command line with your project's output as a parameter. Enter the following code on the command line:
    <FONT face=Verdana size=2><SNIPPET>
    :- installutil /u myservices.exe</FONT>
    <FONT face=Verdana size=2>[Note: If you are using any messagebox,After Installing the service navigate to Log On Tab under properties  and Select the </FONT>
    <FONT face=Verdana size=2>"Allow service to interact with Desktop"].</FONT>

 

 

 

 

 

License

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

About the Author

G.Venkatasubramaniam

Web Developer

Malaysia Malaysia

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 1 PinmemberVVV52528:09 27 Feb '12  
GeneralMy vote of 3 PinmemberEason_Wu17:39 22 Nov '11  
GeneralMy vote of 1 PinmemberAnton Lesnichenko22:06 15 Apr '10  
Generalmake protected service Pinmemberebi_sd2:15 18 Nov '09  
GeneralSuggestion for improvment Pinmembervincentli24:36 7 Jul '09  
Questiondetect the computer shut down PinmemberBMWABCD19:07 2 Jul '07  
GeneralNeeds more stuff Pinmemberspannring18:30 22 Jan '07  

The first few paragraphs makes a fine outline
for an article on Windows Services, but you
need to flesh it out some more.
 

GeneralNice Article PinmemberSathishNellai11:18 27 Sep '06  
GeneralService Description PinmemberKomil5:14 18 Aug '05  
Generalrediffmail.ccurrent user name Pinsusssudip1gmail20:02 2 Jun '05  
GeneralNot new PinmemberJuicy23:52 16 Feb '04  

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

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120529.1 | Last Updated 17 Feb 2004
Article Copyright 2004 by G.Venkatasubramaniam
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid