Professional Documents
Culture Documents
Visual Basic
Visual C++
ASP
Other
What is common Gateway Interface
ADO
The Common Gateway Interface (CGI) is a specification defined by the World Wide Web
Service
Consortium (W3C), defining how a program interacts with a Hyper Text Transfer
Components
Protocol
(HTTP) Server. The Common
Gateway Interface (CGI) provides the
Cursor
Engine
Query Processor
middleware between WWW servers and external databases and information sources.
Why is CGI Used?
Data Providers
Simple Data
OLE DB
ODBCAn interesting
aspect of a CGI enables Web server is that computer programs can be
Main
frame that can accept user input and create a Web page on the fly.
created and
deployed
data
Interactive web pates enable a client to send information to the Web server and get back a
response that depends on the input.
Web Browser
HTTP
Web
Server
CGI
CGI Program
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.
How information is transferred from the Web Browser to a CGI program
GET:
The Web browser submits the forms data as a part of a URL.
POST:
The web browser sends the forms data separately from the URL as a stream of
bits.
Output in
<html>
ASP coding
</html>
HTML format
Client
Request
HTTP Request
Web Server
Browser
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>
Save the coding in a file with .asp as an extension
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
CreateObject: method is ued to create an instance of a component. The ASP built-in
objects cannot be directly instantiated; the web server handles their instantiation itself.
After an object is initialized, its methods and properties are accessed using the same
syntax as that used for built-in objects.
<% myObj=Server.CreateObject(The component) %>
<% myObj.ExecuteRoutine %>
Request Object
It requires to collect information from a user.
The Request object consists of various properties, methods, and collections.
Syntax
Request[.collection|property|method](variable)
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
Buffering the Output
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>
Caching the Output
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
This sends a redirect message to the browser causing it to attempt to connect to a
different URL.
Syntax: Response.write URL
<body>
<%
Response.Redirect "time.asp"
%>
</body>
Data Access Techonology
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.
Universal Data Access Architecture
Microsoft Data Access Components (MDAC) is the practical implementation of the
UDA architecture.
Universal Data Access is a platform for developing enterprise-wide applications that
need access to various relational and non-relational data sources across a network.
UDA architecture consists of three parts: data consumers, services components, and data
providers.
Data Providers: Data providers are components that represent data sources such as SQL
databases, indexed sequential files, and spreadsheets. In an OLE DB environment, these
data providers expose OLE DB interface. Data consumers or service components can
directly access these interfaces.
Service Components: Service components act as an interface between data providers and
data consumers. The are implemented as components.
Data Consumers: Data Consumers are applications that retrieve data from service
components. ADO are used as the programming interface for using OLE DB data. Any
application that uses ADO can be termed as an OLE DB data consumer.
ActiveX Data Objects
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.
Connecting to Microsoft SQL server
<% Set myConnection=Server.CreateObject(ADODB.Connection)
myConnection. Open PROVIDER=SQLOLEDB; DATA SOURCE=schoolmgt; UID=sa;
PWD=admin; DATABASE=school %>
Or
<% Set myConnection=Server.CreateObject(ADODB.Connection)
myConection.PROVIDER=SQLOLEDB
myConnection.ConnectString= DATA SOURCE=schoolmgt; UID=sa; PWD=admin;
DATABASE=school
myConnection.Open %>
Connecting to a Mircrosoft Access DatabaseInserting Records into a Database table
<%
Set myConnection=Server.CeateObject(ADODB.Connection)
myConnection.open provider= microsoft.jet.oledb.4.0; data source=c:\mydatabse.mdb
%>
Closing a SQL Connection
<%
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
Creating a Recordset Object
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]
Different types of Recordsets in ADO
Static cursor: It provides a static copy of the set of records for us to find data or
gernerate reports. Additions, changes, or deletions by other users are not visible.
Dynamic Cursor: It allows changes to the view due to the additions, changes, and
deletions by other users.
Keyset-driven Cursor: It functions line a dynamic cursor, except that it prevents us from
viewing the records that other users add and prevents access to the records that others
users delete.
Forward-only Cursor: It functions identically to a static cursor, except that it only allows
us to scroll forward through the records.
Default cursor type is forward-key cursor while opening the recordset without specifying
the recordset type.
Value that assigned to the CursorType property
adOpenForwardOnly 0
adOpenkeyset
1
adOpenDynamic
2
adOpenStatic
3
Forward-only
Keyset-driven
Dynamic
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
Location of Recordsets
ASP-based
Application
Data Request
Database
Client Side
Data Response
In ASP, each virtual directory on a Web Server is an application, and all the files
and folders in that virtual directory form a part of the application.
It triggers various application scripts based on an event. For example, the start of
an application is an event.
A web site can have different applications, each having individual properties.
Each application can be run in its own memory space, resulting in more security
fo information.
An Application Object
ASP applications are used to retain information that may be used by other web
pages. This is also called maintaining the state in ASP.
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.
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
Lock: it prevents other clients from modifying the properties of the Application
object.
Application.Lock
Unlock: it allows the clients to modify the properties of the Application object.
Application.Unlock
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.
<script language=vbscript runat=Server>
Sub application_onStart
Application.lock
Application(custname)=Jennie
Application.unlock
End sub
Sub Application_onEnd
..
End sub
Application Variables
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.
Some of the purposes of application variables are to:
Display momentary information on every web page, for example, to display the
daily news updates
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.
A Session Object Method
Session.Abandon
A Session Object Property
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
It is one of the objects provided by the Scripting Runtime Library, and is available
in VBScript and Jscript for use in ASP pages on the Server.
It can also be used client-side in IE 5, providing that the pages have the .hta file
extension to indicate that they are part of a Hypertext Application (HTA).
The FileSystemObjects Property
The FileSystemObject object has a single property that allows us to retrieve a list
of all the valid drives on the current machine:
Drives: Returns a collection of Drive objects that are available from the local
machine. This includes network drives that are mapped from this machine.
The FileSystemObjects Methods
GetDrive (drivespec)
GetDriveName(drivespec)
copyFolder(source,destination,overwrite)
CreateFolder(foldername)
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)
Methods for working with Files
Copyfile(source,destination,overwrite)
GetFileName(pathspec): Returns the name part of the path and filename specified
in filespec.
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.
The Drive Object
AvailableSpace: Returns the amount of space available to this user on the drive,
taking into account and/or other restrictions.
DriveType: Returns the type of the drive. The values are Unknown(0),
Removable(1), Fixed(2), Network(3), CDRom(4), and RamDisk(5).
FileSystem: Returns the type of file system for the drive. The values include
FAT, NTFS and CDFS.
FreeSpace: Returns the actual total amount of free space available on the drive.
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.
VolumeName: sets or returns the volume name of the drive if it is a local drive.
ShareName: Returns the network share name for the drive if it is a networked
drive.
The RootFolder property of the Drive object returns a Folder object, through
which we can access all of the content of this drive. We can use the properties and
methods of the folder object to traverse directories on the drive, and to get at all the
properties of this or any folder.
The Folder Objects Properties
The folder object provides a set of properties that we can use to get more
information about current folder, and to change the folder name:
Attributes: Returns the attributes of the folder. Can be a combination of any of the
following values: Normal(0), ReadOnly(1), Hidden(2), System(4), Volume(Name)(8),
Directory(folder)(16), Archive(32), Alias(64), Compressed(128).
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.
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.
Type: Returns a string that is a description of the folder type (such as Recycle
Bin) if available.
The Folder Objects Methods
The Folder object provides a set of methods that can be used to copy, delete and
move the current folder. The work in the same way as the CopyFolder, DeleteFolder and
MoveFolder methods of the FileSystemObject object, but dont require a source
parameter because the source is this folder.
Copy (destination,overwrite)
Delete (force)
Move()
CreateTextFile(filename,overwrite,unicode)
The File object provides access to the properties of a file, and implements
methods that we can use to manipulate the at file.
The File Objects Properties
The file object has series of properties that are similar to the Folder object:
Attributes:
Returns the attributes of the file. Can be a combination of any of
the following values: Normal(0), ReadOnly(1), Hidden(2), System(4), Volume(Name)(8),
Directory(folder)(16), Archive(32), Alias(64) and Compressed(128).
DateCreated: Returns the date and time that the file was created.
DateLastAccessed: Returns the date and time that the file was last accessed.
DateLastModified: Returns the date and time that the file was last modified.
Drive: Returns a drive object representing the drive on which the file resides.
Name: Sets or returns the name of the file.
ParentFolder: Returns the Folder object for the parent folder of this file.
Path: Returns the absolute path of the file, using long file names where
appropriate.
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.
The methods of the File object allow us to copy, delete and move the file. Theres
also a method hat we use to open the file as text stream:
Copy(destination, overwrite)
Delete(force)
Move()
CreateTextFile(filename,overwrite,unicode)
OpenAsTextStream(unicode,format)