164
1 2006 Pearson Education, Inc. All rights rese 2 1 ASP.NET 2.0, Web Forms and Web Controls

2006 Pearson Education, Inc. All rights reserved. 1 21 ASP.NET 2.0, Web Forms and Web Controls

  • View
    217

  • Download
    0

Embed Size (px)

Citation preview

1

2006 Pearson Education, Inc. All rights reserved.

2121ASP.NET 2.0, Web

Forms andWeb Controls

2

2006 Pearson Education, Inc. All rights reserved.

If any man will draw up his case, and put his name at the foot of the first page, I will give him an immediate reply. Where he compels me to turn over the sheet, he must wait my leisure.

— Lord Sandwich

Rule One: Our client is always rightRule Two: If you think our client is wrong, see Rule One.

— Anonymous

A fair question should be followed by a deed in silence.

— Dante Alighieri

3

2006 Pearson Education, Inc. All rights reserved.

You will come here and get books that will open your eyes, and your ears, and your curiosity, and turn you inside out or outside in.

— Ralph Waldo Emerson

4

2006 Pearson Education, Inc. All rights reserved.

OBJECTIVESIn this chapter you will learn: Web application development using ASP.NET. To create Web Forms. To create ASP.NET applications consisting of multiple

Web Forms. To maintain state information about a user with

session tracking and cookies. To use the Web Site Administration Tool to modify

Web application configuration settings. To control user access to Web applications using

forms authentication and ASP.NET login controls. To use databases in ASP.NET applications. To design a master page and content pages to create

a uniform look-and-feel for a Web site.

5

2006 Pearson Education, Inc. All rights reserved.

21.1 Introduction

21.2 Simple HTTP Transactions

21.3 Multitier Application Architecture

21.4 Creating and Running a Simple Web-Form Example

21.4.1 Examining an ASPX File

21.4.2 Examining a Code-Behind File

21.4.3 Relationship Between an ASPX File and a Code-Behind File

21.4.4 How the Code in an ASP.NET Web Page Executes

21.4.5 Examining the XHTML Generated by an ASP.NET Application

21.4.6 Building an ASP.NET Web Application

21.5 Web Controls

21.5.1 Text and Graphics Controls

21.5.2 AdRotator Control

21.5.3 Validation Controls

6

2006 Pearson Education, Inc. All rights reserved.

21.6 Session Tracking

21.6.1 Cookies

21.6.2 Session Tracking with HttpSessionState

21.7 Case Study: Connecting to a Database in ASP.NET

21.7.1 Building a Web Form That Displays Data from a Database

21.7.2 Modifying the Code-Behind File for the Guestbook Application

21.8 Case Study: Secure Books Database Application

21.8.1 Examining the Completed Secure Books Database Application

21.8.2 Creating the Secure Books Database Application

21.9 Wrap-Up

21.10 Web Resources

7

2006 Pearson Education, Inc. All rights reserved.

21.1 Introduction

• ASP.NET 2.0 and Web Forms and Controls– Web application development with Microsoft’s ASP.NET 2.0

technology

– Web Form files have the filename extension .aspx and contain the Web page’s GUI

– Every ASPX file created in Visual Studio has a corresponding class written in a .NET language, such as C#

• Contains event handlers, initialization code, utility methods and other supporting code

• Called the code-behind file

• Provides the ASPX file’s programmatic implementation

8

2006 Pearson Education, Inc. All rights reserved.

21.2 Simple HTTP Transactions

• Simple HTTP Transactions– HTTP specifies a set of methods and headers that allow clients and

servers to interact and exchange information – A Web page is nothing more than an XHTML document– A plain text file containing markup that describe to a Web browser

how to display and format the document’s information– Any XHTML document available for viewing over the Web has a

corresponding URL• An address indicating the location of an Internet resource

– When requesting ASP.NET Web applications, the Web server is usually Microsoft Internet Information Services (IIS)

– The information provided in the header specifies the Multipurpose Internet Mail Extensions (MIME) type of the content that the server is transmitting to the browser

• Internet standard that specifies data formats – Programs can interpret data correctly

9

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.1 | Client interacting with Web server. Step 1: The GET request.

10

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.2 | Client interacting with Web server. Step 2: The HTTP response.

11

2006 Pearson Education, Inc. All rights reserved.

21.3 Multitier Application Architecture

• Web-based applications are multitier applications – Multitier applications divide functionality into separate tiers

• Bottom (information) tier – Maintains data pertaining to the application; typically stores data in a

RDBMS• Middle tier

– Implements business, controller and presentation logic to control interactions between the application’s clients and data

– Acts as an intermediary between data in the information tier and the application’s clients

• Top (client) tier– Application’s user interface: gathers input and displays output– Interacts with the middle tier to make requests and to retrieve data

from the information tier• Displays the data retrieved from the middle tier to the user• The client tier never directly interacts with the information tier

12

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.3 | Three-tier architecture.

13

2006 Pearson Education, Inc. All rights reserved.

21.4.1 Examining an ASPX File

• Examining an ASPX File – ASP.NET comments begin with <%-- and terminate with --%>

– Page directive • Specifies the language of the code-behind file

– AutoEventWireup attribute • Determines how Web Form events are handle

– Inherits attribute • Specifies the class in the code-behind file from which this ASP.NET class

inherits

– ASP.NET markup is not case-sensitive• Using a different case is not problematic

14

2006 Pearson Education, Inc. All rights reserved.

21.4.1 Examining an ASPX File (Cont.)

– runat attribute • Indicates that when a client requests this ASPX file:

– Process the head element and its nested elements on the server

– Generate the corresponding XHTML• Sent to the client

– asp: tag prefix in a control declaration • Indicates that it is an ASP.NET Web control

– Each Web control maps to a corresponding XHTML element

• When processing a Web control, ASP.NET generates XHTML markup that will be sent to the client to represent that control in a Web browser

– span element • Contains text that is displayed in a Web page

15

2006 Pearson Education, Inc. All rights reserved.

1 <%-- Fig. 21.4: WebTime.aspx --%>

2 <%-- A page that displays the current time in a Label. --%>

3 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebTime.aspx.cs"

4 Inherits="WebTime" EnableSessionState="False" %>

5

6 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

7 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

8

9 <html xmlns="http://www.w3.org/1999/xhtml">

10 <head runat="server">

11 <title>A Simple Web Form Example</title>

12 </head>

13 <body>

14 <form id="form1" runat="server">

15 <div>

16 <h2>Current time on the Web server:</h2>

17 <p>

18 <asp:Label ID="timeLabel" runat="server" BackColor="Black"

19 Font-Size="XX-Large" ForeColor="Yellow"

20 EnableViewState="False"></asp:Label>

21 </p>

22 </div>

23 </form>

24 </body>

25 </html>

Outline

WebTime.aspx

ASP.NET comments

Page directive to specify information needed by

ASP.NET to process this file

Document type declaration

Mark up of a label web control

16

2006 Pearson Education, Inc. All rights reserved.

Portability Tip 21.1

The same Web control can map to different XHTML elements, depending on the client browser and the Web control’s property settings.

17

2006 Pearson Education, Inc. All rights reserved.

21.4.2 Examining a Code-Behind File

• Examining a Code-Behind File– System.Web.UI

• Contains classes and controls that assist in building Web-based applications

• Class Page – Provides event handlers and objects necessary for

creating Web-based applications– Method Page_Init

• Handles the Init event• Indicates that a page is ready to be initialized

• Class Control– The base class that provides common functionality for

all Web controls

18

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 21.5: WebTime.aspx.cs

2 // Code-behind file for a page that displays the current time.

3 using System;

4 using System.Data;

5 using System.Configuration;

6 using System.Web;

7 using System.Web.Security;

8 using System.Web.UI;

9 using System.Web.UI.WebControls;

10 using System.Web.UI.WebControls.WebParts;

11 using System.Web.UI.HtmlControls;

12

13 public partial class WebTime : System.Web.UI.Page

14 {

15 // initializes the contents of the page

16 protected void Page_Init( object sender, EventArgs e )

17 {

18 // display the server's current time in timeLabel

19 timeLabel.Text = string.Format( "{0:D2}:{1:D2}:{2:D2}",

20 DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second );

21 } // end method Page_Init

22 } // end class WebTime

Outline

WebTime.aspx.cs

(1 of 2)

Retrieve the current time and formats it as HH:MM:SS

19

2006 Pearson Education, Inc. All rights reserved.

Outline

WebTime.aspx.cs

(2 of 2)

20

2006 Pearson Education, Inc. All rights reserved.

21.4.3 Relationship Between an ASPX File and a Code-Behind File

• ASP.NET creates two classes behind the scenes– A Partial class containing the remainder of the class

• Based on the markup in the ASPX file

– A class based on the ASPX file • Defines the page’s visual representation• The first time the Web page is requested, the class is

compiled, and an instance is created

• Web controls– System.Web.UI.WebControls– Derive from class WebControl

21

2006 Pearson Education, Inc. All rights reserved.

Performance Tip 21.1

Once an instance of the Web page has been created, multiple clients can use it to access the page—no recompilation is necessary. The project will be recompiled only when you modify the application; changes are detected by the runtime environment, and the project is recompiled to reflect the altered content.

22

2006 Pearson Education, Inc. All rights reserved.

21.4.4 How the Code in an ASP.NET Web Page Executes

• How the Code in an ASP.NET Web Page Executes – Init event

• Occurs when an instance of a page is created– Load event occurs and the Page_Load event handler executes

• Inherited from class Page – Typically overridden to perform any processing that is necessary to

restore data from previous requests

– The page processes any events raised by the page’s controls after Page_Load finishes executing

– Unload event occurs when a Web Form object is ready for garbage collection

• Event handler Page_Unload – Inherited from class Page – Contains any code that releases resources

23

2006 Pearson Education, Inc. All rights reserved.

21.4.5 Examining the XHTML Generated by an ASP.NET Application• XHTML Generated by an ASP.NET Application

– XHTML forms can contain visual and nonvisual components

– Attribute method

• Specifies the method by which the Web browser submits the form to the server

– Attribute action

• Identifies the name and location of the resource that will be requested when this form is submitted

– The runat attribute is removed when the form is processed on the server

• The method and action attributes are added

• The resulting XHTML form is sent to the client browser

24

2006 Pearson Education, Inc. All rights reserved.

1 <!-- Fig. 21.6: WebTime.html -->

2 <!-- The XHTML generated when WebTime.aspx is loaded. -->

3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

4 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

5

6 <html xmlns="http://www.w3.org/1999/xhtml">

7 <head>

8 <title>A Simple Web Form Example</title>

9 </head>

10 <body>

11 <form method="post" action="WebTime.aspx" id="form1">

12 <div>

13 <input type="hidden" name="__VIEWSTATE"

14 id="__VIEWSTATE" value=

15 "/wEPDwUJODExMDE5NzY5ZGQ4n4mht8D7Eqxn73tM5LDnstPlCg==" />

16 </div>

17

18 <div>

19 <h2>Current time on the Web server:</h2>

20 <p>

21 <span id="timeLabel" style="color:Yellow;

22 background-color:Black;font-size:XX-Large;">

23 17:13:52

24 </span>

25 </p>

26 </div>

27 </form>

28 </body>

29 </html>

Outline

WebTime.html

Declaration for a non-visual component: hidden input

Represents the text in the label

25

2006 Pearson Education, Inc. All rights reserved.

