Sunday, May 27, 2007

Creating a .NET Windows Service using .NET3.0


1. Definition of a windows service?

Windows service is any application which starts when the computer boots up irrespective of the user. In UNIX it is called a demon process. Once a windows service is installed it can be modified using the Administrative Tool of Control Panel.
Windows Provides a Service Control Manager which controls the start, stop, pause of any given service.
Windows Service by default are run on a virtual user. “Local Service that has administrative rights on the system. The working directory will be the Windows system directory (typically C:\WINNT) and the default temp directory will typically be C:\WINNT\TEMP.
Windows services can be set up to run as any user although running as a user other than the default requires storing a password. It is important to consider that as soon as the password is changed, the service will not run unless the password provided for the service is also changed.
So, it is always preferred to use a default user for windows services, until and unless required.

2. Difference between a normal windows application and a windows service?

If an application is developed which can serve other applications it becomes service.
In the sense say if u own a Travel House and u r having app which displays rate and availability of buses on selected date. Since its limit is within your work area it is an application. But if u designed the same in such a way that it can be used by any Travel Company to design an app. which will use that info and service their clients your app becomes service.
Windows services is different from normal windows application in the sense that for windows application an exe file is enough to install but when it comes to windows services the it is installed by the utility provided by .Net called InstallUtil.exe or an MSI installer.


3. Basic points regarding windows service

a. Windows service can run without a user context.
b. Windows services are generally started when the computer boots up and can be
Started, stopped, paused, and restarted, from the services applet.
c. Windows Services can be managed programmatically and more easily in .NET using the
ServiceController component.
d. User messages are typically written to the Windows Event Log.

4. Creating a .NET Windows Service:

The service we will create does nothing really useful other than serve as a demonstration.

When the service is started we will just log relevant data in a text file at a particular location.

Following steps should be followed in order to create a service:

1. Start Visual Studio .NET and create a new project. Choose C# Project and Windows application.

2. Right Click on “MyService” and click on “Add New Item.”
3. In “Add New Item “window select “Windows Service” and name it “MyService” and click add.
4. Delete Form1.cs and Program.cs so as it is not required, so that the solution explorer looks like.
5. The Code looks something like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;

namespace MyService
{
partial class MyService : ServiceBase
{
public MyService()
{
InitializeComponent();
}

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

protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
}
}
6. Drag and drop timer to your service design view.
Note: Choose timer from components menu and not from Windows forms.

5. Adding Functionality to the service:

Add the following functionality to your service:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Configuration;
using System.IO;



namespace TryingWindowsService
{
partial class MyService : ServiceBase
{
public MyService()
{

InitializeComponent();
}

#region Main
static void Main()
{
System.ServiceProcess.ServiceBase[] ServiceToRun;
ServiceToRun = new System.ServiceProcess.ServiceBase[]
{
new MyService()
};
System.ServiceProcess.ServiceBase.Run(ServiceToRun);
}
#endregion Main


#region start
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
this.timer1.Enabled = true;
FileStream fs = new FileStream(@"d:\temp\windowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter streamwriter = new StreamWriter(fs);
streamwriter.BaseStream.Seek(0, SeekOrigin.End);
streamwriter.WriteLine("WindowsService : ServiceStarted\n");
streamwriter.Flush();
streamwriter.Close();
}
#endregion start


#region Stop
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
this.timer1.Enabled = false;
FileStream fs = new FileStream(@"d:\temp\windowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter streamwriter = new StreamWriter(fs);
streamwriter.BaseStream.Seek(0, SeekOrigin.End);
streamwriter.WriteLine("WindowsService : ServiceStopped\n");
streamwriter.Flush();
streamwriter.Close();
}
#endregion stop

}
}
6. Add Windows Installer to the service

1. To add windows installer service right click on the designer view and then click on “Add Installer” and name the file “MyServiceInstaller”
2. Add the following lines of code to “MyServiceInstaller”:
this.MyServiceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
this. MyServiceInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;

3. The installer code looks like:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;

namespace MyService
{
[RunInstaller(true)]
public partial class ProjectInstaller : Installer
{
public ProjectInstaller()
{
InitializeComponent();
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
}
}
}

4.Build the application


7. Installing the Windows service:

1. Open Visual Studio.NET command prompt
2. Change to bin\Release folder of the project
3. Issue the command InstallUtil.exe MyService.exe to register the service and have it create the appropriate registry entries :
InstallUtil.exe MyService.exe

4. Open the computer managementàServicesàand Check for the program is running.

5. To uninstall the service use the command:
InstallUtil.exe /u MyService.exe
For more information:
http://www.theserverside.com/discussions/thread.tss?thread_id=17304
http://msdn.microsoft.com/msdnmag/issues/01/12/NETServ/
http://en.wikipedia.org/wiki/Windows_service

Points To Ponder:
1. You can set the CanStop property for a service to false. This renders the Stop command unavailable on that particular service; if you try to stop the service from Server Explorer, the necessary menu item appears dimmed. If you try to stop the service from code, the system raises an error: "Failed to stop "
In case of doubts and clarification please feel free to mail at: archita.dash@rediffmail.com

No comments: