Creating Windows Services The Definitive Guide

visual-studio-asp-net

Writing and debugging Windows services is no easy task. It requires tedious work and full attention. At this post, I will depict you verified methods for debugging and preparing an up-running windows service for good. At the end of the post, I will tell you about some possible errors you might get and their solutions.

Step 1

First, go to the Visual Studio 2019 Community Edition create a project option and do create Windows Service in C#.

creating windows service

Step 2

Create the service by filling in the prompts of the Visual Studio 2019.

creating windows service

Step 3

Right-click on the large gray pane and click on the add installer.

creating windows service

Step 4

Now save all the open folders by clicking ctrl + shift + s and later on press on the view code at the design area. This will show you the main coding area your custom codes go in.

creating windows service

Step 5

Add the definitions below to the InitializeComponent function. By this way, the C# Windows Service will never prompt you the Windows credentials again and again before the service run.

creating windows service
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;

this.serviceInstaller1.Description = "My Windows Service";
this.serviceInstaller1.DisplayName = "MyWindowsService.Demo";

Step 6

The code below will write to the file with 2 seconds intervals. The files are located under the Logs folder of the main executable. Most probably it is in the bin folder.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Data.SqlClient;
using System.Collections;

namespace EmailService
{
    public partial class Service1 : ServiceBase
    {
        Timer timer = new Timer();
        public Service1()
        {
            InitializeComponent();
        }
        public void WriteFile(string Message)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog" + ".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);
                }
            }
        }
        protected override void OnStart(string[] args)
        {
            WriteFile("Service is started at " + DateTime.Now);
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = 2000; //number in miliseconds  
            timer.Enabled = true;
        }

        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            WriteFile("Service is recalled at " + DateTime.Now);
        }
        protected override void OnStop()
        {
            WriteFile("Service is stopped at " + DateTime.Now);
        }
    }
}

Step 7

Now you have to register your new Windows service. Bear in mind that you clicked already build the application in the Visual Studio since the operating system will require the latest version of the executable to work as expected.

As the image depicts below:

writing windows service

The registration of the service is as simple as running the command

InstallUtil.exe + Your copied path + \your service name + .exe

For uninstalling the service put a /u flag after the InstallUtil key like:

InstallUtil.exe /u + Your copied path + \your service name + .exe

Sometimes the service can’t get properly uninstalled due to their complex nature. I highly suggest close any services window, resource monitors, the task manager and log out all the other users or else you will get the following error:

The specified service has been marked for deletion.

Also please kill all the running instances of the task.

Find Out Which .Net Framework Is Installed

Please go to the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full. If the Full key is not present, then you don’t have the .NET Framework 4.5 or later installed. This method is for only +4.5 .NET versions.

.NET Value of the Release DWORD
.NET Framework 4.5 All Windows operating systems: 378389
.NET Framework 4.5.1On Windows 8.1 and Windows Server 2012 R2: 378675
On all other Windows operating systems: 378758
.NET Framework 4.5.2All Windows operating systems: 379893
.NET Framework 4.6On Windows 10: 393295
On all other Windows operating systems: 393297
.NET Framework 4.6.1On Windows 10 November Update systems: 394254
On all other Windows operating systems (including Windows 10): 394271
.NET Framework 4.6.2On Windows 10 Anniversary Update and Windows Server 2016: 394802
On all other Windows operating systems (including other Windows 10 operating systems): 394806
.NET Framework 4.7On Windows 10 Creators Update: 460798
On all other Windows operating systems (including other Windows 10 operating systems): 460805
.NET Framework 4.7.1On Windows 10 Fall Creators Update and Windows Server, version 1709: 461308
On all other Windows operating systems (including other Windows 10 operating systems): 461310
.NET Framework 4.7.2On Windows 10 April 2018 Update and Windows Server, version 1803: 461808
On all Windows operating systems other than Windows 10 April 2018 Update and Windows Server, version 1803: 461814
.NET Framework 4.8On Windows 10 May 2019 Update: 528040
On all others Windows operating systems (including other Windows 10 operating systems): 528049

The above table was taken from https://github.com/dotnet/docs/blob/master/docs/framework/migration-guide/how-to-determine-which-versions-are-installed.md

If the server’s .NET version or the application’s .NET version is not the same, you will get the error “Error 1053: the service did not respond to the start or control request in a timely fashion”

Debugging Windows Services The Easy Way

Just put the command below to the start of OnStart method.

Debugger.Launch();

By this way the service will prompt you may I open a new instance of Visual Studio 2019 before starting it and there you go for debugging your application. The easiest way I came across on the Internet when debugging a service was just like this.

Pros of Windows Services

The Windows services are the services which don’t get affected by the other programs and starts with the bootup. It makes the usage a must when it is time to create a scheduled task or checking something regularly. By this way, the necessity is satisfied good with rock-solid Windows services.

Cons of Windows Services

The initiation, deleting and debugging sometimes takes time.