Archive

Archive for the ‘Windows service’ Category

How to debug windows service

February 24, 2010 Leave a comment

Debugging a Windows service under Visual Studio .NET is not straight forward alternative is to create a console application project and then after successful functionality with debugging use the same code in windows service.

Solution to this is that when you create new windows service project  Main() function is available in  Program.cs class.

Do following modification in Program.cs and debug your windows service normally.

static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
//comment these lines while debug
//un-comment when you want to install windows service
//ServicesToRun = new ServiceBase[]
//{
//    new Service1()
//};
//ServiceBase.Run(ServicesToRun);

//comment these lines when you want to install windows service and
//un-comment when you want to debug
Service1 service = new Service1();
service.MethodCalled();//new method added wchich will be called
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

}
}

Now do following changes in Service1.cs

public Service1()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{

//comment these lines when you want to install windows service and
//un-comment when you want to debug
// MethodCalled();
}

protected override void OnStop()
{
}

public void MethodCalled()
{

//Debug will come here after adding break point write your windows service code in this method
}

Using this when you start debugging in Visual Studio debugger will come in method MethodCalled()

Found this solution at http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx by By Lee Humphries

Advertisements