21.4.6 Building an ASP.NET Web Application

• Step 1: Creating the Web Application Project (Fig. 21.7)

– http://localhost (IIS’s root directory) corresponds to C:\InetPub\wwwroot

• Step 2: Examining the Solution Explorer of the Newly Created Project (Fig. 21.8)

• Step 3: Examining the Toolbox in Visual Web Developer (Fig. 21.9)

• Step 4: Examining the Web Forms Designer (Fig. 21.10-11)

• Step 5: Examining the Code-Behind File in the IDE (Fig. 21.12)

• Step 6: Renaming the ASPX File

• Step 7: Renaming the Class in the Code-Behind File and Updating the ASPX File

• Step 8: Changing the Title of the Page

26

2006 Pearson Education, Inc. All rights reserved.

21.4.6 Building an ASP.NET Web Application (Cont.)

• Step 9: Designing the Page (Fig. 21.13)

– Relative positioning

• Positions of controls and other elements are relative to the Web Form’s upper-left corner

– Absolute positioning

• Controls are located exactly where they are dropped on the Web Form

– Visual Web Developer is a WYSIWYG editor

• “What You See Is What You Get”

• Step 10: Adding Page Logic

– Web.config stores configuration settings for an ASP.NET Web application

• Step 11: Running the Program

27

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.7 | Creating an ASP.NET Web Site in Visual Web Developer.

28

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.8 | Solution Explorer window for project WebTime.

Code-behind file

Properties

Refresh

Nest Related Files

View Code

View Designer Copy Web Site

ASP.NET Configuration

ASPX file

29

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.9 | Toolbox in Visual Web Developer.

(a) (b)

30

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.10 | Source mode of the Web Forms Designer.

Design mode button

Source mode button

31

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.11 | Design mode of the Web Forms Designer.

Cursor

Cursor’s current location

32

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.12 | Code-behind file for Default.aspx generated by Visual Web Developer.

33

2006 Pearson Education, Inc. All rights reserved.

Portability Tip 21.2

Absolute positioning is discouraged, because pages designed in this manner may not render correctly on computers with different screen resolutions and font sizes. This could cause absolutely positioned elements to overlap each other or display off-screen, requiring the client to scroll to see the full page content.

34

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.13 | WebTime.aspx after inserting text and a new paragraph.

Cursor position after inserting text and a new paragraph by pressing Enter

Block Format drop-down list

35

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.14 | WebTime.aspx after adding a Label and setting its properties.

Label

36

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.15 | Commonly used Web controls.

Web Control Description

Label Displays text that the user cannot edit.

TextBox Gathers user input and displays text.

Button Triggers an event when clicked.

HyperLink Displays a hyperlink.

DropDownList Displays a drop-down list of choices from which a user can select an item.

RadioButtonList Groups radio buttons.

Image Displays images (e.g., GIF and JPG).

37

2006 Pearson Education, Inc. All rights reserved.

21.5.1 Text and Graphics Controls• Examining Web Controls on a Sample Registration Form

– Image control • Inserts an image into a Web page

– ImageUrl property specifies the file location of the image to display– TextBox control

• Allows the you to obtain text from the user and display text to the user– DropDownList control

• Provides a list of options to the user• Each item in the drop-down list is defined by a ListItem element

– HyperLink control • Adds a hyperlink to a Web page

– NavigateUrl property specifies the resource that is requested– RadioButtonList control

• Provides a series of radio buttons for the user– Button control

• Represents a button that triggers an action when clicked

– Visual Web Developer displays smart tag menus for many ASP.NET controls to facilitate performing common tasks

38

2006 Pearson Education, Inc. All rights reserved.

1 <%-- Fig. 21.16: WebControls.aspx --%>

2 <%-- Registration form that demonstrates Web controls. --%>

3 <%@ Page Language="C#" AutoEventWireup="true"

4 CodeFile="WebControls.aspx.cs" Inherits="WebControls"

5 EnableSessionState="False" %>

6

7 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

8 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

9

10 <html xmlns="http://www.w3.org/1999/xhtml">

11 <head runat="server">

12 <title>Web Controls Demonstration</title>

13 </head>

14 <body>

15 <form id="form1" runat="server">

16 <div>

17 <h3>This is a sample registration form.</h3>

18 <p><em>Please fill in all fields and click Register.</em></p>

19 <p>

20 <asp:Image ID="UserInformationImage" runat="server"

21 ImageUrl="~/Images/user.png" EnableViewState="False" />

22 &nbsp;

23 <span style="color: teal">

24 Please fill out the fields below.</span>

25 </p>

Outline

WebControls.aspx

(1 of 6)

Define an Image control

Set the color of a specific piece of text

39

2006 Pearson Education, Inc. All rights reserved.

26 <table>

27 <tr>

28 <td style="width: 230px; height: 21px" valign="top">

29 <asp:Image ID="FirstNameImage" runat="server"

30 ImageUrl="~/Images/fname.png"

31 EnableViewState="False" />

32 <asp:TextBox ID="FirstNameTextBox" runat="server"

33 EnableViewState="False"></asp:TextBox>

34 </td>

35 <td style="width: 231px; height: 21px" valign="top">

36 <asp:Image ID="LastNameImage" runat="server"

37 ImageUrl="~/Images/lname.png"

38 EnableViewState="False" />

39 <asp:TextBox ID="LastNameTextBox" runat="server"

40 EnableViewState="False"></asp:TextBox>

41 </td>

42 </tr>

43 <tr>

44 <td style="width: 230px" valign="top">

45 <asp:Image ID="EmailImage" runat="server"

46 ImageUrl="~/Images/email.png"

47 EnableViewState="False" />

48 <asp:TextBox ID="EmailTextBox" runat="server"

49 EnableViewState="False"></asp:TextBox>

50 </td>

Outline

WebControls.aspx

(2 of 6)

Define a TextBox control used to collect the user’s first name

40

2006 Pearson Education, Inc. All rights reserved.

51 <td style="width: 231px" valign="top">

52 <asp:Image ID="PhoneImage" runat="server"

53 ImageUrl="~/Images/phone.png"

54 EnableViewState="False" />

55 <asp:TextBox ID="PhoneTextBox" runat="server"

56 EnableViewState="False"></asp:TextBox><br />

57 Must be in the form (555) 555-5555.

58 </td>

59 </tr>

60 </table>

61 <p>

62 <asp:Image ID="PublicationsImage" runat="server"

63 ImageUrl="~/Images/publications.png"

64 EnableViewState="False" />

65 &nbsp;

66 <span style="color: teal">

67 Which book would you like information about?</span>

68 </p>

69 <p>

70 <asp:DropDownList ID="BooksDropDownList" runat="server"

71 EnableViewState="False">

72 <asp:ListItem>Visual Basic 2005 How to Program 3e

73 </asp:ListItem>

74 <asp:ListItem>Visual C# 2005 How to Program 2e

75 </asp:ListItem>

76 <asp:ListItem>Java How to Program 6e</asp:ListItem>

77 <asp:ListItem>C++ How to Program 5e</asp:ListItem>

78 <asp:ListItem>XML How to Program 1e</asp:ListItem>

79 </asp:DropDownList>

80 </p>

Outline

WebControls.aspx

(3 of 6)

Defines a DropDownList

Each item in the drop-down list is defined by a ListItem element

41

2006 Pearson Education, Inc. All rights reserved.

81 <p>

82 <asp:HyperLink ID="BooksHyperLink" runat="server"

83 NavigateUrl="http://www.deitel.com" Target="_blank"

84 EnableViewState="False">

85 Click here to view more information about our books

86 </asp:HyperLink>

87 </p>

88 <p>

89 <asp:Image ID="OSImage" runat="server"

90 ImageUrl="~/Images/os.png" EnableViewState="False" />

91 &nbsp;

92 <span style="color: teal">

93 Which operating system are you using?</span>

94 </p>

95 <p>

96 <asp:RadioButtonList ID="OperatingSystemRadioButtonList"

97 runat="server" EnableViewState="False">

98 <asp:ListItem>Windows XP</asp:ListItem>

99 <asp:ListItem>Windows 2000</asp:ListItem>

100 <asp:ListItem>Windows NT</asp:ListItem>

101 <asp:ListItem>Linux</asp:ListItem>

102 <asp:ListItem>Other</asp:ListItem>

103 </asp:RadioButtonList>

104 </p>

Outline

WebControls.aspx

(4 of 6)Adds a hyperlink to the web page

Defines a RadioButtonList

control

Each item in the drop-down list is defined by a ListItem element

42

2006 Pearson Education, Inc. All rights reserved.

105 <p>

106 <asp:Button ID="RegisterButton" runat="server"

107 Text="Register" EnableViewState="False" />

108 </p>

109 </div>

110 </form>

111 </body>

112 </html>

Outline

WebControls.aspx

(5 of 6)Defines a Button web control

43

2006 Pearson Education, Inc. All rights reserved.

Outline

WebControls.aspx

(6 of 6)Image control

TextBox control

DropDownList control

HyperLink control

RadioButtonList control

Button control

44

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.17 | DropDownList Tasks smart tag menu.

45

2006 Pearson Education, Inc. All rights reserved.

21.5.2 AdRotator Control

•AdRotator control – Randomly selects an image to display

– Generates a hyperlink to the Web page associated with that image

– Browsers that do not support images display alternate text that is specified in the XML document

– The browser loads the Web page associated with that image when a user clicks the image or substituted text

46

2006 Pearson Education, Inc. All rights reserved.

21.5.2 AdRotator Control (Cont.)• AdRotator control

– Accesses an XML file to determine what advertisement image, hyperlink URL and alternate text to display and include in the page

• Create an XmlDataSource control to connect to the XML file – ImageUrl Element

• Specifies the path (location) of the advertisement’s image

– NavigateUrl Element • Specifies the URL for the Web page that loads when a user clicks the

advertisement– The URL cannot contain any whitespace

– AlternateText Element • Contains text that displays in place of the image when the browser cannot

locate or render the image– Also a tooltip

– Impressions Element • Specifies how often a particular image appears, relative to the other images

47

2006 Pearson Education, Inc. All rights reserved.

1 <%-- Fig. 21.18: FlagRotator.aspx --%>

2 <%-- A Web Form that displays flags using an AdRotator control. --%>

3 <%@ Page Language="C#" AutoEventWireup="true"

4 CodeFile="FlagRotator.aspx.cs" Inherits="FlagRotator"

5 EnableSessionState="False" %>

6

7 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

8 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

9

10 <html xmlns="http://www.w3.org/1999/xhtml" >

11 <head runat="server">

12 <title>Flag Rotator</title>

13 </head>

14 <body background="Images/background.png">

15 <form id="form1" runat="server">

16 <div>

17 <h3>AdRotator Example</h3>

18 <p>

19 <asp:AdRotator ID="countryRotator" runat="server"

20 DataSourceID="adXmlDataSource"

21 EnableViewState="False" />

22 <asp:XmlDataSource ID="adXmlDataSource" runat="server"

23 DataFile="~/App_Data/AdRotatorInformation.xml">

24 </asp:XmlDataSource>

25 </p>

26 </div>

27 </form>

28 </body>

29 </html>

Outline

FlagRotator.aspx

(1 of 2)

Defines an AdRotator

control

Defines an XmlDataSource control, which supplies the data

to the AdRotator control

48

2006 Pearson Education, Inc. All rights reserved.

Outline

FlagRotator.aspx

