How to Create and Install Windows Services in .Net

 

To create and Install the Windows Service in .Net is simple. Just follow the following steps.

 

1.   Creating a Windows Service Class (2 Steps)

1.1. Derive a class from “System.ServiceProcess.ServiceBase” and override those methods which you want to response in your service, e.g. “OnStart”, “OnStop”, “OnPause” etc

1.2. Run your services with the method “System.ServiceProcess.ServiceBase.Run”  by passing instances of the derived class.

Note:

For create more than one service, you should set the property “ServiceName” to different values for each instance of derived class. Also you can set additional properties .e.g. “CanPauseAndContinue” etc

 

2.   Creating a Installation Class (4 Steps)

2.1. Derive a class from “System.Configuration.Install.Installer”, with attribute “[RunInstaller(true)]”.

2.2. Create an Instance of “System.ServiceProcess.ServiceProcessInstaller”, and set its property “Account“ to “ServiceAccount.LocalSystem”.

2.3. Create Instances of “System.ServiceProcess.ServiceInstaller”  for each service you want to install and set their property “ServiceName”  to respected services which we created above, also you can set additional properties .e.g. “StartType”, etc

2.4. By using “Installers.AddRange” method, add all instances which created in Installation class.

 

Compiling, Installation and Un-installation

o If all the classes in one file, then just compile it to create Exe.

o Install the service using “InstallUtil <ExeName>”.

o Uninstall the service using “InstallUtil -u <ExeName>”.

 

Run(Stop, Pause, Continue) Service

o You can run(stop, pause, continue) service by using Service Control Manager(SCM).

o You can access SCM by using Services Window(SW).

 

Example Creating a Windows Service in .Net (2 Steps)

 

o In this example we create two services.

o The two services just log the events in the file named by ”strFileName”, when the corresponding event occurs.

o In the derived class constructor, we pass a string to set the property “ServiceName”.

o We name services as “01Service” and “02Service” respectively.

o Also we write a method “private void MessageWriteOnFile(string msgText) “ which logs the entry.

 

//***********************************************************************************//

//**************************** Begin MyWinService.cs **********************************//

//***********************************************************************************//

//Save this file as MyWinService.cs

using System;

using System.ServiceProcess;

using System.IO;

using System.Configuration.Install;

using System.ComponentModel;

 

//Step: 1.1

public class CMyService : System.ServiceProcess.ServiceBase {

      private string strFileName = @"c:\MyService.txt";

                 

      public CMyService (string strServiceName) {

            this.ServiceName = strServiceName;

            this.CanPauseAndContinue = true;

      }

      protected override void OnStart(string[] args) {

            MessageWriteOnFile("Started"); 

      }

      protected override void OnStop() {

            MessageWriteOnFile("Stop" );

      }

      protected override void OnPause() {

            MessageWriteOnFile("Pause" );

      }

      protected override void OnContinue() {

            MessageWriteOnFile("Continue" );

      }

      private void MessageWriteOnFile(string msgText) {

FileStream fs = new FileStream(this.strFileName, FileMode.Append, FileAccess.Write);

            StreamWriter sr = new StreamWriter(fs);

            sr.WriteLine(this.ServiceName + " : " + msgText + " : " + System.DateTime.Now.ToString());

            sr.Flush(); sr.Close(); fs.Close();

      }

 

//Step: 1.2

      public static void Main(string[] args) {

            System.ServiceProcess.ServiceBase.Run

                  ( new System.ServiceProcess.ServiceBase[]

                        {new CMyService("01Service"), new CMyService("02Service") }

                  );

      }

}

 

//Step: 2.1

[RunInstaller(true)]

public class ProjectInstaller : System.Configuration.Install.Installer {

     

      public ProjectInstaller() {

//Step: 2.2

            ServiceProcessInstaller spi = new ServiceProcessInstaller();;

            spi.Account = ServiceAccount.LocalSystem;      

//Step: 2.3

            ServiceInstaller si1 = new ServiceInstaller();

            ServiceInstaller si2 = new ServiceInstaller();

 

            si1.ServiceName = "01Service";

            si1.StartType = ServiceStartMode.Automatic;

 

            si2.ServiceName = "02Service";

            si2.StartType = ServiceStartMode.Automatic;

//Step: 2.4

            this.Installers.AddRange(new Installer[]{ spi, si1, si2 });

      }

}

//***********************************************************************************//

//**************************** End MyWinService.cs **********************************//

//***********************************************************************************//

 

Compiling, Installation and Un-installation

o Compile the file as

csc.exe /t:exe MyWinService.cs

o Install the service as

InstallUtil MyWinService.exe

o To Un-install the service

InstallUtil -u MyWinService.exe

 

Start(Stop, Pause, Continue) Service

o To open Services Window(SW) :

Open Control Panel -> double-click Administrative Tools -> double-click Services

o To open Service Control Manager (SCM):

Double-click “01Service“ service.

Double-click “02Service“ service.

o To Start(Stop, Pause, Continue) :

Click ”Start” Button