views:

53

answers:

3

Hi,

Is it possible to debug a windows service or class library without consuming the code in a launchable app? There is a thread about doing this, but the techniques don't work and keep saying "Cannot start service..." as I am using a windows service.

Thanks

+3  A: 

Are you writing the service in the first place? If so, do yourself a favor and use TopShelf. It will let you create a simple console app that you can debug as a console app, but it can also get registered as a service and run as such.

Massively convenient in my experience as you can easily debug the service if needed without changing any code.

Hristo Deshev
+1 for the link.
dotnetdev
+1  A: 

In you main function, rather than calling ServiceBase.Run(servicesToRun), just run the actual code you want to test.

I usually put in code to check for a command line parameter as in:

-c run in console mode
-i install the service
-u uninstall the service
none run the service

And then set up VS to send in -c while in debug mode.

ho1
This type of thing is precisely what TopShelf automates away for you :-)
Hristo Deshev
Possibly, but it's also 3 extra dlls without any easily accessible documentation and the usual worry about licenses and how well written it is. If I needed all the extra features I'm sure it contains (though I'm not sure what they are since the description is fairly basic) I might be interested.
ho1
A: 

Here's a bit of code that you can use to attach a debugger. I have found it difficult to attach a debugger at the start of the process in the past. When I found this fantastic snip on CodeProject I believe.

Anyway, add this into OnStart, build, install and start your service. Once you have started it will look like it has hung. Attach to the service process (making sure you have the correct Attach to code base selected and presto you can even debug start up.

protected override void OnStart(string[] args)
{
#if DEBUG
    while (!Debugger.IsAttached)      // Waiting until debugger is attached
    {
        RequestAdditionalTime(1000);  // Prevents the service from timeout
        Thread.Sleep(1000);           // Gives you time to attach the debugger   
    }
    RequestAdditionalTime(20000);     // for Debugging the OnStart method,
                                      // increase as needed to prevent timeouts
#endif

    // here is your startup code with breakpoints
} 

HTH

Sres