(2 of 2)

(a)

AdRotator image

AlternativeText displayed in a tooltip

(b)

(c)

49

2006 Pearson Education, Inc. All rights reserved.

1 <?xml version="1.0" encoding="utf-8"?>

2 <!-- Fig. 21.19: AdRotatorInformation.xml -->

3 <!-- XML file containing advertisement information. -->

4 <Advertisements>

5 <Ad>

6 <ImageUrl>Images/france.png</ImageUrl>

7 <NavigateUrl>

8 http://www.odci.gov/cia/publications/factbook/geos/fr.html

9 </NavigateUrl>

10 <AlternateText>France Information</AlternateText>

11 <Impressions>1</Impressions>

12 </Ad>

13

14 <Ad>

15 <ImageUrl>Images/germany.png</ImageUrl>

16 <NavigateUrl>

17 http://www.odci.gov/cia/publications/factbook/geos/gm.html

18 </NavigateUrl>

19 <AlternateText>Germany Information</AlternateText>

20 <Impressions>1</Impressions>

21 </Ad>

22

23 <Ad>

24 <ImageUrl>Images/italy.png</ImageUrl>

25 <NavigateUrl>

26 http://www.odci.gov/cia/publications/factbook/geos/it.html

27 </NavigateUrl>

28 <AlternateText>Italy Information</AlternateText>

29 <Impressions>1</Impressions>

30 </Ad>

Outline

AdRotatorInformation.xml

(1 of 4)Each Ad element represents an advertisement that will

be displayed by the AdRotator control

Specifies the path of the advertisement’s image

Specifies the URL for the Web page that loads when user

clicks on the advertisement

Text that displays in place of the image when the browser cannot render the image

Specifies how often a particular image appears

50

2006 Pearson Education, Inc. All rights reserved.

31

32 <Ad>

33 <ImageUrl>Images/spain.png</ImageUrl>

34 <NavigateUrl>

35 http://www.odci.gov/cia/publications/factbook/geos/sp.html

36 </NavigateUrl>

37 <AlternateText>Spain Information</AlternateText>

38 <Impressions>1</Impressions>

39 </Ad>

40

41 <Ad>

42 <ImageUrl>Images/latvia.png</ImageUrl>

43 <NavigateUrl>

44 http://www.odci.gov/cia/publications/factbook/geos/lg.html

45 </NavigateUrl>

46 <AlternateText>Latvia Information</AlternateText>

47 <Impressions>1</Impressions>

48 </Ad>

49

50 <Ad>

51 <ImageUrl>Images/peru.png</ImageUrl>

52 <NavigateUrl>

53 http://www.odci.gov/cia/publications/factbook/geos/pe.html

54 </NavigateUrl>

55 <AlternateText>Peru Information</AlternateText>

56 <Impressions>1</Impressions>

57 </Ad>

Outline

AdRotatorInformation.xml

(2 of 4)

51

2006 Pearson Education, Inc. All rights reserved.

58

59 <Ad>

60 <ImageUrl>Images/senegal.png</ImageUrl>

61 <NavigateUrl>

62 http://www.odci.gov/cia/publications/factbook/geos/sg.html

63 </NavigateUrl>

64 <AlternateText>Senegal Information</AlternateText>

65 <Impressions>1</Impressions>

66 </Ad>

67

68 <Ad>

69 <ImageUrl>Images/sweden.png</ImageUrl>

70 <NavigateUrl>

71 http://www.odci.gov/cia/publications/factbook/geos/sw.html

72 </NavigateUrl>

73 <AlternateText>Sweden Information</AlternateText>

74 <Impressions>1</Impressions>

75 </Ad>

76

77 <Ad>

78 <ImageUrl>Images/thailand.png</ImageUrl>

79 <NavigateUrl>

80 http://www.odci.gov/cia/publications/factbook/geos/th.html

81 </NavigateUrl>

82 <AlternateText>Thailand Information</AlternateText>

83 <Impressions>1</Impressions>

84 </Ad>

Outline

AdRotatorInformation.xml

(3 of 4)

52

2006 Pearson Education, Inc. All rights reserved.

85

86 <Ad>

87 <ImageUrl>Images/unitedstates.png</ImageUrl>

88 <NavigateUrl>

89 http://www.odci.gov/cia/publications/factbook/geos/us.html

90 </NavigateUrl>

91 <AlternateText>United States Information</AlternateText>

92 <Impressions>1</Impressions>

93 </Ad>

94 </Advertisements>

Outline

AdRotatorInformation.xml

(4 of 4)

53

2006 Pearson Education, Inc. All rights reserved.

21.5.3 Validation Controls

•Validation Control – Determines whether the data in another Web control is in

the proper format

– Provide a mechanism for validating user input on the client

– The validator is converted into ECMAScript when the XHTML for the page is created

• ECMAScript is a scripting language that enhances the functionality and appearance of Web pages

– For security reasons, validation is always performed on the server

54

2006 Pearson Education, Inc. All rights reserved.

21.5.3 Validation Controls (Cont.)– ControlToValidate property

• Indicates Validator verifies a control’s contents

– ErrorMessage Property• Text displayed if the validation fails

– Display property• Determines if the validator is displayed only when validation fails

– RegularExpressionValidator• Matches a Web control’s content against a regular expression

– That expression is assigned to ValidationExpression property

– IsPostBack property • Determines whether the page is being loaded due to a postback

– The current page reloads when the user submits the form

• EnableViewState attribute– Determines whether a Web control’s state persists when a postback

occurs

55

2006 Pearson Education, Inc. All rights reserved.

1 <%-- Fig. 21.20: Validation.aspx --%>

2 <%-- Form that demonstrates using validators to validate user input. --%>

3 <%@ Page Language="C#" AutoEventWireup="true"

4 CodeFile="Validation.aspx.cs" Inherits="Validation" %>

5

6 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

7 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

8

9 <html xmlns="http://www.w3.org/1999/xhtml" >

10 <head runat="server">

11 <title>Demonstrating Validation Controls</title>

12 </head>

13 <body>

14 <form id="form1" runat="server">

15 <div>

16 Please fill out the following form.<br />

17 <em>All fields are required and must

18 contain valid information.</em><br />

19 <br />

Outline

Validation.aspx

(1 of 6)

56

2006 Pearson Education, Inc. All rights reserved.

20 <table>

21 <tr>

22 <td style="width: 100px" valign="top">Name:</td>

23 <td style="width: 450px" valign="top">

24 <asp:TextBox ID="nameTextBox" runat="server">

25 </asp:TextBox><br />

26 <asp:RequiredFieldValidator ID="nameInputValidator"

27 runat="server" ControlToValidate="nameTextBox"

28 ErrorMessage="Please enter your name."

29 Display="Dynamic"></asp:RequiredFieldValidator>

30 </td>

31 </tr>

32 <tr>

33 <td style="width: 100px" valign="top">

34 E-mail address:</td>

35 <td style="width: 450px" valign="top">

36 <asp:TextBox ID="emailTextBox" runat="server">

37 </asp:TextBox>

38 &nbsp;e.g., [email protected]<br />

39 <asp:RequiredFieldValidator ID="emailInputValidator"

40 runat="server" ControlToValidate="emailTextBox"

41 ErrorMessage="Please enter your e-mail address."

42 Display="Dynamic"></asp:RequiredFieldValidator>

Outline

Validation.aspx

(2 of 6)

Defines a RequiredFieldValidator which confirms the TextBox is

not empty

57

2006 Pearson Education, Inc. All rights reserved.

43 <asp:RegularExpressionValidator

44 ID="emailFormatValidator" runat="server"

45 ControlToValidate="emailTextBox"

46 ErrorMessage="Please enter an e-mail address in a

47 valid format." Display="Dynamic"

48 ValidationExpression=

49 "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">

50 </asp:RegularExpressionValidator>

51 </td>

52 </tr>

53 <tr>

54 <td style="width: 100px" valign="top">Phone number:</td>

55 <td style="width: 450px" valign="top">

56 <asp:TextBox ID="phoneTextBox" runat="server">

57 </asp:TextBox>

58 &nbsp;e.g., (555) 555-1234<br />

59 <asp:RequiredFieldValidator ID="phoneInputValidator"

60 runat="server" ControlToValidate="phoneTextBox"

61 ErrorMessage="Please enter your phone number."

62 Display="Dynamic"></asp:RequiredFieldValidator>

Outline

Validation.aspx

(3 of 6)

Defines a RegularExpressionValidator

control to determine whether data is entered in a valid format

Defines a RequiredFieldValidator which confirms the TextBox is

not empty

58

2006 Pearson Education, Inc. All rights reserved.

63 <asp:RegularExpressionValidator

64 ID="phoneFormatValidator" runat="server"

65 ControlToValidate="phoneTextBox"

66 ErrorMessage="Please enter a phone number in a

67 valid format." Display="Dynamic"

68 ValidationExpression=

69 "((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}">

70 </asp:RegularExpressionValidator>

71 </td>

72 </tr>

73 </table>

74 <br />

75 <asp:Button ID="submitButton" runat="server" Text="Submit" />

76 <br /><br />

77 <asp:Label ID="outputLabel" runat="server"

78 Text="Thank you for your submission."

79 Visible="False"></asp:Label>

80 </div>

81 </form>

82 </body>

83 </html>

Outline

Validation.aspx

(4 of 6)

Defines a RegularExpressionValidator

control to determine whether data is entered in a valid format

59

2006 Pearson Education, Inc. All rights reserved.

Outline

Validation.aspx

(5 of 6)

(a)

(b)

60

2006 Pearson Education, Inc. All rights reserved.

Outline

Validation.aspx

(6 of 6)

(c)

(d)

61

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 21.21: Validation.aspx.cs

2 // Code-behind file for the form demonstrating validation controls.

3 using System;

4 using System.Data;

5 using System.Configuration;

6 using System.Web;

7 using System.Web.Security;

8 using System.Web.UI;

9 using System.Web.UI.WebControls;

10 using System.Web.UI.WebControls.WebParts;

11 using System.Web.UI.HtmlControls;

12

13 public partial class Validation : System.Web.UI.Page

14 {

15 // Page_Load event handler executes when the page is loaded

16 protected void Page_Load( object sender, EventArgs e )

17 {

18 // if this is not the first time the page is loading

19 // (i.e., the user has already submitted form data)

20 if ( IsPostBack )

21 {

22 // retrieve the values submitted by the user

23 string name = Request.Form[ "nameTextBox" ];

24 string email = Request.Form[ "emailTextBox" ];

25 string phone = Request.Form[ "phoneTextBox" ];

Outline

Validation.aspx.cs

(1 of 2)

Determines whether the page is being loaded due to a postback

Uses the Request object to retrieve the values of the TextBoxes

62

2006 Pearson Education, Inc. All rights reserved.

26

27 // create a table indicating the submitted values

28 outputLabel.Text +=

29 "<br />We received the following information:" +

30 "<table style=\"background-color: yellow\">" +

31 "<tr><td>Name: </td><td>" + name + "</td></tr>" +

32 "<tr><td>E-mail address: </td><td>" + email + "</td></tr>" +

33 "<tr><td>Phone number: </td><td>" + phone + "</td></tr>" +

34 "<table>";

35

36 outputLabel.Visible = true; // display the output message

37 } // end if

38 } // end method Page_Load

39 } // end class Validation

Outline

Validation.aspx.cs

(2 of 2)

63

