Exception Management Application Block for .NET
Related Links
Patterns and Practices INDEX
.NET Architecture Center
Application Architecture for .NET: Designing Applications and Services
Kenny Jones, Graeme Malcolm, Alex Mackman, Edward JezierskiMicrosoft Corporation
April 2002
Summary: The Exception Management Application Block provides a simple yet extensible framework for handling exceptions With a single line of application code you can easily log exception information to the Event Log or extend it by creating your own components that log exception details to other data sources. OR Notify Operators, WITHOUT Affecting Your Application Code. The Exception Management Application Block CAN Easily Be Used As a Building Block in Your Own .NET Application. (18 Printed Pages)
Introduction
Are you involved in the design and development of .NET applications? Have you ever felt that you spend too much time writing error handling code? Have you struggled to diagnose problems in your applications due to a lack of detailed and consolidated diagnostic information? If so , The Exception Management Application Block for .NET is for you.
The Exception Management Application Block is an exception management framework that can easily be used as a building block in your own .NET application. If you use it, you will reduce the amount of custom error handling code you need to create, test, and maintain YOU WILL Also made your application more robust and easy to debug.
Specifically, The Exception Management Application Block Helps you:
.
· Isolate Exception Management Code from Business Logic Code.
· Handle and log exceptions with a minimal amount of custom code.In an application that references the Exception Management Application Block, you can publish an exception (for logging or operator notification) in a single line of code, as follows:
[C #]
Catch (Exception EX)
{
ExceptionManager.publish (ex);
}
[Visual Basic]
Catch exception
ExceptionManager.publish (ex)
The Remainder of this overview is Divided Into The Following Sections:
What Does The Exception Management Application BLOCK INCLUDE?
Downloading and Installing The Exception Management Application Block
Using the Exception Management Application Block, MANAGEMENT
Configuring The Exception Management Application Block
Extending The Exception Management Application Block
Internal Design
FREQUENTLY Asked Questions
Feedback and support
More information
Collaborators
What Does The Exception Management Application BLOCK INCLUDE?
The Exception Management Application Block Consists of Three Microsoft® Visual Studio® .NET Projects, Full Source Code, and Comprehensive Documentation.
Note You can customize the provided source code to suit individual requirements. However, note that the Exception Management Application Block is fully configurable through standard .NET XML configuration files and requires little, if any, internal customization.
The Visual Studio .Net Projects
Note That Microsoft Visual Basic® and Visual C #TM Versions of the Following Projects Are Available Within The Exception Management Application Block Download:
· Microsoft.ApplicationBlocks.ExceptionManagement. Build this project to build the Microsoft.ApplicationBlocks.ExceptionManagement.dll assembly. This assembly contains the primary ExceptionManager class through which you publish exceptions, together with a DefaultPublisher class used to write exception details to the Windows Event Log and an ExceptionManagerInstaller class used at installation time to create Event sources for use with the Event Log. · Microsoft.ApplicationBlocks.ExceptionManagement.Interfaces. Build this project to build the Microsoft.ApplicationBlocks.ExceptionManagement.Interfaces assembly. This assembly contains the interfaces that are Implement by Publisher Classes. This Includes The defaultpublisher class and optionally Your Own Custom Publishers.
· Exception Management Quick Start Samples. This project provides a set of quick start samples designed to show you how to use the Exception Management Application Block. Build this project to create a simple client application. This helps increase your understanding of how the Exception Management Application Block works and you can use it it as a trouplanooting AID.
The Documentation
Comprehensive Documentation IS Provided. This Includes the Following Main Sections:
· Developing Applications with the Exception Management Application Block. This section includes quick start samples, covering a range of common use cases that help you start to use the Exception Management Application Block quickly and easily. This section also explains how to extend the block by developing Your OWN Custom Publisher Components.
.. · Design and Implementation of the Exception Management Application Block This section includes background design philosophy information that provides insights into the design and implementation of the Exception Management Application Block · Deployment and Operations This section includes installation information;. It discusses deployment options, use Of The Global Assembly Cache, And The Creation of Event Sources by The Installer Class. It Also Includes Configuration, Security, And Troubleshooting Topics.
. This is the Exception Management Application Block, Reference. This is a comprehensive api reason.
System Requirements
To Run The Exception Management Application Block, you need the following:
· Microsoft Windows® 2000, Windows XP Professional
· The RTM Version of The .NET Framework SDK
· The RTM Version of Visual Studio .NET (Recommended But Not Required)
Downloading and Installing The Exception Management Application Block
A Windows Installer File ConTAING The Exception Management Application Block Projects, Source Code and Comprehensive Documentation is Available.
The install process creates a Microsoft Application Blocks for .NET submenu on your Programs menu. On the Microsoft Application Blocks for .NET submenu, there is an Exception Management submenu that includes options to launch the documentation and to launch the Exception Management Application Block Visual Studio .NET SOLUTION.
Go to ms.com Downloads to Open the Download.
Using the Exception Management Application Block, MANAGEMENT
. This section discusses how to use the basic features of the Exception Management Application Block Additional information about these and other related topics can be found in the documentation included with the Exception Management Application Block download.The topics discussed in this section include:
Publishing Exceptions
· Referencing the Exception Management Application Block
Publishing Exceptions
Figure 1 Illustrates How The Exception Management Application Block Integrates Seamless The Chain of Events That Occur When Your Application THROWS AN Exception.
Figure 1. Using the Exception Management Application Block
The Flow of Logic Shown in Figure 1 To Publish An Exception IS FOLLOWS:
.
Note The Exception Manager can publish exceptions of type System.Exception (or any derived type) but you are encouraged to derive your own exception types from BaseApplicationException in order to benefit from additional contextual information provided by this class.
2. The Application Calls The Publish Method of The ExceptionManager Class.
3. The ExceptionManager class uses the ExceptionManagerSectionHandler class to retrieve the application's exception management settings. You can create these in any of the standard .NET XML configuration files at either the application or computer level.
4. The exception management settings in the application's configuration file (if any) are read to determine how the exception should be published.5. If no settings are found, the exception is published in the Windows Event Log by using the DefaultPublisher class. If the application has exception management settings configured, the publishers listed in the configuration file, which can include the DefaultPublisher class and custom publisher classes, are used to publish the exception. All publishers implement at least one of the interfaces defined in the Interfaces assembly.
6. IF An Exception Occurs While Publishing Through a Custom Publisher
Referencing The Exception Management Application Block
To Use the Exception Management Application Block, You Must:
1. Build The Microsoft.ApplicationBlocks.ExceptionManagement Project To Generate The Microsoft.ApplicationBlocks.ExceptionManagement.dll Assembly.
2. Set a reference to the microsoft.ApplicationBlocks.ExceptionManagement.dll assembly.
3. Add a c # using or visual basic imports statement to reasonment the microsoft.applicationBlocks.ExceptionManagement namespace.
You can now publish exceptions by calling the Publish method of the ExceptionManager class. Because this is a static / Shared method, you do not need to instantiate an instance of the ExceptionManager class and can publish an exception through the type name in a single line of Code.
[C #]
Catch (Exception EX)
{
ExceptionManager.publish (ex);
}
[Visual Basic]
Catch exceptionExceptionManager.publish (ex)
Configuring the Exception Manager Application Block
The behavior of the Exception Management Application Block is controlled using standard .NET XML application configuration files; web.config for an ASP.NET application, or appname.exe.config for a Windows application You can also apply configuration settings at the computer level. By using machine.config.
Note if you do not support, The Exception Manager Simply Uses The default publisher to publicows event log.
Configuration Format
The Exception Management Settings in The Configuration File Have The Following Format:
Type = "Microsoft.ApplicationBlocks.exceptionManagement ExceptionManagerSectionHandler, Microsoft.ApplicationBlocks.exceptionManagement "/> Exclude = "( ) TYPE, ( ) Type" incrude = "( ) Type, ( ) TYPE" ExceptionFormat = "XML" Customattr = "Value" /> exceptionManagement> configure> A For complete details of all the configuration options, see the documentation that is supplied with the Exception Management Application Block In summary:.. The mode attribute of the · Enable or disable selected public publishers. · Exclude or include Specific Exception Types. · Specify WHETHER OR NOT The Exception Details Should Be Published in XML Format. · Define custom attributes that are passed by the Exception Manager to individual publishers. These can be used for any purpose. For example, you may want to supply an e-mail address to be used for operator notification purposes or the name of a custom log File. Extending The Exception Management Application Block You may be satisfied with the functionality of the default publisher, which writes exception details to the Windows Event Log. However, you may want to develop your own custom publishers to log exception details to alternate locations or perhaps to notify operators, maybe through Windows Management Instrumentation (WMI), That An Exception Has Occurred. Creating a Custom Publisher To create a custom publisher, you must create a class that implements either the IExceptionPublisher or the IExceptionXmlPublisher interface defined within the Microsoft.ApplicationBlocks.ExceptionManagement.Interfaces.dll assembly. If you want to receive exception details in XML format, implement IExceptionXmlPublisher, 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.The following example shows a simple implementation of the ipceptionpublisher interface. [Visual Basic] Imports system Imports Microsoft.ApplicationBlocks.ExceptionManagement Imports System.Text Imports system.io Imports system.collections.specialized Namespace CustomExceptionPublishers Public Class Custompublisher Implements IExceptionPublisher Private m_logname as string = "c: /testexceptionLog.txt" Public Sub Publish (Byval Exception As Exception, _ Byval AdditionalInfo As NameValueCollection, _ Byval configSettings as namevaluecollection _ Implements IExceptionPublisher.publish 'Load config valueness. IF not configSettings is nothing then IF (Not ConfigSettings ("FileName") Is Nothing) and _ _ (ConfigSettings ("FileName"). Length> 0) THEN m_logname = configSettings ("FileName") END IF END IF 'Create StringBuilder To Maintain Publishing Information. DIM STRINFO AS New StringBuilder () 'Record The Contents of The AdditionAlInfo Collection. IF not additionalinfo is nothing then 'Record general information. Strinfo.appendformat ("----- Exception log entry ------ {0}", _ Environment.newline) Strinfo.appendformat ("{0} general information {0}", _ Environment.newline) Strinfo.appendformat ("{0} Additional Info:", Environment.newline) DIM I as string For Each I in AdditionalInfo Strinfo.appendformat ("{0} {1}: {2}", Environment.Newline, I, _ADDitionalInfo.get (i)) NEXT END IF 'Append the Exception Text IF not exception is nothing then Strinfo.appendformat ("{0} exception information {1}", _ Environment.newline, _ Exception.Message.toString ()) Else Strinfo.appendformat ("{0} {0} no exception. {0}", _ Environment.newline) END IF 'Write the entry to the evenet log. DIM FS as filestream = file.open (m_logname, _ FileMode.Append, _ FILEACCESS.WRITE DIM SW AS New StreamWriter (fs) SW.WRITE (STRINFO.TOSTRING) SW.CLOSE () fs.close () End Sub END CLASS End Namespace [C #] Using system; Using Microsoft.ApplicationBlocks.exceptionManagement; Using system.text; Using system.io; Using system.collections.specialized; Namespace CustomExceptionPublishers { Public Class Custompublisher: IExceptionPublisher { Private string m_logname = @ "c: /testexceptionLog.txt"; Void iExceptionPublisher.publish Exception Exception, NameValueCollection AdditionalInfo, NameValueCollection configSettings) { // load config value if the isy isy. IF (configSettings! = null) { IF (ConfigSettings ["FileName"]! = NULL && ConfigSettings ["filename"]. Length> 0) m_logname = configSettings ["filename"]; } // Create StringBuilder to maintain publishing information. Stringbuilder strinfo = new stringbuilder (); // Record The Contents of The AdditionAlInfo Collection. IF (AdditionalInfo! = NULL) { // Record general information. Strinfo.appendformat ("----- Exception log entry ------ {0}", Environment.newline; Strinfo.appendformat ("{0} general information {0}", Environment.newline; strinfo.appendformat ("{0} Additonal Info:", Environment.newline); FOREACH (String i in additionalinfo) { Strinfo.appendformat ("{0} {1}: {2}", Environment.newline, i, AdditionalInfo.get (i)); } } // append the exception text IF (Exception! = NULL) { Strinfo.appendformat ("{0} Exception Information {1}", Environment.newline, Exception.Message.toString ()); } Else { Strinfo.appendformat ("{0} {0} no exception. {0}", Environment.newline; } // WRITE The entry to the evenet log. FILESTREAM FS = file.open (m_logname, filemode.Append, FileAccess.write; StreamWriter SW = New Streamwriter (FS); SW.WRITE (STRINFO.TOSTRING ()); SW.CLOSE (); fs.close (); } } } Configuring a Custom Publisher After you create a custom publisher component, you need to hook it up with the Exception Manager. You do this by using a standard .NET XML configuration file. The following configuration file fragment shows how to configure the custom publisher shown previously. Type = "Microsoft.ApplicationBlocks.exceptionManagement EXCEPTIONMANAGERSECTIONHANDLER, Microsoft.ApplicationBlocks.exceptionManagement "/> configsections> TYPE = "CustomPublisher.exceptionPublisher" Filename = "c: /custompub.log" /> exceptionManagement> configure> Notice that a custom attribute called fileName is used to configure the name of the exception log for this custom publisher. This setting is passed to the publisher through the Publish method of the IExceptionPublisher interface.Note To turn this custom publisher into an XML publisher that receives exception details in XML format, you need to implement the IExceptionXmlPublisher interface, and then add the exceptionFormat = "xml" attribute to the Internal Design The Main Elements of The Exception Management Application Block Are The Following: · The BaseApplicationException class. This class should be used as the base class for all of your custom application-defined exception classes. It ensures that all exceptions provide a minimum level of contextual information. · The ExceptionManagerSectionHandler class. This class is responsible for reading configuration information from Microsoft .NET-based XML configuration files. You can configure various aspects of the Exception Management Application Block by using XML configuration files. · The ExceptionManager class. This class is used to manage the process of publishing exception information. Its primary purpose is to invoke publishers including the default publisher class and any registered custom publisher classes, which you can create to log information to specific locations or notify operators For Example, THROUGH E-Mail. · The ExceptionManagerInstaller class. This installer class is used at installation time to create the Event sources required by the default publisher (and possibly custom publishers) to write exception details to the Windows Event Log. Event sources are created at installation time (and not run time) because it can not be guaranteed that the security context of the Exception Manager at run time will provide sufficient access rights to be able to create Event sources. · The DefaultPublisher class. This class provides basic publisher functionality, and in the absence of custom publishers IS use by the ExceptionManager Class to Publish Exception Details. It logs Exception Details to the Microsoft Windows Event Log. · The iexceptionpublisher and iexceptionXMLPublisher Interfaces. Publisher Classes Implement has. Figure 2 Illustrates The Main Elements of The Exception Management Application Block. Figure 2. The Main Elements of the Exception Management Application Block The BaseApplicationException Class The ExceptionManagement assembly provides a base application exception class called BaseApplicationException, which is designed to provide a base implementation for exceptions in your application. You are encouraged to derive from this class when you create custom exceptions to ensure that each custom exception raised in your application provides The Base Level of Contextual Information Required for Logging Purposes. This Contextual Information Includes: · The Computer Name where The Exception Was Created. · The date and time when the exception. · The name of the application Domain That Was Hosting Your Application. · The Thread Identity Wheree The Exception Occurred. The Windows Identity of The Thread. · Additional Custom Information. The BaseApplicationException Class Is Also Serializable, Which Means Its State Can Be Passed Over a .net Remoting Boundary. The ExceptionManagerSectionHandler Class The ExceptionManagerSectionHandler Class Is Responsible for Reading The Configuration Details from The This Class is Associated with the The ExceptionManager Class This class is at the heart of the Exception Manager assembly. It is through this class that you publish exceptions. The class is responsible for assimilating exception details and forwarding them to each configured publisher. In the absence of any configured custom publishers, the ExceptionManager class Publishes to the default publisher. The ExceptionManagerInstaller Class This class is an installer class annotated with the RunInstaller (True) attribute. Its purpose is to create the Event sources required by the default publisher when writing to the Windows Event Log. You must ensure that the installer class is instantiated. This may or may NOT HAPPEN AUTOMAAATILY AND Depends on how you install the Exception Manager assembly. for example: · If you package the assevers. · If you install the assembly by copying it to its target location (for example, using xcopy deployment), the installer class is not automatically instantiated. In this event, you should run the Installutil.exe system utility, which instantiates any installer classes within A specified assembly.the defaultpublisher class This class implements the IExceptionPublisher interface and provides publication functionality by logging exception details to the Windows Event Log. In the absence of any further configured custom publishers, this is the only publisher used. You can configure the default publisher (alongside other custom publishers) by creating a The iexceptionpublisher and iexceptionXMLPublisher Interfaces These are the interfaces that publishers implement. A default publisher that logs exception details to the Windows Event Log is supplied, but you may want to develop your own custom publishers. For example, you may want to implement a custom publisher that publishes Event details by Using Windows Management Instrumentation (WMI). XML publishers that want to receive exception details in XML format implement IExceptionXmlPublisher while others (including the DefaultPublisher class) implement IExceptionPublisher. For full details of these interfaces, refer to the Exception Management Application Block documentation. FREQUENTLY Asked Questions What's new in this release? The RTM release of Exception Management Application Block includes the following new features and changes from the Beta 2 release:. · The publisher interface names have changed from IPublishException and IPublishXmlException to IExceptionPublisher and IExceptionXmlPublisher respectively This is to conform to .NET conventions, which state that Only Exception Object Types Should End with The Word "Exception". · The Microsoft.ApplicationBlocks.ExceptionManagement assembly now contains an installer class called ExceptionManagerInstaller. This is used at installation time to create the Event sources used by the default publisher to write to the Windows Event Log. You must ensure that this class is instantiated by your Installation process. ............................... For more information about this issue, see Does the reduced privileges of the ASPNET account, used to run the ASP.NET worker process, cause problems for the exception manager when I'm using it within an ASP.NET Web application? For More Information About Installation and Deployment Issues, See Can I Use Xcopy Deployment To Deploy the Exception Management Assembly · The exclude and include attributes on the For more information, see the "Configuring the Exception Management Application Block" topic, within the Deployment and Operations section of the documentation. · The SerializeToXml method of the ExceptionManager class is now a public method, which allows you to easily serialize exception objects to XML .............. CAN I use xcopy deployment to deploy the exception management assembly? Yes, with a caveat. As part of the installation process, you must ensure that the supplied installer class (ExceptionManagerInstaller) is instantiated in order to allow it to create the Event sources used by the default publisher when writing to the Windows Event Log. If you deploy the Exception Manager assembly within a Windows Installer package, the Windows Installer automatically instantiates the installer class. However, if you use xcopy deployment, you must manually instantiate the installer component by using the Installutil.exe system utility at install time. For more Information, Refer to the Exception Manager Application Block Documentation. Does the reduced privileges of the aspnet account No. This was a problem with the Beta 2 release of the Exception Manager Application Block when used in conjunction with the RTM version of the .NET Framework (where the logon session that hosts the ASP.NET worker process changed from SYSTEM to ASPNET in order To Provide a More Secure Security Context. The problem occurred because the Beta 2 release of the Exception Management Application Block created Event sources at run time when writing exceptions to the Windows Event Log. While the SYSTEM logon session provided the necessary access rights to create Event sources, the ASPNET logon does not. To overcome this problem, the RTM release of the Exception Manager creates Event sources at installation time when administrative rights means that there is no problem creating Event sources. However, you must ensure that the supplied installer class is executed. For more information, see Can I use xcopy deployment to deploy the exception management askEMBLIES? Do I NEED TO Configure The Exception Manager by Using a .NET XML Configuration File? No. If you do not supply any configuration information, the exception manager publishes exception details to the Windows Event Log by using the supplied default publisher component. If you create your own custom publishers, these must be hooked up to the exception manager with configuration settings. you can also use configuration settings to fine tune the behavior of the exception manager. For example, you can determine precisely which exception types should be published and which should be ignored. you can also supply custom attributes which can be used by publishers, For Example to Control Which Event Log Is Used to Log Exception Details. WHEN EXCLUDING OR INCLUDING SPECIFIC EXCETION TYES DO I HAVE TO LIST EACH TYPE EXPLICIY IN THE Configuration File? No. You can use the wild character "*" to exclude or include all exception types. Furthermore, you can prefix a specific type name with a " " character to indicate that you want this type and any type derived from it either included or Excluded. for more information, see the "configuring the Exception Management Application Block" Section WIX The Exception Manager Application Block Documentation.are The Any Other Application Blocks? The Exception Management Application Block is one of several Application Blocks that are being released. These Application Blocks solve the common problems that developers face from one project to the next. They can be plugged into .NET applications quickly and easily. Feedback and support Questions? Comments? Suggestions? For feedback on the Exception Management Application Block, please send an e-mail message to devfdbck@microsoft.com. The Application Blocks for .NET are designed to jumpstart development of .NET distributed applications. The sample code and documentation is provided "as-is." Support is available through Microsoft Product Support for a fee. A NewsGroup Has Also Been Created To Assist You with the Application Blocks for .NET. Use this newsgroup to consult with your counterparts, peers, and Microsoft Support Professionals in an Online, Open Forum. Everyone else benefits from your questions and comments, and our development team is monitoring the newsgroup on a daily basis: Newsgroup: Web-Based Readerhttp: //msdn.microsoft.com/newsgroups/loadframes.asp icp = msdn & slcid = us & newsgroup = microsoft? .public.dotnet.distributed_apps Newsgroup: NNTP Readernews: //msnews.microsoft.com/microsoft.public.dotnet.distributed_appsDo you want to learn and harness the power of .NET Work side by side with technology experts at the Microsoft Technology Centers to learn development best practices?. For more information, please visit http://www.microsoft.com/usa/mtc/. More information The Exception Management Application Block has been designed and developed based on the best practices and general design principles discussed in the Exception Management in .NET Architecture Guide. Read this guide to learn more about exception management. Collaborators Many thanks to the following contributors and reviewers: Susan Warren, Brad Abrams, Andy Dunn, Michael Day, Krzysztof Cwalina, Steve Busby, Chris Brooks, Andrew Roubin (Vorsite Corp.), Jeffrey Richter (Wintellect), Bernard Chen (Sapient), And Matt Drucker (Turner Broadcasting). Thanks, Also, To The Content Team: Tina Burden (EntireNet), Shylender Ramamurthy (Infosys Technologies Ltd), And Filiberto Selvas Patino.