Wednesday, June 28, 2006

Creating windows Services using C#

After the introduction of .NET and C#, writing Windows services becomes an easy job. We have to keep something in mind before starting to write windows service.

Step 1
Create a new project in .NET by selecting windows service. Give relevant name to the service.


Microsoft .NET will generate required code for with these methods and the class will be inherited from “
System.ServiceProcess.ServiceBase” class. ServiceProcess is the base class for windows services. The windows services consist of the following method.

  1. OnStart
  2. OnStop
Step 2
After creating the project, we can write the relevant code on onStart method. There are different types of methodology to achieve the goal. Here I preferred threading, which we can handle easily. Inside the start thread you can have your functionality. We have to install the service for registering the service in windows machine. For this we have to inherit from installer base class. There will be two classes ie service installer and process installer. The two class should be inherited to achieve the relavant functionality.

Step 3 Configuration of the service comes the important part in window service development. Same name should be given inside the service installer class. This will recognise the service installer to install which service during installation. This can be set in property window of service installer control.

“Picture can represent things better than thousand words”

Like that simple code can explain things better. So I will give an example, which is written in C#.



using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Xml;
using System.Data.SqlClient;
using System.Web.Mail;
using System.Threading;


namespace NotificationEngine{
 public class EmailService : System.ServiceProcess.ServiceBase 
 { 
 private bool bStopValue; 
 private int nSleepTime;


public EmailService() { 
 bStopValue = false; 
 nSleepTime = 5000; //default time is 5000 milliseconds. 

// This call is required by the Windows.Forms Component Designer. 
 InitializeComponent();


// TODO: Add any initialization after the InitComponent call 
}


// The main entry point for the process 
 static void Main() 
 { 
 System.ServiceProcess.ServiceBase[] ServicesToRun; 
// More than one user Service may run within the same process. To add 
// another service to this process, change the following line to 
// create a second service object. For example, 
//// 
 ServicesToRun = new System.ServiceProcess.ServiceBase[] 
{
new Service1(), 
new MySecondUserService()
}; 
// ServicesToRun = new System.ServiceProcess.ServiceBase[] 

new EmailService() 
};


System.ServiceProcess.ServiceBase.Run(ServicesToRun); 
}


/// <summary> 
/// Required method for Designer support - do not modify 
 /// the contents of this method with the code editor. 
 /// </summary> 
 private void InitializeComponent() 
 { 
 this.ServiceName = "WindowsService";
}


/// <summary> 
/// Clean up any resources being used. 
/// </summary> 
protected override void Dispose( bool disposing ) 
{ 
if( disposing ) 
{
// if (components != null)
// {
// components.Dispose();
// } 
} 


base.Dispose( disposing ); 
}


/// <summary> 
/// Set things in motion so your service can do its work. 
/// </summary> 
protected override void OnStart(string[] args) 
 { 
 // TODO: Add code here to start your service. 
 bStopValue = false; 
Thread t = new Thread(new ThreadStart(ThreadFun)); 
t.Start(); 
}


private void ThreadFun() 
{ 
 if(AppReader.GetValue("TimerInterval") != null) 
 nSleepTime = int.Parse(AppReader.GetValue("TimerInterval")); 

while(!bStopValue) 
{ 
 bool bRetval = HandleNotification(); 
 System.Threading.Thread.Sleep(nSleepTime); 
 } 
}

/// <summary> 
 /// Stop this service. 
 /// </summary> 
 protected override void OnStop() { 
 // TODO: Add code here to perform any tear-down necessary to stop your service. 
 //For stopping the thread. 
 bStopValue = true; 
 }


private bool HandleNotification() 
 {
// TODO: The code for the required functionality 
 } 
}
}

Ok great, we finished the coding part. Now question arises how to install the process in windows machine!!!!! 

Lets do that.

Install Windows Service in Windows Machine

After writing the code, you will get an executable file which we have to install in the machine. The command is
InstallUtil /LogToConsole=true SaokEmailService.exe

The /LogToConsole is optional. If everything goes fine, you can see the new service will be installed. Click “Services” and you can see the newly installed service in the list. We can start and stop the service using the command net start <service name> and net stop <service name>. Even we can configure to start it automatically when windows start.

Debugging windows service

One of the toughest problems in programming is debugging windows service; But Microsoft Visual studio (any version) made programmers life very simple. Start the windows service. Open the windows service project using visual studio. In the project, select Debug(process. You can see all the process running on the local machine. Select the windows process and click attach. Before doing the above mentioned things, just remember to put a break point in the code. That’s all, now you can debug the program without much effort.





Happy programming!!!