«

Three little tips for debugging .Net Windows Services

  <p>
    If I want to switch to service mode, I just comment out the declaration directive. 
    
    <pre> //#define CONSOLE </pre>
    
    <p>
      Using this technique let&#8217;s me get most of the way towards my service functionality without having to open the Service Control Manager (SCM) once.
    </p></li> 
    
    <li>
      At some point you&#8217;re still going to need to debug the service as a service. Don&#8217;t, I repeat, <b>don&#8217;t do what I did and listen to the MSDN article I mentioned earlier when it comes to launching the debugger</b>. You&#8217;ll drive yourself nuts hitting start in the SCM, and then switching over to VS.NET to attach to the process before the line of code you want to test is hit. Especially if you&#8217;re trying to debug the OnStart method. Instead, add a simple yet beautiful line of code to the service: <pre> 	System.Diagnostics.Debugger.Launch(); </pre>
      
      <p>
        Bam! No more rushing. Go ahead and start your service in the SCM and the &#8220;would you like to debug&#8221; dialog will pop up as soon as that line is reached. If I had realized that earlier I might have avoided a nasty finger sprain ;).
      </p>
    </li>
    
    <li>
      Once you&#8217;re in the home stretch you&#8217;re going to have some bugs to squash. Well, not you, but the other non-perfect devs on your team. <b>Nothing is more annoying than having to stop the darn service every time you need to do a build.</b> Especially since I always forget and wind up getting a bunch of compilation errors about not being able to write to the file. Instead, in VS.NET choose the &#8220;Projects&#8221; menu and click properties. Under the &#8220;Common Properties&#8221; folder you&#8217;ll find the Build Events node. Click on that and enter the following code into the &#8220;Pre-build Event Command Line&#8221; entry box. Now, whenever you do a build the service will be stopped and your build will suceed. Well, if your code is compilable that is. <pre> net stop "MOM Logger Service"<br /> if errorlevel 1 echo "Service wasn't running, ignoring."<br /> if errorlevel 1 goto CSharpEnd<br /></pre>
      
      <p>
        I don&#8217;t claim to be a great batch scripter, but this works. </li> </ol> 
        
        <p>
          Ok, that&#8217;s it. Nothing mindblowing, I know, but this isn&#8217;t <a href="http://blogs.msdn.com/cbrumme/">.Net Notes</a>. Enjoy! </div>