Understanding the ASP.NET Configuration System


ASP.NET provides an extensible, XML-based configuration system that is easy to use and easy to customize. The root configuration file, Machine.config , provides ASP.NET configuration settings for every application in the Web server. In addition, every ASP.NET application contains its own configuration file, called Web.config , which resides in the root of the application. This file provides configuration settings for all files in the root directory and for every child directory below the root.

Machine.config and Web.config are structured the same way, and they define many of the same settings. The Web.config file overrides many of the settings in Machine.config , within the scope of the specific ASP.NET application where the Web.config file resides. ASP.NET also allows you to set up a hierarchy of Web.config files so that every child directory can have its own. The settings in the child directory's Web.config file override the settings in the root directory's Web.config file. The root directory's file, in turn , overrides many settings in the server-level Machine.config file. Certain settings in the Machine.config file have server-level scope and cannot be overridden by individual Web.config files. This includes, for example, the <processModel> configuration element, which controls the behavior of the ASP.NET worker process. You can still access the configuration values and modify them as needed, but you can only do this in Machine.config .

Benefits of ASP.NET Configuration

The ASP.NET configuration system provides several benefits over classic ASP:

  • XML-based file format: The configuration files are XML based, so they are readable and can be edited in any XML editor or in Visual Studio .NET directly. As of this writing, no editor exists specifically for ASP.NET configuration files. The one drawback to this is that you can easily introduce syntax errors into the file during editing. These errors can break the build during compilation, and you may only receive an ambiguously worded error. Make sure you edit configuration files one key at a time and rebuild the application often between edits. This will allow you to catch syntax errors immediately after they occur.

  • Optimized access to settings: The ASP.NET runtime engine caches configuration settings, so they are readily accessible throughout the application. The configuration file provides an excellent alternative to using Application variables for caching global configuration settings.

  • Automatic refresh when settings change: The ASP.NET runtime engine automatically picks up changes to configuration files and applies them to the local application for all subsequent requests. Configuration changes do not require an IIS reset because the application will restart automatically once all current requests have completed. (This feature is convenient , but be aware that if your application uses in-memory session variables, then this information will be lost during an application restart).

  • Extensible for adding custom settings: The ASP.NET configuration system is extensible. The system uses handler classes for processing configuration settings, and these existing classes may be used for processing your own custom configuration settings. Alternatively, you can create custom handler classes to handle the processing.

  • Protected settings: ASP.NET configuration files are protected from direct browser access, so your settings are protected from prying eyes. You may still want to rethink storing passwords in the configuration files because any written password is automatically a security liability. For example, SQL connection strings are commonly stored in configuration files. (You can avoid storing connection strings directly by setting up a trusted connection between the Web server and the SQL Server. Chapter 3, "Writing Optimized Data Access Code," discusses trusted connections.)

Some of these advantages will be obvious to you, but others are probably unfamiliar and require further explanation. The issues will become clearer once you take a closer look at the ASP.NET configuration system. Before proceeding, we need to point out that there is some ambiguity to the term configuration setting because most ASP.NET configuration settings are multidimensional. For example, the <sessionState> configuration element provides several attributes, including mode and timeout. It becomes unclear whether the term setting refers to the element (which has no direct value) or to the attributes ”or to both. To avoid confusion, we will refer to configuration elements and attributes, where the element holds the name and the attributes hold the values. We will use the term configuration setting for the sum total of a configuration element and its attributes.

The Machine.config File

The Machine.config file is located in the folder %windir%\Microsoft.NET\Framework\%version%\config , where %version% is a folder that is named for the current installed version of the .NET Framework. The Machine.config file serves two purposes. First, it defines what the configuration elements are. Second, it specifies initial values for every element's attributes. The Machine.config file is divided into two sections:

  • The configuration section handler (CSH) section: This section provides definitions for the configuration elements, using section handlers. A section handler simply specifies the name of the configuration element and the name of the handler class that will process the configuration attribute values.

  • The configuration implementation section: This section specifies initial attribute values for every configuration element. Essentially , this section implements the configuration elements defined in the previous section.

The terminology sounds confusing, but it is actually straightforward. Listing 2-4 shows a stripped-down version of the Machine.config file.

