1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional ASP.NET 1.0 Special Edition- P23 pdf

40 251 0
Tài liệu đã được kiểm tra trùng lặp

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

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Professional ASP.NET 1.0 Special Edition - P23 pdf
Trường học University of Example
Chuyên ngành Computer Science
Thể loại Document
Năm xuất bản 2004
Thành phố Sample City
Định dạng
Số trang 40
Dung lượng 654,44 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Supporting Web Farms By default, ASP.NET ships with Session state configured to store Session data in the same process as ASP.NET.. We have two options for out-of-process Session state;

Trang 1

</system.web>

</configuration>

The <sessionState> configuration setting supports six attributes (we will show their use shortly):

ƒ mode - The mode setting supports four options; Off, InProc, SQLServer, and StateServer The InProc option, the default, enables in-process state management In-process state management is identical to the behavior of ASP Session There are also two options for out-of-process state management: a Windows NT Service (StateServer) and SQL Server (SQLServer)

ƒ stateConnectionString - Identifies the TCP/IP address and port used to communicate with the Windows NT Service providing state management facilities We must configure the stateConnectionString when mode

ƒ cookieless - Enables support for Session key management without requiring HTTP cookies

ƒ timeout - This option controls the life of a user's Session timeout is a sliding value, and on each request, the timeout period is reset to the current time plus the timeout value

Next, let's implement some of the common scenarios we'll encounter when building applications using Session state

Supporting Web Farms

By default, ASP.NET ships with Session state configured to store Session data in the same process as ASP.NET This

is identical to how ASP Session data is stored The session web farm feature allows several front-end web servers to share a common storage point for Session data, rather than each web server maintaining its own copy This creates a scenario in which the client making the request can be serviced from any server within the server farm This additionally allows an individual server's process to recycle and access to Session data to be maintained

We have two options for out-of-process Session state; a Windows NT Service, which stores the data (in memory) in a separate process from ASP.NET (either on the same server or on a different server), and a SQL Server option, which stores the data in SQL Server Let's look at how we configure both of these options

Out-of-Process - Windows Service

Trang 2

To support the out-of-process Windows Service option (mode="StateServer") we need first to decide which server is going to run the Windows Service used for Session state storage ASP.NET ships with a Windows Service named aspnet_state that needs to be running in order for Session to function in mode="StateServer"

The service can be started by opening a command prompt and entering the following in bold:

> net start aspnet_state

The ASP.NET State Service service is starting

The ASP.NET State Service service was started successfully

Alternatively, we can configure the service using the Services and Applications Microsoft Management Console MMC snap-in (available from Start|Settings|ControlPanel|AdministrativeTools|ComputerManagement) If we view the Services

item in this tool, we are presented with a list of the available services on the server:

Right-clicking on the ASP.NET State Service item opens up a menu that allows us to configure how this service is to be run We can select the start-up options (whether or not Windows should automatically start this service for us) as well as using the toolbar Start and Stop buttons to enable or disable this service ourselves

Once the service has been started, we then need to configure ASP.NET to use this particular service This is done through our configuration file We need to tell ASP.NET which server and port to use for communication with our ASP.NET State service, as well as the fact that we want to use the Windows Service state option

Here is our web.config, with the necessary settings highlighted:

<configuration>

<system.web>

<sessionState

Trang 4

This last point is very, very important Each server, by default, is set to auto-generate its own machine key This machine key is used to encrypt data or to create unique serverspecific values for data (known as hashing) The ID used for Session state is created using the machine key, and thus, for the key to be understood by all the servers in the farm the servers need the same machine key

The machine key has other applications besides sessionState and we will cover it in more detail later in the chapter

In addition to supporting an out-of-process Windows Service, ASP.NET additionally supports an out-of-process option that saves Session data to SQL Server

Out-of-Process - SQL Server

Configuring ASP.NET to support SQL Server for Session state is just as simple as configuring the Windows Service The only difference is that we will use SQL Server To configure SQL Server we need to run a T-SQL script that ships with ASP.NET, InstallSqlState.sql

A T-SQL script to uninstall ASP.NET SQL Server support is also included, called UninstallSqlState.sql

It should be noted that ASP.NET ships with a lightweight version of SQL Server 2000 that has several limitations (limited connections, throttled transactions, and so on) but is for all practical purposes, a normal working version of SQL Server

2000 We can use this developer version of SQL Server 2000 for development purposes, but if we were to deploy and use SQL Server for state management in a production server farm we would want to use SQL Server 2000 Standard or Enterprise versions for optimal performance

