March 19, 2024

SamTech 365

PowerPlatform, Power Apps, Power Automate, PVA, SharePoint, C#, .Net, SQL, Azure News, Tips ….etc

Create a Windows Service in C# or Convert your Console App to a Service

Today, I will explain how we can easily create a Windows Service in C#.

Context :

I had a C# Console App, which connects to NAV Sql Serve DB and pulls data from a pre-defined views into my ASP.Net Project.

Problem : 

I had to convert this C# Console App to a Windows Service.

Here are the simple steps.

1- Create a new Project

In your solution, select Add, and Click New Project

2- Select Windows Service (.net Framework) Template

3- Type your Project Name

4- add a service installer

At this stage, open the Service1.cs > right click > Add installer

This will create a ProjectInstaller.cs file for you, right click (or press F7) to switch to the code view.

PS: make sure you are on the ProjectInstaller.designer.cs instead of the ProjectInstaller.cs.

By default, the ProjectInstaller.designer.cs looks like this :

5- Define the service Title, description and account used to run you Service

In the ProjectInstaller.designer.cs, make sure you specify which account is used to run your service

this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;

And you service Name, Display Name, Description

this.serviceInstaller1.DisplayName = "TRAPS Service";
this.serviceInstaller1.Description = "This Service Connects to NAV Db and applies any modifications to the TRAPS DB";
this.serviceInstaller1.ServiceName = "Service1";

 

6- Your service’s code

Now you can use the pre-defined events in your Service.cs to implement your code.

You will have access to different events such as onstart, onstop, onElapsedTime.

Here is a simple example which outputs to a text file an entry every 5 seconds.

public partial class Service1: ServiceBase {  
        Timer timer = new Timer(); // name space(using System.Timers;)  
        public Service1() {  
            InitializeComponent();  
        }  
        protected override void OnStart(string[] args) {  
            WriteToFile("Service is started at " + DateTime.Now);  
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);  
            timer.Interval = 5000; //number in milisecinds  
            timer.Enabled = true;  
        }  
        protected override void OnStop() {  
            WriteToFile("Service is stopped at " + DateTime.Now);  
        }  
        private void OnElapsedTime(object source, ElapsedEventArgs e) {  
            WriteToFile("Service is recall at " + DateTime.Now);  
        }  
        public void WriteToFile(string Message) {  
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";  
            if (!Directory.Exists(path)) {  
                Directory.CreateDirectory(path);  
            }  
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\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);  
                }  
            }  
        }  
    }

 

7- Install your service

After you implement your service’s code, you need to build your project, and install the service using the InstallUtil.exe (utility), located in the .net framework install path.

Run PowerShell or CommandLine as an administrator

Position your shell in the .net folder

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

Run the InstallUtil.exe with your service.exe path

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