Feb 25 2008

Your need permission to do that...

Category: Tips and TricksJoeGeeky @ 12:36

Here is a common mistake I see time and time again...  Creating EventSources for logging EventLog entries requires administrative rights on most systems.  These days the only time apps generally have the required permission is during the MSI installation process. It is during application installation that you want to register EventLog Event Sources, because doing this at runtime can often lead to SecurityExceptions.  The mechanism to accomplish this is a custom Installer class.  This is pretty easy to implement and can open the door to solutions to other such problems (e.x. Installing Performance Counters, WMI registration, etc...).  Here is a sample:

using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
/// <summary>
/// Facilitates the installation and 
/// deinstallation of Registry 
/// Logging Event Sources
/// in the Windows EventLog
/// </summary>
/// <remarks>
/// This is called by the Setup custom 
/// actions item for install and 
/// uninstall to perform required 
/// actions
/// </remarks>
[RunInstaller(true)]
public sealed class MyRegistryInstaller
    : Installer
{
    /// <summary>
    /// Establishes an application, using 
    /// the specified Source, as a valid 
    /// event source for writing entries 
    /// to a log on the local computer. 
    /// This method can also create a new 
    /// custom log on the local computer. 
    /// </summary>
    /// <param name="stateSaver">
    /// An IDictionary used to save 
    /// information needed to perform a 
    /// commit, rollback, or uninstall 
    /// operation.
    /// </param>
    public override void Install(IDictionary stateSaver)
    {
        base.Install(stateSaver);
        EventLog.CreateEventSource("MyEventSource", "Application");
        Context.LogMessage("Installed EventLog Source");
    }
    /// <summary>
    /// Removes the event source 
    /// registration from the event log 
    /// of the local computer.
    /// </summary>
    /// <param name="savedState">
    /// An IDictionary used to save 
    /// information needed to perform a 
    /// commit, rollback, or uninstall 
    /// operation.
    /// </param>
    public override void Uninstall(IDictionary savedState)
    {
        base.Uninstall(savedState);
        if (EventLog.SourceExists("MyEventSource"))
            EventLog.DeleteEventSource("MyEventSource");
        Context.LogMessage("EventLog Source uninstalled");
    }
}

Tags: