X
07Apr

Understanding how to create and Install Windows Services in C#.Net

Windows Service in C#:

This article is about how to create a Windows Service in C# .net using Visual Studio.


Windows Services:
Windows services are the executable applications which run in the background and doesn’t contain any user interface. Windows services can be scheduled to run automatically whenever operating system boots or can be started/stopped/paused manually from the services window.  
 

1

Above Services window can be opened in following ways:

  1. Open Run window (Window + R) and type services.msc and press Enter.
  2. Control Panel > Administrative Tools > Services
  3. Type services in search option (Win 10 OS).

Scenarios where Windows Services are used:

If there is a requirement where certain task to be done on certain time intervals without user intervention. Consider sending email to the customers, processing some files whenever files are copied to the folder etc.

Step by step process of creating Windows Service:

  1. Open Visual Studio, File > New > Project

2

 

2. Under Visual C# Select, Windows Desktop > Windows Service and give an appropriate name, file location to store project and then click OK

3

 Click on OK button, the below design screen will appear, which is the service. If you want to rename the Service1.cs with any other name, then right click on the file in the solution explorer > Rename.    In the following screen changed name to SampleScheduler.cs

4

3.  Adding Installer to Windows Service:

To run the Windows Service, you need to install the Windows Service application, which registers it with the Services in Control Manager.

Right Click> Add Installer

5

After Adding Installer, ProjectInstaller will be added in your project and ProjectInstaller.cs file will be opened by default. Then save all the files.

6

4. Right-click on the blank area under ProjectInstaller.cs and select View Code:

7

It Contains Constructor which has InitializeComponent method. This method contains the logic which creates and initializes the user interface objects dragged on the design surface and properties window will be provided for form window.

8

It’s important you should not call any method before the call of InitializeComponent method.

 

5. Go to the definition by pressing F12 Key on InitializeComponent method.

Add the below line:

this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;

 

Or the setting can also be changed in design as:

Right click on serviceProcessInstaller1 > Properties

9

 

Account > Select LocalSystem

10

 

You can also provide optional description and display service name by adding following lines of code:

this.serviceInstaller1.Description = "Test Windows Service";  

this.serviceInstaller1.DisplayName = "WindowsService.Test";

this.serviceInstaller1.DisplayName will displays the name under services window.

11

6. In this step we will write code to create timer and text file and write current time in text file using the service in some time intervals. Code will be written in the created in SampleScheduler.cs.

12

 

In the above screenshot, you can see two methods called OnStart() and OnStop().

The OnStart() triggers when the Windows Service starts and the OnStop() triggers when the service stops.

The following code must be written in SampleScheduler.cs file.

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
usin System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.IO;

namespace TestWindowsService
{
    public partial class SampleScheduler : ServiceBase
    {
        Timer timer = new Timer();
        public SampleScheduler()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {   
            WriteTextToFile("Service started at " + DateTime.Now);
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = 10000; //time interval in milliseconds (10Sec) 
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
            WriteTextToFile("Service stopped at " + DateTime.Now);
        }

        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            WriteTextToFile("Service recalled at " + DateTime.Now);
        }

        public void WriteTextToFile(string Message)
        {
            string checkPath = AppDomain.CurrentDomain.BaseDirectory + "\\LogsFile";
            if (!Directory.Exists(checkPath))
            {
                Directory.CreateDirectory(checkPath);
            }
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\LogsFile\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
            if (!File.Exists(filepath))
            {
                // Create a file to write to.   
                using (StreamWriter sw = File.CreateText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
            else
            {
                using (StreamWriter sw = File.AppendText(filepath))
                {
                    sw.WriteLine(Message);
                }

            }
        }
    }
}

Above code will create a text file if it doesn’t exists, calls service every 10 seconds and logs into text file.

7.  Installing Windows Service:

  1. Rebuild the project.
  2. Open command prompt (cmd) in Administrator mode.
  3. Write the below command in command prompt and press Enter.

 

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 

13

 

d. Copy the full path of your Windows Service exe file: go to the project folder as shown in below screenshot.

14

 

15

As shown in above screen shot, that folder location is where the project file is located go to bin> debug then copy the file with the extension .exe. In this case it is “TestWindowsService.exe”.

 

Our final path will be C:\Users\jayatirthk\source\repos\TestWindowsService\TestWindowsService\bin\Debug in that path include “TestWindowsService.exe”.

 

Then add installUtil.exe before the project path while executing in command prompt (same amd which was opened earlier) as shown below.

InstallUtil.exe + your project file path +bin\debug+\yourservicename.exe

 

Final path:

   C:\Users\jayatirthk\source\repos\TestWindowsService\TestWindowsService\bin\debug\ TestWindowsService.exe 

16

In the above step the installation of the Windows Service has been completed.

To open the installed service, follow the steps below:

As explained earlier, above Services window can be opened in following ways:

  1. Open Run window (Window + R) and type services.msc and press Enter.
  2. Control Panel > Administrative Tools > Services
  3. Type services in search option (Win 10 OS).

17

Our Service can seen in the above image.

To start the service:

  1. Click on service as indicated in the above screen shot.
  2. Right click on the service > Start.

You can schedule the service to start automatically by:

right click on service > properties > new window will pop up > Select start up type as Automatic > Click on start. As shown below screen shot

 

18

19

 

As seen in the above image service has been started and new text file is created. Time is being logged every 10 seconds.

How to Uninstall the Service:

You need to add -u in front of InstallUtil.exe in command prompt following the path of the project.

InstallUtil.exe -u C:\Users\jayatirthk\source\repos\TestWindowsService\TestWindowsService\bin\debug\ TestWindowsService.exe 

20

 

 

 

 

Related

What are Frames? How to handle frames in Selenium WebDriver with C#?

IFrame (FullForm: Inline Frame) is an HTML document that is included in another HTML document and is...

Read More >

What is Synchronization? Handling Synchronization in Selenium WebDriver using C#:

Synchronization meaning: when two or more components involved to perform any action, we expect these...

Read More >

Sending Test reports by Email using Office 365, Gmail

Wouldn’t it be great if Test Report are sent automatically across team as soon the Test Execut...

Read More >

Extent Reports in Selenium CSharp (C#)

Reports play a fundamental role when it comes to TESTING. Tester can now  know the real-time r...

Read More >

How to Set Up Selenium WebDriver in Visual Studio Enterprise 2015?

Pre-requisite : Visual Studio Enterprise 2015 application should be installed into the system.Create...

Read More >

Custom Control in WPF

File Upload Custom Control in WPFThis article is about Custom control in WPF, Custom controls are al...

Read More >

ASP.NET: Audit Trail Implementation using Entity Framework

When you are working with certain projects which involves the Customer records, you might need to tr...

Read More >

Create Restful service using Web API

What is Asp.Net Web API?Asp.Net Web API is a framework for building HTTP services that can be consum...

Read More >

Dependency Injection on SignalR

                &nbs...

Read More >

Create custom project templates in Visual Studio

Visual studio installation comes with the various predefined project templates, and we can use one o...

Read More >

Share

Post a Comment

  • Recent
  • Popular
  • Tag
Tags
Monthly Archive
Subscribe
Name

Text/HTML
Text/HTML
Contact Us
  • *
  • *