2006 Pearson Education, Inc. All rights reserved.

Performance Tip 21.2

Setting EnableViewState to False reduces the amount of data passed to the Web server with each request.

64

2006 Pearson Education, Inc. All rights reserved.

1 <!-- Fig. 21.22: Validation.html -->

2 <!-- The XHTML and ECMAScript generated for Validation.aspx -->

3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

4 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

5

6 <html xmlns="http://www.w3.org/1999/xhtml" >

7 <head>

8 <title>Demonstrating Validation Controls</title>

9 </head>

10 <body>

11 <form method="post" action="Validation.aspx"

12 onsubmit="javascript:return WebForm_OnSubmit();" id="form1">

13 <div>

14 <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"

15 value="/wEPDwUJODc5MTExMzA4D2QWAgIDD2QWAgITDw8WBB4EVGV4dAWQ

16 AlRoYW5rIHlvdSBmb3IgeW91ciBzdWJtaXNzaW9uLjxiciAvPldlIHJlY2V

17 pdmVkIHRoZSBmb2xsb3dpbmcgaW5mb3JtYXRpb246PHRhYmxlIHN0eWxlPS

18 JiYWNrZ3JvdW5kLWNvbG9yOiB5ZWxsb3ciPjx0cj48dGQ+TmFtZTogPC90Z

19 D48dGQ+Qm9iPC90ZD48L3RyPjx0cj48dGQ+RS1tYWlsIGFkZHJlc3M6IDwv

20 dGQ+PHRkPmJ3aGl0ZUBlbWFpbC5jb208L3RkPjwvdHI+PHRyPjx0ZD5QaG9

21 uZSBudW1iZXI6IDwvdGQ+PHRkPig1NTUpIDU1NS0xMjM0PC90ZD48L3RyPj

22 wvdGFibGU+HgdWaXNpYmxlZ2RkZHiyTaX3DhELahxLUxCHnaZuvuMd" />

23 </div>

24

25 <script src="/Validation/WebResource.axd?d=kpdxzzpR0gHb8glw78d_

26 hfkpmf1QLBVBMoL34vcFGS41&amp;t=632494248729409088"

27 type="text/javascript"></script>

Outline

Validation.html

(1 of 9)A hidden input in the XHTML

document contains the data of the controls on this page

ECMAScript that provides the implementation for the

validation controls and for performing the postback

65

2006 Pearson Education, Inc. All rights reserved.

28

29 <script type="text/javascript">

30 <!--

31 function WebForm_OnSubmit() {

32 if (ValidatorOnSubmit() == false) return false;

33 return true;

34 }

35 // -->

36 </script>

37

38 <div>

39 Please fill out the following form.<br />

40 <em>All fields are required and must

41 contain valid information.</em><br />

42 <br />

43 <table>

44 <tr>

45 <td style="width: 100px" valign="top">Name:</td>

46 <td style="width: 450px" valign="top">

47 <input name="nameTextBox" type="text"

48 id="nameTextBox" /><br />

49 <span id="nameInputValidator" style="color:Red;

50 display:none;">Please enter your name.</span>

51 </td>

52 </tr>

Outline

Validation.html

(2 of 9)

66

2006 Pearson Education, Inc. All rights reserved.

53 <tr>

54 <td style="width: 100px" valign="top">

55 E-mail address:</td>

56 <td style="width: 450px" valign="top">

57 <input name="emailTextBox" type="text"

58 id="emailTextBox" />

59 &nbsp;e.g., [email protected]<br />

60 <span id="emailInputValidator" style="color:Red;

61 display:none;">Please enter your e-mail address.

62 </span>

63 <span id="emailFormatValidator" style="color:Red;

64 display:none;">Please enter an e-mail address in a

65 valid format.</span>

66 </td>

67 </tr>

68 <tr>

69 <td style="width: 100px" valign="top">Phone number:</td>

70 <td style="width: 450px" valign="top">

71 <input name="phoneTextBox" type="text"

72 id="phoneTextBox" />

73 &nbsp;e.g., (555) 555-1234<br />

74 <span id="phoneInputValidator" style="color:Red;

75 display:none;">Please enter your phone number.

76 </span>

77 <span id="phoneFormatValidator" style="color:Red;

78 display:none;">Please enter a phone number in a

79 valid format.</span>

80 </td>

81 </tr>

82 </table>

Outline

Validation.html

(3 of 9)

67

2006 Pearson Education, Inc. All rights reserved.

83 <br />

84 <input type="submit" name="submitButton" value="Submit"

85 onclick="javascript:WebForm_DoPostBackWithOptions(

86 new WebForm_PostBackOptions(&quot;submitButton&quot;,

87 &quot;&quot;, true, &quot;&quot;, &quot;&quot;,

88 false, false))" id="submitButton" />

89 <br /><br />

90 <span id="outputLabel">Thank you for your submission.<br />

91 We received the following information:

92 <table style="background-color: yellow">

93 <tr><td>Name: </td><td>Bob</td></tr>

94 <tr><td>E-mail address: </td><td>[email protected]</td></tr>

95 <tr><td>Phone number: </td><td>(555) 555-1234</td></tr>

96 </table>

97 </span>

98 </div>

99

100 <script type="text/javascript">

101 <!--

102 var Page_Validators = new Array(

103 document.getElementById("nameInputValidator"),

104 document.getElementById("emailInputValidator"),

105 document.getElementById("emailFormatValidator"),

106 document.getElementById("phoneInputValidator"),

107 document.getElementById("phoneFormatValidator"));

108 // -->

109 </script>

Outline

Validation.html

(4 of 9)

ECMAScript that provides the implementation for the

validation controls and for performing the postback

68

2006 Pearson Education, Inc. All rights reserved.

110

111 <script type="text/javascript">

112 <!--

113 var nameInputValidator =

114 document.all ? document.all["nameInputValidator"] :

115 document.getElementById("nameInputValidator");

116 nameInputValidator.controltovalidate = "nameTextBox";

117 nameInputValidator.errormessage = "Please enter your name.";

118 nameInputValidator.display = "Dynamic";

119 nameInputValidator.evaluationfunction =

120 "RequiredFieldValidatorEvaluateIsValid";

121 nameInputValidator.initialvalue = "";

122

123 var emailInputValidator =

124 document.all ? document.all["emailInputValidator"] :

125 document.getElementById("emailInputValidator");

126 emailInputValidator.controltovalidate = "emailTextBox";

127 emailInputValidator.errormessage =

128 "Please enter your e-mail address.";

129 emailInputValidator.display = "Dynamic";

130 emailInputValidator.evaluationfunction =

131 "RequiredFieldValidatorEvaluateIsValid";

132 emailInputValidator.initialvalue = "";

133

134 var emailFormatValidator =

135 document.all ? document.all["emailFormatValidator"] :

136 document.getElementById("emailFormatValidator");

137 emailFormatValidator.controltovalidate = "emailTextBox";

138 emailFormatValidator.errormessage =

Outline

Validation.html

(5 of 9)

ECMAScript that provides the implementation for the

validation controls and for performing the postback

69

2006 Pearson Education, Inc. All rights reserved.

139 "Please enter an e-mail address in a \r\n " +

140 " valid format.";

141 emailFormatValidator.display = "Dynamic";

142 emailFormatValidator.evaluationfunction =

143 "RegularExpressionValidatorEvaluateIsValid";

144 emailFormatValidator.validationexpression =

145 "\\w+([-+.\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";

146

147 var phoneInputValidator =

148 document.all ? document.all["phoneInputValidator"] :

149 document.getElementById("phoneInputValidator");

150 phoneInputValidator.controltovalidate = "phoneTextBox";

151 phoneInputValidator.errormessage =

152 "Please enter your phone number.";

153 phoneInputValidator.display = "Dynamic";

154 phoneInputValidator.evaluationfunction =

155 "RequiredFieldValidatorEvaluateIsValid";

156 phoneInputValidator.initialvalue = "";

Outline

Validation.html

(6 of 9)

ECMAScript that provides the implementation for the

validation controls and for performing the postback

70

2006 Pearson Education, Inc. All rights reserved.

157

158 var phoneFormatValidator =

159 document.all ? document.all["phoneFormatValidator"] :

160 document.getElementById("phoneFormatValidator");

161 phoneFormatValidator.controltovalidate = "phoneTextBox";

162 phoneFormatValidator.errormessage =

163 "Please enter a phone number in a \r\n " +

164 " valid format.";

165 phoneFormatValidator.display = "Dynamic";

166 phoneFormatValidator.evaluationfunction =

167 "RegularExpressionValidatorEvaluateIsValid";

168 phoneFormatValidator.validationexpression =

169 "((\\(\\d{3}\\) ?)|(\\d{3}-))?\\d{3}-\\d{4}";

170 // -->

171 </script>

172

173 <div>

174 <input type="hidden" name="__EVENTTARGET"

175 id="__EVENTTARGET" value="" />

176 <input type="hidden" name="__EVENTARGUMENT"

177 id="__EVENTARGUMENT" value="" />

178 </div>

179

180 <script type="text/javascript">

181 <!--

182 var theForm = document.forms['form1'];

183

184 if (!theForm) {

185 theForm = document.form1;

186 }

Outline

Validation.html

(7 of 9)

ECMAScript that provides the implementation for the

validation controls and for performing the postback

71

2006 Pearson Education, Inc. All rights reserved.

187

188 function __doPostBack(eventTarget, eventArgument) {

189 if (!theForm.onsubmit || (theForm.onsubmit() != false)) {

190 theForm.__EVENTTARGET.value = eventTarget;

191 theForm.__EVENTARGUMENT.value = eventArgument;

192 theForm.submit();

193 }

194 }

195 // -->

196 </script>

197

198 <script src="/Validation/WebResource.axd?d=2vO6TLcUQjFB3X5GN16w

199 bg2&amp;t=632494248729409088" type="text/javascript"></script>

200

201 <script type="text/javascript">

202 <!--

203 var Page_ValidationActive = false;

204

205 if (typeof(ValidatorOnLoad) == "function") {

206 ValidatorOnLoad();

207 }

Outline

Validation.html

(8 of 9)

ECMAScript that provides the implementation for the

validation controls and for performing the postback

72

2006 Pearson Education, Inc. All rights reserved.

208

209 function ValidatorOnSubmit() {

210 if (Page_ValidationActive) {

211 return ValidatorCommonOnSubmit();

212 }

213 else {

214 return true;

215 }

216 }

217 // -->

218 </script>

219 </form>

220 </body>

221 </html>

Outline

Validation.html

(9 of 9)

ECMAScript that provides the implementation for the

validation controls and for performing the postback

73

2006 Pearson Education, Inc. All rights reserved.

21.6 Session Tracking

• Session Tracking – Tracking individual clients– The request/response system on which the Web operates is

facilitated by HTTP• HTTP is a stateless protocol

– Does not support persistent connections • Web servers cannot maintain state information regarding

particular clients

– A session represents a unique client on a Web site• The client will still be recognized as the same user if the client leaves

a site and returns later– Each client must identify itself to the server

• Help the server distinguish among clients

74

2006 Pearson Education, Inc. All rights reserved.

21.6.1 Cookies

• Cookies– Piece of data stored in a small text file on the user’s computer

• Maintains information about the client during and between browser sessions

– Are sent and received as a collection of type HttpCookieCollection

– Web Forms can examine the cookies it sent to the client during previous communications

– The expiration date determines how long the cookie remains on the client’s computer

