Debugging C# Windows Services the easy way

Have you ever created a C# windows service? I found it really ease to create. But what if something is going wrong? I could never really find a good way of debugging windows services. So most of the time I was writing verbose logs to be able to find the problem. On other way was not running as windows service, but as a simple console application. But somehow there are situations where the console app does work and the windows service doen't. 

Now I found an easy way of debugging windows services. So in this post I will try to explain how to create a simple windows service and be able to debug it.

First  start Visual Studio as Administrator (administrator rights are needed for debugging the windows service).

Secondly create a windows service project. This will create a Program that looks like the code below:

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new YourWindowsService()
            };
            ServiceBase.Run(ServicesToRun);
        }
    }

 In 'YourWindowsService.cs' (where YourWindowsService must be replaced with the name you have choosen) add the selected lines to the OnStart() method.

    protected override void OnStart(string[] args)
    {
        if (args != null && args.Contains("-d"))
        {
            Debugger.Launch();
        }

        // Do Your Things
    }

The code added above checks if one of the arguments is '-d' and ifso it will ask the Debugger to launch. More about this will be explained later in this post.

Build you solution and start a console window to register the service you just created.

Commands for registering windows services are:

sc create YourWindowsServiceName binPath="full-path-to-service.exe"

# start without debugger
sc start YourWindowsServiceName

Your windows service should run now without debugging.

So how start the debugger? Follow the next steps: 

  1. Open the 'Services' of windows
  2. Right click 'YourWindowsService'
  3. Open the properties
  4. Stop the service (if running)
  5. Type '-d' in the Start parameters edit box
  6. Press start.

 

Now the Visual Studio Just-In-Time Debuger will ask to debug:
'Yes, debug YourWindowsService.exe'

Hit yes to allow the Just-In-Time Debuger to start.

The Just-In-Time debugger shows a window to choose the Visual Studio instance to select, if you started visual studio in the first steps as Administrator it will be listed here also. Otherwise choose the version you want (if multiple versions installed) and start debugging.

Visual Studio will open and break at the Debugger.Launch() line.

You have successfully attached a debugger in your windows service.

Never thought it would be so simple as this.