Flylib.com

Books Software

 
 
 

Configuration in the .NET Framework


Configuration in the .NET Framework

The .NET Framework provides three basic types of configuration files: machine, security, and application. Despite their different contents and goals, all configuration files are XML documents and share the same schema. For example, all configuration files begin with a <configuration> node and then differentiate their contents and child nodes according to the final goal and the information they contain.

The XML Schema of Configuration Files

Configuration files are standard XML files that follow a given schema. The schema defines all possible settings for machine, security, and application files. The .NET Framework provides made-to-measure classes to read configuration settings, but no writing facilities are provided. You need to be familiar with XML writers if you want to directly edit the configuration files. (In light of this, bear in mind that XML elements and attribute names are strictly case-sensitive.)

All configuration files have their root in the <configuration> element. Table 12-1 lists the first-level children of the <configuration> element. Each node has a specified number of child elements that provide a full description of the setting. For example, the <system.web> element optionally contains the <authorization> tag in which you can store information about the users who can safely access the ASP.NET application.

Table 12-1: Children of the <configuration> Element

Element

Description

<appSettings>

Contains custom application settings in the specified XML format.

<configSections>

Describes the configuration sections for custom settings. If this element is in a configuration file, it must be the first child of the <configuration> root.

<mscorlib>
   <cryptographySettings >

Cryptography schema; describes the elements that map friendly algorithm names to classes that implement cryptography algorithms.

<runtime>

Run-time settings schema; describes the elements that configure assembly binding and run-time behavior such as probing and assembly redirect.

<startup>

Startup settings schema; contains the elements that specify which version of the common language runtime (CLR) must be used.

<system.diagnostics>

Describes the elements that specify trace switches and listeners that collect, store, and route messages.

<system.net>

Network schema; specifies elements to indicate how the .NET Framework connects to the Internet, including the default proxy, authentication modules, and connection parameters.

<system.runtime.remoting>

Settings schema; configures the client and server applications that exploit the .NET Remoting.

<system.web>

It's the ASP.NET-specific configuration section; contains the elements that control all aspects of the behavior of an ASP.NET application.

Because we're focusing on ASP.NET applications, only the <system.web> section has particular importance for us and only that will be covered in detail. However, this doesn't mean that, as an ASP.NET developer, you'll never be using other sections—most certainly you will!

For example, you'll need <appSettings> and <configSections> if you plan to persist user -profile information on the server, read working information such as connection strings, or specify advertising pictures to rotate. The <configSections> element defines the sections that will be used to group information in the rest of the document. The <appSettings> element contains user-defined nodes whose structure has been previously defined in the <configSections> node. You might need to interact with the <system.diagnostics> section if you want to use a custom trace listener that logs to an application-defined file. You'll probably need <runtime> if some special rules for probing assemblies are required. Furthermore, if the ASP.NET application performs calls to some remote component, you must adjust settings in the <system.runtime.remoting> section.

The elements in Table 12-1 are used to compose the various .config files that all .NET applications are based on in some way. Let's learn a bit more about their internal structure.

The Machine Configuration File

The machine configuration file is named machine.config and is located in the CONFIG subdirectory of the .NET Framework installation path. The first path shown in the following code is typical of version 1.0 of the .NET Framework; the second path refers to version 1.1 of the .NET Framework:

C:\WINNT\Microsoft.NET\Framework\v1.0.3705\CONFIG C:\WINNT\Microsoft.NET\Framework\v1.1.4322\CONFIG

The machine.config file contains machinewide settings that apply to assembly binding, built-in remoting channels, and the ASP.NET runtime. In particular, the machine.config file contains information about the browser capabilities, registered HTTP handlers, and page compilation. Here's an excerpt from machine.config that shows compilation and assembly default settings:

<?xml version="1.0" encoding="UTF-8"?> <configuration> <configSections>



</configSections>



<system.web>



<compilation debug="false" explicit="true" defaultLanguage="vb"> <compilers> <compiler language="c#;cs;csharp" extension=".cs" ... /> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" ... /> <compiler language="js;jscript;javascript" extension=".js" ... />

<compiler language="VJ#;VJS;VJSharp"


extension=".jsl" ... />

</compilers> </compilation> <assemblies> <add assembly="mscorlib"/> <add assembly="System, Version=1.0.5000.0, ... " /> <add assembly="System.Web, Version=1.0.5000.0, ... " /> <add assembly="System.Data, Version=1.0.5000.0, ... " /> <add assembly="System.Web.Services, Version=1.0.5000.0, ... /> <add assembly="System.Xml, Version=1.0.5000.0, ... /> <add assembly="System.Drawing, Version=1.0.5000.0, ... /> <add assembly="System.EnterpriseServices, ... />

