Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
NET
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.
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.
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.
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.
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();
}
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();
}
}
}
}
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.
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.ComponentModel;
using System.Configuration.Install;
namespace CodeGuru.MyWindowsService
{
/// <summary>
/// Summary description for ProjectInstaller.
/// </summary>
[RunInstaller(true)]
public class ProjectInstaller :
System.Configuration.Install.Installer
{
private System.ServiceProcess.ServiceProcessInstaller
serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller serviceInstaller1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public ProjectInstaller()
{
// This call is required by the Designer.
InitializeComponent();
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.
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.
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.
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.