Good exception handling should be put into an application from the very beginning. The Microsoft Exception Management Application Block (EAAB) will allow you to write one line of code in all of your Catch blocks and this one line of code can be configured to call multiple classes to log errors in any way you see fit. The best part is you do not need to recompile your application; you simply have to provide a new DLL that contains these new exception classes.

Microsoft created a generic exception handling class that you can use in any Catch block in addition to any regular error handling code that you might perform. The code in Listing 1 provides you an example of how to use the Exception Management Application Block EAAB:

The Publish method is a shared method of the ExceptionManager class. You pass to it the Exception object that you created in your Catch statement. By default the Publish method will call a routine that Microsoft has already written to put exception information into the Event Log. You may add entries to your application configuration file to override this default behavior. You'll learn how to override the default later in this article.

Benefits of the Exception Manager Class

You can get many benefits from using the Exception Management Application Block.

Consistent interface for handling errorsOne routine that you need to work withCan place exception publishers into separate componentEasily add new exception publishersAdd publishers without changing any code in your application

Getting and Installing the Exception Manager

You can download the Microsoft Exception Management Application Block for Free!

To get the Exception Manager components you need to download the MSI installation package from Microsoft's Web site. You may perform a search at http://msdn.microsoft.com for "Exception Management Application Block" or navigate directly to the following URL:

http://msdn.microsoft.com/downloads/
default.asp?URL=/downloads/sample.asp?url=/
MSDN-FILES/027/001/943/msdncompositedoc.xml

After you download the MSI file, double-click it to install the EAAB. The installation creates a folder on your hard drive, installs the samples, the source code for the component, the help files, and creates an item within your Programs folder so you can access the samples and help from your Start menu. Since this is a .NET component there are no registry entries or anything else that is installed that will affect your Windows system.

Compile the EAAB

