Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Microsoft ASP .NET Professional Projects - Premier Press

.pdf
Скачиваний:
147
Добавлен:
24.05.2014
Размер:
4.63 Mб
Скачать

Figure 10.9: Starting ASPState service.

13.Run Session.aspx. Store a session state value. Stop and restart the IIS using the command-line utility iisreset.

14.Click the Check Session Variable button. You will note that you have retained the Session variable.

The code for this example is included in the ...\samples\sessionstate\OutofProcess subfolder for this chapter on the book's Web site at www.premierpressbooks.com/downloads.asp.

SQL Server Mode

This mode should be used when reliability considerations are paramount. The database can be clustered for handling server failures. The trade-off is performance as this mode is slower than out-of-process. You can set up this mode as follows:

1.Create the ASPState Database by applying the file InstallSqlState.sql

provided with ASP.NET and located at

....\Microsoft.NET\Framework\[version]\ folder with the utility osql.exe as follows:

osql –S [server name] –U [user] –P [password] < InstallSqlState.sql

You can also directly open this file in the SQL Query Analyzer tool (ISQL) of Microsoft SQL Server and execute it. (I find this method better because I don't have to remember passwords, server names, and so on. I can just log on with system administrator rights and execute the script.)

This process will create a database called ASPState, which contains 16 stored procedures and two tables in tempdb. These are AspStateTempSessions and AspStateTempApplications. Now you must stop and restart SQL Server as some startup procedures were created which need to run.

A script to uninstall the ASPState database is also provided. This script is called UninstallSqlState.sql.

2.In the configuration file, set the mode attribute of sessionState to

"SQLServer".

3.<configuration>

4.<system.web>

5.<sessionState

6.mode="SQLServer"

7.stateConnectionString ="tcpip=127.0.0.1:42424"

8.sqlConnectionString="data source=127.0.0.1;user id=sa;password="

9.cookieless="false"

10.timeout="20"

11./>

12.</system.web>

</configuration>

13.Run Session.aspx. Store a session state value. Stop and restart the IIS using the command-line utility iisreset.

14.Click the Check Session Variable button. You will note that you have retained the Session variable.

15.Connect to the tempdb database and run the following queries:

16.select * from AspStateTempSessions

select * from AspStateTempApplications

You will see that the data stored in the SQL server tables AspStateTempSessions and AspStateTempApplications. Note that a unique session id is stored in the database. Figure 10.10 is a sample of the output.

Figure 10.10: State maintained in SQL Server.

We could further enhance the reliability of storing session state by clustering SQL Servers so that if one server becomes unavailable, another one replicating it takes over.

Cookieless State

This feature of the ASP.NET session state allows clients who turn off cookies to take advantage of the session state. In this mode, the session id is "munged" into the URL as follows:

http://localhost/( hmxz0d5554l1bt45faqudj55)/Application/Sessione.aspx

All you have to do to enable this state is set the cookieless attribute to true as follows:

<configuration>

<system.web>

<sessionState

mode="StateServer"

stateConnectionString ="tcpip=127.0.0.1:42424"

sqlConnectionString="data source=127.0.0.1;user id=sa;password="

cookieless="false"

timeout="20"

/>

</system.web>

</configuration>

All modes are supported for cookieless sessions.

The Configuration File

ASP.NET can be configured using two configuration files. These are the machine.config and the web.config files. Each machine has a single machine.config file that holds the default configuration information. Each application can have its own optional web.config file and when such a file exists, it overrides the default machine.config file located in the WinNt\Framework\[Version]\ folder. The "local" web.config file can have only the sections it needs. These sections then override the default machine.config file. The sections not specified in the local web.config file are read from the machine.config file. These configuration files are an XML-based text file. A sample configuration file with two settings is shown here:

<configuration>

<system.web>

<sessionState

mode="StateServer"

stateConnectionString ="tcpip=127.0.0.1:42424"

sqlConnectionString="data source=127.0.0.1;user id=sa;password="

cookieless="false"

timeout="20"

/>

<appSettings>

<add key="dsn" value ="Bhasin;uid=sa;pwd=''"/>

</appSettings>

</system.web>

</configuration>

This file cannot be accessed directly from a browser. The above example shows a file with two configuration sections <sessionState> and <appSettings>. I have already discussed the sessionState section. I will now discuss some other sections contained in this file.

<Configuration>

This is the root element and all configuration sections must be contained within the Configuration tags.

<appSettings>

The appSettings section allows you to use the web.config file as an ini file. You can store application-wide settings here. For example, you can store the DSN name here, which then becomes available to all the pages in the application. The way to do so follows.

In web.config, set this setting as follows:

<appSettings>

<add key="dsn" value ="Bhasin;uid=sa;pwd=''"/>

</appSettings>

This section has one sub-element, which is add. The add sub-element supports two attributes: key and value. The key is the name of the variable you store in the value attribute. You can have as many add sub-elements as you require.

On a Web page you will extract the stored value, using Visual Basic.NET as follows:

AppSettingVb.aspx

<html>

<script language="VB" runat="server">

Sub Page_Load(Src As Object, E As EventArgs)

Dim dsn As String = ConfigurationSettings.AppSettings("dsn")

response.write(dsn)

End Sub

</script>

</html>

You can find this code in the ...\samples\configFile\configAppSettings folder on the book's Web site at www.premierpressbooks.com/downloads.asp.

Here is the code in C#:

AppSettingC.aspx

<script language="C#" runat="server">

public void Page_Load(Object sender, EventArgs e)

{

String s = ConfigurationSettings.AppSettings["dsn"];

dsn.InnerHtml =s;

}

</script>

The DSN entry in web.config is: <B><SPAN id=dsn runat=server/></B>

<Compilation>

This section has one attribute (debug) and two subsections (<compilers> and <assemblies>). The debug attribute is a boolean setting that can be True or False. Setting it to True will compile in debug mode, which is slower and should be turned off in production sites.

In the compiler section, you set the language and extension attributes for each language you will use. Say you associate extension "vb" with the language Visual Basic. All web forms with this extension will have Visual Basic as the default scripting language and you now do not have to declare this language in page directives or script tags.

The <assemblies> subsection enables you to specify which assemblies you want to include when compiling a resource. If you remember from previous chapters, when creating business objects (Chapter 8) and custom controls (Chapter 7), we had to include various assemblies in the bat files which compiled the objects we created. Instead of doing that, we can specify these assemblies here. Remember, however, that we still need to import these assemblies in Web pages using page directives. The <assemblies> sub-element has three more sub-elements: add, remove, and clear. The add sub-element adds assemblies and you can use the * to add all assemblies located in the /bin directory. Remove removes an assembly reference and the clear sub-element removes all references contained in or inherited from the main config.web.

<compilation debug="false" explicit="true" defaultLanguage="vb">

<compilers>

<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider,

System,Version=1.0.2411.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

/>

</compilers>

<assemblies>

<add assembly="mscorlib"/>

<add assembly="System, Version=1.0.2411.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>

<add assembly="*"/>

</assemblies>

</compilation>

<Custom Errors>

ASP.NET provides a lot of helpful information when an error occurs, and while this may be helpful to the developers, it might scare the users of the site. The Custom Error setting allows you to specify a custom error page, which displays your custom error messages. You can also redirect specific errors (say 404 or 500 errors) to separate custom error pages.

The custom error section has two attributes. These are:

§defaultRedirect: Specify your custom error page here.

§mode: This can be On, Off, or RemoteOnly. The On mode redirects all errors to the custom error page. The Off mode turns off custom errors, and the RemoteOnly mode turns on the custom errors only for remote users—if you are on the same server and generate an error, you see the full details of the error. This option is helpful because the developers see the complete details of the error whereas users of the site see only the custom errors.

I will now show you how to create a custom error page. You can find the code in the..samples\configFile\CustomErrors subfolder on the book's Web site at www.premierpressbooks.com/downloads.asp.

web.config for Custom Errors

<configuration>

<system.web>

<customErrors mode="On" defaultRedirect="HandleError.aspx" >

</customErrors>

</system.web>

</configuration>

I have specified my custom error file to be HandleError.aspx, the listing of which is as follows:

HandleError.aspx

<%@Page Language="VB"%>

<html>

<head>

<style>

body {font-family:Tahoma,Arial,sans-serif; font -size:10pt}

</style>

</head>

<body>

<h3>Default Custom Error Page</h3>

<b>There was an error in the page

<b><a href="errorTest.aspx">Return to the previous page</a></b>

</body>

</html>

I have created a test page and I try to navigate to a non-existent page in this file, thus generating an error. Here is the listing:

ErrorTest.aspx

<html>

<head>

<script language="VB" runat="server">

Sub cause_error(Source As Object, E As EventArgs)

Response.Redirect("NonExistantPage.aspx")

End Sub

</script>

<form runat="server">

<asp:Button id="Error" text="Cause Error" onclick="cause_error" runat="server" />

</form>

</head>

</html>

The <customError> section supports one subsection: the <error> sub-element. You can use sub-element to redirect specific error numbers to their own custom error pages. For example:

<configuration>

<system.web>

<customErrors mode="On" defaultRedirect="HandleError.aspx" >

<error statusCode = "500" redirect ="500Error.aspx"/>

</customErrors>

</system.web>

</configuration>

All errors with a status code of 500 will now be redirected to the custom error page 500Error.aspx.

<Globalization>

The Globalization subsection has five attributes. These are:

§requestEncoding: This is the default encoding for all requests.

§responseEncoding: This is the default encoding for all responses.

§fileenCoding: This is the default encoding for all .aspx, asmx, and aspc files.

§culture: This is the default culture used to process requests. This is information regarding language, calendar, and writing system. For

example, English = en. Information pertaining to cultures can be found under the namespace System.Globalization in the

CultureInfo class.

§uiCulture: This is the default culture to lookup resources and also expects a CultureInfo value like en.

Here is an example:

<globalization

fileEncoding="iso-8859-1"

requestEncoding="iso-8859-1"

responseEncoding="iso-8859-1"

culture="en"

uiCulture="en"/>

<httpHandlers>

httpHandlers allow you to map incoming requests to .NET Framework classes that can handle those requests. For example:

<httpHandlers>

<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory" />

</httpHandlers>

This setting tells the .NET Framework that all requests for the file with an extension of aspx should be handled by the .NET Framework class

System.Web.UI.PageHandlerFactory.

As you can see, this section has three attributes. These are:

§verb: This attribute tells the .NET runtime to process the request using a GET, POST, or PUT, or all three separated by a comma (an * implies the same thing).

§path: The path to a file (or a set of files with the same extension) that needs to be processed.

§type: The name of the assembly or class that will handle the request.

You can write your own httpHandlers. Suppose that you want to deny access to web forms called default.aspx. You would first write a simple class to handle requests to this form as follows:

handler.vb

Imports System.Web

Namespace Hersh

Public Class CustomHandlerVB : Implements IHttpHandler

Public Sub ProcessRequest(Context As HttpContext) Implements

IHttpHandler.ProcessRequest

Context.Response.Write("Sorry! Access to this resource is Denied...")

End Sub

Public ReadOnly Property IsReusable As Boolean Implements

IHttpHandler.IsReusable

Get

Return true

End Get

End Property

End Class

End Namespace

A custom HTTP Handler is created using the IHttpHandler interface. This interface contains only two methods: IsReusable and ProcessRequest. The IsReusable method tells the HTTP factory whether the same instance can be used to serve multiple requests, and ProcessRequest takes the HttpContext instance as a parameter which, in turn, makes the response and request intrinsics-accessible. In the preceding example, the request data is ignored and a string is sent back as a response.

You should now compile this class as follows: make.bat

set outdir=g:\aspNetSamples\bin\CustomHandlerVB.dll

set assemblies=System.Web.dll

vbc /t:library /out:%outdir% /r:%assemblies% handler.vb

pause

Make sure that the outdir parameter points to your local /bin directory.

Add the following section to the web.config file:

<configuration>

<system.web>

<httpHandlers>

<add verb="*" path="default.aspx" type="Hersh.CustomHandlerVB,CustomHandlerVB" />

</httpHandlers>

</system.web>

</configuration>

Finally test it out by trying to open a file called default.aspx through IIS. You will get a message that says "Sorry! Access to this resource is denied. . . ."

The complete source for this example is provided in the ...samples\configfile\httpHandler subfolder on the book's Web site at www.premierpressbooks.com/downloads.asp.

<httpModules>

This section enables you to configure HTTP modules for your application. Most of the classes and assemblies that you will need are included by default. You can use this section to add your own handlers.

<httpModules>

<add name="OutputCache" type="System.Web.Caching.OutputCacheModule, System.Web, Version=1.0.2411.0,

Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

<add name="Session" type="System.Web.SessionState.SessionStateModule, System.Web,

Version=1.0.2411.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

<add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule,

System.Web, Version=1.0.2411.0, Culture=neutral,

PublicKeyToken=b03f5f7f11d50a3a" />

</httpModules>

<processModel>

This subsection allows you to configure the process model of your Web applications. A number of settings can be configured. For example:

<processModel

enable="true"

timeout="Infinite"

idleTimeout="Infinite"

shutdownTimeout="0:00:05"

requestLimit="Infinite"

requestQueueLimit="5000"

restartQueueLimit="10"

memoryLimit="60"

webGarden="false"

cpuMask="0xffffffff"

userName="SYSTEM"

password="AutoGenerate"

logLevel="Errors"

clientConnectedCheck="0:00:05"

comAuthenticationLevel="Connect"

comImpersonationLevel="Impersonate" />

The meaning of the attributes is as follows:

§enable: The Boolean which specifies whether this element is enabled.