Friday, December 7, 2007

Create Windows Service with C#.Net - Part 1

While surfing on Internet I found many people for How to create Windows Service?, Installing Windows Service, Schedule Windows Service. I had created one Schedule Windows Service with C#.Net. Here I will give you one example for how to create schedule windows service with less effort, how to add windows service to event log viewer. Why we need Windows Service? Many times we want to run a block of code at perticualr time. For example backup data from one server to other server ever 7 days. For this either we have to create backup data and upload to other server. Sometimes it needed every day, so we have to spend much time for backing up data and upload it to other server.
So why not use a code which create a backup and upload to other server at schedule time we set. This block of code is nothing but a Windows Service.
Creating Windows Service
Open "Create Project" dialog in Visual Studio IDE. Now choose Project Type Visual C# -> Windows. Then select Template Windows Service.
This will give you a blank service template. Right click on the template then choose "View Code" This will give you three code block.
Default constructor for Your service.
public Service1() { InitializeComponent(); }
InitializeComponent() will initialize your service components which are inserted at design time to a windows servie (This will be discussed later).
The second block is for Service Start code.
protected override void OnStart(string[] args) {
//TODO: Add code here to start your service.
}
This is override event for default start event of a service. Window will execute the code written in this block when a service is started.
The third part is for code to execute when the service is stopped.
protected override void OnStop() { // TODO: Add code here to perform any tear-down necessary to stop your service.
}
Add the required code to run your service. In next part we will see how to install the created service.