Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
ASP Other
ADO
What is common Gateway Interface
Service The Common Gateway Interface (CGI) is a specification defined by the World Wide
Components
Cursor Web
Engine Query Processor
Consortium (W3C), defining how a program interacts with a Hyper Text Transfer
Protocol (HTTP) Server. The Common Gateway Interface (CGI) provides the
middleware between WWW servers and external databases and information sources.
Data Providers
ODBC Why is CGI Used?
Simple Data OLE DB
Main frame
An interesting
data aspect of a CGI enables Web server is that computer programs can be
created and deployed that can accept user input and create a Web page on the fly.
Interactive web pates enable a client to send information to the Web server and get back a
response that depends on the input.
HTTP CGI
Web Browser Web
CGI Program
Server
Disk Files
Database
The sequence of events for creating a dynamic HTML document on the fly through CGI
scripting is as follows:
• A client makes an HTTP request by means of a URL. This URL could be typed
into the ‘Location’ window of a browser, be hyperlink or be specified in the
‘Action’ attribute of an HTML <form> tag.
• From the URL, the Web server determines that it should activate the gateway
program listed in the URL and send any parameters passed via the URL to that
program.
• The gateway program processes the information and returns HTML text to the
Web server. The server, in turn, adds a MIME header and returns the HTML text
to the Web browser.
• The Web browser displays the document received from the Web Server.
• GET:
• –The Web browser submits the form’s data as a part of a URL.
• POST:
• –The web browser sends the form’s data separately from the URL as a stream of
bits.
The Web Server must be configured to recognize an HTTP request for a CGI program.
The URL specifying a CGI program looks like any other URL, but the Web Server can
examine the directory name and determine whether the URL is a normal document or a
CGI program.
The Web server expects the CGI program’s name to appear immediately following the
CGI directory (e.g. /cgi-bin/)
The Web Server must be configured to recognize an HTTP request for a CGI program.
The URL specifying a CGI program looks like any other URL, but the Web Server can
examine the directory name and determine whether the URL is a normal document or a
CGI program.
The Web server expects the CGI program’s name to appear immediately following the
CGI directory (e.g. /cgi-bin/).
Programming Languages
CGI programs have been developed in C, C++, Visual Basic Script (VB Script), Perl,
TCL, REXX, Python, Icon, AppleScript, Unix shell script, JavaScript, Java Server
Pages(JSP), Active Server Pages(ASP) and even Dos Batch files.
Static Contents
HTML was used to display linked static contents. It involved manually changing the
contents of HTML pages to customize it for different types of browsers. The server
received the request and sent the HTML document file. The browser then displayed the
document in the requested format. The interaction was limited to the user who was using
a browser and the Web Server. Web pages could not be made to interact with a user, and
they could not show dynamic content.
The systems used earlier involved custom servers delivering particular types of dynamic
content. With the development of Web servers, the need for displaying data dynamically
and also in a customized way arose. Client scripts are processed on the client side.
web server is able to process the requests of clients quickly since it does not not have the
overhead of processing script of the requested file.
Need for Sever-Side Scripting
The need for server-side scripting comes from the need for active web sites, using
information from the databases and customizing the content of the Web pages for each
user.
•The optimal Web page combines server-side and client-side scripting. The general rules
for using client-side and server-side scripting are:
•Any access to the data that resides on the client, such as the time or the type of browser
used, should be implemented with client-side scripting.
•Any access to data that resides anywhere except the client should be implemented with
server-side scripting.
•Minor changes to the HTML layout and properties should be managed on the client side.
•Major differences in the HTML or media that a client will receive should be managed on
the server side.
•Microsoft Active Server pages (ASP) was developed by Microsoft on July 16,1996, as a
powerful and easy technology to create dynamic web pages.
•The main purpose of ASP is to decrease the load on the browser by performing many of
the tasks done earlier by the browser, thus increasing the response time for each request.
•Using ASP, you can combine HTML pages, script commands, and ActiveX components
to create interactive Web pages.
•Microsoft Internet Information Server version 3.0 on Windows NT Server 4.0, Windows
2000 server
•Microsoft Peer Web Services version 3.0 on Windows NT Workstation 4.0, windows
2000 professional
•Microsoft Personal Web Server on Windows 95/98
How an ASP file Executes
Output in
<html>
ASP coding HTML format
</html>
HTTP Request
HTTP Response
ASP delimiters
An ASP file needs to be processed by the Web Server. To signify that the server, and not
the client should evaluate a section of the ASP file, ASP scripts uses the <% and %>
delimiters, or the <script> and </script> tags with the RUNAT attribute set to SERVER.
<html>
<head>
<title> Time Now </title>
</head>
<Body>
The current time is : <%=Time%>
</body>
</html>
<body>
<script language="VbScript" runat="server">
x=time
response.write "The current is" &x
</script>
</body>
<html>
<body>
This is first line of the page <br>
<% x=10*30
Response.write “The product of 10 and 20 is : “&x
%>
</body>
</html>
ASP Objects
•Server: This object is used to provide access to the methods and properties of the Web
server.
•Application: This object is used for the processes of a Web application that are shared by
all the users of the application.
•Session: This object used for storing user information that is needed for a particular
client session.
•Request: This is used to determine information about specific client request such as
whether it was GET or a POST and the cookies passed in the header.
•Response: This object is used to customize the response written from the server to the
client.
•ObjectContext: You can use ObjectContext object to either commit or abort a
transaction initiated by a script in an ASP. The transaction is managed by Microsoft
Transaction Server(MTS).
Server Object
•The ASP Server object can store user-defined variables, and also contain variables
whose values are tied directly to the server itself
•The variables stored in the Server object are common to all the Web pages on the Web
server.
•This enables the value to the same for all the users on all the pages.
Server Properties
•ScriptTimeout: property set the time limit for which a script will be allowed to process a
request.
<% Server.ScriptTimeout = 100 %>
Method
•URLEncode
Server.URLEncode(“<br> The proper way to write</br>”)
•HTMLEncode
Server.HTMLEncode("<br> The proper way to write </br>")
•MapPath: The MapPath method converts the name of a Web directory to the actual
directory path on the Server.
C:\inetpub\
C:\inetpub\aspscripts\test\
Server.MapPath(“/sample.txt”)
C:\inetpub\sample.txt
Server.MapPath(“sample.txt”)
C:\inetpub\aspscripts\test\sample.txt
Request Object
Collection
•Form: This is used to retrieve the values of the form elements in the HTTP request body
–Request.form(element)[(index)|.Count]
•Cookies: This is used to retrieve the values in the cookies sent in an HTTP request.
–Request.Cookies(cookie)[(key)|.attribute]
•QueryString: This is used to retrieve the values of variables in the HTTP query string.
–Request.QueryString(variable)[(index)|.Count]
•ServerVariables: This is used to retrieve the values of predetermined environmental
variables.
–Request.ServerVariables(server environment variable)
Property
•TotalBytes: This is a read-only property. It specifies the total number of bytes a client is
sending in the body of the request.
–Counter=Request.TotalBytes
Method
•To retrieve the data sent to the server from the client.
–Variant=Request.BinaryRead(count)
•The two instances when query strings should not be used are:
•When you need to pass hidden data
•When you are passing a large amount of data.
ServerVariables Collection
•The ServerVariables collection of the Request objec tis used to retrieve the headers that
are part of the request sent by the browser to the Web Server.
•The ServerVariables collection contains both headers and additional information about
the server.
The collections, properties, and methods of the Response object are given below:
•Collection
–Cookies: This is used to set the cookie values
–Response.cookies(cookie)[(key)|.attribute]=value
•Property
–Buffer: This is used to indicate whether the page output is buffered.
–Response.Buffer [=flag]
•CacheControl: This determines whether the proxy servers are able to cache the output
generated by ASP.
–Response.CacheControl[=Cache Control Header]
•Charset: This appends the name of the character set to the content-type header.
–Response.Charset(CharsetName)
•Content-type: This specifies the HTTP content type for the response.
–Response.ContentType [=ContentType]
•Expires: This specifies the length of time before a page cached on a browser expires.
–Response.Expires [=number]
•ExpireAbsolute: This specifies the date and time on which a page cached on a browser
expires.
–Response.ExpiresAbsolute [=[date] [time]]
•IsClientConnect: This indicates whether the client has disconnected from the server
–Response.isClientConnected()
–
•Status: This contains the value of the status line returned by the server.
–Response.status=StatusDescription
–
•Method
•AddHeader: This sets the HTML header name to value
–Response.AddHeader name,value
•AppendToLog: This add a string to the end of the Web server log entry for this request.
–Response.AppendToLog string.
•BinaryWrite: This writes the given information to the current HTTP output without any
character-set conversion.
•Clear: This erases any buffered HTML output.
–Response.clear
•End: This stops the processing of the .asp file and return the current result.
–Response.End
•Flush: This sends the buffered output immediately.
–Response.Flush
•Redirect: This sends a redirect message to the browser causing it to attempt to connect to
a different URL.
–Response.Redirect URL
•Write: This writes a variable to the current HTTP output as a string.
–Response.Write variant
When an Active Server Page is requested, the server processes the page As each line of
the page is being processed, the output is sent to the browser. It creates a cascading effect
of the output because it is displayed one line a time.
<%Response.Buffer=TRUE %>
<HTML>
<HEAD>
<Title> Buffered Output </title>
</head>
<body>
<%
For I=1 to 50
Response.write “Line Number :” &I& “<br>”
Next
%> </body> </html>
•The output is cached to improve system performance in terms of the speed of retrieval of
Web pages.
•If the page is stored in the cache of the browser, every time it is requested for, it can be
displayed from cache.
•The Response object properties, Expires, ExpireAbsolute and CacheControl, can be used
for controlling the caching of pages.
Redirect
<body>
<%
Response.Redirect "time.asp"
%>
</body>
•Web applications used to store a part of the data for future use.
•The data can be stored in databases, electronic spreadsheets, or even text files.
•To access the data that is stored in databases, there are various methods. The main data
access techniques are listed below:
•MDAC-Microsoft Data Access Components (MDAC), contains all the software
components of Microsoft for database access.
•ADO-ActiveX Data Objects (ADO) provides an object-oriented programming interface
for accessing data sources such as Mircrosoft SQL Server and Microsoft Access. You can
use ADO directly in ASP to access data sources.
•ADOX- ADO Extensions (ADOX) for DLL and security is a a collection of objects that
helps to manage database objects.
•RDS- Resource Data Service (RDS) is collection of objects that enables us to
communicate with data sources that located remotely.
•OLE DB- OLE DB is a system-level interface to data providers. ADO uses the set of
interfaces provided by OLE DB to communicate with data sources.
•ODBC- Open Database Connectivity (ODBC) is a standard developed by Microsoft to
simplify the development of applications that need to be independent of database
platforms. ODBC is implemented through a collection of database drivers that are
provided by Microsoft and third party vendors. ODBC database drivers contain driver
libraries that provide an application with the functionality to utilize a variety of database
formats.
•ActiveX Data Objects (ADO) provide and object-oriented programming interface for
accessing a data source by and OLE DB data provider. ADO objects provide fast and
easy access to all types of data. The ADO object model has three components:
•Connection object
•Command Object
•Recordset Object
•Connection Object: The connection object is used to make a connection between an
application and an external data source, such as Microsoft SQL Server, Microsoft Access,
or a text file.
•Command Object: The command object is used to build queries including user-specific
parameters and to access records from a data source, typically, these records are returned
in a Recordset object.
•Recordset Object: is used to access the records returned by a SQL query. Using this
object , you can navigate through the records returned, add new records, modify existing
records, and delete specific records.
ADO Collections
•Errors Collection: is used to return detailed information about runtime errors or other
messages.
•Parameters Collection: is used to pass specific data to a parameterized query or the
stored procedures in a SQL database.
•Fields Collection: The fields Collection is used to to access specific fields in an existing
Recordset object.
<%
Set myConnection=Server.CeateObject(“ADODB.Connection”)
myConnection.open “provider= microsoft.jet.oledb.4.0; data source=c:\mydatabse.mdb”
%>
<%
Set myConnection=Server.CreateObject(“ADODB.Connection”)
myConnection.open “provider=sqloledb; data source=school; uid=sa; pwd=admin;
database=school”
Using the databse
----
---
myConnection.Close
Set myConnection=nothing
%>
Command Object
•The command object represents a command, that is, a SQL statement that can execute
against any data source. The command object is optional in an ADO model because some
data providers cannot supply command execution, but the object is supported if the
provider supports the commands
•A command object requires a Connection object. The data returned on the execution of
command is accepted and stored in a Recordset object.
Property
•ActiveConnection
•CommanText
•CommandType
•Prepared
•State
•Name
Method
•Execute: execute the SQL statement or stored procedures specified in the CommandText
property
•Cancel: Cancels the currently executing command
•CreateParameter: creates a new Parameter object with the specified properties.
Set myConnection=Server.CreateObject(“ADODB.Connection”)
myConnection.open “provider=sqloledb; data source=school; uid=sa; pwd=admin;
database=school”
Set myCommand=Server.CreateObject(“ADODB.Command”)
myCommand.ActiveConnection=myConnecton
myCommand.CommandText=“select * from student”
Set myRecordset = myCommand.Execute
Recordset Object
•ADO recordsets are used to display records that are retrieved from a database table in an
Active Server Page.
•Some of the properties of the Recordset object are given below:
•AbsolutePage
•AbsolutePosition
•ActiveConnection
•BOF
•Eof
•Bookmark
•Cachesize
•CursorType
•EditMode
•LockType
•MaxRecords
•PageCount
•PageSize
•RecordCount
•Source
•Status
•MarshallOption
•CursorLocation
•Filter
Methods
•AddNew
•CancelBatch
•Clone
•Delete
•GetRows
•Move
•MoveFirst
•MoveLast
•MoveNext
•MovePrevious
•NextRecordSet
•Open
•Requery
•Resync
•Supports
•Update
•UpdataBatch
•Close
•A Recordset object need not be created explicitly. The Recordset object is returned
automatically by the Connection object when the SQL Query is executed.
•Syntax
•Set recordset object=<connection object>.execute <SQL query statement>
Creating RecordSets
•RecordSet.Open [source],[activeConnection],[cursortype],[locktype],[options]
•adOpenForwardOnly 0 Forward-only
•adOpenkeyset 1 Keyset-driven
•adOpenDynamic 2 Dynamic
•adOpenStatic 3 Static
Locking Records
•In a multi-user environment, more than one user can simultaneously access a recordset
residing on the server. When more than user requires to update a record in a database
table, it can lead to conflicts.
•This called the problem of cocurrency.
•Such problems can be avoided by locking the Recordset object.
•The LockType property of the RecordSet object determines the type of lock placed on
the data of the associated database during editing.
•LockType
•adLockUnspecfied -1 does not specify the lock
•adLockReadOnly 1
•adLockPessimistic 2
•adLockOptimistic 3
•adLockBatchOptimistic 4
Fields Collection
•This Fields collection contains a Field object for each field(column) in the recordset.
•The fields collection is the default collection of the recordset, and can therefore be
omitted when accessing fields
•rsAuthors.Fields(“au_lname”).value
•rsAuthors(“au_lname”).value
•rsAuthors(1).value
•rsAuthors.Fields(1).value
Filtering RecordSets
Location of Recordsets
ASP-based
Application
Data Request
Database
Data Response
Client Side
•In an ASP-based application, whenever a recordset is created, it is, by default, created as
server-side cursor.
•ASP allows client-and server-side cursors. A cursor that is used on the server-side is
opened and managed by the machine that has the database.
•When a client-side cursor is used, it is opened and managed by the machine hosting the
Active Server Page.
Syntax
RecordsetObject.CursorLocation=locationType
adUseNone: The recordset does not support cursors. This is to enable backward-
compatibility with databases that do not have a cursor object.
adUseClient: The recordset is created on the client machine
asUseServer: The recordset is created on the server machine.
<%
Set MyConnection=Server.CreateObject(“ADODB.Connection”)
MyConnection.Open “PROVIDER=SQLOLEDB;DATA
SOURCE=schoolmgt;UID=sa;PWD=admin;DATABASE=school”
myCommand=“select * from student”
Set MyRecordset=Server.CreateObject (“ADODB.Recordset”)
MyRecordset.CursorLocation=adUseClient
MyRecordset.CursorType=adOpenDynamic
MyRecordset.open myCommand, MyConnection
%>
Maintaining state
ASP applications are used to retain information that may be used by other web pages.
This is also called maintaining state in ASP.
An ASP application maintains two types states:
The application state retains the information of the application that is available to all the
users of the application.
The session state retains the information that is required by a specific user in a session. A
session starts when a user requests for a page from a web site and ends when the
user leaves the web site.
Application Object
An Application object is used to initialize an application, automatically start processes
that are required for an application, and allow the declaration of variables that can
be used by all the users and across all the pages.
Controlling the Start and End of an Application Using the Global.asa file
The Global.asa file resides in the same folder as the application. An application generates
certain events such as when it starts for the first time or when it ends.
Global.asa file contains scripts for the start and end events of an application or a session.
Each application can have only one global.asa file attached to it.
Application variable is used to store data that can be accessed throughout all the pages of
the application and by all the users of the application.
An application can contain any type of data, including arrays and objects.
Display momentary information on every web page, for example, to display the daily
news updates
Count the number of times a user has accessed the site
Hold the data retrieved from the database and display the details on multiple web pages
Enable communication among users, for example, to create applications that help users to
chat.
Session Object
The session object is used to store the information required for a particular session by a
specific user.
The variables stored in the Session object are available to users throughout the
application for a particular session.
The web server automatically creates a Session object for a user who requests for a page
of an application if the user does not already have a session.
The web server destroys the Session object when the session is terminated or timed out.
TimeOut: it has the timeout period for the session state of the current application, in
minutes.
Session.TimeOut=minutes
SessionID: it returns the session ID for the user of the current session.
Session.SessionID
File Handling in ASP
GetDrive (drivespec)
GetDriveName(drivespec)
copyFolder(source,destination,overwrite)
CreateFolder(foldername)
DeleteFolder(folderspec,force): if the optional force parameter is set to True, the folders
will be deleted even if their read-only attribute (or that of any contained files) is set.
The default for force is False.
FolderExists (folderspec): Returns True if the folder specified in folderspec exists, or
False is not.
GetFolder (folderspec): Returns a Folder object corresponding to the folder specified in
folderspec.
GetParentFoldrName (pathspec): Returns the name of the parent folder of the file or
folder specified in pathsepc. Does not check for existence of the folder.
MoveFolder(source,destination)
GetFileName(pathspec): Returns the name part of the path and filename specified in
filespec.
MoveFile(source,destination): Moves the file or files specified in source to the folder
specified in destination. Wildcards can be included in source but not in destination.
OpenTextFile(filename,iomode,create,format): Create a file named filename, or opens an
existing file named filename, and returns a TextStream object that refers to it.
(contd..)
The iomode parameter specifies the type of access required. The permissible values are
ForReading(1 the default), ForWriting(2), and ForAppending(8).
If create parameter is set to True when writing or appending to a file that does not exist, a
new file will be created. The default for create is False.
The format parameter specifies the format of the data to be read from or written to the
file. Permissible values are TristateFalse(0-default) open it as ASCII,
TristateTrue(1) to open it as Unicode, and TriStateDefault(2) to open it using the
system default format.
IsReady: Returns a Boolean value indicating if the drive is ready(true) or not (False).
Path: Returns the path for the drive as a drive letter and colon, I.e. “C:”
RootFolder: Returns a Folder object representing the root folder of the drive.
SerialNumber: Returns a decimal serial number used to uniquely identify a disk volume.
ShareName: Returns the network share name for the drive if it is a networked drive.
TotalSize: Returns the total size (in bytes) of the drive.
VolumeName: sets or returns the volume name of the drive if it is a local drive.
DateCreated: Returns the date and time that the folder was created.
DateLastAccessed: Returns the date and time that the folder was last accessed.
DateLastModified: Returns the date and time that the folder was last modified.
Drive: Returns the drive letter of the drive on which the folder resides.
Files: Returns a Files collection containing File objects representing all the files within
this folder.
IsRootFolder: Returns a Boolean value indicating if the folder is the root folder of the
current drive.
Name: Sets or returns the name of the folder.
ParentFolder: Returns the Folder object for the parent folder of this folder.
Path: Returns the absolute path of the folder, using long file names where appropriate.
Copy (destination,overwrite)
Delete (force)
Move()
CreateTextFile(filename,overwrite,unicode)
Path: Returns the absolute path of the file, using long file names where appropriate.
Shortname: Returns the DOS-style 8.3 version of the file name.
ShortPath: Returns the DOS-style 8.3 version of the absolute path of this file.
Size: Returns the size of the file in bytes
Type: Returns a string that is description of the file type (such as “Text Document” for
a .txt file) if available.