Health Monitoring in ASP.NET 3.5

Posted by: Malcolm Sheridan , on 3/8/2009, in Category ASP.NET
Views: 52349
Abstract: The following article demonstrates how to use health monitoring in ASP.NET 3.5.
Health Monitoring in ASP.NET 3.5
 
I am a big advocate on less is more, and when it comes to writing code to monitor an ASP.NET application, less code is definitely more. As a developer, once you have finished developing your application and it’s deployed into production, you’ll need to monitor it and have it notify you when something goes wrong. There are several ways to do this, from utilising the global.asax file to writing custom classes. But a little known feature in ASP.NET is health monitoring. This gives you the ability to monitor the health of an ASP.NET application. This article won’t delve into the specifics of creating your own custom health monitoring class, but it will focus on what is available to ASP.NET developers out of the box.
To begin with open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application.
New Web App
This will be a small project as most of the work is configurable through the web.config file. Open the Default.aspx page and drag a Button control onto the designer. Add the following code to the Click event:
C#
throw new NotImplementedException("This function has not been implemented.");
 
VB.NET
Throw New NotImplementedException("This function has not been implemented.")
When you click this button, you will be throwing a NotImplementedException exception. That’s it!
The next piece in the puzzle is to determine what you want to happen when an error is encountered by a user on the website. One process that is tried and tested is to send an email to an administrator or developer to notify them something has happened.
To configure this, open the web.config file and add the following code:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="your.email@company">
      <network host="your.smtp.host" port="25"/>
</smtp>
</mailSettings>
</system.net>
 
mailSettings are an easy way to configure email options in your application. Next add the following code which configures the health monitoring for your application:
 
<healthMonitoringenabled="true">
                  <eventMappings>
                        <clear/>
                        <add name="All Errors"
             type="System.Web.Management.WebBaseErrorEvent, System.Web,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
             startEventCode="0"
             endEventCode="2147483647"/>       
                  </eventMappings>
                  <providers>
                        <clear/>
                        <add name="EmailErrorProvider"
             type="System.Web.Management.SimpleMailWebEventProvider"
             to="malcolm.x.sheridan@nab.com.au"
             from="someone@contoso.com"
             buffer="false"
             subjectPrefix="An error has occured."
             bodyHeader="This email is generated from my application." />
                  </providers>
                  <rules>
                        <clear/>                     
                        <add name="Testing Mail Event Providers"
             eventName="All Errors"
             provider="EmailErrorProvider"
             profile="Default"
             minInstances="1"
             maxLimit="Infinite"
             minInterval="00:01:00"
             custom=""/>       
                  </rules>
            </healthMonitoring>
Healh monitoring is split up into five categories. These are:
 
•        eventMappings
•        bufferModes
•        rules
•        providers
•        profiles
 
In this example we are using eventMappings, providers and rules to monitor the health of the application. The list of health monitoring events you can subscribe to are in the web.config file in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG directory. Event mappings are named groups of events that you want to monitor. In the example above, we are mapping to the All Errors event.
The next section we have configured is providers. Providers are used to indicate what type of logging is required. For this example we are subscribing to the SimpleMailWebEventProvider which we configure to send out an email once the All Errors event has been raised.
 The last section is rules. Rules are used to indicate how events are mapped to certain providers. For this example, we have created a rule, Testing Mail Event Providers, which tells the application whenever an All Event is raised, the provider it will use is the EmailErrorProvider,which we have defined in our list of providers, and this will send out an email to the recipient specified in the To field. 
That’s it. If you run the project and click the Throw An Exception button, a NotImplementedException will be thrown, and an email will be sent with information about the request that failed. The email will look similar to this:
This email is generated from my application.
** Application Information **
---------------
Application domain: b641c057-1-128806971313626373
Trust level: Full
Application Virtual Path: /
Application Path: D:\articles\Health Monitoring\HealthMonitoring\
Machine name: WNAB560548
 
 
** Events **
---------------
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 3/5/2009 2:25:36 PM
Event time (UTC): 3/5/2009 3:25:36 AM
Event ID: a08073d247f74e5b8548bac443808132
Event sequence: 8
Event occurrence: 1
Event detail code: 0
 
Process information:
    Process ID: 2904
    Process name: WebDev.WebServer.exe
    Account name: TEST\account
 
Exception information:
    Exception type: System.NotImplementedException
    Exception message: This function has not been implemented.
 
Request information:
    Request URL: http://localhost:49508/default.aspx
    Request path: /default.aspx
    User host address: 127.0.0.1
    User:
    Is authenticated: True
    Authentication Type: NTLM
    Thread account name: TEST\account
 
Thread information:
    Thread ID: 4
    Thread account name: TEST\account
    Is impersonating: False
    Stack trace:    at HealthMonitoring._Default.btnThrowError_Click(Object sender, EventArgs e) in E:\articles\Health Monitoring\HealthMonitoring\Default.aspx.cs:line 9
   at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
   at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
 
I have used this code multiple times to avoid having to write code in the global.asax file to handle global errors. By implementing health monitoring in your applications, you’ll have an application that if it does thrown an exception, it will tell you something is wrong. And all of this without having to write a single line of C# or VB.NET code. Less code is more, and that’s pretty cool!
The source code of this article can be downloaded from here.
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement by Copyscape