December 15, 2012

.NET: Create EventSource in Windows Event Log (with Admin privileges on Windows7)

Problem
We had one project which logs exception and some system information to Windows Event log. We had to write all logs in appropriate EventSource (created only for our application in Application log). As you may know creating EventSource requires Administrative Privileges on Windows Vista and higher. For deployment we use ClickOnce which does not have such a functionality (i.e. to create event source).

In this article I want to describe solutions that we found, I think maybe most of them (but not all) are obviously for you, but I hope this article will be useful .

Resolving
This is what msdn says about EventSource creation (a full article):
To create an event source in Windows Vista and later or Windows Server 2003, you must have administrative privileges.
The reason for this requirement is that all event logs, including security, must be searched to determine whether the event source is unique. Starting with Windows Vista, users do not have permission to access the security log; therefore, a SecurityException is thrown.
In Windows Vista and later, User Account Control (UAC) determines the privileges of a user. If you are a member of the Built-in Administrators group, you are assigned two run-time access tokens: a standard user access token and an administrator access token. By default, you are in the standard user role. To execute the code that accesses the security log, you must first elevate your privileges from standard user to administrator. You can do this when you start an application by right-clicking the application icon and indicating that you want to run as an administrator.

We don't want to force users to run our application manually by administrator. And we don't want always to run our application with administrative privileges (automatically) to be sure that we can create EventSource whenever we need it.

You may ask: why always to run with admin privileges?
Because it is a standard Windows Vista security mechanism. On application startup Windows will analyze manifest and show 'run as administrator' UAC dialog to a user.
For more information about manifest file, run application with administrator privileges and others - you can read here.

I started to investigate this problem and found few solutions: