Microsoft Exception Management Application Blocks

Microsoft Exception Management Application Blocks

xceptions need to be handled in all applications. Having a consistent method of dealing with exceptions will make your application easier to debug. Recording exceptions into an SQL database or the Event log will make tracking and looking up exceptions much easier.

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 errors
  • One routine that you need to work with
  • Can place exception publishers into separate component
  • Easily add new exception publishers
  • Add 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.

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. (See Sidebar: Other Application Blocks)

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.

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

     

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.

     

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.

devx-admin

devx-admin

Share the Post:
USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted