Website Operations in ASP.NET 2.0

 

Jayesh Patel, Bryan Acker, Robert McGovern
Infusion Development

July 2006

Applies to:

   Microsoft ASP.NET 2.0 (in distinction to ASP.NET 1.x)
   Microsoft Internet Information Services (IIS) 6.0 (in distinction to IIS 5.0)
   Microsoft .NET Framework 2.0

Summary: Describes how new features in ASP.NET 2.0 and IIS 6.0 help you deploy, configure, and monitor your Web applications. (24 printed pages)

Contents

Introduction
Deployment
IIS Configuration
Managing Web Applications
Monitoring .NET Applications
Summary

Introduction

ASP.NET 2.0 provides many new features that reduce the time needed to build powerful and complex Web applications. However, building an application is only part of the process. Once the site is built, you have to deploy, monitor, and maintain it during the life span of the application. ASP.NET 2.0, IIS 6.0, and the .NET Framework 2.0 address these issues with several new features that make deploying, configuring, monitoring, and maintaining Web applications easier than ever before.

The new compilation options, for example, let you securely deploy an ASP.NET application on a production server. Once deployed, the application cannot be changed without a full re-deployment. In other circumstances, you may want a completely open deployment where changes can be made to either the source code or the Web pages directly on the production server. An alternate set of compilation options can be used to support this scenario as well.

In terms of configuration, ASP.NET 2.0 provides a built-in administrative Web site that lets you create and configure users, configure data providers, and perform other administrative options through a secure Web interface. As a security measure, this interface is only available through Visual Studio .NET and can only be run on the local host. However, the underlying API is exposed for developers to create their own admin pages for ASP.NET 2.0 Web sites.

ASP.NET 2.0 also expands on the monitoring available in ASP.NET 1.x by providing greater support for hit counters, tracing, debugging, and health monitoring. You can configure and use these features through the new Web site administration console that is now built into every ASP.NET 2.0 application.

If you are working with ASP.NET 2.0, you may also be working with Internet Information Services (IIS) 6.0. Many changes in ASP.NET 2.0 were created to leverage IIS 6.0 features. However, ASP.NET 2.0 is still backward-compatible with IIS 5.0. This article will briefly explore IIS 6.0 features as they relate to ASP.NET 2.0.

The new features in ASP.NET 2.0, combined with the power of IIS 6.0, provide a wealth of options to deploy, configure, and monitor your Web applications. Whether you are a professional systems administrator or a hobbyist building small Web sites, this article will provide you with a solid overview of how to perform IT operations with ASP.NET 2.0 and IIS 6.0.

Deployment

ASP.NET 1.x and the .NET Framework introduced several new mechanisms for deploying Web applications. Compared to classic ASP deployment, the most notable features of ASP.NET deployment are:

  1. No registration   In ASP, any external DLL's had to be registered in the Windows Registry. This registration required careful management of GUIDs in order to prevent compatibility problems. .NET Framework applications use a different model for storing code that doesn't depend on the Windows Registry or GUID identifiers.
  2. No reboots   In ASP, if a developer updated a DLL, the site administrator would have to stop and restart the IIS instance in order to pick up the changed code. Because of the ASP.NET processing model, code changes are automatically detected and loaded without requiring an IIS restart.
  3. More deployment options   Deploying an ASP application required several configuration steps including the creation of a virtual directory and registration of several components. ASP.NET applications, on the other hand, can be deployed through several different mechanisms depending on the target and the desired type of deployment.

In this article we will look at how ASP.NET 2.0 deployment is different than ASP.NET 1.0 and show how to deploy an ASP.NET 2.0 application at each stage of its lifecycle.

Deploying for Development

Visual Studio 2005 includes a light-weight Web server for developing ASP.NET applications. The Web server can only service local requests and is therefore perfect for development. By using this built-in Web server, you no longer need to use IIS on a development machine. You can use the built-in server and get full debugging support without exposing any of your development code or incurring an administrative maintenance load. Another important advantage is that any user can build and test an application using Visual Studio 2005. You no longer need to be an administrator on the computer. It should be noted that you must still deploy your final applications on IIS.

Deploying for Production

ASP.NET 2.0 applications must be deployed to a server with IIS version 5.0 or 6.0. In this paper, we will focus on deploying to IIS 6.0.

Deploying the .NET Framework 2.0

In order to deploy ASP.NET 2.0 applications, you first have to deploy the .NET Framework 2.0 on your server. Fortunately, the .NET Framework was designed so that different versions could co-exist on the same server. In other words, you can deploy version 2.0 of the .NET Framework without uninstalling or modifying any of your applications that use any version 1.x of the framework. However, you will still have to tell the server whether an application should run against 1.x or 2.0. You can use either the MMC snap-in, or the aspnet_regiis.exe tool. For details on aspnet_regiis.exe, see the MSDN tools reference.

The IIS MMC Snap in

ASP.NET 2.0 deploys a special Microsoft Management Console (MMC) snap-in for IIS that lets you decide which applications should use which versions of the .NET Framework.

ms379597.operations_fig01(en-US,VS.80).gif

Figure 1. MMC display of ASP.NET applications

The MMC ASP.NET tab lets you to choose which version of ASP.NET your application uses and displays the Web.config location.

In addition to managing the Framework version, the console has an Edit configuration button that enables you to visually edit most of the Web.config or machine.config settings without having to directly manipulate the Web.config XML file. As an administrator, you will find that this MMC snap-in provides an extremely useful tool for configuring and managing multiple ASP.NET applications on a single server.

Enhanced Code-behind Model

Traditional ASP pages contain the code for both the design (HTML) and logic. Without a rich debugging environment, debugging and code readability becomes difficult as the amount of code increased. The code-behind model separates the design aspect from the logic.

The code-behind feature was first introduced in ASP.NET 1.x. This model separated the design aspect of your pages from the logic, but several issues arose with the model. The code-behind class wasn't automatically compiled at run time, so a project rebuild was required after every update. The model led to brittle code because the controls existed both declaratively and programmatically, and the potential for mismatches and synchronization errors was high.

The new code-behind model takes advantage of partial classes. Partial classes allow you to define different parts of a class in more than one file. These files are combined at compile time. ASP.NET 2.0 eliminates control declarations and allows Web forms and code-behind classes to be compiled at run time.

Compilation Options

