One of the new features of ASP.NET 2.0 that is less talked about is the health monitoring system. It allows you log things like failed logins, unhandled exceptions, expired forms authentication tickets, etc. The new health monitoring system is provider based so you can have it log to the event log or to a sql server out of the box. Of course you can always create your own provider as well.
To create a custom web event, simply create a new class and inherit from WebBaseEvent. For example, if you wanted to log an event every time a button was clicked (for example, Get a Rate, or Make Reservation), create a class that looks like this.
using System;
using System.Web.Management;
public class MakeReservationWebEvent : WebBaseEvent
{
DateTime clickDateTime;
public MakeReservationWebEvent(string message, object source, int eventCode, DateTime myDateTime) : base(message, source, eventCode)
{
// assign to classwide variable
clickDateTime = myDateTime;
}
// override this method to specify which text is logged
public override void FormatCustomEventDetails(WebEventFormatter webEventFormatter)
{
// log a custom message
webEventFormatter.AppendLine("Clicked at: " + clickDateTime.ToString());
}
}
Once you have created your custom web event class, you simply need to register it in your machine.config/web.config.
<healthMonitoring enable="true">
<eventMappings>
<add name="Make Reservation Events" type="MyWebEvent, __code" />
</eventMappings>
<rules>
<!-- log to event log, could also specify SqlWebEeventProvider -->
<add name="Make Reservation Events" eventName="Make Reservation Events" provider="EventLogProvider" />
</rules>
</healthMonitoring>
Firing the custom event is not as straight forward as you would think. First you must instantiate your web event and raise it with the base class. You would put the following in your click event handler:
// instantiate your custom web event
MakeReservationWebEvent makeReservationWebEvent = new MakeReservationWebEvent("Reservation Made", null, 101, DateTime.Now);
// raise the event to be logged
WebBaseEvent.Raise(makeReservationWebEvent);
I think custom web events will prove to be quite powerful and I can see them logging all types of useful information in our applications in the future.
Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=201