Beruflich Dokumente
Kultur Dokumente
When you are working with an application, you open it, do some changes and then
you close it. This is much like a Session. The computer knows who you are. It
knows when you start the application and when you end. But on the internet there
is one problem: the HTTP address doesn't maintain state so that the web server
does not know who you are and what you do.
By creating a unique cookie for each user,ASP solves this problem . The cookie is
sent to the client and it contains information that identifies the user. This interface
is called the Session object.
For a user session,the Session object is used to store information about, or
change settings . Session object is a variable that holds information about one
single user, and are available to all pages in one application. Common information
stored in session variables are name, id, and preferences. The server creates a
new Session object for each new user, and destroys the Session object when the
session expires.
If a user has not requested or refreshed a page in the application for a specified
period,a session ends . By default, this is 20 minutes.
you can set the Timeout property if you want to set a timeout interval that is
shorter or longer than the default,
The example below sets a timeout interval of 10 minutes:
<%
Session.Timeout=10
%>
<%
Session.Abandon
%>
Note: WHEN they should end is the main problem with sessions. If the user's last
request was the final one or not we do not know. So how long we should keep the
session "alive", we do not know. Waiting too long for an idle session uses up
resources on the server, but the user has to start all over again because the
server has deleted all the information if the session is deleted too soon. Finding
the right timeout interval can be difficult!
Tip: If you are using session variables, store SMALL amounts of data in them.
You can store variables in it is the most important thing about the Session object .
.
The example below will set the Session variable username to "Martin Luther" and
the Session variable age to "40":
<%
Session("username")="Martin Luther"
Session("age")=40
%>
It can be reached from ANY page in the ASP application if the value is stored in a
session variable :
Welcome <%Response.Write(Session("username"))%>
<%
If Session.Contents("age")<18 then
Session.Contents.Remove("sale")
End If
%>
<%
Session.Contents.RemoveAll()
%>
All session variables are stored in Contents collection .To see what's stored in it
,you can loop through the Contents collection, :
<%
Session("username")="Donald Duck"
Session("age")=50
dim i
For Each i in Session.Contents
Response.Write(i & "<br />")
Next
%>
Application Object
A group of ASP files may be called an application on the Web . Some purpose can
be achieved when the ASP file work together.In ASP ,the Application object is used
to tie these files together.
For storing and accessing variables from any page, just like the Session object,the
Application object is used . The difference is that in Sessions there is one Session
object for EACH user while ALL users share one Application object .
In the Particular application (like database connection information),the Application
object should hold information that will be used by many pages . This means it is
possible access the information from any page. In an Application object , you can
change the information in one place and the changes will automatically be
reflected on all pages.
Sub Application_OnStart
application("vartime")=""
application("users")=1
End Sub
</script>
In the example above we have created two Application variables: "vartime" and
"users".
Application variables can be accessed like this:
There are
<%
Response.Write(Application("users"))
%>
active connections
<%
Application.Lock
'do some application object operations
Application.Unlock
%>
• With the help of the #include directive, you can insert the content of one
ASP file into another ASP file before the server executes it
• To create functions, headers, footers, or elements that will be reused on
multiple pages,the #include directive is used.
<html>
<body>
<h3>Words of Wisdom:</h3>
<p><!--#include file="wisdom.inc"--></p>
<h3>The time is:</h3>
<p><!--#include file="time.inc"--></p>
</body>
</html>
"One should never increase, beyond what is necessary, the number of entities
required to explain anything."
<%
Response.Write(Time)
%>
If you look into the browser to see the source code, it will look something like this:
<html>
<body>
<h3>Words of Wisdom:</h3>
<p>"One should never increase, beyond what is necessary,
the number of entities required to explain anything."</p>
<h3>The time is:</h3>
<p>11:33:42 AM</p>
</body>
</html>
Place the #include directive inside comment tags to include a file in an ASP page,:
<!--#include virtual="somefilename"-->
or
<!--#include file ="somefilename"-->
To indicate a path beginning with a virtual directory ,use the virtual keyword .
The following line would insert the contents of "header.inc" if a file named
"header.inc" resides in a virtual directory named /html :
To indicate a relative path ,file keyword is used. A relative path begins with the
directory that contains the including file.
The following line would insert the contents of "header.inc" if a file named
"header.inc" resides in a virtual directory named /html,
Note that the path to the included file (headers\header.inc) is relative to the
including file. If the file containing this #include statement is not in the html
directory, the statement will not work.
To include a file from a higher-level directory,you can also use the file keyword
with the syntax (..\)
In the sections above we have used the file extension ".inc" for included files.
Notice that if a user tries to browse an INC file directly, its content will be
displayed. If your included file contains confidential information or information you
do not want any users to see, it is better to use an ASP extension. The source
code in an ASP file will not be visible after the interpretation. An included file can
also include other files, and one ASP file can include the same file more than once.
Important: Included files are processed and inserted before the scripts are
executed.
The following script will not work because before it assigns a value to the
variable ,ASP executes the #include directive:
<%
fname="header.inc"
%>
<!--#include file="<%=fname%>"-->
In an INC file,you cannot open or close a script delimiter . This script will not
work:
<%
For i = 1 To n
<!--#include file="count.inc"-->
Next
%>
Events in Global.asa
Because to insert scripts in the Global.asa file we cannot use the ASP script
delimiters (<% and %>), we put subroutines inside an HTML <script> element
<object> Declarations
With the help of <object> tag it is possible to create objects with session or
application scope in Global.asa .
Note: The <object> tag should be outside the <script>tag
Syntax:
Paramete
Description
r
scope Sets the scope of the object (either Session or Application)
id Specifies a unique id for the object
An id associated with a class id. The format for ProgID is
ProgID [Vendor.]Component[.Version]
Either ProgID or ClassID must be specified.
Examples
The first example creates an object of session scope named "MyCreate" by using
the ProgID parameter:
In the application,the objects declared in the Global.asa file can be used by any
script :
<%=MyAd.GetAdvertisement("/banners/adrot.txt")%>
TypeLibrary Declarations
Syntax
<!--METADATA TYPE="TypeLib"
file="filename"
uuid="typelibraryuuid"
version="versionnumber"
lcid="localeid"
-->
Paramete
Description
r
lcid Optional. The locale identifier to be used for the type library
Error Values
Note:
In the Global.asa file, METADATA tags can appear anywhere (both inside and
outside <script> tags). However, it is recommended that METADATA tags appear
near the top of the Global.asa file.
Restrictions
You can include restrictions in the Global.asa file:
• The text that is written in the Global.asa file can not be displayed. This file
can't display information
• in the Application_OnStart and Application_OnEnd subroutines,you can only
use Server and Application objects . In the Session_OnEnd subroutine, you
can use Server, Application, and Session objects. You can use any built-in
object in the Session_OnStart subroutine
Global.asa Example
In this example we will create a Global.asa file that counts the number of current
visitors.
• When the server starts,the Application_OnStart sets the Application
variable "visitors" to 0
• Every time a new visitor arrives,the Session_OnStart subroutine adds one
to the variable "visitors"
• The Session_OnEnd subroutine subtracts one from "visitors" each time
this subroutine is triggered
The Global.asa file:
<html>
<head>
</head>
<body>
<p>
There are <%response.write(Application("visitors"))%> online now!
</p>
</body>
</html>
In order to send Email from an ASP page on your Web Site, your (Windows / IIS /
NT {wossat?}) Web Host needs to have one of the proprietary mailing
components installed. Think of these "Components" as "Plug In" programs that
add extra functionality to the server. ASK YOUR HOST what they are running and
ASK THEM for some working script examples. If they can't provide you with
these. Dump them!
There are eight basic mailing scripts below I have included for you to play with.
Each of these scripts uses a different kind of mailing component. THE SCRIPTS
WILL ONLY WORK ON A SERVER THAT HAS THE RELEVANT COMPONENT
INSTALLED ON IT. Check with your host to find out what they are running.
Actually, you should have done that before you signed up with them.
Use the basic script examples below and get them working properly FIRST before
you start messing with forms and thingsOnce you have established what mailing
components they have installed,.
ASP Code:
<%
Dim myMail
Set myMail = Server.CreateObject ("CDONTS.NewMail")
myMail.From = "You@YourDomain.co.uk"
myMail.To = "YouAgain@YourOtherAddress.co.uk"
myMail.Subject = "Test email using CDONTS"
myMail.Body = "This is a test email message" & vbcrlf & "sent with CDONTS"
myMail.Send
set myMail=nothing
Response.Write("Your e-mail has been sent")
%>
Microsoft has discontinued the use of CDONTs on Windows 2000, Windows XP and
Windows 2003. You should update the code and use the new CDO technology,if
you have used CDONTs in your ASP applications.
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.TextBody="This is a message."
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'Name or IP of remote SMTP server
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") _
="smtp.server.com"
'Server port
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") _ =25
myMail.Configuration.Fields.Update
myMail.Send
set myMail=nothing
%>
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.Bcc="someoneelse@somedomain.com"
myMail.Cc="someoneelse2@somedomain.com"
myMail.TextBody="This is a message."
myMail.Send
set myMail=nothing
%>
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.CreateMHTMLBody "http://www.designs.univdatabase.com/asp/"
myMail.Send
set myMail=nothing
%>
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.CreateMHTMLBody "file://c:/mydocuments/test.htm"
myMail.Send
set myMail=nothing
%>
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.HTMLBody = "<h1>This is a message.</h1>"
myMail.Send
set myMail=nothing
%>
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.TextBody="This is a message."
myMail.AddAttachment "c:\mydocuments\test.txt"
myMail.Send
set myMail=nothing
%>
<%
Dim MyMail
Set MyMail = Server.CreateObject("SMTPsvg.Mailer")
MyMail.FromName = "Fred Bloggs"
MyMail.FromAddress= "You@YourAddress.co.uk"
MyMail.RemoteHost = "mail.yourdomain.co.uk"
MyMail.AddRecipient= "Joe Bloggs ", "YouAgain@YourOtherAddress.co.uk"
MyMail.Subject = "Test email using ASPMail"
MyMail.BodyText = "This is a test email message" & vbcrlf &"sent with ASPMail"
MyMail.SendMail
Set MyMail = nothing
Response.Write("Your e-mail has been sent")
%>
Response Object
To send output to the user from the server,the ASP Response object is used. Its
collections, properties, and methods are described below:
Collections:
Collectio
Description
n
Sets a cookie value. If the cookie does not exist, it will be created,
Cookies
and take the value that is specified
Properties
Property Description
Buffer Specifies whether to buffer the page output or not
Sets whether a proxy server can cache the output generated
CacheControl
by ASP or not
Appends the name of a character-set to the content-type
Charset
header in the Response object
ContentType Sets the HTTP content type for the Response object
Methods
Method Description
AddHeader Adds a new HTTP header and a value to the HTTP response
AppendToLo
Adds a string to the end of the server log entry
g
Writes data directly to the output without any character
BinaryWrite
conversion
Clear Clears any buffered HTML output
End Stops processing a script, and returns the current result
Flush Sends buffered HTML output immediately
Redirect Redirects the user to a different URL
Write Writes a specified string to the output
Write text with ASP
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>
O/P:
Hello World!
<html>
<body>
<%
response.write("<h2>You can use HTML tags to format the text!</h2>")
%>
<%
response.write("<p style='color:#0000ff'>This text is styled with the style
attribute!</p>")
%>
</body>
</html>
O/P:
<%
if Request.Form("select")<>"" then
Response.Redirect(Request.Form("select"))
end if
%>
<html>
<body>
</form>
</body>
</html>
O/P:
Server Example
Text Example
Go!
<%@ Language=VBScript%>
<% strFileTitle = "Writing"%>
<%ifnotLCase(Request.QueryString("PageView")) = "source" then%>
<%ShowHeader strFileTitle%>
<%< Response.Write "<HTML>"
Response.Write "<HEAD>"
Response.Write "<META NAME=""GENERATOR"" Content=""Microsoft Visual
Studio 6.0"">"
Response.Write "</HEAD>"
Response.Write "<BODY>"
Response.Write "This example is done completely using Response.Write
statement.<BR><BR>"
Response.Write "If you need to produce quotation marks you use
"""
Response.Write "</BODY>"
Response.Write "</HTML>"
ShowFooter
%>
O/P:
Request Object
It is called a request when a browser asks for a page from a server, . To get
information from the user,the ASP Request object is used. Its collections,
properties, and methods are described below:
Collections:
Collection Description
ClientCertificat
Contains all the field values stored in the client certificate
e
Contains all the form (input) values from a form that uses the
Form
post method
ServerVariable
Contains all the server variable values
s
Properties
Property Description
TotalByte Returns the total number of bytes the client sent in the body of the
s request
Methods
Method Description
BinaryRea Retrieves the data sent to the server from the client as part of a
d post request and stores it in a safe array
<html>
<body>
<a href="demo_simplequerystring.asp?color=green">Example</a>
<%
Response.Write(Request.QueryString)
%>
</body>
</html>
O/P:
Example color=green
<html>
<body>
<form action="demo_simpleform.asp" method="post">
Your name: <input type="text" name="fname" size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.Form("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>
</body>
</html>
O/P:
Ravi Submit
Your Name:
Results:
Hello Ravi!
How are you today?
<%
dim numvisits
response.cookies("NumVisits").Expires=date+365
numvisits=request.cookies("NumVisits")
if numvisits="" then
response.cookies("NumVisits")=1
response.write("Welcome! This is the first time you are visiting this Web
page.")
else
response.cookies("NumVisits")=numvisits+1
response.write("You have visited this ")
response.write("Web page " & numvisits)
if numvisits=1 then
response.write " time before!"
else
response.write " times before!"
end if
end if
%>
<html>
<body>
</body>
</html>
O/P:
Welcome! This is the first time you are visiting this Web page.
</TD><TD ALIGN=texttop>
<INPUT type="submit" value="Submit"id=submit1 name=submit1>
<INPUT type="reset"value="Reset" id=reset1 name=reset1>
</TD></TR>
</TABLE>
</FORM> <%else%>
Your Username was:<%=Request.Form("UserName"%><BR>
Your Password was: <%=Request.Form("password")%><BR>
<%endif%>
<%ShowFooter%>
O/P:
rabi
User Name:
Password
Submit Reset
Application Object
An application may be a group of ASP files on the Web. To achieve some ourpose
group of ASP file work together. In ASP ,The Application object is used to tie these
files together.
To store and access variables from any page, just like the Session object,the
Application object is used. The difference is while with Sessions there is one Session
object for EACH user but there is one Application object for ALL users that can be
shared.
In a particular application (like database connection information),the Application
object should hold information that will be used by many pages . This means it is
possible access the information from any page. In an Application object , you can
change the information in one place and the changes will automatically be reflected
on all pages.
The Application object's collections, methods, and events are described below:
Collections:
Collection Description
StaticObject Contains all the objects appended to the application with the
s HTML <object> tag
Methods
Method Description
Contents.RemoveAll(
Deletes all items from the Contents collection
)
Events
Event Description
Occurs when all user sessions are over, and the application
Application_OnEnd
ends
Application_OnStar Occurs before the first new session is created (when the
t Application object is first referenced)
<%@ Language=VBScript%>
<% strFileTitle = "Visit Counter"%>
<% ifLCaseRequest.QueryString("PageView")) = "execute"then%>
<%Dim strDocumentTitle
'The document ID is a compination of the Catagory and document number
'This is to ease administration
<%strDocumentTitle = "Application Variable" %>
<%ShowHeader strFileTitle%>
<
%ifApplication("SimpleApplicationVisitor"""thenApplication("SimpleApplicationVi
sitor" = 0%>
<%=Application("SimpleApplicationVisitor"%> people have viewed this page
since
<% Response.Write Application("StartTime") & " on " Response.Write
Application("StartDate") %>
<%Application("SimpleApplicationVisitor") =
Application("SimpleApplicationVisitor") + 1%>
<%ShowFooter%>
O/P:
Session Object
Session is like when you are working with an application, you open it, do some
changes and then you close it. The computer knows who you are. It knows when
you start the application and when you end. But on the internet there is one
problem: the HTTP address doesn't maintain state so that the web server does not
know who you are and what you do.
By creating a unique cookie for each user,ASP solves this problem . The cookie is
sent to the client and it contains information that identifies the user. This interface
is called the Session object.
For a user session,the Session object is used to store information about, or
change settings . Session object is a variable that holds information about one
single user, and are available to all pages in one application. Common information
stored in session variables are name, id, and preferences. The server creates a
new Session object for each new user, and destroys the Session object when the
session expires
The Session object's collections, properties, methods, and events are described
below:
Collections:
Collection Description
Contains all the items appended to the session through a script
Contents
command
StaticObject Contains all the objects appended to the session with the HTML
s <object> tag
Properties
Property Description
Specifies the character set that will be used when displaying dynamic
CodePage
content
SessionI Returns a unique id for each user. The unique id is generated by the
D server
Sets or returns the timeout period (in minutes) for the Session object
Timeout
in this application
Methods
Method Description
Events
Event Description
<html>
<body>
<%
Response.Write(Session.SessionID)
%>
</body>
</html>
Server Object
To access properties and methods on the server, the ASP Server object is used.
Its properties and methods are described below:
Properties
Property Description
ScriptTimeou Sets or returns the maximum number of seconds a script can run
t before it is terminated
Methods
Method Description
<%
Set fs = Server.CreateObject("Scripting.FileSystemObject")
Set rs = fs.GetFile(Server.MapPath("demo_lastmodified.asp"))
modified = rs.DateLastModified
%>
This file was last modified on: <%response.write(modified)
Set rs = Nothing
Set fs = Nothing
%>
</body>
</html>
In ASP 3.0,the ASPError object was implemented and is available in IIS5 and
later.
In an ASP page,the ASPError object is used to display detailed information of any
error that occurs in scripts . When Server.GetLastError is called, the ASPError
object is created so the error information can only be accessed by using the
Server.GetLastError method.
The ASPError object's properties are described below (all properties are read-
only):
Note:Using Server.GetLastError() method,the properties below can only be
accessed
Properties
Property Description
ASPDescriptio Returns a detailed description of the error (if the error is ASP-
n related)
Returns the column position within the file that generated the
Column
error
Description Returns a short description of the error
File Returns the name of the ASP file that generated the error
Line Returns the line number where the error was detected
Number Returns the standard COM error code for the error
Returns the actual source code of the line where the error
Source
occurred
You can create an AdRotator object using the ASP AdRotator component that
displays a different image each time a user enters or refreshes a page. A text file
includes information about the images..
Syntax
<%
set adrotator=server.createobject("MSWC.AdRotator")
adrotator.GetAdvertisement("textfile.txt")
%>
Example
Assume we have a file called "TopBanners.asp". It looks like this:
<html>
<body>
<%
set adrotator=Server.CreateObject("MSWC.AdRotator")
response.write(adrotator.GetAdvertisement("ads.txt"))
%>
</body>
</html>
*
learnASP.jpg
http://www.ebooks.univdatabase.com/
Visit Academictutorials
80
vyom.gif
http://www.vyom.co.in/
Visit Vyom
20
The lines below the asterisk in the file "ads.txt" specifies the images to be
displayed, the hyperlink addresses, the alternate text (for the images), and the
display rates in percent of the hits. We see that the academictutorials image will
be displayed for 80 % of the hits and the vyom image will be displayed for 20 %
of the hits in the text file above.
Note: To get the links to work when a user clicks on them, we will have to modify
the file "ads.txt" a bit:
REDIRECT TopBanners.asp
*
learnASP.gif
http://www.ebooks.univdatabase.com/
Visit Academictutorials
80
vyom.gif
http://www.vyom.co.in/
Visit Vyom
20
REDIRECT Topbanners.asp
WIDTH 468
HEIGHT 60
BORDER 0
*
learnASP.gif
...
...
The last thing to do is to add some lines of code to the "Topbanners.asp" file:
<%
url=Request.QueryString("url")
If url<>"" then Response.Redirect(url)
%>
<html>
<body>
<%
set adrotator=Server.CreateObject("MSWC.AdRotator")
response.write(adrotator.GetAdvertisement("textfile.txt"))
%>
</body>
</html>
Properties
<%
Specifies the set
size of the adrot=Server.CreateObject("MSWC.AdRotator")
Border borders around adrot.Border="2"
the Response.Write(adrot.GetAdvertisement("ads.txt")
advertisement )
%>
<%
set
Specifies
adrot=Server.CreateObject("MSWC.AdRotator")
whether the
Clickable adrot.Clickable=false
advertisement
Response.Write(adrot.GetAdvertisement("ads.txt")
is a hyperlink
)
%>
<%
set
Name of the
adrot=Server.CreateObject("MSWC.AdRotator")
TargetFram frame to
adrot.TargetFrame="target='_blank'"
e display the
Response.Write(adrot.GetAdvertisement("ads.txt")
advertisement
)
%>
Methods
Returns
<%
HTML that
GetAdvertiseme Response.Write(adrot.GetAdvertisement("ads.tx
displays the
n t"))
advertisemen
%>
t in the page