Transcript aspAllPrint

Web Application Development
with
Active Server Pages
David Henson
[email protected]
http://www.certifiednetworks.com
Introductions
Class Logistics
•
•
•
•
•
3 Meetings
Class Hours – 8:00 to 4:00
Breaks as needed
One Hour Lunch
Suggested Reading:
– Professional Active Server Pages 3.0
• Handouts
Classroom Setup
• Windows 2000 Server Default Installation
• Full Internet IP Connectivity
• SQL7 Default Install
Course Overview
•
•
•
•
•
•
Definitions
Module 1 – Overview
Module 2 – Structure of ASP
Module 3 – Browser/Server Communication
Module 4 – Database Connectivity
Module 5 – Updating Data
Course Overview, Contd.
• Module 6 – Advanced SQL7 Techniques for
Dynamic Sites
• Module 7 – Security
• Module 8 – Email Communication
• Module 9 – Logging Visits
• Module 10 – Dealing with Browsers
Course Overview, Contd.
• Module 11 – OLE Automation
• Module 12 – XML
Definitions
•
•
•
•
•
•
•
ASP
IIS
SQL
HTML
HTTP
SSL
Tags
•
•
•
•
•
•
Browser
IP Address
ADO
OLE/DB
COM
GUID
Module 1 – Overview
•
•
•
•
•
Client Server Communication
On the Back End
On the Front End
Software Configuration
Networking
Client Server Communication
HTTP://…
HTTP://…
On the Back End
• Many Available Options:
– UNIX/LINUX, NT
– Apache, IIS
– ASP, Perl, PHP, C++, VB
On the Front End
•
•
•
•
•
•
Internet Explorer
Netscape
Others
PDAs – Palm Pilot, Windows CE
Cell Phones, Voice Mail Gateway
Crawler, Spider, Other Automated Engines
Software Configuration
• Common Settings for IIS
– Virtual Server
– Virtual Site with host headers
• Common Settings for NT/Windows 2000
– Securing Data with NTFS
Networking
• Name Resolution
– DNS, WINS, LMHOSTS
• Mapping Drives
• FTP
Module 2 – Structure of ASP
•
•
•
•
HTML Tags
ASP Tags
Server Side Includes
Intrinsic Objects
– Request, Response, Server, Application, Session
• Demonstration – Structure of ASP
Common HTML Tags
•
•
•
•
•
•
•
<TABLE></TABLE>
<TR></TR>
<TD></TD>
<FORM></FORM>
<META …>
<HEAD></HEAD>
<BODY></BODY>
•
•
•
•
•
•
<BR>
<HR>
<P></P>
<B></B>
<FONT></FONT>
<INPUT ….>
Common ASP Tags
• <SCRIPT RUNAT=“Server”> </SCRIPT>
• <% %>
• Examples:
<%=variable%>
<%=Request(“firstname”)%>
Common VBScript Syntax
•
•
•
•
Set
If…then
While
String Manipulation– Left(string, 4)
– Right(string, 4)
– Mid(string, 4, 2)
• Various Functions:
IsNull(somevar)
Server Side Includes
• <!--#Include file=“CheckVars.asp”-->
• <!--#Include virtual=“/CheckVars.asp”-->
Intrinsic Objects
•
•
•
•
•
•
Application
Response
Server
Session
Request
ObjectContext
Demonstration – ASP Structure
Lab 2A – Using Basic HTML
and ASP Tags
Module 3 – Communicating Between
Browser and Server
•
•
•
•
•
•
•
Forms
Hidden Inputs
Request Object
Application Object
Session Object
Other Objects
Lab – Browser/Server Communication
Forms
Demo.asp
<%
If not request(“somedata”) = “” then
response.write(“The data is:” & somedata & “<br>”)
end if
%>
<FORM ACTION=“Demo.asp” METHOD=“POST”>
<input type=“text” name=“somedata”>
<input type=“submit”>
</FORM>
Hidden Inputs
<input type=“hidden” name=“test” value= “<%=request(“test”)%>” >
Request Object
• Exposes for use:
– Form Data
– Href parameters
– ServerVariables Collection
Application Object
• Starts up when the first user hits the site
• Ends when the server is shut down
Session Object
• Relies on cookies
• Makes information persistent between pages
• Can be troublesome:
– DNS Round Robin
– Load Balancing
– Timeout, Cookies not allowed by browser
Session Example
…
Session(“userid”) = request(“userid”)
…
Lab 3A – Exploring
Servervariables
Module 4 – Database Connectivity
•
•
•
•
•
•
ADO
Creating an object
Opening the connection
Cursors
Locks
Navigating the recordset
ADO
• Active Data Objects - Microsoft object model that
encapsulates OLE/DB database connectivity
• Main Objects:
– Connection
– Recordset
– Field
• ADOVBS.INC
Creating an object
<%
set cn =
server.createobject(“ADODB.Connection”)
Set rs =
server.createobject(“ADODB.Recordset”)
%>
Opening the connection
<%
cnstring
cnstring
cnstring
cnstring
cnstring
=
=
=
=
=
“PROVIDER=SQLOLEDB;”
cnstring & “SERVER=tws;”
cnstring & “UID=sa;”
cnstring & “PWD=hello;”
cnstring & “DATABASE=cdcollection;”
cn.open cnstring
%>
Opening the recordset
Rs.open source, connection[, cursortype, locktype, options]
<%
sql = “select * from table1”
rs.open sql, cn
%>
Cursors
• From adovbs.inc…
–
–
–
–
Const adOpenForwardOnly = 0
Const adOpenKeyset = 1
Const adOpenDynamic = 2
Const adOpenStatic = 3
Locks
• From adovbs.inc
–
–
–
–
Const adLockReadOnly = 1
Const adLockPessimistic = 2
Const adLockOptimistic = 3
Const adLockBatchOptimistic = 4
Navigating the recordset object
•
•
•
•
•
•
Rs.BOF
Rs.EOF
Rs.movenext
Rs.moveprevious
Rs.movelast
Rs.movefirst
Recordset navigation example
…
<table>
<% do while not rs.eof%>
<TR>
<TD><%=rs.(“firstname”)%></TD>
<TD><%=rs(“lastname”)%></TD>
</TR>
<%rs.movenext%>
<%next%>
</table>
…
Cleaning up
<%
rs.close
cn.close
set rs = nothing
set cn = nothing
%>
Concurrency Issues
• Locking Records:
– Increases data integrity
– Increases contention
– Reduces concurrency
Demonstration - SQL7 Locks and
Transactions
Lab 4A - Database Connectivity
• Part One - Dynamic Page
• Part Two - Universal Database Reader
Module 5 – Updating Data
Methods for Inserts
• INSERT table1 VALUES(‘smith’)
• <%
Rs.addnew
Rs.lastname = “smith”
Rs.update
%>
Methods for updates
• UPDATE table1 SET lastname = ‘smith’
• <%
Rs.lastname = “smith”
Rs.update
%>
Methods for Deletions
• DELETE table1 WHERE lastname = ‘smith’
• <%
Rs.delete
%>
Datatype/space issues
• Single quotes are represented by two single quotes in
ANSI SQL…ADO takes care of it for you
• Do not exceed size limits of field…limit with
maxlength= inside of <input> tags. Example:
• <input type=“text” maxlength=“30”>
Optimizing your queries
• Use SQL Server profiler to spy on your queries
• Firehose cursor = no cursor = superfast!
• Set your cache size on the recordset. Example:
<%
Rs.cachesize = 100
%>
Demonstration - Creating an ASP class
chatroom
Lab 5A – Database
Include File
Module 6 – Advanced SQL 7/ASP Techniques
•
•
•
•
Using Stored Procedures
Firehose Cursors
Dynamic .asp Text File Creation
Server Side CMD Directives
Using Stored Procedures
• Definition: SQL Script with a pre-defined query plan
• Creating Stored Procedures
• Using Parameters with Stored Procedures
• Calling Stored Procedures From ASP
Creating Stored Procedures
CREATE PROC pr_demo AS
BEGIN
select * from table1
END
Creating Stored Procedures with
Parameters
CREATE PROC pr_demo
@fname varchar(30)
AS
BEGIN
SELECT * FROM table1
WHERE firstname = @fname
END
Calling from ASP
• Example:
<%
set cmd=server.createobject(“ADODB.Command”)
Cmd.ActiveConnection = conn
Cmd.CommandText = “pr_demo”
Cmd.CommandType = adCmdStoredProc
Cmd.Execute
%>
Calling w/Parameters from ASP
• cmd.CreateParameter(“@varname, adDataType,
direction, size, defaultvalue”)
• Partial Example:
<%
…
set p1 = cmd.CreateParameter(“@fname”, …)
cmd.parameters.append p1
cmd.Parameters(“@fname”) = request(“fname”)
cmd.Execute
%>
Firehose Cursors
•
•
•
•
•
SQL7 specific
Not using any cursor, freeing resources
SQL7 dumps data as fast as possible
Created when no cursor is specified
Example:
<%
RS.open conn, sql, , adLockReadOnly
%>
Dynamic .asp Text File Creation
• If table does not update frequently, SQL7 can push
out .asp text file into web directory as needed
• Use SQL7 web publishing wizard to create
Server Side CMD Executions
• Allows execution of server side operating system
commands from an .asp file
• Requirements:
– Manual registry change:
– Operating System Rights (No anonymous access)
CMD Execution Registry Change
• Always back up before running regedit.exe to add the
following registry change:
• Location:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet
\Services\W3SVC\Parameters
• Add:
SSIEnableCmdDirective
: type DWORD
CMD Execution User Privileges
• Any command that needs network or operating
system privileges needs the user to be administrator
(non-anonymous)
• Remove anonymous access from the page or from
the site
CMD Execution .asp Code
• Examples:
<!--#exec CMD=“cmd.exe /c net stop mssqlserver”-->
<!--#exec CMD=“cmd.exe /c rebootNT.exe”-->
Lab 6A – Advanced
SQL7/ASP Techniques
Module 7 – Security
•
•
•
•
•
Security Methods
When to use SSL
Setup of SSL Certificate Authority
Setup of SSL Server Certificate
Using Client Certificates
Security Methods
• Server Certificates
• SSL and HTTPS://
• VPN
When to Use SSL
•
•
•
•
Up to 20 times more expensive
Only use when sending/receiving sensitive data
Dialog Box Popup Problems
Links from unsecure pages must include full URL…
– Example:https://www.certifiednetworks.com/secure
Setup of SSL Certificate Authority
• See http://www.verisign.com
• Can setup your own authority for internal use
Setup of SSL Server Certificates
• Step 1 – generate key request, send to authority
• Step 2 – if you are the authority, process request
• Step 3 – install key by supplying password
Using Client Certificates
• Used to verify client identity without using NT
Authentication or Basic Authentication
• Maps client to an NT Account on a one-to-one basis
or a one to many basis
• See http://www.verisign.com for further information
Module 8 – Email Communication
•
•
•
•
How Internet Email Works
Using CDONTS
Using emailto link
Lab – Using CDONTS.NewMail Object
How Internet Email Works
• DNS Lookup for MX record
• Port 25 Connection
• SMTP Protocol used for communication
CDONTS
• Collaboration Data Objects – A set of COM objects
used for email interaction
• CDONTS.NewMail object for simple email
communication from a web page
• NewMail requires SMTP IIS service to be installed
locally
CDONTS.NewMail Example
{…
body = “Info:” & rs(“info")
set ml = server.createobject("CDONTS.Newmail")
ml.from = “[email protected]"
ml.to = request("email")
ml.subject = "The info you requested"
ml.body = body
ml.send
…}
Lab 8A – Using an include file with
CDONTS.Newmail for Notification
Module 9 – Logging Visitors
• Standard IIS Logging
• Logging to an ODBC Datasource
• Using an Include File for Logging/Notification
Standard IIS Logging
• Logs to text file in winnt/system32/logfiles folder
• Formats:
– W3C Extended Log File Format
– NCSA Common Log File Format
• Enabled in properties of the web site, and set on/off
in virtual directory, or folder/file in IIS Manager
Logging to an ODBC Datasouce
• Can be slower than text files
• Database schema must be set up correctly
• Must set up odbc datasource in control panel
• More flexible for reporting purposes…can use SQL
queries to analyze data
ODBC Logging Schema
•
•
•
•
•
CREATE TABLE [dbo].[iislog] (
[ClientHost] [varchar] (255) NULL ,
[username] [varchar] (255) NULL ,
[LogTime] [datetime] NULL ,
Etc….
• See http://www.certifiednetworks.com under utilities
for the sql script for iis logging
Using an Include File for
Logging/Notification
• Use Include file for logging whatever info you want
to your own database..login ID, and of the server
variables, time/date, etc.
• Use include file for sending an email notification
when a page is hit
Lab 9A – Setup of
ODBC Logging
Module 10 – Dealing with browsers
Browser Compatibility Issues
• All browsers are not alike!
• Areas that differ:
– Forms
– Tables
– Fonts
– Tab
– Back Button
– Client Side Javascript/VBScript
Choosing Site Features
IE4/5
Dynamic HTML
ActiveX Controls
<STYLE> formats
Client-side Javascript
Java Apps
HTML Frames
HTML Tables
Direct Text Formatting
HTML Controls
HTML 2.0
Nav 4.x
IE3
Nav3
Nav2
IE2
Other Browsers
??
??
??
??
Testing Websites
• Never assume anything logical is going to happen!
• Make sure your site fails gracefully if you choose
newer technologies and advanced features
Browser Market Share
• Recent Statistics:
– Approximately 50% IE4.x and 5.x
– Approximately 45% Netscape 4.x
• See http://browserwatch.internet.com
Discovering Browser Types
<%
agent = request.servervariables(“HTTP_USER_AGENT”)
%>
• Parse the string for browser type/version
• Option 2: Browsecap component
PDA Limitations
• Limited screen sizes
• Limited support for advanced features
• Basically text-only, limited sites
• WML Specification - new spec for cell phone sites
Lab 10A – Browser
Compatibility
Module 11 – OLE Automation with Excel and
Other Objects
Creating Server Side Objects
• Server.createobject(“PROGID”)
• Example:
– Server.createobject(“Excel.Application.8”)
• Runs in the context of localsystem
Examples:
•
•
•
•
•
Webcams
Email
Document Creation
Notification
Anything!
Object Models
• Each object/application will have its own model
• Excel.application
• Word.application
• Etc….
Lab 11A – Server Side
OLE Automation with Excel
Module 12 - XML
Extensible Markup Language
• Your Tags Have Semantic Meaning
Requirements of an .xml page
• <?xml verion=“1.0”?>
• Extremely precise formatting of text:
• Example:
<begin></begin>
.XML Page Example
<?xml version="1.0"?>
<?xml:stylesheet href="test.css" type="text/css" ?>
<demotable>
<Record>
<personid>1</personid>
<fname>dave</fname>
</Record>
.CSS Style Sheets
PersonID{
Background-Color : ChartReuse;
Color : blue;
Font-Size : 90;
Text-Transform : uppercase;
}
fname{
Background-Color : AntiqueWhite;
Font-Size : x-large;
Line-Height : 200%;
Z-index : (... Any other number ... 3.23 for example);
}
Using ASP to Dynamically Generate
XML pages
Lab 12A – Using XML