Need to modify the ASP.Net slides to more coherently cover the ASP material in the text, chapters 6 - PowerPoint PPT Presentation

About This Presentation
Title:

Need to modify the ASP.Net slides to more coherently cover the ASP material in the text, chapters 6

Description:

Need to modify the ASP.Net s to more coherently cover the ASP material in the text, chapters 6 & 8. Cover reasons to go server-side: Never trust a client – PowerPoint PPT presentation

Number of Views:178
Avg rating:3.0/5.0
Slides: 108
Provided by: calvinEdu
Learn more at: https://cs.calvin.edu
Category:

less

Transcript and Presenter's Notes

Title: Need to modify the ASP.Net slides to more coherently cover the ASP material in the text, chapters 6


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 cant run it properly

2
  • The network is the computer.
  • - Sun Microsystems

3
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
Client/Server Architectures
Server-side processing
Client-side processing
Network
server
client
5
Static Web Sites
HTTP Server
Web Browser
Network
File System
server
client
6
Client-Side Processing
Network
server
client
7
Server-Side Processing
HTTP Server
Application Processor
Network
File System
server
client
4. The browser displays the returned page.
8
Server-Side with a Database
1. The user requests a page that specifies
server-side processing.
HTTP Server
Application Processor
Network
File System
server1
client
4. The application processor produces a web page
to return.
5. The browser displays the returned page.
3. The application processor requests the data
from the database server.
Database Server
database
server2
9
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
Machine Language Examples
Sun SPARC executable machine code 000001110111010
100000101 000001000110000100000110 000000000000010
000000010 000000000000010000000000
000000000000000000000000 000000000000000000000000
000000000000000000000000 000000000000000000000000
000000000000000000000010 000000000000000000000010
000000000000000000000000 000000000000000000000001
000000000000000000000001 00000000001101000011000
0 000000000000000000000000 00000000000000000110010
0 000000000000000000000000 00000001001100010010010
0 000000000000000000000000 00000000000000000000000
0 000000000000000001100100 0000000000000000010000
00 000000000000000000000101 0000000000000000010100
00 000000000000000000110011 0000000000000000001100
01 000000000000000000000000 0000000000000000000001
10 000000000000000000000000 000000000000000001100
100 000000000000000000000001 000000000000000001100
100 000000000000000000000000 000000000000000000000
000 000000000000000000000000 000000000000001001000
000 000000000000000000000000 000000000000001001000
000 000000000000000000000000 000000000000000000000
101 000000000000000000000000 000000000000000000000
000 000000000000000000000000 000000000000000000000
011 000000000000000000000000 00000000000000110010
0100 000000000000000000000000 00000000000000000000
0000 000000000000000000000000 00000000000000000000
0000 000000000000000000000000 00000000000000000010
0001 this goes on for another 1600 lines...
Intel Pentium executable machine
code 000000100111000000010001 0000011001000101010
00110 000001100010010101010100 0000001000010000000
10001 000001100111000101010001 0000011100010001011
00100 000000100111000101010111 0000001000010001010
00011 000000000101000000010101 0000011000010101010
00111 000000110001000101000011 0000011000010101001
10111 000001100110010101010111 0000011001000101011
00000 000001100010010101010100 0000001001110001010
00100 000000000110010001110010 0000010101110100000
10010 000001010111010100110111 0000011001110001010
00111 000001010111010101100101 0000011001110101010
00011 000001110000000101010101 0000011001100001010
10001 000001100010000101000101 0000011000010101001
10111 000000000110010001110010 0000000001000100000
10010 000001100010000001010110 0000011000110001010
00101 000001010111010000010001 0000010101110101001
10111 000001100000010101010101 0000011001110001010
10001 000000000100010001110011 0000011100010100010
10110 000001100110000101000011 0000001100010000000
10001 000000000100010001110011 0000011100100000010
10110 000001110000000101110001 0000000001000101010
00101 000000110001000001100011 0000000001000100011
10011 000001100010010001010110 0000011000100001010
10110 000001100011000101000101 0000000001010000000
10101 000001110010000001010110 0000011101000001010
00101 000000000110010101100100 0000000001000100000
10010 this goes on for another 74 lines...
11
High-Level Language Example
int main() int x, y x 1 y x 2
return 0
12
Compilers
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
  • A compiler translates a program written in a
    high-level language into a machine language
    program.

