Windows Services

What Are Windows Services?

Windows services are specialized software that have no GUI and run without the need of human interaction.

By using Visual Studio.NET, we can create Windows services. Also, we can start, stop, and pause them more easily than ever before. These services are ideal for developing server-based applications, but can also be used on the client side. One of the main advantages of Windows services is that they do not interfere with other windows programs that are running. We need the Windows NT kernel to run Windows services. They cannot be executed on Windows 95/98/ME. Windows services deeply interacts with the operating system.

Where to See Windows Services

We can start, stop, or pause a Windows service from the Windows Services management console. This MMC (Microsoft Management Console) can be opened by selecting the group from the Administrative Tools programs group. All the services currently running on our system will be listed in a later section.

Windows Services in DOTNET

To make a Windows service, we need three types of operational programs. They are as follows:

  • Service Program
  • Service Control Program
  • Service Configuration program

Service Program

A Service Program is the main program where our code resides. Here, we write the actual logic for our service. One point to note here is that each service program can refer to more than one service but each one of these services must contain their own entry point or a Main() method. This Main() method is just like the Main() method in C#.

To write a service class, we need to inherit it from a ServiceBase class. The ServiceBase class is a part of the System.ServiceProcess class.

Service Control Program

A service control program is a part of the operating system. It is responsible for the starting, stopping, and pausing of a Windows service. To implement a Windows service, we need to inherit from the ServiceController class of the System.ServiceProcess class.

Service Configuration Program

Once a service is made, it needs to be installed and configured. Configuration involves that this service will be started manually or at boot time. To implement a service program, we need to inherit from the ServiceProcessInstaller class of ServiceInstaller.

Creating a Windows Service

To create a new Windows service, select a Windows service project. Type a project name and click OK. VS.NET will create the basic code for us. We will just have to write the logic of the code.

There is one important thing to consider in the Main() method:

static void Main()
{

   System.ServiceProcess.ServiceBase[] ServicesToRun;
   //ServiceToRun=New System.ServiceProcess.ServiceBase[]
   //            {new Service1() , new MySecondUserService()};
   ServicesToRun=new System.Serviceprocess.ServiceBase[]
                 {new Service1()};
   System.ServiceProcess.ServiceBase.Run (ServicesToRun);

}

Let's see some code:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Data.OleDb;
using System.IO;
namespace DataLogger
{  //We are creating a class with name Service1 that inherits
   //ServiceBase
   public class Service1 : System.ServiceProcess.ServiceBase
   {
      private System.ComponentModel.IContainer components;
      //Adding the constructor of the class
      public Service1()
      {
         // This call is required by the Windows.Forms Component
         // Designer.
         InitializeComponent();
      }

      // The main entry point for the process
      static void Main()
      {

         System.ServiceProcess.ServiceBase[] ServicesToRun;

         // More than one user Service may run within the same
         // process. To add another service to this process,
         // change the following line to create a second service
         // object. For example,
         //
         // ServicesToRun = New System.ServiceProcess.ServiceBase[]
         //                 {new Service1(),
         //                 new MySecondUserService()};

         //
         ServicesToRun = new System.ServiceProcess.ServiceBase[]
                         { new Service1() };
         // The Run() method is the main method that defines the
         // main entry point for our services
         System.ServiceProcess.ServiceBase.Run(ServicesToRun);
      }

      private void InitializeComponent()
      {
         this.components = new System.ComponentModel.Container();
         this.timer1 = new System.Windows.Forms.Timer
                       (this.components);
         //
         // timer1
         // We are using a timer to monitor a database for seeing
         // that if a specified amount in the items quantity is
         // reached it should write an entry in the log file
         this.timer1.Interval = 120000;
         this.timer1.Tick += new System.EventHandler
                             (this.timer1_Tick);
         //
         // Service1
         // Defining the name of the service
         this.ServiceName = "Service1";

      }

      protected override void Dispose( bool disposing )
      {
         if( disposing )
         {
            if (components !=null)
            {
               components.Dispose();
            }
         }
         base.Dispose( disposing );
      }

      private System.Windows.Forms.Timer timer1;

      //Defining a variable that holds the value of Quantity

      int Quantity=0;    //Quantity of Product Bread

      //OnStart event is fired when we first start our Service