• The Web browser maintains the cookie for the duration of the browsing session if there is no expiration date

– Response object’s Cookies property • Used to write cookies to a client• Used to access cookies

– Can be read by an application only if they were created in the domain in which the application is running

75

2006 Pearson Education, Inc. All rights reserved.

Portability Tip 21.3

Clients may disable cookies in their Web browsers to ensure that their privacy is protected. Such clients will experience difficulty using Web applications that depend on cookies to maintain state information.

76

2006 Pearson Education, Inc. All rights reserved.

1 <%-- Fig. 21.23: Options.aspx --%>

2 <%-- Allows client to select programming languages and access --%>

3 <%-- book recommendations. --%>

4 <%@ Page Language="C#" AutoEventWireup="true"

5 CodeFile="Options.aspx.cs" Inherits="Options" %>

6

7 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

8 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

9

10 <html xmlns="http://www.w3.org/1999/xhtml" >

11 <head runat="server">

12 <title>Cookies</title>

13 </head>

14 <body>

15 <form id="form1" runat="server">

16 <div>

17 <asp:Label ID="promptLabel" runat="server" Font-Bold="True"

18 Font-Size="Large" Text="Select a programming language:">

19 </asp:Label>

20

21 <asp:RadioButtonList ID="languageList" runat="server">

22 <asp:ListItem>Visual Basic 2005</asp:ListItem>

23 <asp:ListItem>Visual C# 2005</asp:ListItem>

24 <asp:ListItem>C</asp:ListItem>

25 <asp:ListItem>C++</asp:ListItem>

26 <asp:ListItem>Java</asp:ListItem>

27 </asp:RadioButtonList>

28

29 <asp:Button ID="submitButton" runat="server" Text="Submit" />

Outline

Options.aspx

(1 of 4)

Declare a RadioButtonList with 5 elements

77

2006 Pearson Education, Inc. All rights reserved.

30

31 <asp:Label ID="responseLabel" runat="server" Font-Bold="True"

32 Font-Size="Large" Text="Welcome to cookies!"

33 Visible="False"></asp:Label>

34 <br /><br />

35

36 <asp:HyperLink ID="languageLink" runat="server"

37 Visible="False" NavigateUrl="~/Options.aspx">

38 Click here to choose another language</asp:HyperLink>

39 <br /><br />

40

41 <asp:HyperLink ID="recommendationsLink" runat="server"

42 Visible="False" NavigateUrl="~/Recommendations.aspx">

43 Click here to get book recommendations</asp:HyperLink>

44 </div>

45 </form>

46 </body>

47 </html>

Outline

Options.aspx

(2 of 4)

Declare two hyperlinks

Does not cause a postback to occur

78

2006 Pearson Education, Inc. All rights reserved.

Outline

Options.aspx

(3 of 4)

(a)

(b)

79

2006 Pearson Education, Inc. All rights reserved.

Outline

Options.aspx

(4 of 4)

(c)

(d)

80

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 21.24: Options.aspx.cs

2 // Processes user's selection of a programming language

3 // by displaying links and writing a cookie to the user's machine.

4 using System;

5 using System.Data;

6 using System.Configuration;

7 using System.Web;

8 using System.Web.Security;

9 using System.Web.UI;

10 using System.Web.UI.WebControls;

11 using System.Web.UI.WebControls.WebParts;

12 using System.Web.UI.HtmlControls;

13 public partial class Options : System.Web.UI.Page

14 {

15 // stores values to represent books as cookies

16 private System.Collections.Hashtable books =

17 new System.Collections.Hashtable();

18

19 // initializes the Hashtable of values to be stored as cookies

20 protected void Page_Init( object sender, EventArgs e )

21 {

22 books.Add( "Visual Basic 2005", "0-13-186900-0" );

23 books.Add( "Visual C# 2005", "0-13-152523-9" );

24 books.Add( "C", "0-13-142644-3" );

25 books.Add( "C++", "0-13-185757-6" );

26 books.Add( "Java", "0-13-148398-6" );

27 } // end method Page_Init

Outline

Options.aspx.cs

(1 of 3)

A data structure to hold book representations

Add each book element into the hash table

81

2006 Pearson Education, Inc. All rights reserved.

28

29 // if postback, hide form and display links to make additional

30 // selections or view recommendations

31 protected void Page_Load( object sender, EventArgs e )

32 {

33 if ( IsPostBack )

34 {

35 // user has submitted information, so display message

36 // and appropriate hyperlinks

37 responseLabel.Visible = true;

38 languageLink.Visible = true;

39 recommendationsLink.Visible = true;

40

41 // hide other controls used to make language selection

42 promptLabel.Visible = false;

43 languageList.Visible = false;

44 submitButton.Visible = false;

45

46 // if the user made a selection, display it in responseLabel

47 if ( languageList.SelectedItem != null )

48 responseLabel.Text += " You selected " +

49 languageList.SelectedItem.Text.ToString();

50 else

51 responseLabel.Text += " You did not select a language.";

52 } // end if

53 } // end method Page_Load

Outline

Options.aspx.cs

(2 of 3)

Determine whether user selected a language

Display the appropriate output

82

2006 Pearson Education, Inc. All rights reserved.

54

55 // write a cookie to record the user's selection

56 protected void submitButton_Click( object sender, EventArgs e )

57 {

58 // if the user made a selection

59 if ( languageList.SelectedItem != null )

60 {

61 string language = languageList.SelectedItem.ToString();

62

63 // get ISBN number of book for the given language

64 string ISBN = books[ language ].ToString();

65

66 // create cookie using language-ISBN name-value pair

67 HttpCookie cookie = new HttpCookie( language, ISBN );

68

69 // add cookie to response to place it on the user's machine

70 Response.Cookies.Add( cookie );

71 } // end if

72 } // end method submitButton_Click

73 } // end class Options

Outline

Options.aspx.cs

(3 of 3)Retrieve the value that corresponds to the key

contained in language

A new cookie object is created to store the language and its

corresponding ISBN number

The cookie is added to the Cookies collection sent as part

of the HTTP response header

83

2006 Pearson Education, Inc. All rights reserved.

1 <%-- Fig. 21.25: Recommendations.aspx --%>

2 <%-- Displays book recommendations using cookies. --%>

3 <%@ Page Language="C#" AutoEventWireup="true"

4 CodeFile="Recommendations.aspx.cs" Inherits="Recommendations" %>

5

6 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

7 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

8

9 <html xmlns="http://www.w3.org/1999/xhtml" >

10 <head runat="server">

11 <title>Book Recommendations</title>

12 </head>

13 <body>

14 <form id="form1" runat="server">

15 <div>

16 <asp:Label ID="recommendationsLabel"

17 runat="server" Text="Recommendations"

18 Font-Bold="True" Font-Size="X-Large">

19 </asp:Label><br /><br />

20

21 <asp:ListBox ID="booksListBox" runat="server" Height="125px"

22 Width="450px"></asp:ListBox><br /><br />

Outline

Recommendations.aspx

(1 of 2)

Display the recommendations created by the code-behind file

84

2006 Pearson Education, Inc. All rights reserved.

23

24 <asp:HyperLink ID="languageLink" runat="server"

25 NavigateUrl="~/Options.aspx">

26 Click here to choose another language

27 </asp:HyperLink>

28 </div>

29 </form>

30 </body>

31 </html>

Outline

Recommendations.aspx

(2 of 2)

85

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 21.26: Recommendations.aspx.cs

2 // Creates book recommendations based on cookies.

3 using System;

4 using System.Data;

5 using System.Configuration;

6 using System.Collections;

7 using System.Web;

8 using System.Web.Security;

9 using System.Web.UI;

10 using System.Web.UI.WebControls;

11 using System.Web.UI.WebControls.WebParts;

12 using System.Web.UI.HtmlControls;

13

14 public partial class Recommendations : System.Web.UI.Page

15 {

16 // read cookies and populate ListBox with any book recommendations

17 protected void Page_Init( object sender, EventArgs e )

18 {

19 // retrieve client's cookies

20 HttpCookieCollection cookies = Request.Cookies;

21

22 // if there are cookies, list the appropriate books and ISBN numbers

23 if ( cookies.Count != 0 )

24 {

25 for ( int i = 0; i < cookies.Count; i++ )

26 booksListBox.Items.Add( cookies[ i ].Name +

27 " How to Program. ISBN#: " + cookies[ i ].Value );

28 } // end if

Outline

Recommendations.aspx.cs

(1 of 2)

Retrieves the cookies from the client

Add the information in the cookie(s) to the booksListBox

86

2006 Pearson Education, Inc. All rights reserved.

29 else

30 {

31 // if there are no cookies, then no language was chosen, so

32 // display appropriate message and clear and hide booksListBox

33 recommendationsLabel.Text = "No Recommendations";

34 booksListBox.Items.Clear();

35 booksListBox.Visible = false;

36

37 // modify languageLink because no language was selected

38 languageLink.Text = "Click here to choose a language";

39 } // end else

40 } // end method Page_Init

41 } // end class Recommendations

Outline

Recommendations.aspx.cs

(2 of 2)

87

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.27 | HttpCookie properties.

Properties Description

Domain Returns a string containing the cookie’s domain (i.e., the domain of the Web server running the application that wrote the cookie). This determines which Web servers can receive the cookie. By default, cookies are sent to the Web server that originally sent the cookie to the client. Changing the Domain property causes the cookie to be returned to a Web server other than the one that originally wrote it.

Expires Returns a DateTime object indicating when the browser can delete the cookie.

Name Returns a string containing the cookie’s name.

Path Returns a string containing the path to a directory on the server (i.e., the Domain) to which the cookie applies. Cookies can be “targeted” to specific directories on the Web server. By default, a cookie is returned only to applications operating in the same directory as the application that sent the cookie or a subdirectory of that directory. Changing the Path property causes the cookie to be returned to a directory other than the one from which it was originally written.

Secure Returns a bool value indicating whether the cookie should be transmitted through a secure protocol. The value true causes a secure protocol to be used.

Value Returns a string containing the cookie’s value.

88

2006 Pearson Education, Inc. All rights reserved.

21.6.2 Session Tracking with HttpSessionState

• Class HttpSessionState– Provides session-tracking

– Every Web Form includes an HttpSessionState object• Accessible through property Session of class Page

– Can store name–value pairs using method Add– When adding an attribute that has the same name, the object

associated with that attribute is replaced

89

2006 Pearson Education, Inc. All rights reserved.

21.6.2 Session Tracking with HttpSessionState (Cont.)

– Property SessionID • Contains the unique session ID

– A sequence of random letters and numbers• The first time a client connects to server, a unique session ID is

created for that client

– Property Timeout • Specifies the maximum amount of time that an HttpSessionState

object can be inactive before it is discarded

– Property Count• Provides the number of session items contained in a Session object

– Property Keys • Returns a collection containing all the session’s keys

90

2006 Pearson Education, Inc. All rights reserved.

1 <%-- Fig. 21.28: Options.aspx --%>

2 <%-- Allows client to select programming languages and access --%>

3 <%-- book recommendations. --%>

4 <%@ Page Language="C#" AutoEventWireup="true"

5 CodeFile="Options.aspx.cs" Inherits="Options" %>

6

7 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

8 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

9

10 <html xmlns="http://www.w3.org/1999/xhtml" >

11 <head runat="server">

12 <title>Sessions</title>

13 </head>

14 <body>

15 <form id="form1" runat="server">

16 <div>

17 <asp:Label ID="promptLabel" runat="server" Font-Bold="True"

18 Font-Size="Large" Text="Select a programming language:">

19 </asp:Label>

20

21 <asp:RadioButtonList ID="languageList" runat="server">

22 <asp:ListItem>Visual Basic 2005</asp:ListItem>

23 <asp:ListItem>Visual C# 2005</asp:ListItem>

24 <asp:ListItem>C</asp:ListItem>

25 <asp:ListItem>C++</asp:ListItem>

26 <asp:ListItem>Java</asp:ListItem>

27 </asp:RadioButtonList>

28

29 <asp:Button ID="submitButton" runat="server" Text="Submit" />

Outline

Options.aspx

(1 of 4)

91

2006 Pearson Education, Inc. All rights reserved.

30

31 <asp:Label ID="responseLabel" runat="server" Font-Bold="True"

32 Font-Size="Large" Text="Welcome to sessions!"

33 Visible="False"></asp:Label><br /><br />

34

35 <asp:Label ID="idLabel" runat="server" Visible="False">

36 </asp:Label><br /><br />

37

38 <asp:Label ID="timeoutLabel" runat="server" Visible="False">

39 </asp:Label><br /><br />

40

41 <asp:HyperLink ID="languageLink" runat="server"

42 Visible="False" NavigateUrl="~/Options.aspx">

43 Click here to choose another language

44 </asp:HyperLink><br /><br />

45

46 <asp:HyperLink ID="recommendationsLink" runat="server"

47 Visible="False" NavigateUrl="~/Recommendations.aspx">

48 Click here to get book recommendations</asp:HyperLink>

49 </div>

50 </form>

51 </body>

52 </html>

Outline

Options.aspx

(2 of 4)

Hidden labels to display tracking information

92

2006 Pearson Education, Inc. All rights reserved.

Outline

Options.aspx

(3 of 4)

(a)

(b)

93

2006 Pearson Education, Inc. All rights reserved.

Outline

Options.aspx

(4 of 4)

(c)

(d)

94

2006 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 21.1

A Web Form should not use instance variables to maintain client state information, because each new request or postback, is handled by a new instance of the page. Web Forms should maintain client state information in HttpSessionState objects, because such objects are specific to each client.

95

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 21.29: Options.aspx.cs

2 // Processes user's selection of a programming language

3 // by displaying links and writing a cookie to the user's machine.

4 using System;

5 using System.Data;

6 using System.Configuration;

7 using System.Web;

8 using System.Web.Security;

9 using System.Web.UI;

10 using System.Web.UI.WebControls;

11 using System.Web.UI.WebControls.WebParts;

12 using System.Web.UI.HtmlControls;

13 public partial class Options : System.Web.UI.Page

14 {

15 // stores values to represent books as cookies

16 private System.Collections.Hashtable books =

17 new System.Collections.Hashtable();

18

19 //initializes the Hashtable of values to be stored as cookies

20 protected void Page_Init( object sender, EventArgs e )

21 {

22 books.Add( "Visual Basic 2005", "0-13-186900-0" );

23 books.Add( "Visual C# 2005", "0-13-152523-9" );

24 books.Add( "C", "0-13-142644-3" );

25 books.Add( "C++", "0-13-185757-6" );

26 books.Add( "Java", "0-13-148398-6" );

27 } // end method Page_Init

Outline

Options.aspx.cs

(1 of 3)

96

2006 Pearson Education, Inc. All rights reserved.

28

29 // if postback, hide form and display links to make additional

30 // selections or view recommendations

31 protected void Page_Load( object sender, EventArgs e )

32 {

33 if ( IsPostBack )

34 {

35 // user has submitted information, so display appropriate labels

36 // and hyperlinks

37 responseLabel.Visible = true;

38 idLabel.Visible = true;

39 timeoutLabel.Visible = true;

40 languageLink.Visible = true;

41 recommendationsLink.Visible = true;

42

43 // hide other controls used to make language selection

44 promptLabel.Visible = false;

45 languageList.Visible = false;

46 submitButton.Visible = false;

47

48 // if the user made a selection, display it in responseLabel

49 if ( languageList.SelectedItem != null )

50 responseLabel.Text += " You selected " +

51 languageList.SelectedItem.Text.ToString();

52 else

53 responseLabel.Text += " You did not select a language.";

54

55 // display session ID

56 idLabel.Text = "Your unique session ID is: " + Session.SessionID;

Outline

Options.aspx.cs

(2 of 3)

Returns the unique session ID

97

2006 Pearson Education, Inc. All rights reserved.

57

58 // display the timeout

59 timeoutLabel.Text = "Timeout: " + Session.Timeout + " minutes.";

60 } // end if

61 } // end method Page_Load

62

63 // write a cookie to record the user's selection

64 protected void submitButton_Click( object sender, EventArgs e )

65 {

66 // if the user made a selection

67 if ( languageList.SelectedItem != null )

68 {

69 string language = languageList.SelectedItem.ToString();

70

71 // get ISBN number of book for the given language

72 string ISBN = books[ language ].ToString();

73

74 Session.Add( language, ISBN ); // add name/value pair to Session

75 } // end if

76 } // end method submitButton_Click

77 } // end class Options

Outline

Options.aspx.cs

(3 of 3)

Returns the maximum amount of time that an HttpSessionState object can be inactive before it is discarded

Place the language and its corresponding ISBN number in the HttpSessionState object

98

2006 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 21.2

One of the primary benefits of using HttpSessionState objects (rather than cookies) is that HttpSessionState objects can store any type of object (not just Strings) as attribute values. This provides you with increased flexibility in determining the type of state information to maintain for clients.

99

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.30 | HttpSessionState properties.

Properties Description

Count Specifies the number of key–value pairs in the Session object.

IsNewSession Indicates whether this is a new session (i.e., whether the session was created during loading of this page).

IsReadOnly Indicates whether the Session object is read-only.

Keys Returns a collection containing the Session object’s keys.

SessionID Returns the session’s unique ID.

Timeout Specifies the maximum number of minutes during which a session can be inactive (i.e., no requests are made) before the session expires. By default, this property is set to 20 minutes.

100

2006 Pearson Education, Inc. All rights reserved.

1 <%-- Fig. 21.31: Recommendations.aspx --%>

2 <%-- Displays book recommendations using sessions. --%>

3 <%@ Page Language="C#" AutoEventWireup="true"

4 CodeFile="Recommendations.aspx.cs" Inherits="Recommendations" %>

5

6 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

7 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

8

9 <html xmlns="http://www.w3.org/1999/xhtml" >

10 <head runat="server">

11 <title>Book Recommendations</title>

12 </head>

13 <body>

14 <form id="form1" runat="server">

15 <div>

16 <asp:Label ID="recommendationsLabel"

17 runat="server" Text="Recommendations"

18 Font-Bold="True" Font-Size="X-Large">

19 </asp:Label><br /><br />

20

21 <asp:ListBox ID="booksListBox" runat="server" Height="125px"

22 Width="450px"></asp:ListBox><br /><br />

Outline

Recommendations.aspx

(1 of 2)

Used to present the recommendations to the user

101

2006 Pearson Education, Inc. All rights reserved.

23

24 <asp:HyperLink ID="languageLink" runat="server"

25 NavigateUrl="~/Options.aspx">

26 Click here to choose another language

27 </asp:HyperLink>

28 </div>

29 </form>

30 </body>

31 </html>

Outline

Recommendations.aspx

(2 of 2)

102

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 21.32: Recommendations.aspx.cs

2 // Creates book recommendations based on a session object.

3 using System;

4 using System.Data;

5 using System.Configuration;

6 using System.Collections;

7 using System.Web;

8 using System.Web.Security;

9 using System.Web.UI;

10 using System.Web.UI.WebControls;

11 using System.Web.UI.WebControls.WebParts;

12 using System.Web.UI.HtmlControls;

13

14 public partial class Recommendations : System.Web.UI.Page

15 {

16 // read cookies and populate ListBox with any book recommendations

17 protected void Page_Init( object sender, EventArgs e )

18 {

19 // stores a key name found in the Session object

20 string keyName;

21

22 // determine whether Session contains any information

23 if ( Session.Count != 0 )

24 {

25 for ( int i = 0; i < Session.Count; i++ )

26 {

27 keyName = Session.Keys[ i ]; // store current key name

Outline

Recommendations.aspx.cs

(1 of 2)

Provides the number of session items contained in

a Session object

Indexes the collection containing all the keys in the session to

receive the current key

103

2006 Pearson Education, Inc. All rights reserved.

28

29 // use current key to display one

30 // of session's name-value pairs

31 booksListBox.Items.Add( keyName +

32 " How to Program. ISBN#: " +

33 Session[ keyName ].ToString() );

34 } // end for

35 } // end if

36 else

37 {

38 // if there are no session items, no language was chosen, so

39 // display appropriate message and clear and hide booksListBox

40 recommendationsLabel.Text = "No Recommendations";

41 booksListBox.Items.Clear();

42 booksListBox.Visible = false;

43

44 // modify languageLink because no language was selected

45 languageLink.Text = "Click here to choose a language";

46 } // end else

47 } // end method Page_Init

48 } // end class Recommendations

Outline

Recommendations.aspx.cs

(2 of 2)

Concatenate and display the string that is the recommendation in the

ListBox

104

2006 Pearson Education, Inc. All rights reserved.

21.7.1 Building a Web Form That Displays Data from a Database

• Step 1: Creating the Project

• Step 2: Creating the Form for User Input (Fig. 21.33)

• Step 3: Adding a GridView Control to the Web Form

• Step 4: Adding a Database to an ASP.NET Web Application

– Database used by an ASP.NET Web site should be located in the project’s App_Data folder

• Step 5: Binding the GridView to the Messages Table of the Guestbook Database (Fig. 21.34-37)

• Step 6: Modifying the Columns of the Data Source Displayed in the GridView (Fig. 21.38)

• Step 7: Modifying the Way the SqlDataSource Control Inserts Data (Fig. 21.39)

105

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.33 | Guestbook application GUI in Design mode.

GridView control

106

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.34 | Change Data Source dialog in Visual Web Developer.

107

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.35 | Configuring the SELECT statement used by the SqlDataSource to retrieve data.

108

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.36 | Previewing the data retrieved by the SqlDataSource.

109

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.37 | Design mode displaying SqlDataSource control for a GridView.

SqlDataSource control

110

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.38 | Removing the MessageID column from the GridView.

111

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.39 | Setting up INSERT parameters based on control values.

112

2006 Pearson Education, Inc. All rights reserved.

21.7.1 Building a Web Form That Displays Data from a Database (Cont.)

•GridView – DataSourceID property

• Identifies the data source that is used to fill the GridView with data at runtime

– HeaderText property • Indicates the text that appears as the column header

– By default, this is the name of the column in the data source

– Each column is represented as a BoundField

113

2006 Pearson Education, Inc. All rights reserved.

21.7.1 Building a Web Form That Displays Data from a Database (Cont.)

• SqlDataSource– ConnectionString property

• Indicates the connection that the SqlDataSource control interacts with • The value of this property uses an ASP.NET expression, delimited by <%$

and %>

– SelectCommand, DeleteCommand, InsertCommand and UpdateCommand properties

• Contain the SELECT, DELETE, INSERT and UPDATE SQL statements, respectively

– Parameters that are set programmatically are defined by Parameter elements

– Parameters that obtain their values from controls are defined by ControlParameter elements

114

2006 Pearson Education, Inc. All rights reserved.

1 <%-- Fig. 21.40: Guestbook.aspx --%>

2 <%-- Guestbook Web application with a form for users to submit --%>

3 <%-- guestbook entries and a GridView to view existing entries. --%>

4 <%@ Page Language="C#" AutoEventWireup="true"

5 CodeFile="Guestbook.aspx.cs" Inherits="Guestbook" %>

6

7 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

8 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

9

10 <html xmlns="http://www.w3.org/1999/xhtml" >

11 <head runat="server">

12 <title>Guestbook</title>

13 </head>

14 <body>

15 <form id="form1" runat="server">

16 <div>

17 <h2><span style="color: navy">

18 Please leave a message in our guestbook:</span></h2>

19

20 <table>

21 <tr>

22 <td style="width: 130px; height: 21px" valign="top">

23 Your name:<br />

24 </td>

25 <td style="width: 300px; height: 21px" valign="top">

26 <asp:TextBox ID="nameTextBox" runat="server"

27 Width="300px"></asp:TextBox>

28 </td>

29 </tr>

Outline

Guestbook.aspx

(1 of 7)

115

2006 Pearson Education, Inc. All rights reserved.

30 <tr>

31 <td style="width: 130px" valign="top">

32 Your e-mail address:<br />

33 </td>

34 <td style="width: 300px" valign="top">

35 <asp:TextBox ID="emailTextBox" runat="server"

36 Width="300px"></asp:TextBox></td>

37 </tr>

38 <tr>

39 <td style="width: 130px" valign="top">

40 Tell the world:<br />

41 </td>

42 <td style="width: 300px" valign="top">

43 <asp:TextBox ID="messageTextBox" runat="server"

44 Height="100px" Rows="8" Width="300px">

45 </asp:TextBox>

46 </td>

47 </tr>

48 <tr>

49 <td style="width: 130px" valign="top">

50 </td>

51 <td style="width: 300px" valign="top">

52 <asp:Button ID="submitButton" runat="server"

53 Text="Submit" />

54 <asp:Button ID="clearButton" runat="server"

55 Text="Clear" />

56 </td>

57 </tr>

58 </table>

59 <br />

Outline

Guestbook.aspx

(2 of 7)

116

2006 Pearson Education, Inc. All rights reserved.

60

61 <asp:GridView ID="messagesGridView" runat="server"

62 AutoGenerateColumns="False" CellPadding="4"

63 ForeColor="#333333" GridLines="None"

64 DataSourceID="messagesSqlDataSource" Width="600px"

65 DataKeyNames="MessageID">

66 <FooterStyle BackColor="#1C5E55" Font-Bold="True"

67 ForeColor="White" />

68 <RowStyle BackColor="#E3EAEB" />

69 <PagerStyle BackColor="#666666" ForeColor="White"

70 HorizontalAlign="Center" />

71 <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True"

72 ForeColor="#333333" />

73 <HeaderStyle BackColor="#1C5E55" Font-Bold="True"

74 ForeColor="White" />

75 <EditRowStyle BackColor="#7C6F57" />

76 <AlternatingRowStyle BackColor="White" />

Outline

Guestbook.aspx

(3 of 7)

Declare the GridView control

Identifies the data source that is used to fill the GridView

with data at runtime

Properties that set various aspects of the GridView’s

appearance and behavior

117

2006 Pearson Education, Inc. All rights reserved.

77 <Columns>

78 <asp:BoundField DataField="Date" HeaderText="Date"

79 SortExpression="Date" />

80 <asp:BoundField DataField="Name" HeaderText="Name"

81 SortExpression="Name" />

82 <asp:BoundField DataField="Email" HeaderText="Email"

83 SortExpression="Email" />

84 <asp:BoundField DataField="Message" HeaderText="Message"

85 SortExpression="Message" />

86 </Columns>

87 </asp:GridView>

88

89 <asp:SqlDataSource ID="messagesSqlDataSource" runat="server"

90 ConnectionString=

91 "<%$ ConnectionStrings:GuestbookConnectionString %>"

92 SelectCommand="SELECT * FROM [Messages]"

93 DeleteCommand="DELETE FROM [Messages] WHERE

94 [MessageID] = @original_MessageID"

95 InsertCommand="INSERT INTO [Messages]

96 ([Date], [Name], [Email], [Message]) VALUES

97 (@Date, @Name, @Email, @Message)"

98 UpdateCommand="UPDATE [Messages] SET [Date] = @Date,

99 [Name] = @Name, [Email] = @Email, [Message] = @Message

100 WHERE [MessageID] = @original_MessageID">

101 <DeleteParameters>

102 <asp:Parameter Name="original_MessageID" Type="Int32" />

103 </DeleteParameters>

Outline

Guestbook.aspx

(4 of 7)

Define the columns that appear in the GridView

Each BoundField represents a column

Define a SqlDataSource

control

Indicates the connection through which the

SqlDataSource control interacts which the database

Defines SQL command statements

118

2006 Pearson Education, Inc. All rights reserved.

104 <UpdateParameters>

105 <asp:Parameter Name="Date" Type="String" />

106 <asp:Parameter Name="Name" Type="String" />

107 <asp:Parameter Name="Email" Type="String" />

108 <asp:Parameter Name="Message" Type="String" />

109 <asp:Parameter Name="original_MessageID" Type="Int32" />

110 </UpdateParameters>

111 <InsertParameters>

112 <asp:Parameter Name="Date" Type="String" />

113 <asp:ControlParameter ControlID="nameTextBox"

114 Name="Name" PropertyName="Text" Type="String" />

115 <asp:ControlParameter ControlID="emailTextBox"

116 Name="Email" PropertyName="Text" Type="String" />

117 <asp:ControlParameter ControlID="messageTextBox"

118 Name="Message" PropertyName="Text" Type="String" />

119 </InsertParameters>

120 </asp:SqlDataSource>

121 </div>

122 </form>

123 </body>

124 </html>

Outline

Guestbook.aspx

(5 of 7)

Indicates the control from which the parameter gets its value

Specifies the property that contains the actual value to be

used as the parameter valueParameters that obtain their values from controls

Parameters that are set programmatically

119

2006 Pearson Education, Inc. All rights reserved.

Outline

Guestbook.aspx

(6 of 7)

(a)

120

2006 Pearson Education, Inc. All rights reserved.

Outline

Guestbook.aspx

(7 of 7)

(b)

121

2006 Pearson Education, Inc. All rights reserved.

21.7.2 Modifying the Code-Behind File for the Guestbook Application

•SqlDataSource– InsertParameters collection

• Contains an item corresponding to each parameter in the SqlDataSource’s INSERT command

– Insert method • Executes the control’s INSERT command against the

database

•GridView method DataBind – Refreshes the information displayed in the GridView

122

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 21.41: Guestbook.aspx.cs

2 // Code-behind file that defines event handlers for the guestbook.

3 using System;

4 using System.Data;

5 using System.Configuration;

6 using System.Web;

7 using System.Web.Security;

8 using System.Web.UI;

9 using System.Web.UI.WebControls;

10 using System.Web.UI.WebControls.WebParts;

11 using System.Web.UI.HtmlControls;

12

13 public partial class Guestbook : System.Web.UI.Page

14 {

15 // Submit Button adds a new guestbook entry to the database,

16 // clears the form and displays the updated list of guestbook entries

17 protected void submitButton_Click( object sender, EventArgs e )

18 {

19 // create a date parameter to store the current date

20 System.Web.UI.WebControls.Parameter date =

21 new System.Web.UI.WebControls.Parameter(

22 "Date", TypeCode.String, DateTime.Now.ToShortDateString() );

23

24 // set the @Date parameter to the date parameter

25 messagesSqlDataSource.InsertParameters.RemoveAt( 0 );

26 messagesSqlDataSource.InsertParameters.Add( date );

Outline

Guestbook.aspx.cs

(1 of 2)

Assign a string representation of the current data to a new object of type Parameter

Remove the Date item in the InsertParameters

collection

Add our Date parameter

123

2006 Pearson Education, Inc. All rights reserved.

27

28 // execute an INSERT SQL statement to add a new row to the

29 // Messages table in the Guestbook database that contains the

30 // current date and the user's name, e-mail address and message

31 messagesSqlDataSource.Insert();

32

33 // clear the TextBoxes

34 nameTextBox.Text = "";

35 emailTextBox.Text = "";

36 messageTextBox.Text = "";

37

38 // update the GridView with the new database table contents

39 messagesGridView.DataBind();

40 } // end method submitButton_Click

41

42 // Clear Button clears the Web Form's TextBoxes

43 protected void clearButton_Click( object sender, EventArgs e )

44 {

45 nameTextBox.Text = "";

46 emailTextBox.Text = "";

47 messageTextBox.Text = "";

48 } // end method clearButton_Click

49 } // end class Guestbook

Outline

Guestbook.aspx.cs

(2 of 2)

Executes the INSERT command against the database: add a row to the Messages table

124

2006 Pearson Education, Inc. All rights reserved.

21.8.1 Examining the Completed Secure Books Database Application

• Form authentication– Protect a page so that only users known to the site can

access it

• Example of visual inheritance:– Master page defines common GUI elements that are

inherited by each page in a set of content pages

125

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.42 | Login.aspx page of the secure books database application.

126

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.43 | CreateNewUser.aspx page of the secure book database application.

127

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.44 | Message displayed to indicate that a user account was created successfully.

128

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.45 | Books.aspx displaying books by Harvey Deitel (by default).

129

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.46 | Books.aspx displaying books by Andrew Goldberg.

130

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.47 | Logging in using the Login control.

131

2006 Pearson Education, Inc. All rights reserved.

21.8.2 Creating the Secure Books Database Application

• Step 1: Creating the Web Site

• Step 2: Setting Up the Web Site’s Folders

• Step 3: Configuring the Application’s Security Settings (Fig. 21.49-53)

– Access rule grants or denies access to a particular Web application directory for a specific user

• Step 4: Examining the Auto-Generated Web.config Files

– authorization element indicates who is authorized to access a folder over the Web

– mode attribute species that we want to use forms authentication

– deny element specifies the users to whom we wish to deny access

• Step 5: Creating a Master Page (Fig. 21.54-56)

– Master directive specifies that this file defines a master page

– script element stores the code that is usually in the code behind file

– ContentPlaceHolder control serves as a placeholder for content that will be defined

132

2006 Pearson Education, Inc. All rights reserved.

21.8.2 Creating the Secure Books Database Application (Cont.)

• Step 6: Creating a Content Page (Fig. 21.57-58)

– Content control will place page-specific content that will replace the master page’s ContentPlaceHolder

• Step 7: Adding a CreateUserWizard Control to a Content Page (Fig. 21.59)

• Step 8: Creating a Login Page (Fig. 21.60)

– ASP.NET writes an encrypted cookie containing data about an authenticated user

– Authenticated user is redirected to the page specified by the Login control’s DestinationPageUrl property

• Step 9: Creating a Content Page That Only Authenticated Users Can Access

• Step 10: Customizing the Secure Page

– LoginName control displays the current authenticated user name

133

2006 Pearson Education, Inc. All rights reserved.

21.8.2 Creating the Secure Books Database Application (Cont.)

• Step 11: Connecting the CreateUserWizard and Login Controls to the Secure Page

• Step 12: Generating a DataSet Based on the Books.mdf Database

– ObjectDataSource encapsulates an object that provides access to a data source

• Step 13: Creating and Configuring an AuthorsTableAdapter (Fig. 21.61)

• Step 14: Creating and Configuring a TitlesTableAdapter (Fig. 21.62-63)

134

2006 Pearson Education, Inc. All rights reserved.

21.8.2 Creating the Secure Books Database Application (Cont.)

• Step 15: Adding a DropDownList Containing Authors’ First and Last Names (Fig. 21.64-66)

– A business object is an object that accesses data through another object

– DropDownList’s AutoPostBack property indicates that a postback occurs each time the user selects an item

• Step 16: Creating a GridView to Display the Selected Author’s Books (Fig. 21.67-68)

– Enable Sorting causes the column headings in the GridView to turn into hyperlinks that allow users to sort the data

– Enable Paging causes the GridView to split across multiple pages

– PageSize property determines the number of entries per page

• Step 17: Examining the Markup in Books.aspx (Fig. 21.69)

135

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.48 | Error message displayed for an unsuccessful login attempt using the Login control.

136

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.49 | Web Site Administration Tool for configuring a Web application.

137

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.50 | Security page of the Web Site Administration Tool.

138

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.51 | Choosing the type of authentication used by an ASP.NET Web application.

139

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.52 | Main page of the Web Site Administration Tool after enabling forms authentication.

140

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.53 | Add New Access Rule page used to configure directory access.

141

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.54 | Master page in Source mode.

142

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.55 | Master page in Design mode.

143

2006 Pearson Education, Inc. All rights reserved.

1 <%-- Fig. 21.56: Bug2Bug.master --%>

2 <%-- Master page that defines common features of all pages in the --%>

3 <%-- secure book database application. --%>

4 <%@ Master Language="C#" %>

5

6 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

7 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

8

9 <html xmlns="http://www.w3.org/1999/xhtml" >

10 <head runat="server">

11 <title>Bug2Bug</title>

12 </head>

13 <body>

14 <form id="form1" runat="server">

15 <div>

16 <table border="0" cellpadding="0" cellspacing="0"

17 style="width: 100%; height: 100%">

18 <tr>

19 <td height="130">

20 <asp:Image ID="headerImage" runat="server"

21 ImageUrl="~/Images/bug2bug.png" />

22 </td>

23 </tr>

Outline

Bug2Bug.master

(1 of 2)

Specify the language is C#

Display logo picture

144

2006 Pearson Education, Inc. All rights reserved.

24 <tr>

25 <td valign="top">

26 <asp:contentplaceholder id="bodyContent"

27 runat="server">

28 </asp:contentplaceholder>

29 </td>

30 </tr>

31 </table>

32 </div>

33 </form>

34 </body>

35 </html>

Outline

Bug2Bug.master

(2 of 2)

Define a ContentPlaceHolder

control

145

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.57 | Content page CreateNewUser.aspx in Source mode.

146

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.58 | Content page CreateNewUser.aspx in Design mode.

147

2006 Pearson Education, Inc. All rights reserved.

1 <%-- Fig. 21.59: CreateNewUser.aspx --%>

2 <%-- Content page using a CreateUserWizard control to register users. --%>

3 <%@ Page Language="C#" MasterPageFile="~/Bug2Bug.master"

4 Title="Create a New User" %>

5

6 <asp:Content ID="Content1" ContentPlaceHolderID="bodyContent"

7 Runat="Server">

8

9 <asp:CreateUserWizard ID="CreateUserWizard1" runat="server"

10 BackColor="#F7F6F3" BorderColor="#E6E2D8" BorderStyle="Solid"

11 BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em"

12 ContinueDestinationPageUrl="~/Secure/Books.aspx">

13

14 <SideBarStyle BackColor="#5D7B9D" BorderWidth="0px"

15 Font-Size="0.9em" VerticalAlign="Top" />

16 <SideBarButtonStyle BorderWidth="0px" Font-Names="Verdana"

17 ForeColor="White" />

18 <NavigationButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC"

19 BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"

20 ForeColor="#284775" />

21 <HeaderStyle BackColor="#5D7B9D" BorderStyle="Solid"

22 Font-Bold="True" Font-Size="0.9em"

23 ForeColor="White" HorizontalAlign="Left" />

24 <CreateUserButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC"

25 BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"

26 ForeColor="#284775" />

27 <ContinueButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC"

28 BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"

29 ForeColor="#284775" />

Outline

CreateNewUser.aspx

(1 of 3)

Specify language, master page, and title

Contains several properties that specify formatting styles for the control

Elements that define additional styles used to format specific

parts of the control

Replaces the master page’s ContentPlaceHolder

148

2006 Pearson Education, Inc. All rights reserved.

30 <StepStyle BorderWidth="0px" />

31 <TitleTextStyle BackColor="#5D7B9D" Font-Bold="True"

32 ForeColor="White" />

33

34 <WizardSteps>

35 <asp:CreateUserWizardStep runat="server">

36 </asp:CreateUserWizardStep>

37 <asp:CompleteWizardStep runat="server">

38 </asp:CompleteWizardStep>

39 </WizardSteps>

40 </asp:CreateUserWizard>

41 </asp:Content>

Outline

CreateNewUser.aspx

(2 of 3)

(a) (b)

Classes that encapsulate the details of creating a user and issuing a

confirmation message

149

2006 Pearson Education, Inc. All rights reserved.

Outline

CreateNewUser.aspx

(3 of 3)

(c)

150

2006 Pearson Education, Inc. All rights reserved.

1 <%-- Fig. 21.60: Login.aspx --%>

2 <%-- Content page using a Login control that authenticates users. --%>

3 <%@ Page Language="C#" MasterPageFile="~/Bug2Bug.master" Title="Login" %>

4

5 <asp:Content ID="Content1" ContentPlaceHolderID="bodyContent"

6 Runat="Server">

7

8 <asp:Login ID="Login1" runat="server" BackColor="#F7F6F3"

9 BorderColor="#E6E2D8" BorderPadding="4" BorderStyle="Solid"

10 BorderWidth="1px" CreateUserText="Click here to create a new user"

11 CreateUserUrl="~/CreateNewUser.aspx"

12 DestinationPageUrl="~/Secure/Books.aspx" DisplayRememberMe="False"

13 Font-Names="Verdana" Font-Size="0.8em" ForeColor="#333333">

14

15 <LoginButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC"

16 BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"

17 Font-Size="0.8em" ForeColor="#284775" />

18 <TextBoxStyle Font-Size="0.8em" />

19 <TitleTextStyle BackColor="#5D7B9D" Font-Bold="True"

20 Font-Size="0.9em" ForeColor="White" />

21 <InstructionTextStyle Font-Italic="True" ForeColor="Black" />

22 </asp:Login>

23 </asp:Content>

Outline

Login.aspx

(1 of 2)

Specify language, master page, and title

Replaces the master page’s ContentPlaceHolder

Create a Login control

The elements define various formatting

style applied to parts of the control

151

2006 Pearson Education, Inc. All rights reserved.

Outline

Login.aspx

(2 of 2)

(a) (b)

152

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.61 | Authors DataTable in the Dataset Designer.

153

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.62 | Query Builder for designing a query that selects books written by a particular author.

154

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.63 | Dataset Designer after adding the TitlesTableAdapter.

155

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.64 | Choosing a business object for an ObjectDataSource.

156

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.65 | Choosing a data method of a business object for use with an ObjectDataSource.

157

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.66 | Choosing a data source for a DropDownList.

158

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.67 | Choosing the data source for a parameter in a business object’s data method.

159

2006 Pearson Education, Inc. All rights reserved.

Fig. 21.68 | Completed Books.aspx in Design mode.

160

2006 Pearson Education, Inc. All rights reserved.

1 <%-- Fig. 21.69: Books.aspx --%>

2 <%-- Displays information from the Books database. --%>

3 <%@ Page Language="C#" MasterPageFile="~/Bug2Bug.master"

4 Title="Book Information" %>

5

6 <asp:Content ID="Content1" ContentPlaceHolderID="bodyContent"

7 Runat="Server">

8

9 Welcome, <asp:LoginName ID="LoginName1" runat="server" />!

10 <asp:LoginStatus ID="LoginStatus1" runat="server"

11 LogoutAction="RedirectToLoginPage"

12 LogoutText="Click here to log out" /><br /><br />

13

14 Author:

15 <asp:DropDownList ID="authorsDropDownList" runat="server"

16 AutoPostBack="True" DataSourceID="authorsObjectDataSource"

17 DataTextField="Name" DataValueField="AuthorID">

18 </asp:DropDownList>

19

20 <asp:ObjectDataSource ID="authorsObjectDataSource"

21 runat="server" SelectMethod="GetData"

22 TypeName="BooksDataSetTableAdapters.AuthorsTableAdapter">

23 </asp:ObjectDataSource><br /><br />

24

25 <asp:GridView ID="titlesGridView" runat="server" AllowPaging="True"

26 AllowSorting="True" AutoGenerateColumns="False" CellPadding="5"

27 DataKeyNames="ISBN" DataSourceID="titlesObjectDataSource"

28 PageSize="4" Width="600px">

Outline

Books.aspx

(1 of 5)

Create a LoginName control; displays the authenticated user’s name when the page is requested

and viewed in a browser

Create a LoginStatus control; redirect user to

login page after logging out

Indicates that changing the selected item in the list

causes a postback to occur

Specifies that this ObjectDataSource

accesses the Books database by calling GetData of BooksDataSet’s

AuthorsTableAdapter

Create the GridView that displays information about the books

written by the selected author

161

2006 Pearson Education, Inc. All rights reserved.

29

30 <Columns>

31 <asp:BoundField DataField="ISBN"

32 HeaderText="ISBN" ReadOnly="True" SortExpression="ISBN" />

33 <asp:BoundField DataField="Title"

34 HeaderText="Title" SortExpression="Title" />

35 <asp:BoundField DataField="EditionNumber"

36 HeaderText="EditionNumber" SortExpression="EditionNumber" />

37 <asp:BoundField DataField="Copyright"

38 HeaderText="Copyright" SortExpression="Copyright" />

39 </Columns>

40

41 <HeaderStyle BackColor="LightGreen" />

42 <AlternatingRowStyle BackColor="LightYellow" />

43 </asp:GridView>

44

45 <asp:ObjectDataSource ID="titlesObjectDataSource" runat="server"

46 SelectMethod="GetDataByAuthorID"

47 TypeName="BooksDataSetTableAdapters.TitlesTableAdapter">

48

49 <SelectParameters>

50 <asp:ControlParameter ControlID="authorsDropDownList"

51 DefaultValue="1" Name="authorID"

52 PropertyName="SelectedValue" Type="Int32" />

53 </SelectParameters>

54 </asp:ObjectDataSource>

55 </asp:Content>

Outline

Books.aspx

(2 of 5)

Define the ObjectDataSource

used to fill the GridView with data

Specifies that the value of method GetDataByAuthorID’s parameter comes from the

SelectedValue property of authorsDropDownList

162

2006 Pearson Education, Inc. All rights reserved.

Outline

Books.aspx

(3 of 5)

(a)

163

2006 Pearson Education, Inc. All rights reserved.

Outline

Books.aspx

(4 of 5)

(b)

164

2006 Pearson Education, Inc. All rights reserved.

Outline

Books.aspx

(5 of 5)

(c)