Chapter 20 ASP Net Web Forms and Web
Chapter 20 – ASP. Net, Web Forms and Web Controls Outline 20. 1 20. 2 20. 3 20. 4 20. 5 20. 6 20. 7 20. 8 20. 9 Introduction Simple HTTP Transaction System Architecture Creating and Running a Simple Web Form Example Web Controls 20. 5. 1 Text and Graphics Controls 20. 5. 2 Ad. Rotator Control 20. 5. 3 Validation Controls Session Tracking 20. 6. 1 Cookies 20. 6. 2 Session Tracking with Http. Session. State Case Study: Online Guest book Case Study: Connecting to a Database in ASP. NET Tracing 2002 Prentice Hall. All rights reserved. 1
2 20. 1 Introduction • Web-Based Application Development – Creates Web content for Web browser clients • Hyper. Text Markup Language (HTML) • Client-side scripting • Images and binary data – Web Forms (Web Form pages) • File extension. aspx • ASPX (Web Form files) contain written code, event handlers, utility methods and other supporting code 2002 Prentice Hall. All rights reserved.
3 20. 2 Simple HTTP Transaction • Hyper. Text Transfer Protocol (HTTP) – Defines methods and headers which allows clients and servers exchange information in uniform way • Uniform Resource Locator (URL) – IP address indicating the location of a resource – All HTML documents have a corresponding URL • Domain Name Server (DNS) – A computer that maintains a database of hostnames and their corresponding IP addresses 2002 Prentice Hall. All rights reserved.
4 20. 2 A Simple HTTP Transaction Fig. 20. 1 Client interacting with Web server. Step 1: The GET request, GET /books/downloads. htm HTTP/1. 1. 2002 Prentice Hall. All rights reserved.
5 20. 2 A Simple HTTP Transaction Fig. 20. 2 Client interacting with Web server. Step 2: The HTTP response, HTTP/1. 1 200 OK. 2002 Prentice Hall. All rights reserved.
6 20. 3 System Architecture • Multi-tier Applications – Web-based applications (n-tier applications) • Tiers are logical groupings of functionality • Information Tier (data tier or bottom tier) – Maintains data pertaining to the applications – Usually stores data in a relational database management systems (RDBMS) • Middle Tier – Acts as an intermediary between data in the information tier and the application's clients 2002 Prentice Hall. All rights reserved.
7 20. 3 System Architecture Fig. 20. 3 Three-tier architecture. 2002 Prentice Hall. All rights reserved.
20. 4 Creating and Running a Simple Web. Form Example • Visual Component – Clickable buttons and other GUI components which users interact • Nonvisual Component – Hidden inputs that store any data that document author specifies such as e-mail address 2002 Prentice Hall. All rights reserved. 8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Directive to specify information This determines how <%-- attribute Fig. 20. 4: Web. Time. aspx --%> needed to type process file Document declaration, <%-A page that contains two labels. --%> event handlers are linked to a specifies document element control’s <%@ Page events language="c#" Codebehind="Web. Time. aspx. cs" name and URI Outline Auto. Event. Wireup="false" Inherits="Web. Time. Test" Enable. Session. State="False" enable. View. State="False"%> <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > Specify Title for web page class in the codebehind file fromsetwhich this Auto. Event. Wire. Up to false ASP. NETStudio document because Visual generates <HTML> <HEAD> <title>Web. Time</title> necessary event <meta name="GENERATOR" Content="Microsoft Visual Studio 7. 0" > <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_default. Client. Script" content="Java. Script"> <meta name="vs_target. Schema" content="http: //schemas. microsoft. com/intellisense/ie 5" > </HEAD> delegates Web. Time. aspx Meta-element that contain information about document 2002 Prentice Hall. All rights reserved. 9
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 Body tag, beginning of Web page’s viewable content <body MS_POSITIONING="Grid. Layout"> <form id="Web. Form 1" method="post" runat="server"> <asp: Label id="prompt. Label" style="Z-INDEX: 101; LEFT: 25 px; POSITION: absolute; TOP: 23 px" runat="server" Font-Size="Medium"> The asp: Label control. Web maps A Simple Form Example </asp: Label> to HTML span element <asp: Label id="time. Label" style="Z-INDEX: 102; LEFT: 25 px; POSITION: absolute; TOP: 55 px" runat="server" Font-Size="XX-Large" Back. Color="Black" Fore. Color="Lime. Green"> </asp: Label> </form> </body> </HTML> Outline Attribute indicate the server processes the form and generate HTML for client Web. Time. aspx 2002 Prentice Hall. All rights reserved. 10
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Outline // Fig. 20. 5: Web. Time. aspx. cs // The code-behind file for a page // that displays the Web server's time. using using System; System. Collections; System. Component. Model; System. Data; System. Drawing; System. Web. Session. State; Contains classes that manage client requests and server responses // definitions for graphical controls used in Web Forms using System. Web. UI; using System. Web. UI. Web. Controls; using System. Web. UI. Html. Controls; Contain classes for creation of Web-based applications and Web. Time. aspx. cs controls namespace Web. Time { /// <summary> /// display current time /// </summary> public class Web. Time. Test : System. Web. UI. Page { protected System. Web. UI. Web. Controls. Label prompt. Label; protected System. Web. UI. Web. Controls. Label time. Label; // event handler for Load event private void Page_Load( object sender, System. Event. Args e ) { Web control labels defined in System. Web. UI. Web. Controls 2002 Prentice Hall. All rights reserved. 11
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 Outline // display current time. Label. Text = String. Format( "{0: D 2}: {1: D 2}: {2: D 2}", Date. Time. Now. Hour, Date. Time. Now. Minute, Date. Time. Now. Second ); } // event handler for Init event; sets // time. Label to Web server's time #region Web Form Designer generated code override protected void On. Init( Event. Args e ) { // // CODEGEN: This call is required by the // ASP. NET Web Form Designer. // Initialize. Component (); base. On. Init( e ); } Set time. Label’s Text property to Web server’s time /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void Initialize. Component() Event raised when { this. Load += new System. Event. Handler( this. Page_Load ); } #endregion Web. Time. aspx. cs Web page loads } // end class Web. Time. Test } // end namespace Web. Time 2002 Prentice Hall. All rights reserved. 12
Outline Web. Time. cs Program Output 2002 Prentice Hall. All rights reserved. 13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 <!-- Fig. 20. 6: Web. Time. html --> <!-- The HTML generated when Web. Time is loaded. --> Outline <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <HEAD> <title>Web. Time</title> <meta name="GENERATOR" Content="Microsoft Visual Studio 7. 0" > <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_default. Client. Script" content="Java. Script"> <meta name="vs_target. Schema" Defines the body of the document content="http: //schemas. microsoft. com/intellisense/ie 5"> </HEAD> Hidden inputs from the user <body MS_POSITIONING="Grid. Layout"> <form name="Web. Form 1" method="post" action="Web. Time. aspx" id="Web. Form 1"> <input type="hidden" name="__VIEWSTATE" value="d. Dwt. Nj. A 2 MTkw. MTQ 5 Ozs+" /> Web. Time. html <span id="prompt. Label" style="font-size: Medium; Z-INDEX: 101; LEFT: 25 px; POSITION: absolute; TOP: 23 px" > A Simple Web Form Example </span> <span id="time. Label" style="color: Lime. Green; background-color: Black; font-size: XX-Large; Z-INDEX: 102; LEFT: 25 px; POSITION: absolute; TOP: 55 px">10: 39: 35 2002 Prentice Hall. All rights reserved. 14
33 34 35 36 </span> </form> </body> </HTML> Outline Web. Time. html 2002 Prentice Hall. All rights reserved. 15
20. 4 Creating and Running a Simple Web Form Example Fig. 20. 7 Creating an ASP. NET Web Application in Visual Studio. 2002 Prentice Hall. All rights reserved. 16
20. 4 Creating and Running a Simple Web Form Example Fig. 20. 8 Visual Studio creating and linking a virtual directory for the Web. Time project folder. 2002 Prentice Hall. All rights reserved. 17
20. 4 Creating and Running a Simple Web Form Example displays all files code-behind file Fig. 20. 9 Solution Explorer window for project Web. Time. 2002 Prentice Hall. All rights reserved. ASPX file 18
20. 4 Creating and Running a Simple Web Form Example Fig. 20. 10 Web Forms menu in the Toolbox. . 2002 Prentice Hall. All rights reserved. 19
20 20. 4 Creating and Running a Simple Web Form Example grids Fig. 20. 11 Design mode of Web Form designer. 2002 Prentice Hall. All rights reserved.
20. 4 Creating and Running a Simple Web Form Example Fig. 20. 12 HTML mode of Web Form designer. 2002 Prentice Hall. All rights reserved. 21
20. 4 Creating and Running a Simple Web Form Example Fig. 20. 13 Code-behind file for Web. Form 1. aspx generated by Visual Studio. NET (part 1). 2002 Prentice Hall. All rights reserved. 22
20. 4 Creating and Running a Simple Web Form Example Fig. 20. 13 Code-behind file for Web. Form 1. aspx generated by Visual Studio. NET (part 2). 2002 Prentice Hall. All rights reserved. 23
20. 4 Creating and Running a Simple Web Form Example Flow. Layout— Controls are placed one after the other Grid. Layout—Controls are placed where they are dropped on the page Fig. 20. 14 Flow. Layout and Grid. Layout illustration. 2002 Prentice Hall. All rights reserved. cursor indicates where next control will go 24
20. 4 Creating and Running a Simple Web Form Example labels Web Form Fig. 20. 15 Web. Form. aspx after adding two Labels and setting their properties. 2002 Prentice Hall. All rights reserved. 25
26 20. 5 Web Controls • Text and Graphics Control – Label, Button, Text. Box, Image Radio. Button. List and Drop. Down. List • Ad. Rotator Control – Randomly selects an image to display and then generates a hyperlink to the Web page associated with that image • Validation Controls – Determines whether the data in another Web control are in the proper format • Validates user input 2002 Prentice Hall. All rights reserved.
27 20. 5 Web Controls 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <%-- Fig. 20. 17: Web. Controls. aspx --%> <%-- Demonstrating some Web controls. --%> Outline 28 <%@ Page language="c#" Codebehind="Web. Controls. aspx. cs" Auto. Event. Wireup="false" Inherits="Web. Controls. Web. Form 1" Enable. Session. State="False" enable. View. State="False"%> <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <HEAD> <title>Web. Form 1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio 7. 0" > <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_default. Client. Script" content="Java. Script"> <meta name="vs_target. Schema" content="http: //schemas. microsoft. com/intellisense/ie 5"> Web. Controls. aspx </HEAD> <body MS_POSITIONING="Grid. Layout"> <form id="Form 1" method="post" runat="server"> <asp: Label id="welcome. Label" style="Z-INDEX: 101; LEFT: 21 px; POSITION: absolute; TOP: 17 px" runat="server" Font-Bold="True" Font-Size="Medium"> This is a sample registration form. </asp: Label> 2002 Prentice Hall. All rights reserved.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 Outline <asp: Image id="operating. Image" style="Z-INDEX: 121; LEFT: 21 px; POSITION: absolute; TOP: 371 px" runat="server" Image. Url="imagesos. png"> control to place </asp: Image> Image image on Web page Specify file location <asp: Image id="publication. Image" style="Z-INDEX: 120; LEFT: 21 px; POSITION: absolute; TOP: 245 px" image display runat="server" Image. Url="imagesdownloads. png"> </asp: Image> 29 of <asp: Image id="user. Image" style="Z-INDEX: 119; LEFT: 21 px; POSITION: absolute; TOP: 91 px" runat="server" Image. Url="imagesuser. png"> </asp: Image> <asp: Text. Box id="email. Text. Box" style="Z-INDEX: 118; LEFT: 95 px; POSITION: absolute; TOP: 161 px" runat="server"> </asp: Text. Box> Web. Controls. aspx <asp: Text. Box id="first. Text. Box" style="Z-INDEX: 117; LEFT: 95 px; POSITION: absolute; TOP: 127 px" runat="server"> </asp: Text. Box> <asp: Text. Box id="last. Text. Box" style="Z-INDEX: 116; LEFT: 341 px; POSITION: absolute; TOP: 127 px" runat="server"> </asp: Text. Box> <asp: Text. Box id="phone. Text. Box" style="Z-INDEX: 115; LEFT: 341 px; POSITION: absolute; TOP: 161 px" runat="server"> </asp: Text. Box> 2002 Prentice Hall. All rights reserved.
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 Outline <asp: Radio. Button. List id="operating. Radio. Button. List " style="Z-INDEX: 114; LEFT: 21 px; POSITION: absolute; TOP: 409 px" runat="server"> 30 <asp: List. Item Value="Windows NT">Windows NT </asp: List. Item> <asp: List. Item Value="Windows 2000">Windows 2000 </asp: List. Item> <asp: List. Item Value="Windows XP">Windows XP </asp: List. Item> <asp: List. Item Value="Linux">Linux</asp: List. Item> <asp: List. Item Value="Other">Other</asp: List. Item> Navigate. Url property specifies the resource that is requested </asp: Radio. Button. List> <asp: Hyper. Link id="books. Hyper. Link" style="Z-INDEX: 113; LEFT: 21 px; POSITION: absolute; TOP: 316 px" runat="server" Navigate. Url="http: //www. deitel. com"> Defines the List. Items that display Click here to view more information about our books. the drop-down list is expanded </asp: Hyper. Link> Web. Controls. aspx when <asp: Drop. Down. List id="books. Drop. Down. List" style="Z-INDEX: 112; LEFT: 21 px; POSITION: absolute; TOP: 282 px" runat="server"> <asp: List. Item Value="XML How to Program 1 e"> XML How to Program 1 e </asp: List. Item> <asp: List. Item Value="C# How to Program 1 e"> C# How to Program 1 e 2002 Prentice Hall. All rights reserved.
104 105 106 2 e"> 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 </asp: List. Item> Outline 31 <asp: List. Item Value="Visual Basic. NET How to Program 2 e </asp: List. Item> <asp: List. Item Value="C++ How to Program 3 e"> C++ How to Program 3 e </asp: List. Item> </asp: Drop. Down. List> <asp: Image id="phone. Image" style="Z-INDEX: 111; LEFT: 266 px; POSITION: absolute; TOP: 161 px" runat="server" Image. Url="imagesphone. png"> </asp: Image> <asp: Image id="email. Image" style="Z-INDEX: 110; LEFT: 21 px; POSITION: absolute; TOP: 161 px" runat="server" Image. Url="imagesemail. png"> </asp: Image> Web. Controls. aspx <asp: Image id="last. Image" style="Z-INDEX: 109; LEFT: 266 px; POSITION: absolute; TOP: 127 px" runat="server" Image. Url="imageslname. png"> </asp: Image> <asp: Image id="first. Image" style="Z-INDEX: 108; LEFT: 21 px; POSITION: absolute; TOP: 127 px" runat="server" Image. Url="imagesfname. png"> </asp: Image> 2002 Prentice Hall. All rights reserved.
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 <asp: Button id="register. Button" style="Z-INDEX: 107; LEFT: 21 px; POSITION: absolute; TOP: 547 px" runat="server" Text="Register"> </asp: Button> Outline 32 Button Web control typically maps <asp: Label id="book. Label" style="Z-INDEX: 106; to an input HTML element with LEFT: 216 px; POSITION: absolute; TOP: 245 px" attribute type and value “button” runat="server" Fore. Color="Dark. Cyan"> Which book would you like information about? </asp: Label> <asp: Label id="fill. Label" style="Z-INDEX: 105; LEFT: 218 px; POSITION: absolute; TOP: 91 px" runat="server" Fore. Color="Dark. Cyan"> Please fill out the fields below. </asp: Label> <asp: Label id="phone. Label" style="Z-INDEX: 104; LEFT: 266 px; POSITION: absolute; TOP: 198 px" runat="server"> Must be in the form (555)555 -5555. </asp: Label> Web. Controls. aspx <asp: Label id="operating. Label" style="Z-INDEX: 103; LEFT: 220 px; POSITION: absolute; TOP: 371 px" runat="server" Height="9 px" Fore. Color="Dark. Cyan"> Which operating system are you using? </asp: Label> <asp: Label id="register. Label" style="Z-INDEX: 102; LEFT: 21 px; POSITION: absolute; TOP: 46 px" runat="server" Font-Italic="True"> Please fill in all fields and click Register. </asp: Label> 2002 Prentice Hall. All rights reserved.
172 </form> 173 </body> 174 </HTML> Outline 33 Image control Text. Box control Web. Controls. aspx Drop. Down. List control Hyperlink control Radio. Button. List control Button control 2002 Prentice Hall. All rights reserved.
34 20. 5. 2 Ad. Rotator Control • Address problem of displaying sponsor advertisement • Randomly selects an image to display – Generate hyperlink to Web page 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline <%-- Fig. 20. 18: Ad. Rotator. aspx --%> <%-- A Web Form that demonstrates class Ad. Rotator. --%> <%@ Page language="c#" Codebehind="Ad. Rotator. aspx. cs" Auto. Event. Wireup="false" Inherits="Ad. Rotator. Test. Ad. Rotator" Enable. Session. State="False" enable. View. State="False"%> <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <HEAD> <title>Web. Form 1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio 7. 0" > <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_default. Client. Script" content="Java. Script"> <meta name="vs_target. Schema" content="http: //schemas. microsoft. com/intellisense/ie 5"> </HEAD> <body MS_POSITIONING="Grid. Layout"> background="images/background. png"> <form id="Form 1" method="post" runat="server"> Ad. Rotator. aspx Set Ad. Rotator control’s Advertisement. File property to Adrotator. Information. xml <asp: Ad. Rotator id="ad. Rotator" style="Z-INDEX: 101; LEFT: 17 px; POSITION: absolute; TOP: 69 px" runat="server" Width="86 px" Height="60 px" Advertisement. File="Ad. Rotator. Information. xml"> </asp: Ad. Rotator> <asp: Label id="ad. Rotator. Label" style="Z-INDEX: 102; LEFT: 17 px; POSITION: absolute; TOP: 26 px" runat="server" Font-Size="Large"> Ad. Rotator Example </asp: Label> 2002 Prentice Hall. All rights reserved. 35
36 37 38 39 </form> </body> </HTML> Outline Ad. Rotator. aspx 2002 Prentice Hall. All rights reserved. 36
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 Outline // Fig. 20. 19: Ad. Rotator. aspx. cs // The code-behind file for a page that // demonstrates the Ad. Rotator class. using using using 37 System; System. Collections; System. Component. Model; System. Data; System. Drawing; System. Web. Session. State; System. Web. UI. Web. Controls; System. Web. UI. Html. Controls; namespace Ad. Rotator. Test { /// page that demonstrates Ad. Rotator public class Ad. Rotator : System. Web. UI. Page { protected System. Web. UI. Web. Controls. Ad. Rotator ad. Rotator; protected System. Web. UI. Web. Controls. Label ad. Rotator. Label; Ad. Rotator. aspx. c s // Visual Studio. NET generated code } // end class Ad. Rotator } // end namespace Ad. Rotator. Test No code-behind because Ad. Rotator control does “all the work” 2002 Prentice Hall. All rights reserved.
Outline 38 Alternate. Text Ad. Rotator. aspx. c s program output Ad. Rotator image 2002 Prentice Hall. All rights reserved.
Outline 39 Ad. Rotator. aspx. c s Program Output 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline <? xml version="1. 0" encoding="utf-8"? > 40 <!-- Fig. 20: Ad. Rotator. Information. xml --> <!-- XML file containing advertisement information. --> Ad elements each provide information <Advertisements> about the advertisement <Ad> <Image. Url>images/us. png</Image. Url> <Navigate. Url> http: //www. odci. gov/cia/publications/factbook/geos/us. html </Navigate. Url> <Alternate. Text>United States Information </Alternate. Text> <Impressions>1</Impressions> </Ad> Alternate. Text is a tool tip which displays the <Ad> message when mouse points over image <Image. Url>images/france. png</Image. Url> <Navigate. Url> http: //www. odci. gov/cia/publications/factbook/geos/fr. html </Navigate. Url> <Alternate. Text>France Information</Alternate. Text> <Impressions>1</Impressions> </Ad> Ad. Rotator. Informa tion. xml <Ad> The higher the Impression value the more <Image. Url>images/germany. png</Image. Url> often the advertisement will appear <Navigate. Url> http: //www. odci. gov/cia/publications/factbook/geos/gm. html </Navigate. Url> <Alternate. Text>Germany Information</Alternate. Text> <Impressions>1</Impressions> </Ad> <Image. Url>images/italy. png</Image. Url> Image. Url specifies the location of the advertisement image 2002 Prentice Hall. All rights reserved.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 <Navigate. Url> http: //www. odci. gov/cia/publications/factbook/geos/it. html </Navigate. Url> <Alternate. Text>Italy Information</Alternate. Text> <Impressions>1</Impressions> </Ad> Outline 41 <Ad> <Image. Url>images/spain. png</Image. Url> <Navigate. Url> http: //www. odci. gov/cia/publications/factbook/geos/sp. html </Navigate. Url> <Alternate. Text>Spain Information</Alternate. Text> <Impressions>1</Impressions> </Ad> Navigate. Url indicates URL for the <Ad> web page that loads when a user <Image. Url>images/latvia. png</Image. Url> clicks the advertisement <Navigate. Url> http: //www. odci. gov/cia/publications/factbook/geos/lg. html </Navigate. Url> <Alternate. Text>Latvia Information</Alternate. Text> <Impressions>1</Impressions> </Ad> Ad. Rotator. Informa tion. xml <Ad> <Image. Url>images/peru. png</Image. Url> <Navigate. Url> http: //www. odci. gov/cia/publications/factbook/geos/pe. html </Navigate. Url> <Alternate. Text>Peru Information</Alternate. Text> <Impressions>1</Impressions> </Ad> 2002 Prentice Hall. All rights reserved.
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 <Ad> <Image. Url>images/senegal. png</Image. Url> <Navigate. Url> http: //www. odci. gov/cia/publications/factbook/geos/sg. html </Navigate. Url> <Alternate. Text>Senegal Information</Alternate. Text> <Impressions>1</Impressions> </Ad> <Image. Url>images/sweden. png</Image. Url> <Navigate. Url> http: //www. odci. gov/cia/publications/factbook/geos/sw. html Image. Url specifies the location </Navigate. Url> <Alternate. Text>Sweden Information</Alternate. Text> of the advertisement image <Impressions>1</Impressions> </Ad> <Image. Url>images/thailand. png</Image. Url> <Navigate. Url> http: //www. odci. gov/cia/publications/factbook/geos/th. html </Navigate. Url> <Alternate. Text>Thailand Information</Alternate. Text> <Impressions>1</Impressions> </Ad> Navigate. Url indicates URL for the web page that loads when a user <Ad> <Image. Url>images/unitedstates. png</Image. Url> clicks the advertisement <Navigate. Url> http: //www. odci. gov/cia/publications/factbook/geos/us. html </Navigate. Url> <Alternate. Text>United States Information </Alternate. Text> <Impressions>1</Impressions> </Ad> Outline 42 Ad. Rotator. Informa tion. xml 2002 Prentice Hall. All rights reserved.
105 </Advertisements> Outline 43 Ad. Rotator. Informa tion. xml 2002 Prentice Hall. All rights reserved.
44 20. 5. 3 Validation Controls • Validators – Determine if data in Web controls are proper format 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline <%-- Fig. 20. 21: Generator. aspx --%> <%-- A Web Form demonstrating the use of validators. --%> <%@ Page language="c#" Codebehind="Generator. aspx. cs" Auto. Event. Wireup="false" Inherits="Word. Generator" %> <HTML> and <HEAD> start tags <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <HEAD> <title>Web. Form 1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio 7. 0" > <meta name="CODE_LANGUAGE" Content="C#" > <meta name="vs_default. Client. Script" content="Java. Script"> <meta name="vs_target. Schema" content= "http: //schemas. microsoft. com/intellisense/ie 5"> </HEAD> <body MS_POSITIONING= "Grid. Layout"> <form id="Form 1" method="post" runat="server"> <asp: Label id="prompt. Label" style="Z-INDEX: 101; LEFT: 16 px; POSITION: absolute; TOP: 23 px" runat="server"> Please enter a phone number in the form 555 -4567: Indicate that </asp: Label> phone. Number. Validator verifies <asp: Regular. Expression. Validator Regular expression with input. Text. Box’s contents id="phone. Number. Validator" style="Z-INDEX: which to validate user input 106; LEFT: 217 px; POSITION: absolute; TOP: 73 px" runat="server" Error. Message= "The phone number must be in the form 555 -4567. " Control. To. Validate ="input. Text. Box" Validation. Expression ="^d{3}-d{4}$"> </asp: Regular. Expression. Validator > Generator. aspx Create a Regular. Expression. Validator name phone. Number. Validator Error. Message’s text to display if error occurs 2002 Prentice Hall. All rights reserved. 45
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 <asp: Required. Field. Validator id="phone. Input. Validator" style="Z-INDEX: 105; LEFT: 217 px; POSITION: absolute; TOP: 47 px" runat="server" Error. Message= "Please enter a phone number. " Displays the words generated Control. To. Validate ="input. Text. Box"> from the</asp: Required. Field. Validator> phone number <asp: Text. Box id="output. Text. Box" style="Z-INDEX: 104; LEFT: 16 px; POSITION: absolute; TOP: 146 px" runat="server" Visible="False" Text. Mode="Multi. Line" Height="198 px" Width="227 px" Font-Bold="True" Font-Names="Courier New"> </asp: Text. Box> <asp: Button id= "submit. Button" style="Z-INDEX: 103; LEFT: 16 px; POSITION: absolute; TOP: 86 px" runat="server" Text="Submit"> </asp: Button> Outline Confirm that input. Text. Box’s content is not empty Generator. aspx <asp: Text. Box id="input. Text. Box" style="Z-INDEX: 102; LEFT: 16 px; POSITION: absolute; TOP: 52 px" runat="server"> </asp: Text. Box> </form> </body> </HTML> 2002 Prentice Hall. All rights reserved. 46
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Fig. 20. 22: Generator. aspx. cs // The code-behind file for a page that // generates words from a phone number. using using using Outline 47 System; System. Collections; System. Component. Model; System. Data; System. Drawing; System. Web. Session. State; System. Web. UI. Web. Controls; System. Web. UI. Html. Controls; namespace Word. Generator { // page that computes all combinations of letters for first // three digits and last four digits in phone number public class Generator : System. Web. UI. Page { protected System. Web. UI. Web. Controls. Text. Box output. Text. Box; protected System. Web. UI. Web. Controls. Text. Box input. Text. Box; Generator. aspx. c s protected System. Web. UI. Web. Controls. Regular. Expression. Validator phone. Number. Validator ; protected System. Web. UI. Web. Controls. Required. Field. Validator phone. Input. Validator ; protected System. Web. UI. Web. Controls. Button submit. Button; protected System. Web. UI. Web. Controls. Label prompt. Label; 2002 Prentice Hall. All rights reserved.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 Outline private void Page_Load( object sender, System. Event. Args e ) { // if page loaded due to a postback if ( Is. Post. Back ) { To output. Text. Box. Text = ""; 48 Determine whether the page is being loaded due prepare the to postback Removes hyphen from output. Text. Box for display Request object to the phone number string // retrieve number and remove "-" string number = Request. Form[ "input. Text. Box" ]; retrieve phone. Text. Box’s number = number. Remove( 3, 1 ); value from Form array // generate words for first 3 digits output. Text. Box. Text += "Here are the words forn" ; output. Text. Box. Text += "the first three digits: nn" ; Compute. Words ( number. Substring( 0, 3 ), "" ); output. Text. Box. Text += "n"; Generator. aspx. c s // generate words for last 4 digits output. Text. Box. Text += "Here are the words forn" ; output. Text. Box. Text += Set output. Text. Box’s "the first four digits: nn" ; Visible property to(true Compute. Words number. Substring( 3 ), "" ); output. Text. Box. Visible = true; } // Method Compute. Words is passed end if a substring And a empty string } // end method Page_Load // Visual Studio. NET generated code 2002 Prentice Hall. All rights reserved.
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 Recursive method generate Outline list of words from string of digits 49 private void Compute. Words( string number, string temporary. Word ) { if ( number == "" ) { Contains digits that are Builds up the list that output. Text. Box +=the temporary. Word + "n"; being converted. Text to letters program displays return; } int current = Int 32. Parse( number. Substring( 0, 1 ) ); Recursion base case, occurs when number equals empty number = number. Remove( 0, 1 ); string Switch structure to make switch ( current ) correct recursive call based on { number in current // 0 can be q or z Generator. aspx. c case 0: Compute. Words ( number, temporary. Word + "q" ); s Compute. Words ( number, temporary. Word + "z" ); break; // 1 has no letters associated with it case 1: Compute. Words ( number, temporary. Word + " " ); break; // 2 can be a, b case 2: Compute. Words ( break; or c number, temporary. Word + "a" ); number, temporary. Word + "b" ); number, temporary. Word + "c" ); 2002 Prentice Hall. All rights reserved.
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 // 3 can be d, e case 3: Compute. Words ( break; or f // 4 can be g, h case 4: Compute. Words ( break; or i // 5 can be j, k case 5: Compute. Words ( break; or l // 6 can be m, n case 6: Compute. Words ( break; or o // 7 can be p, r case 7: Compute. Words ( break; or s Outline 50 number, temporary. Word + "d" ); number, temporary. Word + "e" ); number, temporary. Word + "f" ); temporary. Word concatenated with new letter number, temporary. Word + "g" ); number, temporary. Word + "h" ); number, temporary. Word + "i" ); Make recursive call for each possible option Contains one less digit as a result of the call to method Remove number, temporary. Word + "j" ); number, temporary. Word + "k" ); number, temporary. Word + "l" ); Generator. aspx. c s number, temporary. Word + "m" ); number, temporary. Word + "n" ); number, temporary. Word + "o" ); number, temporary. Word + "p" ); number, temporary. Word + "r" ); number, temporary. Word + "s" ); 2002 Prentice Hall. All rights reserved.
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 // 8 can be t, u case 8: Compute. Words ( break; or v // 9 can be w, x case 9: Compute. Words ( break; or y Outline 51 number, temporary. Word + "t" ); number, temporary. Word + "u" ); number, temporary. Word + "v" ); number, temporary. Word + "w" ); number, temporary. Word + "x" ); number, temporary. Word + "y" ); } // end switch } // end method Compute. Words } // end class Generator. aspx. c s } // end namespace Word. Generator 2002 Prentice Hall. All rights reserved.
Outline 52 Generator. aspx. c s Program Output 2002 Prentice Hall. All rights reserved.
Outline 53 Generator. aspx. c s Program Output 2002 Prentice Hall. All rights reserved.
Outline 54 Generator. aspx. c s Program Output 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <!-- Fig. 20. 23: Generator. html --> <!-- The HTML page that is sent to the client browser. --> Outline <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <HEAD> <title>Web. Form 1</title> <meta name="GENERATOR" content="Microsoft Visual Studio 7. 0" > <meta name="CODE_LANGUAGE" content="C#" > <meta name="vs_default. Client. Script" content="Java. Script"> <meta name="vs_target. Schema" content="http: //schemas. microsoft. com/intellisense/ie 5"> </HEAD> <body MS_POSITIONING= "Grid. Layout"> <form name="Form 1" method="post" action="Generator. aspx" language="javascript" ECMAScript provides implementation onsubmit="Validator. On. Submit(); " id="FORM 1"> <input type="hidden" name="__VIEWSTATE" for validation controls value="d. Dwx. Mjgy. Mz. M 3 ozs+" /> Generator. html <script language= "javascript" src= "/aspnet_client/system_web/1_0_3215_11/ Web. UIValidation. js"> </script> 2002 Prentice Hall. All rights reserved. 55
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 <span id="phone. Number. Validator" controltovalidate ="input. Text. Box" errormessage = "The phone number must be in the form 555 -4567. " evaluationfunction = "Regular. Expression. Validator. Evaluate. Is. Valid " validationexpression ="^d{3}-d{4}$" style="color: Red; Z-INDEX: 106; LEFT: 217 px; POSITION: absolute; TOP: 73 px; visibility: hidden; " > The phone number must be in the form 555 -4567. </span> Outline <input name="input. Text. Box" type="text" id="input. Text. Box" style="Z-INDEX: 102; LEFT: 16 px; POSITION: absolute; TOP: 52 px" /> <input type="submit" name="submit. Button" value="Submit" onclick= "if ( " + "typeof(Page_Client. Validate) == 'function') " + "Page_Client. Validate(); " language="javascript" id="submit. Button" style="Z-INDEX: 103; LEFT: 16 px; POSITION: absolute; TOP: 86 px" /> <span id="phone. Input. Validator" controltovalidate ="input. Text. Box" errormessage ="Please enter a phone number. " evaluationfunction = "Required. Field. Validator. Evaluate. Is. Valid " initialvalue ="" style="color: Red; Z-INDEX: 105; LEFT: 217 px; POSITION: absolute; TOP: 47 px; visibility: hidden; ">Please enter a phone number. Generator. html 2002 Prentice Hall. All rights reserved. 56
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 </span> Outline <span id="prompt. Label" style="Z-INDEX: 101; LEFT: 16 px; POSITION: absolute; TOP: 23 px" > Please enter a phone number in the form 555 -4567: </span> <script language= "javascript"> <!-var Page_Validators = new Array( document. all[ "phone. Number. Validator"], ECMAScript provides implementation document. all[ "phone. Input. Validator"] ); // --> for validation controls </script> <script language= "javascript"> <!-var Page_Validation. Active = false; Generator. html if ( typeof(client. Information) != "undefined" && client. Information. app. Name. index. Of("Explorer") != -1 ) { if ( typeof(Page_Validation. Ver) == "undefined" ) alert( "Unable to find script library " + "'/aspnet_client/system_web/'"+ "'1_0_3215_11/Web. UIValidation. js'. " + "Try placing this file manually, or " + "reinstall by running 'aspnet_regiis -c'. "); 2002 Prentice Hall. All rights reserved. 57
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 else if ( Page_Validation. Ver != "125" ) alert( "This page uses an incorrect version " + "of Web. UIValidation. js. The page " + "expects version 125. " + "The script library is " + Page_ Validation. Ver + ". "); else Validator. On. Load (); Outline } function Validator. On. Submit() { if (Page_Validation. Active) { Validator. Common. On. Submit (); } } // --> </script> </form> </body> </HTML> Generator. html 2002 Prentice Hall. All rights reserved. 58
59 20. 6 Session Tracking • Personalization – Tailored to client’s needs – Customer loyalty – Session ID • Privacy protection – Release of vital possibly private data 2002 Prentice Hall. All rights reserved.
60 20. 6. 1 Cookies • Cookies – Text file stored by a Web site on a individual’s computer that allows the site to track the actions of the visitor • Records sites that the user visits and identifies shopping preferences • Cookies can store name-value pairs • Web Server can never access cookies created outside the domain associated with that server 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 <%-- Fig. 20. 24: Options. Page. aspx --%> <%-- This ASPX page allows the user to choose a language. --%> Outline 61 <%@ Page language="c#" Codebehind="Options. Page. aspx. cs" Auto. Event. Wireup="false" Inherits="Cookies. Options. Page" %> <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <HEAD> <title>Recommendations. Page</title> <meta name="GENERATOR" Content= "Microsoft Visual Studio 7. 0" > <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_default. Client. Script" content= "Java. Script"> <meta name="vs_target. Schema" content= "http: //schemas. microsoft. com/intellisense/ie 5"> </HEAD> Options. Page. aspx <body> <form id="Recommendations. Page" method="post" runat="server"> Label Web control <P> <asp: Label id= "prompt. Label" runat="server" Font-Bold= "True">Select a programming language: </asp: Label> <asp: Label id= "welcome. Label" runat="server" Font-Bold= "True" Visible="False"> Welcome to Cookies! You selected </asp: Label> </P> 2002 Prentice Hall. All rights reserved.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 <P> <asp: Radio. Button. List id="language. List" runat= "server"> <asp: List. Item Value="C#">C#</asp: List. Item> Outline 62 <asp: List. Item Value="C++">C++</asp: List. Item> <asp: List. Item Value="C">C</asp: List. Item> Defines five radio buttons <asp: List. Item Value="Python">Python </asp: List. Item> <asp: List. Item Value="Visual Basic. NET"> Visual Basic. NET </asp: List. Item> </asp: Radio. Button. List> </P> Options. Page. aspx <P> <asp: Button id= "submit. Button" runat="server" Text= "Submit"> </asp: Button> </P> Request current page, does not cause a postback <P> <asp: Hyper. Link id="language. Link" runat="server" Navigate. Url ="Options. Page. aspx" Visible="False"> Click here to choose another language. </asp: Hyper. Link> </P> <asp: Hyper. Link id="recommendations. Link" runat= "server" Navigate. Url="Recommendations. Page. aspx" 2002 Prentice Hall. All rights reserved.
70 Visible="False">Click here to get book recommendations. 71 </asp: Hyper. Link> 72 </P> 73 </form> 74 </body> 75 </HTML> Outline 63 Options. Page. aspx 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Fig. 20. 25: Option. Page. aspx. cs // A listing of program languages that the user can choose from. using using using Outline 64 System; System. Collections; System. Component. Model; System. Data; System. Drawing; System. Web. Session. State; System. Web. UI. Web. Controls; System. Web. UI. Html. Controls; namespace Cookies { // page contains language options in a Radio. Button. List, // will add a cookie to store their choice public class Options. Page : System. Web. UI. Page { protected System. Web. UI. Web. Controls. Label prompt. Label; protected System. Web. UI. Web. Controls. Label welcome. Label; Options. Page. aspx. cs protected System. Web. UI. Web. Controls. Radio. Button. List language. List; protected System. Web. UI. Web. Controls. Hyper. Link language. Link; protected System. Web. UI. Web. Controls. Hyper. Link recommendations. Link ; protected System. Web. UI. Web. Controls. Button submit. Button; protected Hashtable books = new Hashtable(); Define books as a Hashtable, stores key-value 2002 Prentice Hall. All rights reserved.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 // event handler for Load event private void Page_Load( object sender, System. Event. Args e ) { if ( Is. Post. Back ) { // if postback has occurred, user has submitted // information, so display welcome message // and appropriate hyperlinks welcome. Label. Visible = true; Two hyperlinks language. Link. Visible = true; recommendations. Link. Visible = true; made visible // hide option information submit. Button. Visible = false; prompt. Label. Visible = false; language. List. Visible = false; Outline 65 are Options. Page. aspx. cs Determines whether the // notify user of what they have chosen if ( language. List. Selected. Item != null ) user welcome. Label. Text += language. List. Selected. Item. To. String() + ". "; else welcome. Label. Text += "no language. "; selected a language } // end if } // end method Page_Load 2002 Prentice Hall. All rights reserved.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 Outline override protected void On. Init( Event. Args e ) { // add values to Hashtable books. Add( "C#", "0 -13 -062221 -4" ); books. Add( "C++", "0 -13 -089571 -7" ); books. Add( "C", "0 -13 -089572 -5" ); books. Add( "Python", "0 -13 -092361 -3" ); books. Add( "Visual Basic. NET", "0 -13 -456955 -5" ); 66 Initialize. Component (); base. On. Init( e ); } // Visual Studio. NET generated code // when user clicks Submit button // create cookie to store user's choice private void submit. Button_Click( object sender, System. Event. Args e ) { // if choice was made by user if ( language. List. Selected. Item != null ) { string language = language. List. Selected. Item. To. String(); Options. Page. aspx. cs string ISBN = books[ language ]. To. String(); Returns value corresponding to key contained in language // create cookie, name-value pair is // language chosen and ISBN number from Hashtable New cookie object Http. Cookie cookie = new Http. Cookie( created to store language, ISBN ); and ISBN number 2002 Prentice Hall. All rights reserved.
99 100 101 102 103 104 105 106 107 108 109 Outline // add cookie to response, // thus placing it on user's machine Response. Cookies. Add( cookie ); } // end if } // end method submit. Button_Click 67 Cookie is added to the cookie collection sent as part of HTTP response header } // end class Options. Page } // end namespace Cookies Options. Page. aspx. cs 2002 Prentice Hall. All rights reserved.
Outline 68 Options. Page. aspx. cs Program Output 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 <%-- Fig. 20. 26: Recommendations. Page. aspx --%> <%-- This page shows recommendations --%> <%-- retrieved from the Hashtable. --%> Outline 69 <%@ Page language="c#" Codebehind="Recommendations. Page. aspx. cs" Auto. Event. Wireup="false" Inherits="Cookies. Recommendations. Page" %> <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <HEAD> <title>Web. Form 1</title> <meta name="GENERATOR" Content= "Microsoft Visual Studio 7. 0" > <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_default. Client. Script" content="Java. Script"> <meta name="vs_target. Schema" content= "http: //schemas. microsoft. com/intellisense/ie 5"> </HEAD> Recommendations. P age. aspx <body MS_POSITIONING= "Grid. Layout"> Label displays text recommendations <form id="Form 1" method="post" runat="server"> <asp: Label id="recommendations. Label" style="Z-INDEX: 101; LEFT: the 21 px; POSITION: absolute; Displays recommendations created TOP: 25 px" runat="server" Font-Bold="True" by the code-behind file Font-Size="X-Large">Recommendations </asp: Label> <asp: List. Box id="books. List. Box" style="Z-INDEX: 102; LEFT: 21 px; POSITION: absolute; TOP: 82 px" runat= "server" Width="383 px" Height="91 px"> </asp: List. Box> 2002 Prentice Hall. All rights reserved.
36 37 38 </form> </body> </HTML> Outline 70 Recommendations. P age. aspx 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 Outline // Fig 20. 27: Recommendations. Page. aspx. cs // Reading cookie data from the client. using using using 71 System; System. Collections; System. Component. Model; System. Data; System. Drawing; System. Web. Session. State; System. Web. UI. Web. Controls; System. Web. UI. Html. Controls; namespace Cookies { // page displays cookie information and recommendations public class Recommendations. Page : System. Web. UI. Page { protected System. Web. UI. Web. Controls. List. Box books. List. Box; protected System. Web. UI. Web. Controls. Label recommendations. Label ; Recommendations. P age. aspx. cs // Visual Studio. NET generated code override protected void On. Init( Event. Args e ) { Initialize. Component (); base. On. Init( e ); Method to retrieve cookies from the client // retrieve client's cookies Http. Cookie. Collection cookies = Request. Cookies; 2002 Prentice Hall. All rights reserved.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 Outline 72 // if there are cookies other than the ID cookie, // list appropriate books and ISBN numbers Ensure that there is at least if ( cookies != null && cookies. Count != 1 ) Determine whether at one cookie besides for ( int i = 1; i < cookies. Count; i++ ) least two cookies exist ASP. NET_Session. ID books. List. Box. Items. Add( Add information in other cookies[ i ]. Name + " How to Program. ISBN#: " + cookies into list box cookies[ i ]. Value ); // if ifno nolanguage cookies Execute // chosen, so no was selected besides ID, no options were recommendations made else { recommendations. Label. Text = "No Recommendations. "; books. List. Box. Items. Clear(); books. List. Box. Visible = false; } } // end method On. Init Recommendations. P age. aspx. cs } // end class Recommendations. Page } // end namespace Cookies 2002 Prentice Hall. All rights reserved.
Outline 73 Recommendations. P age. aspx. cs Program Output 2002 Prentice Hall. All rights reserved.
74 20. 6. 1 Cookies 2002 Prentice Hall. All rights reserved.
20. 6. 2 Session Tracking with Http. Session. State • Http. Session. State – Http. Session. State objects can store any type of objects (not just Strings) as attribute values 2002 Prentice Hall. All rights reserved. 75
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 <%-- Fig. 20. 29: Options. Page. aspx --%> <%-- Page that presents a list of language options. --%> Outline 76 <%@ Page language="c#" Codebehind="Options. Page. aspx. cs" Auto. Event. Wireup="false" Inherits= "Sessions. Options. Page" %> <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <HEAD> <title>Recommendations. Page</title> <meta name="GENERATOR" Content= "Microsoft Visual Studio 7. 0" > <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_default. Client. Script" content="Java. Script"> <meta name="vs_target. Schema" content= "http: //schemas. microsoft. com/intellisense/ie 5"> </HEAD> Options. Page. aspx <body> <form id="Recommendations. Page" method="post" runat="server"> <P> <asp: Label id= "prompt. Label" runat="server" Font-Bold=" True">Select a programming language: </asp: Label> <asp: Label id= "welcome. Label" runat="server" Font-Bold= "True" Visible="False"> Welcome to Cookies! You selected </asp: Label> </P> <P> 2002 Prentice Hall. All rights reserved.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 <asp: Radio. Button. List id="language. List" runat= "server"> Outline 77 <asp: List. Item Value="C#">C#</asp: List. Item> <asp: List. Item Value="C++">C++</asp: List. Item> <asp: List. Item Value="C">C</asp: List. Item> <asp: List. Item Value="Python">Python </asp: List. Item> <asp: List. Item Value="Visual Basic. NET"> Visual Basic. NET </asp: List. Item> </asp: Radio. Button. List> </P> <P> Options. Page. aspx <asp: Button id= "submit. Button" runat="server" Text="Submit"> </asp: Button> </P> <asp: Label id= "id. Label" runat="server"> </asp: Label> </P> <asp: Label id= "timeout. Label" runat="server"> </asp: Label> </P> <P> 2002 Prentice Hall. All rights reserved.
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 <asp: Label id= "new. Session. Label" runat="server"> </asp: Label> </P> Outline 78 <P> <asp: Hyper. Link id="language. Link" runat="server" Navigate. Url ="Options. Page. aspx" Visible="False"> Click here to choose another language. </asp: Hyper. Link> </P> <asp: Hyper. Link id="recommendations. Link" runat= "server" Navigate. Url="Recommendations. Page. aspx" Visible="False"> Click here to get book recommendations. </asp: Hyper. Link> </P> </form> </body> </HTML> Options. Page. aspx 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Fig. 20. 30: Options. Page. aspx. cs // A listing of programming languages, // choice is stored in page’s Session object. using using using Outline 79 System; System. Collections; System. Component. Model; System. Data; System. Drawing; System. Web. Session. State; System. Web. UI. Web. Controls; System. Web. UI. Html. Controls; namespace Sessions { // page contains language options in a Radio. Button. List // will add cookie to store user’s choice public class Options. Page : System. Web. UI. Page { protected System. Web. UI. Web. Controls. Label prompt. Label; protected System. Web. UI. Web. Controls. Label welcome. Label; protected System. Web. UI. Web. Controls. Label id. Label; protected System. Web. UI. Web. Controls. Label timeout. Label; Options. Page. aspx. cs protected System. Web. UI. Web. Controls. Hyper. Link language. Link; protected System. Web. UI. Web. Controls. Hyper. Link recommendations. Link ; protected System. Web. UI. Web. Controls. Radio. Button. List language. List; protected System. Web. UI. Web. Controls. Button submit. Button; 2002 Prentice Hall. All rights reserved.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 private Hashtable books = new Hashtable(); Outline 80 // event handler for Load event private void Page_Load( object sender, System. Event. Args e ) { // if page is loaded due to postback, load session // information, hide language options from user if ( Is. Post. Back ) { // display components that contain session information welcome. Label. Visible = true; language. Link. Visible = true; recommendations. Link. Visible = true; // hide components submit. Button. Visible = false; prompt. Label. Visible = false; language. List. Visible = false; Options. Page. aspx. cs // set labels to display Session information if ( language. List. Selected. Item != null ) welcome. Label. Text += Specify maximum amount of time language. List. Selected. Item. To. String() + ". "; Session. ID contains that an Http. Session. State object else session’s welcome. Label unique ID. Text += "no language. "; can be inactive before discarded id. Label. Text += "Your unique session ID is: " + Session. ID; timeout. Label. Text += "Timeout: " + Session. Timeout + " minutes"; } // end if 2002 Prentice Hall. All rights reserved.
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 Outline } // end method Page_Load 81 override protected void On. Init( Event. Args e ) { // add values to Hashtable books. Add( "C#", "0 -13 -062221 -4" ); books. Add( "C++", "0 -13 -089571 -7" ); books. Add( "C", "0 -13 -089572 -5" ); books. Add( "Python", "0 -13 -092361 -3" ); books. Add( "Visual Basic. NET", "0 -13 -456955 -5" ); Initialize. Component (); base. On. Init( e ); } // Visual Studio. NET generated code // when user clicks Submit button, // store user's choice in session object private void submit. Button_Click( object sender, System. Event. Args e ) { if ( language. List. Selected. Item != null ) { string language = language. List. Selected. Item. To. String(); string ISBN = books[ language ]. To. String(); Options. Page. aspx. cs // store in session object as name-value pair // name is language chosen, value is Method Add to place language and its // ISBN number for corresponding book corresponding recommended book’s Session. Add( language, ISBN ); } // end if ISBN into Http. Session. State object 2002 Prentice Hall. All rights reserved.
105 106 107 108 109 110 } // end method submit. Button_Click Outline 82 } // end class Options. Page } // end namespace Sessions Options. Page. aspx. cs 2002 Prentice Hall. All rights reserved.
Outline 83 Options. Page. aspx. cs Program Output 2002 Prentice Hall. All rights reserved.
20. 6. 2 Session Tracking with Http. Session. State 2002 Prentice Hall. All rights reserved. 84
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <%-- Fig. 20. 32: Recommendations. Page. aspx --%> <%-- Read the user's session data. --%> Outline 85 <%@ Page language="c#" Codebehind="Recommendations. Page. aspx. cs" Auto. Event. Wireup="false" Inherits="Sessions. Recommendations. Page" %> <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <HEAD> <title>Web. Form 1</title> <meta name="GENERATOR" Content= "Microsoft Visual Studio 7. 0" > <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_default. Client. Script" content= "Java. Script"> <meta name="vs_target. Schema" content= "http: //schemas. microsoft. com/intellisense/ie 5"> </HEAD> <body MS_POSITIONING= "Grid. Layout"> <form id="Form 1" method="post" runat="server"> <asp: Label id="recommendations. Label" style="Z-INDEX: 101; LEFT: 21 px; POSITION: absolute; TOP: 25 px" runat="server" Font-Bold="True" Font-Size="X-Large">Recommendations </asp: Label> Recommendations. P age. aspx List. Box Web control that is used to present recommendations to user <asp: List. Box id="books. List. Box" style="Z-INDEX: 102; LEFT: 21 px; POSITION: absolute; TOP: 84 px" runat= "server" Width="383 px" Height="91 px"> </asp: List. Box> 2002 Prentice Hall. All rights reserved.
34 35 36 </form> </body> </HTML> Outline 86 Recommendations. P age. aspx 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 Outline // Fig. 20. 33: Recommendations. Page. aspx. cs // Reading session data from the user. using using using 87 System; System. Collections; System. Component. Model; System. Data; System. Drawing; System. Web. Session. State; System. Web. UI. Web. Controls; System. Web. UI. Html. Controls; namespace Sessions { // page displaying session information and recommendations public class Recommendations. Page : System. Web. UI. Page { protected System. Web. UI. Web. Controls. List. Box books. List. Box; Recommendations. P age. aspx. cs protected System. Web. UI. Web. Controls. Label recommendations. Label ; // Visual Studio. NET generated code // event handler for Init event override protected void On. Init( Event. Args e ) { Initialize. Component (); base. On. Init( e ); Event handler On. Init retrieves session information 2002 Prentice Hall. All rights reserved.
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 Outline // determine if Session contains information if ( Session. Count != 0 ) { // iterate through Session values, // display in List. Box for ( int i = 0; i < Session. Count; i++ ) { // store current key in session. Name string key. Name = Session. Keys[ i ]; // use current key to display // Session's name/value pairs books. List. Box. Items. Add( key. Name + " How to Program. ISBN#: " + Session[ key. Name ] ); } // end for 88 Iterates through the Indexing the Session object with key name If no language was Recommendations. P ever selected age. aspx. cs } else { recommendations. Label. Text = "No Recommendations"; books. List. Box. Visible = false; } } // end method On. Init } // end class Recommendations. Page } // end namespace Sessions 2002 Prentice Hall. All rights reserved.
Outline 89 Recommendations. P age. aspx. cs Program Output 2002 Prentice Hall. All rights reserved.
90 20. 7 Case Study: Online Guest Book • Guest Book – Data submitted on the guest-book form often are stored in a database located on the Web server’s machine 2002 Prentice Hall. All rights reserved.
91 20. 7 Case Study: Online Guest Book Fig. 20. 34 Guest book application GUI. 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 <%-- Fig. 20. 35: Welcome. aspx --%> <%-- A Web Form demonstrating a guest book. --%> Outline <%@ Page language="c#" Codebehind="Welcome. aspx. cs" Auto. Event. Wireup="false" Inherits="Guestbook. Guest. Book. Test" %> <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <HEAD> Figure presents <title>Web. Form 1</title> <meta name="GENERATOR" Content= "Microsoft Visual Studio 7. 0" > <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_default. Client. Script" content="Java. Script"> <meta name="vs_target. Schema" content= "http: //schemas. microsoft. com/intellisense/ie 5"> data. Gid displays all </HEAD> guest-book entries the ASPX file Welcome. aspx <body MS_POSITIONING= "Grid. Layout"> <form id="Form 1" method="post" runat="server"> <asp: Data. Grid id="data. Grid" style="Z-INDEX: 101; LEFT: 13 px; POSITION: absolute; TOP: 301 px" runat= "server" Width="698 px" Horizontal. Align="Left" Border. Color="#E 7 E 7 FF" Border. Width="1 px" Grid. Lines="Horizontal" Back. Color="White" Data. Source="<%# data. View %>" Border. Style="None" Cell. Padding="3"> <Selected. Item. Style Font-Bold="True" Fore. Color= "#F 7 F 7 F 7" Back. Color="#738 A 9 C"> </Selected. Item. Style> <Alternating. Item. Style Back. Color ="#F 7 F 7 F 7"> 2002 Prentice Hall. All rights reserved. 92
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 </Alternating. Item. Style> Outline <Item. Style Horizontal. Align ="Left" Fore. Color= "#4 A 3 C 8 C" Back. Color="#E 7 E 7 FF"> </Item. Style> <Header. Style Font-Bold="True" Fore. Color="#F 7 F 7 F 7" Back. Color ="#4 A 3 C 8 C"> </Header. Style> <Footer. Style Fore. Color="#4 A 3 C 8 C" Back. Color= "#B 5 C 7 DE"> </Footer. Style> <Pager. Style Horizontal. Align ="Right" Fore. Color= "#4 A 3 C 8 C" Back. Color="#E 7 E 7 FF" Mode= "Numeric. Pages"> </Pager. Style> </asp: Data. Grid> Welcome. aspx <asp: Button id= "clear. Button" style="Z-INDEX: 111; LEFT: 354 px; POSITION: absolute; TOP: 262 px" runat="server" Width="57 px" Text="Clear"> </asp: Button> <asp: Button id= "submit. Button" style="Z-INDEX: 110; LEFT: 205 px; POSITION: absolute; TOP: 264 px" runat="server" Text="Submit"> </asp: Button> <asp: Text. Box id="message. Text. Box" style="Z-INDEX: 109; LEFT: 111 px; POSITION: absolute; TOP: 139 px" runat="server" Width="427 px" Height="107 px" Text. Mode="Multi. Line"> </asp: Text. Box> 2002 Prentice Hall. All rights reserved. 93
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 <asp: Label id="message. Label" style="Z-INDEX: 108; LEFT: 13 px; POSITION: absolute; TOP: 149 px" runat="server" Width="59 px" Height="9 px"> Tell the world: </asp: Label> Outline <asp: Label id="email. Label" style="Z-INDEX: 107; LEFT: 13 px; POSITION: absolute; TOP: 91 px" runat="server" Width="76 px">E-mail address: </asp: Label> <asp: Text. Box id="email. Text. Box" style="Z-INDEX: 106; LEFT: 111 px; POSITION: absolute; TOP: 99 px" runat="server" Width="428 px"> </asp: Text. Box> <asp: Label id="name. Label" style="Z-INDEX: 104; LEFT: 13 px; POSITION: absolute; TOP: 59 px" runat="server" Width="84 px">First Name: </asp: Label> Welcome. aspx <asp: Text. Box id="name. Text. Box" style="Z-INDEX: 105; LEFT: 111 px; POSITION: absolute; TOP: 59 px" runat="server" Width="428 px"> </asp: Text. Box> <asp: Label id="prompt. Label" style="Z-INDEX: 102; LEFT: 13 px; POSITION: absolute; TOP: 12 px" runat="server" Fore. Color="Blue" Font-Size="X-Large"> Please leave a message in our guest book: </asp: Label> </form> </body> </HTML> 2002 Prentice Hall. All rights reserved. 94
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Fig. 20. 36: Welcome. aspx. cs // The code-behind file for the guest book page. using using using Outline 95 System; System. Collections; System. Component. Model; System. Data; System. Drawing; System. Web. Session. State; System. Web. UI. Web. Controls; System. Web. UI. Html. Controls; System. IO; namespace Guestbook { // allows user to leave messages public class Guest. Book. Form : System. Web. UI. Page { protected System. Web. UI. Web. Controls. Label prompt. Label; protected System. Web. UI. Web. Controls. Label name. Label; protected System. Web. UI. Web. Controls. Label email. Label; protected System. Web. UI. Web. Controls. Label message. Label; Welcome. aspx. cs protected System. Web. UI. Web. Controls. Data. Grid data. Grid; protected System. Web. UI. Web. Controls. Button submit. Button; protected System. Web. UI. Web. Controls. Button clear. Button; protected System. Web. UI. Web. Controls. Text. Box name. Text. Box; protected System. Web. UI. Web. Controls. Text. Box email. Text. Box; protected System. Web. UI. Web. Controls. Text. Box message. Text. Box; 2002 Prentice Hall. All rights reserved.
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 Outline protected System. Data. View data. View; 96 // handle Page's Load event private void Page_Load( object sender, System. Event. Args e ) { data. View = new Data. View( new Data. Table() ); } // end method Page_Load // Visual Studio. NET generated code // places all the messages in the guest book into a // table; messages are separated by horizontal rules public void Fill. Message. Table() Method to place guest book { Create Data. Table object from entries in Data. Table table = data. View. Table; Data. View’s Table property table. Columns. Add( "Date" ); Welcome. aspx. cs Form necessary columns using table. Columns. Add( "First Name" ); table. Columns. Add( "e-mail" ); Columns collection’s Add method table. Columns. Add( "Message" ); // open guest book file for reading Stream. Reader reader = new Stream. Reader( Request. Physical. Application. Path + "guestbook. txt" ); char[] separator = { 't' }; // read in line from file string message = reader. Read. Line(); Begin to read each line in text file 2002 Prentice Hall. All rights reserved.
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 Outline while ( message != null ) { //added splittothe string into its four parts table through string[] parts = message. Split( separator ); Load. Data. Row 97 // load data into table. Load. Data. Row( parts, true ); Break each line read from file into four tokens Indicate that changes will be accepted // read in one line from file message = reader. Read. Line(); } // update grid data. Grid. Data. Source = table; data. Grid. Data. Bind(); reader. Close(); Method to refresh Data. View Welcome. aspx. cs } // end method Fill. Message. Table Create thatto guest book // Stream. Writer add user’s entry private submit. Button_Click( references filevoid containing object sender, System. Event. Args Concatenate guestbook entries project { folder with file name // open stream for appending to e ) file Event handler to add user’s information to Retrieve path of guestbook. txt application’s root directory Stream. Writer guestbook = new Stream. Writer( Request. Physical. Application. Path + "guestbook. txt", true ); Append appropriate message to guestbook file True specify that new information will be appended to file // write new message to file guestbook. Write. Line( Date. Time. Now. Date. To. String(). Substring( 0, 10 ) + "t" + name. Text. Box. Text + "t" + email. Text. Box. Text + "t" + message. Text. Box. Text ); 2002 Prentice Hall. All rights reserved.
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 Outline // clear textboxes and close stream name. Text. Box. Text = ""; email. Text. Box. Text = ""; message. Text. Box. Text = ""; guestbook. Close(); 98 Fill. Message. Table (); } // end method submit. Button_Click // clear all text boxes private void clear. Button_Click( object sender, System. Event. Args e ) { name. Text. Box. Text = ""; Clears all the Text. Boxes by email. Text. Box. Text = ""; setting properties to empty string message. Text. Box. Text = ""; } // end method clear. Button_Click Welcome. aspx. cs } // end class Guest. Book. Form } // end namespace Guestbook 2002 Prentice Hall. All rights reserved.
Outline 99 Welcome. aspx. cs Program Output 2002 Prentice Hall. All rights reserved.
Outline 100 Welcome. aspx. cs Program Output 2002 Prentice Hall. All rights reserved.
20. 8 Case Study: Connecting to a Database in ASP. NET • Web-based application to view list of publications by specified author 2002 Prentice Hall. All rights reserved. 101
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 <%-- Fig. 20. 37: Login. aspx --%> <%-A page that allows the user to log in. --%> Add Web user control Outline to ASPX file <%@ Page language="c#" Codebehind="login. aspx. cs" Auto. Event. Wireup="false" Inherits="Database. Login" %> <%@ Register Tag. Prefix="Header" Tag. Name="Image. Header" Src="Image. Header. ascx" %> User. HTML control’s tag name and <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD 4. 0 Transitional//EN" > <HTML> tag prefix <HEAD> <title>Web. Form 1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio 7. 0" > <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_default. Client. Script" content="Java. Script"> <meta name="vs_target. Schema" content="http: //schemas. microsoft. com/intellisense/ie 5"> </HEAD> <body MS_POSITIONING= "Grid. Layout" bg. Color="#ffebff"> <form id="Form 1" method="post" runat="server"> <asp: label id="name. Label" style="Z-INDEX: 101; LEFT: 15 px; POSITION: absolute; TOP: 188 px" runat="server">Name </asp: label> Login. aspx <asp: label id="prompt. Label" style="Z-INDEX: 108; LEFT: 15 px; POSITION: absolute; TOP: 145 px" runat="server">Please select your name and enter your password to log in: </asp: label> <asp: customvalidator id="invalid. Password. Validator " style="Z-INDEX: 107; LEFT: 262 px; POSITION: absolute; TOP: 221 px" runat="server" Control. To. Validate ="password. Text. Box" Font-Bold="True" 2002 Prentice Hall. All rights reserved. 102
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 Fore. Color="Dark. Cyan" Error. Message="Invalid password!"> </asp: customvalidator> Outline <asp: requiredfieldvalidator id="required. Password. Validator " style="Z-INDEX: 106; LEFT: 262 px; POSITION: absolute; TOP: 221 px" runat="server" Control. To. Validate ="password. Text. Box" Font-Bold="True" Fore. Color="Dark. Cyan" Error. Message ="Please enter a password!" > </asp: requiredfieldvalidator> <asp: dropdownlist id="name. List" style="Z-INDEX: 105; LEFT: 92 px; POSITION: absolute; TOP: 185 px" runat="server" Width="154 px"> </asp: dropdownlist> <asp: button id= "submit. Button" style="Z-INDEX: 104; LEFT: 92 px; POSITION: absolute; TOP: 263 px" runat="server" Text="Submit"> </asp: button> Login. aspx <asp: textbox id= "password. Text. Box" style="Z-INDEX: 103; LEFT: 92 px; POSITION: absolute; TOP: 221 px" runat="server" Text. Mode="Password"> </asp: textbox> <asp: label id="password. Label" style="Z-INDEX: 102; LEFT: 15 px; POSITION: absolute; TOP: 220 px" runat="server">Password </asp: label> Image. Header element is added to the file <Header: Image. Header id="Image. Header 1" runat="server"> 2002 Prentice Hall. All rights reserved. 103
68 69 70 71 </Header: Image. Header> </form> </body> </HTML> Outline Login. aspx 2002 Prentice Hall. All rights reserved. 104
1 2 3 4 5 6 7 8 9 10 <%-- Fig. 20. 38: Image. Header. ascx --%> <%-- Listing for the header user control. --%> Outline 105 <%@ Control Language="c#" Auto. Event. Wireup="false" Codebehind="Image. Header. ascx. cs" Inherits="Database. Image. Header" Target. Schema="http: //schemas. microsoft. com/intellisense/ie 5" %> <asp: Image id="Image 1" runat="server" Image. Url="bug 2 bug. png"> </asp: Image> Image. Header. ascx 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // Fig. 20. 39: Login. aspx. cs // The code-behind file for the page that logs the user in. using using using Outline System; System. Collections; System. Component. Model; System. Data; System. Drawing; System. Web. Session. State; System. Web. UI. Web. Controls; System. Web. UI. Html. Controls; System. Web. Security; namespace Database { // allows users to log in public class Login : System. Web. UI. Page { protected System. Data. Ole. Db. Data. Adapter ole. Db. Data. Adapter 1; protected System. Data. Ole. Db. Command ole. Db. Select. Command 1; protected System. Data. Ole. Db. Command ole. Db. Insert. Command 1; protected System. Data. Ole. Db. Command ole. Db. Update. Command 1; protected System. Data. Ole. Db. Command ole. Db. Delete. Command 1; protected System. Data. Ole. Db. Connection ole. Db. Connection 1; Login. aspx. cs 2002 Prentice Hall. All rights reserved. 106
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 Outline protected System. Web. UI. Web. Controls. Label password. Label; protected System. Web. UI. Web. Controls. Label name. Label; protected System. Web. UI. Web. Controls. Label prompt. Label; protected System. Web. UI. Web. Controls. Drop. Down. List name. List; protected System. Web. UI. Web. Controls. Button submit. Button; protected System. Web. UI. Web. Controls. Required. Field. Validator required. Password. Validator ; protected System. Web. UI. Web. Controls. Custom. Validator invalid. Password. Validator ; protected System. Web. UI. Web. Controls. Text. Box password. Text. Box; protected System. Data. Ole. Db. Data. Reader data. Reader ; Two validators Allow specification on validity condition of a field // handle Page's Load event private void Page_Load( object sender, System. Event. Args e ) { // if page loads due to postback, process information // otherwise, page is loading for first time, so // do nothing If page is loaded for first time if ( !Is. Post. Back ) { // open database connection Execute SQL query, retrieve ole. Db. Connection 1. Open(); Login. aspx. cs all rows from Authors table of Books database // execute query data. Reader = ole. Db. Data. Adapter 1. Select. Command. Execute. Reader(); // while we can read a row from query result, Place item in first column // add first item to drop-down list each row into namelist while ( data. Reader. Read() ) name. List. Items. Add( data. Reader. Get. String( 0 ) ); of 2002 Prentice Hall. All rights reserved. 107
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 Outline // close database connection ole. Db. Connection 1. Close(); } } // end Page_Load // Visual Studio. NET generated code Execute every time user click Submit, use to validate password // validate user name and password private void invalid. Password. Validator _Server. Validate( object source, System. Web. UI. Web. Controls. Server. Validate. Event. Args args ) { // open database connection ole. Db. Connection 1. Open(); // set select command to find password of username // from drop-down list ole. Db. Data. Adapter 1. Select. Command. Text = "SELECT * FROM Users WHERE login. ID = '" + Request. Form[ "name. List" ]. To. String() + "'"; Login. aspx. cs data. Reader = ole. Db. Data. Adapter 1. Select. Command. Execute. Reader(); data. Reader. Read(); 2002 Prentice Hall. All rights reserved. 108
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 // // // if { Outline if password is correct, create Method Set. Auth. Cookie writes an encrypted authentication ticket for this user and redirect cookie totoclient containing information user to Authors. aspx; otherwise set Is. Valid false ( args. Value == data. Reader. Get. String(necessary 1 ) ) to authenticate the user Forms. Authentication. Set. Auth. Cookie( Value property contains value of Request. Form[ "namelist" ], false ); the control that Custom. Validator Session. Add( "name", Request. Form[ "name. List" ]. To. String() ); name is validating String containing user A boolean to specify whether Response. Redirect( "Authors. aspx" ); this cookie should persist Is. Valid contains boolean representing result If authenticated, user redirected // close database connection to Authors. aspx If Is. Valid is true, HTML form ole. Db. Connection 1. Close(); is submitted to Web server // end method invalid. Password. Validator _Server. Validate Login. aspx. cs } else args. Is. Valid = false; } } // end class Login } // end namespace Database 2002 Prentice Hall. All rights reserved. 109
Outline Login. aspx. cs Program Output 2002 Prentice Hall. All rights reserved. 110
Outline Login. aspx. cs Program Output 2002 Prentice Hall. All rights reserved. 111
Outline Login. aspx. cs Program Output 2002 Prentice Hall. All rights reserved. 112
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 <%-- Fig. 20. 40: Authors. aspx --%> <%-- This page allows a user to chose an author and display --%> <%-- that author's books. --%> <%@ Page language="c#" Codebehind="Authors. aspx. cs" Auto. Event. Wireup="false" Inherits="Database. Authors" %> <%@ Register Tag. Prefix="Header" Tag. Name="Image. Header" Src="Image. Header. ascx" %> <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <HEAD> <title>Authors</title> <meta name="GENERATOR" Content="Microsoft Visual Studio 7. 0" > <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_default. Client. Script" content="Java. Script"> <meta name="vs_target. Schema" content="http: //schemas. microsoft. com/intellisense/ie 5"> </HEAD> <body MS_POSITIONING= "Grid. Layout" bg. Color="#ffebff"> <form id="Authors" method="post" runat="server"> <asp: Drop. Down. List id="name. List" style="Z-INDEX: 103; LEFT: 90 px; POSITION: absolute; TOP: 157 px" runat="server" Width="158 px" Height="22 px"> </asp: Drop. Down. List> Outline Authors. aspx <Header: Image. Header id="Head 1" runat="server"> </Header: Image. Header> 2002 Prentice Hall. All rights reserved. 113
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 <asp: Label id="Label 2" style="Z-INDEX: 102; LEFT: 28 px; POSITION: absolute; TOP: 157 px" runat="server" Width="48 px" Height="22 px">Authors: </asp: Label> Outline <asp: Button id= "Button 1" style="Z-INDEX: 104; LEFT: 29 px; POSITION: absolute; TOP: 188 px" runat="server" Width="78 px" Text="Select"> </asp: Button> <asp: Label id="Label 3" style="Z-INDEX: 105; LEFT: 19 px; POSITION: absolute; TOP: 127 px" runat="server" Width="210 px" Visible="False">You chose </asp: Label> <asp: Data. Grid id="data. Grid" style="Z-INDEX: 106; LEFT: 12 px; POSITION: absolute; TOP: 151 px" runat="server" Height="23 px" Width="700 px" Fore. Color="Black" Allow. Paging="True" Data. Source="<%# data. View 1 %>" Visible="False" Allow. Sorting="True"> Authors. aspx Visible property set to false, control not visible <Edit. Item. Style Back. Color="White"></Edit. Item. Style> <Alternating. Item. Style Fore. Color ="Black" Back. Color="Light. Goldenrod. Yellow"> </Alternating. Item. Style> <Item. Style Back. Color="White"></Item. Style> <Header. Style Back. Color="Light. Green"></Header. Style> <Pager. Style Next. Page. Text="Next & gt; " Prev. Page. Text="& lt; Previous"> </Pager. Style> 2002 Prentice Hall. All rights reserved. 114
64 65 66 67 </asp: Data. Grid> </form> </body> </HTML> Outline Authors. aspx 2002 Prentice Hall. All rights reserved. 115
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // Fig. 20. 41: Authors. aspx. cs // The code-behind file for a page that allows a user to choose an // author and then view a list of that author's books. using using using Outline 116 System; System. Collections; System. Component. Model; System. Data; System. Drawing; System. Web. Session. State; System. Web. UI. Web. Controls; System. Web. UI. Html. Controls; namespace Database { // let user pick an author, then display that author's books public class Authors : System. Web. UI. Page { protected System. Web. UI. Web. Controls. Drop. Down. List name. List; protected System. Web. UI. Web. Controls. Label chose. Label; protected System. Web. UI. Web. Controls. Button select. Button; protected System. Web. UI. Web. Controls. Label authors. Label; protected System. Web. UI. Web. Controls. Data. Grid data. Grid; Authors. aspx. cs protected System. Data. Ole. Db. Data. Adapter ole. Db. Data. Adapter 1; protected System. Data. Ole. Db. Connection ole. Db. Connection 1; protected System. Data. Ole. Db. Data. Reader data. Reader ; protected System. Data. Ole. Db. Command ole. Db. Select. Command 1; 2002 Prentice Hall. All rights reserved.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 Outline protected System. Data. Ole. Db. Command ole. Db. Insert. Command 1; protected System. Data. Ole. Db. Command ole. Db. Update. Command 1; protected System. Data. Ole. Db. Command ole. Db. Delete. Command 1; 117 protected System. Data. Table data. Table 1 = new Data. Table(); protected System. Data. View data. View 1; protected static string sort. String = "Title"; Sort string in ascending order by title // on page load private void Page_Load( object sender, System. Event. Args e ) { // test whether page was loaded dueifto postback Determine page loaded if ( !Is. Post. Back ) as result of postback event Authors. aspx. cs { // open database connection try { Execute database command ole. Db. Connection 1. Open(); Open database connection to retrieve author’s first and last name // execute query Iterate through result set data. Reader = and add author’s first and ole. Db. Data. Adapter 1. Select. Command. Execute. Reader(); last names to name. List // while we can read a row from result of // query, add first item to dropdown list while ( data. Reader. Read() ) name. List. Items. Add( data. Reader. Get. String( 0 ) + " " + data. Reader. Get. String( 1 ) ); } 2002 Prentice Hall. All rights reserved.
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 // if database cannot be found catch( System. Data. Ole. Db. Exception ) { authors. Label. Text = "Server Error: Unable to load database!" ; } Outline 118 // close database connection finally { ole. Db. Connection 1. Close(); } } else { // set some controls to be invisible name. List. Visible = false; select. Button. Visible = false; chose. Label. Visible = false; The initial set of controls displayed to user are hidden in the postback Authors. aspx. cs // set other controls to be visible authors. Label. Visible = true; data. Grid. Visible = true; Add the selected author’s control // add author name to label name to the label authors. Label. Text = "You Chose " + name. List. Selected. Item + ". "; int author. ID = name. List. Selected. Index + 1; try { // open database connection ole. Db. Connection 1. Open(); 2002 Prentice Hall. All rights reserved.
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 // grab title, ISBN and publisher name for each book ole. Db. Data. Adapter 1. Select. Command. Text = "SELECT Titles. Title, Titles. ISBN, " + "Publishers. Publisher. Name FROM Author. ISBN Populates Data. Table" + "INNER JOIN Titles ON Author. ISBN = " + rows "Titles. ISBN, Publishersargument WHERE " with + by query "(Author. ISBN. Author. ID = returned " + author. ID + ")"; Outline 119 // fill dataset with results Create database query to ole. Db. Data. Adapter 1. Fill( data. Table 1 ); retrieve information and assign data. View 1 = new Data. View( data. Table 1 ); to Command. Text property data. View 1. Sort = sort. String; data. Grid. Data. Bind(); // bind grid to data source } // if database cannot be found catch( System. Data. Ole. Db. Exception ) { authors. Label. Text = "Server Error: Unable to load database!" ; } Authors. aspx. cs // close database connection finally { ole. Db. Connection 1. Close(); } } } // end method Page_Load 2002 Prentice Hall. All rights reserved.
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 // on new page private void On. New. Page( object sender, Data. Grid. Page. Changed. Event. Args e ) { // set current page to next page data. Grid. Current. Page. Index = e. New. Page. Index; data. View 1. Sort = sort. String; data. Grid. Data. Bind(); // rebind data } // end method On. New. Page Outline Method to handle the Data. Grid’s Page. Index. Changed event 120 Sort data and rebind it so that next page of data can be displayed // Visual Studio. NET generated code Method to handle Sort event of Data. Grid control // handles Sort event sort. String assigned to Sort. Expression private void data. Grid_Sort. Command( object Propertysource, indicates column System. Web. UI. Web. Controls. Data. Grid. Sort. Command. Event. Args e ) Data. View’s Sort property of e by which data is sorted { Authors. aspx. cs // get table to sort. String = e. Sort. Expression. To. String(); data. View 1. Sort = sort. String; // sort data. Grid. Data. Bind(); // rebind data } // end method data. Grid_Sort. Command } // end class Authors } // end namespace Database 2002 Prentice Hall. All rights reserved.
Outline 121 Authors. aspx. cs Program Output 2002 Prentice Hall. All rights reserved.
Outline 122 Authors. aspx. cs Program Output 2002 Prentice Hall. All rights reserved.
123 20. 9 Tracing • Place statement throughout code-behind file to output information during execution • Tracing in Web forms – Response. Write • Must remove all tracing statement when completed – Page tracing • Actions of individual page – – – Application tracing Control Tree Cookie Collection Headers Collection Server Variables 2002 Prentice Hall. All rights reserved.
124 20. 9 Tracing Trace property is set to false, “Using warnings” no displayed Fig. 20. 42 ASPX page with tracing turned off. 2002 Prentice Hall. All rights reserved.
125 20. 9 Tracing Request Details section provides information about the request Trace Information section contains output by calling methods Write and Warn List al controls contained on the page Fig. 20. 43 Tracing enabled on a page. 2002 Prentice Hall. All rights reserved. Page when Trace property set to True
Generated when programmer views the trace. axd file 126 20. 9 Tracing Fig. 20. 44 Tracing information for a project. 2002 Prentice Hall. All rights reserved. View Details links direct browser to page similar to Fig. 20. 43
- Slides: 126