To run the InstallSqlState.sql script, we will use a tool that ships with SQL Server (and MSDE); OSQL.exe OSQL allows us to apply a T-SQL script to a SQL Server Our InstallSqlState.sql T-SQL script creates several stored procedures and creates several temporary databases for ASP.NET Session to use

The script only needs to be run once on any given SQL Server, and we will need sa (administrator) level access to run the script To run the script, open a command prompt and navigate to the

\WINNT\Microsoft.NET\Framework\[version]\ directory and type:

> OSQL -S localhost -U sa -P <InstallSqlState.sql

1> 2> 3> 1> 2> 3> 4> 5> 6> 1> 2> 3> 4> 5> 6> 1> 2> 3> 4> 5> 1> 2> 3> 4> 5> 6> 7> 8> 1> 2> 3> 4> 5> 6> 7> 8> 1> 2> 3> 4> 5> 6> 7> 8> 1> 2> 3> 4> 5> 6> 7> 8> 9> 10> 11> 12> 13> 14> 15> 16> 17> 18> 19> 20> 21> 22> 23> 1> 2> 3> 4> The CREATE DATABASE process is allocating 0.63 MB on disk 'ASPState'

Trang 5

The CREATE DATABASE process is allocating 0.49 MB on disk 'ASPState_log'

1> 2> 3> 1> 2> 3> 1> 2> 1> 2> 3> 4> 5> 6> 7> 8> 9> 10> 11> 12> 13> 1> 2> 3> 4> 5> 6> 7> 8> 9> 10> 11> 12> 13> 14> 15> 16> 17> 18> 19> 20> 21> 22> 23> 24> 25> 26> 27> 28> 29> 30> 31> 1> 2> 3> 4> 5> 6> 7> 1> 2> 3> (1 row affected)

Trang 6

Next, we need to change our configuration settings to use SQL Server (highlighted):

Session data stored in SQL is inaccessible to other applications It is serialized as a protected type and should not be read

or modified by applications other than ASP.NET

ASP.NET accesses the data stored in SQL via stored procedures By default, session data is stored in the TempDB

Trang 7

database The stored procedures may be modified, for example, if we wished to store to tables other than TempDB However, this is an option best saved for DBAs

From the developer's point of view, writing code that uses Session in any of the above modes is completely transparent However, we should briefly discuss choosing a mode as the mode selection can impact on the performance of the application

Choosing a Mode

There are three modes from which we can choose when building an application:

ƒ In-process (default) - In-process will perform best because the Session data is kept within the ASP.NET process and local memory access will always be faster than having to go out-of-process Additional reasons include web applications hosted on a single server, applications in which the user is guaranteed to be redirected to the correct server, or when Session data is not critical (in the sense that it can be easily re-created)

ƒ Windows Service - This mode is best used when performance is important and there are multiple web servers servicing requests With this out-of-process mode, you get the performance of reading from memory and the reliability of a separate process that manages the state for all servers

ƒ SQL Server - This mode is best used when the reliability of the data is fundamental to the stability of the application, as the data is stored in SQL Server The performance isn't as fast as the Windows Service, but the tradeoff is the higher level of reliability

Now that we have examined the supported options for web farms, let's turn our attention to another one of the great new features of ASP.NET Session: support for clients that don't accept HTTP cookies

Cookieless Session

Since HTTP is a stateless environment, in order to maintain state across requests through Session, both the client and the server need to maintain a key This key is used to identify the client's Session across requests The server can then use the key to access the data stored for that user By default, the server gives the client a key using an HTTP cookie On subsequent requests to that server, the client will present the HTTP cookie and the server then has access to the session key

However, some clients choose not to accept HTTP cookies for a variety of reasons, a common one being the perceived privacy issue When this happens the site has to either 'adapt' and not support cookies (and Session), or build the application to not require use of Session A third option, first provided with IIS 4, is an ISAPI filter that can extract the session ID out of the cookie and pass it as part of the URL This concept is supported by ASP.NET as a first class feature This feature is known as cookieless Session state, and it works with any of the supported mode options

Individual applications can be configured to support either cookie or cookieless, but not both

Trang 8

We can enable cookieless Session support by simply setting a flag in our configuration system (highlighted):

Trang 9

As you can see from this, the session ID reqe3wvsxfoabvilmkmvq2p is embedded within the URL Below is the source

in Visual Basic NET for this You will notice that no special changes have been made to the sourcecode to support embedding the Session ID in the URL:

<Script runat=server>

Public Sub Session_Add(sender As Object, e As EventArgs)

