banner



Can A Windows Service Install Another Windows Service

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 computer boots, can exist paused and restarted without whatsoever user interaction.
  • Easily installable by running the control line utility InstallUtil.exe and passing the path to the service'due south executable file.

Why a Windows Service?

1 of the well-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 alarm to the customer for every one hr.

And so edifice a Windows Service could be one of the reliable solutions to do the goal that tin can practise the required job in the backside the scenes without interfering others users on the aforementioned computer.

Introduction

This article explains a step-past-stride process of developing and installing a Windows Service to do 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. Choose "Visual C#" >> "Windows" project type and select "Windows Service" from the correct hand side and name the project "TestWindowsService" as shown in the post-obit screenshot.

new project window

After you click "OK", the project will be created and you will see the blueprint view of the service as shown in the post-obit screen. Correct-click the "Service1.cs" file in Solution Explorer and rename it "to" Scheduler or any other name that yous want to give it. Then click "click here to switch to code view".

code view

In the code view, you lot tin can see two methods called OnStart() and OnStop(). The OnStart() triggers when the Windows Service starts and the OnStop() triggers when the service stops.

          using System; using Organisation.Collections.Generic; using System.ComponentModel; using System.Information; using System.Diagnostics; using Organisation.Linq; using System.ServiceProcess; using Arrangement.Text; using Organization.Threading.Tasks; using Organization.Timers;  namespace TestWindowService {     public partial class 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 grade will be useful to create the methods that we require in the project. If your TestWindowService is a large projection, you tin create a ClassLibrary project and reference it to your TestWindowService.

new class

Library.cs

Make the class public and declare it as a Static class.

          using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO;  namespace TestWindowService {     public static class Library     {      } }        

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

          public static void WriteErrorLog(Exception ex) {     StreamWriter sw = zippo;     try     {         sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);         sw.WriteLine(DateTime.Now.ToString() + ": " + ex.Source.ToString().Trim() + "; " + ex.Bulletin.ToString().Trim());         sw.Flush();         sw.Close();     }     catch     {     } }        

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

          public static void WriteErrorLog(string Message) {     StreamWriter sw = cipher;     try     {         sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);         sw.WriteLine(DateTime.Now.ToString() + ": " + Message);         sw.Flush();         sw.Close();     }     take hold of     {     } }        

Scheduler.cs

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

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

Write the following lawmaking 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 = truthful;     Library.WriteErrorLog("Examination window service started"); }  private void timer1_Tick(object sender, ElapsedEventArgs due east) {     //Write code here to practice some task depends on your requirement     Library.WriteErrorLog("Timer ticked and some job has been washed successfully"); }        

Write the following lawmaking in the OnStop() method:

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

Scheduler.cs [Design]

At present render to the Scheduler.cs [Design] and correct-click on the editor window and so click "Add Installer".

Add Installer

And so you lot can see that at that place will exist a new file chosen "ProjectInstaller.cs" equally shown in the following.

new file called ProjectInstaller

Installer

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

Properties

Change the ServiceName to "Examination Windows Service" (or your own name) and StartType to "Transmission" (or yous can cull "Automatic" if you demand this service to exist automatic).

Test Windows Service

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

change Account property

Build the projection to see the .exe file at the location where you created the solution.

Build the project

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

Installing the Windows Service

Get to "First" >> "All Programs" >> "Microsoft Visual Studio 2012" >> "Visual Studio Tools" then click "Developer Command Prompt for VS2012".

Type the following command:

cd <physical location of your TestWindowService.exe file>

in my example it is :

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

Installing the Window Service

Side by side blazon the post-obit control:

InstallUtil.exe "TestWindowService.exe"

and press Enter.

TestWindowService

Here you go, the TestWindowService is installed successfully.

installed successfully

How to kickoff the Windows Service

Since nosotros chose StartType = Manual, nosotros must start the Windows Service manually by visiting the "Services and Applications" window in the calculator.

StartType

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

LogFile.txt

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

LogFile

As you tin can see in the preceding screen, you tin find the LogFile.txt file at the physical location that your TestWindowService solution exists.

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

logs

If y'all look at the preceding log file, nosotros can evidence that our Windows Service is running and doing the job that we wanted on a 30 seconds interval.

Stop the Windows Service

To finish the Windows Service, just click "End" link in the Services window past selecting our TestWindowService.

Logfile later stopping our service:

Stop the window service

Type the following two commands in the "Programmer 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 computer.

Summary

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

I believe that I accept explained each pace clearly that can exist easily understandable for a beginner to develop and install a Windows Service.

Can A Windows Service Install Another Windows Service,

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

Posted by: farrelladlyinit.blogspot.com

0 Response to "Can A Windows Service Install Another Windows Service"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel