using System;
using System.ServiceProcess;
namespace WeatherService.Framework
{
///
/// A generic Windows Service that can handle any assembly that
/// implements IWindowsService (including AbstractWindowsService)
///
public partial class WindowsServiceHarness : ServiceBase
{
///
/// Get the class implementing the windows service
///
public IWindowsService ServiceImplementation { get; private set; }
///
/// Constructor a generic windows service from the given class
///
/// Service implementation.
public WindowsServiceHarness(IWindowsService serviceImplementation)
{
// make sure service passed in is valid
if (serviceImplementation == null)
{
throw new ArgumentNullException("serviceImplementation",
"IWindowsService cannot be null in call to GenericWindowsService");
}
// set instance and backward instance
ServiceImplementation = serviceImplementation;
// configure our service
ConfigureServiceFromAttributes(serviceImplementation);
}
///
/// Override service control on continue
///
protected override void OnContinue()
{
// perform class specific behavior
ServiceImplementation.OnContinue();
}
///
/// Called when service is paused
///
protected override void OnPause()
{
// perform class specific behavior
ServiceImplementation.OnPause();
}
///
/// Called when a custom command is requested
///
/// Id of custom command
protected override void OnCustomCommand(int command)
{
// perform class specific behavior
ServiceImplementation.OnCustomCommand(command);
}
///
/// Called when the Operating System is shutting down
///
protected override void OnShutdown()
{
// perform class specific behavior
ServiceImplementation.OnShutdown();
}
///
/// Called when service is requested to start
///
/// The startup arguments array.
protected override void OnStart(string[] args)
{
ServiceImplementation.OnStart(args);
}
///
/// Called when service is requested to stop
///
protected override void OnStop()
{
ServiceImplementation.OnStop();
}
///
/// Set configuration data
///
/// The service with configuration settings.
private void ConfigureServiceFromAttributes(IWindowsService serviceImplementation)
{
var attribute = serviceImplementation.GetType().GetAttribute();
if (attribute != null)
{
// wire up the event log source, if provided
if (!string.IsNullOrWhiteSpace(attribute.EventLogSource))
{
// assign to the base service's EventLog property for auto-log events.
EventLog.Source = attribute.EventLogSource;
}
CanStop = attribute.CanStop;
CanPauseAndContinue = attribute.CanPauseAndContinue;
CanShutdown = attribute.CanShutdown;
// we don't handle: laptop power change event
CanHandlePowerEvent = false;
// we don't handle: Term Services session event
CanHandleSessionChangeEvent = false;
// always auto-event-log
AutoLog = true;
}
else
{
throw new InvalidOperationException(
string.Format("IWindowsService implementer {0} must have a WindowsServiceAttribute.",
serviceImplementation.GetType().FullName));
}
}
}
}