When the configuration file update is detected in themachine.config, ASP.NET creates a new application domain to service new requests.. Listing 31-7: HTTP Module configuration setting fr
Trang 1then that particular setting overrides the default ASP.NET setting inherited from themachine.config
or the rootweb.configfile Theweb.configfiles in the subdirectories or subfolders can override these
settings or inherit the settings (such as the 10-minute session timeout)
The configuration settings for virtual directories are independent of the physical directory structure
Unless the manner in which the virtual directories are organized is exclusively specified, configuration
problems can result
Note that these inheritance/override rules can be blocked in most cases by using theallowOverride =
"false"mechanism shown in Listing 31-3
Detecting Configuration File Changes
ASP.NET automatically detects when configuration files, such asmachine.configorweb.config, are
changed This logic is implemented based on listening for file-change notification events provided by the operating system
When an ASP.NET application is started, the configuration settings are read and stored in the ASP.NET cache A file dependency is then placed on the entry within the cache in themachine.configand/or
web.configconfiguration file When the configuration file update is detected in themachine.config,
ASP.NET creates a new application domain to service new requests The old application domain is
destroyed as soon as it completes servicing all its outstanding requests
Configuration File Format
The main difference betweenmachine.configandweb.configis the filename Other than that, their
schemas are the same Configuration files are divided into multiple groups The root-level XML element
in a configuration file is named<configuration> This pseudoweb.configfile has a section to control ASP.NET, as shown in Listing 31-6
Listing 31-6: A pseudo web.config file
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<section name="[sectionSettings]" type="[Class]"/>
<sectionGroup name="[sectionGroup]">
<section name="[sectionSettings]" type="[Class]"/>
</sectionGroup>
</configSections>
</configuration>
Values within brackets [ ] have unique values within the real configuration file.
The root element in the XML configuration file is always<configuration> Each of the section handlers and settings are optionally wrapped in a<sectionGroup> A<sectionGroup>provides an
organi-zational function within the configuration file It allows you to organize configuration into unique
groups — for instance, the<system.web>section group is used to identify areas within the configuration file specific to ASP.NET
Trang 2Config Sections
The<configSections>section is the mechanism to group the configuration section handlers associated
with each configuration section When you want to create your own section handlers, you must declare
them in the<configSections>section The<httpModules>section has a configuration handler that is
set toSystem.Web.Caching.HttpModulesSection, and the<sessionState>section has a configuration
handler that is set toSystem.Web.SessionState.SessionStateSectionclasses, as shown in Listing 31-7
Listing 31-7: HTTP Module configuration setting from the machine.config file
<configSections>
<sectionGroup>
<section name="httpModules"
type="System.Web.Configuration.HttpModulesSection,
System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</sectionGroup>
</configSections>
Common Configuration Settings
The ASP.NET applications depend on a few common configuration settings These settings are common
to both theweb.configandmachine.configfiles In this section, you look at some of these common
configuration settings
Connecting Strings
In ASP.NET 1.0 and 1.1, all the connection string information was stored in the<appSettings>section
However, ever since ASP.NET 2.0, a section called<connectionStrings>was included that stores all
kinds of connection-string information Even though storing connection strings in the<appSettings>
element works fine, it poses the following challenges:
❑ When connection strings are stored inappSettingssection, it is impossible for a data-aware
control such asSqlCacheDependencyorMembershipProviderto discover the information
❑ Securing connection strings using cryptographic algorithms is a challenge
❑ Last, but not least, this feature does not apply to ASP.NET only; rather, it applies to all the NET
application types including Windows Forms, Web Services, and so on
Because the connection-string information is stored independently of theappSettingssection, it can be
retrieved using the strongly typed collection methodConnectionStrings Listing 31-8 gives an example
of how to store connecting strings
Listing 31-8: Storing a connection string
<configuration>
<connectionStrings>
<add
name = "ExampleConnection"
Trang 3connectionString = "server=401kServer;database=401kDB;
uid=WebUser;pwd=P@$$worD9" />
</connectionStrings>
</configuration>
Listing 31-9 shows how to retrieve the connection string (ExampleConnection) in your code
Listing 31-9: Retrieving a connection string
VB
Public Sub Page_Load (sender As Object, e As EventArgs)
Dim dbConnection as New _
SqlConnection(ConfigurationManager.ConnectionStrings("ExampleConnection")
.ConnectionString)
End Sub
C#
public void Page_Load (Object sender, EventArgs e)
{
SqlConnection dbConnection = new
SqlConnection(ConfigurationManager.ConnectionStrings["ExampleConnection"]
.ConnectionString);
}
This type of construction has a lot of power Instead of hard-coding your connection strings into each
and every page within your ASP.NET application, you can store one instance of the connection string
centrally (in theweb.configfile for instance) Now, if you have to make a change to this connection
string, you can make this change in only one place rather than in multiple places.
Configuring Session State
Because Web-based applications utilize the stateless HTTP protocol, you must store the
application-specific state or user-application-specific state where it can persist TheSessionobject is the common store where
user-specific information is persisted Session store is implemented as aHashtableand stores data based
on key/value pair combinations
ASP.NET 1.0 and 1.1 had the capability to persist the session store data inInProc,StateServer, and
SqlServer ASP.NET 2.0 and 3.5 adds one more capability calledCustom TheCustomsetting gives
the developer a lot more control regarding how the session state is persisted in a permanent store For
example, out of the box ASP.NET 3.5 does not support storing session data on non-Microsoft databases such as Oracle, DB2, or Sybase If you want to store the session data in any of these databases or in a
custom store such as an XML file, you can implement that by writing a custom provider class (See the
section ‘‘Custom State Store’’ later in this chapter and Chapter 22 to learn more about the new session
state features in ASP.NET 3.5.)
You can configure the session information using the<sessionState>element as presented in Listing 31-10
Trang 4Listing 31-10: Configuring session state
<sessionState
mode="StateServer"
cookieless="false"
timeout="20"
stateConnectionString="tcpip=ExampleSessionStore:42424"
stateNetworkTimeout="60"
sqlConnectionString=""
/>
The following list describes each of the attributes for the<sessionState>element shown in the
preced-ing code:
❑ mode: Specifies whether the session information should be persisted The mode setting supports
five options:Off,InProc,StateServer,SQLServer, andCustom The default option isInProc
❑ cookieless: Specifies whether HTTP cookieless Session key management is supported
❑ timeout: Specifies theSessionlifecycle time Thetimeoutvalue is a sliding value; at each
request, the timeout period is reset to the current time plus the timeout value For example,
if thetimeoutvalue is 20 minutes and a request is received at 10:10 AM, the timeout occurs
at 10:30 AM
❑ stateConnectionString: Whenmodeis set toStateServer, this setting is used to identify the
TCP/IP address and port to communicate with the Windows Service providing state
management
❑ stateNetworkTimeout: Specifies the timeout value (in seconds) while attempting to store state in
an out-of-process session store such asStateServer
❑ sqlConnectionString: Whenmodeis set toSQLServer, this setting is used to connect to the SQL
Server database to store and retrieve session data
Web Farm Support
Multiple Web servers working as a group are called a Web Farm If you would like to scale out your
ASP.NET application into multiple servers inside a Web Farm, ASP.NET supports this kind of
deploy-ment out of the box However, the session data needs to be persisted in an out-of-process session state
such asStateServerorSQLServer
State Server
BothStateServerandSQLServersupport the out-of-process session state However, theStateServer
stores all the session information in a Windows Service, which stores the session data in memory Using
this option, if the server that hosts the session state service goes down in the Web farm, all the ASP.NET
clients that are accessing the Web site fail; there is no way to recover the session data
You can configure the session state service using the Services dialog available by choosing Start ➪
Set-tings ➪ Control Panel ➪ Administrative Tools ➪ Computer Management if you are using Windows XP,
and Start ➪ Control Panel ➪ System and Maintenance ➪ Administrative Tools ➪ Services if you are
using Windows Vista (as shown in Figure 31-2)
Trang 5Figure 31-2
Alternatively, you can start the session state service by using the command prompt and entering thenet startcommand, like this:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\> net start aspnet_state
The ASP.NET State Service service is starting
The ASP.NET State Service service was started successfully
All compatible versions of ASP.NET share a single state service instance, which is the service installed
with the highest version of ASP.NET For example, if you have installed ASP.NET 2.0 on a server where
ASP.NET 1.0 and 1.1 are already running, the ASP.NET 2.0 installation replaces the ASP.NET 1.1’s
state server instance The ASP.NET 2.0 service is guaranteed to work for all previous compatible versions
of ASP.NET.
SQL Server
When you choose theSQLServeroption, session data is stored in a Microsoft SQL Server database
Even if SQL Server goes down, the built-in SQL Server recovery features enable you to recover all the
Trang 6session data Configuring ASP.NET to support SQL Server for session state is just as simple as
configur-ing the Windows Service The only difference is that you run a T-SQL script that ships with ASP.NET,
InstallSqlState.sql The T-SQL script that uninstalls ASP.NET SQL Server support, called
Uninstall-SqlState.sql, is also included The install and uninstall scripts are available in the Framework folder
An example of using the SQL Server option is presented in Listing 31-11
Listing 31-11: Using the SQLServer option for session state
<configuration>
<system.web>
<sessionState
mode="SQLServer"
sqlConnectionString="data source=ExampleSessionServer;
user id=ExampleWebUser;password=P@55worD"
cookieless="false"
timeout="20"
/>
</system.web>
</configuration>
ASP.NET accesses the session data stored in SQL Server via stored procedures By default, all the session
data is stored in the Temp DB database However, you can modify the stored procedures so they are
stored in tables in a full-fledged database other than Temp DB
Even though the SQL Server–based session state provides a scalable use of session state, it could become
the single point of failure This is because SQL Server session state uses the same SQL Server database for
all applications in the same ASP.NET process This problem has been fixed ever since ASP.NET 2.0, and
you can configure different databases for each application Now you can use theaspnet_regsql.exe
utility to configure this However, if you are looking for a solution for older NET Frameworks, a fix is
available athttp://support.microsoft.com/default.aspx?scid = kb;EN-US;836680.
Because the connection strings are stored in the strongly typed mode, the connection string information
can be referenced in other parts of the configuration file For example, when configuring session state to
be stored in SQL Server, you can specify the connection string in theconnectionStringssection, and
then you can specify the name of the connection string in the<sessionState>element, as shown in
Listing 31-12
Listing 31-12: Configuring session state with a connection string
<configuration>
<connectionStrings>
<add name = "ExampleSqlSessionState"
connectionString = "data source=ExampleSessionServer;
user id=ExampleWebUser;password=P@55worD" />
</connectionStrings>
<system.web>
<sessionState
mode="SQLServer"
sqlConnectionString="ExampleSqlSessionState"
Trang 7timeout="20"
/>
</system.web>
</configuration>
Custom State Store
The session state in ASP.NET 3.5 is based on a pluggable architecture with different providers that inherit theSessionStateStoreProviderBaseclass If you want to create your own custom provider or use a
third-party provider, you must set the mode toCustom
You specify the custom provider assembly that inherits theSessionStateStoreProviderBaseclass, as
shown in Listing 31-13
Listing 31-13: Working with your own session state provider
<configuration>
<system.web>
<sessionState
mode="Custom"
customProvider="CustomStateProvider">
<providers>
<add name="CustomStateProvider"
type="CustomStateProviderAssembly, CustomStateProviderNamespace.CustomStateProvider"/>
</providers>
</sessionState>
</system.web>
</configuration>
In the previous example, you have configured the session state mode as custom because you have speci-fied the provider name asCustomStateProvider From there, you add the provider element and include the type of the provider with namespace and class name
You can read more about the provider model and custom providers in Chapters 12 and 13.
Compilation Configuration
ASP.NET supports the dynamic compilation of ASP.NET pages, Web services, HttpHandlers, ASP.NET application files (such as theGlobal.asaxfile), source files, and so on These files are automatically
compiled on demand when they are first required by an ASP.NET application
Any changes to a dynamically compiled file causes all affected resources to become automatically invali-dated and recompiled This system enables developers to quickly develop applications with a minimum
of process overhead because they can just press Save to immediately cause code changes to take effect
within their applications
Trang 8The ASP.NET 1.0 and 1.1 features are extended in ASP.NET 2.0 and 3.5 to account for other file types,
including class files The ASP.NET compilation settings can be configured using the<compilation>
section inweb.configormachine.config The ASP.NET engine compiles the page when necessary and
saves the generated code in code cache This cached code is used when executing the ASP.NET pages
Listing 31-14 shows the syntax for the<compilation>section
Listing 31-14: The compilation section
<! compilation Attributes >
<compilation
tempDirectory="directory"
debug="[true|false]"
strict="[true|false]"
explicit="[true|false]"
batch="[true|false]"
batchTimeout="timeout in seconds"
maxBatchSize="max number of pages per batched compilation"
maxBatchGeneratedFileSize="max combined size in KB"
numRecompilesBeforeAppRestart="max number of recompilations "
defaultLanguage="name of a language as specified in a <compiler/> element below"
<compilers>
<compiler language="language"
extension="ext"
type=".NET Type"
warningLevel="number"
compilerOptions="options"/>
</compilers>
<assemblies>
<add assembly="assembly"/>
</assemblies>
<codeSubDirectories>
<codeSubDirectory directoryName="sub-directory name"/>
</codeSubDirectories>
<buildproviders>
<buildprovider
extension="file extension"
type="type reference"/>
</buildproviders>
</compilation>
Now take a more detailed look at these<compilation>attributes:
❑ batch: Specifies whether the batch compilation is supported The default value istrue
❑ maxBatchSize: Specifies the maximum number of pages/classes that can be compiled into a
single batch The default value is 1000
❑ maxBatchGeneratedFileSize: Specifies the maximum output size of a batch assembly
compila-tion The default value is 1000 KB
❑ batchTimeout: Specifies the amount of time (minutes) granted for batch compilation to occur If
this timeout elapses without compilation being completed, an exception is thrown The default
value is 15 minutes
❑ debug: Specifies whether to compile production assemblies or debug assemblies The default
is false
Trang 9❑ defaultLanguage: Specifies the default programming language, such asVBorC#, to use in
dynamic compilation files Language names are defined using the<compiler>child element
The default value isVB
❑ explicit: Specifies whether the Microsoft Visual Basic code compile option is explicit The
default istrue
❑ numRecompilesBeforeAppRestart: Specifies the number of dynamic recompiles of resources
that can occur before the application restarts
❑ strict: Specifies the setting of the Visual Basic strict compile option
❑ tempDirectory: Specifies the directory to use for temporary file storage during compilation
By default, ASP.NET creates the temp file in the[WinNT\Windows]\Microsoft.NET\Framework\ [version]\Temporary ASP.NETFiles folder
❑ compilers: The<compilers>section can contain multiple<compiler>subelements, which are used to create a new compiler definition:
❑ Thelanguageattribute specifies the languages (separated by semicolons) used in dynamic compilation files For example,C#; VB
❑ Theextensionattribute specifies the list of filename extensions (separated by semicolons) used for dynamic code For example,.cs; vb
❑ Thetypeattribute specifies NET type/class that extends theCodeDomProviderclass used
to compile all resources that use either the specified language or the file extension
❑ ThewarningLevelattribute specifies how the NET compiler should treat compiler
warn-ings as errors Five levels of compiler warnwarn-ings exist, numbered 0 through 4 When the compiler transcends the warning level set by this attribute, compilation fails The meaning
of each warning level is determined by the programming language and compiler you’re using; consult the reference specification for your compiler to get more information about the warning levels associated with compiler operations and what events trigger compiler warnings
❑ ThecompilerOptionsattribute enables you to include compiler’s command-line switches while compiling the ASP.NET source
❑ assemblies: Specifies assemblies that are used during the compilation process
❑ codeSubDirectories: Specifies an ordered collection of subdirectories containing files
com-piled at runtime Adding thecodeSubDirectoriessection creates separate assemblies
❑ buildproviders: Specifies a collection of build providers used to compile custom resource files
Browser Capabilities
Identifying and using the browser’s capabilities is essential for Web applications The browser capabili-ties component was designed for the variety of desktop browsers, such as Microsoft’s Internet Explorer, Netscape, Opera, and so on The<browserCaps>element enables you to specify the configuration
settings for the browser capabilities component The<browserCaps>element can be declared at the
machine, site, application, and subdirectory level
TheHttpBrowserCapabilitiesclass contains all the browser properties The properties can be set and
retrieved in this section The <browserCaps> element has been deprecated since ASP.NET 2.0 and now
you should instead focus on using.browserfiles.
Trang 10When a request is received from a browser, the browser capabilities component identifies the browser’s
capabilities from the request headers
For each browser, compile a collection of settings relevant to applications These settings may either
be statically configured or gathered from request headers Allow the application to extend or modify the
capabilities settings associated with browsers and to access values through a strongly typed object model
The ASP.NET mobile capabilities depend on the browser capabilities component
In ASP.NET 3.5, all the browser capability information is represented in browser definition files The
browser definitions are stored in*.browserfile types and specified in XML format A single file may
contain one or more browser definitions The*.browserfiles are stored in theConfig\Browsers
subdirec-tory of the Framework installation direcsubdirec-tory (for example,[WinNT\Windows]\Microsoft.NET\Framework\
v2.0.50727\CONFIG\Browsers), as shown in Figure 31-3 Application-specific browser definition files are
stored in the/Browserssubdirectory of the application
In ASP.NET 1.0 and 1.1, the browser cap information was stored in themachine.configandweb.config
files themselves.
Figure 31-3