Wednesday, October 27, 2010

EventLog.WriteEntry from a ASP.NET page

The page is run as NETWORK SERVICE. I would not ask you to either change it to LOCAL SYSTEM, or put NETWORK SERVICE to the administrator group.
The later sounds quite stupid. But a colleague of mine did find somebody proposing it as a solution on the net.

The simplest code fragment that you would find at many places on the net should look like the following. I too found it on the net.
protected void Page_Load(object sender, EventArgs e)
{
// Create the source, if it does not already exist.
if (!EventLog.SourceExists("hoge"))
{
//An event log source should not be created and immediately used.
//There is a latency time to enable the source, it should be created
//prior to executing the application that uses the source.
//Execute this sample a second time to use the new source.
EventLog.CreateEventSource("hoge", "Application");
// The source is created. Exit the application to allow it to be registered.
return;
}

// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "hoge";

// Write an informational entry to the event log.
myLog.WriteEntry("hello world.");
return;
}

This would not run as NETWORK SERVICE. However, there is actually only one instruction that cannot be performed with NETWORK SERVICE privilege. It is the “CreateEventSource()”. The instruction to actually write an event, WriteEntry(), runs with no problem.
Since CreateEventSource() needs to run only once, you either take it out and run in a separate console app, or runs the above code only once as LOCAL SYSTEM then change it back to NETWORK SERVICE immediately after that.