ASP.NET 2.0 offers three different compilation models for a Web application:

  1. Normal (ASP.NET 1.x)   In a typical ASP.NET Web application, the code-behind files were compiled into an assembly and stored in the /bin directory. The Web pages (.ASPX files) were compiled on demand. This model worked well for most Web sites. However, the compilation process made the first request of any ASP.NET page slower than subsequent requests. ASP.NET 2.0 continues to support this model of compilation.

  2. Deployment pre-compilation   A new feature of ASP.NET 2.0 allows for full compilation of your project prior to deployment. In the full compilation, all the code-behind files, ASPX pages, HTML, graphics resources, and other back-end code are compiled into one or more executable assemblies, depending on the size of the application and the compilation settings. The assemblies contain all the compiled code for the Web site, and the resource files and configuration files are copied without modification. This compilation method provides for the greatest performance and security at the cost of removing all ability to modify the Web site post-deployment. If you are working with highly visible or highly secure Web sites, this option is the best choice for final deployment. However, if you are building a small site running on your local intranet, and the site changes frequently, full pre-compilation may not be needed.

    The ASP.NET 2.0 compilation model also enables you to pre-compile all the code-behind files for your application and still make updates to your code. You can compile your code-behind and original .ASPX files (both partial classes) into a single pre-compiled class (the page's base class). If you chose to edit your .aspx file at run time, you must simply recompile your page.

  3. Full runtime compilation   At the other extreme of deployment pre-compilation, ASP.NET 2.0 provides a new mechanism to compile the entire application at run time. That is, you can put your un-compiled code-behind files and any other associated code in the new \app_code directory and let ASP.NET 2.0 create and maintain references to the assembly that will be generated from these files at run time. This option provides the greatest flexibility in terms of changing Web site content at the cost of storing uncompiled code on the server.

Choosing the best compilation option will depend on your exact circumstances and needs. However, the compilation model remains flexible. Even if you choose to make use of the \app_code directory to store your code-behind files, you may still deploy your application using the full compilation method. Choosing the best compilation option will depend on your exact circumstances and needs. However, the compilation model remains flexible. Even if you choose to make use of the \app_code directory to store your code-behind files, you may still deploy your application using the full compilation method.

For more details on the compilation models, see ASP.NET 2.0 Internals.

Limiting Recompiles

One subtle feature of ASP.NET 2.0 is that the ASP.NET run time will allow only a fixed number of run-time recompiles on an application before the entire application is restarted. Basically, after a certain number of recompilations on the fly, the ASP.NET run time determines that the entire application may no longer be valid. Rather than risk errors, the run time automatically shuts down the application instance and reloads the entire application.

As a systems administrator, you should never have to worry about this process because it's transparent and automatic. The only concern is whether or not the application maintains session. If you've configured your application to use an out-of-state process or a database, then it will automatically retain the active sessions even if the application restarts.

You can configure the number of allowable recompiles by adjusting the numRecompilesBeforeAppRestart attribute on the <compilation> tag of the Web.config or machine.config file.

Deploying Applications

There are several ways to manually install an ASP.NET application. The two preferred methods are:

  1. **XCOPY   **XCOPY deployment allows you to copy .NET Framework application files from one computer to another. (The term XCOPY refers to a DOS command that performs mass file transfers.) This method is the fastest and easiest deployment option for self-contained applications. XCOPY works best for development and testing, and in some Web application scenarios. However, the XCOPY method cannot be used with the Global Assembly Cache (GAC) or for applications that require registration or configuration on the target computer. For Web applications, XCOPY works extremely well provided that a virtual directory has been created and configured on the production server (or servers).
  2. **Microsoft Windows Installer (MSI)   **Many administrators prefer a traditional installer program in order to automate virtual directory setup and allow for repeated deployments. Although MSI was available before the .NET Framework, Visual Studio offers a simplified tool for rapidly creating MSI files for .NET applications. Your MSI file can build Code Access Security policies on the target machine, create desktop icons and menu items, insert registry entries, and allow for easy uninstalls of a .NET Framework application. For an ASP.NET application, an MSI file offers the advantages of automatic creation of the virtual directory and the opportunity to automate any other setup tasks. MSI deployments work best for the initial deployment of an application to a new server.

In ASP.NET 2.0, you can use either of these methods, or deploy directly from Visual Studio 2005 using the FTP or SharePoint communication options described in the next section.

Updating Applications

After an ASP.NET application has been deployed, you can update it in several different ways, depending on the security policies you assign to your server.

XCOPY

ASP.NET is designed to reload applications when any of the application's components change. For example, if you copy new DLLs or ASPX pages to a Web server, the application will automatically load the changed code. By simply copying the new files over the old files, you automatically update your application. Therefore, XCOPY gives you a way to perform an installation to multiple Web servers without shutting down your entire Web farm. You can simply perform a staggered copy operation to each server.

MSI

If you chose to update with an MSI file, you will have to create a new installation package and redeploy. Because MSI uses the Microsoft Installer Framework, you may have to temporarily shut down your application in order to uninstall the old version and reinstall the new one. Fortunately, because ASP.NET applications run within their own CLR application domain, you do not need to reboot the server or restart the IIS process. The application simply restarts in a new application domain within the CLR process.

As during deployment, using an MSI package for updating your ASP.NET application has several advantages over XCOPY. MSI updates often work best for multiple server deployments or complex development models that go through several layers of development, testing, acceptance, and production.

Support for FTP, SharePoint, and IIS

Visual Studio 2005 has built-in support for editing and updating remote Web projects. You can update and maintain your application using File Transfer Protocol (FTP), Microsoft SharePoint, or by direct communication with a locally accessible IIS instance. The variety of methods makes it easier for you to deploy and maintain your applications.

ms379597.operations_fig02(en-US,VS.80).gif

Figure 2. FTP maintenance dialog box

For example, if you use either the Open Web Site or New Web Site dialog boxes, you can connect to a Web site and use FTP to transfer or update files.

No more FrontPage

ASP.NET 1.x applications were designed to integrate with IIS through FrontPage Server Extensions (FPSE). However FPSE added an extra administrative burden and security risks. Many hosting companies considered FPSE an "unnecessary service" and disabled it, forcing ASP.NET developers to use other means to deploy and work with their applications.

In ASP.NET 2.0, FPSE are no longer required or necessary. Thanks to the deployment and updating options described above, Visual Studio 2005 developers have more and better options for delivering their code to a Web server.

IIS Configuration

Currently, most ASP.NET 1.x applications run on Microsoft IIS 5.0. ASP.NET 2.0 was designed to leverage the features of IIS 6.0. IIS 6.0 is secure on installation, as it is configured in a locked-down state and won't do much by default except serve static Web pages. This helps eliminate some of those denial of service attacks that target processes that you didn't even know were running. You must manually configure the software to perform more advanced functions, such as ASP and ASP.NET site serving. When you add advanced functionality, IIS 6.0 warns you about potential security risks and makes recommendations about the best way to configure the server securely. Also, IIS 6.0 has more aggressive limits and timeouts so that the software presents a smaller attack surface to the outside world.

Migrating from IIS 5.0

Several issues may occur when you migrate from IIS 5.0 to IIS 6.0 (including issues with DSN and ODBC connections, ISAPI applications, and COM+ components), but the most common migration issue occurs because IIS 6.0 can run in one of two distinct modes of operation, which are called application isolation modes. Application isolation separates an application by process boundaries to prevent applications from affecting one another. Application isolation is configured differently for each of the two IIS application isolation modes.

  • IIS 5.0 Isolation Mode   IIS 5.0 isolation mode should be used only when an application depends on the memory model and process of IIS 5.0. You may have configured your ASP.NET applications to take advantage of the IIS 5.0 model. If you want to continue using the IIS 5.0 isolation, which requires settings in the machine.config file, use the IIS 5.0 isolation mode. Although some applications may run only in IIS 5.0, IIS 5.0 ASP.NET applications run in the ASP.NET worker process, not the inetinfo.exe. For that reason, you should not experience difficulty migrating your IIS 5.0 ASP.NET applications to IIS 6.0.
  • Worker Process Isolation Mode   Worker process isolation mode runs all application code in an isolated environment. Unlike earlier versions of IIS, there is no performance hit because there are fewer processor instructions being run when you switch from one application pool to another. Worker process isolation mode is compatible with most existing Web sites and applications, and is now the default setting. Whenever possible, run IIS 6.0 in worker process isolation mode to benefit from the enhanced performance and security in IIS 6.0.

IIS 6.0 Architecture

ms379597.operations_fig03(en-US,VS.80).gif

Figure 3. Comparison of IIS architecture

The first thing to note about the new IIS 6.0 architecture is that the HTTP listener and cache run in the kernel level for maximum performance. The other portions of a Web application run in the user level.

The Web Administration Service (WAS) replaces IISAdmin as the user mode component of the Web server. WAS can monitor applications for stalled processes, stop and restart applications, and provide services including processor affinity.

Each application runs in the context of an application pool. An application pool can contain one or more applications. Each application in a pool shares a primary process (w3wp.exe). You can use application pools to group related applications and optimize resource usage.

Application Reliability

The goal of the new architecture for IIS 6.0 is to completely isolate each application from every other application and the core Web server. IIS 6.0 allows you to implement several features to improve the reliability of your application.

Periodic Application Recycling

To increase application reliability, IIS 6.0 implements periodic process recycling. Your application will automatically restart when certain criteria (e.g. uptime, number of requests, scheduled times, memory consumption) are reached. Recycling your applications ensures that your application will be available and prevents unwanted applications from taking over the system. It should be noted that you must create code to maintain state when your application recycles.

ms379597.operations_fig04(en-US,VS.80).gif

Figure 4. Recycle worker process dialog box

Microsoft recommends configuring recycling for the application pool hosting your ASP.NET 2.0 applications as follows:

  • Disable recycling based on time (set periodicRestartTime to 0).
  • Enable used memory recycling, setting it to the minimum of 800 MB or 60 percent of physical RAM, whichever is lower. This is a good starting point to prevent your applications from returning OutOfMemory exceptions while under load (set periodicRestartPrivateMemory).

Pinging

Health check (pinging) is designed to detect any deadlocks in a worker process thread. Each worker process (W3WP.exe) thread is pinged. If the process doesn't respond in the specified time, the process will be killed (by default), or you can configure the process to perform a certain action.

ms379597.operations_fig05(en-US,VS.80).gif

Figure 5. Enable pinging dialog box

ASP.net 2.0 builds on top of this by using the ResponseDeadLockInterval property to help it determine when an application is ill and needs to be recycled. This will happen after the next ping arrives, and can be tracked via events written to the NT Application Event Log, source W3SVC-WP.

Crash detection and rapid fail protection

IIS 6.0 can detect when a worker process crashes. IIS 6.0 will automatically launch a new process if there is a demand with no interruption in service.

ms379597.operations_fig06(en-US,VS.80).gif

Figure 6. Adjusting the Failover properties

Metabase Now in XML

IIS 6.0 implement several key changes to the metabase. The metabase is the memory-resident database used for storing most IIS configuration settings. IIS 6.0 changes the format from a proprietary binary format to an XML format to make it easier to edit and configure the metabase to your specific needs. IIS 6.0 allows you to edit the metabase without stopping IIS services on your machine. This significantly reduces downtime for your application.

IIS 6.0 implements the metabase explorer to make it easier to back up and restore the metabase, even to a different machine. This functionality lets you create a master machine that can be cloned on other machines. The new metabase history feature automatically creates backups whenever any changes are made to the metabase.

ms379597.operations_fig07(en-US,VS.80).gif

Figure 7. Metabase explorer

For more information on migrating to IIS 6.0 and new features, please read Inside IIS 6 and the Microsoft PowerPoint presentation downloadable from https://support.microsoft.com/servicedesks/Webcasts/wc112002/WC112002.ppt.

Managing Web Applications

Once you have a Web site deployed on a production server, you still have to manage the application. In particular, if you deploy an ASP.NET 2.0 application that leverages the new personalization, membership, and profile features, you will need to make sure that the providers are properly configured and that the users and roles are properly defined.

Web Site Administration Tool Overview

To simplify the process of managing users, ASP.NET 2.0 provides a built-in Web site configuration tool. The Web Site Administration Tool is a simple Web site that can only be accessed on localhost through Visual Studio 2005. Through this tool, an administrator can manage the application by configuring services such as user management, the personalization providers, security, and profiles. The tool also allows you to easily configure counters, debugging and tracing information for your application.

ms379597.operations_fig08(en-US,VS.80).gif

Figure 8. Web Site Administration Tool

Managing Providers

Many of the new features in ASP.NET 2.0 depend on communication between the Web application and a data store. In order to provide this access in a consistent fashion, ASP.NET 2.0 uses the provider factory model. A provider is both a pattern and a point where developers can extend the ASP.NET 2.0 framework to meet specific data store needs. For example, a developer can create a new provider to support the user identification system, or to store personalization data in an alternate data store.

Most custom providers will interact with database backend systems. However, the programmer is free to implement the required provider methods and classes using any medium or algorithm so long as it meets the models required interface specification.

The Web Site Administration Tool allows you to manage providers without writing any code. By simply clicking on the Provider tab, you have the option to configure, delete, or add new providers to store your site information.

ms379597.operations_fig09(en-US,VS.80).gif

Figure 9. Provider management screen

ASP.NET 2.0 offers both SQL Server 2005 Express Edition and SQL Server providers.

When you add a new provider, ASP.NET automatically builds a database in the C:\inetpub\application_name\data folder. The following code is automatically added to the machine.config file:

<connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=WPTVPC;Integrated
     Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Listing 1. Machine.config file connection strings

The database contains predefined tables to host users, roles, profiles, and additional information for your site.

Profiles

In ASP.NET 1.x applications, user-specific data was often stored in the session and persisted to a database when necessary. This process was often inefficient and required the development of special framework code.

ASP.NET 2.0 helps solve this problem by providing a new profile service. A profile is simply a set of data that is associated with each user. The profile can contain any serializable data type from basic data types (for examples, string or int) to complex objects. Unlike in ASP.NET 1.x, the management of the profile is automatic. ASP.NET 2.0 takes care of creating and storing the user profile automatically.

The heart of the profile service is the profile provider. The profile provider contains all the code and structure necessary to persist and load user data to a data store. Similar to the membership provider, the profile provider is designed so that you can replace it with a provider that matches your choice of data store.

ASP.NET 2.0 provides a provider model that allows you to use any type of database for your provider, but the administration tool only supports SQL Server databases.

Managing Users

The security page of the Web Site Administration tool lets you add and edit users, roles, and access rules.

ms379597.operations_fig11(en-US,VS.80).gif

Figure 10. Security configuration options

The tool allows you to create roles and users. Users can be assigned to roles by simply selecting a check box of available roles.

ms379597.operations_fig12(en-US,VS.80).gif

Figure 11. User management screen

Managing Other Features

The Web Site Administration Tool also allows you to store profile and application information. By storing a user's profile information, you can display customized information and layouts for each user, depending on their preferences. You can store information in .NET Framework data types or custom data types.

ms379597.operations_fig13(en-US,VS.80).gif

Figure 12. Profile property settings screen

The Application management screen allows you to configure SMTP options for your application and application settings, as well as debugging and tracing options. The debugging section also allows you to set default or custom error pages and messages.

Improved Configuration APIs

In an effort to simply the process of managing your applications, the NET 2.0 Framework has enhanced the APIs you can use to access or modify the configuration of your application. The System.Configuration object model changed significantly from version 1.x. One important new class is the ConfigurationManager class. The ConfigurationManager class allows you to access your configuration files and retrieve information programmatically. The ConfigurationManager properties allow you to retrieve data from the <appSettings> and <ConnectionStrings> sections of the application configuration file, open the machine.config and Web.config files, and create custom configuration sections in your application that are added at run time.

Monitoring .NET Applications

With most Web sites relying on rapid data transfer and having more and more users, monitoring the performance of your Web application is essential. The .NET 1.x Framework includes many tools for monitoring your application. The .NET 2.0 Framework expands on existing features and includes several new features to help you monitor your application more efficiently and more accurately.

Event Tracing

Event tracing allows you to gather important information when events fire (for example, when a user logs into your application). Event tracing is highly scalable, and requires very little overhead (generally less than 5 percent CPU cycles at maximum load). The following diagram displays the event tracing model.

ms379597.operations_fig16(en-US,VS.80).gif

Figure 13. Event tracing model

Events are recorded by event tracing sessions. The event tracing model is the same as the event tracing model offered in ASP.NET 1.x, but several new events (for parsing, compilation and rendering) are available. The system can support up to 32 simultaneous event tracing sessions. On Windows 2000, two of these sessions are reserved for special purposes. On Windows XP, three of these sessions are reserved. The remaining sessions are available for general use. Each event tracing session maintains a set of buffers, called a buffer pool, where the tracing session temporarily stores event data.

ASP.NET 2.0 introduces many new events that are separated into four distinct areas:

  • Page: events that correspond to the execution of specific ASP.NET page-related events, such as Page_Load, etc.
  • Infrastructure: those events that are primarily related to the entering and leaving of various parts of the ASP.NET infrastructure
  • Module: events that are logged as a request enters and leaves various HTTP pipeline modules
  • AppService: those events that are logged as part of the new application services and functionality offered by ASP.NET 2.0

The events are logged into the ETW infrastructure (Event Tracing for Windows) described above.

Controllers

Event trace controllers start and stop event tracing sessions, manage buffer pools, and obtain execution statistics for sessions. Session statistics include the number of buffers used, the number of buffers delivered, the number of events and buffers lost, and the size and location of the log file, if it is used.

The command-line tool Logman.exe can be used to consume traces.

logman create trace ASPNET –o "mylog"
logman update trace ASPNET –pf events.txt

Listing 2. Controlling an event using the logman utility

Providers

Event trace providers are responsible for event delivery. The event trace provider registers the event classification and gives each event class a unique GUID that allows the class to talk to Windows services like the event listener. After an event tracer is registered, it can be enabled or disabled by an event trace controller. Generally, if a provider has been enabled, it generates events, but while it is disabled, it does not. ASP.NET has its own provider that you can view by running

logman query providers

Listing 3. Querying events with logman

Consumers

An event trace consumer can select one or more event tracing sessions as a source of events. A consumer can request events from multiple event tracing sessions and your system will return the events chronologically. Consumers can receive events stored in log files, or from sessions that deliver events in real time. You can specify the start and stop times to ensure that only events that occur in the specified time frame are delivered.

For more information about the event tracing model and event consumers, please look at the class reference that comes with .NET Framework 2.0.

Health Monitoring

In addition to the tracing model, ASP.NET 2.0 also provides full-featured application monitoring and health monitoring. This system consists of a fully extensible event model and an event engine that can send the events to a variety of sinks. For example, you can configure your ASP.NET application to send an e-mail every day indicating that the server is running and including the amount of free memory. Similarly, you can create a health event linked to unhandled exceptions. The exception contents, the request header, and the time and date can all be sent to an error logging database.

ASP.NET 2.0 includes built in events including a heartbeat, application lifetime events (start/stop/compile), and error trapping events (unhandled exceptions). However, you can easily build on these base classes to create and throw your own events from within your application. You might, for example, create a custom event to note when the one-hundredth user clicked on a particular link.

The real power of the ASP.NET 2.0 health monitoring system is that it is fully configurable through the Web.config and machine.config files. Using normal XML, you can define events, define providers (event sinks), and wire specific events to specific providers.

Creating an Event

An event is similar in structure to an exception. That is, the event class itself has very little functionality other than to act as a message container. In terms of health monitoring, all events inherit from Sytstem.Web.Management.WebBaseEvent. However, you can also derive from advanced base classes for specialized purposes such as gathering HTTP request data or handling exceptions.

using System;
using System.Web.Management;

public class CustomEvent : WebBaseEvent
{
  public const int EventCode = WebEventCodes.WebExtendedBase + 10;
  public MyEvent(string message, object eventSource) 
                : base(message, eventSource, EventCode)
  { }
}

Listing 4. A custom event

The most important part of creating a custom event is to provide a unique EventCode. All the built-in event codes are in the WebEventCodes enumeration. Custom events should have numbers that start with WebEventCodes.WebExtendedBase + 1. The only other common task in creating a custom event is to initialize the event properly.

Using Events

Although the built-in events automatically fire, you can add code to your application to launch custom events at any time:

<script runat="server">
  void Page_Load(Object sender, EventArgs e) {
    // Raise a custom event
    MyEvent myEvent = new MyEvent("loading webevent sample page", this);  
    myEvent.Raise();
  }
</script>

Listing 5. Raising an event

When you raise an event from an ASP.NET page, you simply create a new instance of the event and then execute the Raise() method. The Raise() method automatically passes the event instance to the health monitoring engine. The engine then maps the event to a profile and provider and hands the event over to the correct provider. The provider ultimately delivers the event to the proper sink.

Configuring Health Monitoring

Health monitoring is configured in the new <healthMonitoring> section in the machine.config or Web.config file. You can configure the <healthMonitoring> section to set up a Web heart beat that periodically reports the state of your application. You can also configure your application to generate events and pass the events through various providers.

Configuring Events

Each event must be identified in the event mappings section. Events are identified by a unique name and a full type. The event name is used as a link in the rules section:

  <!--  Event mappings define the events that are monitored -->
  <eventMappings>
    <add  name="SampleWebRequests" 
         type="Samples.AspNet.SampleWebRequestEvent,
               SampleWebRequestEvent,Version=0.0.0.0, Culture=neutral, 
               PublicKeyToken=f0c63b9a560d5e5a"/>
  </eventMappings>

Listing 6. The event mapping section

ASP.NET 2.0 comes with several built in events, which are configured to the following names:

  • All Events   The All Events name captures any WebBaseEvent. This event category is a broad catchall for every event captured by the health monitoring system.
  • Heart Beats    Heart beat events leverage WebHeartBeatEvent to provide regular notification on the status of a Web application.
  • Application Lifetime Events   Application lifetime events include starting and stopping the application, as well as recompiling all or part of the application. These events are based on WebApplicationLifetimeEvent, and report the date, time and current conditions when the lifetime event occurred.
  • All Errors   The All Errors category collects any exception or error detected by the system. These events are based on WebBaseErrorEvent.
  • Infrastructure Errors   Errors that are related to the ASP.NET runtime or IIS are captured using the WebErrorEvent. These events are a subclass of the All Errors category and relate primarily to system administrators rather than application developers.
  • Request Processing Errors   Any error or exception that occurs during a request triggers a WebRequestErrorEvent. This event records the request that came in and the error associated with processing the request. Request processing errors are also a subset of the All Errors category.
  • All Audits   The health monitoring system can be used to provide audit trials through the WebAuditEvent. This event automatically records the actions of the active user in a Web application. If you are using impersonation, the audit events will help you keep track of who is using your application and how they are using it.
  • Failure Audits   The WebFailureAuditEvent is a special type of audit event triggered when a user attempts to log in to your Web site with an invalid username or password. This event also occurs when a user cannot be validated for a specific resource.
  • Success Audits   The WebSuccessAuditEvent is the counterpart to the failure event and occurs whenever a user is authenticated or performs some other action that requires an audit record.

Custom events are easy to build, although you have to add code to your application to raise the events.

Configuring Providers

Each provider must be registered in the config file. Registering a provider requires an application-unique name and a type. The type contains the full strong name for the actual provider class. The provider name is used as a link in the rules section:

<healthMonitoring Enabled="true" heartBeatInterval="0">

  <!-- Providers link health events to various targets such as WMI or SMTP email -->
  <providers>
    <add name="WmiEventProvider"
         type="System.Web.Management.WebWmiEventProvider,
               System.Web,Version=1.2.3400.0,Culture=neutral,
               PublicKeyToken=b03f5f7f11d50a3a"/>
  </providers>

Listing 7. Providers

ASP.NET 2.0 comes with providers for WMI, the Windows Event Monitor, SMTP e-mail, and SQL Server databases. You can build custom providers to connect to other event sinks by extending the proper base class.

Mapping Events to Providers

The last step in configuring health monitoring is to use rules to wire up the events to the providers. A rule provides a link between a friendly event name, the event class, the provider, and the event profile, or category. You can also use rules to define a minimum interval for launching specific events.

  <!-- Rules link events to providers and profiles, and define 
intervals for event checking -->
  <rules>
    <add name="Custom Database Events"
      eventName="CustomDBEvents"
      provider="WmiEventProvider"
      profile="Database"
      minInterval="00:01:00" />
 
    <add name="Standard Web Requests"
      eventName="All Events"
      provider="SqlEventProvider"
      profile="Default"
      minInterval="00:01:00" />
  </rules>
 
</healthMonitoring>

Listing 8. Rules

A rule performs several different tasks that are configured through the various attributes:

  • name   The rule name is the friendly name that will appear when an event is sent to a sink.
  • eventName   The eventName maps to an event configured in the <eventMappings> section.
  • provider    The provider is a link to a provider configured in the <providers> section. Any event matching this rule will be passed through the provider to the target supported by the provider. For example, the System.Web.Management.SqlWebEventProvider will automatically write the event to a SQL Server database.
  • profile   Different providers use the profile attribute as a filter for displaying events. For example, an e-mail provider may immediately send a message for any event with a profile of "urgent" but may only send a daily e-mail with a compilation of the day's "routine" profile events.
  • minInterval   Some events, such as heart beats, must fire at a minimum interval. You can set the minimum event interval using this attribute.

Through this configuration section, you can set up various health-related events and map the events to various providers. You might, for example, set up a heart beat that sends a WMI event every 10 minutes. Similarly, you could set up an e-mail alert for any uncaught exceptions.

Summary

ASP.NET 2.0, IIS 6.0, and the .NET Framework 2.0 implement several new features that make deploying, configuring, monitoring, and maintaining Web applications easier than ever before for both professional Web site administrators and Web site hobbyists. Not only can you deploy your application using any of the new deployment methods, you can decide how the code should be deployed thanks to the new compilation options.

The built-in administrative Web site lets you create and configure users, configure data providers, and perform other administrative options through a secure Web interface. Similarly, the ASP.NET MMC snap-in lets you manage multiple Web sites on a single server using a simple interface. You no longer have to worry about manually editing config files or struggling with which application uses which version of the Framework. The ASP.NET console lets you control all of these items from a single interface.

Finally, in terms of monitoring, ASP.NET 2.0 expands on the monitoring available in ASP.NET 1.x by providing greater support for hit counters, tracing, debugging, and health monitoring. Developers can create counters for an application, page, or even a control on the page, and these counters can be read from a variety of sources.

ASP.NET 2.0 and IIS 6.0 combine to provide a very flexible and useful platform whether you are deploying and hosting a single simple application or many complex applications.

 

About the authors

Jayesh Patel—Jay Patel is a developer in both .NET Framework and Java technologies. Jay's research focuses on pattern-based programming and agile methodologies.

Bryan Acker—Bryan Acker is a technical writer for Infusion Development. Bryan has a strong background in ASP and ASP.NET Web development and Web hosting.

Robert McGovern—Rob McGovern is a senior writer, developer, and project manager for Infusion Development. Rob has worked on several different ASP.NET projects, including CodeNotes for ASP.NET and the JSP to ASP.NET migration guide. Rob is also a Microsoft MVP for Virtual Earth.

Infusion Development Corporation is a Microsoft Certified Solutions Provider offering customized software development, training, and consulting services for Fortune 1000 Corporations, with an emphasis on the financial-services industry. With offices in New York and Toronto, Infusion Development has established an international client base, including some of the world's largest companies in the financial service, securities brokerage, and software development industries.

© Microsoft Corporation. All rights reserved.