Header Ads

Header ADS

Windows Services in C#

 


Hello friends, welcome to you all once again on your own website.In this tutorial, we will discuss how to create Windows Service in C#. So if you want to learn from basic to advance. then today all of you should read this post carefully because today I am going to explain full information about this topic in full details to all of you.

Windows Services

Windows service is a computer program that runs in the background to execute some tasks. It can be automatically started when the computer boots, can be paused and restarted without any User interaction. For example sending a newsletter everyday afternoon, send an email/sms alert to the customer for every one hour.

You may also find all services running on your machine in the following ways:

  • Go to Control Panel and select "Services" or "Task Scheduler"inside "Windows Tools."
  • Next, open the Run window (Window + R), type services.msc, and press ENTER.


How to create a Windows service

Let's create a Windows Service in C# using Visual Studio.

Step 1 - Open the Visual Studio 2019 and Select a new project.



Step 2 - Select the Project Type Windows Services, and click on next.


Step 3 - give the title of the Project and then Click on the Create.


Step 4 - Once you click the Create button, the below screen will appear, which is your service(Design).


Step 5 - 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.



After Adding Installer, ProjectInstaller will add to your project, and ProjectInstakker.cs file will be open. Don't forget to save everything (by pressing the ctrl + shift + s key)



Solution Explore looks like this:



Step 6 - Right-click on the blank area and select "View Code." or Click on switch to code view.



Step 7 - Create separeate class Log and write the following code like given blow. This class will help  to write log in notepad.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace DemoWindowsService
{
    public static class Log
    {
        public static void writeEventLog(string Message)
        {
            string Date = System.DateTime.Now.ToString("dd-MM-yyyy");
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            StreamWriter sw = null;
            try
            {
                //string Date = System.DateTime.Now.ToString("dd-MM-yyyy");
                sw = new StreamWriter(path + "\\DemoService " + Date + ".txt", true);
                sw.WriteLine(DateTime.Now.ToString() + " : " + Message);
                sw.Flush();
                sw.Close();
            }
            catch (Exception)
            {
               throw; 
            }
        }
    }
}

Step 8 - Write the following code on Service class like given blow. 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Threading;
using System.IO;
using System.Timers;
namespace DemoWindowsService
{
    [RunInstaller(true)]
    public partial class Service1 : ServiceBase
    {
        private System.Timers.Timer timer =null;
        public Service1()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {
            Log.writeEventLog("Timer is set for 10 seconds.");
            timer = new System.Timers.Timer();
            //1000 = One Second
            this.timer.Interval = 10000;
            this.timer.Elapsed += new ElapsedEventHandler(this.timer_tick);
            this.timer.Enabled = true;
            Log.writeEventLog("Demo Service Started.");            
        }
        private void timer_tick(object sender, ElapsedEventArgs e)
        {
            Log.writeEventLog("******** -- Event: Timer_Tick -- ********");
            Log.writeEventLog("Timer Ticked and some operations are running... etc");
            Log.writeEventLog("Operation completed successfully.");
        }

        protected override void OnStop()
        {
            Log.writeEventLog("******** -- Event: OnStop -- ********");
            Log.writeEventLog("Attempt to shut down the service");
            timer.Stop();
            timer = null;
            Log.writeEventLog("Service Shut Down by User");
        }
    }
}

Step 9 - Set the property of ServiceInstaller and serviceProcessInstaller tool like following figure.

  



Code explanation - the above code will call service every 10 seconds, create a folder if none exists, and write our message.

Step 10. Rebuild your application.

Step 11 -  Search "Command Prompt" and run as administrator.


Step 12 - Fire the below command in the command prompt and press ENTER.

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


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




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 -i D:\MVC_Project\DemoWindowsService\DemoWindowsService\bin\Debug\DemoWindowsService.exe



Check the status of a Windows Service.

Open services by following the below steps:

  1. Press the Window key + R.
  2. Type services.msc
  3. Find your Service.


You may notice that the Windows service is running.


Check Windows Service Output 

The service will create a text file with the following text in it. 


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 D:\MVC_Project\DemoWindowsService\DemoWindowsService\bin\Debug\DemoWindowsService.exe

Today I told you all through this post about how you can create Windows Service in C#. if you all like this post. then definitely share it with your friends. If there is any confusion. then all of you will tell me in the comments below. I will surely answer each and every comment.

No comments

Theme images by DNY59. Powered by Blogger.