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:

<a href="http://msdn.microsoft.com/downloads/";>http://msdn.microsoft.com/downloads/<;/a>
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 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 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 element shown in Listing 3 into your web.config file. It goes after the element but before the <system.web> element.

Next you create the element as you defined in your

shown in Listing 3. The element will contain one or more 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 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 element for the Email publisher as shown below.

<!-- Publishes to EMail -->
<publisher mode="on" assembly="ErrorCommon"
type="ErrorCommon.EMeMail"
FromEMail="<a href="mailto://Webmaster@pdsa.com">Webmaster@pdsa.com</a>"
ToEMail="<a href="mailto://PSheriff@pdsa.com">PSheriff@pdsa.com</a>"
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.

Listing 1: Call the Publish method to handle all your exceptions

Try
' Some code here
Catch exp As Exception
ExceptionManager.Publish(exp)
' Any other code goes here
End Try

Listing 2: The exception management log holds some great information for a developer

General Information
*********************************************
Additional Info:
ExceptionManager.MachineName: PDSATOSHIBA5
ExceptionManager.TimeStamp: 8/8/2002 7:34:41 PM
ExceptionManager.FullName:
Microsoft.ApplicationBlocks.ExceptionManagement,
Version=1.0.936.22735, Culture=neutral,
PublicKeyToken=null
ExceptionManager.AppDomainName:
/LM/w3svc/1/root/Temp/WebArch-6-126733340751540176
ExceptionManager.ThreadIdentity:
ExceptionManager.WindowsIdentity: PDSATOSHIBA5\ASPNET
1) Exception Information
*********************************************
Exception Type: System.Data.SqlClient.SqlException
Errors: System.Data.SqlClient.SqlErrorCollection
Class: 16
LineNumber: 1
Message: Invalid object name 'Prodcts'.
Number: 208
Procedure:
Server: PDSATOSHIBA5
State: 1
Source: .Net SqlClient Data Provider
TargetSite: System.Data.SqlClient.SqlDataReader
ExecuteReader(System.Data.CommandBehavior,
System.Data.SqlClient.RunBehavior, Boolean)
HelpLink: NULL
StackTrace Information
*********************************************
at System.Data.SqlClient.SqlCommand.ExecuteReader
(CommandBehavior cmdBehavior, RunBehavior runBehavior,
Boolean returnStream)
at System.Data.SqlClient.SqlCommand.System.Data.IDbCommand.
ExecuteReader(CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(Object data,
Int32 startRecord, Int32 maxRecords, String srcTable,
IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet
dataSet, Int32 startRecord, Int32 maxRecords, String
srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet
dataSet)
at Microsoft.ApplicationBlocks.Data.SqlHelper.
ExecuteDataset(SqlConnection connection, CommandType
commandType, String commandText, SqlParameter[]
commandParameters) in D:\Microsoft Application Blocks
for .NET\Data Access\Code\VB\Microsoft.
ApplicationBlocks.Data\SQLHelper.vb:line 462
at Microsoft.ApplicationBlocks.Data.SqlHelper.
ExecuteDataset(String connectionString, CommandType
commandType, String commandText, SqlParameter[]
commandParameters) in D:\Microsoft Application Blocks
for .NET\Data Access\Code\VB\Microsoft.
ApplicationBlocks.Data\SQLHelper.vb:line 381
at Microsoft.ApplicationBlocks.Data.SqlHelper.
ExecuteDataset(String connectionString, CommandType
commandType, String commandText) in D:\Microsoft
Application Blocks for .NET\Data Access\Code\VB\
Microsoft.ApplicationBlocks.Data\SQLHelper.vb:line 358
at WebArch.WebForm1.GridLoad() in
D:\Temp\WebArch\<a href="http://WebForm1.aspx.vb">WebForm1.aspx.vb</a>:line 35.

Listing 3: Create a element to inform the .NET Framework that you have some special handler classes for certain elements within the config file

<configSections>
<section name="exceptionManagement"
type="Microsoft.ApplicationBlocks.ExceptionManagement. _
ExceptionManagerSectionHandler, Microsoft. _
ApplicationBlocks.ExceptionManagement" />
</configSections>

Listing 4: Inform the EAAB of new publishers by adding elements to the element in your configuration file for your application

<exceptionManagement>
<!-- Default Publisher -->
<!-- NOTE: logName is name of app,
applicationName is name of Log -->
<publisher mode="off" logName="ExceptionSample"
applicationName="Application"
assembly="Microsoft.ApplicationBlocks.
ExceptionManagement"
type="Microsoft.ApplicationBlocks.ExceptionManagement. _
DefaultPublisher" />
<!-- Publishes to SQL Server -->
<publisher mode="on" assembly="ErrorCommon"
type="ErrorCommon.EMSQL"
SQLConnect="Server=localhost;Database=Northwind;
uid=sa;pwd=sa" />
<!-- Publishes to E-Mail -->
<publisher mode="on" assembly="ErrorCommon"
type="ErrorCommon.EMeMail"
FromEMail="<a href="mailto://Webmaster@pdsa.com">Webmaster@pdsa.com</a>"
ToEMail="<a href="mailto://PSheriff@pdsa.com">PSheriff@pdsa.com</a>"
Subject="Exception from VB.NET Application" />
</exceptionManagement>

Listing 5: Calling the ExceptionManager class can be enchanced by passing additional information in the form of a NameValueCollection object

Private Sub ExceptionSample()
Dim ds As New DataSet()
Dim strSQL As String
strSQL = "SELECT * FROM Prodcts"
Try
ds = SqlHelper.ExecuteDataset(conCONNECT, _
CommandType.Text, strSQL)
' Do something with the DataSet
Catch exp As Exception
ExceptionManager.Publish(exp, _
ErrorCommon.EMInfo.AdditionalInfo( _
"frmMain", "ExceptionSample"))
MessageBox.Show(exp.Message)
End Try
End Sub

Listing 6: Build a NameValueCollection object to pass any additional information you want logged to the Exception Manager class

Public Class EMInfo
Public Shared Function AdditionalInfo( _
ByVal FormName As String, _
ByVal ApplicationName As String) As _
System.Collections.Specialized.NameValueCollection
Dim nvc As New _
System.Collections.Specialized.NameValueCollection()
nvc.Add("FormName", FormName)
nvc.Add("ApplicationName", ApplicationName)
Return nvc
End Function
End Class

Listing 7: Creating an exception publisher is very straightforward

Imports Microsoft.ApplicationBlocks.Data
Imports Microsoft.ApplicationBlocks. _
ExceptionManagement
Imports System.Collections.Specialized
Public Class EMSQL
Implements IExceptionPublisher
Public Sub Publish(ByVal exception As Exception, _
ByVal additionalInfo As NameValueCollection, _
ByVal configSettings As NameValueCollection) _
Implements IExceptionPublisher.Publish
Dim strConn As String
Dim strSQL As String
Dim strFormName As String
Dim strAppName As String
If Not (AdditionalInfo Is Nothing) Then
' Process Additional Info
With AdditionalInfo
strFormName = .Item("FormName")
strAppName = .Item("ApplicationName")
End With
End If
If Not (configSettings Is Nothing) Then
' Retrieve Attributes from Config File
strConn = configSettings.Item("SQLConnect")
End If
strSQL = "INSERT INTO ErrorLog("
strSQL &= "szUser_nm, szForm_nm, "
strSQL &= "dtError_dt, szAppl_nm, szError_tx )"
strSQL &= " VALUES('{0}', '{1}', '{2}', '{3}', '{4}')"
strSQL = String.Format(strSQL, _
System.Security.Principal.WindowsIdentity. _
GetCurrent.Name, _
strFormName, Now(), _
strAppName, _
Replace(Exception.ToString(), "'", "''"))
Try
SqlHelper.ExecuteNonQuery(strConn, _
CommandType.Text, strSQL)
Catch exp As Exception
' Log error from Exception Manager
' into Application Event Log
Throw exp
End Try
End Sub
End Class

Listing 8: The ErrorLog table

CREATE TABLE ErrorLog
(
lError_id int IDENTITY (1, 1) NOT NULL PRIMARY KEY,
szUser_nm varchar(50) NULL,
szForm_nm varchar(50) NULL,
dtError_dt datetime NULL,
szAppl_nm varchar(50) NULL,
szError_tx varchar(2500) NULL
)
GO

Listing 9: Use the SmtpMail object in .NET to send an e-mail when an exception occurs

Imports Microsoft.ApplicationBlocks.Data
Imports Microsoft.ApplicationBlocks. _
ExceptionManagement
Imports System.Collections.Specialized
Imports System.Web.Mail
Public Class EMeMail
Implements IExceptionPublisher
Public Sub Publish(ByVal exception As Exception, _
ByVal additionalInfo As NameValueCollection, _
ByVal configSettings As NameValueCollection) _
Implements IExceptionPublisher.Publish
Dim strFromEmail As String
Dim strToEmail As String
Dim strSubject As String
Dim strFormName As String
Dim strAppName As String
If Not (additionalInfo Is Nothing) Then
' Retrieve Additional Info
With additionalInfo
strFormName = .Item("FormName")
strAppName = .Item("ApplicationName")
End With
End If
If Not (configSettings Is Nothing) Then
' Retrieve Attributes from Config File
With configSettings
strFromEmail = .Item("FromEMail")
strToEmail = .Item("ToEMail")
strSubject = .Item("Subject")
End With
End If
strSubject &= " - " & strFormName & _
" - " & strAppName
Try
' Send Exception via Email
SmtpMail.SmtpServer = "127.0.0.1"
SmtpMail.Send(strFromEmail, strToEmail, _
strSubject, exception.ToString())
Catch exp As Exception
' Log error from Exception Manager
' into Application Event Log
Throw exp
End Try
End Sub
End Class