Listing 2-4: A Simple Machine.config File
start example
 <?xml version="1.0" encoding="UTF-8"?> <  configuration  >      <  configSections  >          <  sectionGroup  name="  system.web  ">              <  section  name="  httpHandlers  "                   type="System.Web.Configuration.HttpHandlersSectionHandler,                       System.Web"/>              <  section  name="  sessionState  "                   type="System.Web.SessionState.SessionStateSectionHandler,                       System.Web " allowDefinition="MachineToApplication"/>              <  section  name="  trace  "                   type="System.Web.Configuration.TraceConfigurationHandler,                      System.Web "/>          </  sectionGroup  >      </  configSections  >      <  system.web  >           <  sessionState  mode="InProc" stateConnectionString="               tcpip=127.0.0.1:42424"               stateNetworkTimeout="10" sqlConnectionString="data source=127.0.0.1;               user id=sa;password=" cookieless="false" timeout="20"/>           <  trace  enabled="false" localOnly="true" pageOutput="false"                    requestLimit="10"                    traceMode="SortByTime"/>           <  httpHandlers  >                    <add verb="*" path="*.aspx"                             type="System.Web.UI.PageHandlerFactory"/>                    <add verb="*" path="trace.axd"                             type="System.Web.Handlers.TraceHandler"/>           </httpHandlers>      </  system.web  > </configuration> 
end example
 

The <configuration> node is the root node for the overall file. The section handlers are contained within the <configSections> tags. A section handler is simply an XML tag that defines the name of the configuration element and the type (or class ) that processes the configuration attribute values. Listing 2-4 shows section handlers for the <httpHandlers> , <sessionState> , and <trace> configuration elements. Notice the convention of using Pascal-case, or camel-case , for element and attribute names . The Web.config file is case sensitive and will generate compilation errors if it includes a section handler that does not use camel-case. For example, you must type the attribute value for <sessionState> mode as "InProc" ”not as "Inproc" or a similar variation. Notice also the use of section groups, which organize section handlers into related groups. The listing shows a section group called system.web .

The lower half of the file, between the <system.web> tags, is the implementation section. This section specifies initial values for the configuration elements defined in the top half of the file. You do not see the attributes defined directly in the file; instead, you can only see where they are implemented. The handler classes actually define what the element attributes are. The handler class is also responsible for returning an object that provides programmatic access to the configuration element. For example, the handler class for <sessionState> returns an object of type HttpSessionState. Again, you can't tell this from the configuration file. The lesson here is to document your classes well should you develop your own custom handler classes! The .NET Framework provides a number of generic handler classes in addition to the specialized classes. You should find the available handler classes to be adequate for defining most configuration elements.

The Web.config File

The Web.config file is easy to understand once you know how the Machine.config file is structured. Everything you can do in Machine.config , you can also do in Web.config . This means you can create new section handlers and implement existing ones. When you create a new ASP.NET application project using Visual Studio .NET, it will automatically create a Web.config file in the root. If you open this file, you will notice that all of its contents are devoted to implementing existing configuration elements. In fact, <configSections> elements are not initially added to the file. You can override almost any configuration setting (with the exception of <processModel> ) by adding it to the Web.config file and then changing one or more attribute values. Table 2-4 summarizes the ASP.NET configuration elements that are initially included in the Web.config file.

Table 2-4: The ASP.NET Configuration Elements

ELEMENT

DESCRIPTION

Authentication

This element sets the authentication policy for the application. Possible modes are "Windows," "Forms," "Passport," and "None."

Authorization

This element sets the authorization policy for the application. You can allow or deny access to application resources by user or by role. Also, you can use wildcards: * for everyone and ? for anonymous (unauthenticated) users.

Compilation

This element sets several compilation settings for the application, including whether the debug mode is "True." This mode inserts debugging symbols into the compiled page. Debug pages are larger and execute more slowly, so you should use them only for testing purposes.

Custom Errors

This element allows you to set custom error pages for specific errors if the mode is set to "On." If the mode is set to "RemoteOnly," then remote users will see custom errors, and local users will see standard ASP.NET error screens that contain full details of the error, including a stack trace. If the mode is set to "Off," then all users will see the standard ASP.NET error screens.

Globalization

This element sets the character encoding for requests and responses. The default value is "UTF-8."

