- •Preface
- •Who Should Read This Book
- •Organization and Presentation
- •Contacting the Authors
- •Acknowledgments
- •Contents
- •Introduction
- •Why Microsoft .NET?
- •The Microsoft .NET Architecture
- •Internet Standards
- •The Evolution of ASP
- •The Benefits of ASP.NET
- •What Is .NET?
- •.NET Experiences
- •.NET Clients
- •.NET Services
- •.NET Servers
- •Review
- •Quiz Yourself
- •Installation Requirements
- •Installing ASP.NET and ADO.NET
- •Installing the .NET Framework SDK
- •Testing Your Installation
- •Support for .NET
- •Review
- •Quiz Yourself
- •Designing a Database
- •Normalization of Data
- •Security Considerations
- •Review
- •Quiz Yourself
- •Creating a Database
- •Creating SQL Server Tables
- •Creating a View
- •Creating a Stored Procedure
- •Creating a Trigger
- •Review
- •Quiz Yourself
- •INSERT Statements
- •DELETE Statements
- •UPDATE Statements
- •SELECT Statements
- •Review
- •Quiz Yourself
- •The XML Design Specs
- •The Structure of XML Documents
- •XML Syntax
- •XML and the .NET Framework
- •Review
- •Quiz Yourself
- •ASP.NET Events
- •Page Directives
- •Namespaces
- •Choosing a Language
- •Review
- •Quiz Yourself
- •Introducing HTML Controls
- •Using HTML controls
- •How HTML controls work
- •Intrinsic HTML controls
- •HTML Control Events
- •The Page_OnLoad event
- •Custom event handlers
- •Review
- •Quiz Yourself
- •Intrinsic Controls
- •Using intrinsic controls
- •Handling intrinsic Web control events
- •List Controls
- •Rich Controls
- •Review
- •Quiz Yourself
- •Creating a User Control
- •Adding User Control Properties
- •Writing Custom Control Methods
- •Implementing User Control Events
- •Review
- •Quiz Yourself
- •Common Aspects of Validation Controls
- •Display property
- •Type Property
- •Operator Property
- •Using Validation Controls
- •RequiredFieldValidator
- •RegularExpressionValidator
- •CompareValidator
- •RangeValidator
- •CustomValidator
- •ValidationSummaryx
- •Review
- •Quiz Yourself
- •Maintaining State Out of Process for Scalability
- •No More Cookies but Plenty of Milk!
- •Out of Process State Management
- •Review
- •Quiz Yourself
- •Introducing the Key Security Mechanisms
- •Web.config and Security
- •Special identities
- •Using request types to limit access
- •New Tricks for Forms-based Authentication
- •Using the Passport Authentication Provider
- •Review
- •Quiz Yourself
- •ASP.NET Updates to the ASP Response Model
- •Caching with ASP.NET
- •Page Output Caching
- •Absolute cache expiration
- •Sliding cache expiration
- •Fragment Caching
- •Page Data Caching
- •Expiration
- •File and Key Dependency and Scavenging
- •Review
- •Quiz Yourself
- •A Brief History of Microsoft Data Access
- •Differences between ADO and ADO.NET
- •Transmission formats
- •Connected versus disconnected datasets
- •COM marshaling versus text-based data transmission
- •Variant versus strongly typed data
- •Data schema
- •ADO.NET Managed Provider Versus SQL Managed Provider
- •Review
- •Quiz Yourself
- •Review
- •Quiz Yourself
- •Creating a Connection
- •Opening a Connection
- •Using Transactions
- •Review
- •Quiz Yourself
- •Building a Command
- •Connection property
- •CommandText property
- •CommandType property
- •CommandTimeout property
- •Appending parameters
- •Executing a Command
- •ExecuteNonQuery method
- •Prepare method
- •ExecuteReader method
- •Review
- •Quiz Yourself
- •Introducing DataReaders
- •Using DataReader Properties
- •Item property
- •FieldCount property
- •IsClosed property
- •RecordsAffected property
- •Using DataReader Methods
- •Read method
- •GetValue method
- •Get[Data Type] methods
- •GetOrdinal method
- •GetName method
- •Close method
- •Review
- •Quiz Yourself
- •Constructing a DataAdapter Object
- •SelectCommand property
- •UpdateCommand, DeleteCommand, and InsertCommand properties
- •Fill method
- •Update method
- •Dispose method
- •Using DataSet Objects
- •DataSetName property
- •CaseSensitive property
- •Review
- •Quiz Yourself
- •Constructing a DataSet
- •Tables property
- •TablesCollection Object
- •Count property
- •Item property
- •Contains method
- •CanRemove method
- •Remove method
- •Add method
- •DataTable Objects
- •CaseSensitive property
- •ChildRelations property
- •Columns property
- •Constraints property
- •DataSet property
- •DefaultView property
- •ParentRelations property
- •PrimaryKey property
- •Rows property
- •Dispose method
- •NewRow method
- •Review
- •Quiz Yourself
- •What Is Data Binding?
- •Binding to Arrays and Extended Object Types
- •Binding to Database Data
- •Binding to XML
- •TreeView Control
- •Implement the TreeView server control
- •Review
- •Quiz Yourself
- •DataGrid Control Basics
- •Binding a set of data to a DataGrid control
- •Formatting the output of a DataGrid control
- •Master/Detail Relationships with the DataGrid Control
- •Populating the Master control
- •Filtering the detail listing
- •Review
- •QUIZ YOURSELF
- •Updating Your Data
- •Handling the OnEditCommand Event
- •Handling the OnCancelCommand Event
- •Handling the OnUpdateCommand Event
- •Checking that the user input has been validated
- •Executing the update process
- •Deleting Data with the OnDeleteCommand Event
- •Sorting Columns with the DataGrid Control
- •Review
- •Quiz Yourself
- •What Is Data Shaping?
- •Why Shape Your Data?
- •DataSet Object
- •Shaping Data with the Relations Method
- •Review
- •Quiz Yourself
- •OLEDBError Object Description
- •OLEDBError Object Properties
- •OLEDBError Object Methods
- •OLEDBException Properties
- •Writing Errors to the Event Log
- •Review
- •Quiz Yourself
- •Introducing SOAP
- •Accessing Remote Data with SOAP
- •SOAP Discovery (DISCO)
- •Web Service Description Language (WSDL)
- •Using SOAP with ASP.NET
- •Review
- •Quiz Yourself
- •Developing a Web Service
- •Consuming a Web Service
- •Review
- •Quiz Yourself
- •ASP and ASP.NET Compatibility
- •Scripting language limitations
- •Rendering HTML page elements
- •Using script blocks
- •Syntax differences and language modifications
- •Running ASP Pages under Microsoft.NET
- •Using VB6 Components with ASP.NET
- •Review
- •Quiz Yourself
- •Preparing a Migration Path
- •ADO and ADO.NET Compatibility
- •Running ADO under ASP.NET
- •Early Binding ADO COM Objects in ASP.NET
- •Review
- •Quiz Yourself
- •Answers to Part Reviews
- •Friday Evening Review Answers
- •Saturday Morning Review Answers
- •Saturday Afternoon Review Answers
- •Saturday Evening Review Answers
- •Sunday Morning Review Answers
- •Sunday Afternoon Review Answers
- •What’s on the CD-ROM
- •System Requirements
- •Using the CD with Windows
- •What’s on the CD
- •The Software Directory
- •Troubleshooting
- •ADO.NET Class Descriptions
- •Coding Differences in ASP and ASP.NET
- •Retrieving a Table from a Database
- •Displaying a Table from a Database
- •Variable Declarations
- •Statements
- •Comments
- •Indexed Property Access
- •Using Arrays
- •Initializing Variables
- •If Statements
- •Case Statements
- •For Loops
- •While Loops
- •String Concatenation
- •Error Handling
- •Conversion of Variable Types
- •Index
Session 12—Maintaining State in ASP.NET |
115 |
No More Cookies but Plenty of Milk!
In ASP.NET you can configure your application to store state without the use of cookies, also known as the cookieless method. In this method, ASP.NET simply munges the session id information into the URL of the requested page. This allows you to very easily implement your session information in a standard aspx page on server Foo, pass that information along to a relative path static html page, and then finally pass it back to a third aspx page and maintain state across the session. In order to do this, the session id information is encoded into the URL and thus isn’t dependent on the client to store it as a cookie. An example of a munged URL used when the cookieless method is used:
http://localhost/session12cookieless/(a5kb53fnuscirn55a4vt1gyt)/Webform2. aspx
The value a5kb53fnuscirn55a4vt1gyt highlighted in bold above is a unique key, which has been “munged” into the URL. This unique key allows the .NET Framework to locate session information specific to the user. In a cookie based implementation a similar value would be stored on the user’s hard drive as a cookie.
Advantages
The advantages of this method are:
Supports state maintenance for all browsers, even those without cookie support.
Allows you to pass session information between dynamic and static pages.
Disadvantages
The disadvantages of this method include:
Security risk associated with URL munging the data.
If implemented in-process, still requires that the user visit the session storing server to retrieve values.
How to make it happen
To implement this method, follow these steps:
1.Open the web.configWeb.config in the virtual directory of your ASP.NET application.
2.Locate the <system.Web> section of the Web.config file, or if none exists, create one.
3.Locate the <sessionstate> element.
4.Set the value of cookieless = true.
5.Save Web.config.
116 |
Saturday Afternoon |
Here is an example of a correctly configured Web.config file enabling cookieless state maintenance:
<?xml version=”1.0” encoding=”utf-8” ?> <configuration>
<system.Web>
<sessionState
mode=”InProc”
stateConnectionString=”tcpip=127.0.0.1:42424” sqlConnectionString=”data source=127.0.0.1;user id=sa;password=” cookieless=”true”
timeout=”20”
/>
</system.Web>
</configuration>
Note
When modifying the Web.config file be sure to pay particular notice to the capitalization of sections and elements, the file is case sensitive and incorrect capitalization will create errors.
After implementing the method as described above you can now test the use of the cookieless option by turning off cookies in your Web browser, create a virtual directory, add the Web.config file to the virtual directory and create the following three pages illustrated in Listings 12-1, 12-2, and 12-3.
Listing 12-1 Code for Webform1.aspx
<HTML>
<HEAD>
<SCRIPT RUNAT=”server” ID=”Script1”>
Sub btn1_Click(Sender As Object, E As EventArgs) Session(“SomeValue”) = text1.Value
span1.InnerHtml = “Session data created/updated! <P>Your session contains:” & Session(“SomeValue”) & “</font>”
End Sub </SCRIPT>
</HEAD>
<BODY>
<FORM RUNAT=”server” ID=”Form1”>
<INPUT ID=”text1” TYPE=”text” RUNAT=”server” NAME=”text1”> <INPUT TYPE=”submit” ID=”btn1” NAME=”btn1” ONSERVERCLICK=”Btn1_Click” RUNAT=”server” VALUE=”Submit Query”>
</FORM>
<ASP:HYPERLINK ID=”HyperLink1” RUNAT=”server” NAVIGATEURL=”StaticPage1.htm”>Click here to navigate to a static page.</ASP:HYPERLINK>
<BR>
<SPAN ID=”span1” NAME=”span1” RUNAT=”server”></SPAN> </BODY>
</HTML>
Session 12—Maintaining State in ASP.NET |
117 |
Listing 12-2 Code for Webform2.aspx
<HTML>
<HEAD>
<SCRIPT RUNAT=”server” ID=”Script1”> Sub Page_Load()
span1.InnerHtml = “Session data Recovered! <P>Your session contains: “ & Session(“SomeValue”) & “</font>”
End Sub </SCRIPT>
</HEAD>
<BODY>
<FONT SIZE=”6”><SPAN ID=”span1” NAME=”span1” RUNAT=”server”></FONT> <P>
Click <A HREF=”Webform1.aspx”>here</A> to modify the session variable </P>
</SPAN>
</BODY>
</HTML>
Listing 12-3 Code for staticpage1.htm
<HTML>
<HEAD>
<TITLE>Static Page</TITLE> </HEAD>
<BODY>
<P>
Static HTML Page. Of course there are no values to read, but click <A HREF=”Webform2.aspx”>
here</A> and you will see that session can still be recovered.
</P>
</BODY>
</HTML>
Open the Webform1.aspx page, and look at the URL in your browser, you should see that upon loading that page ASP.NET has now established a session id embedded in your Web browser. ASP.NET will use this unique key to track all of your session variables. Type in a value that you would like to store, then click the Submit Query button. You will see that the submitted value has been stored. Next, follow the hyperlink to the staticpage1.htm file. Although no session information is available here because it is an .htm file, you will see that the embedded session id remains in your browsers URL. Now follow the hyperlink to the Webform2.aspx page. You will see that the session information has been recovered!
In the previous example, you will notice that we set the mode attribute to InProc. This means that the state will be stored in process or in the physical memory of the server it was launched from when the session state was implemented. This means that if the server were to crash, all session information would be lost. This mode is effectively the mode that you operate in under traditional ASP. As we discussed earlier, this provides little in the way of redundancy or failover support needed for highly scalable Web applications.
118 |
Saturday Afternoon |
Out of Process State Management
We will now look at two new methods in ASP.NET that use external state management. This technique stores session values in an external state store instead of the ASP.NET worker process. By storing it out of process, you can make certain that state is stored across worker process restarts (such as when the machine must be restarted) as well as across multiple machines (such as you would commonly face in a Web farm). There are two external state management approaches:
The first method relies on using SQL Server to store state. This option provides you the most scalability and redundancy but requires you to have SQL Server. There is no Oracle support for this approach as of yet!
The second method utilizes an “ASP.NET state store.” This is a dedicated NT Service that can run on any Windows NT or Windows 2000 server.
Session Management with SQL Server
In this method, ASP.NET will utilize a database called ASPState on a selected SQL Server to store session information. Using this method you can choose to set the property Cookieless to either True or False, at your discretion, since where or how the unique session id is stored has no impact on the method used to store the values associated with the session id. The session id stored in the cookie or alternatively munged in the URL will be the unique key used to query the ASPState database and track session variables.
Advantages
The advantages of this method are:
Stores session state out of process, allowing you to run your application across multiple servers.
Supports request-based load balancing.
Provides extensive redundancy, reliability, and uptime when used in conjunction with clustering and hardware or software load balancing.
Ability to support periodic “code rot” purges.
Ability to partition an application across multiple worker processes.
Ability to partition an application across multiple Web farm machines.
Disadvantages
The disadvantages are:
Additional network traffic for database queries.
Maintenance of SQL Server database.
Session 12—Maintaining State in ASP.NET |
119 |
How to make it happen
Note
In order to use the SQL Server session management, you first need to make sure that you have SQL Server installed or available along with the InstallSqlState.sql file that ships with the Premium version of the .NET Framework SDK. You should also have administrative access to SQL Server.
1.You will need to locate the InstallSqlState.sql file that ships with the Premium version of the .NET Framework. This file creates a database for storing state values on a SQL Server Database of your choice. To implement this method, you need to install this script only once on your targeted database. You will need administrative access to SQL Server to execute this script.
2.To run the script, launch a command prompt, Start Programs Accessories Command Prompt.
3.Navigate to the [Drive]\WINNT\Microsoft.NET\Framework\[version] directory, where [Drive] is the installation drive such as C:\ and [version] is the version of the .NET Framework installed.
4.Type OSQL –S localhost –U [Administrator Userid] –P [Password] <InstallSqlState.sql.
5.An illustrative example of a properly formatted command line would be:
OSQL –S localhost -U sa -P < InstallSqlState.sql
6.Press Enter.
To uninstall this database, you can execute the SQL script UninstallSqlState.sql using the same process described in this session.
Note
This will create a database called ASPState on the selected SQL Server instance. We recommend that you restart SQL Server to make sure that the scripts have been applied. Next, we need to update the <system.Web> section of the Web.config file we used earlier in this session.
In order to activate SQL Server State Maintenance set the value of mode=”SQLServer”. Additionally set the sqlConnectionString=”data source=127.0.0.1;user id=sa; password=”, where data source is the IP address or name of your SQL Server; user id is an administrative user id, and of course the password for the administrator. Finally save the Web.config file. The following example provides an example of a properly configured Web.config file to support SQL Server State Maintenance:
<?xml version=”1.0” encoding=”utf-8” ?> <configuration>
<system.Web>
<sessionState
mode=”SQLServer”
sqlConnectionString=”data source=127.0.0.1;user id=sa;password=” stateConnectionString=”tcpip=127.0.0.1:42424”
cookieless=”true”
timeout=”20”
/>
</system.Web>
</configuration>
120 |
Saturday Afternoon |
Now you can run the same series of pages that you built earlier in the session, and you should see that they produce exactly the same results. What really should get you excited is to see what happens when you start and stop the SQL Server database when these pages are running to see how the recovery of session information is executed! Now that should make a few Web farm developers real happy!
Session Management with ASP.NET State Server
A second out of process approach to session state management utilizes an NT service and a file-based dictionary rather than a database to store state. This solution is likely to be used by shops that do not utilize SQL Server as their primary database in a Web farm, possibly using Oracle, or for smaller Web farms that do not yet need the scalability of SQL Server.
The ASP.NET State Server runs externally from worker processes in a dedicated .NET State Server process that runs as a Windows NT service. There is no end-user code allowed to run in the same process, thus eliminating the chance of unstable code breaking the service; additionally, no live object references are maintained.
The ASP.NET State Server stores blobs of binary data, either in memory or on disk. The
.NET worker processes are then able to take advantage of this simple storage service by saving (using .NET serialization services) all objects contained within a client’s Session collection object at the end of each Web request. Whenever the client needs to access the Session collection, the .NET objects will be retrieved as binary streams from the state
server by the appropriate worker process. It is then deserialized into a live instance of the object and placed back into a new Session collection object exposed to the request handler. The information stored in the collection is then accessed via the same methods used for in-process and SQL Server approaches described earlier in the session.
Advantages
The advantages of this method are:
Stores session state out of process, allowing you to run your application across multiple servers.
Supports request-based load balancing.
Provides adequate redundancy, reliability, and uptime when used in conjunction with clustering and hardware or software load balancing.
Ability to support periodic “code rot” purges.
Ability to partition an application across multiple worker processes.
Ability to partition an application across multiple Web farm machines.
Disadvantages
The disadvantages are:
Additional network traffic for data communication.
Managing a new NT Service.