Before you can use the EAAB you need to compile the source code. Microsoft does not supply a DLL with the installation. Open your Start | Programs menu and find the Microsoft Application Blocks for .NET | Exception Management | Source Code (VB) menu. Choose the Exception Management Application Block source code and VS.NET will load the VB.NET source code for you to compile. (You could also choose the C# source code as well, since Microsoft supplies both.) VB.NET loads two projects within this solution. One project supplies the interfaces that the classes will implement within the other project, and that you will implement when you create custom publishers. The other project contains several classes that help implement the Exception Management Application Block.

Select Build | Build Solution from the VS.NET menu and a Bin folder will be created under the folder where you installed the EAAB. Within this BIN folder you will find two DLLs:

Microsoft.ApplicationBlocks.ExceptionManagement
.dll
Microsoft.ApplicationBlocks.ExceptionManagement
.Interfaces.dll

You will need to include both of these as references within any project in which you wish to use the EAAB.

Overview of Exception Management

When you call ExceptionManager.Publish, this method does not actually write the exception data to anywhere. ExceptionManager.Publish calls the classes that are defined in your application's configuration file (Web.Config in ASP.NET or your applications *.config file). Figure 1 shows a graphical decision tree that describes the process the ExceptionManager.Publish method employs to log errors.

Figure 1: Exception Management is very flexible through the use of the Config file. ##Exceptions_Fig1.jpg##

After it calls the Publish method the EAAB will check to see if there is an <exceptionManagement> entry in your configuration file. If not, it calls the default publisher to log information about the exception into the machine's Application Event Log.

If an <exceptionManagement> entry exists in your configuration file, EAAB reads this information, invokes the classes identified as exception publishers one by one, and passes the exception information to each one. In this manner you can add new entries to your configuration file, create a new class to handle an exception, and you can thus add publishers at any time!

Example of a Log Entry

When the default publisher of the EAAB logs an error into the log file, it not only records the exception information but it also gathers additional information such as the MachineName, the date and time, the full name of the exception manager that entered the data, the application domain name (in the case of a Web application), the Thread Identity (if any), and the WindowsIdentity of the Windows account the process is running under. Listing 2 shows an example error from a Web application running on my local machine. I purposely misnamed a table in an SQL statement and then attempted to fill a DataReader from that table.

Setting Up Your Config File

To inform the EAAB of your intentions to use different publishers you will enter information into your application's configuration file. To develop an ASP.NET Web application you will enter the <configSections> element shown in Listing 3 into your web.config file. It goes after the <configuration> element but before the <system.web> element.

Next you create the <exceptionManagement> element as you defined in your <section name...> shown in Listing 3. The <exceptionManagement> element will contain one or more <publisher> elements. Each of the different publishers can contain many different attributes. Some of the attributes mean something to the exception management classes or you can add your own custom attributes that you can read from the element once you are within your own custom publisher. Listing 4 shows you three different publishers defined within the <exceptionManagement> element. First you have the Default publisher, next you have a publisher that writes to a SQL Server table, and then you have a publisher that will publish to a specified e-mail address.

Each publisher has a Mode attribute that can have a value of either "on" or "off", allowing you to turn each of the publishers on or off as you need.

Passing Additional Information

The ExceptionManager class allows you to pass a NameValueCollection object as an additional parameter to the Publish method. Inside NameValueCollection you will create name/value pairs. A NameValueCollection object is a keyed-pair collection of values. You can place anything you want into this object.

To help you create Name/Value pairs you might want to create a class with a Shared method into which you pass as many arguments as you wish. This method can create name/value pairs out of each of these arguments. Listing 5 shows an example of calling a class named EMInfo to create these name/value pairs.

The EMInfo Class

The EMInfo class has one method named AdditionalInfo that accepts two parameters: FormName and ApplicationName. The System.Collections.Specialized namespace initializes a new NameValueCollection object and then adds each of the arguments to the collection using the Add method as you can see in Listing 6.

You can add additional arguments to this method by simply adding the new arguments then using the Add method on the NameValueCollection object to insert them into the collection.

Logging Errors Into a Database

A Log entry is nice to have but I prefer placing exception information into a database like SQL Server. You get a couple of great benefits when you place errors into a database.

You can centralize all of your exceptions. In the case of a Web farm you don't want the exceptions from different machines in different registries. If you log to a database, all servers in your Web farm can write to just one place.You can create a Web page to look up all the errors from anywhere on the Internet. You do not need to physically be on the machine where the event log resides to view your errors.

Creating an Exception Publisher

The Exception Management Application Block gives you an interface that you can implement to create your own publisher?a great benefit! Listing 7 shows the class you would create to implement the IExceptionPublisher interface. This class, called EMSQL, will log exceptions to a SQL Server database table.

In the above class you need to create a Publish method that implements the IExceptionPublisher.Publish interface. This interface requires you to accept an Exception object and two NameValueCollection parameters. The Exception object is the same object you pass from your front-end application. The NameValueCollection named additionalInfo will contain any NameValueCollection you pass such as the one you created earlier using the EMInfo class. The last argument, configSettings, is passed from the ExceptionManager class and is the XML from the web.config file that defines this publisher.

Consider the following XML that you would place into your configuration file to have the ExceptionManager call the EMSQL class's Publish method.

<!-- Publishes to SQL Server -->
<publisher mode="on" assembly="ErrorCommon"
  type="ErrorCommon.EMSQL"
  SQLConnect="Server=localhost;
     Database=Northwind;uid=sa;pwd=sa" />

This XML has four attributes: mode, assembly, type, and SQLConnect. The configSettings argument contains a name/value pair for each one of these attributes. To retrieve the SQLConnect value you would write code like the following:

strConn = configSettings.Item("SQLConnect")

You can add any attributes that you want for your publisher and then retrieve them using the Item property of the configSettings object.

After you retrieve any additional information items and your configuration file settings you can write additional code to do what you want with all of this data. In the Publish method of the EMSQL class you will write a record into a SQL Server database using the Microsoft Data Access Application Block SqlHelper class.

The ErrorLog Table

The ErrorLog table, Listing 8, used in the EMSQL class has just a few fields. However, you could add additional information by adding arguments to the AdditionalInfo method of the EMInfo class and then passing them to your INSERT statement within your EMSQL class.

Publishing Errors via E-mail

Publishing exceptions by sending them to a specific e-mail address is very similar to publishing them to a database. You create an entry in your configuration file that identifies which class to call and then you will write that class and implement the Publish method according to the IExceptionPublisher interface. Listing 9 shows an example of a class that will send any errors via e-mail.

The code in the Publish method of the EMeMail class is passed the configuration information in the configSettings object. This object contains the name/value pairs that come from the configuration file for your application. If you remember from the beginning of this article, you added the attributes FromEMail, ToEMail and Subject to the <publisher> element for the Email publisher as shown below.

<!-- Publishes to EMail -->
<publisher mode="on" assembly="ErrorCommon"
  type="ErrorCommon.EMeMail"
  FromEMail="Webmaster@pdsa.com"
  ToEMail="PSheriff@pdsa.com"
  Subject="Exception from VB.NET Application" />

The Publish method uses these attributes, the form name and application name passed in the additional info, and the exception object information to send an e-mail to the appropriate person about the exception that has occurred in this application.

Summary

Good exception tracking can really help developers after the application is deployed. Many users neglect to report errors back to the programmer. By creating a logging mechanism programmers can look up any and all errors without relying on the user. Microsoft supplies the Exception Management Application Block as a free download on their Web site. The ExceptionManager class will publish exceptions to the Event Log by default. Using a combination of web.config entries and your own custom classes that define a specific interface you can create your own publishers in a matter of minutes.