Creating, Installing, Debugging Windows Services

When I started working on windows services, I had some difficulty with how to install it, what are necessary functionalities, how to debug it etc. I am sharing my leaning from a beginner’s point of view that how to create a service from scratch.

Part 1 – Creating a Windows Service Project

You can select Windows Service template on the new project screen in the windows section to create a windows service project.

Create Project Dialog

This is what it first looks like after you create the project.

This is what it first looks like after you create the project.

I changed the default code in the class to the code below, and added a timer as the functionality is to be performed at regular intervals. and custom event log entry to track service actions.

Timer serviceTimer = new Timer();
public PracticeService()
{
    InitializeComponent();
    if (!System.Diagnostics.EventLog.SourceExists("PracticeSource"))
    {
        System.Diagnostics.EventLog.CreateEventSource("PracticeSource","PracticeLog");
    }
    eventLog1.Source = "PracticeSource";
    eventLog1.Log = "PracticeLog";
}

protected override void OnStart(string[] args)
{
    eventLog1.WriteEntry("Practice Service Started", EventLogEntryType.Information);
    InitializeTimer();
}

protected override void OnStop()
{
    eventLog1.WriteEntry("Practice Service Stopped", EventLogEntryType.Information);
    serviceTimer.Dispose();
}

private void InitializeTimer()
{
    try
    {
        if (serviceTimer != null)
        {
            serviceTimer.AutoReset = true;
            serviceTimer.Interval = Convert.ToDouble(60 * 1000);
            serviceTimer.Enabled = true;
            serviceTimer.Elapsed += serviceTimer_Elapsed;
            eventLog1.WriteEntry("Service Timer Initialized", EventLogEntryType.Information);
        }
    }
    catch (Exception ex)
    {
        eventLog1.WriteEntry(ex.Message, EventLogEntryType.Error);
    }
}
protected void serviceTimer_Elapsed(object sender,ElapsedEventArgs e)
{
    //Your Functionality
    eventLog1.WriteEntry("Elapsed Event Called", EventLogEntryType.Information);
}

To install the service with necessary information in itself we need to add an installer file to this project. An installer class can be found under General tab while adding items to the project.

Installer Class

Add the components ServiceProcessInstaller and ServiceInstaller to the Installer Class from the toolbox and initialize their properties

Installer Class Design View

//
// PracticeServiceInstaller
//
this.PracticeServiceInstaller.Description = "This service is created for practice purposes.";
this.PracticeServiceInstaller.DisplayName = "Practice Service";
this.PracticeServiceInstaller.ServiceName = "PracticeService";
this.PracticeServiceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
//
// PracticeServiceProcessInstaller
//
this.PracticeServiceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.PracticeServiceProcessInstaller.Password = null;
this.PracticeServiceProcessInstaller.Username = null;

Above is the code in the designer file of installer class after initializing the properties. If the service requires special permissions you can use a user with same permissions.

Now build the project in Release mode and we are ready for deployment. For debugging build the project in Debug mode.

Part 2 – Installing a Windows Service

To install the service copy the contents of project output folder(debug/release) to the deployment folder in my case it is “G:\Deployments\PracticeService”

Deployment Folder

Now to install the service open command prompt go to .NET framework folder. As we have entered all the required information regarding service in installer, we won’t be needed to enter any information here and installation will be smooth. We run InstallUtil.exe program to install our service, it takes ‘/i’ as first argument for installation and ‘/u’ for uninstall. The second argument is the path to the service, in my case it is “G:\Deployments\PracticeService\PracticeService.exe”.

After installation our service is now visible in Services Manager Screen

Services Manager

When we start the service and let it run for few minutes we can see the PracticeLog created in the Event Viewer. Here we can see the event happening where we have written entry in the event log like serviceTimer_Elpased event.

Event Viewer

Part 3 – Debugging windows service.

Debugging windows service is as easy as debugging any other program. You just have to attach the Visual Studio Debugger to your service. The service may not get displayed at first because by default it shows the service running of current user. To display you service in the debugger just check the checkbox labeled “Show processes from all users”, then you can debug your code. Make sure that the service deployed should be built in Debug mode not the release mode.

Debugging

If you want to debug the service code without deploying it, there is another way by adding a module to the project and calling the service “OnStart” function in it. Set it as the start-up object and you can debug by running the project the usual way.

The information provided here is easily available on the internet if you search for it, I just wanted to accumulate all the this information at one place so as to have a step by step way for a beginner to start working with Windows Services.

About these ads

About Utkarsh Puranik

Software Engineer by Profession, Gamer by Nature, Techy by Attitude and a Good Person at Heart
This entry was posted in Technology and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s