Listing 31-47: Creating your own custom key-value pair section in the web.config After you have this in place within yourweb.configfile, you can then programmatically get access
Trang 1requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices"
type="System.Web.Configuration.ScriptingWebServicesSectionGroup,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="jsonSerialization"
type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
requirePermission="false" allowDefinition="Everywhere"/>
<section name="profileService"
type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="authenticationService"
type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"
requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="roleService"
type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
Once you have made this reference to theSystem.Configuration.NameValueFileSectionHandlerobject and have given it a name (in this case,MyCompanyAppSettings), then you can create a section in your
web.configthat makes use of this reference This is illustrated in Listing 31-47
Listing 31-47: Creating your own custom key-value pair section in the web.config
<configuration>
<MyCompanyAppSettings>
<add key="Key1" value="This is value 1" />
<add key="Key2" value="This is value 2" />
</MyCompanyAppSettings>
<system.web>
<! Removed for clarity >
</system.web>
</configuration>
After you have this in place within yourweb.configfile, you can then programmatically get access to
this section, as illustrated in Listing 31-48
Trang 2Listing 31-48: Getting access to your custom section in the web.config file
VB
Dim nvc As NameValueCollection = New NameValueCollection()
nvc = System.Configuration.ConfigurationManager.GetSection("MyCompanyAppSettings")
Response.Write(nvc("Key1") + "<br />")
Response.Write(nvc("Key2"))
C#
NameValueCollection nvc = new NameValueCollection();
nvc = ConfigurationManager.GetSection("MyCompanyAppSettings") as
NameValueCollection;
Response.Write(nvc["Key1"] + "<br />");
Response.Write(nvc["Key2"]);
For this to work, you are going to have to import theSystem.Collections.Specializednamespace into
the file, as this is where you will find theNameValueCollectionobject
Using the DictionarySectionHandler Object
TheDictionarySectionHandlerworks nearly the same as theNameValueFileSectionHandler.The
dif-ference, however, is that theDictionarySectionHandlerreturns aHashTableobject instead of returning
anObject
This handler is presented in Listing 31-49
Listing 31-49: Making a reference to the DictionarySectionHandler object
<configSections>
<section name="MyCompanyAppSettings"
type="System.Configuration.DictionarySectionHandler, System,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
restartOnExternalChanges="false" />
<! Removed for clarity >
</configSections>
Once in place, you can then make the sameMyCompanyAppSettingssection in theweb.configfile, as
shown in Listing 31-50
Listing 31-50: Creating your own custom key-value pair section in the web.config
<configuration>
<MyCompanyAppSettings>
<add key="Key1" value="This is value 1" />
<add key="Key2" value="This is value 2" />
Trang 3<system.web>
<! Removed for clarity >
</system.web>
</configuration>
Now that theweb.configfile is ready, you can call the items from code using theConfigurationAPI, as illustrated in Listing 31-51
Listing 31-51: Getting access to your custom section in the web.config file
VB
Dim ht As Hashtable = New Hashtable()
ht = System.Configuration.ConfigurationManager.GetSection("MyCompanyAppSettings")
Response.Write(ht("Key1") + "<br />")
Response.Write(ht("Key2"))
C#
Hashtable ht = new Hashtable();
ht = ConfigurationManager.GetSection("MyCompanyAppSettings") as
Hashtable;
Response.Write(ht["Key1"] + "<br />");
Response.Write(ht["Key2"]);
Using the SingleTagSectionHandler Object
TheSingleTagSectionHandlerworks almost the same as the previousNameValueFileSectionHandler
andDictionarySectionHandler However, this object looks to work with a single element that contains the key-value pairs as attributes
This handler is presented in Listing 31-52
Listing 31-52: Making a reference to the DictionarySectionHandler object
<configSections>
<section name="MyCompanyAppSettings"
type="System.Configuration.SingleTagSectionHandler, System,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
restartOnExternalChanges="false" />
<! Removed for clarity >
</configSections>
Once in place, you can make a differentMyCompanyAppSettingssection in theweb.configfile, as
presented in Listing 31-53
Trang 4Listing 31-53: Creating your own custom key-value pair section in the web.config
<configuration>
<MyCompanyAppSettings Key1="This is value 1" Key2="This is value 2" />
<system.web>
<! Removed for clarity >
</system.web>
</configuration>
Now that theweb.configfile is complete, you can call the items from code using theConfiguration
API, as illustrated in Listing 31-54
Listing 31-54: Getting access to your custom section in the web.config file
VB
Dim ht As Hashtable = New Hashtable()
ht = System.Configuration.ConfigurationManager.GetSection("MyCompanyAppSettings")
Response.Write(ht("Key1") + "<br />")
Response.Write(ht("Key2"))
C#
Hashtable ht = new Hashtable();
ht = ConfigurationManager.GetSection("MyCompanyAppSettings") as
Hashtable;
Response.Write(ht["Key1"] + "<br />");
Response.Write(ht["Key2"]);
Using Your Own Custom Configuration Handler
You can also create your own custom configuration handler To do this, you first need to create a class that
represents your section in theweb.configfile In your App_Code folder, create a class calledMyCompany
Settings This class is presented in Listing 31-55
Listing 31-55: The MyCompanySettings class
VB
Public Class MyCompanySettings
Inherits ConfigurationSection
<ConfigurationProperty("Key1", DefaultValue:="This is the value of Key 1", _
IsRequired:=False)> _
Public ReadOnly Property Key1() As String
Get Return MyBase.Item("Key1").ToString()
Trang 5End Get
End Property
<ConfigurationProperty("Key2", IsRequired:=True)> _
Public ReadOnly Property Key2() As String
Get
Return MyBase.Item("Key2").ToString() End Get
End Property
End Class
C#
using System.Configuration;
public class MyCompanySettings : ConfigurationSection
{
[ConfigurationProperty("Key1", DefaultValue = "This is the value of Key 1",
IsRequired = false)]
public string Key1
{
get
{
return this["Key1"] as string;
}
}
[ConfigurationProperty("Key2", IsRequired = true)]
public string Key2
{
get
{
return this["Key2"] as string;
}
}
}
You can see that this class inherits from theConfigurationSectionand the two properties that are
created using theConfigurationPropertyattribute You can use a couple of attributes here, such as the
DefaultValue,IsRequired,IsKey, andIsDefaultCollection
Once you have this class in place, you can configure your application to use this handler, as illustrated in Listing 31-56
Listing 31-56: Making a reference to the MyCompanySettings object
<configSections>
<section name="MyCompanySettings" type="MyCompanySettings" />
<! Removed for clarity >
</configSections>
You can now use this section in yourweb.configfile, as illustrated in Listing 31-57
Trang 6Listing 31-57: Creating your own custom key-value pair section in the web.config
<configuration>
<MyCompanySettings Key2="Here is a value for Key2" />
<system.web>
<! Removed for clarity >
</system.web>
</configuration>
From there, you can programmatically access this from code, as illustrated in Listing 31-58
Listing 31-58: Getting access to your custom section in the web.config file
VB
Dim cs As MyCompanySettings = New MyCompanySettings()
cs = ConfigurationManager.GetSection("MyCompanySettings")
Response.Write(cs.Key1 + "<br />")
Response.Write(cs.Key2)
C#
MyCompanySettings cs = ConfigurationManager.GetSection("MyCompanySettings") as
MyCompanySettings;
Response.Write(cs.Key1 + "<br />");
Response.Write(cs.Key2);
Summar y
In this chapter, you have seen the ASP.NET configuration system and learned how it does not rely on the
IIS metabase Instead, ASP.NET uses an XML configuration system that is human-readable
You also looked at the two different ASP.NET XML configuration files:
Themachine.configfile applies default settings to all Web applications on the server However, if the
server has multiple versions of the framework installed, themachine.configfile applies to a particular
framework version On the other hand, a particular Web application can customize or override its own
configuration information usingweb.configfiles Using aweb.configfile, you can also configure the
applications on an application-by-application or folder-by-folder basis
Next, you looked at some typical configuration settings that can be applied to an ASP.NET application,
such as configuring connecting strings, session state, browser capabilities, and so on Then you looked at
an overview of new ASP.NET Admin Objects and learned how to program configuration files Finally,
you learned how to protect the configuration section using cryptographic algorithms
Trang 7Instr umentation
Many ASP.NET developers do more than just build an application and walk away They definitely
think about how the application will behave after it is deployed Instrumentation is the task that
developers undertake to measure and monitor their ASP.NET applications Depending on the
situ-ation, some instrumentation operations occur at design time, whereas others are ongoing processes
that begin at runtime
ASP.NET 3.5 gives you greater capability to apply instrumentation techniques to your applications
You will find that the ASP.NET framework includes a large series of performance counters, the
capability to work with the Windows Event Tracing system, possibilities for application tracing
(covered in Chapter 24), and the most exciting part of this discussion — a health monitoring system
that allows you to log a number of different events over an application’s lifetime
You can monitor a deployed application in several ways First, you learn how to work with the
Windows event log
Wor king with the Event Log
When working with Visual Studio 2008, you can use the event log in the Server Explorer of the
IDE in a couple of different ways You can get to the event log section in the Server Explorer by
expanding the view of the server you want to work with (by clicking the plus sign next to the
server) until you see the Event Logs section You also have the option to right-click the Event Logs
node and select Launch Event Viewer from the list of available options This selection displays the
same Event Viewer you are familiar with From the Event Viewer or from the Server Explorer you
can work directly with events recorded to your system
The other option available from the Server Explorer is to expand the Event Logs node of the tree
view in the Server Explorer so that you can see the additional nodes such as Application,
Secu-rity, and System If you are on Windows Vista, you will see a series of additional event categories
Expanding any of these sub-nodes allows you to see all the events that have been registered in the
event log These events are arranged by type, which makes browsing for specific events rather easy,
as illustrated in Figure 32-1
Trang 8Figure 32-1
Reading from the Event Log
It is possible to read and to write events to and from the event log from your NET application If you are
interested in reading events from the event log, you can do so rather simply by using theEventLogobject
that is provided by NET in theSystem.Diagnosticsnamespace
To see an example of using this object, you can create an ASP.NET page that displays all the entries
contained within a specified event log To create it, you need a DropDownList control, a Button control,
and a GridView control In Visual Studio NET 2002 and 2003, a Components tab was located within the
Toolbox, and you could simply drag and drop the Event Log component onto your design surface in
order to start working with it In Visual Studio 2005, you won’t find this tab within the Toolbox, but it
still isn’t too hard to find the objects you need Listing 32-1 shows the simple ASP.NET page that enables
you to easily display the contents of the event log
Listing 32-1: Displaying the contents of the event logs within the browser
VB
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Diagnostics" %>
<script runat="server">
Trang 9Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Dim el As EventLog = New EventLog()
el.Source = DropDownList1.SelectedItem.Text
GridView1.DataSource = el.Entries
GridView1.DataBind()
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Working with Event Logs</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Application</asp:ListItem>
<asp:ListItem>Security</asp:ListItem>
<asp:ListItem>System</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Submit" /><br />
<br />
<asp:GridView ID="GridView1" runat="server"
BackColor="LightGoldenrodYellow" BorderColor="Tan"
BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None">
<FooterStyle BackColor="Tan" />
<SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
<PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
HorizontalAlign="Center" />
<HeaderStyle BackColor="Tan" Font-Bold="True" />
<AlternatingRowStyle BackColor="PaleGoldenrod" />
<RowStyle VerticalAlign="Top" />
</asp:GridView>
</div>
</form>
</body>
</html>
C#
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Diagnostics" %>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
EventLog el = new EventLog();
el.Source = DropDownList1.SelectedItem.Text;
GridView1.DataSource = el.Entries;
GridView1.DataBind();
}
Trang 10Note that you are going to have to run this with credentials that have administrative rights for this code
sample to work.
For this code to work, you import theSystem.Diagnosticsnamespace if you are not interested in fully
qualifying your declarations After you do so, you can create an instance of theEventLogobject to give
you access to theSourceproperty In assigning a value to this property, you use theSelectedItem.Text
property from the DropDownList control on the page Next, you can provide all theEventLogentries as
the data source value to the GridView control Finally, you bind this data source to the GridView In the
end, you get something similar to the results illustrated in Figure 32-2
Figure 32-2
As you can see, it is simple to pull all the events from the event log and write them to the browser screen
The next section looks at writing values back to the event log
Writing to the Event Logs
Not only can you read from the event logs, but you can write to them as well This can be quite handy if
you want to record specific events in an event log The following table provides a short description of the
main event logs available to you Windows Vista has other event categories, but these are the main event
categories that you will use