SessionState

This element sets the Session State mode for the application. Possible modes are "InProc," "SQLServer," "StateServer," and "None." Chapter 4, "Optimizing Application and Session State Management," discusses session state.

Trace

This element sets attributes for application-level tracing. Trace logs may post directly to a page, or they may be stored in a trace.axd file. Chapter 8, "Debugging and Tracing ASP.NET Applications," discusses tracing.

The Machine.config file contains several other configuration elements that are not initially included in the Web.config file. The most important of these elements are <processModel> and <httpRuntime> , which directly affect the performance, availability, and stability of your ASP.NET applications. These elements are discussed in some detail in the "Optimal ASP.NET Configuration" section.

Custom Configuration Elements

The power of ASP.NET configuration lies in its extensibility. You can easily define custom configuration elements using generic handler classes. Alternatively, you can add custom elements as key-value pairs without having to define a handler class. The configuration files allow you to add custom elements in two ways:

  • Application settings: Add key-value pairs to a specialized section handler called <appSettings> . The setting is defined and implemented in the same line using the key-value attribute values.

  • Custom configuration settings: Add custom section handlers directly into <configSections> . You can either create a custom handler class or use a generic handler class. You must implement the setting in a separate area of the file.

The details of each approach will become immediately clear when you see some examples. But first we need to mention the System.Configuration namespace, without which it would not be possible to define and to read custom configuration settings. Table 2-5 summarizes the more important class members in the System.Configuration namespace.

Table 2-5: The System.Configuration Namespace

CLASS MEMBER

DESCRIPTION

IConfigurationSectionHandler

Defines the interface that must be implemented in all configuration handler classes for them to resolve configuration settings.

NameValueSectionHandler

Provides name-value pair configuration information for a configuration section handler. You can implement this class handler in your own custom sections.

DictionarySectionHandler

Provides key-value pair configuration information for a configuration section handler. You can implement this class handler in your own custom sections.

ConfigurationSettings

Provides access to configuration settings in a specific configuration section.

AppSettings

Provides access to custom sections in the <appSettings> section group.

GetConfig()

Provides access to custom sections in the <configSections> section group.

The System.Configuration namespace includes generic handler classes you can use in custom configuration settings. These include NameValueSectionHandler and DictionarySectionHandler. The namespace includes a class called ConfigurationSettings, which gives you read-only, programmatic access to configuration settings once they have been defined and implemented.

Now let's take a look at examples of the two approaches for defining custom configuration elements.

Application Settings

Application settings are simply key-value pairs that you define to store custom values. They are stored as child <add> elements below the <appSettings> element, which in turn resides below the root <configuration> element. Each <add> element contains key and value attributes. Application settings are appropriate for simple information that is widely accessed throughout the ASP.NET application. Database connection strings are one good example:

 <configuration>     <appSettings>         <add key=" ConnectionString"             value=" server=machineName\sqlServer;uid=sa;pwd=;database=dev;" />     </appSettings> </configuration> 

You have programmatic access to this key value using the AppSettings property of the ConfigurationSettings class:

 ' Retrieve the connection string from Web.config Dim strConn As String = _              ConfigurationSettings.AppSettings("ConnectionString") Response.Write("The 'Connection String' is: "& strConn) 

Application settings are quick and easy to use but are limited in what they can store.

Custom Configuration Settings

You must define custom configuration settings by adding a section handler to the <configSections> element. You can also add section groups to organize the custom section handlers. Consider the following example: Define a menu system that associates screen names with Web page names. The menu elements should be enclosed in a section group. The XML definition could look something like this:

 <!-- configuration settings --> <configSections>         <!-- Declares a section group called myMenuGroup -->         <sectionGroup name="myMenuGroup">                  <!-- Declares a section name called myMenuItem -->                  <section name="myMenuItem"                    type="System.Configuration.DictionarySectionHandler, System,                      Version=1.0.3300.0, Culture=neutral,                      PublicKeyToken=b77a5c561934e089"/>         </sectionGroup> </configSections> 

