banner



How To Create An Application Service In Windows 10

What is a Windows Service

  • Enables you to create long-running executable applications that run in their own windows session.
  • Can be automatically started when the reckoner boots, can be paused and restarted without whatsoever user interaction.
  • Hands installable by running the command line utility InstallUtil.exe and passing the path to the service's executable file.

Why a Windows Service?

Ane of the nigh common requirements of some businesses is long-running scheduled jobs based on some time interval. For example: sending a newsletter everyday afternoon or send an email alert to the client for every ane 60 minutes.

So building a Windows Service could be 1 of the reliable solutions to do the goal that can do the required job in the behind the scenes without interfering others users on the same reckoner.

Introduction

This article explains a stride-by-pace process of developing and installing a Windows Service to exercise a scheduled job based on a time interval.

Open Visual Studio and from the menus select "File" -> "New" -> "Project...".

A New Project window will open. Cull "Visual C#" >> "Windows" project blazon and select "Windows Service" from the right hand side and proper name the project "TestWindowsService" equally shown in the following screenshot.

new project window

After you lot click "OK", the project will exist created and you lot will see the design view of the service equally shown in the following screen. Right-click the "Service1.cs" file in Solution Explorer and rename it "to" Scheduler or whatever other name that you desire to give information technology. Then click "click hither to switch to code view".

code view

In the lawmaking view, yous tin see 2 methods chosen OnStart() and OnStop(). The OnStart() triggers when the Windows Service starts and the OnStop() triggers when the service stops.

          using System; using Organization.Collections.Generic; using System.ComponentModel; using Organization.Data; using Organisation.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; using System.Timers;  namespace TestWindowService {     public partial course Scheduler : ServiceBase     {         public Scheduler()         {             InitializeComponent();         }         protected override void OnStart(string[] args)         {          }         protected override void OnStop()         {          }     } }        

Right-click the TestWindowService project, add a new class and name it "Library.cs". This class will be useful to create the methods that we require in the project. If your TestWindowService is a big project, you lot tin create a ClassLibrary project and reference it to your TestWindowService.

new class

Library.cs

Make the form public and declare it every bit a Static class.

          using System; using Organization.Collections.Generic; using System.Linq; using Organisation.Text; using Arrangement.Threading.Tasks; using Arrangement.IO;  namespace TestWindowService {     public static form Library     {      } }        

Create a log method (WriteErrorLog) to log the exceptions.

          public static void WriteErrorLog(Exception ex) {     StreamWriter sw = zilch;     try     {         sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);         sw.WriteLine(DateTime.At present.ToString() + ": " + ex.Source.ToString().Trim() + "; " + ex.Message.ToString().Trim());         sw.Flush();         sw.Close();     }     grab     {     } }        

Create i more than log method (WriteErrorLog) to log the custom messages.

          public static void WriteErrorLog(string Bulletin) {     StreamWriter sw = zip;     try     {         sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", truthful);         sw.WriteLine(DateTime.Now.ToString() + ": " + Message);         sw.Flush();         sw.Close();     }     grab     {     } }        

Scheduler.cs

Now render to our Scheduler.cs file and declare a Timer.

          using System; using System.Collections.Generic; using Organisation.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using Organisation.ServiceProcess; using System.Text; using System.Threading.Tasks; using Arrangement.Timers;  namespace TestWindowService {     public fractional class Scheduler : ServiceBase     {         private Timer timer1 = naught;          public Scheduler()         {             InitializeComponent();         }         protected override void OnStart(cord[] args)         {         }         protected override void OnStop()         {         }     } }                  

Write the following code in the OnStart() method and timer1_Tick():

          protected override void OnStart(string[] args) {     timer1 = new Timer();     this.timer1.Interval = 30000; //every 30 secs     this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);     timer1.Enabled = true;     Library.WriteErrorLog("Test window service started"); }  individual void timer1_Tick(object sender, ElapsedEventArgs due east) {     //Write code here to do some job depends on your requirement     Library.WriteErrorLog("Timer ticked and some job has been done successfully"); }        

Write the following code in the OnStop() method:

          protected override void OnStop() {     timer1.Enabled = simulated;     Library.WriteErrorLog("Test window service stopped"); }        

Scheduler.cs [Design]

Now return to the Scheduler.cs [Design] and right-click on the editor window then click "Add Installer".

Add Installer

Then you tin can see that there will be a new file called "ProjectInstaller.cs" as shown in the following.

new file called ProjectInstaller

Installer

Right-click on the "serviceInstaller1" and click "Backdrop".

Properties

Change the ServiceName to "Test Windows Service" (or your own name) and StartType to "Manual" (or you tin can choose "Automatic" if you demand this service to be automatic).

Test Windows Service

Right-click the serviceProcessInstaller1, go to the properties window and change "Account" to "LocalSystem".

change Account property

Build the project to come across the .exe file at the location where you lot created the solution.

Build the project

That's all. Your Windows Service is all gear up to install in your machine.

Installing the Windows Service

Go to "Starting time" >> "All Programs" >> "Microsoft Visual Studio 2012" >> "Visual Studio Tools" then click "Programmer Control Prompt for VS2012".

Type the following command:

cd <concrete location of your TestWindowService.exe file>

in my case it is :

cd C:\Sandbox\WindowServices\TestWindowService\TestWindowService\bin\Debug

Installing the Window Service

Side by side type the following command:

InstallUtil.exe "TestWindowService.exe"

and printing Enter.

TestWindowService

Here you lot go, the TestWindowService is installed successfully.

installed successfully

How to start the Windows Service

Since nosotros chose StartType = Transmission, we must start the Windows Service manually past visiting the "Services and Applications" window in the computer.

StartType

Select the Test Windows Service and click "Start" to start the service. Go to the "TestWindowService.exe" location to see the logs.

LogFile.txt

Since we are tracking our Windows Service past writing some logs to a .txt file called LogFile.txt, we tin exam the working condition of our Windows Service by looking at this log file.

LogFile

As you can come across in the preceding screen, yous can notice the LogFile.txt file at the physical location that your TestWindowService solution exists.

Click the LogFile.txt to see the logs, whether our service is doing the job that nosotros set information technology to do for every 30 seconds.

logs

If you wait at the preceding log file, we can show that our Windows Service is running and doing the task that nosotros wanted on a 30 seconds interval.

Stop the Windows Service

To stop the Windows Service, just click "Stop" link in the Services window by selecting our TestWindowService.

Logfile after stopping our service:

Stop the window service

Blazon the following two commands in the "Developer Command Prompt for VS2012" to uninstall the TestWindowService.exe.

  1. cd <physical location of your TestWindowService.exe file>
    and press Enter. In my instance information technology is:
    cd C:\Sandbox\WindowServices\TestWindowService\TestWindowService\bin\Debug
  2. InstallUtil.exe /u "TestWindowService.exe"
    And press enter.
    After executing the preceding commands, the TestWindowService will be uninstalled from your estimator.

Summary

In this article, I explained how to develop a Windows Service and install it using InstallUtil.exe from a control prompt.

I believe that I take explained each footstep conspicuously that can exist easily understandable for a beginner to develop and install a Windows Service.

How To Create An Application Service In Windows 10,

Source: https://www.c-sharpcorner.com/UploadFile/naresh.avari/develop-and-install-a-windows-service-in-C-Sharp/

Posted by: lukasikracrought.blogspot.com

0 Response to "How To Create An Application Service In Windows 10"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel