September 22, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Creating a Windows Service in .NET

  • April 2, 2003
  • By Mark Strawmyer
  • Send Email »
  • More Articles »

What is a Windows Service?

Before building a Windows Service, you need to understand what one is. Windows Service applications are long-running applications that are ideal for use in server environments. Windows Service applications do not have a user interface or produce any visual output. Any user messages are typically written to the Windows Event Log. Services can be automatically started when the computer is booted. They do not require a logged in user in order to execute and can run under the context of any user including the system. Windows Services are controlled through the Service Control Manager where they can be stopped, paused, and started as needed.

Windows Services were introduced as a part of the Windows NT operating system, and thus were previously knwn as NT Services. They are not available on Windows 9x and Windows Me. You need to use one of the operating systems in the NT generation such as Windows NT, Windows 2000 Professional, or Windows 2000 Server to run a Windows Service. Newer versions of Windows should also work. Examples of Windows Services are server products such as Microsoft Exchange, SQL Server, and other applications such as Windows Time that sets the computer clock.

Create a Windows Service

The service you will create does nothing really useful other than serve as a demonstration. When the service is started an entry will be logged into a database indicating that it has started. A database entry will be create by the service on a specified interval during the time in which it is running. The service will create a final database entry when stopping. The service will also automatically log an entry in the Windows Application Log when it is successfully started or stopped.

Micrsoft Visual Studio .NET makes it relatively simple to create a Windows Service. The instructions for starting our demo service are outlined below.

  1. Start a new project
  2. Select Windows Service from the list of available project templates
  3. The designer will open in design mode
  4. Drag a Timer object from the Components tab in the Toolbox onto the design surface (Warning: make sure you use the Timer from the Components tab and not the one from the Windows Forms tab)
  5. Through the Timer properties set the Enabled property to False and the Interval property to 30000 milliseconds
  6. Switch to the code behind view (F7) to add functionality to the service

Makeup of a Windows Service

In the code behind class you will notice that your Windows Service extends the System.ServiceProcess.Service class. All Windows Services built in .NET must extend this class. It requires your service to override the following methods which Visual Studio will include by default.

  • Dispose - clean up any managed and unmanaged resources
  • OnStart - control the service startup
  • OnStop - control the service stoppage

Sample Database Table Script

The following T-SQL script can be used to create the database table used in the example. I am using SQL Server as my database of choice. You can easily modify this example to work with Access or any other database of your choice.

CREATE TABLE [dbo].[MyServiceLog] (   [in_LogId] [int] IDENTITY (1, 1) NOT NULL,   [vc_Status] [nvarchar] (40)            COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,   [dt_Created] [datetime] NOT NULL) ON [PRIMARY]

Sample Windows Service

Below is all of the source code for a Windows Service called MyService. The majority of this source code was generated automatically by Visual Studio.

using System;using System.Collections;using System.ComponentModel;using System.Data;using System.Data.SqlClient;using System.Diagnostics;using System.ServiceProcess;namespace CodeGuru.MyWindowsService{  public class MyService : System.ServiceProcess.ServiceBase  {   private System.Timers.Timer timer1;   /// <remarks>    /// Required designer variable.   /// </remarks>   private System.ComponentModel.Container components = null;   public MyService()   {       // 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;        ServicesToRun = new System.ServiceProcess.ServiceBase[] { new MyService() };     System.ServiceProcess.ServiceBase.Run(ServicesToRun);   }   /// <summary>    /// Required method for Designer support - do not modify    /// the contents of this method with the code editor.   /// </summary>   private void InitializeComponent()   {     this.timer1 = new System.Timers.Timer();     ((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();     //      // timer1     //      this.timer1.Interval = 30000;     this.timer1.Elapsed +=    new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);     //      // MyService     //      this.ServiceName = "My Sample Service";     ((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();   }   /// <summary>   /// Clean up any resources being used.   /// </summary>   protected override void Dispose( bool disposing )   {     if( disposing )     {      if (components != null)       {         components.Dispose();      }     }     base.Dispose( disposing );   }   /// <summary>   /// Set things in motion so your service can do its work.   /// </summary>   protected override void OnStart(string[] args)   {     this.timer1.Enabled = true;     this.LogMessage("Service Started");   }    /// <summary>   /// Stop this service.   /// </summary>   protected override void OnStop()   {     this.timer1.Enabled = false;     this.LogMessage("Service Stopped");   }   /*    * Respond to the Elapsed event of the timer control    */   private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)   {     this.LogMessage("Service Running");   }   /*    * Log specified message to database    */   private void LogMessage(string Message)   {     SqlConnection connection = null;     SqlCommand command = null;     try     {      connection = new SqlConnection( "Server=localhost;Database=SampleDatabase;Integrated Security=false;User Id=sa;Password=;");command = new SqlCommand("INSERT INTO MyServiceLog (vc_Status, dt_Created) VALUES ('" + Message + "',getdate())", connection);      connection.Open();      int numrows = command.ExecuteNonQuery();     }     catch( Exception ex )     {      System.Diagnostics.Debug.WriteLine(ex.Message);     }     finally     {      command.Dispose();      connection.Dispose();     }   }  }}




Page 1 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel