Sukumar Raju's Blog

MCP

Sponsors

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. It allows to change 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 discuss Exception Handling application block configuration to implement consist exception handling with in ASP.NET web application.

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.

image 

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

image

Step 2    Adding Logging Handler

After choosing 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 event log
  • An e-mail message
  • A database
  • A message queue
  • A text file

    Here Exception Application block using Logging Application block to log excetpions to Application events.

  • Add Logging Handler

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

    image

    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.

    Step 3  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.

    image

    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.

    Logging-Formater-Type

    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.

    logging-settings

    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 application events using Exception handling policy ‘MyPolicy’.

    using-Exception-Policy-code

    Logged exception in Application events

    Running the above code logs an event to windows application events as shown below.

    image

    Step 5   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.

    Step 5.1   Add Exception Handling Application block

    Using the configuration tool by selecting application –> New option from context menu , add the exception handling application block as shown below.

    image

    Step 5.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.

    image

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

    image

    Step 5.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 Exception class is selected.

    choose-TypeSelector-Excepiton

    Step 5.4   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 and using the name spaces where ever you want to use application blocks.

    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:

    http://msdn.microsoft.com/en-us/library/cc309212.aspx

    http://www.codersource.net/csharp_exception_handling_enterprise_library.aspx

    http://www.devx.com/dotnet/Article/35736

  • Comments

    Enterprise Library: Exception Handling Application Block | Windows 7 Serials said:

    Pingback from  Enterprise Library: Exception Handling Application Block | Windows 7 Serials

    # February 8, 2010 11:11 PM

    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

    Dew Drop – February 9, 2010 | Alvin Ashcraft's Morning Dew said:

    Pingback from  Dew Drop – February 9, 2010 | Alvin Ashcraft's Morning Dew

    # February 9, 2010 8:16 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

    meridilik said:

    Привет, сегодня на моих глазах произошла просто шокирующая история. В практически пустом вагоне электрички, возвращалась домой в дачный поселок. В вагоне никого практически не было, впереди нас сидела девушка. Лет 19, наверное. Пожилая пара и еще несколько женщин. Из тамбура в вагон пришла компания гопоты. 5 человек, лет по 20-25. Ничего не говоря, я просто оторопела, подбежали к той молодой девушке, заломили руки через сиденье. Один из подонков пирачинный нож достал и прошел по вагону, осматривая сидящих людей. Я тогда не знаю, просто душа в пятки ушла. Он сказал, что то вроде сидите смирно и вам ничего не сделают. В общем, с девушке стащили джинсы, одежду верхнюю. Один руки держал, второй сверху навалился, рот залепили. Достали ремень, и стали пряжкой пороть. Я была в шоке. Изверги по очереди ее пороли, я да же не знаю, сколько времени прошло, минут 30, наверное, пороли пока она сознания не потеряла, потом насиловали. Закончили, обмякшее тело девушки положили на сидение, оделись и спокойно пошли обратно в тамбур. Я просто в шоке страшном, как только они ушли, выбежала на следующей остановке, бежала долго, не помню куда и что. Всю ночь руки тряслись, не знаю, что стало с той девушкой, что вообще это было. Ужас, я теперь боюсь ездить в электричке.

    А вы тут говорите о порядочности какой-то, где она, если такое просто происходит на людях.

    # February 15, 2010 1:55 PM

    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
    Leave a Comment

    (required) 

    (required) 

    (optional)

    (required)