Notice that we have written a full type definition of the handler class for the <myMenuItem> element. The .NET runtime was unable to load the DictionarySectionHandler class unless the full type definition was provided. Now you can implement some menu items:

 <!-- Menu details: key=[Screen Name]; value=[Web Page Name] --> <myMenuGroup>         <myMenuItem>                   <add key="Login" value="login.aspx"/>                   <add key="Browse" value="browse.aspx"/>                   <add key="Purchase" value="purchase.aspx"/>                   <add key="Tracking" value="tracking.aspx"/>                   <add key="Logout" value="logout.aspx"/>         </myMenuItem> </myMenuGroup> 

You have programmatic access to the menu items using the GetConfig() static method of the ConfigurationSettings class:

 ' Retrieve myMenu items from Web.config Dim dctMenuItems As IDictionary Dim enmMenuItems As IDictionaryEnumerator dctMenuItems = ConfigurationSettings.GetConfig("myMenuGroup/myMenuItem") enmMenuItems = dctMenuItems.GetEnumerator() While enmMenuItems.MoveNext()     Response.Write(enmMenuItems.Key & ": " & enmMenuItems.Value & "<BR>") End While 

Optimal ASP.NET Configuration

Much of the discussion in this book focuses on how to improve the performance of your ASP.NET applications. The ASP.NET configuration system is as much about efficiency as it is about performance. It is efficient to store application-level configuration settings in XML-based files that are cached at runtime. In classic ASP, application-level information is typically stored in Application variables, which have more drawbacks than benefits. For example, Application variables must be compiled into the application, and their values can be changed in only two ways. One way is to reset the value in code, then recompile the Web application. This change requires an application restart to take effect. The other way is to provide programmatic access to the variable so that users can change the value at runtime. This approach creates concurrency problems and can lead to unstable Web applications. Classic ASP essentially provides no intrinsic support for a system administrator to update a configuration setting in an outside source location and then have the changes smoothly propagated through the Web application. Developers can, and do, implement workaround systems, but it shouldn't have to be that hard!

On the issue of performance, the ASP.NET configuration system provides several settings that directly control the performance and availability of ASP.NET applications. Two of the best examples include the <processModel> and the <httpRuntime> elements.

The ASP.NET Worker Process

ASP.NET provides new safeguards against performance crashes by isolating ASP.NET execution in a separate process from IIS. This process is called the ASP.NET worker process , or aspnet_wp.exe . Classic ASP applications typically run in the same process as IIS, which means that memory leaks and resource crunches can cause the IIS process to become unstable and lock up or crash. Classic ASP applications may also be configured to run in a separate process, but this approach may reduce application performance by up to a factor of 10. ASP.NET anticipates that issues and errors can occur in applications, so the worker process is designed to shut down and recycle automatically in the event that errors occur.

The Common Language Runtime (CLR) adds an additional level of stability because it provides type safety, optimized memory management, and automatic garbage collection. Stray pointers and unused references should never linger on the .NET managed heap as long as the application is written entirely using managed code. However, the .NET Framework supports unmanaged COM+ components , using its COM InterOp Services support. Unmanaged code operates outside of the control of the CLR and may generate memory leaks. ASP.NET applications that use unmanaged code are susceptible to the very application instability problems that the CLR is designed to prevent.

The ASP.NET worker process is designed with fault tolerance in mind to ensure the maximum availability for your ASP.NET application. ASP.NET is designed, under certain conditions, to shut down the existing worker process and to create a new process thread. This action may disrupt the requests for a certain number of users, but it may also prevent the application from experiencing a crash, which would ultimately affect all users for a certain period of time. The ASP.NET worker process is configured in the Machine.config file only, using the <processModel> element. Several of the element's attributes set the conditions under which the worker process must be recycled. This happens, for example, if the number of queued requests grows too large or if the process has been idle for a certain amount of time. Table 2-6 describes several of the <processModel> element's important attributes.

Table 2-6: The <processModel> Configuration Element

ATTRIBUTE

DESCRIPTION

Enable

Enables the processModel settings. The default value is "True."

Timeout

The total life of the process before it must be shut down and recycled. This is equivalent to an absolute expiration timestamp and will occur regardless of how well or poorly the process is running. However, the Timeout is specified in duration, rather than a specific date. The default value is "Infinite."

IdleTimeout

The amount of time that the process can be idle before it is shut down. The default value is "Infinite," meaning that an idle process will never shut down.

