Create Windows Services in the .Net Framework
By Douglas Reilly, May 01, 2002
One of the unsung heroes in the success of Microsoft 2000 is the ability to run applications as services, and now, as Douglas shows us, the .Net Framework makes creating a Windows Service much easier.
Create Windows Services in the .Net Framework
Example 1:
The main source module for SqlServiceMonitor
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
namespace SqlMonitorService
{
public class SqlMonitorService :
System.ServiceProcess.ServiceBase
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private bool m_IsRunning=false;
private MonitorThread monitorThread = null;
public SqlMonitorService()
{
// This call is required by the Windows.Forms
// Component Designer.
InitializeComponent();
// TODO: Add any initialization after the
// InitComponent call
monitorThread = new MonitorThread();
monitorThread.ServerName="Dell933";
monitorThread.DatabaseName="TEST";
monitorThread.SQLUser="sa";
monitorThread.SQLPassword="badpassword";
monitorThread.interval=120;
monitorThread.eventSource="SqlServiceMonitor";
}
// The main entry point for the process
static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new
System.ServiceProcess.ServiceBase[] {
new SqlMonitorService() };
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()
{
//
// SqlMonitorService
//
this.ServiceName = "SqlServiceMonitor";
}
/// <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)
{
// Create the thread object, passing in the
// monitorThread.workerThread method
// using a ThreadStart delegate.
Thread InstanceCaller =
new Thread(
new ThreadStart(
monitorThread.workerThread)
);
IsRunning=true;
// Start the thread.
InstanceCaller.Start();
}
/// <summary>
/// Stop this service.
/// </summary>
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down
// necessary to stop your service.
IsRunning=false;
}
/// <summary>
/// Used to trigger service stop
/// </summary>
public bool IsRunning
{
get
{
return m_IsRunning;
}
set
{
m_IsRunning=value;
monitorThread.IsRunning=value;
}
}
}
class MonitorThread
{
public bool IsRunning = false;
public string ServerName;
public string DatabaseName;
public string SQLUser;
public string SQLPassword;
public string eventSource;
public int interval;
public void onSuccess(string message)
{
if (!EventLog.SourceExists(eventSource))
{
EventLog.CreateEventSource(eventSource,"Application");
}
EventLog MyLog=new EventLog();
MyLog.Source=eventSource;
MyLog.WriteEntry(
message,System.Diagnostics.EventLogEntryType.Information);
}
public void onFailure(string message)
{
if (!EventLog.SourceExists(eventSource))
{
EventLog.CreateEventSource(eventSource,"Application");
}
EventLog MyLog=new EventLog();
MyLog.Source=eventSource;
MyLog.WriteEntry(
message,System.Diagnostics.EventLogEntryType.Error);
}
public void workerThread()
{
int Seconds;
string SqlString;
string message;
System.Data.SqlClient.SqlConnection cn;
while ( IsRunning )
{
// While being responsive, wait interval seconds...
// Alternatives: Use Mutex or some other
// object, and do wait with timeout for
// longer period...
Seconds=0;
while ( IsRunning && Seconds<(interval) )
{
System.Threading.Thread.Sleep(1000);
Seconds++;
}
// We waited interval seconds, now see if we can connect...
SqlString="User ID="+SQLUser+";Pwd="+SQLPassword+";
Initial Catalog="+DatabaseName+";Server="+ServerName;
try
{
cn=new SqlConnection(SqlString);
cn.Open();
message="Connection Successful!";
this.onSuccess(message);
}
catch ( System.Exception e)
{
ServiceController
sc=new ServiceController("MSSQLSERVER",ServerName);
try
{
message="SQL Server Service status on "+ServerName+
" is "+sc.Status.ToString();
}
catch ( System.Exception ex )
{
message=
"Cannot get status of SQL Server
Service! Exception: "+
ex.ToString();
}
message=message+"\nFailure: "+e.ToString();
this.onFailure(message);
}
}
}
}
}