Presentation is loading. Please wait.

Presentation is loading. Please wait.

© Keith Vander Linden, 2005 1 Need to modify the ASP.Net slides to more coherently cover the ASP material in the text, chapters 6 & 8. Cover reasons to.

Similar presentations


Presentation on theme: "© Keith Vander Linden, 2005 1 Need to modify the ASP.Net slides to more coherently cover the ASP material in the text, chapters 6 & 8. Cover reasons to."— Presentation transcript:

1 © Keith Vander Linden, 2005 1 Need to modify the ASP.Net slides to more coherently cover the ASP material in the text, chapters 6 & 8. Cover reasons to go server-side: – Never trust a client – The DB is on the server – The client can’t run it properly

2 © Keith Vander Linden, 2005 2 The network is the computer. - Sun Microsystems

3 © Keith Vander Linden, 2005 3 Building Dynamic Web Pages ● Client-Server Architectures (Section 1.4) Client-Server Architectures ● Client-Side Scripting (Chapters 3 & 4) Client-Side Scripting ● Web Servers (Chapter 5) Web Servers ● Server-Side Processing (Chapters 6, 8 & 10) Server-Side Processing

4 © Keith Vander Linden, 2005 4 Server-side processing Client/Server Architectures server Networ k client Client-side processing

5 © Keith Vander Linden, 2005 5 Static Web Sites server Networ k client HTTP Server File System Web Browser 1. The user uses a web browser to request a particular page. 2. The HTTP server receives the request and returns the source file for the requested page. 3. The browser displays the returned page.

6 © Keith Vander Linden, 2005 6 Client-Side Processing server Networ k client 2. The server is called only when necessary… 1. Browser scripts interact with the user.

7 © Keith Vander Linden, 2005 7 Server-Side Processing server Networ k client HTTP Server File System 1. The user requests a page that specifies server-side processing. 3. The application processor runs the requested program, which produces a web page to return. 4. The browser displays the returned page. Application Processor 2. The server requests the processing specified.

8 © Keith Vander Linden, 2005 8 Server-Side with a Database server 1 Networ k client HTTP Server File System 1. The user requests a page that specifies server-side processing. 5. The browser displays the returned page. Application Processor 2. The server requests the processing specified. server 2 Database Server database 3. The application processor requests the data from the database server. 4. The application processor produces a web page to return.

9 © Keith Vander Linden, 2005 9 Programs vs. Scripts ● Computers only understand programs written in a specially designed machine language:machine language – Machine language programs are hard to write. – They are machine-specific. ● In contrast, high-level languages:high-level languages – Are easier to write because they are modeled on well- understood human formalisms. – Require a program to translate them into machine language: Compiler Interpreter

10 © Keith Vander Linden, 2005 10 Machine Language Examples Sun SPARC executable machine code 000001110111010100000101 000001000110000100000110 000000000000010000000010 000000000000010000000000 000000000000000000000000 000000000000000000000010 000000000000000000000000 000000000000000000000001 000000000000000000000001 000000000011010000110000 000000000000000000000000 000000000000000001100100 000000000000000000000000 000000010011000100100100 000000000000000000000000 000000000000000001100100 000000000000000001000000 000000000000000000000101 000000000000000001010000 000000000000000000110011 000000000000000000110001 000000000000000000000000 000000000000000000000110 000000000000000000000000 000000000000000001100100 000000000000000000000001 000000000000000001100100 000000000000000000000000 000000000000000000000000 000000000000001001000000 000000000000000000000000 000000000000000000000101 000000000000000000000000 000000000000000000000000 000000000000000000000011 000000000000000000000000 000000000000001100100100 000000000000000000000000 000000000000000000000000 000000000000000000100001 … this goes on for another 1600 lines... Intel Pentium executable machine code 000000100111000000010001 000001100100010101000110 000001100010010101010100 000000100001000000010001 000001100111000101010001 000001110001000101100100 000000100111000101010111 000000100001000101000011 000000000101000000010101 000001100001010101000111 000000110001000101000011 000001100001010100110111 000001100110010101010111 000001100100010101100000 000001100010010101010100 000000100111000101000100 000000000110010001110010 000001010111010000010010 000001010111010100110111 000001100111000101000111 000001010111010101100101 000001100111010101000011 000001110000000101010101 000001100110000101010001 000001100010000101000101 000001100001010100110111 000000000110010001110010 000000000100010000010010 000001100010000001010110 000001100011000101000101 000001010111010000010001 000001010111010100110111 000001100000010101010101 000001100111000101010001 000000000100010001110011 000001110001010001010110 000001100110000101000011 000000110001000000010001 000000000100010001110011 000001110010000001010110 000001110000000101110001 000000000100010101000101 000000110001000001100011 000000000100010001110011 000001100010010001010110 000001100010000101010110 000001100011000101000101 000000000101000000010101 000001110010000001010110 000001110100000101000101 000000000110010101100100 000000000100010000010010 … this goes on for another 74 lines...

11 © Keith Vander Linden, 2005 11 High-Level Language Example int main() { int x, y; x = 1; y = x + 2; return 0; }

12 © Keith Vander Linden, 2005 12 Compilers int main() { int x, y; x = 1; y = x + 2; return 0; } SPARC machine code: 000001110111010100000101 000001000110000100000110 000000000000010000000010 000000000000010000000000 000000000000000000000000 000000000000000000000010 000000000000000000000000 000000000000000000000001 000000000000000000000001 000000000011010000110000 000000000000000000000000 000000000000000001100100 000000000000000000000000 000000010011000100100100 000000000000000000000000 000000000000000001100100 000000000000000001000000 000000000000000000000101 000000000000000001010000 000000000000000000110011 000000000000000000110001 000000000000000000000000 000000000000000000000110 000000000000000000000000 000000000000000001100100 000000000000000000000001 000000000000000001100100 000000000000000000000000 000000000000000000000000 000000000000001001000000 000000000000000000000000 000000000000000000000101 000000000000000000000000 000000000000000000000000 000000000000000000000011 000000000000000000000000 000000000000001100100100 000000000000000000000000 000000000000000000000000 000000000000000000100001 000001110111010100000101 000001000110000100000110 000000000000010000000010 000000000000010000000000 000000000000000000000000 000000000000000000000010 000000000000000000000000 000000000000000000000001 000000000000000000000001 000000000011010000110000 000000000000000000000000 000000000000000001100100 000000000000000000000000 000000010011000100100100 000000000000000000000000 000000000000000001100100 000000000000000001000000 000000000000000000000101 000000000000000001010000 000000000000000000110011 000000000000000000110001 000000000000000000000000 000000000000000000000110 000000000000000000000000 000000000000000001100100 000000000000000000000001 000000000000000001100100 000000000000000000000000 000000000000000000000000 000000000000001001000000 000000000000000000000000 000000000000000000000101 Intel machine code: 000000100111000000010001 000001100100010101000110 000001100010010101010100 000000100001000000010001 000001100111000101010001 000001110001000101100100 000000100111000101010111 000000100001000101000011 000000000101000000010101 000001100001010101000111 000000110001000101000011 000001100001010100110111 000001100110010101010111 000001100100010101100000 000001100010010101010100 000000100111000101000100 000000000110010001110010 000001010111010000010010 000001010111010100110111 000001100111000101000111 000001010111010101100101 000001100111010101000011 000001110000000101010101 000001100110000101010001 000001100010000101000101 000001100001010100110111 000000000110010001110010 000000000100010000010010 000001100010000001010110 000001100011000101000101 000001010111010000010001 000001010111010100110111 000001100000010101010101 000001100111000101010001 000000000100010001110011 000001110001010001010110 000001100110000101000011 000000110001000000010001 000000000100010001110011 000001110010000001010110 000001110000000101110001 000000000100010101000101 000000110001000001100011 000000000100010001110011 000001100010010001010110 000001100010000101010110 000001100011000101000101 000000000101000000010101 000001110010000001010110 000001110100000101000101 000000000110010101100100 000000000100010000010010 Intel C++ compiler Sun C++ compiler A compiler translates a program written in a high- level language into a machine language program.

13 © Keith Vander Linden, 2005 13 Interpreters ● An interpreter decodes a script written in a high-level language, executing it on-the-fly. ● Interpreted scripts tend to run more slowly than compiled programs. “3” PRINT 1+2 Interpreter

14 © Keith Vander Linden, 2005 14 Server-side processing server Networ k client Client-side processing Client/Server Technologies

15 © Keith Vander Linden, 2005 15 ● 1995 ● A hybrid of compilation and interpretation ● Based on a virtual machine ● Designed for a heterogeneous, networked environment. James Gosling (1956- ) Java Sun Microsystem’s “Green Team” was commissioned to ponder the next wave of computing. Images from javasoft.com August, 2003 What’s the Big Idea

16 © Keith Vander Linden, 2005 16 Client-Side Scripting ● Example: An Acme Attack Planner ● Technologies: – Forms (http://www.w3schools.com/html/html_forms.asp) Formshttp://www.w3schools.com/html/html_forms.asp – JavaScript (http://www.w3schools.com/js) JavaScripthttp://www.w3schools.com/js

17 © Keith Vander Linden, 2005 17 The Acme Attack Planner

18 planner.htm (1)

19 planner.htm (2)

20 © Keith Vander Linden, 2005 20 …other stuff here… …form stuff here… HTML Forms

21 © Keith Vander Linden, 2005 21 …other stuff here… Attack Name: …other form elements here… Form Input Boxes

22 © Keith Vander Linden, 2005 22 …other stuff here… Attack Location: desert flats cliff top the big rock the cave …other stuff here… Form Selection Lists

23 © Keith Vander Linden, 2005 23 Form Radio Buttons …other stuff here… Tool: Dynamite Mallet Arrow …other stuff here…

24 © Keith Vander Linden, 2005 24 Form Check Boxes …other stuff here… Status: Reviewed with friend …other stuff here…

25 © Keith Vander Linden, 2005 25 Form Command/Reset Buttons …other stuff here… …other stuff here…

26 © Keith Vander Linden, 2005 26 Post vs. Get ● Get ● Post

27 © Keith Vander Linden, 2005 27 JavaScript ● JavaScript is designed to add interactivity to HTML web pages: – Developed by Netscape – has a C/C++/Java-like syntax ● JavaScript ≠ Java – It is not object-oriented. – It has limited capabilities.

28 © Keith Vander Linden, 2005 28 HTML and JavaScript …other stuff here… Acme Attack Planner document.write(new Date()); …other stuff here…

29 © Keith Vander Linden, 2005 29 HTML and JavaScript (cont.)

30 © Keith Vander Linden, 2005 30 function validEntries() { …function code here… return true; } …HTML header/body here… Script Functions

31 © Keith Vander Linden, 2005 31 function validEntries() { // Alert the user when they don’t name the plan. if (document.frmAttackPlanner.txtName.value == ""){ alert ("Please enter a name for your attack"); document.frmAttackPlanner.txtName.select(); return false; } …more functions… return true; } …HTML header/body here… Script Functions

32 © Keith Vander Linden, 2005 32 function validEntries() { …previous functions… var dateValue = new Date(document.frmAttackPlanner.txtDate.value); if (isNaN(dateValue)) { alert ("Please enter a date in MM/DD/YYYY format."); document.frmAttackPlanner.txtDate.select(); return false; } …more functions… return true; } …HTML header/body here… Script Functions (cont.)

33 © Keith Vander Linden, 2005 33 function validEntries() { …previous functions… // There's no need to validate the attack location // because it has a default value. …more functions… return true; } …HTML header/body here… Script Functions (cont.)

34 © Keith Vander Linden, 2005 34 function validEntries() { …previous functions… var toolChecked = false; var toolValue = ""; // Save this value for the database update. for (var i=0; i<document.frmAttackPlanner.optTool.length; i++) { if (document.frmAttackPlanner.optTool[i].checked == true) { toolChecked = true; toolValue = document.frmAttackPlanner.optTool[i].value; } if (toolChecked == false) { alert ("Please select a tool."); return false; } …more functions… } Script Functions (cont.)

35 © Keith Vander Linden, 2005 35 function validEntries() { …previous functions… //validate review status if (document.frmAttackPlanner.chkReviewed.checked == false) { alert ("Please review your plans with a friend then check the status box."); document.frmAttackPlanner.chkReviewed.select(); return false; } …more functions… } Script Functions (cont.)

36 © Keith Vander Linden, 2005 36 function validEntries() { …previous functions… var triesValue = parseInt(document.frmAttackPlanner.txtTries.value); //triesValue contains only the whole integer part of whatever is entered. if (isNaN(triesValue)) { alert ("Please enter a whole number for the expected number of tries"); document.frmAttackPlanner.txtTries.select(); return false; } …more functions… } Script Functions (cont.)

37 © Keith Vander Linden, 2005 37 function validEntries() { …previous functions… if (confirm("You were hurt badly last time you tried this combination. " + "Do you really want to do it again?")) { alert ("The following plan has been saved:" + "\n\tName:\t" + document.frmAttackPlanner.txtName.value + "\n\tDate:\t" + dateValue + "\n\tLocation:\t" + document.frmAttackPlanner.lstLocation.options[ document.frmAttackPlanner.lstLocation.selectedIndex].text + "\n\tTool:\t" + toolValue + "\n\tTries:\t" + triesValue + "\nGood luck!"); } else { alert ("Wise move; now, make some changes."); return false; } Script Functions (cont.)

38 © Keith Vander Linden, 2005 38 An Image Swapper

39 IS 341 - Home Page <!-- var latinSeal = new Image() latinSeal.src = "../../images/calvin-seal-latin.gif" var englishSeal = new Image() englishSeal.src = "../../images/calvin-seal.gif" function setSeal(seal) { document.images[0].src=seal.src; } // --> …some other stuff… <a href="http://www.calvin.edu" onMouseOver="setSeal(latinSeal)" onMouseOut="setSeal(englishSeal)"> <img src="../../images/calvin-seal.gif" alt="I prefer the Latin" width="95px"> …some other stuff… index.html

40 © Keith Vander Linden, 2005 40 JavaScript Reference Material ● JavaScript data types (Netscape 2.0): – Boolean true, false – Number:Integer1, 0, 1, 2, 3 – Number:Floating Point3.141, -3.01, 36e9 – Number:Octal05, 06, 07, 010 – Number:Hexadecimal0x8, 0x9, 0xA, 0xB – String"cat", "dog", "" – Nullnull ● A JavaScript Reference/Tutorial: – http://www.w3schools.com/js/ http://www.w3schools.com/js/

41 © Keith Vander Linden, 2005 41 Server-side processing Client/Server Architectures server Networ k client Client-side processing

42 © Keith Vander Linden, 2005 42 Web Servers ● Computers running software that processes information requests from web clients ● Web servers communicate with clients using the Hypertext Transfer Protocol (HTTP). ● Web servers provide access to many information types, e.g.: – html, text, gif, postscript,… – front ends to applications

43 © Keith Vander Linden, 2005 43 Hyper-Text Transfer Protocol ● Web servers communicate with clients using HTTP: – Request Types, e.g.: GET POST – Response Types, e.g.: 200 404 ● The HTTP protocol is: – Stateless – Anonymous

44 © Keith Vander Linden, 2005 44 HTTP – A Static Page server Networ k client HTTP Server File System Web Browser GET/ IS/341/index.html HTTP/1.1 User-Agent: Mozilla/5.0 Host: myhost.calvin.edu Accept: */* Date 8/12/03 HTTP/1.1/200 Server: Apache/2.0 Content-type: text/html Date: 8/12/03 …The HTML source code… Port 80

45 © Keith Vander Linden, 2005 45 HTTP – Client-Side Processing server Networ k client HTTP Server File System Web Browser GET/ acme/orders.html HTTP/1.1 User-Agent: Mozilla/5.0 Host: myhost.calvin.edu Accept: */* Date 8/12/03 HTTP/1.1/200 Server: Apache/2.0 Content-type: text/html Date: 8/12/03 …The HTML source code with scripts… Port 80

46 © Keith Vander Linden, 2005 46 HTTP – Server-Side Processing server Networ k client HTTP Server File System Web Browser POST/ index.html HTTP/1.1 User-Agent: Mozilla/5.0 Host: myhost.calvin.edu Accept: */* Date 8/12/03 q=%22calvin+college%22& … HTTP/1.1/200 Server: Apache/2.0 Content-type: text/html Date: 8/12/03 …The HTML source code… Application Processor Port 80

47 © Keith Vander Linden, 2005 47 Tim Berners-Lee (1955- ) World Wide Web ● The world's first web server (info.cern.ch) on Dec. 25, 1990. ● Included the key elements of the WWW: – URL – HTTP – HTML Images from www.w3.org August, 2003www.w3.org

48 © Keith Vander Linden, 2005 48 Virtual Document Tree File system structure ≠ Virtual document tree – The server computer maintains a standard, hierarchical file system. – The server software provides access only to the files in its virtual document tree. C:\inetpub C:\inetpub\wwwroot C:\acme C:\ http://pella.calvin.edu/acme http://pella.calvin.edu/

49 © Keith Vander Linden, 2005 49 Handling Multiple Users ● HTTP servers/Application processors must hand multiple client requests. ● How to run application processes: – Within the server process itself – One separate server process per request – Some combination of the two (e.g., threads)

50 © Keith Vander Linden, 2005 50 HTTPS ● HTTPS is HTTP working over the secure sockets layer (SSL). ● SSL provides: – Encryption – Authentication

51 © Keith Vander Linden, 2005 51 Comparing IIS and Apache ● Apache – Open Source – Most commonly used – Seen as more reliable and more secure ● Internet Information Server – Microsoft – Better integration with ASP.Net – Nicer administration IDE Images from www.apache.org/www.microsoft.com August, 2003www.apache.orgwww.microsoft.com

52 © Keith Vander Linden, 2005 52 Client/Server Architectures Client-side processing server Networ k client HTTP Server File System Application Processor

53 © Keith Vander Linden, 2005 53 Server-Side Scripting ● Examples: – Acme new user registration Acme new user registration – Acme products table Acme products table ● Technologies: –.Net Framework (http://www.w3schools.com/ngws).Net Frameworkhttp://www.w3schools.com/ngws – VB.Net ( http://msdn.microsoft.com/vbasic/) VB.Net http://msdn.microsoft.com/vbasic/ – ASP.Net (http://www.w3schools.com/aspnet) ASP.Nethttp://www.w3schools.com/aspnet – ADO.Net (http://www.w3schools.com/aspnet/aspnet_dbconnection.asp) ADO.Nethttp://www.w3schools.com/aspnet/aspnet_dbconnection.asp

54 © Keith Vander Linden, 2005 54 Acme New User Registration

55 AcmeNewUser.aspx (1)

56 AcmeNewUser.aspx (2)

57 AcmeNewUser.aspx.vb

58 AcmeNewUser.aspx.vb (2)

59 © Keith Vander Linden, 2005 59 Acme Products Table

60 Products.aspx (1)

61 Products.aspx.vb

62 Products.aspx.vb (2)

63 © Keith Vander Linden, 2005 63.Net Framework ● Microsoft’s network-oriented development architecture ● Components: – Common language runtime – Class library

64 © Keith Vander Linden, 2005 64.Net vs. Java ● Similar technologies ●.Net (late 1990s/early 2000s) – Cleaner/newer implementation – Tightly integrated with Windows – Nicer IDEs ● Java (mid-1990s) – Multi-platform – Loosely integrated with the OS – Java community process Images from www.microsoft.com/www.javasoft.com August, 2003www.microsoft.com/www.javasoft.com

65 © Keith Vander Linden, 2005 65 VB.Net ● Not just for GUIs anymore: – VB.Net != VB6 – VB.Net  Java ● Compiled, server or client-side ● Integrated with Microsoft’s.Net framework and development tools

66 © Keith Vander Linden, 2005 66 VB.Net: Data Types Dim b As Boolean b = True Label1.Text += "Boolean: " + _ b.ToString() + " “ Dim d As DateTime d = DateTime.Now Label1.Text += "DateTime: " + _ d.ToString() + " “ Dim i As Integer i = 10 Label1.Text += "Integer: " + _ i.ToString() + " “ Dim j As Double j = 3.14159 Label1.Text += "Double: " + _ j.ToString() + " “ Dim s As String s = "a string" Label1.Text += s + " "

67 © Keith Vander Linden, 2005 67 VB.Net: Control Structures 'Print out an encouraging message. If DateTime.Now.DayOfWeek.ToString() = "Saturday" Then Label1.Text += " Take heart, it's Saturday! " End If 'Now, count from 10 to 1. Label1.Text += " Watch me count down from 10: " Dim count As Integer For count = 10 To 1 Step -1 Label1.Text += count.ToString() + " " Next Label1.Text += " "

68 © Keith Vander Linden, 2005 68 VB.Net: Procedures Private Sub My_Procedure(ByVal parm As String) Label1.Text += "My_Procedure prints: " + parm End Sub Private Function My_Function(ByVal parm As Integer) Return parm + 1 End Function In the main function… Label1.Text += " " My_Procedure("something to print out") Label1.Text += " My_Function returns: " + _ My_Function(1).ToString() Label1.Text += " "

69 © Keith Vander Linden, 2005 69 ASP.Net ● Active Server Pages ● Component of the.Net framework ● Supports dynamic web pages: – Web Forms (.aspx) Rich & HTML server controls Validation server controls – Web Services (.asmx)

70 © Keith Vander Linden, 2005 70 ASP.Net Processing server Networ k client IIS Server File System ASP.Net Processor 1&2. Initial request by browser and initial response by server. 3&4*. Postback event/arguments and dynamic response.

71 © Keith Vander Linden, 2005 71 ASP.Net vs. ASP ● ASP is an older technology (1996). ● ASP.Net: – Supports hybrid server/client-side event handlers – Separates HTML from “backing” code – Compiles its code

72 © Keith Vander Linden, 2005 72 ASP.Net vs. JSP ● ASP.Net – Microsoft platforms only – Widely used and supported – Supports multiple.Net languages ● JSP – Multi-platform support – Less widely used – Java only

73 © Keith Vander Linden, 2005 73 A Simple Example (cont.)

74 © Keith Vander Linden, 2005 74 A Simple Example

75 © Keith Vander Linden, 2005 75 A Simple Example (cont.)

76 © Keith Vander Linden, 2005 76 A Simple Example (cont.)

77 © Keith Vander Linden, 2005 77 ASP.Net in VS.Net

78 © Keith Vander Linden, 2005 78 Web Forms <form id="Form1“ method="post” runat="server"> …ASP.Net objects go here…

79 © Keith Vander Linden, 2005 79 Server Controls ‏ Common ASP.Net Server controls: – Label – TextBox – TextField – Checkbox – RadioButton – SubmitButton – ResetButton

80 © Keith Vander Linden, 2005 80 Server Controls (cont.) <asp:textbox id="txtFirst" style="Z- … " tabIndex="1" runat="server“ MaxLength="25“ Height="24“ Width="128px">

81 © Keith Vander Linden, 2005 81 Validation Controls ‏ Common ASP.Net Validation controls: – Required field – Range – Compare – Regular Expression – Custom

82 © Keith Vander Linden, 2005 82 Validation Controls (cont.)

83 © Keith Vander Linden, 2005 83 Validation Controls (cont.)

84 © Keith Vander Linden, 2005 84 Custom Validators

85 © Keith Vander Linden, 2005 85 Custom Validators (cont.) function ValidateUsername (val, args) { var currentUsername = new String(); args.IsValid=false; currentUsername.value=document.Form1.txtUsername.value; if (currentUsername.value.length < 6) { document.Form1.txtUsername.select(); } else { args.IsValid=true; }

86 © Keith Vander Linden, 2005 86 Event Handlers ‏ Common ASP.Net Events: – Button clicking – Text entry – Field validation – Document loading

87 © Keith Vander Linden, 2005 87 Event Handlers (cont.) Private Sub btnSubmit_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnSubmit.Click ‘Called if the form passes client-side validation If Me.IsValid Then lblMessage.Text = “Add to the database: " & _ txtFirst.Text & " " & txtMI.Text & _ " " & txtLast.Text & "..." End If End Sub

88 © Keith Vander Linden, 2005 88 Event Handlers (cont.) Private Sub CustomValidator1_ServerValidate(ByVal source As _ System.Object, ByVal args As _ System.Web.UI.WebControls.ServerValidateEventArgs) _ Handles CustomValidator1.ServerValidate If txtUsername.Text.Length < 6 Then args.IsValid = False Else args.IsValid = True End If End Sub

89 © Keith Vander Linden, 2005 89 Database Programming ● The world of information technology revolves around databases. ● Most database work is done through database application programs. ● Approaches to database programming: – Embedded SQL commands – Database API – A new database language

90 © Keith Vander Linden, 2005 90 Relational databases fields records tables General-purpose programming languages standard data types classes The problem is to bind: relational fields, records and tables native 4GL variables, arrays and classes 3.14159 “pi” Impedance Mismatch 1234

91 © Keith Vander Linden, 2005 91 ADO.Net ● ActiveX Data Objects ● Microsoft’s generic database API ● Comparisons: – ADO.Net vs ODBC/JDBC – ADO.Net vs ADO

92 © Keith Vander Linden, 2005 92 ADO.Net Classes Connected Data – Connection – Command – Data Reader – Data Adaptor – … Disconnected Data – Data Set – Data Table – Data Row – …

93 © Keith Vander Linden, 2005 93 ADO.Net Example 1. Establish a Connection to the Acme database. 2. Create objects to bridge the gap to SQL Server: – Data Reader/Adapter – SQL Command 3. Work with the data: – Data Set (optional) 4. Close the connection.

94 © Keith Vander Linden, 2005 94 Me.SqlConnection1 = New System.Data.SqlClient.SqlConnection Me.SqlConnection1.ConnectionString = "workstation id=PELLA;packet " & _ "size=4096;data source=PELLA;persist security info=True;" & _ "initial catalog=acme;user id=accountID;password=password" SqlConnection ● All interactions between the VB program and the database will be done through this object. ● Connections should be closed when no longer needed.

95 © Keith Vander Linden, 2005 95 SqlCommand Me.SqlSelectCommand1 = New System.Data.SqlClient.SqlCommand Me.SqlSelectCommand1.Connection = Me.SqlConnection1 Me.SqlSelectCommand1.CommandText = & _ "SELECT name, unitPrice, color, size, imageFileName “ & _ “FROM Products” ● Commands are ADO.Net objects that represent standard SQL commands. ● These strings are passed to the database to be executed.

96 © Keith Vander Linden, 2005 96 SqlDataReader Dim dataReader As System.Data.SqlClient.SqlDataReader Me.SqlConnection1.Open() dataReader = SQLCommand.ExecuteReader() While dataReader.Read() …access row values with: dataReader.GetXXX(index)… End While Me.SqlConnection1.Close() ● A DataReader is a forward-only, read- only window into the database. ● They can contain tables resulting from many queries.

97 © Keith Vander Linden, 2005 97 1. Connection SQL Server VB.Net Using a DataReader 3. The DataReader provides high-speed, one-way data flow. 2. SQL Command

98 © Keith Vander Linden, 2005 98 SqlDataAdaptor Me.SqlDataAdapter1 = New System.Data.SqlClient.SqlDataAdapter Me.SqlSelectCommand1 = New System.Data.SqlClient.SqlCommand Me.SqlConnection1 = New System.Data.SqlClient.SqlConnection Me.SqlDataAdapter1.SelectCommand = Me.SqlSelectCommand1 …create a dataset… Me.SqlDataAdapter1.Fill(DataSet1, “someResultname") …use the dataset… ● DataAdaptors mediate database/program communication. ● It supports the creation and resynching of disconnected data sets.

99 © Keith Vander Linden, 2005 99 DataSet Dim DataSet1 As New DataSet Dim aTable As DataTable Dim aRow As DataRow …load the dataset… aTable = DataSet1.Tables(0) For Each aRow In aTable.Rows …access row values with: aRow("imageFileName") … Next ● DataSets are a disconnected cache of data on the client. ● They support (potentially many): – DataTables – DataRows

100 © Keith Vander Linden, 2005 100 1. Connection SQL Server VB.Net Using a DataAdaptor/DataSet DataSet 3/4. The DataAdaptor supports disconnected two-way interaction. 2. SQL Command

101 © Keith Vander Linden, 2005 101 A Simple Example

102 © Keith Vander Linden, 2005 102 SqlDataReader Code Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs)_ Handles MyBase.Load Dim dataReader As System.Data.SQLClient.SQLDataReader Me.SQLConnection1.Open() dataReader = Me.SqlSelectCommand1.ExecuteReader() Label2.Text = “ Our favorite Acme character: ” While (dataReader.read()) Label2.Text += dataReader.GetString(0) + “ “ Label2.Text += dataReader.GetString(1) + “ “ Label2.Text += dataReader.GetString(2) + “ “ Label2.Text += “<img src=‘/acme/secure/images” Label2.Text += dataReader.GetString(3) Label2.Text += “’ alt=‘my favorite coyote’>” End While End Sub

103 © Keith Vander Linden, 2005 103 A Simple Example (cont.)

104 © Keith Vander Linden, 2005 104

105 © Keith Vander Linden, 2005 105

106 © Keith Vander Linden, 2005 106

107 © Keith Vander Linden, 2005 107 Another Example

108 © Keith Vander Linden, 2005 108

109 © Keith Vander Linden, 2005 109

110 © Keith Vander Linden, 2005 110

111 © Keith Vander Linden, 2005 111 DataAdaptor/ DataSet Example

112 © Keith Vander Linden, 2005 112 DataAdaptor/Set Code Public Class Products Inherits System.Web.UI.Page ‘Code created by Visual Studio Private Sub InitializeComponent() Me.SqlDataAdapter1 = New System.Data.SqlClient.SqlDataAdapter Me.SqlSelectCommand1 = New System.Data.SqlClient.SqlCommand Me.SqlConnection1 = New System.Data.SqlClient.SqlConnection Me.SqlDataAdapter1.SelectCommand = Me.SqlSelectCommand1 Me.SqlSelectCommand1.Connection = Me.SqlConnection1 Me.SqlConnection1.ConnectionString = "workstation id=PELLA;packet " & _ "size=4096;data source=PELLA;persist security info=True;" & _ "initial catalog=acme;user id=accountID;password=password" End Sub …other stuff (including the page_init subroutine)… End Class

113 © Keith Vander Linden, 2005 113 DataAdaptor/Set Code (2) Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_ Handles MyBase.Load …more stuff here… Dim DataSet1 As New DataSet Dim aTable As DataTable Dim aRow As DataRow Me.SqlSelectCommand1.CommandText = "SELECT name, unitPrice, color, size,” & _ “imageFileName FROM Products" Me.SqlDataAdapter1.Fill(DataSet1, "dsProducts") aTable = DataSet1.Tables(0) Label3.Text=" Product ”& _ “ Name Size Color Price " For Each aRow In aTable.Rows Label3.Text += " " Label3.Text += " " + tableValue(aRow("name")) + " " Label3.Text += " " + tableValue(aRow("size")) + " " Label3.Text += " " + tableValue(aRow("color")) + " " Label3.Text += " " + & _ tableValue(Format(aRow("unitPrice"), "$###,###,###.##")) + " " Label3.Text += " " Next …more stuff here… End Sub

114 © Keith Vander Linden, 2005 114 DataAdaptor/Set Code (3) Function tableValue(ByVal item As Object) If (item.ToString() = "") Then Return " " Else Return item End If End Function

115 © Keith Vander Linden, 2005 115 Database Updates …in the Web Form Designer Generated Code section… Me.SqlInsertCommand1 = New System.Data.SqlClient.SqlCommand Me.SqlDataAdapter1.InsertCommand = Me.SqlInsertCommand1 …in page_load()… Me.SqlSelectCommand1.CommandText = "Select MAX(ID) FROM Customers“ Dim dataReader As System.Data.SqlClient.SqlDataReader Dim uniqueID As Integer dataReader = Me.SqlSelectCommand1.ExecuteReader() If (dataReader.Read()) Then uniqueID = dataReader.GetInt32(0) + 1 Else uniqueID = 0 End If dataReader.Close() …continued on next slide…

116 © Keith Vander Linden, 2005 116 Database Updates (2) …continued from previous slide… Me.SqlInsertCommand1.CommandText = _ "INSERT INTO Customers(id, loginId, password, …other fields… ) VALUES (" & _ "'" & uniqueID.ToString() & "', " & _ "'" & username.Text & "', " & _ "'" & password.Text & "', " & _ "'" & System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "md5") &_ "', " & "'" & txtPwdHint.Text & "')“ Me.SqlInsertCommand1.ExecuteNonQuery() …continued on next slide…

117 © Keith Vander Linden, 2005 117 …continued from previous slide… Private Sub CustomValidator2_ServerValidate(ByVal source As System.Object, _ ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles _ CustomValidator2.ServerValidate Me.SqlSelectCommand1.CommandText = _ "Select id FROM Customers WHERE loginID = '" & txtUsername.Text & "'" Dim dataReader As System.Data.SqlClient.SqlDataReader dataReader = Me.SqlSelectCommand1.ExecuteReader() If (dataReader.Read()) Then args.IsValid = False Else args.IsValid = True End If dataReader.Close() End Sub Database Updates (3)

118 © Keith Vander Linden, 2005 118 Presenting Data ● Data has generally been presented with: – Report-generating tools – Thin programmed wrappers ● Problems with these approaches include: – Continuous connection requirements – Tight data/display coupling

119 © Keith Vander Linden, 2005 119 De-Coupling Data and Display ● Be careful to distinguish the presentation of the data from the data model itself. ● System architectures typically do this: – MVC – Layered architectures

120 © Keith Vander Linden, 2005 120 Data Display Controls ● ASP.Net provides 3 template-based data controls: – DataList – DataGrid – Repeater ● These controls simulate smart-client applications in a web application. Wile E. Coyote genius Sylvester hungry … Wile Sylvester … E Coyote Wile E. and Sylvester rule…

121 © Keith Vander Linden, 2005 121 1. Connection SQL Server VB.Net Using a DataGrid DataSet 3/4. The DataAdaptor supports disconnected two-way interaction. 2. SQL Command DataGrid Bind

122 © Keith Vander Linden, 2005 122 DataGrid Event Handlers ● DataGrid events signal event handlers, including: – Item Selected – Editing/Cancel/Update/Delete – Paging – Sorting ● These generate post-backs over the web.

123 © Keith Vander Linden, 2005 123 Example

124 © Keith Vander Linden, 2005 124 Example

125 © Keith Vander Linden, 2005 125 Example Code Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load 'Initialize the sorting arguments and data. If Not IsPostBack() Then Viewstate("SortedColumn") = "name" Viewstate("SortOrder") = "ASC" FillAndBind() End If End Sub

126 © Keith Vander Linden, 2005 126 Example Code (cont.) Private Sub FillSortedDataSet() 'Refill the dataset with the appropriate sorting. SqlDataAdapter1.SelectCommand.CommandText &= " order by " & _ ViewState("SortedColumn") & " " & _ ViewState("SortOrder") SqlDataAdapter1.Fill(DataSet11, "products") End Sub Private Sub BindDataGridWithHeaders() 'Rebind the datagrid with the appropriate headers. UpdateColumnHeaders(ViewState("SortedColumn"), _ ViewState("SortOrder")) DataGrid1.DataBind() End Sub Private Sub FillAndBind() FillSortedDataSet() BindDataGridWithHeaders() End Sub

127 © Keith Vander Linden, 2005 127 Example Code (cont.) Private Sub DataGrid1_EditCommand(ByVal source As Object, _ ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) _ Handles DataGrid1.EditCommand 'Edit the datagrid row in the click event's item index. DataGrid1.EditItemIndex = e.Item.ItemIndex FillAndBind() End Sub Private Sub DataGrid1_CancelCommand(ByVal source As Object, _ ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) _ Handles DataGrid1.CancelCommand 'Reset the datagrid's edit item to nothing. DataGrid1.EditItemIndex = -1 FillAndBind() End Sub

128 © Keith Vander Linden, 2005 128 Example Code (cont.) Private Sub DataGrid1_UpdateCommand(ByVal source As Object, _ ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) _ Handles DataGrid1.UpdateCommand 'Refill the dataset in sorted order so we can edit it. FillSortedDataSet() 'Loop through the edited row's columns, updating the dataset values. Dim ProductRow As DataRow = DataSet11.Products(e.Item.DataSetIndex) Dim i As Integer For i = 2 To DataSet11.Products.Columns.Count ProductRow(DataSet11.Products.Columns(i - 1).Caption) = _ CType(e.Item.Cells(i).Controls(0), TextBox).Text() Next 'Re-synch the dataset with the database. SqlDataAdapter1.Update(DataSet11) 'Turn off editing in the datagrid and bind the new values. DataGrid1.EditItemIndex = -1 DataGrid1.DataBind() End Sub

129 © Keith Vander Linden, 2005 129 Example Code (cont.) Private Sub DataGrid1_SortCommand(ByVal source As Object, _ ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) _ Handles DataGrid1.SortCommand 'Reset the sort column and order arguments properly. If ViewState("SortedColumn") = e.SortExpression _ And ViewState("SortOrder") = "ASC" Then ViewState("SortOrder") = "DESC" Else ViewState("SortOrder") = "ASC" End If ViewState("SortedColumn") = e.SortExpression 'Refill/bind the data with the new sorting order. FillAndBind() End Sub

130 © Keith Vander Linden, 2005 130 Example Code (cont.) Private Sub UpdateColumnHeaders(ByVal SortExpression As String, _ ByVal SortDirection As String) 'Change the sorting arrows on the datagrid header. Dim c As DataGridColumn For Each c In DataGrid1.Columns 'Clear any tags that might be present c.HeaderText = System.Text.RegularExpressions.Regex.Replace(c.HeaderText, _ "\s ", String.Empty) 'Put the appropriate arrow on the column being sorted. If c.SortExpression = SortExpression Then If SortDirection = "ASC" Then c.HeaderText &= " <img src=""images/up.gif"" _ border=""0"">" Else c.HeaderText &= " <img src=""images/down.gif"" _ border=""0"">" End If Next End Sub

131 © Keith Vander Linden, 2005 131 Example Code (cont.) Private Sub DataGrid1_PageIndexChanged(ByVal source As Object, _ ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) _ Handles DataGrid1.PageIndexChanged 'Move to appropriate page of the data and refill/bind. DataGrid1.CurrentPageIndex = e.NewPageIndex FillAndBind() End Sub

132 © Keith Vander Linden, 2005 132 Dramatization Act out a use case for the application just described.


Download ppt "© Keith Vander Linden, 2005 1 Need to modify the ASP.Net slides to more coherently cover the ASP material in the text, chapters 6 & 8. Cover reasons to."

Similar presentations


Ads by Google