Wednesday, April 11, 2012

How to debug ASP.NET Windows Service

Debugging a code at development or troubleshooting stage is a very basic need for any application.

However, debugging of .NET Windows Service is not as straight-forward as debugging a Windows Application.

Perform following steps to enable debugging of Windows Service in .NET. (Code sample in C#.Net)

1. Open Program.cs file.
2. Jump to "Main()" method in Program class. This is the entry point of Windows Service execution, so you must be having code to instantiate and run your service class in Main() method.
3. We need to tweak code of Main() method to include #if directive that executes code based on symbol (symbol means, Debug, Release, etc)
So your Main() method should have below structure after this change:


static void Main()
{

#if (!DEBUG)

Your Original code to instantiate and run Service class -- DO NOT ALTER IT

#else

Call to your service class method you wish to debug

#endif

}


4. Now run your application, and make sure you are running it in a Debug mode (and not in release mode) if you wish to debug it.
You should now be able to debug your Windows Service code.

5. Also there is no harm in keeping this code in your release to production server, because when you build a Windows Service in Release mode you will see the code you had written in #else block (in above sample) is grayed out (color of disabled text), indicating it will not be executed, rather the one written in #if block will be executed.

No comments:

Post a Comment

Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.

Thanks
Nirman

Blog Archive