<add assembly="System.Web.Mobile, ... />

<add assembly="*" /> </assemblies>



</system.web>



</configuration>

Note 

The lines in boldface type refer to changes in version 1.1 of the .NET Framework. Also, notice that the version number of the assemblies in version 1.1 is 1.0.5000.0.

Declaring a section in the machine.config file enables you to exploit those settings from within any ASP.NET application that runs on that computer. Note, though, that settings defined in machine.config can be overwritten and even canceled in the application configuration file (web.config). More on this later in the "ASP.NET Applications Configuration" section.

Security Configuration Files

Security configuration files contain information about the code groups and the permission sets associated with a policy level. A code group is a logical grouping of code that specifies certain conditions for membership. Any code that meets the given criteria can be included in the group. Code groups have associated permission sets. A permission set, in turn , defines the resources that can be accessed at execution time. A policy level describes all the security measures for the specified context—enterprise, machine, or user. The CLR grants permissions to an assembly based on the minimum set of permissions granted by any of the policy levels.

Security configuration files have names and locations that depend on the policy level. The configuration file for the enterprise policy level is named enterprisesec.config and resides in the same directory as the machine.config file. Contained in the same folder, the security.config file characterizes the machine policy level. The enterprise level groups security settings for the entire enterprise; the machine policy level, on the other hand, defines the security for the local machine. Both levels can be configured only by an administrator.

The user policy configuration file affects the code in all the processes associated with the user. Named security.config , the file resides in a folder under the user profile subtree . The path for a machine running version 1.1 of the .NET Framework is shown here.

C:\Documents and Settings\[UserName]\Application Data\Microsoft\ CLR Security Config\v1.1.4322

Caution 

Editing the contents of the security files, and thereby modifying the security policies, is a potentially critical task that should be accomplished using the .NET Framework Configuration administrative tool (an MMC snap-in named mscorcfg .msc) or the Code Access Security Policy tool (a command-line tool named caspol .exe).

Application Configuration Files

Application-specific configuration files contain settings consumed by the CLR as well as by the application itself. The CLR reads information such as the assembly binding policy, the location of remote objects, and ASP.NET runtime settings. The application can read settings that correspond to the parameters it needs to work within. The name and location of the application configuration file depend on the application's model, which can be one of the following: Windows Forms or console executable, ASP.NET application or Web service, or Internet Explorer–hosted application. Table 12-2 shows the names used.

Table 12-2: Configuration Files for Applications

Application Type

Configuration File

Windows Forms

[ApplicationName].exe.config

Console

[ApplicationName].exe.config

ASP.NET

web.config

Web service

web.config

Hosted by Internet Explorer

The name of the file doesn't have to follow specific rules, but the location must be on the same virtual directory as the application.

More often than not, configuration files contain sensitive information the CLR and the ASP.NET runtime need to know and process. Both the CLR and the ASP.NET runtime treat XML files that have a particular name (for example, web.config) as special resources. For this reason, you can't really use different names for them. What you can do, instead, is move the application-specific information—the content of the <appSettings> section—to a distinct file. (More on this later in the "Persisting Application Settings" section.) If you move system information out of the web.config file, that information will easily be ignored by the ASP.NET runtime and might affect the overall functionality of the application.

Managing Configuration Settings

All sections used in a configuration file must be declared in the initial <configSections> section. The following code snippet demonstrates how the <system.web> section is declared in machine.config:

<configSections>



<sectionGroup name="system.web">



<section name="compilation" type="CompilationConfigurationHandler, System.Web, ... /> <section name="pages" type="PagesConfigurationHandler, System.Web, ... />



</sectionGroup>



</configSections>

The <sectionGroup> element has no other role than marking and grouping a few child sections, thus creating a sort of namespace for them. In this way, you can have sections with the same name living under different groups. The <section> element takes two attributes— name and type . The name attribute denotes the name of the section being declared. The type attribute indicates the name of the managed class that reads and parses the contents of the section from the configuration file. The value of the type attribute is a comma-separated string that includes the class and full name of the assembly that contains it.

The <section> element also has two optional attributes— allowDefinition and allowLocation specifically targeted at ASP.NET applications. These two attributes are ignored by configuration readers controlled by other types of applications. The allowDefinition attribute specifies which configuration files the section can be used in. Feasible values for the allowDefinition attribute are in Table 12-3.

Table 12-3: Values for the allowDefinition Attribute

Value

Description

Everywhere

The section can be used in any configuration file. (Default.)

MachineOnly

The section can be used only in the machine.config file.

MachineToApplication

