Archive

Posts Tagged ‘software’

Debugging Windows Service

January 10, 2013 1 comment

I was working with a windows service nearly one year and hopefully I will be working with this in next couple of months, may be next couple of years due to working on a product based company.  🙂

As most of the developers have experienced, it was a headache to debug a windows service.  So think about working with a same windows service around a yearL. Very beginning I found a solution. That was

  1. Have a key on app.config  as “DebugMode=true”
  2. In the code, I have put following line of code, where I mostly want to debug. (if I want new place, I add same code there) DebugMode value will be assigned based on app.config key.

if (DebugMode)
System.Diagnostics.Debugger.Launch();

  1. This was fine. But issue was  with this way is,

Every time I had to compile the code, prepare the setup, uninstall and install on machine. If single line of code changed, had to follow same steps. (Installed version of code and IDE code version should be exactly match)

So today I came up with a better solution. Simple steps. But it saves time, especially when release is nearby :).

  1. Get rid of config key 🙂
  2. Above debug mode property populated by this way. This will get value based on configuration. If we select debug, this will be true and if we select release, this will be false.

public static bool DebugMode

{

get

{

bool isDebugMode = false;

#if DEBUG

isDebugMode = true;

#endif

return isDebugMode;

}

}

  1. I will add here whole Main method of Program.cs class. Only we need to change is, select the correct configuration. After finish the debug, select configuration as ‘release’ and build the setup. Don’t be confused with the code. what I do here is,
    1. If debug mode is true, do exactly what I do in the windows service class and start the application. You have to change the project type to ‘console application’ to open the console. But what I wanted here is not to see console, I just wanted to hit the break point without going through set of steps.
    2. If debug mode is false, call the windows service as normally.

static void Main()

{

if (DebugMode)

{

try

{

string serverURL = string.Format(“http://localhost:{0}/”, ConfigurationManager.AppSettings[“ServerPort”]);

AppHost _appHost = new AppHost();

MiddleWareEngine = new MiddleWareEngine();

MiddleWareEngine.StartEngine();//starting middleware

//Now run the Services.

_appHost = new AppHost();

_appHost.Init();

_appHost.Start(serverURL);

Console.WriteLine(string.Concat(“Middleware Server Started on “, serverURL));

}

catch (Exception ex)

{

Console.WriteLine(“Error: ” + ex.Message);

}

}

Else //Release mode

{

ServiceBase[] ServicesToRun;

ServicesToRun = new ServiceBase[] { new DominateRFIDAlertService() };

ServiceBase.Run(ServicesToRun);

}

}

Advertisements