Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1415 Chapter 31: Configuration then that particular setting overrides the default ASP.NET setting inherited from the machine.config or the root web.config file. The web.config files 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 the allowOverride = "false" mechanism shown in Listing 31-3. Detecting Configuration File Changes ASP.NET automatically detects when configuration files, such as machine.config or web.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 the machine.config and/or web.config configuration file. When the configuration file update is detected in the machine.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 between machine.config and web.config is 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 >.Thispseudo web.config file 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. 1415 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1416 Chapter 31: Configuration Config 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 to System.Web.Caching.HttpModulesSection ,andthe< sessionState > section has a configuration handler that is set to System.Web.SessionState.SessionStateSection classes, 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 the web.config and machine.config files. 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 in appSettings section, it is impossible for a data-aware control such as SqlCacheDependency or MembershipProvider to 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 the appSettings section, it can be retrieved using the strongly typed collection method ConnectionStrings . Listing 31-8 gives an example of how to store connecting strings. Listing 31-8: Storing a connection string < configuration > < connectionStrings > < add name = "ExampleConnection" 1416 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1417 Chapter 31: Configuration connectionString = "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 the web.config file 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-specific state where it can persist. The Session object is the common store where user-specific information is persisted. Session store is implemented as a Hashtable and stores data based on key/value pair combinations. ASP.NET 1.0 and 1.1 had the capability to persist the session store data in InProc , StateServer ,and SqlServer . ASP.NET 2.0 and 3.5 adds one more capability called Custom .The Custom setting 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 inListing 31-10. 1417 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1418 Chapter 31: Configuration Listing 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 ,and Custom .Thedefaultoptionis InProc . ❑ cookieless : Specifies whether HTTP cookieless Session key management is supported. ❑ timeout :Specifiesthe Session lifecycle time. The timeout value is a sliding value; at each request, the timeout period is reset to the current time plus the timeout value. For example, if the timeout value is 20 minutes and a request is received at 10:10 AM, the timeout occurs at 10:30 AM. ❑ stateConnectionString :When mode is set to StateServer , 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 as StateServer . ❑ sqlConnectionString :When mode is set to SQLServer , 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 as StateServer or SQLServer . State Server Both StateServer and SQLServer support the out-of-process session state. However, the StateServer 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). 1418 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1419 Chapter 31: Configuration Figure 31-2 Alternatively, you can start the session state service by using the command prompt and entering the net start command, 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, t he 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 the SQLServer option, 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 1419 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1420 Chapter 31: Configuration session 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 thatyourunaT-SQLscriptthatshipswithASP.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 the aspnet_regsql.exe utility to c onfigure this. However, if you are looking for a solution for older .NET Frameworks, a fix is available at http://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 the connectionStrings section, 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 w ith 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" 1420 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1421 Chapter 31: Configuration cookieless="false" timeout="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 the SessionStateStoreProviderBase class. If you want to create your own custom provider or use a third-party provider, you must set the mode to Custom . You specify the custom provider assembly that inherits the SessionStateStoreProviderBase class, 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 as CustomStateProvider . 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 the Global.asax file), 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. 1421 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1422 Chapter 31: Configuration The 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 in web.config or machine.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 is true . ❑ 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 . 1422 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1423 Chapter 31: Configuration ❑ defaultLanguage :Specifiesthedefaultprogramming language, such as VB or C# ,tousein dynamic compilation files. Language names are defined using the < compiler > child element. The default value is VB . ❑ explicit : Specifies whether the Microsoft Visual Basic code compile option is explicit. The default is true . ❑ 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.NET Files folder. ❑ compilers :The< compilers > section can contain multiple < compiler > subelements, which are used to create a new compiler definition: ❑ The language attribute specifies the languages (separated by semicolons) used in dynamic compilation files. For example, C#; VB . ❑ The extension attribute specifies the list of filename extensions (separated by semicolons) used for dynamic code. For example, .cs; .vb . ❑ The type attribute specifies .NET type/class that extends the CodeDomProvider class used to compile all resources that use either the specified language or the file extension. ❑ The warningLevel attribute specifies how the .NET compiler should treat compiler warn- ings as errors. Five levels of compiler warnings 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. ❑ The compilerOptions attribute 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 the codeSubDirectories section 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,andsoon.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. The HttpBrowserCapabilities class 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 .browser files. 1423 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1424 Chapter 31: Configuration When 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 *.browser file types and specified in XML format. A single file may contain one or more browser definitions. The *.browser files are stored in the Config \ Browsers subdirec- tory of the Framework installation directory (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 /Browsers subdirectory of the application. In ASP.NET 1.0 and 1.1, the browser cap information was stored in the machine.config and web.config files themselves. Figure 31-3 1424 . 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, t he ASP. NET 2.0 installation replaces the ASP. NET 1.1’s state server instance 1422 Chapter 31 : Configuration The 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. state service by using the command prompt and entering the net start command, like this: C: Windows Microsoft .NET Framework v2.0 .50 727 > net start aspnet_state The ASP. NET State Service