SPARC machine code 000001110111010100000101
000001000110000100000110 000000000000010000000010
000000000000010000000000 000000000000000000000000
000000000000000000000000 000000000000000000000000
000000000000000000000000 000000000000000000000010
000000000000000000000010 000000000000000000000000
000000000000000000000001 00000000000000000000000
1 000000000011010000110000 00000000000000000000000
0 000000000000000001100100 00000000000000000000000
0 000000010011000100100100 00000000000000000000000
0 000000000000000000000000 0000000000000000011001
00 000000000000000001000000 0000000000000000000001
01 000000000000000001010000 0000000000000000001100
11 000000000000000000110001 0000000000000000000000
00 000000000000000000000110 000000000000000000000
000 000000000000000001100100 000000000000000000000
001 000000000000000001100100 000000000000000000000
000 000000000000000000000000 000000000000000000000
000 000000000000001001000000 000000000000000000000
000 000000000000001001000000 000000000000000000000
000 000000000000000000000101 000000000000000000000
000 000000000000000000000000 000000000000000000000
000 000000000000000000000011 00000000000000000000
0000 000000000000001100100100 00000000000000000000
0000 000000000000000000000000 00000000000000000000
0000 000000000000000000000000 00000000000000000000
0000 000000000000000000100001 0000011101110101000
00101 000001000110000100000110 0000000000000100000
00010 000000000000010000000000 000000000000000000
000000 000000000000000000000000 000000000000000000
000000 000000000000000000000000 000000000000000000
000010 000000000000000000000010 000000000000000000
000000 000000000000000000000001
000000000000000000000001 000000000011010000110000
000000000000000000000000 000000000000000001100100
000000000000000000000000 000000010011000100100100
000000000000000000000000 000000000000000000000000
000000000000000001100100 00000000000000000100000
0 000000000000000000000101 00000000000000000101000
0 000000000000000000110011 00000000000000000011000
1 000000000000000000000000 00000000000000000000011
0 000000000000000000000000 0000000000000000011001
00 000000000000000000000001 0000000000000000011001
00 000000000000000000000000 0000000000000000000000
00 000000000000000000000000 0000000000000010010000
00 000000000000000000000000 0000000000000010010000
00 000000000000000000000000 0000000000000000000001
01
int main() int x, y x 1 y x 2
return 0
Intel C compiler
Sun C compiler
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.

Interpreter
3
PRINT 12
14
Client/Server Technologies
Server-side processing
Client-side processing
Network
server
client
15
James Gosling (1956- )Java
  • 1995
  • A hybrid of compilation and interpretation
  • Based on a virtual machine
  • Designed for a heterogeneous, networked
    environment.

