Hello everyone, I just want to share the idea of how to debug the windows service source code from Visual Studio to find out any implementation issue in our code. Particularly when you are in some project where Windows Services are implemented, then there will be some difficulties to debug the solution. Still we can log the process in simple text file or database table or SharePoint list but this won’t be that much effective when compare to debugging your code line by line.
Create a simple Windows Service Project from your visual studio.
The windows service project automatically adds a component class named Service1 and it inherits from System.ServiceProcess.ServiceBase.
Well, we can also call Windows Service project as Non-UI project, because it does not support User Interface (UI). Also service can be long running and it may not run under ‘logged In’ account. By default, services run under the System account. But we can make use of ServiceProcessInstaller to specify under which account the service should run.
You can replace this default Service1.cs to the name you want. VS automatically renames all its references. Make sure you changed the name in Service1.Designer.cs file as well,
private void InitializeComponent()
components = new System.ComponentModel.Container();
this.ServiceName = "MyService";
An executable may contain more than one service but it should contain separate ServiceInstaller for each service. In our case we have only one Service (MyService).
When we start a service, the executable runs the OnStart method for that service. Running the executable does not run the service but it loads the service. The service is retrieved (example, started and stopped) over the Service Control Manager (SCM).
Here, in the below simple example we are writing simple text in the notepad available in a particular folder in your system using Windows Service. And we will see how to debug the code.
The simplest way of debugging is, calling your functionality from Program.cs Main() function instead of calling it from your service. Please note that this method is used only for debugging your code.
The functionality to write text into notepad has been defined in the WriteIntoNotepad() function.
Then simply press F5, you will be prompted with the below dialog. Press OK and you can debug your code.
I kept the functionality of this service simple so that we can under how to debug directly from Main() function.