Built-in Providers


Now that you've seen the types of built-in events that you can monitor, we'll show how you can record them to various logs using the built-in providers that come with ASP.NET 2.0. Figure 7-2 shows the class hierarchy of the built-in providers, which all ultimately derive from WebEventProvider.

Figure 7-2. Built-in Web event providers


In order to use any of these providers, you need to refer to them in configuration. By default, three providers are already configured for you in the machine-wide web.config file, as shown in Listing 7-1 (I've removed the assembly strong names from many config snippets in this chapter for brevity).

Listing 7-1. Default Web event providers in the root web.config file

<!-- excerpt from root web.config file that ships with ASP.NET 2.0 --> <healthMonitoring>   <providers>     <add name="EventLogProvider"          type="System.Web.Management.EventLogWebEventProvider" />     <add name="SqlWebEventProvider"          type="System.Web.Management.SqlWebEventProvider"          connectionStringName="LocalSqlServer"          maxEventDetailsLength="1073741823"          buffer="false"          bufferMode="Notification" />     <add name="WmiWebEventProvider"          type="System.Web.Management.WmiWebEventProvider" />   </providers>   <!-- ... --> </healthMonitoring> 

Notice that the "enabled" attribute on <healthMonitoring> isn't set here, which means the entire Web event system is disabled by default. As you'll see in the following listings, you'll need to enable this yourself in your web.config file if you want to record any Web events.

The event log provider is a simple example to start with. It doesn't need any configuration: its job is to synchronously write each event it receives to the Windows application event log. System administrators like a high signal-to-noise ratio in their event logs, so it's wise to limit the amount of data you log using this provider to higher priority events. Listing 7-2 is an example of what a Web event recorded by this provider looks like, as copied from the event log.

Listing 7-2. A Web event sent to the event log

Event Type: Information Event Source:     ASP.NET 2.0.50727.0 Event Category:   Web Event Event ID:   1305 Date:       7/5/2006 Time:       4:06:35 PM User:      N/A Computer:   GROMIT Description: Event code: 1001 Event message: Application is starting. Event time: 7/5/2006 4:06:35 PM Event time (UTC): 7/5/2006 10:06:35 PM Event ID: 4bd8b3da2b6142fcae0b6f4d150f9e5a Event sequence: 1 Event occurrence: 1 Event detail code: 0 Application information:     Application domain: a444bacb-10-127966107943906250     Trust level: Full     Application Virtual Path: /sample     Application Path: C:\essentialasp.net\sample     Machine name: GROMIT Process information:     Process ID: 2948     Process name: WebDev.WebServer.EXE     Account name: GROMIT\Alice 

Windows Management Instrumentation (WMI) is a well-known interface for management tools such as IBM Tivoli, Microsoft Operations Manager, and so on. Using the WmiWebEventProvider, you can turn Web events into WMI events that will light up these management tools when events occur. WMI aficionados will be happy to know that ASP.NET ships with a Managed Object Format (MOF) file that describes the shape of all of the built-in Web events generated by ASP.NET.[4] To use this provider, you can simply refer to it (see Listing 7-1).

[4] The ASPNET.MOF file can be found in the %SystemRoot%\Microsoft.NET\Framework\<version> directory. For more information on MOF files and WMI, see Developing WMI Solutions: A Guide to Windows Management Instrumentation by Craig Tunstall and Gwyn Cole (Addison-Wesley, 2003).

The TraceWebEventProvider is a special adapter that funnels each Web event it receives into the System.Diagnostics tracing engine. You'll see how to use this provider later in this chapter.

The E-Mail Providers

Two providers send SMTP (e-mail) messages for each Web event. Both of these providers can be configured with a common set of attributes that determine e-mail headers (from, to, cc, bcc), how many events should be buffered before sending an e-mail (maxEventsPerMessage), the maximum number of events you want in any given e-mail (maxMessagesPerNotification), as well as a subject prefix for the e-mail. These providers both use the services of System.Net.Mail, which relies on the system.net/mailSettings/smtp section in web.config (see Listing 7-3). You won't see any exceptions if the e-mail provider fails to send e-mail, but you will see errors in the application event log that can help you diagnose problems about these e-mails. One thing that might confuse you when you first try to use either of these e-mail providers is that unless buffering is enabled, by default they will send a unique e-mail for each Web event. We'll talk about how buffering works shortly.

The SimpleMailWebEventProvider creates text e-mail messages and lets you control formatting at a very basic level through a set of additional string-valued attributes on the provider: bodyHeader, bodyFooter, and separator. The maxEventLength attribute allows you to throttle the length of text allotted to any single event description in case the notification e-mails get too large.

If you need something fancier, TemplatedMailWebEventProvider lets you create an ASPX page that will be used to format these e-mail messages as HTML. Along with the common attributes listed above, you'll need to add one more attribute named "template" that specifies which ASPX page is to be used for formatting. The provider communicates the current set of events that need logging to your page via a static property on TemplatedMailWebEventProvider called CurrentNotification, which is of type MailEventNotificationInfo. This gives you all the information you need to build an HTML page, which the provider will then use as the body of the e-mail message.

Listing 7-3 is a sample configuration you can use to get started with templated Web event e-mails. We've used the convenient "pickup directory" configuration for System.Net.Mail so that each e-mail will be represented by a file on the hard drive, which is great for quick testing (if you double-click one of the resulting .EML files, it will open up in Outlook Express so that you can view it). We've also set detailedTemplateErrors="true", so any errors that occur while compiling or processing the template will be output into the e-mail message as text, which is very helpful when you're developing a template.

Listing 7-3. Configuring the TemplatedMailWebEventProvider

<!-- web.config --> <configuration>   <system.web>     <healthMonitoring enabled="true" heartbeatInterval="30">       <providers>         <add name="MyMailProvider"              type="System.Web.Management.TemplatedMailWebEventProvider"              buffer="true"              bufferMode="Critical Notification"              from="webserver@fabrikam.com"              to="sysadmins@fabrikam.com"              template="~/formatter.aspx"              detailedTemplateErrors="true"             />       </providers>       <!-- we'll explain rules and profiles shortly -->       <rules>           <add name="Email These Events"                eventName="All Events"                provider="MyMailProvider"                profile="Critical" />       </rules>     </healthMonitoring>   </system.web>   <!-- specify that each e-mail should be placed in an .EML file -->   <system.net>     <mailSettings>       <smtp deliveryMethod="SpecifiedPickupDirectory">         <specifiedPickupDirectory pickupDirectoryLocation="c:\mail"/>       </smtp>     </mailSettings>   </system.net> </configuration> 

Listing 7-4 contains the code for formatter.aspx. This page uses data binding to output a few details from the collection of Web events into a GridView. Figure 7-3 shows what one of these formatted e-mails looks like in Outlook Express.

Listing 7-4. Formatter.aspx

<!-- formatter.aspx --> <body>     <form  runat="server">     <div>      <asp:GridView  runat="server"                    AutoGenerateColumns="false"                    EnableViewState="false">         <Columns>              <asp:BoundField DataField="EventCode" HeaderText="Code" />              <asp:BoundField DataField="EventTime" HeaderText="Time" />              <asp:BoundField DataField="Message" HeaderText="Message" />         </Columns>      </asp:GridView>     </div>     </form> </body> // codebehind file formatter.aspx.cs using System; using System.Web; using System.Web.UI; using System.Web.Management; public partial class WebEventMailFormatter : System.Web.UI.Page {     protected void Page_Load(object sender, EventArgs e)     {         gridView.DataSource = TemplatedMailWebEventProvider.             CurrentNotification.Events;         gridView.DataBind();     } } 

Figure 7-3. E-mail notification


The SQL Provider

When you run aspnet_regsql, the resulting database includes a table called aspnet_WebEvent_Events, which includes columns for each property of WebBaseEvent. The SqlWebEventProvider writes each Web event it receives into this table, which you can then query using any tool you like. This is an excellent choice for detailed, noisy error messages, because you can write tools to view and manage the logged data however you like. Web events that you wouldn't want to e-mail to an administrator or put in the event log can be recorded in the database for later tracking. Nothing stops you from using a DELETE query to get rid of noise later on, once it's been analyzed. Also, nothing stops you from using more than one database. You might use one database for doing statistical data mining (this one might get pretty noisy, but that's what it's for). You could set up a separate database for critical security audit events and grant security personnel permission to use it. Listing 7-5 (in the next section) shows an example that uses two instances of the SQL provider simultaneously.

Note that SqlWebEventProvider always obtains its database connection using the worker process' security identity (even if you've turned on impersonation), so be sure to add this user account to the database role called aspnet_WebEvent_FullAccess, granting it permission to log Web events in the database.




Essential ASP. NET 2.0
Essential ASP.NET 2.0
ISBN: 0321237706
EAN: 2147483647
Year: 2006
Pages: 104

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net