Sun Microsystems Green Team was commissioned
to ponder the next wave of computing.
Images from javasoft.com August, 2003
16
Client-Side Scripting
  • Example An Acme Attack Planner
  • Technologies
  • Forms (http//www.w3schools.com/html/html_form
    s.asp)
  • JavaScript (http//www.w3schools.com/js)

17
The Acme Attack Planner
18
planner.htm (1)
19
planner.htm (2)
20
HTML Forms
ltbodygt other stuff here ltform
name"frmAttackPlanner" onsubmit"return
validEntries()"gt form stuff
here lt/formgt
lt/bodygt
21
Form Input Boxes
ltbodygt other stuff here ltform
name"frmAttackPlanner" onsubmit"return
validEntries()"gt lttable align"center"gt lttr
gt lttdgtAttack Namelt/tdgt lttdgtltinput
type"text" name"txtName"gtlt/tdgt lt/trgt
other form elements here lt/tablegt
lt/formgt lt/bodygt
22
Form Selection Lists
other stuff here lttrgt lttd
valign"top"gtAttack Locationlt/tdgt lttdgt
ltselect name"lstLocation"gt ltoptiongtdesert
flatslt/optiongt ltoptiongtcliff toplt/optiongt
ltoptiongtthe big rocklt/optiongt
ltoptiongtthe cavelt/optiongt lt/selectgt
lt/tdgt lt/trgt other stuff here
23
Form Radio Buttons
other stuff here lttrgt lttd
valign"top"gtToollt/tdgt lttdgt ltinput
type"radio" name"optTool" value"dynamite"gtDyna
miteltbrgt ltinput type"radio" name"optTool"
value"mallet"gtMalletltbrgt ltinput
type"radio" name"optTool" value"arrow"gtArrowltb
rgt lt/tdgt lt/trgt other stuff here
24
Form Check Boxes
other stuff here lttrgt
lttdgtStatuslt/tdgt lttdgtltinput type"checkbox"
name"chkReviewed"gtReviewed with
friendlt/tdgt lt/trgt other stuff here
25
Form Command/Reset Buttons
other stuff here lttrgt lttdgtlt/tdgt
lttdgt ltinput type"submit" value"Submit"gt
ltinput type"reset"gt lt/tdgt lt/trgt other
stuff here
26
Post vs. Get
  • Get
  • Post

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
HTML and JavaScript
ltbodygt other stuff here lth2gtAcme
Attack Plannerlt/h2gt ltscript language"javascrip
t"gt document.write(new Date())
lt/scriptgt other stuff here lt/bodygt
29
HTML and JavaScript (cont.)
30
Script Functions
ltscript language"javascript"gt function
validEntries() function code here
return true lt/scriptgt
HTML header/body here
31
Script Functions
ltscript language"javascript"gt function
validEntries() // Alert the user when they
dont name the plan. if (document.frmAttackPla
nner.txtName.value "") alert ("Please
enter a name for your attack")
document.frmAttackPlanner.txtName.select()
return false more functions
return true lt/scriptgt HTML
header/body here
32
Script Functions (cont.)
ltscript language"javascript"gt 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
lt/scriptgt HTML header/body here
33
Script Functions (cont.)
ltscript language"javascript"gt function
validEntries() previous functions
// There's no need to validate the attack
location // because it has a default
value. more functions return
true lt/scriptgt HTML header/body here
34
Script Functions (cont.)
ltscript language"javascript"gt function
validEntries() previous functions
var toolChecked false var toolValue ""
// Save this value for the database update.
for (var i0 iltdocument.frmAttackPlanner.optTool.
length i) if (document.frmAttackPlanner
.optTooli.checked true)
toolChecked true toolValue
document.frmAttackPlanner.optTooli.value
if (toolChecked false)
alert ("Please select a tool.") return
false more functions
lt/scriptgt
35
Script Functions (cont.)
ltscript language"javascript"gt 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.frm
AttackPlanner.chkReviewed.select() return
false more functions
lt/scriptgt
36
Script Functions (cont.)
ltscript language"javascript"gt function
validEntries() previous functions
var triesValue parseInt(document.frmAttackPla
nner.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 lt/scriptgt
37
Script Functions (cont.)
ltscript language"javascript"gt 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.txt
Name.value "\n\tDate\t"
dateValue "\n\tLocation\t"
document.frmAttackPlanner.lstLocation.options
document.frmAttackPl
anner.lstLocation.selectedIndex.text
"\n\tTool\t" toolValue
"\n\tTries\t" triesValue
"\nGood luck!") else alert ("Wise
move now, make some changes.") return
false lt/scriptgt
38
An Image Swapper
39
lthtmlgt ltheadgt lttitlegtIS 341 - Home
Pagelt/titlegt ltscript type"text/javascript"
language"Javascript"gt lt!-- 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.images0.srcseal.
src // --gt lt/scriptgt lt/headgt ltbody
class"main"gt some other stuff lta
href"http//www.calvin.edu"
onMouseOver"setSeal(latinSeal)"
onMouseOut"setSeal(englishSeal)"gt ltimg
src"../../images/calvin-seal.gif" alt"I prefer
the Latin" width"95px"gt lt/agt some other
stuff lt/bodygt lt/htmlgt
index.html
40
JavaScript Reference Material
  • JavaScript data types (Netscape 2.0)
  • Boolean true, false
  • NumberInteger 1, 0, 1, 2, 3
  • NumberFloating Point 3.141, -3.01, 36e9
  • NumberOctal 05, 06, 07, 010
  • NumberHexadecimal 0x8, 0x9, 0xA, 0xB
  • String "cat", "dog", ""
  • Null null
  • A JavaScript Reference/Tutorial
  • http//www.w3schools.com/js/

41
Client/Server Architectures
Server-side processing
Client-side processing
Network
server
client
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
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
HTTP A Static Page
GET/ IS/341/index.html HTTP/1.1 User-Agent
Mozilla/5.0 Host myhost.calvin.edu Accept /
Date 8/12/03
Port 80
HTTP Server
Web Browser
Network
File System
server
client
HTTP/1.1/200 Server Apache/2.0 Content-type
text/html Date 8/12/03 ltHTMLgt The HTML
source code lt/HTMLgt
45
HTTP Client-Side Processing
GET/ acme/orders.html HTTP/1.1 User-Agent
Mozilla/5.0 Host myhost.calvin.edu Accept /
Date 8/12/03
Port 80
HTTP Server
Web Browser
Network
File System
server
client
HTTP/1.1/200 Server Apache/2.0 Content-type
text/html Date 8/12/03 ltHTMLgt The HTML
source code with scripts lt/HTMLgt
46
HTTP Server-Side Processing
POST/ index.html HTTP/1.1 User-Agent
Mozilla/5.0 Host myhost.calvin.edu Accept /
Date 8/12/03 q22calvincollege22
Port 80
HTTP Server
Application Processor
Web Browser
Network
File System
server
client
HTTP/1.1/200 Server Apache/2.0 Content-type
text/html Date 8/12/03 ltHTMLgt The HTML
source code lt/HTMLgt
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, 2003
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\
http//pella.calvin.edu/
C\inetpub
C\acme
http//pella.calvin.edu/acme
C\inetpub\wwwroot
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
HTTPS
  • HTTPS is HTTP working over the secure sockets
    layer (SSL).
  • SSL provides
  • Encryption
  • Authentication

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, 2003
52
Client/Server Architectures
Client-side processing
HTTP Server
Application Processor
Network
File System
server
client
53
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_db
    connection.asp)

54
Acme New User Registration
55
AcmeNewUser.aspx (1)
56
AcmeNewUser.aspx (2)
57
AcmeNewUser.aspx.vb
58
AcmeNewUser.aspx.vb (2)
59
Acme Products Table
60
Products.aspx (1)
61
Products.aspx.vb
62
Products.aspx.vb (2)
63
.Net Framework
  • Microsofts network-oriented development
    architecture
  • Components
  • Common language runtime
  • Class library

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, 2003
65
VB.Net
  • Not just for GUIs anymore
  • VB.Net ! VB6
  • VB.Net ? Java
  • Compiled, server or client-side
  • Integrated with Microsofts .Net framework and
    development tools

66
VB.Net Data Types
Dim b As Boolean b True Label1.Text
"Boolean " _ b.ToString() "ltbrgt Dim d As
DateTime d DateTime.Now Label1.Text
"DateTime " _ d.ToString() "ltbrgt Dim i As
Integer i 10 Label1.Text "Integer " _
i.ToString() "ltbrgt Dim j As Double j
3.14159 Label1.Text "Double "
_ j.ToString() "ltbrgt Dim s As String s "a
string" Label1.Text s "ltbrgt"
67
VB.Net Control Structures
'Print out an encouraging message. If
DateTime.Now.DayOfWeek.ToString() "Saturday"
Then Label1.Text "ltpgtTake heart, it's
Saturday!lt/pgt" End If 'Now, count from 10 to
1. Label1.Text "ltpgtWatch me count down from
10ltbrgt" Dim count As Integer For count 10 To 1
Step -1 Label1.Text count.ToString() "
" Next Label1.Text "lt/pgt"
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.T
ext "ltpgt" My_Procedure("something to print
out") Label1.Text "ltbrgtMy_Function returns "
_ My_Function(1).ToString() Label1.Text
"lt/pgt"
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
ASP.Net Processing
12. Initial request by browser and initial
response by server.
IIS Server
ASP.Net Processor
Network
File System
server
client
34. Postback event/arguments and dynamic
response.
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
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
A Simple Example (cont.)
74
A Simple Example
75
A Simple Example (cont.)
76
A Simple Example (cont.)
77
ASP.Net in VS.Net
78
Web Forms
ltform id"Form1 method"post
runat"server"gt ASP.Net objects go
here lt/formgt
79
Server Controls
  • Common ASP.Net Server controls
  • Label
  • TextBox
  • TextField
  • Checkbox
  • RadioButton
  • SubmitButton
  • ResetButton

80
Server Controls (cont.)
ltasptextbox id"txtFirst" style"Z- "
tabIndex"1" runat"server MaxLength"25
Height"24 Width"128px"gt lt/asptextboxgt
81
Validation Controls
  • Common ASP.Net Validation controls
  • Required field
  • Range
  • Compare
  • Regular Expression
  • Custom

82
Validation Controls (cont.)
83
Validation Controls (cont.)
84
Custom Validators
85
Custom Validators (cont.)
function ValidateUsername (val, args) var
currentUsername new String()
args.IsValidfalse currentUsername.valuedocum
ent.Form1.txtUsername.value if
(currentUsername.value.length lt 6)
document.Form1.txtUsername.select() else
args.IsValidtrue
86
Event Handlers
  • Common ASP.Net Events
  • Button clicking
  • Text entry
  • Field validation
  • Document loading

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
databaseltbr /gt" _
txtFirst.Text " " txtMI.Text _
" " txtLast.Text "..." End If End
Sub
88
Event Handlers (cont.)
Private Sub CustomValidator1_ServerValidate(ByVal
source As _ System.Object, ByVal args As
_ System.Web.UI.WebControls.ServerValidateEventAr
gs) _ Handles CustomValidator1.ServerValidate
If txtUsername.Text.Length lt 6 Then
args.IsValid False Else args.IsValid
True End If End Sub
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
Impedance Mismatch
  • Relational databases
  • fields
  • records
  • tables
  • General-purpose programming languages
  • standard data types
  • classes

pi
3.14159
1
2
3
4
91
ADO.Net
  • ActiveX Data Objects
  • Microsofts generic database API
  • Comparisons
  • ADO.Net vs ODBC/JDBC
  • ADO.Net vs ADO

92
ADO.Net Classes
  • Connected Data
  • Connection
  • Command
  • Data Reader
  • Data Adaptor
  • Disconnected Data
  • Data Set
  • Data Table
  • Data Row

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
SqlConnection
Me.SqlConnection1 New System.Data.SqlClient.SqlC
onnection Me.SqlConnection1.ConnectionString
"workstation idPELLApacket "
_ "size4096data sourcePELLApersist security
infoTrue" _ "initial catalogacmeuser
idaccountIDpasswordpassword"
  • All interactions between the VB program and the
    database will be done through this object.
  • Connections should be closed when no longer
    needed.

95
SqlCommand
Me.SqlSelectCommand1 New System.Data.SqlClient.S
qlCommand Me.SqlSelectCommand1.Connection
Me.SqlConnection1 Me.SqlSelectCommand1.CommandTex
t _ "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
SqlDataReader
Dim dataReader As System.Data.SqlClient.SqlDataRea
der Me.SqlConnection1.Open() dataReader
SQLCommand.ExecuteReader() While
dataReader.Read() access row values with
dataReader.GetXXX(index) End While Me.SqlConnect
ion1.Close()
  • A DataReader is a forward-only, read-only window
    into the database.
  • They can contain tables resulting from many
    queries.

97
Using a DataReader
1. Connection
SQL Server
VB.Net
  • 3. The DataReader provides high-speed, one-way
    data flow.

98
SqlDataAdaptor
Me.SqlDataAdapter1 New System.Data.SqlClient.Sql
DataAdapter Me.SqlSelectCommand1 New
System.Data.SqlClient.SqlCommand Me.SqlConnection1
New System.Data.SqlClient.SqlConnection Me.SqlD
ataAdapter1.SelectCommand Me.SqlSelectCommand1
create a dataset Me.SqlDataAdapter1.Fill(DataSe
t1, someResultname") use the dataset
  • DataAdaptors mediate database/program
    communication.
  • It supports the creation and resynching of
    disconnected data sets.

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
Using a DataAdaptor/DataSet
1. Connection
SQL Server
VB.Net
DataSet
  • 3/4. The DataAdaptor supports disconnected
    two-way interaction.

101
A Simple Example
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.SQLDataRea
der Me.SQLConnection1.Open() dataReader
Me.SqlSelectCommand1.ExecuteReader()
Label2.Text ltpgtOur favorite Acme
characterlt/pgt While (dataReader.read())
Label2.Text dataReader.GetString(0)
Label2.Text dataReader.GetString(1)
Label2.Text dataReader.GetString(2)
ltbr /gt Label2.Text ltimg
src/acme/secure/images Label2.Text
dataReader.GetString(3) Label2.Text
altmy favorite coyotegt End While End Sub
103
A Simple Example (cont.)
104
(No Transcript)
105
(No Transcript)
106
(No Transcript)
107
Another Example
108
(No Transcript)
109
(No Transcript)
110
(No Transcript)
111
DataAdaptor/DataSet Example
112
DataAdaptor/Set Code
Public Class Products Inherits System.Web.UI.Page
Code created by Visual Studio
ltSystem.Diagnostics.DebuggerStepThrough()gt
Private Sub InitializeComponent()
Me.SqlDataAdapter1 New System.Data.SqlClient.Sql
DataAdapter Me.SqlSelectCommand1 New
System.Data.SqlClient.SqlCommand
Me.SqlConnection1 New System.Data.SqlClient.SqlC
onnection Me.SqlDataAdapter1.SelectCommand
Me.SqlSelectCommand1 Me.SqlSelectCommand1.Conn
ection Me.SqlConnection1 Me.SqlConnection1.C
onnectionString "workstation idPELLApacket "
_ "size4096data sourcePELLApersist
security infoTrue" _ "initial
catalogacmeuser idaccountIDpasswordpassword"
End Sub other stuff (including the
page_init subroutine) End Class
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(DataSet
1, "dsProducts") aTable DataSet1.Tables(0)
Label3.Text"lttable border1 cellpadding5
width100gtlttrgtltthgtProductlt/thgt _
ltthgtNamelt/thgtltthgtSizelt/thgtltthgtColorlt/thgtltthgtPri
celt/thgtlt/trgt" For Each aRow In aTable.Rows
Label3.Text "lttrgt" Label3.Text
"lttd aligncentergtltimg src""Images/" _
aRow("imageFileName") """ height75pxgtlt/tdgt"
Label3.Text "lttd aligncentergt"
tableValue(aRow("name")) "lt/tdgt"
Label3.Text "lttd aligncentergt"
tableValue(aRow("size")) "lt/tdgt"
Label3.Text "lttd aligncentergt"
tableValue(aRow("color")) "lt/tdgt"
Label3.Text "lttd alignrightgt" _
tableValue(Format(aRow("unitPrice"),
",,.")) "lt/tdgt" Label3.Text
"lt/trgt" Next more stuff here End Sub
114
DataAdaptor/Set Code (3)
Function tableValue(ByVal item As Object) If
(item.ToString() "") Then Return
"nbsp" Else Return item End
If End Function
115
Database Updates
in the Web Form Designer Generated Code
section Me.SqlInsertCommand1 New
System.Data.SqlClient.SqlCommand Me.SqlDataAdapte
r1.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
Database Updates (2)
continued from previous slide Me.SqlInsertComma
nd1.CommandText _ "INSERT INTO Customers(id,
loginId, password, other fields ) VALUES ("
_ "'" uniqueID.ToString() "', " _ "'"
username.Text "', " _ "'" password.Text
"', " _ "'" System.Web.Security.FormsAuthent
ication.HashPasswordForStoringInConfigFile(txtPass
word.Text, "md5")_ "', " "'"
txtPwdHint.Text "') Me.SqlInsertCommand1.Execu
teNonQuery() continued on next slide
117
Database Updates (3)
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
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
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
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. and Sylvester rule
121
Using a DataGrid
1. Connection
SQL Server
VB.Net
DataGrid
Bind
DataSet
  • 3/4. The DataAdaptor supports disconnected
    two-way interaction.

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
Example
124
Example
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
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("SortedC
olumn"), _
ViewState("SortOrder")) DataGrid1.DataBind() En
d Sub Private Sub FillAndBind()
FillSortedDataSet() BindDataGridWithHeaders() E
nd Sub
127
Example Code (cont.)
Private Sub DataGrid1_EditCommand(ByVal source As
Object, _ ByVal e As System.Web.UI.WebControls.Dat
aGridCommandEventArgs) _ 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.DataGridCom
mandEventArgs) _ Handles DataGrid1.CancelCommand
'Reset the datagrid's edit item to nothing.
DataGrid1.EditItemIndex -1 FillAndBind() End
Sub
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.I
tem.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(DataS
et11) 'Turn off editing in the datagrid and
bind the new values. DataGrid1.EditItemIndex
-1 DataGrid1.DataBind() End Sub
129
Example Code (cont.)
Private Sub DataGrid1_SortCommand(ByVal source As
Object, _ ByVal e As System.Web.UI.WebControls.Dat
aGridSortCommandEventArgs) _ 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
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 ltimggt tags
that might be present c.HeaderText
System.Text.RegularExpressions.Regex.Replace(c.Hea
derText, _
"\slt.gt", String.Empty)
'Put the appropriate arrow on the column being
sorted. If c.SortExpression
SortExpression Then If SortDirection
"ASC" Then c.HeaderText " ltimg
src""images/up.gif"" _
border""0""gt"
Else c.HeaderText " ltimg
src""images/down.gif"" _
border""0""gt"
End If End If Next End Sub
131
Example Code (cont.)
Private Sub DataGrid1_PageIndexChanged(ByVal
source As Object, _ ByVal e As System.Web.UI.WebCo
ntrols.DataGridPageChangedEventArgs) _ Handles
DataGrid1.PageIndexChanged 'Move to
appropriate page of the data and refill/bind.
DataGrid1.CurrentPageIndex e.NewPageIndex
FillAndBind() End Sub
132
Dramatization
  • Act out a use case for the application just
    described.
Write a Comment
User Comments (0)
About PowerShow.com