views:

282

answers:

6

I want to debug a service written in C# and the old fashioned way is just too long. I have to stop the service, start my application that uses the service in debug mode (Visual studio 2008), start the service, attach to the service process and then navigate in my Asp.Net application to trigger the service.

I basically have the service running in the background, waiting for a task. The web application will trigger a task to be picked up by the service.

What I would like to do is to have a console application that fires the service in an effort for me to debug. Is there any simple demo that anybody knows about?

Thank you Jack

+1  A: 

Here is a blog post about running your windows service as a console app.

You could also just create a new Console Application that references the same logic as your service to test methods, or set up Unit Tests on your services' logic

Matt Dearing
+1  A: 

I have used unit tests to debug difficult setups in the past, just write a unit test that calls whatever service method with whatever parameters and set debug breakpoints in the unit test.

Using testdriven.net or jetbrains testrunner makes it easier.

BioBuckyBall
A: 

I tend to have either a config setting or use a directive for debug builds:

 #if DEBUG
    Debugger.Break();
 #endif

or

if(Settings.DebugBreak)
            Debugger.Break();

I put that in the OnStart method of the service component. Then you are prompted automatically and attached to the process.

HollyStyles
+1  A: 

You might want to check out TopShelf as well in your adventures.

http://codebetter.com/blogs/dru.sellers/archive/2009/01/11/topshelf.aspx

http://code.google.com/p/topshelf/

dodegaard
+1  A: 

You can do something like this in the main entry point:

static void Main()
{
#if DEBUG
    Service1 s = new Service1();
    s.Init(); // Init() is pretty much any code you would have in OnStart().
#else
    ServiceBase[] ServicesToRun;
    ServicesToRun=new ServiceBase[] 
    { 
        new Service1() 
    };
    ServiceBase.Run(ServicesToRun);
#endif
}

and in your OnStart Event handler:

protected override void OnStart(string[] args)
{
    Init();
}
scottm
+1 - I have almost the exact same code in a couple of services I have written.
37Stars
+5  A: 

The approach I always take is to isolate out all of your application's logic into class libraries. This makes your service project really just a shell that hosts your class libraries as a service.

By doing this, you can easily unit test and debug your code, without having to deal with the headache of debugging a service by attaching to a process. I'd recommend unit testing of course, but if you're not doing that then adding a console application that calls the same entry point as your service is the way to go.

Aaron Daniels