ASP.NET Programming with C# and SQL Server First Edition

Download Report

Transcript ASP.NET Programming with C# and SQL Server First Edition

ASP.NET Programming
with C# and SQL Server
First Edition
Chapter 9
Maintaining State
Information
Objectives
In this chapter, you will:
• Save state information with query strings, hidden
form fields, and post back
• Save state information with cookies
• Save state information with the Session state,
Application state, and Profiles
ASP.NET Programming with C# and SQL Server, First Edition
2
Introduction
• The Web was not originally designed to store
information about a user’s visit to a Web site
• Today, storing user information is an important
capability for ease of use
ASP.NET Programming with C# and SQL Server, First Edition
3
Understanding State Information
• Hypertext Transfer protocol (HTTP) manages
hypertext links for navigating Web pages
• State information: information about individual
visits to a Web site
• HTTP was originally designed to be stateless,
with no persistent data about a visit to a Web site
– This design hampered interactivity and limited
personalization
ASP.NET Programming with C# and SQL Server, First Edition
4
Understanding State Information
(cont’d.)
• State information allows a server to:
– Customize Web pages based on user preferences
– Temporarily store information for a user
– Allow a user to create bookmarks for returning to
specific locations within a Web site
– Provide shopping carts that store order information
– Store user IDs and passwords
– Use counters to keep track of how many times a
user has visited a site
ASP.NET Programming with C# and SQL Server, First Edition
5
Understanding State Information
(cont’d.)
• Sample application: Skyward Aviation Web site
– Implements frequent flyer login functionality
– Tracks information about the user’s entire visit
– Stores user profile in a table named FrequentFlyers,
which is in a database named SkywardAviation
• Three basic tools for maintaining state:
– Query strings
– Hidden form fields
– Post back and view state functionality of Web server
controls
ASP.NET Programming with C# and SQL Server, First Edition
6
Understanding State Information
(cont’d.)
Figure 9-1 Skyward Aviation Web site flow
ASP.NET Programming with C# and SQL Server, First Edition
7
Figure 9-2 Skyward Aviation home page
ASP.NET Programming with C# and SQL Server, First Edition
8
Understanding State Information
(cont’d.)
Figure 9-3 FrequentFlyers table fields
ASP.NET Programming with C# and SQL Server, First Edition
9
Query Strings
• Query strings are a quick way to pass data from
one Web page to another
• Add a question mark (?) after a URL with the query
string
– Query string consists of name=value pairs,
separated by an ampersand (&)
• This is the same functionality that occurs when
using a form with method=“get”
• Use the QueryString collection in the receiving
page to access the query string
• The query string is visible to users and is not secure
ASP.NET Programming with C# and SQL Server, First Edition
10
Hidden Form Fields
• A hidden form field is not displayed on a Web
browser
– Can be used to temporarily store data
• Use <input type=“hidden”> to create a
hidden form field
– name and value are the only attributes available
• Post back maintains view state by assigning form
values to a hidden form field named __VIEWSTATE
• Hidden form field values can be seen by opening a
Web page’s source code in the browser
ASP.NET Programming with C# and SQL Server, First Edition
11
Saving State with Post Back
• Post back and view state functionality in ASP.NET
makes state preservation easier and more robust
• MultiView control: used to hide and display areas
of a page that are defined by a View control
– Used to simulate a multipage form
• View control: acts as a container for text, markup,
and other controls
– Only one View control within a MultiView control can
be displayed at a given time
– The data on the form fields is preserved during post
back operations
ASP.NET Programming with C# and SQL Server, First Edition
12
Saving State with Post Back (cont’d.)
• To move between views within a MultiView control,
add a button to each View control
– Set the CommandName attribute to control the view to
display
• CommandName attribute values:
– NextView: displays the next View control
– PrevView: displays the previous View control
– SwitchViewByID: displays the View control with
the matching ID value in the CommandArgument
attribute
– SwitchViewByIndex: displays a View control
based on its index number
ASP.NET Programming with C# and SQL Server, First Edition
13
Figure 9-4 Pages of a multipage form
ASP.NET Programming with C# and SQL Server, First Edition
14
Saving State with Post Back (cont’d.)
• Use the Page_LoadComplete() event handler to
display information that was gathered on preceding
pages
• ActiveViewIndex: indicates which view is active
– Value of -1 means no view is active
ASP.NET Programming with C# and SQL Server, First Edition
15
Figure 9-5 Final page of the frequent flyer enrollment form
ASP.NET Programming with C# and SQL Server, First Edition
16
Figure 9-6 Account Profile page
ASP.NET Programming with C# and SQL Server, First Edition
17
Simulating Multipage Forms with the
Wizard Web Server Control
• Wizard Web server control: creates a multistep
wizard-style interface for gathering user input
– Used to hide and display areas of a page
– Automate navigation
• Syntax: <asp:Wizard ID=“id”
runat=“server”>
• <asp:WizardSteps> element: a container for
<asp:WizardStep> elements that represent
each step in the wizard
• Title attribute in each step is used to generate
navigation links
ASP.NET Programming with C# and SQL Server, First Edition
18
Wizard Web Server Controls (cont’d.)
Table 9-1 Common Wizard control behavior attributes
ASP.NET Programming with C# and SQL Server, First Edition
19
Wizard Web Server Controls (cont’d.)
Table 9-2 WizardStep control attributes
ASP.NET Programming with C# and SQL Server, First Edition
20
Wizard Web Server Controls (cont’d.)
• You can use Wizard Tasks in Design view to
create the Wizard control
• Styles section of a Wizard’s Properties page
controls the appearance of a wizard
– StepStyle: options for formatting an interim wizard
step
• Step box on Wizard Tasks menu allows you to
change the currently displayed wizard step in
Design view
• Use WizardStep Collection Editor to add/remove
steps
ASP.NET Programming with C# and SQL Server, First Edition
21
Wizard Web Server Controls (cont’d.)
Figure 9-7 Wizard Tasks menu
ASP.NET Programming with C# and SQL Server, First Edition
22
Wizard Web Server Controls (cont’d.)
Figure 9-8 WizardStep Collection Editor
ASP.NET Programming with C# and SQL Server, First Edition
23
Wizard Web Server Controls (cont’d.)
• Templates are available to control the appearance
of portions of a Wizard control
– Templates give you greater control over the design
and layout of a wizard
• Templates primarily determine the text and
elements to place in a specific area of the wizard
• Style objects primarily determine the formatting of
the text and elements
• Wizard control supports events related to the
navigation buttons and the changing of active steps
ASP.NET Programming with C# and SQL Server, First Edition
24
Wizard Web Server Controls (cont’d.)
Table 9-3 Wizard control templates
ASP.NET Programming with C# and SQL Server, First Edition
25
Wizard Web Server Controls (cont’d.)
Table 9-4 Wizard control events
ASP.NET Programming with C# and SQL Server, First Edition
26
Figure 9-9 Steps in the Fitness Survey wizard
ASP.NET Programming with C# and SQL Server, First Edition
27
Figure 9-10 Contact information page
ASP.NET Programming with C# and SQL Server, First Edition
28
Saving State Information with Cookies
• Query strings and hidden form fields do not
permanently maintain state information
• Cookies: small text file stored on a user’s
computer, containing information about the user
– Cookies are sent to the Web server and are used to
customize the Web page for the client
– Cookies can be temporary or persistent
• Temporary cookies: remain available only for the
current browser session
• Persistent cookies: remain available as a stored
text file on the client computer
ASP.NET Programming with C# and SQL Server, First Edition
29
Creating Cookies
• ASP.NET provides several ways to store cookies
• Cookies[] collection of the Response object:
– A mechanism for storing cookies as name=value pairs
– Syntax:
Response.Cookies[“cookieName].Value= “value”;
• HttpCookie class: used for creating a cookie
– Syntax:
HttpCookie cookieName = new
HttpCookie(“cookieName”);
– Use the Value property to assign a value
ASP.NET Programming with C# and SQL Server, First Edition
30
Creating Cookies (cont’d.)
• HttpCookie class provides greater control
– Lets you treat cookies as objects
• Can also store multiple name=value pairs, called
subkeys, in a single cookie
– Overcomes the limitation of 20 cookies per server or
domain on a client system
– Syntax for Cookies[] collection:
Response.Cookies[“cookieName”][“subkeyName”]
= “value”;
– Syntax for HttpCookie class:
cookieObject.Values[“subkeyName”]=“subkeyValue”;
ASP.NET Programming with C# and SQL Server, First Edition
31
Setting Cookie Expiration Dates
• Use the Expires property of the cookie object to
set how long it can remain on a client system
– If omitted, the cookie is available only for the current
browser setting
• Assign a DateTime structure to the Expires
property
– Use the Now property and one of the Add()
methods such as AddDays() or AddMonths()
ASP.NET Programming with C# and SQL Server, First Edition
32
Configuring Cookie Availability to
Other Web Pages on the Server
• Path property of a cookie object or
Response.Cookies[] collection: specifies
availability of a cookie to other Web pages on a
server
• By default, a cookie is available to all Web pages in
the same directory
– With a path specified, it is available to all Web pages
in the specified path and in all subdirectories
– Use a slash indicating the root directory to make it
available to all directories on a server
• Always place cookie programs in their own directory
ASP.NET Programming with C# and SQL Server, First Edition
33
Sharing Cookies Across a Domain
• Use the Domain property of a cookie object and
assign a domain to it to share the cookies across a
domain
– Cannot share cookies outside of a domain
• Use the Domain property of the
Response.Cookies[] collection to share cookies
across a domain
ASP.NET Programming with C# and SQL Server, First Edition
34
Securing Cookie Transmissions
• Secure Sockets Layer (SSL): used to encrypt
data and transfer it across a secure Internet
connection
– URLs start with https instead of http
• Secure property of a cookie object: indicates that
it can only be transmitted across a secure Internet
connection
ASP.NET Programming with C# and SQL Server, First Edition
35
Reading Cookies
• When a browser requests a Web page, it sends
any existing cookies for that Web site along with
the request
• Cookies are available in the Request.Cookies[]
collection
• Use the Value property to retrieve the value
• Always check if the cookie exists prior to
attempting to read it
– NullReferenceException will result from
trying to read a non-existent cookie
ASP.NET Programming with C# and SQL Server, First Edition
36
Modifying and Deleting Cookies
• You cannot directly modify the value assigned to a
cookie or subkey
• You must overwrite the old cookie with a new
cookie
• To delete a cookie, set its expiration to a date in
the past
– Can assign a value of yesterday by passing -1 to the
AddDays() method
• To delete a subkey, call the Remove() method of
the Values collection
ASP.NET Programming with C# and SQL Server, First Edition
37
Working with Session State,
Application State, and Profiles
• State information can be managed in three ways:
– Session state
– Application state
– Profile properties
ASP.NET Programming with C# and SQL Server, First Edition
38
Storing Session Information with
Session State
• A Request object is instantiated when a client
requests a URL and is destroyed when the URL is
delivered to the client
– You cannot use the same Request object with
different pages in an application
• Session state: stores specific client information
that is available to all pages for the current
ASP.NET session
• SessionStateItemCollection object: stores
session data
ASP.NET Programming with C# and SQL Server, First Edition
39
Storing Session Information with
Session State (cont’d.)
• You can access the
SessionStateItemCollection object through
the Session[] collection
• Use the <sessionState> element in the
Web.config file to configure session state
• An ASP.NET session has a default life span of 20
minutes
ASP.NET Programming with C# and SQL Server, First Edition
40
Table 9-5 Common attributes of the <sessionState> element
ASP.NET Programming with C# and SQL Server, First Edition
41
Using Cookieless Sessions
• By default, ASP.NET stores a session ID in a
cookie on the client’s browser
• If a browser does not accept cookies, ASP.NET
uses cookieless sessions
– Session ID is stored in a Web page’s URL
• Add the cookieless attribute to the
<sessionState> element to configure a Web site
to use cookieless sessions
– Use the AutoDetect value to use cookies if the
browser accepts them or cookieless if the browser
does not accept them
ASP.NET Programming with C# and SQL Server, First Edition
42
Storing Global Information with
Application State
• Application state: preserves information that can
be shared by all clients accessing an application
• Stored in an HttpApplicationState object
– Accessed through the Application[] collection
• Application state starts when the first client requests
one of the application’s pages, and then runs until
the server shuts down or is restarted or until the
application is restarted
• You can create your own application state variables
in the Application[] collection
ASP.NET Programming with C# and SQL Server, First Edition
43
Storing Global Information with
Application State (cont’d.)
• Use the Remove() and RemoveAll() methods of
the HttpApplicationState.Contents
property to remove application state variables
• Use the Lock() method of the
HttpApplicationState class to prevent other
clients from accessing properties of the
HttpApplicationState object while it is being
updated by a client
– Use the UnLock() method to cancel the Lock()
method
ASP.NET Programming with C# and SQL Server, First Edition
44
Storing User Information in Profiles
• If an application shuts down or restarts, all data
stored in the application state is lost
• Profiles: automatically store and retrieve strongly
typed state information to and from a SQL Server
database
– ASP.NET handles accessing the information for you
• Profiles are much more powerful than other
ASP.NET state preservation techniques
ASP.NET Programming with C# and SQL Server, First Edition
45
Storing User Information in Profiles
(cont’d.)
• You must perform these steps to use profiles:
– Use the aspnet_regsql.exe tool to configure the
aspnetdb SQL Server database used for storing
profile information
– Configure the connection information to the SQL
Server database
– Define profile properties using the <profile>
element in the Web.config file
• Edit the machine.config file to set the
connection information
– Use the <connectionStrings> element
ASP.NET Programming with C# and SQL Server, First Edition
46
Storing User Information in Profiles
(cont’d.)
• Add a provider name of
AspNetSqlProfileProvider in the
machine.config file to manage the storage of
profile information
• To define profile properties, add <profile>
elements to the <system.web> element in the
Web.config file
– Specify the type attribute to assign .NET class
types such as int32, System.Double, or
System.String
ASP.NET Programming with C# and SQL Server, First Edition
47
Summary
• State information is information about individual
visits to a Web site
• HTTP was originally designed to be stateless
• Pass data from one Web page to another using a
query string with ?, followed by name=value pairs
• Hidden form fields temporarily store data to be sent
to a server
• MultiView Web server controls hide and display
areas of a page that are defined by a View control
ASP.NET Programming with C# and SQL Server, First Edition
48
Summary (cont’d.)
• Wizard Web server controls create multistep
interfaces for gathering user input
• Cookies are small pieces of information about a
user stored in text files on the user’s computer
• Temporary cookies remain available only for the
current browser session, while persistent cookies
are stored in text files on client computers
• Session state stores specific client information that
is available to all pages in an ASP.NET application
• Cookieless sessions store the session ID in a Web
page’s URL instead of in a cookie
ASP.NET Programming with C# and SQL Server, First Edition
49
Summary (cont’d.)
• Use application state to preserve information to be
shared by all clients accessing an application
• Profiles automatically store and retrieve strongly
typed state information to and from a SQL Server
database
ASP.NET Programming with C# and SQL Server, First Edition
50