Logging Application Events using a Simple Windows Service in C#

In this article we are going to focus on the steps required to create a Windows Service using Visual C# Windows Service Template in Microsoft Visual Studio 2012. We will create a Windows service and then Deploy it on the machine. We will see how to log information in the Application Event log when the Service is either Started/Paused/Resumes/Stopped.

In this article we are going to focus on the steps required to create a Windows Service using Visual C# Windows Service Template in Microsoft Visual Studio 2012. We will create a Windows service and then Deploy it on the machine. We will see how to log information in the Application Event log when the Service is either Started/Paused/Resumes/Stopped.

About Windows Service:1.Microsoft implements many services in every operating system. 2.With Windows Service we can create a simple data mining application or a complicated multitier, multi-tier business solution.

Step1: Open Microsoft Visual Studio 2012. From the File Menu, Select New Project. For the Project Type, expand Visual C# and then select Windows. In the Templates Pane, select Windows Service. In the Name textbox, type MyDemoService and then Click OK.

Step2: In the solution explorer you will see Service1.cs which represents the service. Rename it to DemoService.cs. Right click DemoService.cs file and select View Code.

We will find OnStart and OnStart methods in the DemoService class along with the class constructor. Notice that both the methods are blank but these methods are required for the service to run properly. OnStart method represents the entry point into your service. This method is called by the Service Control Manager(SCM) when the user clicks Start on the Control Panel Services screen. OnStart method takes the "args" as an array of strings argument which contains the parameters defined in the Administrative Tools->Services->Service Properties.

The OnStop method represents the exit point of our service. Here we can add clean up code. This method is called when the user clicks Stop on the Services tab under Administrative Tools.

OnPause and OnContinue are the other two important methods.OnPause allows a user to temporarily suspend your service without shutting down.OnContinue allows the service to resume where the service was paused.To use the OnPause and OnContinue methods, first enable these features in the service as follows:1.Double click DemoService.cs in the Solution Explorer to open the DemoService.cs Design window.2.Left click in the Design window to view the DemoService.cs Deisgn Properties tab.3.Set the CanPauseAndContinue property to True.

Step3:Write code for OnStart,OnStop,OnPause and OnContinue events: Now we will write code in the OnStart,OnStop,OnPause and OnContinue events. We will write Try Catch blocks so that we can handle exceptions occurred in the service.

In this OnStart method, we are logging an event to the Application Log when the service is started. Here we are creating an instance of the EventLog class and then set the source to "Demo Service" then write the entry into the Application Log and then dispose the EvenLog instance. After this the method returns and the SCM assumes the service is running. Write the below OnStop method which writes an event to the Application log when the user stops the service. Notice that here we are writing a different message with a different EventID to identify what the service is doing.

Step4: Installing the Windows ServiceThere are some prerequisites to install a Windows Service. We need to add two components – ServiceProcessInstaller and ServiceController to allow the .NET Framework to install the service and make it compatible with the Win32 subsystem. Open Solution Explorer, right click DemoService.cs and select View Designer. In the Toolbox, expand Components section and then drag a ServiceController onto the DemoService.cs design window. After it is added, we will see it on the designer as ServiceController1.

Right-click ServiceController1 and select Properties. In the properties window, type the ServiceName as DemoService, This name will be listed on the Administrative Tools->Service page.Double click DemoService.cs to open the Design window. Right click anywhere in the gray window and select Add Installer. Right click ServiceInstaller1 and select Properties. Type DemoService for the Service Name. Type "Demo Service" for Description property. Type"Demo Service" for DisplayName. This is the name we will see in the service list.

Step 5:Setting the Startup Options:Right click the ServiceProcessInstaller1 object and select Properties. For the Account property select LocalSystem. When the service in the context of LocalSystem account it provides extensive local privileges and presents the computer's credentials to any remote computer. This is a very powerful account and allows you to perform almost any action.

Step 6:Additional configuration options:In order to secure our service, we will set some optional security settings from visual studio. 1.Adding Signature Key File(snk file):Select MyDemoService Properties from the project menu and then click Signing tab. Select Sign the Assembly option then Select the drop-down box and choose New. Type in Demo as the key file.snk name and DemoService as the password.

Step 7:Adding Security-Specific Settings:Click the Security tab and enable the default security settings by selecting the Enabled ClickOnce Security Settings checkbox. Save the settings and close the Properties window.

Step 8:Building,Installing and Deploying the Windows Service:Now Build the project by Right clicking the project and choosing the Build Option. After we build the project successfully we are going to deploy it now. Open the Solution Explorer and Right Click theMyDemoService Project and select "Open Folder in File Explorer". Now Navigate to ../bin/Debug folder and copy the path. Run the Visual Studio Command Prompt as an administrator and navigate to the Service Debug folder as shown below.Cd C:\Users\Admin\Documents\visual studio 2012\Projects\MyDemoService\bin\DebugThen run the installutil command and install the service as shown below:C:\Users\Admin\Documents\Visual Studio 2012\Projects\MyDemoService\bin\Debug>installutil mydemoservice.exeThis will run the .NET installutil utility, which will register your service.

Step 9:Verifying that the Service is installed:After our service is installed, Go to Administrative Tools -> Services Windows and see the service "DemoService" with a DisplayName and Description of "Demo Service".Right click the Service and Click Start.

Step 10:View the Service Message for Start/Stop/Pause/Continue events in the Event ViewerIn the EventViewer(Run->EventVwr), In the Application log, we will find the EventID 1000 with a Source of DemoService. On Double Clicking the event we will see "Demo Starting" message, this is the information we typed in the OnStart method code. Similarly Rightclick the service and select Pause then Select Continue and then Select Stop which will log the events in the Application Log with the EventIDs 1001,1002,1003 and respective messages for Pause,Continue and Stop events respectively.