Custom Exceptions using Microsoft Exception Management Application Block

The Microsoft Exception Management Application Block provides a very simple framework for handling exceptions. It also provides the Interface to implement custom exception to log the error in different Data sources like

  1. Text File
  2. Alert to Pager
  3. MSMQ
  4. Data base
  5. Email Notification

In both Text and XML format based on from which interface you are Inheriting from IExceptionPublisher, ExceptionXmlPublisher respectively.

To create a custom exception publisher, you must create a class that implements either the IExceptionPublisher or the IExceptionXmlPublisher interface defined within the Microsoft.ApplicationBlocks.ExceptionManagement.Interfaces.dll assembly.

This Exception Management Application Block, which writes default exception details to the Windows Event Log, suppose If you want to receive exception details in XML format, implement ExceptionXmlPublisher, otherwise implement IExceptionPublisher. Each interface includes a single method called Publish, through which you receive exception details together with other optional configuration settings and custom attributes.

Advantages

With a single line of code you can easily log exception details information into the windows System Event Log or you can create custom publisher extending or creating a class from ExceptionXmlPublisher or IExceptionPublisher this will log exception details to other data sources [above mentioned]

This Exception Management Application Block is a simple framework that can easily used as any .NET application. When we use this, we will reduce the error handling code as well as make it more efficient way of error handling in our application and we will also make our application more robust and easier to debug. And also this helps the following way Manage exceptions in an efficient and consistent way. It isolates exception management code from business logic code and log exceptions with a minimal amount of custom code.

Here is the Implementation of Custom Exceptions Publisher using Exception Publisher.

This will store the Exception Details in Text Format

using
System;
using
System.Text;
using
System.IO;
using
System.Web.Mail ;
using
System.Collections.Specialized;
using
Microsoft.ApplicationBlocks.ExceptionManagement ;
namespace
CustomExceptionManagement
{
///
<summary>
///
Summary description for Class1.
///
</summary>
public class
ExceptionPublisher :IExceptionPublisher
{
public
ExceptionPublisher()
{
}
private string
_LogFileName = @"C:\DCWeatherErrorLog.txt";
private string
_OpMail = "";
void
IExceptionPublisher.Publish(Exception exception, NameValueCollection AdditionalInfo,NameValueCollection ConfigSettings)
{
// Load Config values if they are provided.
if (ConfigSettings != null
)
{
if (ConfigSettings["fileName"] != null
&& ConfigSettings["fileName"].Length > 0)
{
_LogFileName = ConfigSettings["fileName"];
}
if (ConfigSettings["operatorMail"] !=null
&& ConfigSettings["operatorMail"].Length >
0)
{
_OpMail = ConfigSettings["operatorMail"];
}
}
// Create StringBuilder to maintain publishing information.
StringBuilder errInfo = new
StringBuilder();
// Record the contents of the AdditionalInfo collection.
if (AdditionalInfo != null
)
{
errInfo.AppendFormat("{0}Exception From:", Environment.NewLine);
foreach (string i in
AdditionalInfo)
{
errInfo.AppendFormat("{0}{1}: {2}", Environment.NewLine, i, AdditionalInfo.Geti));
}
}
// Append the exception text
errInfo.AppendFormat("{0}{0}Exception Information{0}{1}", Environment.NewLine, exception.ToString());
// Write to the log file.
using
(StreamWriter sw = File.AppendText(_LogFileName))
{
sw.WriteLine(errInfo.ToString());
sw.WriteLine("----------------------------------");
}
// Email
if
(_OpMail.Length > 0)
{
string
subject = "Exception Notification";
string
body = errInfo.ToString();
SmtpMail.Send("[email protected]", _OpMail, subject, body);
}
}
}
}

OUTPUT

Exception From:ExceptionManager.MachineName: SEENRAMADURAI
ExceptionManager.TimeStamp: 8/21/2003 12:37:11 PM
ExceptionManager.FullName: Microsoft.ApplicationBlocks.ExceptionManagement,
Version=1.0.1242.22429,Culture=neutral, PublicKeyToken=null
ExceptionManager.AppDomainName: DCWeatherService.exe
ExceptionManager.ThreadIdentity:
ExceptionManager.WindowsIdentity: ITS\SRamadurai

