Search This Blog

Monday, June 18, 2012

Windows Service


What is a Windows Service?
Windows Service applications are long-running applications that are ideal for use in server environments. The 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, formerly NT Services, were introduced as a part of the Windows NT operating system. 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. 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 we will create does nothing really useful other than serve as a demonstration. When the service is started we will log an entry in a database indicating that it has started. The service will create a database entry 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.
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 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.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace TestWS
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        #region Event
            protected override void OnStart(string[] args)
            {
                try
                {
                 
                    System.Timers.Timer timer1 = new System.Timers.Timer();
                    timer1.Enabled = true;
                    timer1.Interval = 5000;
                    timer1.Start();
                    timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
                    writeLog("EmailService Start..");
                   
                }
                catch
                {
                    writeLog("Exception occur in starting");
                }
            }
            private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                writeLog("Timer Elapse..");
                fetchData();
            }
            protected override void OnStop()
            {
                writeLog("EmailService Stop..");
            }
        #endregion

        #region Methods
            protected void fetchData()
            {
                SqlConnection connection = null;
                SqlCommand command = null;
                try
                {
                    connection = new SqlConnection("Server=localhost;Database=SampleDatabase;Integrated Security=false;User Id=sa;Password=;");
                    command = new SqlCommand("SELECT COUNT(1) FROM SampleDatabase.dbo.TestTable", connection);
                    connection.Open();
                    int numrows = Convert.ToInt32(command.ExecuteScalar());
writeLog(numrows.ToString() + "rows exist in TestTable");
                }
                catch( Exception ex )
                {
                    writeLog(ex.Message);
                }
                finally
                {
                    command.Dispose();
                    connection.Dispose();
                }
            }
            public void writeLog(string str)
            {
                System.IO.StreamWriter streamWriter = File.AppendText(Application.ExecutablePath + DateTime.Now.ToString("ddMMyyyy").ToString() + "log.txt");
                streamWriter.WriteLine(DateTime.Now + ": " + str);
                streamWriter.Close();
                streamWriter.Dispose();
            }
        #endregion

    }
}
Install the Windows Service
Windows Services are different than normal Windows based applications. It is not possible to run a Windows Service by simply running an EXE. The Windows Service should be installed by using the InstallUtil.exe provided with the .NET Framework or through a deployment project such as a Microsoft Installer (MSI) file.
Add an Installer
Having created the Windows Service will not be enough for the InstallUtil program to be able to install the service. You must also add an Installer to your Windows Service so that the InstallUtil, or any other installation program, knows what configuration settings to apply to your service.
  1. Switch to the design view for the service
  2. Right click and select Add Installer
  3. Switch to the design view of the ProjectInstaller that is added
  4. Set the properties of the serviceInstaller1 component
    1. ServiceName = My Sample Service
    2. StartType = Automatic
  5. Set the properties of the serviceProcessInstaller1 component
    1. Account = LocalSystem
  6. Build the Solution
The following code contained in the ProjectInstaller.cs source file was automatically generated by Visual Studio after having completed the steps above.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;


namespace TestWS
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }
    }
}
Use InstallUtil to Install the Windows Service
Now that the service has been built you need to install it for use. The following instructions will guide you in installing your new service.
  1. Open a Visual Studio .NET Command Prompt
  2. Locate exe file in bin directory.
  3. Issue the command InstallUtil.exe TestWs.exe to register the service and have it create the appropriate registry entries.
InstallUtil /  i [Path of the exe]
  1. In the Services section underneath Services and Applications you should now see your Windows Service included in the list of services.
Click Run and type “services.msc” then enter
  1. Start your service by right clicking on it and selecting Start
Each time you need to change your Windows Service it will require you to uninstall and reinstall the service. Prior to uninstalling the service it is a good idea to make sure you have the Services management console closed. If you do not you may have difficulty uninstalling and reinstalling the Windows Service. To uninstall the service simply reissue the same InstallUtil command used to register the service and add the /u command switch.
InstallUtil /  u  [Path of the exe]

Debug the Windows Service
As with all other aspects, debugging a Windows Service is different than a normal application. More steps are required to debug a Windows Service. The service cannot be debugged by simply executing it in the development environment as you can with a normal application. The service must first be installed and started, which we covered in the previous section. Once it is started you attach Visual Studio to the running process in order to step through and debug the code. Remember, each change you make to the Windows Service will require you to uninstall and reinstall the service.
Attach to a Running Windows Service
Here are the directions for attaching to a Windows Service in order to debug the application. These instructions assume that you have already installed the Windows Service and it is currently running.
  1. Load the project into Visual Studio
  2. Click on the Debug menu
  3. Click on the Processes menu item
  4. Make sure the Show system processes is selected
  5. Locate your process in the Available Processes list based on the name of your executable and click on it
  6. Click the Attach button
  7. Click OK
  8. Click Close
  9. Set a break point in the timer1_Elapsed method and wait for it to execute
Summary
You should now have a rough idea of what windows services are, how to create, install, and debug them. There is additional functionality with Windows Services that you can explore. This functionality includes the capability to pause (OnPause) and resume (OnContinue). The ability to pause and resume are not enabled by default and are setup through the Windows Service properties.

No comments:

Post a Comment