The section can be used in the machine.config file and in the application's web.config file. You cannot use the section in web.config files located in subdirectories of the virtual folder.

{% if main.adsdop %}{% include 'adsenceinline.tpl' %}{% endif %}

The allowLocation attribute determines whether the section can be used within the <location> section. The <location> section in a machine.config file allows you to apply the specified machinewide settings only to the resources below a given path. (More on the <location> element later in the "The <location> Section" section.)

Many sections in the configuration files support three special elements named <add>, <remove>, and <clear>. The <add> element adds a new setting to the specified section, while <remove> removes the specified one. The <clear> element clears all the settings that have previously been defined in the section. The <remove> and <clear> elements are particularly useful in ASP.NET configuration files in which a hierarchy of files can be created. For example, you can use the <remove> element in a child web.config file to remove settings that were defined at a higher level in the configuration file hierarchy.

The <remove> and <clear> elements don't affect the actual data stored in the configuration file. Removing a section doesn't erase the related data from the file, it simply removes the data from the in-memory tree of settings that ASP.NET builds and maintains for an application.

Note 

Sections are a necessary syntax element in configuration files. However, you don't need to declare sections in all application-specific web.config files. When processing a web.config file, in fact, the reader builds a configuration tree starting from the root machine.config file. Because all standard sections are already declared in the machine.config that ships with the .NET Framework, your application needs to declare only custom sections you plan to use.

Finally, bear in mind that an exception is thrown if a configuration section lacks a corresponding entry in the <configSections> section and when the layout of the data does not match the declaration.

The ConfigurationSettings Class

To programmatically read application settings, you use the ConfigurationSettings class from the System.Configuration namespace. ConfigurationSettings is a small, sealed class that simply provides one static method ( GetConfig ) and one static property ( AppSettings ).

The AppSettings property is a read-only NameValueCollection object designed to get the information stored in the <appSettings> section. If no setting is specified, or if no <appSettings> section exists, an empty collection is returned. The GetConfig method returns the configuration settings for the specified section, as shown here:

public static object GetConfig(string sectionName);

Although the method signature indicates an object return type, the actual return value you get from a call to GetConfig is determined by the handler class specified for the requested section. Internally, the GetConfig method first determines the name and location of the configuration file to access and then proceeds by creating a specialized XML text reader to operate on the XML document.

A more specialized tool for reading application settings is the AppSettingsReader class. This class provides a single method, named GetValue , for reading values of a particular type from the configuration file. The GetValue method takes two arguments—the name of the setting to retrieve and the type to return—as shown here:

public object GetValue(string key, Type type);

The GetValue method retrieves the value of the given setting using the AppSettings property and then performs an automatic cast to the specified type. Unlike the AppSettings property of the ConfigurationSettings object, the GetValue method works in a strongly typed way.

Section Handlers

A section handler is a .NET Framework class that implements the IConfigurationSectionHandler interface. It interprets and processes the configuration settings stored in a section and stores them in an appropriate object. The XML schema of the input data and the type of the returned object depend on the implementation of the section handler. A few predefined section handlers exist and are listed in Table 12-4. All these section handlers belong to the System.Configuration namespace and are implemented in the System assembly.

Table 12-4: Predefined Section Handlers

Class

Description

DictionarySectionHandler

Reads name/value pairs, and groups them in a hash-table object.

IgnoreSectionHandler

The System.Configuration classes ignore the sections marked with this handler because their contents will be processed by other components . This handler is an alternative to using and declaring custom handlers.

NameValueFileSectionHandler

Reads name/value pairs from a file referenced in the <appSettings> section, and groups them in a NameValueCollection object. This handler allows you to link an external, custom file to web.config.

NameValueSectionHandler

Reads name/value pairs, and groups them in a NameValueCollection object.

SingleTagSectionHandler

Reads settings from attributes stored in a single XML node. The data is returned as a hash table.

The IgnoreSectionHandler handler deserves a bit more attention. The handler simply tells the system's configuration reader to ignore any data stored under the specified section. It could be argued that one shouldn't flood a system's .config file with data that will be processed outside the standard configuration pipeline. Although this is a strong recommendation for user code, some system modules (for example,.NET Remoting) store some of their general settings in the machine.config file but then use internal readers to process the information. To preserve file consistency and avoid exceptions, the IgnoreSectionHandler handler is used. A better alternative is either using a custom configuration file or defining a custom section handler.

Later in this chapter in the "Creating New Configuration Sections" section, we'll discuss how to create custom sections and a custom section handler to manage the configuration of an ASP.NET application. By now, you should have enough background information to fully understand the details of the configuration machinery of ASP.NET applications.