ShutdownTimeout

The amount of time that the process is given to shut down gracefully before it is killed . ASP.NET initially sets this value to 5 seconds, [0:00:05].

RequestLimit

The total number of requests to serve before the process is shut down. The default value is "Infinite."

RequestQueueLimit

The number of queued requests allowed before the process is shut down. ASP.NET initially sets this value to 5,000 requests. We recommend setting this number closer in line to 20 percent higher than your maximum expected loads.

RestartQueueLimit

The number of requests kept in queue while the process is restarting. For example, if the value is set to 10, then the 11 th user would receive an HTTP 403 error, or equivalent, indicating that the server has understood the request but is refusing (too busy) to fulfill it. The default value is "10," but you may want to increase this value for high-volume Web sites.

MemoryLimit

The percentage of physical memory that the process is allowed to use before it must be recycled. ASP.NET initially sets this value to 60 percent, but you should choose a percentage with which you feel comfortable. Some administrators may feel more comfortable setting the percentage to 50 percent or lower, in order to stay well clear of the "red zone," in which all server processes begin to get affected by sharply reduced available memory. Of course, this percentage depends on what other processes and applications are running on the server.

ClientConnectedCheck

The amount of time that a request is left in the queue before ASP.NET checks to verify that the client is still connected. ASP.NET initially sets this value to 5 seconds, [0:00:05]. This feature is extremely useful for handling the scenario where a user gets impatient waiting for a server response and clicks the submit button (in other words, resubmitting the form) multiple times. Doing so effectively disconnects earlier requests. The clientConnectedCheck attribute saves ASP.NET from having to waste time servicing requests that are currently disconnected.

ResponseDeadlockInterval

Provides deadlock detection. The amount of time allowed for a response while a request is still executing. ASP.NET initially sets this value to 3 minutes, [0:03:00].

responseRestartDeadlockInterval

The amount of time to wait before restarting the worker process following a deadlock. ASP.NET initially sets this value to 9 minutes, [0:09:00].

MaxWorkerThreads

The maximum number of worker threads per CPU. ASP.NET initially sets this value to 25. We do not recommend changing this value, although the allowed range is from 5 to 100.

MaxIOThreads

The maximum number of IO threads per CPU. ASP.NET initially sets this value to 25. We do not recommend changing this value, although the allowed range is from 5 to 100.

The HTTP Runtime Engine

The HTTP runtime engine is responsible for managing the processing of HTTP requests. This includes delegating requests to the appropriate handler classes. The <httpRuntime> configuration element provides attributes for optimizing how the HTTP runtime engine works. The element can be included in the Web.config file and modified on a per-application basis. Initially, the element is defined in the Machine.config only, so it applies across all ASP.NET applications. The <httpRuntime> element settings provide an additional line of defense against application crashes. Table 2-7 summarizes several of the <httpRuntime> element's important attributes.

Table 2-7: The <httpRuntime> Configuration Element

ATTRIBUTE

DESCRIPTION

ExecutionTimeout

The amount of time before a request is timed out. ASP.NET initially sets this value to 90 seconds.

maxRequestLength

The maximum request length that ASP.NET will accept, in kilobytes (Kb). ASP.NET initially sets this value to 4096 Kb. This attribute is designed to prevent denial-of-service attacks that occur through repeated large file uploads that overwhelm a Web server. You should set this value close to the largest size file you expect to have uploaded.

MinFreeThreads

The minimum number of free threads that will be kept available for processing new requests. ASP.NET initially sets this value to 8.

MinLocalRequestFreeThreads

The minimum number of free threads that will be kept available for processing new local requests. New local threads may be spawned for multithreaded processing on the Web server. This attribute reduces the chances for deadlocks by ensuring that a minimum pool of threads is reserved for local, multithreaded processes.

AppRequestQueueLimit

The maximum number of requests that will be queued when no threads are available for additional processing. Additional requests will receive an HTTP 403 error, or equivalent, indicating that the server has understood the request but is refusing (too busy) to fulfill it. The default value is 100.




Performance Tuning and Optimizing ASP. NET Applications
Performance Tuning and Optimizing ASP.NET Applications
ISBN: 1590590724
EAN: 2147483647
Year: 2005
Pages: 91

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