Geeks With Blogs

News QTP and Stuff
Theo Moore Questions... Morphology? Longevity? Incept dates?

I recently wrote a Windows service for the development team here at work. Apparently, the devs were all committed to other projects and this extra curricular activity popped up. Being a developer in tester's clothing, I was asked if I'd do it.

Interestingly, this was originally to be a Powershell script, but the more I worked on it the less it sounded like PS and the more it sounded like a service...pretty straight forward stuff: comes alive at configurable times, looks for files in a folder, processes the files, moves them, updates a database. Pretty simple stuff.

Given that we are a Java shop, I got some funny looks when I told them I'd write it in C#...but, no one really objected.

Anyway, I found debugging the service to be a pain. You have to compile the app, install the service, attach to the running process, etc., for every little change you make. What an annoyance!

Fortunately, an aquaintance of mine noticed me tweeting about it and sent the following to help me out by sending me the following (note that it assumes the classname is "OrderService"):

1. In your service class add the following subroutine:
internal void Start()
{
OnStart(new string[] { });
}

2. In Program.cs modify the Main routine as follows:
static void Main()
{
#if(!DEBUG)
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new OrderService() };
ServiceBase.Run(ServicesToRun);
#else
OrderService service = new OrderService();
service.Start();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#endif
}

What this does is basically switch the directive based on your compiler settings. If you are in Release or a user defined mode, it will compile to run as a service and not launch anything without being installed. However, if you are in debug mode, it will hit your entry point defined in 1 to start your service as if it was being launched by Windows. Keep in mind that when you go to deploy this to production, you MUST compile in a non DEBUG mode. Otherwise it will spin indefinitely when you attempt to start it up under the services control panel.

This works very well, and makes debugging much simpler. Of course, some things you can't still find until you install and run the service, but this is great for debugging those quick, little changes.

Nice! Thanks, Brandon!!

Posted on Monday, July 20, 2009 12:19 PM | Back to top


Comments on this post: windows service: debugging simplified

Comments are closed.
Comments have been closed on this topic.
Copyright © Theo Moore | Powered by: GeeksWithBlogs.net