Windows service

A service is a small program that usually starts when the Windows operating system loads. A service will run in the background while Windows is running.
Previously called an NT service, the core function of a Windows aervice is to run an application in the background. There are few things that make them different from a Windows application. A Windows service starts much before any user logs in to the system . A Windows service can also be setup in such a way that it requires a user to start it manually – the ultimate customization!

Why are Windows Services needed ?

a. Running services in background like antivirus
b. Disk or memory access monitoring
c. To implement security systems for an application
d. Log error messages in the background for an application
e. Enable a user to create long-running executable applications that run in their own Windows sessions.
f. These can be automatically started when the computer boots and can be paused and restarted.
g. They are ideal for use on a server.


Let's see How to create

Step 1. Create Structure of the Service
To create a new Window Service, pick Windows Service option from your Visual C# Projects, give your service a name, and click OK.

Free Image Hosting
The result look like this. The Wizard adds WebService1.cs class to your project.
Free Image Hosting
Set your TimeService to your own name so it would be easier to recognize your service during testing OR you can set this property programmatically using this line this.ServiceName = " TimeService ";

The default code of WebService1.cs added by the Wizard looks like here
namespace TimeService
{
using System;
using System.Collections;
using System.Core;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Web.Services;
using System.Diagnostics;
using System.ServiceProcess;
public class WinService1 : System.ServiceProcess.ServiceBase
{
///
/// Required designer variable.
///

private System.ComponentModel.Container components;
public WinService1()
{
// This call is required by the WinForms 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 WinService1(), new
ySecondUserService()};
//
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WinService1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "WinService1";
}
///
/// Set things in motion so your service can do its work.
///

protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
}
///
/// Stop this service.
///

protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
}
}
Step 2. Add functionality to your service
Right-click on the design surface and select Add Installer (see Figure 3).

Figure 3. Adding the Installer
Free Image Hosting Two installers will be added: ServiceProcessInstaller1 and ServiceInstaller1 (see Figure 4). These two controls are used by the InstallUtil.exe utility when installing the Windows Service (more on this in the next section).

Figure 4. Adding the two Installer controls
Free Image Hosting Right-click on ServiceProcessInstaller1 and select Properties. Set the Account property to LocalSystem.
Right-click on ServiceInstaller1 and select Properties. Set the StartType to Manual.

Step 3. Add functionality to your service
As you saw WebService1.cs, there are two overridden functions OnStart and OnStop. The OnStart function executes when you start your service and the OnStop function gets execute when you stop a service. I write some text to a text file when you start and stop the service.
protected override void OnStart(string[] args)
{
FileStream fs = new FileStream(@"c:\temp\mcWindowsService.txt" ,
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(" mcWindowsService: Service Started \n");
m_streamWriter.Flush();
m_streamWriter.Close();
}
///
/// Stop this service.
///

protected override void OnStop()
{
FileStream fs = new FileStream(@"c:\temp\mcWindowsService.txt" ,
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(" mcWindowsService: Service Stopped \n"); m_streamWriter.Flush();
m_streamWriter.Close();
}

Step 3: Install and Run the Service


Build of this application makes one exe, mcWinService.exe. You need to call installutil to
egister this service from command line.
installutil C:\TimeService \bin\Debug\TimeService .exe
You use /u option to uninstall the service.
installutil /u C:\TimeService \bin\Debug\TimeService .exe
Run the application

Step 4: Start and Stop the Service
You need to go to the Computer Management to Start to start and stop the service. You can use Manage menu item by right clicking on My Computer.

Under Services and Applications, you will see the service mcWinService. Start and Stop menu item starts and stops the service.

Free Image Hosting by FreeImageHosting.net Step 5: Test the Service
Go to your temp directory and see if text file is there with contents or not.
That's it.