Session("cart") = text1.Value

span1.InnerHtml = "Session data updated! <P>" + _

"Your session contains: <font color=red>" + _

Session("cart") + "</font>"

End Sub

Public Sub CheckSession(sender As Object, e As EventArgs)

If (Session("cart") Is Nothing) Then

span1.InnerHtml = "NOTHING, SESSION DATA LOST!"

Else

Trang 10

span1.InnerHtml = "Your session contains:" + _

"<font color=red>" + Session("cart") + "</font>"

End If

End Sub

</Script>

<form runat=server>

<input id=text1 type=text runat=server>

<input type=submit runat=server OnServerClick="Session_Add"

Value="Add to Session State">

<input type=submit runat=server OnServerClick="CheckSession"

Value="View Session State">

</form>

<a href="SessionState_cs.aspx">C# Example</A>

<hr size=1>

<font size=6><span id=span1 runat=server/></font>

Additionally, for relative URLs (as viewed by the browser) within the page, such as:

<a href="SessionState_cs.aspx">C# Example</a>

ASP.NET will automatically add the session ID into the URL Below is the link that the client receives:

Trang 11

<a href="/( yxxn2w555rn13henl2sxd055)/ SessionState_cs.aspx">C# Example</a>

Note the ID is added directly after the name of the application root In the above example, you can see that /Session is

marked as an application

The new features for Session state in ASP.NET are very powerful We can configure Session to be stored in a separate process from the ASP.NET worker process, which allows our Session data to be available in both a server farm and in the rare case that our web server crashes In addition to the great support for out-of-process Sessions state, support for cookieless Sessions has also been added Cookieless session allows us to use Session for clients that don't accept HTTP cookies Next, let's look at a feature of ASP.NET that replaces Response.Write() debugging for ASP pages

Call the Add routine: 4 + 5 = <%=Add(4,5)%>

The output of this is:

Call the Add routine: 4 + 5 = 9

Classic ASP Tracing

Trang 12

Although a simple example, what if within the Add function, we wished to know the parameters of a and b as the code was executing? A common technique ASP developers use is to add Response.Write() statements in their code to trace the actions of their code as it's executed:

<Script runat="server">

Public Function Add(a As Integer, b As Integer) As Integer

Response.Write("Inside Add() a: " + a.ToString() + "<BR>")

Response.Write("Inside Add() b: " + b.ToString() + "<BR>")

Return a + b

End Function

</Script>

Call the Add routine: 4 + 5 = <BR><%=Add(4,5)%>

The output of which is:

Call the Add routine: 4 + 5 =

Trang 13

statements:

<Script runat="server">

Public Function Add(a As Integer, b As Integer) As Integer

Trace.Write("Inside Add() a: ", a.ToString())

Trace.Write("Inside Add() b: ", b.ToString())

Return a + b

End Function

</Script>

Call the Add routine: 4 + 5 = <%=Add(4,5)%>

If we request this page, using the default settings of ASP.NET (by default trace output is not enabled), we would see the following result in our browser:

Call the Add routine: 4 + 5 = 9

We can think of tracing as 'debug mode' for ASP.NET applications, since tracing code can be left in our scripts and when tracing is disabled, the trace statements are simply ignored

Viewing Trace Output

To view the results of the Trace.Write() statements, we have two options:

ƒ Enable page tracing

ƒ Enable application tracing

By default, once tracing is enabled, the results are only presented to local clients - this is configurable, as we will see in

a moment

Enable Page Tracing

Trang 14

We can enable page tracing by adding a directive to the top of our ASP.NET Page:

<%@ Page Trace="true" %>

<Script runat="server">

Public Function Add(a As Integer, b As Integer) As Integer

Trace.Write("Inside Add() a: ", a.ToString())

Trace.Write("Inside Add() b: ", b.ToString())

Return a + b

End Function

</Script>

Call the Add routine: 4 + 5 = <%=Add(4,5)%>

This will add a trace output to the bottom of the requested page Included with this output are our Trace.Write() outputs:

Trang 15

Enable Application Tracing

Adding Trace="true" statements to the top of our ASP.NET pages isn't difficult, but what if we had a larger application consisting of several ASP.NET pages? Or, what if we wanted to trace the output of our application and view the results, but

at the same time not output the trace section at the end of each page? Application tracing allows us to accomplish all of this

We can enable application tracing by creating a web.config file with trace settings in it for our web application:

Trang 16

We can set the enabled flag to true (the inherited machine.config default is false), request our page, and then use

a special tool to view our application traces; trace.axd:

