Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
Master in web technology e security - Guido Boella 2
ASP
• Server-side scripting technology diMicrosoft per creare web pages interattive
• Una pagina asp è una pagina contenenteHTML (ma non solo) inframmezzato dascript tag da eseguire sul server
• Possibilità di usare oggetti COM e ADO diWindows e di manipolare documenti XML
Master in web technology e security - Guido Boella 3
ASP
• ASP per IIS e PWS di Microsoft, ma anchealtre piattaforme (Chili!ASP di ChiliSoft)
• Consente facile collegamento con ADO
• Il server riceve una richiesta dal client cheriguarda una pagina .asphttp://www.di.unito.it/date.asp
• La pagina (date.asp) contiene un documentohtml inframmezzato con del codice(VBscript, javascript)
Master in web technology e security - Guido Boella 4
• Prima di inviare il documento, il serveresegue lui stesso le parti di programma inun thread interno
• Il codice genera in output parte deldocumento che viene sostituito agli scripttag
• Parametri ed output gestiti come oggetti daVBscript
• Introduce il concetto di sessione(ma utilizza comunque i cookies)
Master in web technology e security - Guido Boella 5
ISAPI(internet server api)
• Permette legame con dynamic link libraries(DLL) che sono eseguite nello spazio dimemoria del server
• ISAPI filter: permette il controllo delleinformazioni dal client al server (persicurezza) e viceversa
• Una pagina trovata dal server vieneinterpretata dal filtro ISAPI asp.dll che necambia il contenuto
Master in web technology e security - Guido Boella 6
Pagine attive - tread del server
CLIENT
(UA,browser)
Web server
(Apache, IIS)
Macchina del server
programmi
ISAPI filter
.html request
response
Altre applicazioniADO
Master in web technology e security - Guido Boella 9
Logfile169.254.154.181 - - [02/Aug/2000:22:25:52 +0100] "GET /Default.aspHTTP/1.1" 200 2425
169.254.154.181 - - [02/Aug/2000:22:25:52 +0100] "GET/IISSamples/Default/IE.GIF HTTP/1.1" 304 140169.254.154.181 - -[02/Aug/2000:22:27:28 +0100] "GET /asp/Pro ASP 3.0/Chapter08/Connection/Connection.asp?|23|80004005|[Microsoft][Driver_ODBC_Microsoft_Access_97]_Impossibile_trovare_il_file_'(sconosciuto)'. HTTP/1.1" 200 1151
169.254.163.196 - - [02/Aug/2000:23:40:53 +0100] "GET /ASP/Pro ASP3.0/Chapter 10/publishers.xml HTTP/1.1" 304 140
169.254.163.196 - - [02/Aug/2000:23:45:25 +0100] "GET /ASP/Pro ASP3.0/Chapter 11/RecordsetToList.xsl HTTP/1.1" 200 959
169.254.146.182 - - [03/Aug/2000:00:31:19 +0100] "GET /asp/Pro ASP3.0/Chapter 08/Recordsets/Recordset.asp?Action=Fields HTTP/1.1" 200 1345
Master in web technology e security - Guido Boella 11
VBscript• Sottoinsieme del linguaggio Visual Basic di
Microsoft: senza tipi
• Linguaggio interpretato senza compilazioneprecedente per maggiore modificabilità
• Orientato agli oggetti, ma senza classi
• Un solo tipo di dato, implicito: Variantil tipo della variabile dipende dal contesto:string, integer, object, currency, date,boolean
• Operatori per conversione di tipo esplicita
Master in web technology e security - Guido Boella 12
Variabili
• Dichiarazione implicita o esplicita di variabili:Dim x, y, z (return è fine espressione)
• Assegnazionex=1w="stringa" (dichiarazione implicita)
• Array:Dim v(9), k(10,1) (v ha 10 indici, 0 ... 9)ReDim v(20)Redim preserve v(30)
Master in web technology e security - Guido Boella 13
Stringhe
Dim strA, strX
strX = "una"
strA = "sono" & strX & "stringa" & "spezzata _ e molto lunga"
Master in web technology e security - Guido Boella 14
Subroutine e funzioni
• Come in Pascal, si distinguono dalleprocedure le funzioni che restituiscono unvalore
• Il valore di ritorno va assegnato ad unavariabile speciale che ha lo stesso nomedella funzione (come in Pascal)
• Parametri passati per call by reference• Variabili locali hanno la durata della
procedura e sono solo visibili in essa
Master in web technology e security - Guido Boella 15
'subroutine
Sub scrivi (strX, strY)
dim strZ
strZ = strX & strY
response.write(strZ)
End Sub
'funzione
Function square (intX)
square = intX * intX
End Function
Master in web technology e security - Guido Boella 16
Strutture di controllo
If condition Then statement
If condition Then statement statements ...
Endif
If condition Then statementsElse statementsEndif
BLOCCO!
METAVARIABILE!
Master in web technology e security - Guido Boella 17
Select Case expressionCase value
statements...Case value
statementsEnd Select
Select Case strOPCase "+"
x = x + yCase "-"
x = x - yEnd Select
Master in web technology e security - Guido Boella 18
For var = start To finish [Step value]statements
Next
For intX = 1 to 10 Step 2 Response.write(intX)Next
• output135
Master in web technology e security - Guido Boella 19
Do While condition (While o Until)statements
Loop
intX = 3Do While intX > 0
Response.write(intX)intX = intX + 1
Loop• output321
Master in web technology e security - Guido Boella 20
HTML fa parte del programma<html><body>
<% Dim i
for i = 1 to 10 step 2 %>
<BR>passo <%= i %>
<% next %>
</body></html>
Master in web technology e security - Guido Boella 21
Script per Client (IE5)
<html><body>
<script language="VBscript"><!--
'commento
comandi VBscript
-->
</script>
...
</body></html>
COMMENTO HTMLPER COMPATIBILITA'
VBscript NON E' NECESSARIAMENTEIL LINGUAGGIO DI DEFAULT
Master in web technology e security - Guido Boella 22
Script per server
<html><body>
<script language="VBscript" runat="server">Comandi VBscript</script><p>
<% Comandi VBscript
%>
<p>
<% Comandi VBscript %>
Sono le <%= time %>
</body></html>
IL TESTO PRODOTTOSOSTITUISCE LO SCRIPT
LO SCRIPT E' PER ILSERVER
TAG INTERPRETATOSOLO DAL SERVER
TAG CHE RIPORTAVALORE DI UNA
VARIABILE
Master in web technology e security - Guido Boella 23
Non spezzare i tag...
<html><body>
<% Comandi VBscript %>
<p><b>Testo html</b>
<% Comandi VBscript %>
</body></html>
<html><body>
<% Comandi VBscript
Response.write("<p><b>Testo html</b>")
Comandi VBscript %>
</body></html>
2 CONTEXT SWITCH
TESTO HTML SCRITTODA VBscript
Master in web technology e security - Guido Boella 24
Inclusione script
<html><body>
<%@language="VBscript"%>
<script language="VBscript" runat="server" src="/aspscript/script.inc" ></script>
<p>
<!--# include file="/aspscript/script1.inc" -->
<p>
<% response.write square(5) %>
</body></html>
SETTA LINGUAGGIODI DEFAULT
INCLUSIONE SSI STYLE:SSI PROCESSATE PRIMA
DI ASP
Master in web technology e security - Guido Boella 25
Efficienza e sicurezza• Con Windows2000 i file html possono essere
denominati .asp: prima di parsificarli oeseguirli si controlla la presenza del tag <%
• I file asp vengono compilati e mantenuti nellacache per essere eseguiti fino a modifiche
• I COM creati in pagina asp possono essere"run out-of-process"
• Asp script e client-side script possono esserecodificati con BASE64 encription. Lo scriptengine li decodifica runtime
Master in web technology e security - Guido Boella 26
Oggetti intriseci di ASP• Request: mette a disposizioni informazioni
mandate da client tramite metodi e variabili:– HTTP metavariables– cookies– query string appese a URL– certificati SSL
• Response: informazioni mandate al client:– header http– cookies– output (message body): Response.write
(Sostituiscono stdin e stdout di CGI)
Master in web technology e security - Guido Boella 27
• Application: creato al caricamento di asp.dllcon la prima richiesta. Contiene variabili eoggetti globali accessibili ad ogni script
• Session: oggetto associato a ciascun utente alprimo collegamento. Contiene le informazioniaccessibili a tutte le pagine visitate da un datoutente. Timeout stabilisce la sua durata dopoultimo collegamento.
• Server: offre metodi per creare nuovi processie oggetti COM (e ADO)
• ASPError: informazione su ultimo errore
Master in web technology e security - Guido Boella 28
Collection di Request
• Query string: coppie attributo-valore inviateda form con metodo GET (URL munging)
• Form: coppie attributo valore inviate daform con metodo POST
• Cookies
• ServerVariables: metavariabili HTTP
• ClientCertificate
ESEMPIO
Master in web technology e security - Guido Boella 29
Collection
<TABLE CELLPADDING=0 CELLSPACING=0>
<%
For Each keyItem In Request.servervariables()
strItemValue = Request.servervariables(keyItem)
Response.Write "<TR><TD>" & keyItem & " = " &strItemValue & "</TD></TR>"
Next
%>
</TABLE>
Master in web technology e security - Guido Boella 30
Query stringWhat is the capital city of Sweden? <BR>
<A HREF="q2answer.asp?answer=Reykavik&rw=wrong">Reykavik</A>
<A HREF="q2answer.asp?answer=Stockholm&rw=right">Stockholm</A>
<%
Response.Write("Your answer was " & Request.QueryString("answer") &"...<BR>")
If Request.QueryString("rw")="right" Then
Response.Write("That's the correct answer!")
Else
Response.Write("No, that's the wrong answer.")
End If
%>
Master in web technology e security - Guido Boella 31
Form
<%
For Each Item in Request.Form
Response.Write("For element '" & Item &_
"' you've entered the value '" &Request.Form(Item) &_
"'<BR>")
Next
%>
Master in web technology e security - Guido Boella 32
Multivalue form<FORM NAME="MultiChoice" ACTION="DealWithForm3.asp"
METHOD="POST">
<H2>Which continents have you visited? </H2><BR>
<INPUT NAME="Cnent" TYPE=CHECKBOX VALUE="Africa">Africa <BR>
<INPUT NAME="Cnent" TYPE=CHECKBOX VALUE="NorthAmerica"> North America <BR>
<% Response.Write("You've really been to all these places?" & "<BR>")
For i = 1 To Request.Form("Cnent").Count
Response.Write (Request.Form("Cnent")(i) & "<BR>")
Next
Response.Write("<BR>" & "Impressive...")
End If %>
Master in web technology e security - Guido Boella 33
Collection e variabili di Response• Cookies: le coppie attributo valore inviate
dal server allo user agent client
• Buffer: output bufferizzato fino a flush (pergestire errori runtime dello script)
• Content-type = mime-type ("text/xml")
• CacheControl = public o private
• Expires minuti (per proxy servers)
• PICS("...") (per filtrare contenuto pagina)
• status = messaggio (200 OK, 404 not found)
Master in web technology e security - Guido Boella 34
Metodi di Response• AddHeader("name", "content") va usato
prima di spedire il contenuto della pagina
• End(), Flush()
• Redirect("url") 303 Object Moved url
• Write(string)
• BinaryWrite(Array) per inviare immaginisenza conversione di testo
Master in web technology e security - Guido Boella 35
<FORM ACTION="show.asp"METHOD="POST">firstname: <INPUT TYPE="TEXT" NAME="first">lastname: <INPUT TYPE="TEXT" NAME="last"><INPUT TYPE="SUBMIT"></FORM>
<% firstname = Request.form("first") lastname = Request.form("last") Response.write(Request.form) For each objitem in Request.form Response.write objitem & ":" & Request.form(objitem) For intloop = 1 to Request.form.count Response.write Request.form(intloop) Next %>
first=Guido&last=Boella ...
show.asp
FORM HTML
OUTPUT
Master in web technology e security - Guido Boella 36
Cookies• Vanno creati prima di creare output in quantosi trovano nell'header
intCount = Request.Cookies("count")Response.Cookies("count") = intCount + 1Response.Cookies("count") .domain="di.unito.it"Response.Cookies("count") .domain="/docsrv/guido/"Response.Cookies("count") .expires = #date#Response.Write "Hai visitato questo sito " & _
intCount & "volte"VIRTUAL
PATH
Master in web technology e security - Guido Boella 37
<FORMACTION=<% =Request.ServerVariables("SCRIPT_NAME") %>METHOD="GET">login: <INPUT TYPE="TEXT" NAME="login"VALUE = <% = Request.QueryString("login") %>passwd: <INPUT TYPE="TEXT" NAME="passwd"><INPUT TYPE="SUBMIT"></FORM>
<% login = Request.form("login") passwd = Request.form("passwd") Response.Cookies("loginInfo")("login")= login Response.Cookies("loginInfo")("passwd")= passwd %>
INDIRIZZO DELLOSCRIPT
Master in web technology e security - Guido Boella 38
•SECURE SOCKET LAYER REDIRECT (PORT 443)
<% if Request.ServerVariables("SERVER_PORT") = 443 THEN
Response.Redirect("/securepages/default.asp") else Response.Redirect("/normalpages/default.asp") %>
• Genera un messaggioHTTP/1.1 302 Object Movedlocation /securepages/default.asp
•Stesso effetto su lato client<META HTTP-EQUIV="REFRESH" CONTENT="0;URL=/securepages/default.asp">
Master in web technology e security - Guido Boella 39
L'oggetto Application• METODI E VARIABILI:
Contents: collection di variabili(application("nomevar"))lock(), unlock(): solo una pagina .asp puòessere eseguita per impedire interferenze
• EVENTI:onStart: subroutine eseguita alla creazionedell'oggetto ApplicationonEnd: eseguita alla chiusura
• File di inizializzazione: GLOBAL.ASA
Master in web technology e security - Guido Boella 40
L'oggetto Session• METODI e VARIABILI:
Contents: collection di variabili(session("nomevar"))Timeout: durata session; default 10 min.
• EVENTI:onStart: subroutine eseguita alla creazionedell'oggetto SessiononEnd: eseguita alla chiusura
• File di inizializzazione: GLOBAL.ASA
Master in web technology e security - Guido Boella 41
Global.asa<SCRIPT LANGUAGE=VBScript RUNAT=Server>
Sub Application_OnStart Application("visits") = 0 Application("Active")= 0End Sub
Sub Application_OnEnd
End Sub CONTINUA
•VARS.ASPThere have been <B><%=Session("VisitorID")%></B> total visits to this site.<BR>You are one of <B> <%=Application("Active")%></B> active visitors.<BR>Your session started at <%= Session("Start") %>
NELLA STESSA DIRECTORY DI GLOBAL.ASA
Master in web technology e security - Guido Boella 42
Sub Session_OnStart Session.Timeout = 1 Session("Start")=Now Application.lock Application("visits")= Application("visits") + 1 intTotal_visitors = Application("visits") Session("VisitorID") = intTotal_visitors Application("Active")= Application("Active") + 1 Application.unlockEnd Sub
Sub Session_OnEnd Application.lock Application("Active")= Application("Active") - 1 Application.unlockEnd Sub</SCRIPT>
Master in web technology e security - Guido Boella 43
SessionID• Asp mantiene automaticamente la gestione delle
Session grazie ai Cookies
• Se non è attiva la ricezione dei Cookies nelbrowser, la Session non funziona
• Il server assume che richieste HTTP con stessosessionid arrivino dallo stesso utente
• Il Cookie è generato in maniera casuale perevitare interferenze: può essere intercettato esfruttato da hacker per spacciarsi per l'utente
• Connessione SSL permette il criptaggiodell'identificatore Session
Master in web technology e security - Guido Boella 44
• Il cookie sessionID viene inviato solo almomento di una assegnazione alla collectionsession (e.g., session("user")="guido"): masenza buffering l'header è inviato senza idHTTP_COOKIE: … ASPSESSIONIDFFFESKDR=FMCLMFDAKHFDCGHDCCPAPOCC;
• La session espira in base al valore disession.timeout (default=20min) o alla chiusuradel browser (cookie ha expires = 0)
• La session è associata al singolo server:problemi con le server farm; violo load balanceinviando stesso sessionid a stessa macchina
Master in web technology e security - Guido Boella 45
Esempio session<% response.expires = -10000
if NOT request.querystring("user")="" then
session.timeout=1
session("user")=request.querystring("user")
response.write "You are " & session("user") & " "
response.write "<br><a href=" &request.servervariables("SCRIPT_NAME") & ">Go back to startpage</a>"
end if
if session("user") = "" then %>
<form method="get" action="<%=request.servervariables("SCRIPT_NAME") %>">
<input type=text name="user">what's your name?</input></form><%
else
response.write "<Br>Hello " & session("user")
end if %>
DISABILITO CACHE
Durata session 1min
Master in web technology e security - Guido Boella 46
L'oggetto Server• METODI e VARIABILI:
createObject("id"): crea istanza di oggetto erestituisce reference (set). id è cslid "{RB23...}" oProgid: "ADODB.Connection" (vendor.component)
• Execute("url"), Transfer("url"): trasferisce ilcontrollo a script url assieme al contesto (e ritorna)
• GetLastError(): reference ad errore
• File di errore è chiamato tramite server.Transfer:C:¥WINDOWS¥HELP¥common¥400.htm ecc.
• Per eliminare un oggetto x e recuperare la memoria:set x = nothing
Master in web technology e security - Guido Boella 47
Counter<% Dim objFSO, objCountFile ' object vars for FSO and File
Dim strCountFileName ' filename of count text file
Dim iCount ' count variable
strCountFileName=Server.MapPath(Request.ServerVariables("SCRIPT_NAME") & ".cnt")
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
' Open the file as a text stream (1 = ForReading, True = Create)
Set objCountFile = objFSO.OpenTextFile(strCountFileName, 1, True)
If Not objCountFile.AtEndOfStream Then iCount =CLng(objCountFile.ReadAll)
Else
iCount = 0
End If
objCountFile.Close CONTINUA
Master in web technology e security - Guido Boella 48
Set objCountFile = Nothing
iCount = iCount + 1
Set objCountFile = objFSO.CreateTextFile(strCountFileName, True)
objCountFile.Write iCount
objCountFile.Close
Set objCountFile = Nothing
Set objFSO = Nothing
Response.Write "This page has been visited by " & iCount _
& " people"
%>
Master in web technology e security - Guido Boella 49
Script di benvenuto
<%
Dim dHour
dHour = Hour(Now)
If dHour < 12 Then
Response.Write "Good morning!"
ElseIf dHour < 17 Then
Response.Write "Good afternoon!"
Else
Response.Write "Good evening!"
End If
%> We hope you are enjoying our sample code.<BR>
<BR> If you are curious it is currently <%= Time() %> on <%= Date()%>.<BR>
Master in web technology e security - Guido Boella 50
Time counter<% If Request.QueryString("time") = "" Then %>You ... <BR><% Elsedifftime = DateDiff("s", Request.QueryString("time"), Now()) %>You spent <%= difftime %> seconds.<BR>
<% End If %><BR><A HREF="time.asp?time=<%=Server.URLEncode(Now())%>">How long have I spent on thispage?</A><BR>
<% totaltime = session("time") session("time") = difftime + totaltime
application.lock
atotaltime = application("atime")
application("atime") = difftime + atotaltime
application.unlock %><BR>You have spent<%= session("time") %> seconds during this session.
Master in web technology e security - Guido Boella 51
File System• I comandi per gestire i files sono metodi
dell'oggetto "Scripting.FileSystemObject"
• Per manipolare files occorre quindi creare unaistanza dell'oggetto file system
• Metodi:openTextFile(nomefile, r/w, create): apre il filenomefile ("c:¥asp¥file.txt") creando un oggettostream corrispondente. r/w: forReading=1,forWriting=2, forAppending=8. create è true ofalsecreateTextFile(nomefile, create): crea lo streamdel file nomefile
Master in web technology e security - Guido Boella 52
FileSystemObject
• Metodi:fileExists(nomefile): controlla esistenza diun filedeletefile(nomefile): cancella il file
Master in web technology e security - Guido Boella 53
Oggetto stream• Uno stream è creato dal metodo di apertura
file del fileSystemObject o daopenAsTextStream di un oggetto file
• Variabili:atEndOfStream: vero se lo stream è vuoto oè stato letto tutto
• Metodi:readall, readline: lettura file o lineawrite stringa: scritturawriteline stringa: scrittura con a capoclose(): chiusura stream
Master in web technology e security - Guido Boella 54
Stream
• Uno stream è un flusso di caratteri leggibilio scrivibili
• Con ADO2.1 esistono solo streamcorrispondenti a files
• Con ADO2.5 si possono usare stream inmemoria senza un file corrispettivo
• Gli oggetti Request e Response diventanostream di input e output
Master in web technology e security - Guido Boella 55
Oggetto file• Un oggetto file è creato con il metodo
getfile(nomefile) dell'oggettofileSystemObject
• L'oggetto file contiene le proprietà del file epermette di accedere al contenuto creandouna stream con openAsTextFile
• Variabili:name, dateLastModified, type
• MetodiopenAsTextFile(): crea stream
Master in web technology e security - Guido Boella 56
Gestione file
<% Dim objFSODim objFileDim dateModifiedSet objFSO = Server.CreateObject("Scripting.FileSystemObject")Set objFile = objFSO.GetFile(Server.MapPath("modified.asp"))dateModified = objFile.DateLastModified %>This file was modified on <%= dateModified %> or <%FormatDateTime(dateModified, 1) %><% Set objFile = NothingSet objFSO = Nothing %>
Master in web technology e security - Guido Boella 57
Text file<!--METADATA TYPE="TypeLib" FILE="c:¥Programmi¥File
comuni¥System¥ADO¥MSADOr15.dll"-->
<% strTextFile = Server.MapPath("MyFile.txt")
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
If Len(Request.Form("cmdUpdate")) Then
strNewText = Request.Form("txtContent")
arrLines = Split(strNewText, vbCrLf)
Set objTStream = objFSO.OpenTextFile(strTextFile, 2)
For intLine = 0 To UBound(arrLines)
strThisLine = arrLines(intLine)
If Len(strThisLine) > 4 Then objTStream.WriteLine Mid(strThisLine, 6)
Next
objTStream.Close
End If
Master in web technology e security - Guido Boella 58
<FORM ACTION="<% = Request.ServerVariables("SCRIPT_NAME") %>"METHOD="POST">
The contents of the disk file <B><% = strTextFile %></B> are:<P>
<TEXTAREA NAME="txtContent" ROWS="10" COLS="50" >
<% Set objTStream = objFSO.OpenTextFile(strTextFile, 1)
Do While Not objTStream.AtEndOfStream
intLineNum = objTStream.Line
strLineNum = Right("00" & CStr(intLineNum), 3)
strLineText = objTStream.ReadLine
Response.Write strLineNum & ": " & strLineText & vbCrLf
Loop
objTStream.Close
%></TEXTAREA><P>
<INPUT TYPE="SUBMIT" NAME="cmdUpdate"VALUE=" ">
</FORM></BODY></HTML>s
Master in web technology e security - Guido Boella 59
Oggetto Dictionary
• Una tabella associativa in ASP è unaistanze dell'oggetto Dictionary:"Scripting.Dictionary"
• Variabili:keys: restituisce l'array delle chiaviitems: restituisce l'array dei valoricount: numero elementi della tabella
Master in web technology e security - Guido Boella 60
Oggetto Dictionary
• Metodi:item("chiave"): il valore associato allachiave. Abbreviazione: ("chiave")add chiave, valore: inserisce la coppiachiave-valore nella tabellaexists("chiave"): vero se alla chiave èassociato un valore nella tabella
Master in web technology e security - Guido Boella 61
Oggetto Dictionary
<% Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.Add "Apple", "Red"
objDictionary.Add "Lemon", "Yellow"
strValue = objDictionary.Item("Apple")
if objDictionary.Exists("Apple") then
objDictionary.Item("Apple") = "Green"
end if
arKeys = objDictionary.keys
for i = 0 to objDictionary.Count -1
Response.Write "<BR>Key = " & arKeys(i) & " -- Value = " &objDictionary.Item(arKeys(i))
next
arItems = objDictionary.items
%>
Master in web technology e security - Guido Boella 62
Gestione directory
<% strPathInfo = Request.ServerVariables("PATH_INFO")strPhysicalPath = Server.MapPath(strPathInfo)Set objFSO = CreateObject("Scripting.FileSystemObject")set objFile = objFSO.GetFile(strPhysicalPath)set objFolder = objFile.ParentFolderset objFolderContents = objFolder.Files%><TABLE><%For Each objFileItem in objFolderContents
%><TR><TD><A HREF="<%= objFileItem.Name %>">
<%= objFileItem.Name %></A></TD><TD><%= objFileItem.type %></TD><TD><%= objFileItem.size %></TD><TD><%= objFileItem.DateLastModified %></TD></TR>
<% Next %>
Master in web technology e security - Guido Boella 63
VBscript non e' l'unico linguaggio<%@ LANGUAGE = PerlScript %><html><BODY> <BODY BGCOLOR=#FFFFFF><TABLE CELLPADDING=3 BORDER=0 CELLSPACING=0><TR VALIGN=TOP ><TD WIDTH=400></TD></TR></TABLE><%
for ($i = 3; $i < 8; $i++) {%>
<font size=<%= $i %>>"Hello World!"
</font><BR>
<% } %></BODY></HTML>
Master in web technology e security - Guido Boella 64
VBscript non e' l'unico linguaggio<%@ LANGUAGE = Javascript %><html><BODY> <BODY BGCOLOR=#FFFFFF><TABLE CELLPADDING=3 BORDER=0 CELLSPACING=0><TR VALIGN=TOP ><TD WIDTH=400></TD></TR></TABLE><%
for (i = 3; i < 8; i++) {%>
<font size=<%= i %>>"Hello World!"
</font><BR>
<% } %></BODY></HTML>
Master in web technology e security - Guido Boella 67
Shopping cart
<% 'Sub AddItemToCart(iItemID, iItemCount) If dictCart.Exists(iItemID) Then
dictCart(iItemID) = dictCart(iItemID) + iItemCountElse
dictCart.Add iItemID, iItemCountEnd IfResponse.Write iItemCount & " of item # " & iItemID & " have beenadded to your cart.<BR><BR>" & vbCrLf
End Sub
Master in web technology e security - Guido Boella 68
Sub RemoveItemFromCart(iItemID, iItemCount) If dictCart.Exists(iItemID) Then
If dictCart(iItemID) <= iItemCount ThendictCart.Remove iItemID
ElsedictCart(iItemID) = dictCart(iItemID) - iItemCount
End IfResponse.Write iItemCount & " of item # " & iItemID & " have
been removed from your cart.<BR><BR>" & vbCrLfElse
Response.Write "Couldn't find any of that item yourcart.<BR><BR>" & vbCrLfEnd If
End Sub
Master in web technology e security - Guido Boella 69
Sub ShowItemsInCart()Dim KeyDim aParameters ' as Variant (Array)Dim sTotal, sShipping %>
<TABLE Border=1 CellPadding=3 CellSpacing=1> <TR><TD>Item #</TD> ... </TR> <%sTotal = 0For Each Key in dictCart
aParameters = GetItemParameters(Key) %><TR><TD ALIGN="Center"><%= Key %></TD>
<%= aParameters(1) %><%= dictCart(Key) %> <A HREF="./shopping.asp?action=del&item=<%= Key%>
&count=1">Remove One</A>   <TD>$<%= aParameters(2) %></TD>
<TD>$<%=FormatNumber(dictCart(Key) * CSng(aParameters(2)),2) %></TD></TR><%sTotal = sTotal + (dictCart(Key) * CSng(aParameters(2)))
Next
Master in web technology e security - Guido Boella 70
<% sTotal = sTotal + (dictCart(Key) * CSng(aParameters(2)))NextIf sTotal <> 0 Then
sShipping = 7.5Else
sShipping = 0End IfsTotal = sTotal + sShipping %>
$<%= FormatNumber(sShipping,2) $<%= FormatNumber(sTotal,2) %></TD></TR></TABLE><% End Sub
Master in web technology e security - Guido Boella 71
Sub ShowFullCatalog()iItemCount = 3 %><TABLE Border=1 CellPadding=3 CellSpacing=1> <TR><TD>Image</TD> … </TR><% For I = 1 to iItemCount
aParameters = GetItemParameters(I) %> <TR> <TD><IMG SRC="<%= aParameters(0) %>"></TD> …
<TD><A HREF="./shopping.asp?action=add&item=<%= I%>&count=1">Add this to my cart!</A></TD> </TR><% Next %></TABLE><%
End Sub
Master in web technology e security - Guido Boella 72
GetItemParameters(iItemID)Dim aParameters ' 3 stringhe image path, description, price
Select Case iItemID Case 1
aParameters = Array("./images/shop_shirt.gif", "ASP T-Shirt", "15.00") Case 2
aParameters = Array("./images/shop_kite.gif", "ASP Kite", "17.50") Case 3
aParameters = Array("./images/shop_watch.gif", "ASP Watch", "35.00")End Select
GetItemParameters = aParametersEnd Function%>
Master in web technology e security - Guido Boella 73
<%If IsObject(Session("cart")) Then
Set dictCart = Session("cart")Else
Set dictCart = Server.CreateObject("Scripting.Dictionary")End IfsAction = CStr(Request.QueryString("action"))iItemID = CInt(Request.QueryString("item"))iItemCount = CInt(Request.QueryString("count"))
Select Case sActionCase "add"
AddItemToCart iItemID, iItemCountShowItemsInCart%><A HREF="./shopping.asp?action=">Continue Looking</A><A HREF="./shopping.asp?action=checkout>Checkout"></A>
Master in web technology e security - Guido Boella 74
<% Case "del"RemoveItemFromCart iItemID, iItemCountShowItemsInCart
Case "viewcart"ShowItemsInCart
Case "checkout"PlaceOrder
Case Else ' ShopShowFullCatalog
End Select
' Return cart to Session for storageSet Session("cart") = dictCart%>
Master in web technology e security - Guido Boella 76
SQL: Structured Query Language(SeQueL)
• Linguaggio per l'interazione con database tramiteActiveX Data Object (ADO)
• Operazioni:– leggere informazioni
– selezionare informazioni
– cambiare e cancellare dati
– (modificare la struttura del database)
• Ispirato al linguaggio naturale
• Sintassi: keyword arguments keyword arguments...
Master in web technology e security - Guido Boella 77
Category ID Room ID Description ManufacturerSports Equipment Bedroom Exercise Bike Adventure WorksFurniture Living Room Gray three-cushion sofa Fitch & MatherSports Equipment Garage Mountain Bike Crawford & BicyclesElectronic Den Computer Bits, Bytes & Chips, Inc.Tool Garage Cordless drill ProElectron, Inc.Furniture Dining Room Ebony inlaid table unknownTool Garage Table saw Shear SavvyCollectible Den Baseball card collectionJewelry Bedroom Pearl neclaceElectronic Living Room Audio-Visual Receiver AVTech
Furniture Living Room Gray three-cushion sofa Fitch & Mather
RECORD
TABELLAFIELD
Master in web technology e security - Guido Boella 78
Select
• Reperimento dati specificando:– tabella
– colonne tabella
– ordine
– restrizioni
• SELECT * FROM household inventory(prendi tutti (*) i record (con tutte le colonne) dallatabella household invenctory)
Master in web technology e security - Guido Boella 79
• Selezione campi (colonne)SELECT description, manufacturer FROMhousehold inventory
• Selezione recordSELECT roomid, description FROM householdinventory WHERE roomid = livingroom
SELECT roomid, description FROM householdinventory WHERE date BETWEEN #20/01/90#AND #01/03/99#
SELECT roomid, description FROM householdinventory WHERE roomid LIKE '%room'
room iddiventaroomid
Master in web technology e security - Guido Boella 80
• Ordinamento del recordsetSELECT roomid, description FROM householdinventory ORDER BY roomidSELECT roomid, description FROMhouseholdinventory ORDER BY date DESC
• Unione tabelle: JOINSELECT a.roomid AS roomid, b.manufacturer ASmanufacturer FROM a INNER JOIN b ONa.description = b.description
Master in web technology e security - Guido Boella 81
• Inserimento di un recordINSERT INTO inventory (roomid, description,manufacturer, ...) VALUES ('bedroom', 'lamp','Brigthlight inc.', ...)
• Modifica di (un) record specifici(o):UPDATE inventory SET manufacturer='Darklight'WHERE description='lamp' ANDroomid='bedroom'
(modifica tutti i record che matchano i criteri)
STESSO ORDINECAMPI DEI VALORI
Master in web technology e security - Guido Boella 82
Category ID Room ID Description ManufacturerSports Equipment Bedroom Exercise Bike Adventure WorksFurniture Living Room Gray three-cushion sofa Fitch & MatherSports Equipment Garage Mountain Bike Crawford & BicyclesElectronic Den Computer Bits, Bytes & Chips, Inc.Tool Garage Cordless drill ProElectron, Inc.Furniture Dining Room Ebony inlaid table unknownTool Garage Table saw Shear SavvyCollectible Den Baseball card collectionJewelry Bedroom Pearl neclaceElectronic Living Room Audio-Visual Receiver AVTech
Description ManufacturerExercise Bike Adventure WorksGray three-cushion sofa Fitch & MatherMountain Bike Crawford & BicyclesComputer Bits, Bytes & Chips, Inc.Cordless drill ProElectron, Inc.Ebony inlaid table unknownTable saw Shear SavvyBaseball card collectionPearl neclaceAudio-Visual Receiver AVTech
Room ID DescriptionLiving Room Gray three-cushion sofaLiving Room Audio-Visual Receiver
SELECT description, manufacturer FROM household inventory
SELECT room id, description FROM household inventory
WHERE room id = living room
Master in web technology e security - Guido Boella 83
A
B
Room ID DescriptionBedroom Exercise BikeLiving Room Gray three-cushion sofa
Garage Mountain BikeDen ComputerGarage Cordless drillDining Room Ebony inlaid tableGarage Table sawDen Baseball card collectionBedroom Pearl neclaceLiving Room Audio-Visual Receiver
Description ManufacturerExercise Bike Adventure WorksGray three-cushion sofa Fitch & Mather
Mountain Bike Crawford & BicyclesComputer Bits, Bytes, Inc.Cordless drill ProElectron, Inc.Ebony inlaid table unknownTable saw Shear SavvyBaseball card collectionPearl neclaceAudio-Visual Receiver AVTech
Room ID ManufacturerBedroom Adventure WorksLiving Room Fitch & Mather
Garage Crawford & BicyclesDen Bits, Bytes, Inc.Garage ProElectron, Inc.Dining Room unknownGarage Shear SavvyDenBedroomLiving Room AVTech
Master in web technology e security - Guido Boella 84
Gerarchia di WindowsASP
ActiveX Data Object (ADO)
OLEDBprovider per
ODBC
OLEDBprovider per
EXCEL
DB
XSL
ODBC
Master in web technology e security - Guido Boella 85
ActiveX Data Object (ADO)
• ADO è parte di COM (MS component object model)
• E' costituito da una gerarchia di oggetti:
ConnectionCommand
ParameterRecordset
Fields
• Si opera creando gli oggetti e manipolandoli
Master in web technology e security - Guido Boella 86
• Connection: la connessione con il database indicando
• Command: per eseguire comandi sul database a cui ci siè collegati con la connessione. I comandi sono espressiin SQL
• Recordset: insieme di record di un database. Offremetodi per manipolare l'insieme(spostamento, lettura...)
• Command e Recordset possono creare implicitamenteuna connessione anche senza connection
Gli oggetti Connection,Command e Recordset
Master in web technology e security - Guido Boella 87
Connection• L'oggetto connection crea una connessione
ad un database che puo' essere utilizzata perpiù operazioni di consultazione o modificadel database
• L'oggetto creato può essere passatoall'oggetto Recordset per indicare ildatabase a cui si sta accedendo
• Specifica del DB: o tramite DSN creato daldriver ODBC di Microsoft o indicando ildriver specifico del DBMS da usare ed ilnome del file.
Master in web technology e security - Guido Boella 88
Oggetto Connection
• Variabili:state: 1 se la connessione ha avuto successo(costante adStateOpen)
• Metodi:execute(querySql): invia un query aldatabase e restituisce un recordsetclose(): chiude la connessione (implicito afine script)BeginTrans, CommitTrans, RollbackTransper gestione transazioni
Master in web technology e security - Guido Boella 89
Permessi• La connessione fra server e database con
NT è condizionata dal settaggio di permessi
• Su IIS è possibile indicare per ogni file odirectory quale utente utilizzare per ilcollegamento:
• utente associato a richiesta anonima (didefault IUS_nomemacchina)
• utente e password passate tramite HTTP econtrollate con elenco password di sistema
Master in web technology e security - Guido Boella 90
Security
• Nella stringa di connessione è possibilespecificare IUD e PWD per utente epassword
• Settaggio utente epassword nel databaseo nel driver ODBCdi Microsoft
Master in web technology e security - Guido Boella 91
Gli oggetti Connection,Command e Recordset
Dim dbRCSSet dbRCS = Server.CreateObject(ADODB.Recordset)
sqlStatement = "SELECT * FROM household inventory"
dbRCS.open sqlStatement, DSN="nomedb"
dbRCS.MoveFirst
Response.Write dbRCS("name")
dbRCS.close
Master in web technology e security - Guido Boella 92
Connessione implicita
Dim dbRCS 'dichiaro variabile per contenere recordset
'creo oggetto ADOSet dbRCS = Server.CreateObject(ADODB.Recordset)
'preparo SQL statement e poi riempio recordset
sqlStatement = "SELECT * FROM household inventory"
dbRCS.open sqlStatement, DNS="db.mdb" 'connessione
dbRCS.MoveFirst 'indice del recordset
Response.Write dbRCS("name") 'accesso a field "name"
dbRCS.close
Master in web technology e security - Guido Boella 93
ConnessioneDim stP
'indico driver da usare in connessione e file
stP="Driver={Microsoft Access Driver (*.mdb)}; _
DBQ=C:¥guido¥master¥inventario.mdb" 'file di MS Access
'creo oggetto connessione
set objC =Server.CreateObject("ADODB.Connection")
objC.Open stP 'apro la connessione ed eseguo un comando
objC.execute("INSERT INTO vv _ '_ è a capo in VBscript(description, money) VALUES ('lampada', 100)")
set rsauthors = Server.CreateObject("ADODB.Recordset")
rsauthors.open "authors", objC 'nome connessione
rsauthors.movefirst ...
Master in web technology e security - Guido Boella 94
Connessione
Dim stP
'connessione tramite Data Source NamestP = "DSN=pubs" 'creo oggetto connessione
set objC =Server.CreateObject("ADODB.Connection")
objC.Open stP 'apro la connessione ed eseguo un comando
objC.execute("INSERT INTO vv _ '_ è a capo in VBscript(description, money) VALUES ('lampada', 100)")
Master in web technology e security - Guido Boella 98
Oggetto recordset
• Struttura dati formata dalla lista di recordprovenienti dal database e da un indicatoredi quale è il record corrente
• Il record è formato da un insieme di coppieattributo valore (variabili name e value)
• Permette la modifica in locale dei dati e illoro aggiornamento sul database
Master in web technology e security - Guido Boella 99
Oggetto recordset
• Variabili:state: 1 se la connessione ha avuto successoEOF e BOF: l'indicatore ha sorpassatol'ultimo (o il primo) record (EOF e BOFsono entrambe veri se il recordset è vuoto)Fields: collezione dei campi del recordcorrenteRecordCount: numero di record nelrecordset
Master in web technology e security - Guido Boella 100
Oggetto recordset• Metodi
Open querySQL, connessione, [cursor],[lock]MoveFirst, MoveNext, MovePrevious,MoveLast: spostamento indicatore nellalista dei recordaddNew: aggiunge nuovo recordFind: cerca il record che soddisfa un vincoloUpdate: aggiorna le modifiche del recordcorrente su databaseUpdateBatch: aggiorna tutti i record
Master in web technology e security - Guido Boella 101
CursorDynamic cursor — allows you to viewadditions, changes, and deletions by other users;allows all types of movement through theRecordset that doesn't rely on bookmarks; andallows bookmarks if the provider supports them.
Keyset cursor — behaves like a dynamiccursor, except that it prevents you from seeingrecords that other users add, and prevents accessto records that other users delete. Data changesby other users will still be visible. It alwayssupports bookmarks and therefore allows alltypes of movement through the Recordset.
Master in web technology e security - Guido Boella 102
CursorStatic cursor — provides a static copy of a set ofrecords for you to use to find data or generate reports;always allows bookmarks and therefore allows all typesof movement through the Recordset. Additions,changes, or deletions by other users will not be visible.This is the only type of cursor allowed when you open aclient-side Recordset object.
Forward-only cursor — allows you to only scrollforward through the Recordset. Additions, changes, ordeletions by other users will not be visible. Thisimproves performance in situations where you need tomake only a single pass through a Recordset.
Master in web technology e security - Guido Boella 103
Locking del recordset• adLockBatchOptimistic 4 Indicates optimistic batch
updates. Required for batch update mode.adLockOptimistic 3 Indicates optimistic locking, recordby record. The provider uses optimistic locking, lockingrecords only when you call the Update method.adLockPessimistic 2 Indicates pessimistic locking, recordby record. The provider does what is necessary to ensuresuccessful editing of the records, usually by lockingrecords at the data source immediately after editing.adLockReadOnly 1 Indicates read-only records. Youcannot alter the data.adLockUnspecified -1 Does not specify a type of lock.For clones, the clone is created with the same lock type asthe original.
Master in web technology e security - Guido Boella 104
Creazione Recordset
Set rsAuthors = Server.CreateObject("ADODB.Recordset")
With rsAuthors
Select Case Request.QueryString("Action")
Case "Create"
.Open "authors", "Driver={Microsoft Access _
Driver (*.mdb)};DBQ=c:¥asp¥Pro ASP 3.0¥pubs.mdb"
If .State = adStateOpen Thenresponse.write "Recordset created successfully"
elseResponse.Write "Recordset creation failed"
end if
Master in web technology e security - Guido Boella 105
Display records
Case "Display"
.Open "authors", strConn
If .State = adStateOpen Then
If not .EOF and not .BOF then
While not .EOF
response.write .Fields("au_fname") & ", " & _
.Fields("au_lname") & "<BR>"
rsAuthors.MoveNext
wend
else response.write "Recordset empty” end if
else
Response.Write = "Recordset creation failed"
end if
Master in web technology e security - Guido Boella 106
Mostra campi di un record
Case "Fields"
.Open "authors", strConn
If .State = adStateOpen Then
If not .EOF and not .BOF then
for each fld in .Fields
response.write fld.name & " : " & _
fld.value & "<BR>"
next
else
response.write "Recordset empty"
end if
else
Response.Write = "Recordset creation failed"
end if
Master in web technology e security - Guido Boella 107
Tabella per form dati.Open "authors", strConn, adOpenDynamic, adLockOptimistic
If .State = adStateOpen Then
Response.write"<TABLE><TR><TD>Field</TD><TD>Value</TD>"
For each fld in .Fields
response.write "<TR><TD>" & fld.name &"</TD><TD><INPUT _ TYPE=""TEXT"" NAME=" & fld.name& " SIZE=""21"" VALUE= ” _ & fld.value & "></TD>"
next
response.write "</TABLE><P><INPUT TYPE=""SUBMIT""NAME =""Submit"" VALUE=""Edit Record"">"
else
Response.Write = "Recordset creation failed"
end if
Master in web technology e security - Guido Boella 108
Gestione errori If objConn.Errors.Count > 0 Then For each objError in objConn.Errors If objError.number <> 0 then Response.Write "<TABLE BORDER=1>" & _
"<TR><TD>Error Property</TD><TD>Contents</TD>"& _
"</TR><TR><TD>Number</TD><TD>" &objError.Number & _"</TD></TR><TR><TD>NativeError</TD><TD>" & _
objError.NativeError & "</TD></TR>" & _ "<TR><TD>SQLState</TD><TD>" & objError.SQLState
& _"</TD></TR><TR><TD>Source</TD><TD>" & _
objError.Source & "</TD></TR>" & _ "<TR><TD>Description</TD><TD>" & _ objError.Description & "</TD></TR></TABLE><P>" End If Next
Master in web technology e security - Guido Boella 109
Aggiunta record rsauthors.Open "authors", strConn, adOpenkeyset, _
adLockOptimisticrsAuthors.Find "au_lname = '" & request.form("clastname") _ & "'"If rsAuthors.state = adStateOpen then
rsAuthors.AddNewrsAuthors.Fields("au_id") = request.form("au_id")
rsAuthors.Fields("au_lname") = request.form("au_lname") rsAuthors.Fields("zip") = request.form("zip") rsAuthors.Fields("contract") = request.form("contract") rsAuthors.Update response.write "Record added - Record Number = " & _rsAuthors.AbsolutePosition
Master in web technology e security - Guido Boella 111
XMLDOM
• Asp offre una serie di metodi per gestire fileXML
• Il contenuto di un file XML diventa unoggetto di ASP e non solo una stringa dicaratteri
• I recordset di un database possono esseretrasformati in un file XML
• Necessari IE5, IIS5 con ADO2.5 per pienafunzionalità
Master in web technology e security - Guido Boella 112
IE5 e XML
• Il browser IE5 (e forse Netscape 6) offronola possibilità di incorporare file XMLall'interno di una pagina HTML e dimanipolarli con VBscript (come con ASP) oJscript
• I dati XML (xml data island) possonoessere visualizzati in tabelle o in singolielementi XML tramite DATAFLD
• XMLHTTP permette di trasmettere oggettiXML al server e viceversa
Master in web technology e security - Guido Boella 113
Perché passare dati al client?
• Per avere applicazioni che rispondono inmaniera più veloce
• Per alleggerire il carico di lavoro del server:one page web applications
Master in web technology e security - Guido Boella 114
IE5, XML e XSL
• Il browser IE5 permette di visualizzare unfile XML facendolo tradurre da unostylesheet CSS
<?xml version="1.0"?><?xml-stylesheet type="text/css" href="menu.css" ?>
Master in web technology e security - Guido Boella 115
CSS per XMLmenu.xml<?xml version="1.0"?><?xml-stylesheet type="text/css" href="menu.css" ?><Menu effective="2000-04-01" expires="2000-06-30"> <Appetizers> <Item> <Name>Deep Fried Mushrooms with Stuff inThem</Name> <Price>6.00</Price> <Description>All mushrooms look alike. Focus on theconversation</Description> </Item>
menu.css:NAME {BACKGROUND-COLOR: teal; COLOR: white;
DESCRIPTION {BACKGROUND-COLOR: white;COLOR: blue;}
Master in web technology e security - Guido Boella 116
XSL PER DHTML
links.xml XML file contiene la descrizionegerarchica del menu
links.xsl regole XSL per generare i link dei menu'con gli appositi comandi onclick, id, e attributodisplay
menu.js contiene funzioni javascript per attivareattributo display di un DIV e la chiamata allatraduzione xsl da links.xml tramite links.xsl
Master in web technology e security - Guido Boella 117
<!ELEMENT Team (Manager , Members , Person+ )>
<!ATTLIST Team project ID #REQUIRED >
<!ELEMENT Manager EMPTY>
<!ATTLIST Manager person IDREF #REQUIRED >
<!ELEMENT Members EMPTY>
<!ATTLIST Members people IDREFS #REQUIRED >
<!ELEMENT Person (Name )>
<!ATTLIST Person sn ID #REQUIRED >
<!ELEMENT Name (First , Last )>
<!ELEMENT First (#PCDATA )>
<!ELEMENT Last (#PCDATA )>
ESEMPIO DTD
Master in web technology e security - Guido Boella 118
<?xml version="1.0"?><!DOCTYPE Team SYSTEM "team.dtd">
<Team project="a134">
<Manager person="a1"/>
<Members people="b1 c2 c9"/>
<Person sn="a1">
<Name>
<First>John</First>
<Last>Doe</Last>
</Name>
</Person>
<Person sn="b1">
<Name>
<First>Dudley</First>
<Last>Doright</Last>
</Name>
</Person></Team>
ESEMPIO XML
Master in web technology e security - Guido Boella 119
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="stylecontacts.xsl" ?>
<CONTACT_INFO>
<BUSINESS><CONTACT>
<NAME>John Doe</NAME>
<PHONE>555-5319</PHONE></CONTACT>
</BUSINESS>
<PERSONAL><CONTACT relation="family">
<NAME>Mary Jones</NAME>
<PHONE>555-9013</PHONE></CONTACT>
<CONTACT>
<NAME>Mike Wilson</NAME>
<PHONE>555-4138</PHONE></CONTACT>
</PERSONAL></CONTACT_INFO>
ESEMPIO XML con XSL
Master in web technology e security - Guido Boella 120
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<HTML> <BODY>
<xsl:apply-templates />
</BODY></HTML>
</xsl:template>
Master in web technology e security - Guido Boella 121
<xsl:template match="CONTACT_INFO">
<xsl:for-each select="./*">
<xsl:choose>
<xsl:when test="[!nodeName()='PERSONAL']">
<DIV STYLE="background-color:teal;"> Personal Contacts </DIV>
</xsl:when>
<xsl:otherwise>
<DIV STYLE="background-color:black;"> Business Contacts</DIV>
</xsl:otherwise></xsl:choose>
<xsl:apply-templates /><P/></xsl:for-each> </xsl:template>
• PROVA DI STYLESHEETS
Master in web technology e security - Guido Boella 122
<xsl:template match="CONTACT">
<xsl:for-each select=".">
<DIV>
<xsl:if test=".[@relation = 'family']">
<xsl:attribute name="STYLE">font-weight:bold</xsl:attribute>
</xsl:if>
<xsl:value-of select="NAME"/>
<DIV STYLE="font-size:10pt;left:.25cm;position:relative;">
<xsl:value-of select="PHONE"/>
</DIV>
</DIV>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Master in web technology e security - Guido Boella 123
NUOVO STYLESHEET<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">Traduzione root element<br/>
Elenco contatti:
<xsl:apply-templates select="*" /></xsl:template>
<xsl:template match="PERSONAL">
<xsl:apply-templates select="*" />
</xsl:template>
<xsl:template match="CONTACT"><A>
<xsl:attribute name="href">chiama.asp?<xsl:value-of select="./PHONE">
</xsl:value-of>"</xsl:attribute></A><br/>
<xsl:value-of select="./NAME"></xsl:value-of>
<xsl:value-of select="./@relation"></xsl:value-of>
</xsl:template></xsl:stylesheet>
Master in web technology e security - Guido Boella 124
Data island
• Due modi per includere XML dentro unapagina html
<XML ID="XMLID"> <XMLDATA> <DATA>TEXT</DATA> </XMLDATA></XML>
<XML SRC="http://localhost/xmlFile.xml"></XML>
Master in web technology e security - Guido Boella 125
Data island
• Il contenuto è accessibile (in javascript)tramite il suo id nella proprietà all deldocument (in DHTML) o direttamente
function returnXMLData(){ return document.all("XMLID").XMLDocument.nodeValue; }
function returnXMLData(){ return XMLID.documentElement.text; }
RESTITUISCONO LA ROOT XML
Master in web technology e security - Guido Boella 126
Data binding
• Oppure il contenuto è accessibile inDHTML tramite gli attributi DATASRC eDATAFLD
• DATASRC fa riferimento all'ID del dataisland preceduto da #
• DATAFLD si riferisce ad un elemento XML• DATASRC può essere associato ad una
TABLE, ma DATAFLD non può essereassociato a TD direttamente: solo tramitealtro tag come DIV
Master in web technology e security - Guido Boella 127
Data binding
• Si può settare il contenuto di un elementoHTML direttamente usando la propertyinnerText o InnerHTML:
<div id="testo"></div><script>test.innerText="prova"</script><script>test.innerHTML=xmlid.documentelement.text</script>
Master in web technology e security - Guido Boella 128
Esempio
<HTML> <BODY><XML ID="xmlMeetings"> <?xml version="1.0" ?> <meetings> <meeting> <date>1/1/99</date> <time>9:00</time> <location>104</location> </meeting> <meeting> <date>2/1/99</date> <time>13:00</time> <location>34</location> </meeting> </meetings></XML><table datasrc="#xmlMeetings"> <tr> <td><div datafld="date"></div></td> <td><div datafld="time"></div></td> <td><div datafld="location"></div></td> </tr> </table>
</BODY> </HTML>
Master in web technology e security - Guido Boella 129
XML in HTML<XML ID="dsoData" SRC="authorsasxml.xml"></XML>
<TABLE DATASRC="#dsoData"> <TR> <TD> <INPUT TYPE="TEXT" DATAFLD="au_id"></INPUT> </TD> <TD> <INPUT TYPE="TEXT" DATAFLD="au_fname"></INPUT> </TD> </TR></TABLE>
Master in web technology e security - Guido Boella 130
XML in HTML<XML ID="dsoData" SRC="authors.xml"></XML>
<TABLE ID="tblData" BORDER="1" DATASRC="#dsoData"DATAFLD="rs:data">
<TR><TD>
<TABLE ID="tblData" BORDER="1" DATASRC="#dsoData"DATAFLD="z:row">
<THEAD><TR><TD>au_id</TD></TR></THEAD>
<TBODY>
<TR>
<TD><SPAN DATAFLD="au_id"></SPAN></TD>
<TD><SPAN DATAFLD="au_fname"></SPAN></TD>
<TD><SPAN DATAFLD="au_lname"></SPAN></TD>
</TR></TBODY></TABLE>
LEGATO AD UN SOTTOINSIEMEDEL DOCUMENTO
Master in web technology e security - Guido Boella 131
XML DOM e ASP
• Il modello ad oggetti DOM permette divedere un documento XML come unastruttura dati di un linguaggio diprogrammazione (API)
• Il parser XML è il programma che permettedi caricare il file XML, verificare la suacorrispondenza con il DTD e creare lastruttura dati manipolabile da XML
Master in web technology e security - Guido Boella 132
• La struttura dati è un albero dove la radice èla root del documento XML: /
• Comandi di ASP (ma anche Jscript o PHP4)permettono di accedere o modificare lastruttura dati
• Traduzione tramite XSL in ASP sul server
• Creazione oggetto XML:Set source = Server.CreateObject("Microsoft.XMLDOM")source.async = falsesource.validateOnParse= true 'non necessario: è default
• Caricamento filesource.load(sourceFile)
Master in web technology e security - Guido Boella 133
APPLICAZIONE STILE ON SERVER
<%@ Language=VBScript %> (ON CLIENT)<%sourceFile = Request.ServerVariables("APPL_PHYSICAL_PATH")+ "¥Chapter 08¥contacts_basic.xml"styleFile = Request.ServerVariables("APPL_PHYSICAL_PATH") +"¥Chapter 08¥stylecontacts_basic.xsl"
Set source = Server.CreateObject("Microsoft.XMLDOM")source.async = falsesource.load(sourceFile)Set style = Server.CreateObject("Microsoft.XMLDOM")style.async = falsestyle.load(styleFile)Response.Write(source.transformNode(style))%>
Master in web technology e security - Guido Boella 134
Compatibilità con vecchi browser<%@ Language="JavaScript" %><%
var userAgent = newString(Request.ServerVariables("HTTP_USER_AGENT"));
if (userAgent.indexOf("MSIE 5") >= 0)
Response.Redirect("contacts.xml");
else
Response.Write(OnServer());
function OnServer() {
var doc, stylesheet;
doc = Server.CreateObject("microsoft.xmldom");
stylesheet = Server.CreateObject("microsoft.xmldom");
if (doc != null && stylesheet != null){
doc.load(Server.MapPath("contacts.xml"));
stylesheet.load(Server.MapPath("stylecontacts.xsl"));…
Master in web technology e security - Guido Boella 135
<authors> <author> <name>Graham Greene</name> <id>32454345</id> </author> <author> <name>James Joyce</name> <id>43535345</id> </author></authors>
authors
author author
name name idid
Master in web technology e security - Guido Boella 136
authors
author author
name name idid
documentelement
lastchildfirstchild
parentNodefirstchild
nextSibling previousSibling
childNodes
Master in web technology e security - Guido Boella 137
authors
author author
name name idid
documentelement.firtchild author (1)documentelement.childnodes.item(1) author (1)documentelement.firtchild.parentNode documentnamednodemap("name").item(1) name (1)documenteelement.firtchild.firstchild.text G. Greenedocumentelement.firtchild.nextsibling author (2)documentelement.lastchild.previousSibling author (1)
Master in web technology e security - Guido Boella 138
Accesso a documento XML• Creazione oggetto
set objXML = Server.CreateObject("Microsoft.XMLDOM")oppure Microsoft.FreeThreadedXMLDOM in global.asa comevariabile di applicazione
• ATTENZIONE: bisogna fare riferimento alla libreria giusta<!-- METADATA TYPE="typelib"FILE="c:¥Progammi¥filecomuni¥system¥msxml.dll" -->
• Caricamento oggetto da file:objXML.load(strSourceFile)e.g. strSourceFile = server.MapPath("asp") & "¥file.xml"
• Selezione di un nodo:set objColor = objXML.selectSingleNode("color")restituisce un oggetto node
Master in web technology e security - Guido Boella 139
Esempi
<XML attributo1="valore1" attributo2="valore2">
<Team project="a134">
<Manager person="a1"/>
<Members people="b1 c2 c9">
<Person sn="a1">
<Name>
<First>John</First><Last>Doe</Last></Name>
</Person>
<Person sn="b1">
<Name>
<First>Dudley</First><Last>Doright</Last></Name>
</Person></Members></Team>
</XML>
Master in web technology e security - Guido Boella 140
•VALIDAZIONE E GESTIONE ERRORI IN XML<% Language = VBScript %><HTML><HEAD> <TITLE> Verifire - an XML Verify utility</TITLE></HEAD><BODY><FORM ACTION="verifire.asp" METHOD="POST"> Enter File to Verify: <INPUT TYPE="TEXT"VALUE="<%=Request.Form("TestFile")%>" NAME="TestFile"> <BR>Display the file (if it is ok?) <INPUT TYPE="CHECKBOX" NAME="Show"> <BR> <INPUT TYPE="SUBMIT" VALUE="Test This"></FORM> CONTINUA
VERIFILE
Master in web technology e security - Guido Boella 141
<% If Request.Form("TestFile") <> "" Then
Dim ObjXML, objRootElement
Set objXML = Server.CreateObject("Microsoft.XMLDOM")
objXML.ValidateOnParse = True
objXML.Load(Server.MapPath(Request.Form("TestFile")))
If objXML.ParseError.errorCode <> 0 Then
Response.Write ("Error: " & objXML.parseError.reason )
Response.Write ("At Line " & objXML.parseError.line & ", ")
Else Response.Write (Request.Form("TestFile") & "is valid")
If Request.Form("Show") = "on" Then
Set objRootElement = objXML.documentElement
Response.Write (objRootElement.xml)
End If End IfEnd If %>
</BODY></HTML>
Master in web technology e security - Guido Boella 142
• Percorrimento nodelist (di foglie):
Selezione per nome:set objNames = bjXML.getElementsByTagName("name")
' restituisce una nodelist
dim strArr(objNames.length)
for itemX = 0 to objNames.lenght -1
strArr(itemX) = objNames.item(strArr).text
next
Master in web technology e security - Guido Boella 143
Conteggio nodi XML<% var nodes = 0; var doc = new ActiveXObject("microsoft.xmldom"); doc.async = false; doc.load(Server.MapPath("menu.xml")); if (doc.readyState == 4 && doc.parseError.errorCode == 0) {Traverse(doc.documentElement); Response.Write("Nodes in the DOM for menu.xml: " + nodes);} else Response.Write("Error: " + doc.parseError.reason); doc = null;
function Traverse(node){ nodes += 1; if (node.attributes != null) nodes += node.attributes.length; for (var i = 0; i < node.childNodes.length; i++) Traverse(node.childNodes(i));} %>
Master in web technology e security - Guido Boella 144
• PROPRIETA' di XMLDOM• async* Indicates whether asynchronous download is permitted.
Read/write.
• attributes Contains the list of attributes for this node. Read-only.
• baseName* Returns the base name for the name qualified with thenamespace. Read-only.
• childNodes Contains a node list containing the children (for nodes thatcan have children). Read-only.
• dataType* Specifies the data type for this node. Read/write.
• definition* Returns the definition of the node in the DTD or schema.Read-only.
• doctype Contains the document type node that specifies the DTD forthis document. Read-only.
• documentElement Contains the root element of the document.Read/write.
• firstChild Contains the first child of this node. Read-only.
Master in web technology e security - Guido Boella 145
• implementation Contains the XMLDOMImplementation object for thisdocument. Read-only.
• lastChild Returns the last child node. Read-only.
• namespaceURI* Returns the URI for the namespace. Read-only.
• nextSibling Contains the next sibling of this node in the parent's childlist. Read-only.
• nodeName Contains the qualified name of the element, attribute, orentity reference, or a fixed string for other node types. Read-only.
• nodeType Specifies the XML DOM node type, which determines validvalues and whether the node can have child nodes. Read-only.
• nodeTypedValue* Contains this node's value, expressed in its defineddata type. Read/write.
• nodeTypeString* Returns the node type in string form. Read-only.
• nodeValue Contains the text associated with the node. Read/write.
• ondataavailable* Specifies the event handler for the ondataavailableevent. Read/write.
Master in web technology e security - Guido Boella 146
• onreadystatechange* Specifies the event handler to be called when thereadyState property changes. Read/write.
• ontransformnode* Specifies the event handler for the ontransformnodeevent. Read/write.
• ownerDocument Returns the root of the document that contains thisnode. Read-only.
• parentNode Contains the parent node (for nodes that can have parents).Read-only.
• parsed* Contains True if this node and all descendants have beenparsed and instantiated; False if any nodes remain to be parsed. Read-only.
• parseError* Returns an XMLDOMParseError object that containsinformation about the last parsing error. Read-only.
• prefix* Returns the namespace prefix. Read-only.
• preserveWhiteSpace* Contains True if default processing preserveswhite space; False otherwise. Read/write.
• previousSibling Contains the left sibling of this node. Read-only.
Master in web technology e security - Guido Boella 147
• readyState* Indicates the current state of the XML document. Read-only.
• resolveExternals* Indicates whether external definitions (resolvablenamespaces, DTD external subsets, and external entity references) areto be resolved at parse time, independent of validation. Read/write.
• specified* Indicates whether the node (usually an attribute) is explicitlyspecified or derived from a default value in the DTD or schema. Read-only.
• text* Contains the text content of the node and its subtrees. Read/write.
• url* Returns the canonicalized URL for the last loaded XML document.Read-only.
• validateOnParse* Indicates whether the parser should validate thisdocument. Read/write.
• xml* Contains the XML representation of the node and all itsdescendants. Read-only.
* denotes an extension to the W3C DOM.
Master in web technology e security - Guido Boella 148
• Metodi di XMLDOM• abort* Aborts an asynchronous download in progress.
• appendChild Appends newChild as the last child of this node.
• cloneNode Creates a new node that is an exact clone of this node.
• createAttribute Creates a new attribute with the specified name.
• createCDATASection Creates a CDATA section node that contains thesupplied data.
• createComment Creates a comment node that contains the supplieddata.
• createDocumentFragment Creates an empty DocumentFragment object.
• createElement Creates an element node using the specified name.
• createEntityReference Creates a new EntityReference object.
• createNode* Creates a node using the supplied type, name, andnamespace.
• createProcessingInstruction Creates a processing instruction node thatcontains the supplied target and data.
Master in web technology e security - Guido Boella 149
• createTextNode Creates a text node that contains the supplied data.
• getElementsByTagName Returns a collection of elements that have thespecified name.
• hasChildNodes Returns True if this node has children.
• insertBefore Inserts a child node to the left of the specified node or atthe end of the list.
• load* Loads an XML document from the specified location.
• loadXML* Loads an XML document using the supplied string.
• nodeFromID* Returns the node whose ID attribute matches thesupplied value.
• removeChild Removes the specified child node from the list of childrenand returns it.
• replaceChild Replaces the specified old child node with the suppliednew child node in the set of children of this node, and returns the oldchild node.
• save* Saves an XML document to the specified location.
Master in web technology e security - Guido Boella 150
• selectNodes* Applies the specified pattern-matching operation to thisnode's context and returns the list of matching nodes.
• selectSingleNode* Applies the specified pattern-matching operation tothis node's context and returns the first matching node.
• transformNode* Processes this node and its children using the suppliedXSL style sheet and returns the resulting transformation.
• transformNodeToObject* Processes this node and its children using thesupplied XSL style sheet and returns the resulting transformation in thesupplied object.
• Eventi di XMLDOM
• ondataavailable* Indicates that XML document data is available.
• onreadystatechange* Indicates when the readyState property changes.
• ontransformnode* Fires before each node in the style sheet is applied toeach node in the XML source.
Master in web technology e security - Guido Boella 151
XMLDOMDOMDocument Represents the top node of the XML DOM tree.
XMLDOMNode Represents a single node in the documenttree; the base interface for accessing data in the XML objectmodel. Valid node types are defined in the DOMNodeTypeenumeration. This interface includes support for data types,namespaces, DTDs, and XML schemas.
XMLDOMNodeList Supports iteration and indexed accessoperations on the live collection of XMLDOMNode objects.
XMLDOMNamedNodeMap Provides iteration and access byname to the collection of attributes. This interface includessupport for namespaces.
XMLDOMParseError Returns detailed information about the lasterror, including the error number, line number, characterposition, and a text description.
Master in web technology e security - Guido Boella 152
XMLHttpRequest Provides client-side protocol support forcommunication with HTTP servers.
XTLRuntime Implements methods that can be called from XSLstyle sheets.
• DOM ObjectsXMLDOMAttribute Represents an attribute object.
XMLDOMCDATASection Quotes or escapes blocks of text sothat text is not interpreted as markup language.
XMLDOMCharacterData Provides text manipulationmethods used by several objects.
XMLDOMComment Represents the content of an XMLcomment.
XMLDOMDocumentFragment Represents a lightweight objectthat is useful for tree insert operations.
Master in web technology e security - Guido Boella 153
XMLDOMDocumentType Contains information associatedwith the document type declaration.
XMLDOMElement Represents the element object.
XMLDOMEntity Represents a parsed or unparsed entity inthe XML document.
XMLDOMEntityReference Represents an entity referencenode.
XMLDOMImplementation Provides methods that areindependent of any particular instance of the document objectmodel.
XMLDOMNotation Contains a notation declared in the DTD orschema.
XMLDOMProcessingInstruction Represents a processinginstruction, which XML defines to keep processor-specificinformation in the text of the document.
Master in web technology e security - Guido Boella 154
XMLDOMText Represents the text content of an element orattribute.
The DOMNodeType enumeration lists all valid node types.
Master in web technology e security - Guido Boella 156
XML Schema• Microsoft ha (giustamente) proposto una
alternativa al formalismo DTD (documenttype definition) per specificare documentiXML perchè un DTD non è un documentoXML
• Uno Schema XML specifica gli elementiche possono essere presenti in un documentie gli attributi a loro associati usando XMLcome sintassi
• Uniformità e possibile utilizzo di XSL
Master in web technology e security - Guido Boella 157
DTD e XML
<!DOCTYPE PGROUP [<!ELEMENT PGROUP (PERSONA+, GRPDESCR) ><!ELEMENT PERSONA (#PCDATA) ><!ELEMENT GRPDESCR (#PCDATA) >]>
<?xml version="1.0" ?><PGROUP> <PERSONA>MACBETH</PERSONA> <PERSONA>BANQUO</PERSONA> <GRPDESCR>generals of the king's army.</GRPDESCR></PGROUP>
Master in web technology e security - Guido Boella 158
Schema e XML<?xml version="1.0"?><Schema name="schema_sample_1" xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes"> <ElementType name="PERSONA" content="textOnly"
model="closed"/> <ElementType name="GRPDESCR" content="textOnly"
model="closed"/> <ElementType name="PGROUP" content="eltOnly"
model="closed"> <element type="PERSONA" minOccurs="1"
maxOccurs="*"/> <element type="GRPDESCR" minOccurs="1"
maxOccurs="1"/> </ElementType></Schema>
Master in web technology e security - Guido Boella 159
Content model di un elemento
• Definizione di elementi e attributi:<elementType name="nometag"><attributeType name="nomeatt">
• Occorrenza di elementi e attributi comeparte di altri:<elementType name="autore">
<element type="nome"/><attribute type="elenco"/>
</elementType>
• attributeType può essere locale o globaleper essere condiviso
TYPE, non NAME
Master in web technology e security - Guido Boella 160
ElementType ed element
• Attributi ElementType:– content: textonly, eltonly, mixed (default), empty
(mixed: <nome>Bill <tag/> Gates</nome>)
– order: seq (default), one (solo uno dei figli), many(duplicazioni)
– model (novità): open (default), closedse un content model è open, può contenereelementi e attributi appartenenti ad altrinamespace senza che siano dichiarati localmente
Master in web technology e security - Guido Boella 161
• Attributi ElementType:– content: textonly, eltonly, mixed (default), empty
(mixed: <nome>Bill <tag/> Gates</nome>)
– order: seq (default), one (solo uno dei figli), many(duplicazioni)
– model (novità): open (default), closedse un content model è open, può contenereelementi e attributi appartenenti ad altrinamespace senza che siano dichiarati localmente(diventa possibile riutilizzare schemi standardsenza ridefinirli, vedi SOAP e Biztalk)
Master in web technology e security - Guido Boella 162
<ElementType name="shipTo" xmlns:e-com="http://e-commerce.org/stuff.xml"> <element type="e-com:Address"/></ElementType>
<PurchaseOrder xmlns:e-com="http://e-commerce.org/stuff.xml"> <shipTo> <e-com:Address> <e-com:name>Alice Smith</e-com:name> <e-com:street>123 Maple Street</e-com:street> </e-com:Address> </shipTo> <orderDate>1999-05-20</orderDate> <shipDate>1999-05-25</shipDate></PurchaseOrder>
SCHEMA aperto
DOCUMENTO aperto
ELEMENTO DI ALTRO NAMESPACE
Master in web technology e security - Guido Boella 163
Element• Attributi di Element:
– minOccurs e maxOccurs: numero di occorrenzepossibili dell'elemento nel content model0,1, ..., * (infinite)
• Raggruppamento di Elementi (con proprietà"order", "minOccurs", "maxOccurs"):
<elementType name="autore"><element type="nome"/>
<group order="one"> <element type="address"/> <element type="email"/> </group>
</elementType>SOLO UNO DEI DUE
ELEMENTI
Master in web technology e security - Guido Boella 164
Attributi
• Gli attributi non possono conteneresottoelementi, non hanno ordinamento, nè sipossono porre alternative, occorrono unasola volta
• Opzionalità od obbligatorietà: required =yes o no
• Range di valori e default:<AttributeType="number" default = "no" dt:values= "yes no" required=yes>
NAMESPACE dei tipi
Master in web technology e security - Guido Boella 165
• Elementi e attributi si possono tiparenamespace dei tipi:xmlns:dt="urn:schemas-microsoft-com:datatypes">
<Schema name="myschema"
xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:dt="urn:schemas-microsoft-com:datatypes">
<ElementType name="pages" dt:type="int"/>
<AttributeType="number" required=yes>
<datatype dt:type= "int"/>
</ElementType>
</Schema> NAMESPACE dt
Master in web technology e security - Guido Boella 166
Estensione per vincoli semantici
<ElementType name="pages" xmlns:myExt="urn:myschema-extensions">
<datatype dt:type="int" />
<myExt:min>50</myExt:min>
<myExt:max>100</myExt:max>
</ElementType>
RESTRIZIONI NONSINTATTICHE, CIOE' NONVERIFICATE DA XML MADA APPLICAZIONE CHE
USA XML
Master in web technology e security - Guido Boella 167
<Schema xmlns="urn:schemas-microsoft-com:xml-data"xmlns:dt="urn:schemas-microsoft-com:datatypes">
<ElementType name="au_id" content="textOnly"/>
<ElementType name="au_lname" content="textOnly"/>
<ElementType name="au_fname" content="textOnly"/>
<ElementType name="phone" content="textOnly"/>
<ElementType name="Author" content="eltOnly">
<element type="au_id"/>
<element type="au_lname"/>
<element type="au_fname"/>
<element type="phone"/>
</ElementType>
<ElementType name="Authors" content="eltOnly">
<element type="Author" maxOccurs="*"/>
</ElementType>
</Schema>
Master in web technology e security - Guido Boella 168
<Authors> <Author> <au_id>172-32-1176</au_id> <au_lname>White</au_lname> <au_fname>Johnson</au_fname> <phone>408 496-7223</phone> <address>10932 Bigge Rd.</address> … </Author> <Author> <au_id>213-46-8915</au_id> <au_lname>Green</au_lname> <au_fname>Marjorie</au_fname> <phone>415 986-7020</phone> <address>309 63rd St. #411</address> </Author></Authors>
Master in web technology e security - Guido Boella 169
<xml xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema">
<s:Schema id="RowsetSchema">
<s:ElementType name="row" content="eltOnly">
<s:AttributeType name="au_id" rs:number="1" rs:writeunknown="true">
<s:datatype dt:type="string" dt:maxLength="11" rs:maybenull="false" />
</s:AttributeType>
<s:AttributeType name="au_lname" rs:number="2" rs:writeunknown="true">
<s:datatype dt:type="string" dt:maxLength="40" rs:maybenull="false" />
</s:AttributeType>
<s:AttributeType name="au_fname" rs:number="3" rs:writeunknown="true">
<s:datatype dt:type="string" dt:maxLength="20" rs:maybenull="false" />
</s:AttributeType>
...
<s:extends type="rs:rowbase" />
</s:ElementType>
</s:Schema>
Master in web technology e security - Guido Boella 170
<rs:data>
<z:row au_id="172-32-1176" au_lname="White" au_fname="Johnson"phone="408 496-7223" address="10932 Bigge Rd." city="Menlo Park"state="CA" zip="94025" contract="True" />
<z:row au_id="213-46-8915" au_lname="Green" au_fname="Marjorie"phone="415 986-7020" address="309 63rd St. #411" city="Oakland"state="CA" zip="94618" contract="True" />
<z:row au_id="238-95-7766" au_lname="Carson" au_fname="Cheryl"phone="415 548-7723" address="589 Darwin Ln." city="Berkeley"state="CA" zip="94705" contract="True" />
<z:row au_id="267-41-2394" au_lname="O'Leary" au_fname="Michael"phone="408 286-2428" address="22 Cleveland Av. #14" city="San Jose"state="CA" zip="95128" contract="True" />
<z:row au_id="274-80-9391" au_lname="Straight" au_fname="Dean"phone="415 834-2919" address="5420 College Av." city="Oakland"state="CA" zip="94609" contract="True" />
</rs:data>
</xml>
XML e XSL
Master in web technology e security - Guido Boella 171
Salvare recordset in XML
<%
strsql = request.querystring("sql")
if NOT strsql="" then
strFile="c:¥asp¥file2.xml"
Set rsAuthors = Server.CreateObject("ADODB.Recordset")
Set objFSO = CreateObject("Scripting.FileSystemObject")
if objFSO.FileExists(strFile) then
objFSO.deletefile strFile
end if
set objFSO = nothing
Master in web technology e security - Guido Boella 172
With rsAuthors
.Open strsql, "Driver={Microsoft Access Driver (*.mdb)};DBQ=c:¥asp¥Pro ASP 3.0¥pubs.mdb"
If (.state = 1) then
.save strFile, 1 'adPersistent
.close()
end if
End with
Set objFSO = CreateObject("Scripting.FileSystemObject")
set objFile = objFSO.getFile(strFile)
set objStream = objFile.openAsTextStream()
response.write "<textarea>"& objStream.readAll()&"</textarea>"
objFile.close
Master in web technology e security - Guido Boella 173
XML da DB
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="contatti1.xsl" ?>
<rs:data xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"xmlns:rs="urn:schemas-microsoft-com:rowset"xmlns:z="#RowsetSchema">
<z:row au_id="172-32-1176" au_lname="White" au_fname="Johnson"phone="408 496-7223" address="10932 Bigge Rd." city="MenloPark" state="CA" zip="94025" contract="True" />
<z:row au_id="213-46-8915" au_lname="Green" au_fname="Marjorie"phone="415 986-7020" address="309 63rd St. #411" city="Oakland"state="CA" zip="94618" contract="True" />
<z:row au_id="238-95-7766" au_lname="Carson" au_fname="Cheryl"phone="415 548-7723" address="589 Darwin Ln." city="Berkeley"state="CA" zip="94705" contract="True" />
</rs:data>
Master in web technology e security - Guido Boella 174
XSL per XML e DB
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">Traduzione root element<br/>
Elenco contatti:
<xsl:apply-templates select="*" /></xsl:template>
<xsl:template match="rs:data"><xsl:apply-templates select="*"/></xsl:template>
<xsl:template match="z:row"><A>
<xsl:attribute name="href">chiama.asp?<xsl:value-of select="./@au_id">
</xsl:value-of>"</xsl:attribute></A><br/>
<xsl:value-of select="./@au_lname"></xsl:value-of>
<xsl:value-of select="./@au_fname"></xsl:value-of>
</xsl:template></xsl:stylesheet>
Master in web technology e security - Guido Boella 175
Recordset data island<INPUT TYPE=TEXT DATASRC=#xmlPeople DATAFLD=NAME>
<INPUT DATASRC=#xmlPeople DATAFLD="ADDRESS">
<INPUT DATASRC=#xmlPeople DATAFLD="TEL">
<INPUT ID="first" TYPE=button VALUE="<<"onClick="xmlPeople.recordset.moveFirst()">
<INPUT ID="prev" TYPE=button VALUE="<" onClick=
"if (xmlPeople.recordset.absoluteposition > 1)
xmlPeople.recordset.movePrevious()">
<INPUT ID="next" TYPE=button VALUE=">" onClick=
"if (xmlPeople.recordset.absoluteposition < xmlPeople.recordset.recordcount) xmlPeople.recordset.moveNext()">
<INPUT ID="last" TYPE=button VALUE=">>"onClick="xmlPeople.recordset.moveLast()">
<INPUT ID="add" TYPE=BUTTON VALUE="Add Person"onClick="xmlPeople.recordset.addNew()">
Master in web technology e security - Guido Boella 176
Asynchronous loadingdocParser.ondataavailable = DataAvailHandlerdocURL = FileURL.value;docParser.load(docURL); ...function DataAvailHandler(){
// Get the number of attributes of the rootvar nodeCount = docParser.childNodes.length;var docRoot = docParser.documentElement;
// Count the first level nodes in the treeif (docRoot != null){ nodeCount += docRoot.childNodes.length; }
document.all("status").innerHTML = nodeCount + " XML nodesloaded so far";}
Master in web technology e security - Guido Boella 178
Comunicare XML
• Se una pagina sul client ha bisogno non solodi ricevere ma anche di inviare informazioniin XML si può usare protocollo XMLHTTPdi Microsoft
• Non è necessario usare GET e POST, néricaricare l'intera pagina sul client
• Possibilità di gestione sincrona o asincronadella risposta
Master in web technology e security - Guido Boella 179
Client
Page A
XMLfile A
Server
POSTXMLfile A
HTTP RESPONSE
Post
Master in web technology e security - Guido Boella 181
Client
Page A
XMLfile A
Server
XMLHTTPXMLfile A
HTTP RESPONSE
XMLHTTP
Master in web technology e security - Guido Boella 183
XMLHttpRequest Properties,Methods, and Events
Properties
onreadystatechange* Specifies the event handler to be calledwhen the readyState property changes. Read/write.
readyState Represents the state of the request. Read-only.
responseBody Represents the response entity body as anarray of unsigned bytes. Read-only.
responseStream Represents the response entity body asan IStream. Read-only.
responseText Represents the response entity body as astring. Read-only.
responseXML Represents the response entity body as parsedby the MSXML parser. Read-only.
Master in web technology e security - Guido Boella 184
status Represents the HTTP status code returned by arequest. Read-only.
statusText Represents the HTTP response line status.Read-only.
* denotes an extension to the W3C DOM.
Methods
abort Cancels the current HTTP request.
getAllResponseHeaders Retrieves the values of all theHTTP headers.
getResponseHeader Retrieves the value of an HTTP headerfrom the response body.
open Initializes a Microsoft.XMLHTTP request, andspecifies the method, URL, and authentication informationfor the request.
Master in web technology e security - Guido Boella 185
send Sends an HTTP request to the server and receives aresponse.
setRequestHeader Specifies the name of an HTTP header.
Master in web technology e security - Guido Boella 186
XMLHTTP Request<script language="javascript">
function sendit(){
var oMsg = new ActiveXObject("Microsoft.XMLHTTP")
oMsg.open("POST", "<%=sURL%>", false)
oMsg.setRequestHeader("MethodName", "enterOrder")
oMsg.setRequestHeader("MessageType", "Call")
oMsg.setRequestHeader("Content-Type", "text/xml-SOAP")
oMsg.send(oOrder.XMLDocument)
alert(oMsg.responseText)</script>
<xml id="oOrder"><root>
<description>Personal Stereo</description>
<price>76.34</price></root></xml>
Master in web technology e security - Guido Boella 187
XMLHTTP Response<% Response.ContentType = "text/xml"
Response.Expires = 0
Dim fso, logfile, xmldoc, strResult
Set xmldoc = Server.CreateObject("Microsoft.XMLDOM")
xmldoc.async=false
xmldoc.load(Request)
if xmldoc.parseError.errorCode <> 0 then … end if
strProcdate =server.HTMLEncode(cstr(FormatDateTime(Now,vbLongDate)))
strResult = "<orderconfirmation>Your order … "
response.write strResult %>
Master in web technology e security - Guido Boella 188
XMLHTTP request II
<script> function postXML() { var xmlhttp = new
ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.Open("POST",
"http://localhost/asp/aspxml/code/other/ping.asp", false); alert(XML.value); xmlhttp.Send(XML.value); alert("Round tripped XML document:¥n¥n" +
xmlhttp.responseXML.xml); }</script><textarea id=XML rows=12 cols=60><XML>This is the XML document that will be round
tripped...</XML></textarea>