I have developed a Windows service in C#. I have created a installer with Visual Studio 2008, which installs the Windows service. Everything is good so far. I want to make sure that the event source has been created at install time, so that any error/exception conditions at runtime are correctly logged to the Windows event log.
Does the event source get automatically created (and removed) as part of the windows service installation (and uninstallation), or do I have to handle this myself and create a custom action to create and delete it as follows?
protected override void OnBeforeInstall(IDictionary savedState)
{
base.OnBeforeInstall(savedState);
if (!EventLog.SourceExists(ServiceName))
EventLog.CreateEventSource(ServiceName, "Application");
}
protected override void OnAfterUninstall(IDictionary savedState)
{
base.OnAfterInstall(savedState);
if (EventLog.SourceExists(ServiceName))
EventLog.DeleteEventSource(ServiceName);
}
It appears to me like the ServiceInstaller
automatically creates a DataSource during installation with the same name as the service, so there's no need for any extra code.
From the ServiceInstaller documentation
When the installation is performed, it automatically creates an EventLogInstaller to install the event log source associated with the ServiceBase derived class. The Log property for this source is set by the ServiceInstaller constructor to the computer's Application log. When you set the ServiceName of the ServiceInstaller (which should be identical to the ServiceBase..::.ServiceName of the service), the Source is automatically set to the same value. In an installation failure, the source's installation is rolled-back along with previously installed services.