      protected override void OnStart(string[] args)
      {
         // TODO: Add code here to start your service.

         // Here we are making a connection to the database and
         // checking in the customers table that quantity of the
         // item bread should not be less then 100. If so, add
         // an entry in the log file

         OleDbConnection con=new OleDbConnection
                             ("Provider=Microsoft.Jet.OLEDB.4.0;
                               Data Source=C:\\Documents and
                               Settings\\DeepBlueIce\\My Documents\\
                               tach.mdb");
         con.Open();
         OleDbCommand com=new OleDbCommand("Select *
                              from Customer where item='Bread'",con);
         OleDbDataReader dr=com.ExecuteReader();

         while(dr.Read())
         {

            Quantity=dr.GetInt32(2);
         }
         dr.Close();

         con.Close();
         if(Quantity<100)
         {
            FileStream fs=new FileStream(@"C:\log.doc",
                          FileMode.OpenOrCreate,FileAccess.ReadWrite);
            StreamWriter sw=new StreamWriter(fs);
            sw.BaseStream.Seek (0,SeekOrigin.End);
            sw.WriteLine("\nProduct Quantity is less then minimum
                           value");
            sw.Flush();
            fs.Close();
         }
      }

      /// <summary>
      /// Stop this service.
      /// </summary>
      ///
      // This event is fired when our service is stopped
      protected override void OnStop()
      {

      }
      // Below is the code that constantly monitors the database
      // tables

      private void timer1_Tick(object sender, System.EventArgs e)
      {
         // TODO: Add code here to start your service.
         OleDbConnection con=new OleDbConnection
                             ("Provider=Microsoft.Jet.OLEDB.4.0;
                               Data Source=C:\\Documents and
                               Settings\\DeepBlueIce\\My Documents
                               \\tach.mdb");
         con.Open();
         OleDbCommand com=new OleDbCommand("Select * from Customer
                                            where item='Bread'",con);
         OleDbDataReader dr=com.ExecuteReader();

         while(dr.Read())
         {

            Quantity=dr.GetInt32(2);
         }
         dr.Close();

         con.Close();
         if(Quantity<100)
         {
            FileStream fs=new FileStream(@"C:\log.doc",
                          FileMode.OpenOrCreate,FileAccess.ReadWrite);
            StreamWriter sw=new StreamWriter(fs);
            sw.BaseStream.Seek (0,SeekOrigin.End);
            sw.WriteLine("\nProduct Quantity is less then minimum
                          value");
            sw.Flush();
            fs.Close();
         }
      }
   }
}

To install this service, go to the console and move to the directory where the EXE of the service exists.

Type the following line in the console window:

installutil DataLogger.exe

This will install the service and register it in the Registry at

HKEY_LOCAL_MACHINE\System\DataLogger

To start this service, open the MMC console and press the start Button.

The program above was a Service Program where we have written the actual logic we want to implement. Now comes the question of how to control this program. One way is to go to MMC and Start, Stop, and Pause our service. Another way is to do this stuff programmatically through code. For this, the .NET SDK provides a class called the ServiceController class, by which the state of a Windows service can be maintained. For this, we have to import system.ServiceProcess.

Let us see a code example that stops a specified service if it is started.

using System;
using System.ServiceProcess;

namespace MyServiceController
{

   class Class1
   {

      [STAThread]
      static void Main(string[] args)
      {  // We are getting all the services from the service
         // controller array and putting them into a
         // ServiceController array.
         ServiceController[] services=ServiceController.GetServices();
         // Iterating each service to check that if a service named
         // MyService is found then check that its status whether
         // it is running or stopped. If found running then it will
         // stop that service; else it starts that service
         foreach(ServiceController x in services)
         {
            if(x.DisplayName=="Myservice")
            {
               if (x.Status==System.ServiceProcess.
                             ServiceControllerStatus.Running)
               {
                  x.Stop();
               }
               else
               {
                  x.Start();
               }
            }
            else
            {

            }
         }
      }
   }
}

A Service controller has the following seven states:

  • Running
  • Stopped
  • Paused
  • Start Pending
  • Stop Pending
  • Pause Pending
  • Continue Pending

Events

An event is a process that is executed when a specific task is done.

In Windows services, event logging is a useful way to get our desired data. It gives us info about how our Windows services is working. We can see the event log from Start -> Programs -> Administrative Tools -> Event Viewer.

Event logs are of the following different types:

  1. Application Log
  2. Security Log
  3. Directory Service
  4. DNS Server
  5. File Replication Service

To use events in our Windows service, we need to implement System.Diagnostics:

.

EventLog e=new EventLog();
e.Log=.Application.;
e.Source=.My Windows Service.;
e.WriteEntry(.Product Quantity is Less then minimum level.);

.

The code above creates an event log on the Application tab of the Windows Event Viewer. Whenever our product's quantity is less then 100, it will create an entry in the event log. The WriteEntry method is used to write an entry in the corresponding log.

Where We Can Utilize Windows Services

Suppose you are managing a company's Web site. It have required that it wants the info about every file that has been uploaded to its FTP account. It wants the time and other important info too. In a sense, it was a very difficult task before .NET. Before, .NET network administrators wrote certain scripts and put the files in the Windows startup. This causes a mess monitoring such files, and a flaw in this case was that any user can fiddle in these files. DOTNET paved the path for developers to make such applications much easier by using Windows services.

A Windows service is a highly specialized type of application designed to run for extended periods in its own Windows session, usually with no user interface. Fields where we can utilize our knowledge about windows Services include the following:

Network connection management

  • Disk access monitoring
  • Certain security tasks
  • Database Monitoring
  • TCP/IP packet monitoring
  • Anti-Virus Monitoring
  • Exchange Call Monitoring
  • POP UP and Ads Blocker
  • Network Monitoring

Beside Windows services in DOTNET, Microsoft has provided us with a big set of services, such as Alerter, automatic updates, ClipBook, indexing, Fax Service, Messenger, Net Logon, IIS, Telephoney, Telnet, Wins Client, and so forth.



About the Author

Ali Sufyan

I am a software developer and a Database designer.I love to work in Java and DotNet.Also to crave new paths of technology

Comments

  • Windows service Notification

    Posted by GovardhanReddy on 01/13/2007 04:14am

    Hi Can u help me on windows service notification. Plz it is impartent for me give me solution as early as possible Regards Govardhan

    Reply
  • So, so

    Posted by liviub72 on 05/16/2005 04:15am

    The second part (service detection) offers some new info for a beginner like me, but the first part is just copy-paste from MSDN. No error handling, no "cleaning" when the service is stopped, etc. In fact, I don't understand why the Timer is not started on "OnStart" and stopped on "OnStop" and why the same code appears into the "OnStart" proc but also into the timer handler.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

RSS Feeds