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

The Ansible Architecture

Ansible is an open source, IT automation tool. It can configure systems, deploy software, and orches...

Read More >

Implementing Azure DevSecOps with Microsoft Credential Scanner

Let’s look at CredScan which is a Microsoft Code Analysis extension and it is abbreviated as MSCA i...

Read More >

Git Command line Options

Git is a free and open source distributed version control system designed to handle everything from ...

Read More >

VSTS Copy Dashboard Tool

The Copy Dashboard tool replicates/copies the existing dashboard from one team to either single or m...

Read More >

Parallel Execution using Selenium Webdriver and TestNG

While testing a web application it is very important to test the application on different browsers. ...

Read More >

Exclusive CxO Roundtable at C-SOaP addresses

img{ display:block; } #outlook a{ padding:0; } body{ width:100% !important; } body{ ma...

Read More >

What’s New On Microsoft Dynamics NAV 2018

As most of us know that Microsoft NAV 2018 has released a great feature about API in 2018, to suppor...

Read More >

Kubernetes basic Objects

In this article, we will learn about the basic objects of Kubernetes in detail with their respective...

Read More >

Identifying Web Elements using Selenium Webdriver

What is Web Element?             &n...

Read More >

Share

Post a Comment

  • Recent
  • Popular
  • Tag
  • The Ansible Architecture

    Ansible is an open source, IT automation tool. It can configure systems, deploy software, and orchestrate more advanced IT tasks such as continuous deployments or zero downtime rolling updates. In thi...
  • Subversion (Centralized Version Control System)

    Version control system is a repository of files, often the files for the source code of computer programs with monitored access. They are essential for any form of distributed, collaborative developme...
  • Volume management in Kubernetes

    Since pods created in k8s are ephemeral, we are able to get the data as long as pods are alive, but if pods are terminated data stored in it completely lost and it cannot be get back, for that we need...
  • LDAP Integration with Sonatype Nexus

    Sonatype Nexus supports the Repository Manager integration with various active directory systems for authentication, such as Microsoft Exchange / Active Directory, OpenLDAP, ApacheDS, and others. In o...
Tags
Monthly Archive
Subscribe
Name

Contact Us
  • *
  • *