trace.axd is a special HTTP Handler used to view trace output for an application We will discuss this tool, tracing, and the Trace object in more detail in Chapter 22 Let's turn our attention to the configuration settings found in the web.config file we created

Trace Configuration Settings

The <trace> section within the configuration file provides us with some additional options not available when enabling tracing on a page These options include:

ƒ enabled - We can set the enabled option to true or false Tracing is either enabled at an application-level,

or it is disabled at the application-level If we set enabled="false", page tracing is still supported using the Trace directive discussed earlier By default, this value is set to false

enabled="[true | false]"

Trang 17

ƒ requestLimit - The total number of trace requests to keep cached in memory on a perapplication basis Tracing exposes a special resource, trace.axd, used to view trace output when pageOutput is set to false

By default, the value of requestLimit is 10

requestLimit = "[int]"

ƒ pageOutput - When tracing is enabled through the configuration file, the administrator is given the option to either enable or disable tracing on each page pageOutput tracing enables details to be traced for every page within an application However, pageOutput tracing may be turned off while applicationlevel tracing is still enabled (enabled = "true") What this does is keep trace requests in memory, such that they are available via trace.axd but not within the output of a page By default pageOutput is set to false

pageOutput = "[true | false]"

ƒ traceMode - The tracemode setting gives us control over how trace detail information is output Data may be sorted by time or category, where category is either the settings made by the system or the Trace.Write() settings enabled by the developer By default traceMode is set to SortByTime

traceMode = "[SortByTime | SortByCategory]"

ƒ localOnly - By default, localOnly is set to true When tracing is enabled, the localOnly flag determines whether or not the trace output is to be displayed only to local requests (those made through http://localhost) or for any request Since tracing is best used as a debug tool during development, it is suggested that the default setting be left as true

localOnly = "[true | false]"

Tracing is a great tool for debugging applications during development Tracing should not, however, be enabled for deployed applications When tracing is enabled, it consumes resources, and we want our applications as lean and mean

as possible This does not mean that we need to remove the Trace.Write() statements from our code When tracing

is not enabled, these statements are ignored and do not affect the performance of our application

For deployed applications, the recommendation is to use the Windows Event Log for application logging/tracing A sample use of the Windows Event Log is shown for the Application_OnError event discussed in the previous chapter

If you did any amount of coding in ASP, you will no doubt remember those helpful error codes, such as 0x800A01A8 ASP.NET makes some dramatic improvements on the level of detail available when errors occur, however, we don't always want that type of rich data displayed to end users With ASP.NET's custom errors configuration option, we can control how ASP.NET displays application error messages

Custom Errors

When a run-time or design-time error occurs within our application, ASP.NET will display a very helpful error page For example, a compilation error (such as forgetting to declare that C# is used) generates an error page that describes the error, highlights the line of code, provides detailed compiler output, and the complete source for the page:

Trang 18

While this is unbelievably useful for aiding in debugging the application, we obviously don't want to display this type of error detail to end users By default, this type of error detail is only available to requests to http://localhost Requests from other domains will display a helpful error page, without the details, that describes how to enable the ASP.NET application

to show richer error messages to remote clients:

What this error page describes is the <customErrors> section of configuration:

<configuration>

<system.web>

Trang 19

defaultRedirect, or finally show an IIS error.

ƒ On - ASP.NET will use user-defined error pages and will not use the rich, developeroriented ASP.NET error page

If a custom error page is not provided, ASP.NET will show the error page describing how to enable remote viewing of errors

ƒ Off - ASP.NET will always use ASP.NET's rich error page, with stack traces and compilation issues, when an error occurs

Always Showing ASP.NET Error Pages

If we want to always show the rich ASP.NET error page, such as when a team of developers are working against a single server, we could enable this mode by adding a web.config file with the following setting:

<configuration>

<system.web>

<customErrors mode="Off" />

</system.web>

Trang 20

</configuration>

In a production environment, we want to leave the default setting, mode="RemoteOnly", or mode="On", to ensure that remote users do not see rich error detail We also want to provide custom error pages

Custom Error Pages

For production applications, we always want to provide ASP.NET with a custom error page so that the enduser sees a friendly, helpful message rather than a developer-oriented message There are two ways in which we can support custom error pages:

ƒ Default redirects - A defined error page that the client is redirected to whenever an error occurs on the system

ƒ Custom redirects - A defined error page that the client is redirected to whenever a specific HTTP error occurs, for example the 404 Not Found error

Let's look at both of these starting with default redirects

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

TỪ KHÓA LIÊN QUAN