Sunday, 16 February 2020

C# - Create a Windows Service


Create a Windows Service
Step 1
Open Visual Studio, go to File > New and select Project. Now select a new project from the Dialog box and select “Window Service”.

 

Step 2

Go to Visual C# -> ”Windows Desktop” -> ”Windows Service,” give your project an appropriate name.

 

Step 3

Right-click on the blank area and select “Add Installer.”

Adding Installers to the Service

Before you can run a Windows Service, you need to install the Installer, which registers it with the Service Control Manager.
After Adding Installer, ProjectInstaller will add in your project and ProjectInstakker.cs file will be open. Save everything

 

Step 4

Right click on blank area and select “View Code”

 

Step 5

Its has a Constructor, which contains the InitializeComponent method.
The InitializeComponent method contains the logic which creates and initializes the user interface objects dragged on the form's surface and provides the Property Grid of Form Designer.
InitializeComponent method.  (You are not allowed to call any method before the call of this method)

 

Step 6

Select the InitializeComponent method and go the definition.

Step 7
Now add the below line while installing the service:
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;

You also can add a description and display the service name (optionally).
this.serviceInstaller1.Description = "ConfigReader"; 
this.serviceInstaller1.DisplayName = "ConfigReader";

Step 8

Implement a timer, and code to call a service at a given time.  Create a simple and write in a text file.

ConfigReader.cs 

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;  

namespace MyService {  
    public partial class ConfigReader: 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);  
                }  
            }  
        }  
    }  
}


Step 9: Rebuild Your Application

Right-click on your project or solution and select Rebuild.

 

Step 10

Search “command Prompt” and run the program as an administrator:

 

Step 11

Fire the below command in the command prompt and press Enter.
 cd C:\Windows\Microsoft.NET\Framework\v4.0.30319

 

Step 12

Now Go to your project source folder > bin > Debug and copy the full path of the Windows Service.exe file

 

Step 13 

Open the command prompt and fire the below command and press enter.

Syntax

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

Our Path

InstallUtil.exe C:\Users\ktwong\Desktop\MBIConfigReader\MBIConfigReaderService\MBIConfigReaderService\bin\Debug\MBIConfigReaderService.exe

 

Step 14

Open services by following the below steps:
  1. Press Window key + R.
  2. Type services.msc
  3. Find your Service.

Service Output  

A log folder will be created in your bin folder. 
If you want to uninstall the service, fire the below command.
  1. Syntax InstallUtil.exe -u + Your copied path + \your service name + .exe
  2. Our path InstallUtil.exe -u C:\Users\Faisal-Pathan\source\repos\MyFirstService\MyFirstService\bin\Debug\MyFirstService.exe
Summary
Create a Windows Service and install/uninstall it using the InstallUtil.exe from a command prompt.


No comments:

Post a Comment