Creating Windows Service - C#

Posted by Techie Cocktail | 1:36 PM | | 4 comments »

Creating a windows service is not a big deal. But as most people don’t often create windows service they tend to do some silly mistakes when they have to create one. Hence I thought of writing up a sample code demonstrating its basics.

Steps:
a. Create a new Windows Service Project. Go to File -> New -> Project and select 'Windows Service' Project template from Windows tab as shown in the figure.



b. The wizard creates for you Service1.cs by default.



c. Let’s see the default code view created by VS.



d. Now let’s add some functionality to this service. Most of the services have timers implemented in them so as to perform a particular task at regular intervals in the background. Lets add a timer and set to fire a method or an action at regular interval as set.


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

namespace MyService
{
public partial class MyFirstService : ServiceBase
{
private Timer _timer;

public MyFirstService()
{
InitializeComponent();

//instantiate the timer and set its interval to fire every one hour.
_timer = new Timer();
_timer.Interval = 3600000;

//perform the action immediately on service start.
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
}

void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
//Write a msg in a text file with the time at which the Elapsed event was raised.
WriteMsgToTextFile(string.Format("Hello: {0}", e.SignalTime.ToString()));
}

protected override void OnStart(string[] args)
{
//start the timer.
_timer.Start();
}

protected override void OnStop()
{
//stop the timer onStop
_timer.Stop();
}

private void WriteMsgToTextFile(string msg)
{
try
{
if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "msg.txt"))
{
using (StreamWriter sw = File.CreateText(AppDomain.CurrentDomain.BaseDirectory + "msg.txt"))
{
sw.WriteLine(DateTime.Now.ToString() + ": " + msg);
sw.Close();
}
}
else using (StreamWriter sw = File.AppendText(AppDomain.CurrentDomain.BaseDirectory + "msg.txt"))
{
sw.WriteLine(DateTime.Now.ToString() + ": " + msg);
sw.Close();
}
}
catch (Exception ex)
{
//Write Logs.
}
}
}
}


e. Now after the code is written successfully, it's time to install the service. For this you need to add the service installer to the project.

f. In the properties window as below, you would see an 'Add Installer' link at the bottom. Click on that to add the installer to your project.



g. This adds two objects 'ServiceProcessInstaller' & 'ServiceInstaller' as below.



h. Also you would have 'ProjectInstaller' files added to your Solution Explorer.



i. Installing the service: To install your windows service, go to the projects ‘bin’ directory. You will see the 'MyService' (in this case) application. Use the below command from your command line to install the service.

C:\Program Files\Microsoft Visual Studio 9.0\VC>
installutil E:\FirstService\MyService\MyService\bin\Debug\MyService.exe

This install the service successfully. You can see your service installed by going to Start -> Run -> 'Services.msc', you would see your service.



To uninstall your service, use the '/u' switch as below.
installutil /u E:\FirstService\MyService\MyService\bin\Debug\MyService.exe

Comments:
As seen in the SCM (Service Control Manager), the service appears as 'Manual'. This is because the startup type property of the ServiceInstaller was set to Manual.

Service Process Installer has 'Account' property which has values – 'LocalService', 'NetworkService', 'LocalSystem', 'User'. It indicates the account under which the service will run.

User - allows the service to impersonate a specific user whether or not that user is logged in. The account is mostly useful during development and not when installing the service in production. The problem with this account is that if the user changes their password, the services needs to be reconfigured with the new password to enable it to function.

Local System - system account with high privileges. This account is similar to Administrator account.
It provides full access to the local system's resources.

Local Service – provides a lower privilege level account. The account is ideal that requires limited or no access to the network resources.

Network Service - this account is built into windows. It provides less privilege to the local computer. The account is ideal for services that require substantial access to network resources.

Reference: MSDN

4 comments

  1. Anonymous // January 13, 2010 at 10:44 AM  

    Concise and helpful. Thank you.

    P.S. Unfortunately, the banner of the web page takes too much space and its annoying and distractive.

  2. Anonymous // March 31, 2010 at 12:39 PM  

    excellent effort to walk through a windows service. very helpful information.

    the banner of the web page is really very annoying and takes too time.

  3. Anonymous // November 1, 2010 at 1:38 PM  

    Nice. But you should be more specific about the installer. Because by default you wont get the link of the installer at the bottom of properties. So Just click the Service and click view designer. Then on the designer surface right click and Add installer option will be their.

  4. Ruchira Sumithra Arachchi // October 23, 2011 at 5:16 AM  

    Wow..it's good. I did some tutorials before to develop service. but this is the thing i wanted. Continuously do a given work :) thanks a lot!