Sunday, 2 August 2020

create and Install the Windows service in C#

How to create a Windows service in C#?

 
Let's create a Windows Service in C# using Visual Studio. 
 
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” and click on the OK button.
 
windows service
 
Step 2
 
Go to Visual C# -> ”Windows Desktop” -> ”Windows Service” and give an appropriate name and then click OK
 
windows service 
 
Once you click the OK button the below screen will appear, which is your service
 
windows service 
 
Step 3
 
Right-click on the blank area and select “Add Installer”
 

How to Add an Installer to a Windows Service

 
Before you can run a Windows Service, you need to install the Installer, which registers it with the Service Control Manager.
 
windows service 
 
After Adding Installer, ProjectInstaller will add in your project and ProjectInstakker.cs file will be open. Don’t forget to save everything (by pressing ctrl + shift + s key)
 
windows service 
 
Solution Explore looks like this:
 
windows service 
 
Step 4
 
Right-click on the blank area and select “View Code”
 
windows service
 
Step 5
 
Its has Constructor which contains InitializeComponent method:
 
The InitializeComponent method contains the logic which creates and initializes the user interface objects dragged on the forming surface and provided the Property Grid of Form Designer.
 
Very important: Don't ever try to call any method before the call of InitializeComponent method.
 
windows service 
 
Step 6
 
Select InitializeComponent method and press F12 key to go definition
 
windows service 
 
Step 7
 
Now add the below line:
 
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
 
You also can add description and display service name (optionally).
  1. this.serviceInstaller1.Description = "My First Service demo";  
  2. this.serviceInstaller1.DisplayName = "MyFirstService.Demo";  
windows service
 
Step 8
 
In this step, we will implement a timer, and code to call the service at a given time. We will create a text file and write the current time in the text file using the service. 
 
windows service 
 
Service1.cs class 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Diagnostics;  
  6. using System.IO;  
  7. using System.Linq;  
  8. using System.ServiceProcess;  
  9. using System.Text;  
  10. using System.Threading.Tasks;  
  11. using System.Timers;  
  12. namespace MyFirstService {  
  13.     public partial class Service1: ServiceBase {  
  14.         Timer timer = new Timer(); // name space(using System.Timers;)  
  15.         public Service1() {  
  16.             InitializeComponent();  
  17.         }  
  18.         protected override void OnStart(string[] args) {  
  19.             WriteToFile("Service is started at " + DateTime.Now);  
  20.             timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);  
  21.             timer.Interval = 5000; //number in milisecinds  
  22.             timer.Enabled = true;  
  23.         }  
  24.         protected override void OnStop() {  
  25.             WriteToFile("Service is stopped at " + DateTime.Now);  
  26.         }  
  27.         private void OnElapsedTime(object source, ElapsedEventArgs e) {  
  28.             WriteToFile("Service is recall at " + DateTime.Now);  
  29.         }  
  30.         public void WriteToFile(string Message) {  
  31.             string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";  
  32.             if (!Directory.Exists(path)) {  
  33.                 Directory.CreateDirectory(path);  
  34.             }  
  35.             string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/''_') + ".txt";  
  36.             if (!File.Exists(filepath)) {  
  37.                 // Create a file to write to.   
  38.                 using(StreamWriter sw = File.CreateText(filepath)) {  
  39.                     sw.WriteLine(Message);  
  40.                 }  
  41.             } else {  
  42.                 using(StreamWriter sw = File.AppendText(filepath)) {  
  43.                     sw.WriteLine(Message);  
  44.                 }  
  45.             }  
  46.         }  
  47.     }  
  48. }  
Code explanation - the above code will call service every 5 seconds and create a folder if none exists and write our message.
 
Step 9. Rebuild your application.
 
Right-click on your project or solution and select Rebuild.
 
windows service 
 
Step 10
 
Search “Command Prompt” and run as administrator
 
windows service 
 
Step 11
 
Fire the below command in the command prompt and press ENTER.
 
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 
 
windows service 
 
Step 12
 
Now Go to your project source folder > bin > Debug and copy the full path of your Windows Service exe file.
 
windows service
 
windows service
 

Installing a Windows Service

 
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\Faisal-Pathan\source\repos\MyFirstService\MyFirstService\bin\Debug\MyFirstService.exe
 
windows service 
 

Check the status of a Windows Service

 
Open services by following the below steps:
  1. Press Window key + R.
  2. Type services.msc
  3. Find your Service.
windows service
 
windows service
 
You may notice that the Windows service is running. 
 
windows service
 

Check Windows Service Output 

 
The service will create a text file with the following text in it. 
 
windows service 
 
The log folder will be created in your bin folder.
 

Uninstalling a Windows Service

 
If you want to uninstall your 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

No comments: