Sukumar Raju's Blog

MCP

Sponsors

Tags

News



SharePoint SharePoint

More reading these days Patterns and practicces


Interesting to work with ASP.NET Membership provider

Suggested Reading C# Book


patterns & practices Application Architecture Guide 2.0


MVP Blog Badge.

Grab this badge here!


Enterprise Library 4.1 :: Exception Handling Application Block

The Exception Handling application block is designed to handle most common exception handling tasks in consistent approach. It allows changing exception handling after the application is deployed by using exception policies that are defined in the application configuration file. It offers the best practices for handling exceptions in .NET applications.

This article discusses Exception Handling application block configuration to implement consistent exception handling with in ASP.NET web application and logging the exceptions to windows events log using Logging application block.

Exception Policies

The policies define how certain exception types are handled by the Exception Handling Application block. A policy can have multiple exception types associated with it. Each exception type within the policy can have one or more exception handlers.

Step 1 Enterprise Library Configuration Tool

Enterprise Library configuration tool is installed with Enterprise Library to configure application blocks within the application. In order to configure Exception Application block start Enterprise Library configuration tool as shown in picture: 1 below; Right click the Web.config and choose Edit Enterprise Library configuration in context menu.

Note that if the configuration tool is not shown from Web.config context menu, it can be accessed from C:\Enterprise Library 4.1 HOL\Lib [Note that the path may change depending on your installation destination]. Name of the tool is EntLibConfig and the icon is same as the one below in context menu.

clip_image002

When you select Edit Enterprise Library Configuration on Context menu, configuration tool opens Webconfig as shown in below picture: 2 to configure Exception Application block

clip_image004

Step 2   Configuring application to log exceptions

The process of configuring this type of handler involves adding the exception handling application block to the configuration file, creating an exception policy, selecting an exception type, adding the logging handler and finally configuring the logging handler to log exceptions to windows events log as discussed below.

2.1   Add Exception Handling Application block

Using the configuration tool by selecting your application –> New option from context menu, add the Exception Handling Application Block as shown below.

clip_image006

2.2 Adding Exception policy

After creating exception application block, next step is to create an exception policy. Right click the exception handling application block and select New Exception Policy from context menu as shown below.

clip_image008

The new exception policy is named as exception policy by default. You can change the policy to your desired name by selecting Rename from context menu as shown below.

clip_image010

2.3 Adding the Exception Type

Next step in configuration is adding the exception type for this exception policy to handle. To add Exception Type right click the Exception Policy node and choose New Exception Type. This opens a Type selector window as show in below picture, in which you can select a known class that inherits from System.Exception.

Alternatively, you can click the Load an Assembly button to select a custom assembly that contains exception classes. In this example base class Exception is selected.

clip_image012

Step 3 Adding Logging Handler

After choosing the Exception Type, the next step is to configure Logging Application Block to log the exception to desired location. It is feasible to configure Logging Application Block to log the exceptions or other information to desired location such as

  •  The windows application event log
  •  An e-mail message
  •  A database
  •  A message queue
  •  A text file

Here Exception Application block using Logging Application block to log exceptions to windows events log.

3.1 Add Logging Handler

Right click Exception from context menu and choose New --> Logging Handler as shown below

clip_image014

Remember that a policy can have multiple exception types associated with it. Each exception type within the policy can have one or more exception handlers.

3.2 Configuring Logging Handler

Here I have explained the logging application block category that will be used to log exceptions. You can configure the Logging Handler by selecting properties window on right hand as shown below.

Properties

Note that you can change the category name from General to something meaningful, especially if there will be many types of logging events within your application.

The next step is to choose the Formatter Type. Click the button next to Formatter Type and choose the formatter as shown below.

clip_image018

The output of the TextExceptionFormatter will be simple name-value pairs of data. The output of the XMLExceptionFromatter will contain XML data that is placed in Message section of Log file.

Note that important settings you configure are EventId, Title, LogCategory and Severity as shown below.

clip_image020

That is it!!

You are ready to handle exceptions using best practice in consistent manner and log them using Logging application block.

Step 4 Logging Exceptions to application events

Here I have discussed how the exception is generated and logged to windows application events log using Exception handling policy ‘MyPolicy’ [Note that MyPolicy is the policy name declared in step 2.2 above].

clip_image022

Testing: Logged exception in Windows Application events log

Running the above code logs from ASP.NET Page Load event has logged an event to windows application events as shown below.

clip_image024

Step 5 Adding required Enterprise Library libraries and name spaces

The last part of the configuration is to make sure that you have added below out lined assemblies to your web application \bin folder by selecting Add Reference from context menu and using the required name spaces.

Assemblies

Exception Handling assembly

Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll

The core Logging Application Block assembly:-

  • Microsoft.Practices.EnterpriseLibrary.Logging.dll

Formats the exception and sends it to the Logging Application Block:-  

  •   Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.dll

Namespaces

  • using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
  • using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging;
  • using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;
  • using Microsoft.Practices.EnterpriseLibrary.Logging;

References:

Comments

http://ignou-student.blogspot.com said:

great article, thanks for posting this article.

# February 8, 2010 11:29 PM

Matt said:

Good article! We should be doing something like this to log our exceptions

# February 9, 2010 5:06 AM

developer said:

I am not a fan of enterprise library. It too havy and have little benefit. Use Log4Net instead

# February 10, 2010 8:46 AM

virender said:

great article,post more Enterprise Library articles

# February 10, 2010 9:50 AM

Bob said:

The best thing I have ever read...amazing!

# February 11, 2010 4:49 AM

Martinis said:

Да уж. А еще говорят, что мировой кризис по миру гялет...

# February 11, 2010 2:26 PM

Mikiliandgello said:

Вообще да, мне это напоминает ситуацию с выборами призидента Украины. Выборы прошли, а не факт, кто призедентом будет. Да, блин, демократия. Хех, простите за флуд небольшой, навеяло просто.

# February 12, 2010 8:52 AM

anouar said:

great article, please post more ones

# February 12, 2010 11:06 AM

Mikiliandgello said:

Вообще да, мне это напоминает ситуацию с выборами призидента Украины. Выборы прошли, а не факт, кто призедентом будет. Да, блин, демократия. Хех, простите за флуд небольшой, навеяло просто.

# February 12, 2010 1:35 PM

Breddipitti said:

Автор жжет, спасибо - интересная новость.

# February 14, 2010 3:40 AM

Werikusy said:

Хех, наконец-то Януковича официально короновали ,как думаете, комедия под названием выборы на Украине продолжится?

# February 14, 2010 3:49 PM

http://ignou-student.blogspot.com said:

great article i want to use it on my current .net project.

# February 14, 2010 11:46 PM

danimikanika said:

Очень интересная. глубокая мысль - заставило задуматься.

# February 15, 2010 7:04 AM

shrinath.net said:

It is not working for , can any one please help me

# March 2, 2010 5:33 AM

sukumarraju said:

Hi shrinath.net

Try to explain what is your current problem, so that further help can be provided.

what do you mean to say 'It is not working?' , try to elaborate.

Thanks

# March 2, 2010 3:34 PM

semimax said:

Hi there,

I have configured the enterprise library a/c to the second article but in which i have addded Divide by zero exception type also.. And then i tried to use it in my application but at the runtime it successfully catches divide by zero error however; when it's trying to execute that statement it gives me this exception i.e. "The exception policy 'Divide by Zero' couldn't be found" ..??

I dont know why it's coming?? :( can anyone help me out?

# April 8, 2010 3:26 AM

semimax said:

Resolved!! i wasn't passing the correct policy name.. that's it is giving error..

Thanks

# April 26, 2010 8:42 AM

sukumarraju said:

Thanks for all your response.  Have updated the article to elaborate in detail.

Your comments are appreciated to input more as required. Will be writing few more articles this weekend.

# July 30, 2010 6:13 PM

karthik said:

can u also please explain hoe to define our own exception formatter because i wnat to log only the exception message but not the entire stack trace

# August 19, 2010 10:10 AM

Vinod said:

Hi,

Added  Microsoft.Practices.EnterpriseLibrary.Logging.dll and  Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.dll references to my project. When i try to build my application its throws error saying Microsoft.Practices.EnterpriseLibrary.Logging.dll does not strongly named.

Could you please help me in this regards,

Vinod

# September 6, 2010 4:48 AM

sukumarraju said:

Hi Vinod,

If you are referencing Enterprise library application blicks from "C:\EntLib41Src\Bin". where your demo project libraries are stored. These libraries are not strongly typed.

By default configuration file takes the reference of DLL's which are there on the installation location

"C:\Program Files\Microsoft Enterprise Library 4.1 - October 2008\Bin"

Try the above resolution and let me know further.

So you need to reference dll's from the "C:\Program Files\Microsoft Enterprise Library 4.1 - October 2008\Bin" location.

# September 6, 2010 7:38 AM

incosejoisk said:

You certainly deserve a round of applause for your post and more specifically, your blog in general. Very high quality material

# January 25, 2011 11:45 PM

loss secret tip weight said:

I just sent this post to a bunch of my friends as I agree with most of what you’re saying here and the way you’ve presented it is awesome.

# February 12, 2011 3:08 PM

Uriliopsili said:

I find myself coming to your blog more and more often to the point where my visits are almost daily now!

# February 26, 2011 7:06 PM

bahglyday said:

Very informative post. Thanks for taking the time to share your view with us.

# March 3, 2011 3:20 PM

twingigma said:

You certainly deserve a round of applause for your post and more specifically, your blog in general. Very high quality material

# July 15, 2011 3:05 PM

rtyecript said:

I really liked the article, and the very cool blog

# August 24, 2011 7:13 AM

Noushad said:

Nice artical for beginers

# September 30, 2011 6:21 AM

George Antony said:

Thanks sukumar. the article is very helpfull in configuring exception handling in EL 4.1 .

# October 29, 2011 4:45 AM

seo said:

I think this is a real great blog article.Thanks Again. Keep writing.

# May 7, 2012 9:27 AM

social said:

I really liked your blog article.Thanks Again.

# May 7, 2012 4:24 PM

Moataz said:

Great Article , Thank you !

# December 31, 2012 4:26 AM

Moataz said:

Please would you tell me what if i want to log in flat file not in the event viewer what are the steps to follow ?!

# December 31, 2012 5:01 AM

sukumarraju said:

Hello Moataz,

To log into flat file it is required to configure the log source.

www.microsoft.com/.../details.aspx

Download the Hands on tutorials and implement the same. It is quite configurable and straight forward.

Let me know further queries.

# February 5, 2013 12:03 PM

Whittle said:

Excellent way of explaining, and nice post to take facts concerning my presentation focus, which i am going to present in

school.

# September 13, 2013 8:33 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)