Professional ASP.NET 3.5 in C# and Visual Basic Part 148 pps

10 436 0
Professional ASP.NET 3.5 in C# and Visual Basic Part 148 pps

Đang tải... (xem toàn văn)

Thông tin tài liệu

Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1435 Chapter 31: Configuration ❑ validateRequest : Specifies whether ASP.NET should validate all the incoming requests that are potentially dangerous like the cross-site script attack and the script injection attack. This fea- ture provides out-of-the-box protection against cross-site scripting and script injection attacks by automatically checking all parameters in the request, ensuring that their content does not include HTML elements. For more information about this setting, visit http://www.asp.net/faq/ RequestValidation.aspx . ❑ namespaces : Optionally, you can import a collection of assemblies that can be included in the precompilation process. ❑ compilationMode : Specifies how ASP.NET should compile the current Web application. Sup- ported values are Never , Always ,and Auto .Whenyouset compilationMode = "Never" ,this means that the pages should never be compiled. A part error occurs if the page has constructs that require compilation. When you set compilationMode = "Always" , this means that the pages are always compiled. When you set compilationMode = "Auto" , ASP.NET does not compile the pages if that is possible. Include Files Unlike ASP.NET 1.0 and 1.1, ASP.NET 2.0 and 3.5 support include files in both the machine.config and the web.config files. When configuration content is to be included in multiple places or inside the location elements, an include file is an excellent way to encapsulate the content. Any section in a configuration file can include content from a different file using the configSource attribute in the < pages > section. The value of the attribute indicates a virtual relative filename to the include file. Listing 31-27 is an example of such a directive. Listing 31-27: Adding additional content to the web.config file < configuration > < system.web > < pages configSource="SystemWeb.config" / > < /system.web > < /configuration > The configuration include files can contain information that applies to a single section, and a single include file cannot contain more than one configuration section or a portion of a section. If the config- Source attribute is present, the section element in the source file should not contain any other attribute or any child element. Nevertheless, the include file is not a full configuration file. It should contain only the include section, as presented in Listing 31-28. Listing 31-28: The SystemWeb.config file < pages authentication mode="Forms" / > The configSource attribute cannot be nested. An include file cannot nest another file inside it using the configSource attribute. When an ASP.NET configuration file is changed, the application is restarted at runtime. When an exter- nal include file is used within the configuration file, the configuration reload happens without restarting the application. 1435 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1436 Chapter 31: Configuration Configuring ASP.NET Runtime Settings The general configuration settings are those that specify how long a given ASP.NET resource, such as a page, is allowed to execute before being considered timed-out. The other settings specify the maximum size of a request (in kilobytes) or whether to use fully qualified URLs in redirects. These settings can be specified using the < httpRuntime > section within a configuration file. The < httpRuntime > element is applied at the ASP.NET application at the folder level. Listing 31-29 shows the default values used in the < httpRuntime > section. Listing 31-29: The <httpRuntime> section < configuration > < system.web > < httpRuntime useFullyQualifiedRedirectUrl="false" enable="true" executionTimeout="90" maxRequestLength="4096" requestLengthDiskThreshold="512" appRequestQueueLimit="5000" minFreeThreads="8" minLocalRequestFreeThreads="4" enableKernelOutputCache="true" / > < /system.web > < /configuration > Enabling and Disabling ASP.NET Applications The enable attribute specifies whether the current ASP.NET application is enabled. When set to false , the current ASP.NET application is disabled, and all the clients trying to connect to this site receive the HTTP 404 — File Not Found exception. This value should be set only at the machine or application level. If you set this value in any other level (such as subfolder level), it is ignored. This great feature enables the administrators to bring down the application for whatever reason without starting or stopping IIS. The default value is true . Outside of this setting, it is also p ossible to take applications offline quickly by simply placing an App_Offline.htm file in the root of your application. This .htm file does not need to actually contain anything (it will not make any difference). Just having the file in the root directory causes the application domain to come down, and all requests to the application get a Page Not Found error. Fully Qualified Redirect URLs The useFullyQualifiedRedirectUrl attribute specifies whether the client-side redirects should include the fully qualified URL. When you are programming against the mobile devices, some devices require specifying fully qualified URLs. The default value is false . Request Time-Out The executionTimeout setting specifies the timeout option for an ASP.NET request time-out. The value of this attribute is the amount of time in seconds during which a resource can execute before ASP.NET 1436 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1437 Chapter 31: Configuration times the request out. The default setting is 110 seconds. If you have a particular ASP.NET page or Web service that takes longer than 110 seconds to execute, you can extend the time limit in the configuration. Maximum Request Length The maxRequestLength attribute specifies the maximum file-size upload accepted by ASP.NET runtime. For example, if the ASP.NET application is required to process huge files, it is better to change this setting. The default is 4096. This number represents kilobytes (KB or around 4 MB). Web applications are prone to attacks these days. The attacks range from a script injection attack to a denial of service (DoS) attack. The DoS is a typical attack that bombards the Web server with requests for large files. This huge number of requests ultimately brings down the Web server. The maxRequestLength attribute could save you from a DoS attack by setting a restriction on the size of requests. Buffer Uploads In ASP.NET 1.0 or 1.1, when a HTTP post is made (either a normal ASP.NET form post, file upload, or an XMLHTTP client-side post), the entire content is buffered in memory. This works out fine for smaller posts. However, when memory-based recycling is enabled, a large post can cause the ASP.NET worker process to recycle before the upload is completed. To avoid the unnecessary worker process recycling, ASP.NET 3.5 includes a setting called requestLengthDiskThreshold . This setting enables an administrator to configure the file upload buffering behavior without affecting the programming model. Administrators can configure a threshold below which requests will be buffered into memory. After a request exceeds the limit, it is transparently buffered on disk and consumed from there by whatever mechanism is used to consume the data. The valid values for this setting are numbers between 1 and Int32.MaxSize in KB. When file buffering is enabled, the files are uploaded to the codegen folder. The default path for the codegen folder is the following: [WinNT \ Windows] \ Microsoft.NET \ Framework \ [version] \ Temporary ASP.NET Files \ [ApplicationName] The files are buffered using a random name in a subfolder within the codegen folder called Uploads . The location of the codegen folder can be configured on a per application basis using the tempDirectory attribute of the < compilation > section. This is not a change in ASP.NET; rather it is an internal change. When an ASP.NET 1.0 or 1.1 appli- cation is migrated to the .NET Framework 2.0 or 3.5, the ASP.NET application automatically takes advantage of this feature. Thread Management ASP.NET runtime uses free threads available in its thread pool to fulfill requests. The minFreeThreads attribute indicates the number of threads that ASP.NET guarantees is available within the thread pool. The default number of threads is eight. For complex applications that require additional threads to com- plete processing, this simply ensures that the threads are available and that the application will not be blocked while waiting for a free thread to schedule more work. The minLocalRequestFreeThreads attribute controls the number of free threads dedicated for local request processing; the default is four. 1437 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1438 Chapter 31: Configuration Application Queue Length The appRequestQueueLimit attribute specifies the maximum number of requests that ASP.NET queues for the current ASP.NET application. ASP.NET queues requests when it does not have enough free threads to process them. The minFreeThreads attribute specifies the number of free threads the ASP.NET application should maintain, and this setting affects the number of items stored in the queue. When the number of requests queued exceeds the limit set in the appRequestQueueLimit setting, all the incoming requests are rejected and an HTTP 503 - Server Too Busy error is thrown back to the browser. Output Caching The enableKernelOutputCache specifies whether the output caching is enabled at the IIS kernel level ( Http.sys ). At present, this setting applies only to Web servers IIS6 and higher. Configuring the ASP.NET Worker Process When a request for an ASP.NET page is received by IIS, it passes the request to an unmanaged DLL called aspnet_isapi.dll .The aspnet_isapi.dll further passes the request to a separate worker process, aspnet_wp.exe if you are working with IIS5, which runs all the ASP.NET applications. With IIS6 and higher, however, all the ASP.NET applications are run by the w3wp.exe process. The ASP.NET worker process can be configured using the < processModel > section in the machine.config file. All the configuration sections talked about so far are read by managed code. On the other hand, the < processModel > section is read by the aspnet_isapi.dll unmanaged DLL. Because the configura- tion information is read by an unmanaged DLL, the changed process model information is applied to all ASP.NET applications only after an IIS restart. The code example in Listing 31-30 shows the default format for the < processModel > section. Listing 31-30: The structure of the <processModel> element < processModel enable="true|false" timeout="hrs:mins:secs|Infinite" idleTimeout="hrs:mins:secs|Infinite" shutdownTimeout="hrs:mins:secs|Infinite" requestLimit="num|Infinite" requestQueueLimit="num|Infinite" restartQueueLimit="num|Infinite" memoryLimit="percent" cpuMask="num" webGarden="true|false" userName="username" password="password" logLevel="All|None|Errors" clientConnectedCheck="hrs:mins:secs|Infinite" responseDeadlockInterval="hrs:mins:secs|Infinite" responseRestartDeadlockInterval="hrs:mins:secs|Infinite" comAuthenticationLevel="Default|None|Connect|Call| 1438 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1439 Chapter 31: Configuration Pkt|PktIntegrity|PktPrivacy" comImpersonationLevel="Default|Anonymous|Identify| Impersonate|Delegate" maxWorkerThreads="num" maxIoThreads="num" / > The following section looks at each of these attributes in more detail: ❑ enable : Specifies whether the process model is enabled. When set to false , the ASP.NET appli- cations run under IIS’s process model. When ASP.NET is running under IIS6 or higher in native mode, the IIS6 or higher process model is used and most of the < processModel > section within the configuration file is simply ignored. The autoConfig and requestQueueLimit attributes are still applied in this case. ❑ timeout : Specifies how long the worker process lives before a new worker process is created to replace the current worker process. This value can be extremely useful if a scenario exists where the application’s performance starts to degrade slightly after running for several weeks, as in the case of a memory leak. Rather than your having to manually start and stop the process, ASP.NET can restart automatically. The default value is Infinite . ❑ idleTimeout : Specifies how long the worker process should wait before it is shut down. You can shut down the ASP.NET worker process automatically using the idleTimeout option. The default value is Infinite . You can also set this value to a time using the format, HH:MM:SS:. ❑ shutdownTimeout : Specifies how long the worker process is given to shut itself down gracefully before ASP.NET calls the Kill command on the process. Kill is a low-level command that force- fully removes the process. The default value is 5 seconds. ❑ requestLimit : Specifies when the ASP.NET worker process should be recycled after a certain number of requests are served. The default value is Infinite . ❑ requestQueueLimit : Instructs ASP.NET to recycle the worker process if the limit for queued requests is exceeded. The default setting is 5000. ❑ memoryLimit : Specifies how much physical memory the worker process is allowed to consume before it is considered to be misbehaving or leaking memory. The default value is 60 percent of available physical memory. ❑ username and password : By default, all ASP.NET applications are executed using the ASPNET identity. If you want an ASP.NET application to run with a different account, you can provide the username and the password pair using these attributes. ❑ logLevel : Specifies how the ASP.NET worker process logs events. The default setting is to log errors only. However, you can also disable logging by specifying None or you can log everything using All . All the log items are written to the Windows Application Event Log. ❑ clientConnectedCheck :The clientConnectedCheck setting enables you to check whether the client is still connected at timed intervals before performing work. The default setting is 5seconds. ❑ responseDeadlockInterval : Specifies how frequently the deadlock check should occur. A dead- lock is considered to exist when requests are queued and no responses have been sent during this interval. After a deadlock, the process is restarted. The default value is 3 minutes. 1439 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1440 Chapter 31: Configuration ❑ responseRestartDeadlockInterval : Specifies, when a deadlock is detected by the runtime, how long the runtime should wait before restarting the process. The default value is 9 minutes. ❑ comAuthenticationLevel : Controls the level of authentication for DCOM security. The default is set to Connect . Other values are Default , None , Call , Pkt , PktIntegrity ,and PktPrivacy . ❑ comImpersonationLevel : Controls the authentication level for COM security. The default is set to Impersonate . Other values are Default , Anonymous , Identify ,and Delegate . ❑ webGarden : Specifies whether Web Garden mode is enabled. The default setting is false .AWeb Garden lets you host multiple ASP.NET worker processes on a single server, thus providing the application with better hardware scalability. Web Garden mode is supported only on multi- processor servers. ❑ cpuMask : Specifies which processors should be affinities to ASP.NET worker processes when webGarden = "true" .The cpuMask is a hexadecimal value. The default value is all processors, shown as 0xFFFFFFFF . ❑ maxWorkerThreads : Specifies the maximum number of threads that exist within the ASP.NET worker process thread pool. The default is 20. ❑ maxIoThreads : Specifies the maximum number of I/O threads that exist within the ASP.NET worker process. The default is 20. Running Multiple Web Sites with Multiple Versions of Framework In the same context, multiple Web sites within the given Web server can host multiple Web sites, and each of these sites can be bound to a particular version of a .NET Framework. This is typically done using the aspnet_regiis.exe utility. The aspnet_regiis.exe utility is shipped with each version of the framework. This utility has multiple switches. Using the -s switch allows you to install the current version of the .NET Framework runtime on a given Web site. Listing 31-31 shows how to install .NET Framework version 1.1 on the ExampleApplication Web site. Listing 31-31: Installing .NET Framework version 1 .1 on the ExampleApplication Web site C: \ WINDOWS \ Microsoft.NET \ Framework \ v1.1.4322 > aspnet_regiis -s W3SVC/1ROOT/ExampleApplication Storing Application-Specific Settings Every Web application must store some application-specific information for its runtime use. The < appSettings > section of the web.config file provides a way to define custom application settings for an ASP.NET application. The section can have multiple < add > subelements. Its syntax is as follows: < appSettings > < add key="[key]" value="[value]"/ > < /appSettings > The < add > subelement supports two attributes: ❑ key : Specifies the key value in an appSettings hash table ❑ value :Specifiesthevalueinan appSettings hash table 1440 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1441 Chapter 31: Configuration Listing 31-32 shows how to store an application-specific connection string. The key value is set to Appli- cationInstanceID ,andthe value is set to the ASP.NET application instance and the name of the server on which the application is running. Listing 31-32: Application instance information < appSettings > < add key="ApplicationInstanceID" value="Instance1onServerOprta"/ > < /appSettings > Programming Configuration Files In ASP.NET 1.0 and 1.1 versions of the Framework provided APIs that enabled you only to read informa- tion from the configuration file. You had no way to write information into the configuration file because no out-of-the-box support was available. However, some advanced developers wrote their own APIs to write the information back to the configuration files. Because the web.config file is an XML file, devel- opers were able to open configuration file using the XmlDocument object, modify the settings, and write it back to the disk. Even though this approach worked fine, the way to access the configuration settings were not strongly typed. Therefore, validating the values was always a challenge. However, ASP.NET 3.5 includes APIs (ASP.NET Management Objects) to manipulate the configuration information settings in machine.config and web.config files. ASP.NET Management Objects provide a strongly typed programming model that addresses targeted administrative aspects of a .NET Web Appli- cation Server. They also govern the creation and maintenance of the ASP.NET Web configuration. Using the ASP.NET Management Objects, you can manipulate the configuration information stored in the con- figuration files in the local or remote computer. These can be used to script any common administrative tasks or the writing of installation scripts. All of the ASP.NET Management Objects are stored in the System.Configuration and System.Web. Configuration namespaces. You can access the configuration using the WebConfigurationManager class. The System.Configuration.Configuration class represents a merged view of the configuration settings from the machine.config and hierarchical web.config files. The System.Configuration and System.Web.Configuration namespaces have multiple classes that enable you to access pretty much all the settings available in the configuration file. The main difference between System.Configuration and System.Web.Configuration namespaces is that the System.Configuration namespace contains all the classes that apply to all the .NET applications. On the other hand, the System.Web.Configuration namespace contains the classes that are applicable only to ASP.NET Web applications. The following table shows the important classes in System.Configuration and their uses. Class Name Purpose Configuration Enables you to manipulate the configuration stored in the localcomputeroraremoteone. ConfigurationElementCollection Enables you to enumerate the child elements stored inside the configuration file. AppSettingsSection Enables you to manipulate the < appSettings > section of the configuration file. ConnectionStringsSettings Enables you to manipulate the < connectionStrings > section of the configuration file. 1441 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1442 Chapter 31: Configuration Class Name Purpose ProtectedConfigurationSection Enables you to manipulate the < protectedConfiguration > section of the configuration file. ProtectedDataSection Enables you to manipulate the < protectedData > section of the configuration file. The next table shows classes from the System.Web.Configuration and their uses. Class Name Purpose AuthenticationSection Enables you to manipulate the < authentication > section of the configuration file. AuthorizationSection Enables you to manipulate the < authorization > section of the configuration file. CompilationSection Enables you to manipulate the < compilation > section of the configuration file. CustomErrorsSection Enables you to manipulate the < customErrors > section of the configuration file. FormsAuthenticationConfiguration Enables you to manipulate the < forms > section of the configuration file. GlobalizationSection Enables you to manipulate the < globalization > section of the configuration file. HttpHandlersSection Enables you to manipulate the < httpHandlers > section of the configuration file. HttpModulesSection Enables you to manipulate the < httpModules > section of the configuration file. HttpRuntimeSection Enables you to manipulate the < httpRuntime > section of the configuration file. MachineKeySection Enables you to manipulate the < machineKey > section of the configuration file. MembershipSection Enables you to manipulate the < membership > section of the configuration file. PagesSection Enables you to manipulate the < pages > section of the configuration file. ProcessModelSection Enables you to manipulate the < processModel > section of the configuration file. WebPartsSection Enables you to manipulate the < webParts > section of the configuration file. 1442 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1443 Chapter 31: Configuration All the configuration classes are implemented based on simple object-oriented based architecture that has an entity class that holds all the data and a collection class that has methods to add, remove, enumerate, and so on. Start your configuration file programming with a simple connection string enumeration, as shown in the following section. Enumerating Connection Strings In a Web application, you can store multiple connection strings. Some of them are used by the system and the others may be application-specific. You can write a very simple ASP.NET application that enumerates all the connection strings stored in the web.config file, as shown in Listing 31-33. Listing 31-33: The web.config file < ?xml version="1.0" ? > < configuration > < appSettings > < add key="symbolServer" value="192.168.1.1" / > < /appSettings > < connectionStrings > < add name="ExampleApplication" connectionString="server=ExampleApplicationServer; database=ExampleApplicationDB;uid=WebUser;pwd=P@$$worD9" providerName="System.Data.SqlClient" / > < /connectionStrings > < system.web > < compilation debug="false" / > < authentication mode="None" / > < /system.web > < /configuration > As shown in Listing 31-33, one application setting points to the symbol server, and one connection string is stored in the web.config file. Use the ConnectionStrings collection of the System.Web.Configuration .WebConfigurationManager class to read the connection strings, as seen in Listing 31-34. Listing 31-34: Enum.aspx VB Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) GridView1.DataSource = _ System.Web.Configuration.WebConfigurationManager.ConnectionStrings GridView1.DataBind() End Sub C# protected void Page_Load(object sender, EventArgs e) { GridView1.DataSource = System.Web.Configuration.WebConfigurationManager.ConnectionStrings; GridView1.DataBind(); } 1443 Evjen c31.tex V2 - 01/28/2008 4:01pm Page 1444 Chapter 31: Configuration As shown in Listing 31-34, you’ve bound the ConnectionStrings property collection of the WebConfigu- rationManager class into the GridView control. The WebConfigurationManager class returns an instance of the Configuration class and the ConnectionStrings property is a static (shared in Visual Basic) prop- erty. Therefore, you are just binding the property collection into the GridView control. Figure 31-5 shows the list of connection strings stored in the ASP.NET application. Figure 31-5 Adding a connection string at runtime is also a very easy task. If you do it as shown in Listing 31-35, you get an instance of the configuration object. Then you create a new connectionStringSettings class. You add the new class to the collection and call the update method. Listing 31-35 shows examples of this in both VB and C#. Listing 31-35: Adding a connection string VB Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) ’ Get the file path for the current web request Dim webPath As String = Request.ApplicationPath Try ’ Get configuration object of the current web request Dim config As Configuration = _ System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(webPath) ’ Create new connection setting from text boxes Dim newConnSetting As New _ ConnectionStringSettings(txtName.Text, txtValue.Text, txtProvider.Text) ’ Add the connection string to the collection 1444 . "Auto" , ASP. NET does not compile the pages if that is possible. Include Files Unlike ASP. NET 1.0 and 1.1, ASP. NET 2.0 and 3. 5 support include files in both the machine.config and the web.config files application-specific. You can write a very simple ASP. NET application that enumerates all the connection strings stored in the web.config file, as shown in Listing 31 -33 . Listing 31 -33 : The web.config file < ?xml. are just binding the property collection into the GridView control. Figure 31 -5 shows the list of connection strings stored in the ASP. NET application. Figure 31 -5 Adding a connection string at

Ngày đăng: 05/07/2014, 19:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan