Monday, July 13, 2009

Steps to Creating Windows service with timers.

Steps to Creating Windows service with timers.
we can use Windows service as the way to run task that run Constantly and doe not need any user interface. Here are the Steps to create Windows Service.

1).Open Visual Studio

2).File->New Project->Windows Service

3).In these Step

a).add code to run at start of service on OnStart Method
b).add code to run at Stop of service on OnStop Method

To run any task constantly we have to provide timer.Which Executes that task on
some intarval.

Here is the code to Implement Windows Service with Timer.

Replace Code in Service1.cs With Code Below

using System;
using System.ServiceProcess;
using System.Threading;
using System.IO;
namespace WinService
{

public partial class Service1 : ServiceBase

{

Timer t;
FileStream fs;

public Service1()
{
InitializeComponent();
}
private void WriteDate(object state)
{
fs = new FileStream(@"C:\MyService.txt", FileMode.Append, FileAccess.Write);

byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(DateTime.Now.ToString() +
Environment.NewLine);
fs.Write(b, 0, b.Length); fs.Close();

}
protected override void OnStart(string[] args)
{
TimerCallback tc = new TimerCallback(WriteDate);
object state = new object(); t = new Timer(tc, state, 0, 5000);

fs = new FileStream(@"C:\MyService.txt", FileMode.Create, FileAccess.Write);
fs.Close();
}

protected override void OnStop()
{
t.Change(Timeout.Infinite, 1000); fs = null;
}

}

}

4).In Service1[Design] Mode ->Properties Set ServiceName=MyService
5).In Service1[Design] Mode ->Right Click ->AddInstaller
This Will Add.

a).Service Installer.

b).ServiceProcessInstaller.

This both are User to Install service on system and Add that service in Service
Control Manager.

6).Right Click on ServiceInstaller->Properties then.

Set DisplayName=MyServiceTest
Description=This is a test
StartupType=Automatic

7).Right Click on ServiceProcessInstaller->Properties then.

Set Account=LocalSystem. Your Service
will run Under Previlege of these account.

8).Now Build Your Service and resolve any error. after completing build
Successfully.it is time to install the service.

there will be Myservice.exe file in bin
directory of your project.
9).Open VisualStudio Command Prompt (Start->VisualStudio 200->VisialStudio
Tools->Command Prompt).

10).Type Comand:InstallUtil.exe -i path to Myservice.exe


This Will Install Service on your System. this will also
add Service to service control manager.

11).Goto Service Control Manager.

12).Start the service.

13).Monitor C:\MyService.txt to check
whether times work or not?

This is all to Use Windows Service.

Thanks.