Wednesday, 11 March 2009

Debugging a Windows Service in Visual Studio.NET

There is an easy way to debug a windows service in .NET, without having to install it each time (then restart as its marked for deletion!!).

1. Create a new Windows Service Project using the default template.
2. Open "Program.cs"
3. In "Main()" use the following code...

Code Snippet
  1. #if (!DEBUG)
  2.     System.ServiceProcess.ServiceBase[] ServicesToRun;
  3.     ServicesToRun = new System.ServiceProcess.ServiceBase[] { new [Service Name]() };
  4.     System.ServiceProcess.ServiceBase.Run(ServicesToRun);
  5. #else
  6.     // Debug code: this allows the process to run as a non-service.
  7.     // It will kick off the service start point, but never kill it.
  8.     // Shut down the debugger to exit
  9.     [Service Name] service = new [Service Name]();
  10.     service.[Service Main Method]();
  12.     // Put a breakpoint on the following line to always catch
  13.     // your service when it has finished its work
  14.     System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
  15. #endif
End of Code Snippet

4. Replace [Service Name] with the class name of your service.
5. Add a method to your [Service Name].cs file (which is also called from "OnStart(string[] args)". This method will contain all of the logic which is debugged. Reference this method in "Program.cs"
6. Set the compiler to DEBUG mode, and start putting some breakpoints in!!

The same applies for VB.NET users

No comments: