© keith vander linden, 2005 1 need to modify the asp.net slides to more coherently cover the asp...
TRANSCRIPT
2
© Keith Vander Linden, 2005
The network is the computer.- Sun Microsystems
3
© Keith Vander Linden, 2005
Building Dynamic Web Pages
● Client-Server Architectures (Section 1.4)
● Client-Side Scripting (Chapters 3 & 4)
● Web Servers (Chapter 5)
● Server-Side Processing (Chapters 6, 8 & 10)
4
© Keith Vander Linden, 2005
Server-sideprocessing
Client/Server Architectures
server
Network
client
Client-sideprocessing
5
© Keith Vander Linden, 2005
Static Web Sites
server
Network
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
Client-Side Processing
server
Network
client
2. The server is called only when necessary…
1. Browser scripts interact with the user.
7
© Keith Vander Linden, 2005
Server-Side Processing
server
Network
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
Server-Side with a Database
server1
Network
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.
server2
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
Programs vs. Scripts
● Computers only understand programs written in a specially designed machine language:– Machine language programs are hard to write.– They are machine-specific.
● In contrast, 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
Machine Language ExamplesSun SPARC executable machine code
000001110111010100000101 000001000110000100000110000000000000010000000010 000000000000010000000000 000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000010 000000000000000000000010000000000000000000000000 000000000000000000000001 000000000000000000000001 000000000011010000110000000000000000000000000000 000000000000000001100100000000000000000000000000 000000010011000100100100000000000000000000000000 000000000000000000000000 000000000000000001100100 000000000000000001000000000000000000000000000101 000000000000000001010000000000000000000000110011 000000000000000000110001000000000000000000000000 000000000000000000000110 000000000000000000000000 000000000000000001100100000000000000000000000001 000000000000000001100100000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000001001000000000000000000000000000000 000000000000001001000000000000000000000000000000 000000000000000000000101000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000000011 000000000000000000000000 000000000000001100100100000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000100001
… this goes on for another 1600 lines...
Intel Pentium executable machine code
000000100111000000010001 000001100100010101000110000001100010010101010100 000000100001000000010001000001100111000101010001 000001110001000101100100000000100111000101010111 000000100001000101000011000000000101000000010101 000001100001010101000111000000110001000101000011 000001100001010100110111000001100110010101010111 000001100100010101100000000001100010010101010100 000000100111000101000100000000000110010001110010 000001010111010000010010000001010111010100110111 000001100111000101000111000001010111010101100101 000001100111010101000011000001110000000101010101 000001100110000101010001000001100010000101000101 000001100001010100110111000000000110010001110010 000000000100010000010010000001100010000001010110 000001100011000101000101000001010111010000010001 000001010111010100110111000001100000010101010101 000001100111000101010001000000000100010001110011 000001110001010001010110000001100110000101000011 000000110001000000010001000000000100010001110011 000001110010000001010110000001110000000101110001 000000000100010101000101000000110001000001100011 000000000100010001110011000001100010010001010110 000001100010000101010110000001100011000101000101 000000000101000000010101000001110010000001010110 000001110100000101000101000000000110010101100100 000000000100010000010010
… this goes on for another 74 lines...
11
© Keith Vander Linden, 2005
High-Level Language Example
int main(){ int x, y; x = 1; y = x + 2; return 0;}
12
© Keith Vander Linden, 2005
Compilers
int main(){ int x, y; x = 1; y = x + 2; return 0;}
SPARC machine code:000001110111010100000101 000001000110000100000110000000000000010000000010 000000000000010000000000 000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000010 000000000000000000000010000000000000000000000000 000000000000000000000001 000000000000000000000001 000000000011010000110000000000000000000000000000 000000000000000001100100000000000000000000000000 000000010011000100100100000000000000000000000000 000000000000000000000000 000000000000000001100100 000000000000000001000000000000000000000000000101 000000000000000001010000000000000000000000110011 000000000000000000110001000000000000000000000000 000000000000000000000110 000000000000000000000000 000000000000000001100100000000000000000000000001 000000000000000001100100000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000001001000000000000000000000000000000 000000000000001001000000000000000000000000000000 000000000000000000000101000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000000011 000000000000000000000000 000000000000001100100100000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000100001 000001110111010100000101 000001000110000100000110000000000000010000000010 000000000000010000000000 000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000010 000000000000000000000010000000000000000000000000 000000000000000000000001 000000000000000000000001 000000000011010000110000000000000000000000000000 000000000000000001100100000000000000000000000000 000000010011000100100100000000000000000000000000 000000000000000000000000 000000000000000001100100 000000000000000001000000000000000000000000000101 000000000000000001010000000000000000000000110011 000000000000000000110001000000000000000000000000 000000000000000000000110 000000000000000000000000 000000000000000001100100000000000000000000000001 000000000000000001100100000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000001001000000000000000000000000000000 000000000000001001000000000000000000000000000000 000000000000000000000101
Intel machine code:000000100111000000010001 000001100100010101000110000001100010010101010100 000000100001000000010001000001100111000101010001 000001110001000101100100000000100111000101010111 000000100001000101000011000000000101000000010101 000001100001010101000111000000110001000101000011 000001100001010100110111000001100110010101010111 000001100100010101100000000001100010010101010100 000000100111000101000100000000000110010001110010 000001010111010000010010000001010111010100110111 000001100111000101000111000001010111010101100101 000001100111010101000011000001110000000101010101 000001100110000101010001000001100010000101000101 000001100001010100110111000000000110010001110010 000000000100010000010010000001100010000001010110 000001100011000101000101000001010111010000010001 000001010111010100110111000001100000010101010101 000001100111000101010001000000000100010001110011 000001110001010001010110000001100110000101000011 000000110001000000010001000000000100010001110011 000001110010000001010110000001110000000101110001 000000000100010101000101000000110001000001100011 000000000100010001110011000001100010010001010110 000001100010000101010110000001100011000101000101 000000000101000000010101000001110010000001010110 000001110100000101000101000000000110010101100100 000000000100010000010010
IntelC++ compiler
SunC++ compiler
A compiler translates a program written in a high-level language into a machine language program.
13
© Keith Vander Linden, 2005
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
Server-sideprocessing
server
Network
client
Client-sideprocessing
Client/Server Technologies
15
© Keith Vander Linden, 2005
● 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 theBig Idea
16
© Keith Vander Linden, 2005
Client-Side Scripting
● Example: An Acme Attack Planner● Technologies:
– Forms (http://www.w3schools.com/html/html_forms.asp)
– JavaScript (http://www.w3schools.com/js)
20
© Keith Vander Linden, 2005
<body>
…other stuff here…
<form name="frmAttackPlanner" onsubmit="return validEntries()">
…form stuff here…
</form> </body>
HTML Forms
21
© Keith Vander Linden, 2005
<body>
…other stuff here…
<form name="frmAttackPlanner" onsubmit="return validEntries()">
<table align="center"><tr> <td>Attack Name:</td> <td><input type="text"
name="txtName"></td></tr>
…other form elements here…
</table> </form> </body>
Form Input Boxes
22
© Keith Vander Linden, 2005
…other stuff here… <tr> <td valign="top">Attack Location:</td> <td> <select name="lstLocation"> <option>desert flats</option> <option>cliff top</option> <option>the big rock</option> <option>the cave</option> </select> </td></tr>
…other stuff here…
Form Selection Lists
23
© Keith Vander Linden, 2005
Form Radio Buttons
…other stuff here… <tr> <td valign="top">Tool:</td> <td> <input type="radio" name="optTool"
value="dynamite">Dynamite<br> <input type="radio" name="optTool"
value="mallet">Mallet<br> <input type="radio" name="optTool"
value="arrow">Arrow<br> </td></tr>
…other stuff here…
24
© Keith Vander Linden, 2005
Form Check Boxes
…other stuff here… <tr> <td>Status:</td> <td><input type="checkbox" name="chkReviewed">Reviewed with friend</td></tr>
…other stuff here…
25
© Keith Vander Linden, 2005
Form Command/Reset Buttons
…other stuff here…
<tr> <td></td> <td> <input type="submit" value="Submit"> <input type="reset"> </td></tr>
…other stuff here…
26
© Keith Vander Linden, 2005
Post vs. Get
● Get
● Post
27
© Keith Vander Linden, 2005
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
HTML and JavaScript
<body>
…other stuff here…
<h2>Acme Attack Planner</h2> <script language="javascript"> document.write(new Date()); </script>
…other stuff here…
</body>
29
© Keith Vander Linden, 2005
HTML and JavaScript (cont.)
30
© Keith Vander Linden, 2005
<script language="javascript"> function validEntries() {
…function code here…
return true; }</script>
…HTML header/body here…
Script Functions
31
© Keith Vander Linden, 2005
<script language="javascript"> 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; }</script>
…HTML header/body here…
Script Functions
32
© Keith Vander Linden, 2005
<script language="javascript"> 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; }</script>
…HTML header/body here…
Script Functions (cont.)
33
© Keith Vander Linden, 2005
<script language="javascript"> function validEntries() {
…previous functions…
// There's no need to validate the attack location // because it has a default value.
…more functions…
return true; }</script>
…HTML header/body here…
Script Functions (cont.)
34
© Keith Vander Linden, 2005
<script language="javascript"> 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>
Script Functions (cont.)
35
© Keith Vander Linden, 2005
<script language="javascript"> 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>
Script Functions (cont.)
36
© Keith Vander Linden, 2005
<script language="javascript"> 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>
Script Functions (cont.)
37
© Keith Vander Linden, 2005
<script language="javascript"> 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>
Script Functions (cont.)
38
© Keith Vander Linden, 2005
An Image Swapper
<html><head><title>IS 341 - Home Page</title><script type="text/javascript" language="Javascript"> <!-- 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; } // --></script></head>
<body class="main">
…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"></a>
…some other stuff…
</body></html>
index.html
40
© Keith Vander Linden, 2005
JavaScript Reference Material
● JavaScript data types (Netscape 2.0):– Boolean true, false– Number:Integer 1, 0, 1, 2, 3– Number:Floating Point 3.141, -3.01, 36e9– Number:Octal 05, 06, 07, 010– Number:Hexadecimal 0x8, 0x9, 0xA, 0xB– String "cat", "dog", ""– Null null
● A JavaScript Reference/Tutorial:– http://www.w3schools.com/js/
41
© Keith Vander Linden, 2005
Server-sideprocessing
Client/Server Architectures
server
Network
client
Client-sideprocessing
42
© Keith Vander Linden, 2005
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
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
HTTP – A Static Page
server
Network
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.0Content-type: text/html Date: 8/12/03 <HTML> …The HTML source code… </HTML>
Port 80
45
© Keith Vander Linden, 2005
HTTP – Client-Side Processing
server
Network
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.0Content-type: text/html Date: 8/12/03 <HTML> …The HTML source code with
scripts… </HTML>
Port 80
46
© Keith Vander Linden, 2005
HTTP – Server-Side Processing
server
Network
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/03q=%22calvin+college%22& …
HTTP/1.1/200 Server: Apache/2.0Content-type: text/html Date: 8/12/03 <HTML> …The HTML source code… </HTML>
Application Processor
Port 80
47
© Keith Vander Linden, 2005
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, 2003
48
© Keith Vander Linden, 2005
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
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
HTTPS
● HTTPS is HTTP working over the secure sockets layer (SSL).
● SSL provides:– Encryption
– Authentication
51
© Keith Vander Linden, 2005
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, 2003
52
© Keith Vander Linden, 2005
Client/Server Architectures
Client-sideprocessing
server
Network
client
HTTP Server
File System
Application Processor
53
© Keith Vander Linden, 2005
Server-Side Scripting● Examples:
– Acme new user registration– Acme products table
● Technologies:– .Net Framework (http://www.w3schools.com/ngws)
– VB.Net (http://msdn.microsoft.com/vbasic/)
– ASP.Net (http://www.w3schools.com/aspnet)
– ADO.Net (http://www.w3schools.com/aspnet/aspnet_dbconnection.asp)
63
© Keith Vander Linden, 2005
.Net Framework
● Microsoft’s network-oriented development architecture
● Components:– Common language runtime
– Class library
64
© Keith Vander Linden, 2005
.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, 2003
65
© Keith Vander Linden, 2005
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
VB.Net: Data TypesDim b As Booleanb = TrueLabel1.Text += "Boolean: " + _ b.ToString() + "<br>“
Dim d As DateTimed = DateTime.NowLabel1.Text += "DateTime: " + _ d.ToString() + "<br>“
Dim i As Integeri = 10Label1.Text += "Integer: " + _ i.ToString() + "<br>“
Dim j As Doublej = 3.14159Label1.Text += "Double: " + _
j.ToString() + "<br>“
Dim s As Strings = "a string"Label1.Text += s + "<br>"
67
© Keith Vander Linden, 2005
VB.Net: Control Structures
'Print out an encouraging message.If DateTime.Now.DayOfWeek.ToString() = "Saturday" Then Label1.Text += "<p>Take heart, it's Saturday!</p>"End If
'Now, count from 10 to 1.Label1.Text += "<p>Watch me count down from 10:<br>"Dim count As IntegerFor count = 10 To 1 Step -1 Label1.Text += count.ToString() + " "NextLabel1.Text += "</p>"
68
© Keith Vander Linden, 2005
VB.Net: Procedures
Private Sub My_Procedure(ByVal parm As String) Label1.Text += "My_Procedure prints: " + parmEnd Sub
Private Function My_Function(ByVal parm As Integer) Return parm + 1End Function
In the main function…
Label1.Text += "<p>"My_Procedure("something to print out")Label1.Text += "<br>My_Function returns: " + _
My_Function(1).ToString()Label1.Text += "</p>"
69
© Keith Vander Linden, 2005
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
ASP.Net Processing
server
Network
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
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
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
A Simple Example (cont.)
77
© Keith Vander Linden, 2005
ASP.Net in VS.Net
78
© Keith Vander Linden, 2005
Web Forms
<form id="Form1“ method="post” runat="server">
…ASP.Net objects go here…
</form>
79
© Keith Vander Linden, 2005
Server Controls
Common ASP.Net Server controls:
– Label– TextBox– TextField– Checkbox– RadioButton– SubmitButton– ResetButton
80
© Keith Vander Linden, 2005
Server Controls (cont.)<asp:textbox id="txtFirst" style="Z- … " tabIndex="1" runat="server“ MaxLength="25“ Height="24“ Width="128px"></asp:textbox>
81
© Keith Vander Linden, 2005
Validation Controls
Common ASP.Net Validation controls:
– Required field– Range – Compare– Regular
Expression– Custom
82
© Keith Vander Linden, 2005
Validation Controls (cont.)
83
© Keith Vander Linden, 2005
Validation Controls (cont.)
84
© Keith Vander Linden, 2005
Custom Validators
85
© Keith Vander Linden, 2005
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
Event Handlers
Common ASP.Net Events:
– Button clicking– Text entry– Field validation– Document
loading
87
© Keith Vander Linden, 2005
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:<br />" & _ txtFirst.Text & " " & txtMI.Text & _ " " & txtLast.Text & "..." End IfEnd Sub
88
© Keith Vander Linden, 2005
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 IfEnd Sub
89
© Keith Vander Linden, 2005
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
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
1 2 3 4
91
© Keith Vander Linden, 2005
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
ADO.Net Classes
Connected Data– Connection– Command– Data Reader– Data Adaptor– …
Disconnected Data– Data Set– Data Table– Data Row– …
93
© Keith Vander Linden, 2005
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
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
SqlCommand
Me.SqlSelectCommand1 = New System.Data.SqlClient.SqlCommandMe.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
SqlDataReader
Dim dataReader As System.Data.SqlClient.SqlDataReaderMe.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
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
SqlDataAdaptorMe.SqlDataAdapter1 = New System.Data.SqlClient.SqlDataAdapterMe.SqlSelectCommand1 = New System.Data.SqlClient.SqlCommandMe.SqlConnection1 = New System.Data.SqlClient.SqlConnectionMe.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
DataSetDim DataSet1 As New DataSetDim aTable As DataTableDim 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
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
A Simple Example
102
© Keith Vander Linden, 2005
SqlDataReader CodePrivate 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 = “<p>Our favorite Acme character:</p>” While (dataReader.read()) Label2.Text += dataReader.GetString(0) + “ “ Label2.Text += dataReader.GetString(1) + “ “ Label2.Text += dataReader.GetString(2) + “<br />“ Label2.Text += “<img src=‘/acme/secure/images” Label2.Text += dataReader.GetString(3) Label2.Text += “’ alt=‘my favorite coyote’>” End While
End Sub
107
© Keith Vander Linden, 2005
Another Example
111
© Keith Vander Linden, 2005
DataAdaptor/DataSet Example
112
© Keith Vander Linden, 2005
DataAdaptor/Set CodePublic Class Products Inherits System.Web.UI.Page
‘Code created by Visual Studio <System.Diagnostics.DebuggerStepThrough()> 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
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="<table border=1 cellpadding=5 width=100%><tr><th>Product</th>”& _ “<th>Name</th><th>Size</th><th>Color</th><th>Price</th></tr>" For Each aRow In aTable.Rows Label3.Text += "<tr>" Label3.Text += "<td align=center><img src=""Images/" + _
aRow("imageFileName") + """ height=75px></td>" Label3.Text += "<td align=center>" + tableValue(aRow("name")) + "</td>" Label3.Text += "<td align=center>" + tableValue(aRow("size")) + "</td>" Label3.Text += "<td align=center>" + tableValue(aRow("color")) + "</td>" Label3.Text += "<td align=right>" + & _
tableValue(Format(aRow("unitPrice"), "$###,###,###.##")) + "</td>" Label3.Text += "</tr>" Next…more stuff here…End Sub
114
© Keith Vander Linden, 2005
DataAdaptor/Set Code (3)
Function tableValue(ByVal item As Object) If (item.ToString() = "") Then Return " " Else Return item End IfEnd Function
115
© Keith Vander Linden, 2005
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.SqlDataReaderDim uniqueID As IntegerdataReader = Me.SqlSelectCommand1.ExecuteReader()If (dataReader.Read()) Then uniqueID = dataReader.GetInt32(0) + 1Else uniqueID = 0End If
dataReader.Close()
…continued on next slide…
116
© Keith Vander Linden, 2005
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
…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
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
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
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
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
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
Example
125
© Keith Vander Linden, 2005
Example CodePrivate 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 IfEnd Sub
126
© Keith Vander Linden, 2005
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
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
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
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
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 <img> 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 End If NextEnd Sub
131
© Keith Vander Linden, 2005
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