Playing Chicken With Common Sense

When you want to debug a windows service using the Visual Studio IDE you can either attach to the process which isn't fun after 5 minutes or you can do the following.

Create a Visual Studio Solution

Let's start by creating a new Visual Studio Solution named "EmailProcessor Solution".

  1. File | New | Project
    1. Project types: Windows
    2. Templates: Windows Service
    3. Name: EmailProcessor
    4. Location: C:\Projects\wijix\
    5. Solution Name: EmailProcessor Solution

FileNewProject_thumb2[2] 

You should have a solution explorer that looks similar to the following:

 SolutionExplorer[1]

Debugging the Windows Service

We now have to add some code to the windows service to allow it to be debugged from the IDE easily.

Now open Program.cs and replace main with the following:

using System;
 
namespace EmailProcessor
{
    static class Program
    {
        static void Main()
        {
#if DEBUG
            Service1 windowsService = new Service1();
            windowsService.Start();
            do
            {
                System.Threading.Thread.Sleep(1000);
            } while (true);
#else
            System.ServiceProcess.ServiceBase[] ServicesToRun;
            ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
#endif
        }
    }
}

We have one more thing to do and then we will be able to run this like a normal app from the IDE.  Open Service1.cs and add a public method Start() and then change the OnStart(...) method to call the Start() method you just created.  See Screenshot.

Service1.cs[1] 

At this point we have created a windows service capable of being ran (debugged) from Visual Studio without having to attach to a process.

  • 0 Comments
  • E-mail
  • Kick it!
  • Shout it
  • Bookmark and Share

Control panel

RecentComments

Comment RSS