Tuesday, November 3, 2009

Systems Diagnostics

For some reason, this is one of those topics I've really dreaded about the exam. I guess it's because most of my .NET Development has been done on ASP.NET, using log4net for my logging.

Consequently, I've tended to stay away from the Systems.Diagnostic (the stuff that writes to the Windows Event Log).

Ah, well, this is a good time to learn it, since the exam covers it.

Here is a test program I wrote to use the System.Diagnostic.EventLog, as well as System.Diagnostic.Debug.


using System;
using System.Diagnostics;

namespace Diagnostics
{
class Program
{
static void Main(string[] args)
{
String applicationEventSource = "Test Diagnostic Application";
if (!EventLog.SourceExists(applicationEventSource))
{
EventLog.CreateEventSource(applicationEventSource, "Application");
}

// Use static method to write an entry. Default EventLogEntryType is Information
EventLog.WriteEntry(applicationEventSource, "Hello, world!");

// Try using instance-specific methods to write a test error
EventLog eventLog = new EventLog("Application");
eventLog.Source = applicationEventSource;
eventLog.WriteEntry("Test error", EventLogEntryType.Error);

// Test debug
Debug.Listeners.Add(new ConsoleTraceListener());
String testString = "Company";
Debug.WriteLine("Test");
Debug.WriteLineIf(testString != "My Company", "Incorrect Company");
Console.ReadKey();
}
}
}

No comments:

Post a Comment