Exception Information
System.Data.SqlClient.SqlException: Login failed for user 'dcuapp'.
at System.Data.SqlClient.ConnectionPool.GetConnection(Boolean& isInTransaction)
at System.Data.SqlClient.SqlConnectionPoolManager.GetPooledConnection
SqlConnectionString options,Boolean& isInTransaction)
at System.Data.SqlClient.SqlConnection.Open()
at DCWeatherService.Form1.GetZipCodes()in
d:\work\severobjects\dcweatherservice\form1.cs:line 244
----------------------------------

Here is the Implementation of Custom Exceptions Publisher using ExceptionXmlPublisher

This will store the Exception Details in XML Format

using
System;
using
System.Collections.Specialized;
using
System.IO;
using
System.Web.Mail ;
using
Microsoft.ApplicationBlocks.ExceptionManagement ;
using
System.Text;
using
System.Xml;
using
System.Configuration;
using
System.Messaging;
namespace
CustomExceptionManagement
{
///
<summary>
///
Summary description for ExceptionPublisherXML.
///
</summary>
public class
ExceptionXMLPublisher:IExceptionXmlPublisher
{
private string
_OpMail = "";
private string logFilePath=null
;
private string
msmqName=@".\ErrorLog";
public
ExceptionXMLPublisher()
{
logFilePath=ConfigurationSettings.AppSettings["LogFilePath"];
}
private static string
CurrentDateAndTimeInFileFormat()
{
string
CurrDate = DateTime.Now.ToString();
CurrDate= CurrDate.Replace('/','-');
return
CurrDate=CurrDate.Replace(':','.');
}
void
IExceptionXmlPublisher.Publish(XmlDocument ExceptionInfo, NameValueCollection ConfigSettings)
{
string
_LogFileName = @"C:\ErrorLog.xml";
if (ConfigSettings != null
)
{
if (ConfigSettings["operatorMail"] !=null
&& ConfigSettings["operatorMail"].Length > 0)
{
_OpMail = ConfigSettings["operatorMail"];
}
if (ConfigSettings["fileName"] != null
)
{
_LogFileName = ConfigSettings["fileName"];
_LogFileName=logFilePath+CurrentDateAndTimeInFileFormat()+_LogFileName;
}
}
//This code will check configfile Email options is exists to notify the Error
if
(_OpMail.Length > 0)
{
string
subject = "Exception Notification";
string
body = ExceptionInfo.OuterXml.ToString();
SmtpMail.Send("[email protected]", _OpMail, subject, body);
}

using
(StreamWriter sw = File.AppendText(_LogFileName))
{
sw.WriteLine(ExceptionInfo.OuterXml.ToString());
}
//This Code will check the QName in Configfile if exists then it will log the Error In MSMQ
if (ConfigSettings["QName"] != null
)
{
msmqName=ConfigSettings["QName"];
MessageQueue msmq=
new
MessageQueue(msmqName);
Message msg=
new
Message();
msg.Label= "DCWeather";
msg.Body =ExceptionInfo.OuterXml.ToString();
msmq.Send(msg);
}
}
}
}

XML Output

Calling the Custom Exception in Application Code

static void Main(string[] args)
{
try
{
int a=10;
int b=0;
int c=a/b;
}
catch ( Exception ex)
{
ExceptionManager.Publish(ex);
}
}

Configuring a Custom Publisher

After we creating a custom publisher component, we need to attach it with the Exception Manager. For this we use a .NET XML configuration file for Application. The following configuration file format shows how to configure the custom publisher.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<
configSections>
<
section name="exceptionManagement" type=
"Microsoft.ApplicationBlocks.ExceptionManagement.ExceptionManagerSectionHandler,Microsoft
.ApplicationBlocks.ExceptionManagement"
/>
</
configSections>
<exceptionManagement mode="on">
<
publisher assembly="CustomExceptionManagement"
type="CustomExceptionManagement.ExceptionPublisher"
operatorMail="[email protected]" />
<
publisher assembly="CustomExceptionManagement"
type="CustomExceptionManagement.ExceptionPublisher" fileName="c:\VZMoneyError.txt" />
<
publisher assembly="CustomExceptionManagement" type="CustomExceptionManagement.ExceptionXMLPublisher" exceptionFormat="xml" fileName="c:\VZMoneyError.XML" />
<
publisher assembly="CustomExceptionManagement" type="CustomExceptionManagement.ExceptionXMLPublisher" exceptionFormat="xml" operatorMail="[email protected]" />
<
publisher assembly="CustomExceptionManagement" type="CustomExceptionManagement.ExceptionXMLPublisher" exceptionFormat="xml" MSMQName=".\ErrorLogsQ" />
</
exceptionManagement>
</
configuration>


Similar Articles