Lab 8: ASP.NET 2.0 Configuration API and Health Monitoring Estimated time to complete this lab: 45 minutes ASP.NET 2.0 s configuration API fills a hole in ASP.NET 1.x by providing an easy-to-use and extensible API for reading and writing configuration settings. Applications can now read their own configuration settings without parsing raw XML, and they see a merged view of those settings that includes settings inherited from configuration files higher in the directory hierarchy. Moreover, writing configuration settings is as easy as reading them, and implementing custom configuration sections requires little more than deriving from System.Configuration.ConfigurationSection. Health monitoring, sometimes called Web events, is another notable addition to the platform. Thanks to the health monitoring subsystem, a few simple statements in Web.config can configure an application to write an entry to the Windows event log when a login fails, e-mail a system administrator when an unhandled exception occurs, and more. In addition, you can extend the health monitoring subsystem by defining Web events of your own. The purpose of this lab is to acquire first-hand experience with both the configuration API and health monitoring. You ll begin by enabling Failure Audit events in the MyComics application you ve been working on since Lab 2 and seeing what happens when someone tries to log in with an invalid user name or password. Then you ll use the configuration API to allow administrators to turn Failure Audits on and off from MyComics admin page. Next, you ll implement a custom Web event and modify MyComics to fire that event when comics are deleted from the admin page. Finally, you ll use the SQL Server Web event provider to record custom Web events in a SQL Server database. Lab Setup If you have not completed Lab 2 (ASP.NET 2.0 Data Access) previous to this lab, enable database caching as follows: a. Open a Visual Studio command prompt window. You ll find it under All Programs->Microsoft Visual Studio 2005 ->Visual Studio Tools->Visual Studio Command Prompt. b. Navigate to the C:\MSLabs\ASP.NET\LabFiles\Database directory. c. Type CacheSetup.
2 Lab 8: ASP.NET 2.0 Configuration API and Health Monitoring Exercise 1 Enable Failure Audit events Failure audit events fire when the membership service detects a failed login and in response to other failures during an application s lifetime. In this exercise, you ll enable Failure Audit events in MyComics, configure them to use the Windows event log provider, and use the Windows Event Viewer to audit failed login attempts Tasks 1. Copy the Security database Detailed Steps a. Copy ASPNETDB.MDF and aspnetdb_log.ldf from the C:\MSLabs\ASP.NET\Starter\<Language>\Lab4\App_Data folder to the C:\MSLabs\ASP.NET\Starter\<Language>\Lab8\App_Data folder. This database was created when you ran the ASP.NET Configuration tool in Lab 4. It contains the security settings for the Web application, including users, roles and access rules. 2. Open the Web site a. Start Microsoft Visual Studio and use the File->Open Web Site command to open the C:\MSLabs\ASP.NET\Starter\<Language>\Lab8 site. 3. Enable Failure Audit events 4. Perform some failed logins 5. View the Windows event log a. Double-click Web.config in Solution Explorer to open it for editing. b. Add the following statements to the <system.web> section of Web.config: <healthmonitoring enabled="true"> <rules> <remove name="failure Audits Default" /> <add name="mycomics Failure Audit Events" eventname="failure Audits" provider="eventlogprovider"/> </rules> </healthmonitoring> c. Save your changes and close Web.config. a. Launch Default.aspx and click the Login button to go to the login page. b. Attempt to log in with an invalid user name or password. c. Repeat the previous step several times to generate a series of Failure Audit events. d. Close your browser and return to Visual Studio. a. Open the Windows Event Viewer (All Programs->Control Panel->Administrative Tools->Event Viewer). b. Double-click Application in Event Viewer s left pane. c. Examine the entries in the right pane. Do you see entries reflecting the failed login attempts? d. Double-click one of the entries corresponding to a failed login attempt. What kind of information do you see there? Is it possible to discern the user name (or names) used in the failed login attempts? e. Suppose you wanted to limit log entries reporting failed login attempts to no more than one every five seconds. How would you go about it? f. Close the Windows Event Viewer and return to Visual Studio.
Lab 8: ASP.NET 2.0 Configuration API and Health Monitoring 3 Exercise 2 Build a configuration interface In this exercise, you ll modify MyComics admin page to enable administrators to turn Failure Audit events on and off by clicking a check box. You ll use the configuration API to toggle the setting. Tasks 1. Add a CheckBox to Admin.aspx 2. Use the configuration API to turn Web events on and off Detailed Steps a. Open Admin.aspx in the designer and switch to Design view. It is in Secure folder. b. Add a CheckBox to the right of the DropDownList. Insert a couple of spaces between the DropDownList and the CheckBox to provide some separation between the two. c. Set the CheckBox s Text property to Enable Web events. d. Set the CheckBox s AutoPostBack property to true. e. Set the CheckBox s Font to 10-point Verdana. f. Double-click the CheckBox to add a CheckedChanged event handler. a. Add the following statement to the using statements already present in Admin.aspx.<cs or vb>: using System.Web.Configuration; Imports System.Web.Configuration b. Add the following code to the body of the CheckBox1_CheckedChanged method: Configuration config = WebConfigurationManager.OpenWebConfiguration (Request.ApplicationPath); ConfigurationSectionGroup group = config.sectiongroups["system.web"]; HealthMonitoringSection section = (HealthMonitoringSection) group.sections["healthmonitoring"]; section.enabled = CheckBox1.Checked; config.save (); Dim config As Configuration = _ WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath) Dim group As ConfigurationSectionGroup = config.sectiongroups("system.web") Dim section As HealthMonitoringSection = _ CType(group.Sections("healthMonitoring"), HealthMonitoringSection) section.enabled = CheckBox1.Checked config.save c. Add the following Page_Load method to the Admin_aspx class in Admin.aspx.<cs or vb> to initialize the check box so that it reflects the current enabled/disabled state of health monitoring: If the Page_Load method is not in the code, go to design view and double click on the page so it is created. void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) { Configuration config = WebConfigurationManager.OpenWebConfiguration (Request.ApplicationPath); ConfigurationSectionGroup group = config.sectiongroups["system.web"]; HealthMonitoringSection section =
4 Lab 8: ASP.NET 2.0 Configuration API and Health Monitoring } } (HealthMonitoringSection) group.sections["healthmonitoring"]; CheckBox1.Checked = section.enabled; If Not Page.IsPostBack Then Dim config As Configuration = _ WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath) Dim group As ConfigurationSectionGroup = _ config.sectiongroups("system.web") Dim section As HealthMonitoringSection = _ CType(group.Sections("healthMonitoring"), HealthMonitoringSection) CheckBox1.Checked = section.enabled End If 3. Test the results a. Launch Default.aspx and click the Admin link at the top of the page to go to the login page. b. Log in using the Administrator account you created in Lab 4 to go to the admin page. c. Verify that the Enable Web events check box is present and that it s checked, as shown below. d. Click Enable Web events to uncheck it. e. Return to Visual Studio and open Web.config. How has the <healthmonitoring> element changed? f. Close Web.config and return to your browser. g. Click the Logout link to log out. h. Click the Admin link to go back to the login page. i. Try to log in several times with an invalid user name or password. j. Log in using the Administrator account you created in Lab 4. k. Use the Windows Event Viewer to view Application events. Verify that no entries appear there for the failed login attempts you just performed. l. Go back to your browser where Admin.aspx is showing and click Enable Web events to check it. m. Click the Logout link to log out. n. Click the Admin link to go back to the login page.
Lab 8: ASP.NET 2.0 Configuration API and Health Monitoring 5 o. Try to log in several times with an invalid user name or password. p. Use the Windows Event Viewer to view Application events. Verify that the event log contains entries reflecting the failed login attempts you just performed. q. Close the Windows Event Viewer and your browser and return to Visual Studio.
6 Lab 8: ASP.NET 2.0 Configuration API and Health Monitoring Exercise 3 Implement a custom Web event One of the characteristics of the health monitoring subsystem is that it s extensible. You can define Web events of your own and fire them from your code. In this exercise, you ll define a custom Web event named MyComicsWebEvent that fires when the admin page is used to delete a comic from the database. Then you ll log instances of that event in the Windows event log. Tasks 1. Create the MyComicsWebE vent class Detailed Steps a. Right-click C:\..\Lab8 in Solution Explorer and use the Add ASP.NET Folder- >Bin command to create a new folder named Bin. b. Right-click C:\..\Lab8 in Solution Explorer and use the New Folder command to create a new folder named Source. NOTE: You re going to place the source code for MyComicsWebEvent in the Source directory instead of the Code directory because custom Web event classes don t work if they re autocompiled. Specifically, they don t get autocompiled early enough in the application s lifetime to be properly recognized in Web.config. The solution is to compile them separately and drop the resulting assemblies into the application s bin subdirectory. c. Right-click the Source folder and use the Add New Item command to add a class named MyComicsWebEvent. If Visual Studio warns that the class should go in the Code directory and asks if you d rather put it there instead, answer No. d. Add the following statement above the Public Class MyComicsWebEvent statement: using System.Web.Management; Imports System.Web.Management e. Implement the MyComicsWebEvent class as follows: public class MyComicsWebEvent : WebBaseEvent { int _comicid; public MyComicsWebEvent (string message, object source, int eventcode, int comicid) : base (message, source, eventcode) { _comicid = comicid; } public override void FormatCustomEventDetails (WebEventFormatter formatter) { formatter.appendline ("Comic ID: " + _comicid.tostring()); } } Namespace MyComicsWebEvent Public Class MyComicsWebEvent Inherits WebBaseEvent Dim _comicid As Integer Public Sub New(ByVal message As String, ByVal source As Object, ByVal
Lab 8: ASP.NET 2.0 Configuration API and Health Monitoring 7 eventcode As Integer, ByVal comicid As Integer) MyBase.New(message, source, eventcode) _comicid = comicid End Sub Public Overrides Sub FormatCustomEventDetails(ByVal formatter As System.Web.Management.WebEventFormatter) MyBase.FormatCustomEventDetails(formatter) formatter.appendline("comic ID: " & _comicid.tostring) End Sub End Class End Namespace f. Open a Visual Studio Command Prompt window (All Programs->Microsoft Visual Studio 2005 Beta->Visual Studio Tools->Visual Studio Command Prompt). g. Type cd \MSLabs\ASP.NET\Starter\< or CS>\Lab8\source to go to the Source directory. h. Execute the following commands to compile MyComicsWebEvent.<cs or vb> and place the resulting assembly in the bin subdirectory: cd \MSLabs\ASP.NET\Starter\CS\Lab8\source csc /t:library /out:..\bin\mycomicswebevent.dll MyComicsWebEvent.cs cd \MSLabs\ASP.NET\Starter\\Lab8\source vbc /t:library /out:..\bin\mycomicswebevent.dll MyComicsWebEvent.vb i. Make sure that the compilation succeeded. Then close the Visual Studio Command Prompt window and return to Visual Studio. j. Right click on the Bin folder and choose Refresh Folder. You should now see the dll you just built in Solution Explorer. 2. Modify Admin.aspx to fire MyComicsWebE vents a. Open Admin.aspx in the designer and switch to Design view. b. Click the ObjectDataSource1 control to select it. c. Go to the Properties window and click the lightning bolt icon to display a list of ObjectDataSource events. d. Double-click Deleting to add a handler for ObjectDataSource1.Deleting events. e. Add the following statement to the using statements already present in Admin.aspx.<cs or vb>: using System.Web.Management; Imports System.Web.Management f. Add the following field declaration to the Admin_aspx class. This field will be used to store the ID of the comic that s about to be deleted when the ObjectDataSource fires a Deleting event: int _comicid = -1; Dim _comicid as Integer = -1 g. Add the following statement to the ObjectDataSource1_Deleting method: _comicid = (int) e.inputparameters[0]; _comicid = CInt(e.InputParameters(0))
8 Lab 8: ASP.NET 2.0 Configuration API and Health Monitoring 3. Register MyComics WebEvents h. Add the following statements to the ObjectDataSource1_Deleted method already present in Admin.aspx.<cs or vb> to fire a MyComicsWebEvent when a comic is deleted: MyComicsWebEvent mcwe = new MyComicsWebEvent("Comic book deleted", null, 100001, _comicid); WebBaseEvent.Raise(mcwe); Dim mcwe As New MyComicsWebEvent.MyComicsWebEvent( _ "Comic book deleted", sender, 100001, _comicid) WebBaseEvent.Raise(mcwe) a. Double-click Web.config in Solution Explorer to open it for editing. b. Add the following section to the <healthmonitoring> section of Web.config:, task 4 <eventmappings> <add name="mycomics Web Events" type="mycomicswebevent, MyComicsWebEvent" /> </eventmappings> c. Add the following element to the <rules> section of Web.config: <add name="mycomics Web Events" eventname="mycomics Web Events" provider="eventlogprovider" /> d. Save your changes and close Web.config. 4. Test the results a. Launch the Admin page in your browser. b. Go to the admin page and verify that the Enable Web events box is checked. (If it s not, check it.) c. Click one of the Delete buttons to delete a comic book. d. Start the Windows Event Viewer and double-click Application to view application events. e. Verify that the custom Web event appears in the event log, as shown below. Verify that the event code is 100001 and that the event message is Comic book deleted. Scroll down in the description box and verify that the ID of the comic that was deleted appears, too.
Lab 8: ASP.NET 2.0 Configuration API and Health Monitoring 9
Exercise 4 Use the SQL Server Web Event Provider EventLogProvider logs Web events in the Windows event log, but other providers enable Web events to be logged in other media. The SQL Server Web event provider, for example, permits Web events to be logged in ASP.NET s SQL Server database. In this exercise, you ll use the SQL Server Web event provider to log MyComicsWebEvents in SQL Server. Tasks Detailed Steps 1. Change providers a. Open Web.config and change this: <add name="mycomics Web Events" eventname="mycomics Web Events" provider="eventlogprovider" /> to this: <add name="mycomics Web Events" eventname="mycomics Web Events" provider="sqlwebeventprovider" /> b. Add the following section to the <healthmonitoring> section of Web.config: <buffermodes> <add name="buffer" maxbuffersize="1000" maxflushsize="100" urgentflushthreshold="100" regularflushinterval="00:05:00" urgentflushinterval="00:01:00" maxbufferthreads="1"/> </buffermodes> <providers> <remove name="sqlwebeventprovider" /> <add name="sqlwebeventprovider" type="system.web.management.sqlwebeventprovider" buffermode="buffer" connectionstringname="localsqlserver"/> </providers> c. Save your changes and close Web.config. 2. Fire several MyComicsWebEvents. 3. View the events in SQL Server a. Launch MyComics in your browser. b. Go to the admin page and verify that the Enable Web events box is checked. (If it s not, check it.) c. Delete several comic books using the admin page s Delete buttons. a. Select the Solution Explorer window. b. Click the plus sign next to the App_Data directory and right click on ASPNETDB.MDF, select Open c. Click the plus sign next to ASPNETDB ->Tables to view the Tables. d. Right click aspnet_webevent_events and select Show Table Data. e. Verify that the MyComicsWebEvents were logged in the database s aspnet_webevents_events table.