Search This Blog

ASP - Active Server Page


ASP Introduction

ASP is a powerful tool for making dynamic and interactive Web pages.
An ASP file can contain text, HTML tags and scripts. Scripts in an ASP file are executed on the server.
What you should already know
Before you continue you should have some basic understanding of the following:
• HTML / XHTML
• A scripting language like JavaScript or VBScript

What is ASP?
• ASP stands for Active Server Pages
• ASP is a Microsoft Technology
• ASP is a program that runs inside IIS
• IIS stands for Internet Information Services
• IIS comes as a free component with Windows 2000
• IIS is also a part of the Windows NT 4.0 Option Pack
• The Option Pack can be downloaded from Microsoft
• PWS is a smaller - but fully functional - version of IIS
• PWS can be found on your Windows 95/98 CD

ASP Compatibility
• To run IIS you must have Windows NT 4.0 or later
• To run PWS you must have Windows 95 or later
• ChiliASP is a technology that runs ASP without Windows OS
• InstantASP is another technology that runs ASP without Windows

What is an ASP File?
• An ASP file is just the same as an HTML file
• An ASP file can contain text, HTML, XML, and scripts
• Scripts in an ASP file are executed on the server
• An ASP file has the file extension ".asp"
How Does ASP Differ from HTML?
• When a browser requests an HTML file, the server returns the file
• When a browser requests an ASP file, IIS passes the request to the ASP engine. The ASP engine reads the ASP file, line by line, and executes the scripts in the file. Finally, the ASP file is returned to the browser as plain HTML
________________________________________

What can ASP do for you?
• Dynamically edit, change, or add any content of a Web page
• Respond to user queries or data submitted from HTML forms
• Access any data or databases and return the results to a browser
• Customize a Web page to make it more useful for individual users
• The advantages of using ASP instead of CGI and Perl, are those of simplicity and speed
• Provide security - since ASP code cannot be viewed from the browser
• Clever ASP programming can minimize the network traffic

You can run ASP on your own PC.
________________________________________
Your Windows PC as a Web Server
• Your own PC can act as a web server if you install IIS or PWS
• IIS or PWS turns your computer into a web server
• Microsoft IIS and PWS are free web server components
________________________________________
I
IS - Internet Information Server
IIS is a set of Internet-based services for servers created by Microsoft for use with Microsoft Windows.
IIS comes with Windows 2000, XP, and Vista. It is also available for Windows NT.
IIS is easy to install and ideal for developing and testing web applications.
________________________________________

PWS - Personal Web Server
PWS is for older Windows system like Windows 95, 98, and NT.
PWS is easy to install and can be used for developing and testing web applications including ASP.
We don't recommend running PWS for anything else than training. It is outdated and has security issues.
________________________________________

Windows Web Server Versions
• Windows Vista Business, Enterprise and Ultimate come with IIS 7
• Windows Vista Home Premium comes with IIS 7
• Windows Vista Home Edition does not support PWS or IIS
• Windows XP Professional comes with IIS 5.1
• Windows XP Home Edition does not support IIS or PWS
• Windows 2000 Professional comes with IIS 5.0
• Windows NT Professional comes with IIS 3 and also supports IIS 4
• Windows NT Workstation supports PWS and IIS 3
• Windows ME does not support PWS or IIS
• Windows 98 comes with PWS
• Windows 95 supports PWS
________________________________________

How to Install IIS on Windows Vista
Follow these steps to install IIS on Windows Vista:
1. Open the Control Panel from the Start menu
2. Double-click Programs and Features
3. Click "Turn Windows features on or off" (a link to the left)
4. Select the check box for Internet Information Services (IIS), and click OK
After you have installed IIS, make sure you install all patches for bugs and security problems. (Run Windows Update).
________________________________________

How to Install IIS on Windows XP and Windows 2000
Follow these steps to install IIS on Windows XP and Windows 2000:
1. On the Start menu, click Settings and select Control Panel
2. Double-click Add or Remove Programs
3. Click Add/Remove Windows Components
4. Click Internet Information Services (IIS)
5. Click Details
6. Select the check box for World Wide Web Service, and click OK
7. In Windows Component selection, click Next to install IIS
Test Your Web
After you have installed IIS or PWS follow these steps:
1. Look for a new folder called Inetpub on your hard drive
2. Open the Inetpub folder, and find a folder named wwwroot
3. Create a new folder, like "MyWeb", under wwwroot
4. Write some ASP code and save the file as "test1.asp" in the new folder
5. Make sure your Web server is running (see below)
6. Open your browser and type "http://localhost/MyWeb/test1.asp", to view your first web page
Note: Look for the IIS (or PWS) symbol in your start menu or task bar. The program has functions for starting and stopping the web server, disable and enable ASP, and much more.
ASP Basic Syntax Rules
Write Output to a Browser
An ASP file normally contains HTML tags, just like an HTML file. However, an ASP file can also contain server scripts, surrounded by the delimiters <% and %>.
Server scripts are executed on the server, and can contain any expressions, statements, procedures, or operators valid for the scripting language you prefer to use.
The response.write Command
The response.write command is used to write output to a browser. The following example sends the text "Hello World" to the browser:
Example


<% response.write("Hello World!") %>


There is also a shorthand method for the response.write command. The following example also sends the text "Hello World" to the browser:

Example


<% ="Hello World!" %>



The example above writes "Hello World!" into the body of the document.
________________________________________

Using JavaScript in ASP
To set JavaScript as the default scripting language for a particular page you must insert a language specification at the top of the page:
<%@ language="javascript"%>


<% Response.Write("Hello World!") %>


Note: JavaScript is case sensitive! You will have to write your ASP code with uppercase letters and lowercase letters when the language requires it.
________________________________________

Other Scripting Languages
ASP is shipped with VBScript and JScript (Microsoft's implementation of JavaScript). If you want to script in another language, like PERL, REXX, or Python, you will have to install script engines for them.


ASP Variables

A variable is used to store information.
Declaring a variable:
Variables are used to store information. The following example demonstrates how to declare a variable, assign a value to it, and use the value in a text.

Declare an array

Arrays are used to store a series of related data items. The following example demonstrates how to declare an array that stores names.

Loop through the HTML headings
How to loop through the six headings in HTML.

Time-based greeting using VBScript
This example will display a different message to the user depending on the time on the server.

Time-based greeting using JavaScript
This example is the same as the one above, but the syntax is different.


Lifetime of Variables

A variable declared outside a procedure can be accessed and changed by any script in the ASP file.

A variable declared inside a procedure is created and destroyed every time the procedure is executed. No scripts outside the procedure can access or change the variable.
To declare variables accessible to more than one ASP file, declare them as session variables or application variables.

Session Variables

Session variables are used to store information about ONE single user, and are available to all pages in one application. Typically information stored in session variables are name, id, and preferences.
Application Variables
Application variables are also available to all pages in one application. Application variables are used to store information about ALL users in one specific application.
________________________________________

ASP Procedures

In ASP you can call a JavaScript procedure from a VBScript and vice versa.
________________________________________

Procedures

The ASP source code can contain procedures and functions:

Example


<% sub vbproc(num1,num2) response.write(num1*num2) end sub %>




You can call a procedure like this:

Result: <%call vbproc(3,4)%>

Or, like this:

Result: <%vbproc 3,4%>





Insert the <%@ language="language" %> line above the tag to write the procedure/function in another scripting language:
Example
<%@ language="javascript" %>


<% function jsproc(num1,num2) { Response.Write(num1*num2) } %>



Result: <%jsproc(3,4)%>





________________________________________

Differences between VBScript and JavaScript

When calling a VBScript or a JavaScript procedure from an ASP file written in VBScript, you can use the "call" keyword followed by the procedure name. If a procedure requires parameters, the parameter list must be enclosed in parentheses when using the "call" keyword. If you omit the "call" keyword, the parameter list must not be enclosed in parentheses. If the procedure has no parameters, the parentheses are optional.
When calling a JavaScript or a VBScript procedure from an ASP file written in JavaScript, always use parentheses after the procedure name.
________________________________________
ASP Forms and User Input

The Request.QueryString and Request.Form commands are used to retrieve user input from forms.
User Input
The Request object can be used to retrieve user information from forms.
Example HTML form



First Name:


Last Name:





User input can be retrieved with the Request.QueryString or Request.Form command.
________________________________________

Request.QueryString

The Request.QueryString command is used to collect values in a form with method="get".
Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send.
If a user typed "Bill" and "Gates" in the HTML form above, the URL sent to the server would look like this:
http://www.w3schools.com/simpleform.asp?fname=Bill&lname=Gates
Assume that "simpleform.asp" contains the following ASP script:

Welcome
<% response.write(request.querystring("fname")) response.write(" " & request.querystring("lname")) %>

The browser will display the following in the body of the document:
Welcome Bill Gates



Examples

A form with method="get"
How to interact with the user, with the Request.QueryString command.




Your name:

<% dim fname fname=Request.QueryString("fname") If fname<>"" Then
Response.Write("Hello " & fname & "!
")
Response.Write("How are you today?")
End If
%>



________________________________________
Request.Form
The Request.Form command is used to collect values in a form with method="post".
Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
If a user typed "Bill" and "Gates" in the HTML form above, the URL sent to the server would look like this:
http://www.w3schools.com/simpleform.asp
Assume that "simpleform.asp" contains the following ASP script:

Welcome
<% response.write(request.form("fname")) response.write(" " & request.form("lname")) %>

The browser will display the following in the body of the document:
Welcome Bill Gates

Example:
A form with method="post"
How to interact with the user, with the Request.Form command.




Your name:

<% dim fname fname=Request.Form("fname") If fname<>"" Then
Response.Write("Hello " & fname & "!
")
Response.Write("How are you today?")
End If
%>



A form with radio buttons
How to interact with the user, through radio buttons, with the Request.Form command.

<% dim cars cars=Request.Form("cars") %>


Please select your favorite car:



value="Volvo">Volvo



value="Saab">Saab



value="BMW">BMW




<% if cars<>"" then
Response.Write("Your favorite car is: " & cars & "
")
end if
%>





________________________________________
Form Validation
User input should be validated on the browser whenever possible (by client scripts). Browser validation is faster and reduces the server load.
You should consider server validation if the user input will be inserted into a database. A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error.
7 ASP Cookies


What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With ASP, you can both create and retrieve cookie values.
________________________________________
How to Create a Cookie?
The "Response.Cookies" command is used to create cookies.
Note: The Response.Cookies command must appear BEFORE the tag.
In the example below, we will create a cookie named "firstname" and assign the value "Alex" to it:
<% Response.Cookies("firstname")="Alex" %>
It is also possible to assign properties to a cookie, like setting a date when the cookie should expire:
<% Response.Cookies("firstname")="Alex" Response.Cookies("firstname").Expires=#May 10,2012# %>

________________________________________
How to Retrieve a Cookie Value?
The "Request.Cookies" command is used to retrieve a cookie value.
In the example below, we retrieve the value of the cookie named "firstname" and display it on a page:

<% fname=Request.Cookies("firstname") response.write("Firstname=" & fname) %>
Output: Firstname=Alex
________________________________________
A Cookie with Keys
If a cookie contains a collection of multiple values, we say that the cookie has Keys.
In the example below, we will create a cookie collection named "user". The "user" cookie has Keys that contains information about a user:
<% Response.Cookies("user")("firstname")="John" Response.Cookies("user")("lastname")="Smith" Response.Cookies("user")("country")="Norway" Response.Cookies("user")("age")="25" %>

________________________________________
Read all Cookies
Look at the following code:
<% Response.Cookies("firstname")="Alex" Response.Cookies("user")("firstname")="John" Response.Cookies("user")("lastname")="Smith" Response.Cookies("user")("country")="Norway" Response.Cookies("user")("age")="25" %>
Assume that your server has sent all the cookies above to a user.
Now we want to read all the cookies sent to a user. The example below shows how to do it (note that the code below checks if a cookie has Keys with the HasKeys property):



<% dim x,y for each x in Request.Cookies response.write("

")
if Request.Cookies(x).HasKeys then
for each y in Request.Cookies(x)
response.write(x & ":" & y & "=" & Request.Cookies(x)(y))
response.write("
")
next
else
Response.Write(x & "=" & Request.Cookies(x) & "
")
end if
response.write "
"
next
%>



Output:
firstname=Alex
user:firstname=John
user:lastname=Smith
user:country=Norway
user:age=25
________________________________________
What if a Browser Does NOT Support Cookies?
If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. There are two ways of doing this:
1. Add parameters to a URL
You can add parameters to a URL:
Go to Welcome Page
And retrieve the values in the "welcome.asp" file like this:
<% fname=Request.querystring("fname") lname=Request.querystring("lname") response.write("

Hello " & fname & " " & lname & "!
")
response.write("Welcome to my Web site!
")
%>
2. Use a form
You can use a form. The form passes the user input to "welcome.asp" when the user clicks on the Submit button:

First Name:
Last Name:

Retrieve the values in the "welcome.asp" file like this:
<% fname=Request.form("fname") lname=Request.form("lname") response.write("

Hello " & fname & " " & lname & "!
")
response.write("Welcome to my Web site!
")
%>
8.ASP Session Object

A Session object stores information about, or change settings for a user session.
________________________________________
The Session object
When you are working with an application on your computer, 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 open the application and when you close it. However, on the internet there is one problem: the web server does not know who you are and what you do, because the HTTP address doesn't maintain state.
ASP solves this problem by creating a unique cookie for each user. The cookie is sent to the user's computer and it contains information that identifies the user. This interface is called the Session object.
The Session object stores information about, or change settings for a user session.
Variables stored in a Session object hold 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.
________________________________________
When does a Session Start?
A session starts when:
• A new user requests an ASP file, and the Global.asa file includes a Session_OnStart procedure
• A value is stored in a Session variable
• A user requests an ASP file, and the Global.asa file uses the tag to instantiate an object with session scope ________________________________________ When does a Session End? A session ends if a user has not requested or refreshed a page in the application for a specified period. By default, this is 20 minutes. If you want to set a timeout interval that is shorter or longer than the default, use the Timeout property. The example below sets a timeout interval of 5 minutes: <% Session.Timeout=5 %> Use the Abandon method to end a session immediately: <% Session.Abandon %> Note: The main problem with sessions is WHEN they should end. We do not know if the user's last request was the final one or not. So we do not know how long we should keep the session "alive". Waiting too long for an idle session uses up resources on the server, but if the session is deleted too soon the user has to start all over again because the server has deleted all the information. Finding the right timeout interval can be difficult! Tip: Only store SMALL amounts of data in session variables! ________________________________________ Store and Retrieve Session Variables The most important thing about the Session object is that you can store variables in it. The example below will set the Session variable username to "Donald Duck" and the Session variable age to "50": <% Session("username")="Donald Duck" Session("age")=50 %> When the value is stored in a session variable it can be reached from ANY page in the ASP application: Welcome <%Response.Write(Session("username"))%> The line above returns: "Welcome Donald Duck". You can also store user preferences in the Session object, and then access that preference to choose what page to return to the user. The example below specifies a text-only version of the page if the user has a low screen resolution: <%If Session("screenres")="low" Then%> This is the text version of the page <%Else%> This is the multimedia version of the page <%End If%> ________________________________________ Remove Session Variables The Contents collection contains all session variables. It is possible to remove a session variable with the Remove method. The example below removes the session variable "sale" if the value of the session variable "age" is lower than 18: <% If Session.Contents("age")<18 then Session.Contents.Remove("sale") End If %> To remove all variables in a session, use the RemoveAll method: <% Session.Contents.RemoveAll() %> ________________________________________ Loop Through the Contents Collection The Contents collection contains all session variables. You can loop through the Contents collection, to see what's stored in it: <% Session("username")="Donald Duck" Session("age")=50 dim i For Each i in Session.Contents Response.Write(i & " ") Next %> Result: username age If you do not know the number of items in the Contents collection, you can use the Count property: <% dim i dim j j=Session.Contents.Count Response.Write("Session variables: " & j) For i=1 to j Response.Write(Session.Contents(i) & " ") Next %> Result: Session variables: 2 Donald Duck 50 ________________________________________ Loop Through the StaticObjects Collection You can loop through the StaticObjects collection, to see the values of all objects stored in the Session object: <% dim i For Each i in Session.StaticObjects Response.Write(i & " ") Next %> 9. ASP Application Object A group of ASP files that work together to perform some purpose is called an application. ________________________________________ Application Object An application on the Web may consists of several ASP files that work together to perform some purpose. The Application object is used to tie these files together. The Application object is used to store and access variables from any page, just like the Session object. The difference is that ALL users share ONE Application object (with Sessions there is ONE Session object for EACH user). The Application object holds information that will be used by many pages in the application (like database connection information). The information can be accessed from any page. The information can also be changed in one place, and the changes will automatically be reflected on all pages. ________________________________________ Store and Retrieve Application Variables Application variables can be accessed and changed by any page in an application. You can create Application variables in "Global.asa" like this: In the example above we have created two Application variables: "vartime" and "users". You can access the value of an Application variable like this: There are <% Response.Write(Application("users")) %> active connections. ________________________________________ Loop Through the Contents Collection The Contents collection contains all application variables. You can loop through the Contents collection, to see what's stored in it: <% dim i For Each i in Application.Contents Response.Write(i & " ") Next %> If you do not know the number of items in the Contents collection, you can use the Count property: <% dim i dim j j=Application.Contents.Count For i=1 to j Response.Write(Application.Contents(i) & " ") Next %> ________________________________________ Loop Through the StaticObjects Collection You can loop through the StaticObjects collection, to see the values of all objects stored in the Application object: <% dim i For Each i in Application.StaticObjects Response.Write(i & " ") Next %> ________________________________________ Lock and Unlock You can lock an application with the "Lock" method. When an application is locked, the users cannot change the Application variables (other than the one currently accessing it). You can unlock an application with the "Unlock" method. This method removes the lock from the Application variable: <% Application.Lock 'do some application object operations Application.Unlock %> 10.ASP Including Files The #include Directive You can insert the content of one ASP file into another ASP file before the server executes it, with the #include directive. The #include directive is used to create functions, headers, footers, or elements that will be reused on multiple pages. ________________________________________ How to Use the #include Directive Here is a file called "mypage.asp":

Words of Wisdom:

The time is:

Here is the "wisdom.inc" file: "One should never increase, beyond what is necessary, the number of entities required to explain anything." Here is the "time.inc" file: <% Response.Write(Time) %> If you look at the source code in a browser, it will look something like this:

Words of Wisdom:

"One should never increase, beyond what is necessary, the number of entities required to explain anything."

The time is:

11:33:42 AM ________________________________________ Syntax for Including Files To include a file in an ASP page, place the #include directive inside comment tags: or The Virtual Keyword Use the virtual keyword to indicate a path beginning with a virtual directory. If a file named "header.inc" resides in a virtual directory named /html, the following line would insert the contents of "header.inc": The File Keyword Use the file keyword to indicate a relative path. A relative path begins with the directory that contains the including file. If you have a file in the html directory, and the file "header.inc" resides in html\headers, the following line would insert "header.inc" in your file: 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. ________________________________________ Tips and Notes 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 ASP executes the #include directive before it assigns a value to the variable: <% fname="header.inc" %> You cannot open or close a script delimiter in an INC file. The following script will NOT work: <% For i = 1 To n Next %> But this script will work: <% For i = 1 to n %> <% Next %> 11.ASP The Global.asa file The Global.asa file The Global.asa file is an optional file that can contain declarations of objects, variables, and methods that can be accessed by every page in an ASP application. All valid browser scripts (JavaScript, VBScript, JScript, PerlScript, etc.) can be used within Global.asa. The Global.asa file can contain only the following: • Application events • Session events • declarations • TypeLibrary declarations • the #include directive Note: The Global.asa file must be stored in the root directory of the ASP application, and each application can only have one Global.asa file. ________________________________________ Events in Global.asa In Global.asa you can tell the application and session objects what to do when the application/session starts and what to do when the application/session ends. The code for this is placed in event handlers. The Global.asa file can contain four types of events: Application_OnStart - Occurs when the FIRST user calls the first page in an ASP application. This event occurs after the Web server is restarted or after the Global.asa file is edited. The "Session_OnStart" event occurs immediately after this event. Session_OnStart - This event occurs EVERY time a NEW user requests his or her first page in the ASP application. Session_OnEnd - This event occurs EVERY time a user ends a session. A user-session ends after a page has not been requested by the user for a specified time (by default this is 20 minutes). Application_OnEnd - This event occurs after the LAST user has ended the session. Typically, this event occurs when a Web server stops. This procedure is used to clean up settings after the Application stops, like delete records or write information to text files. A Global.asa file could look something like this: Note: Because we cannot use the ASP script delimiters (<% and %>) to insert scripts in the Global.asa file, we put subroutines inside an HTML Global.asa can also be used to control page access. The example below shows how to redirect every new visitor to another page, in this case to a page called "newpage.asp": And you can include functions in the Global.asa file. In the example below the Application_OnStart subroutine occurs when the Web server starts. Then the Application_OnStart subroutine calls another subroutine named "getcustomers". The "getcustomers" subroutine opens a database and retrieves a record set from the "customers" table. The record set is assigned to an array, where it can be accessed from any ASP page without querying the database: ________________________________________ Global.asa Example In this example we will create a Global.asa file that counts the number of current visitors. • The Application_OnStart sets the Application variable "visitors" to 0 when the server starts • The Session_OnStart subroutine adds one to the variable "visitors" every time a new visitor arrives • The Session_OnEnd subroutine subtracts one from "visitors" each time this subroutine is triggered The Global.asa file: To display the number of current visitors in an ASP file: There are <%response.write(Application("visitors"))%> online now! 12.ASP Sending e-mail with CDOSYS CDOSYS is a built-in component in ASP. This component is used to send e-mails with ASP. ________________________________________ Sending e-mail with CDOSYS CDO (Collaboration Data Objects) is a Microsoft technology that is designed to simplify the creation of messaging applications. CDOSYS is a built-in component in ASP. We will show you how to use this component to send e-mail with ASP. How about CDONTs? Microsoft has discontinued the use of CDONTs on Windows 2000, Windows XP and Windows 2003. If you have used CDONTs in your ASP applications, you should update the code and use the new CDO technology. Examples using CDOSYS Sending a text e-mail: <% 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.Send set myMail=nothing %> Sending a text e-mail with Bcc and CC fields: <% 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 %> Sending an HTML e-mail: <% Set myMail=CreateObject("CDO.Message") myMail.Subject="Sending email with CDO" myMail.From="mymail@mydomain.com" myMail.To="someone@somedomain.com" myMail.HTMLBody = "

This is a message.

" myMail.Send set myMail=nothing %> Sending an HTML e-mail that sends a webpage from a website: <% 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.w3schools.com/asp/" myMail.Send set myMail=nothing %> Sending an HTML e-mail that sends a webpage from a file on your computer: <% 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 %> Sending a text e-mail with an Attachment: <% 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 %> Sending a text e-mail using a remote server: <% 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 %> II ASP Objects 1)ASP Response Object The ASP Response object is used to send output to the user from the server. ________________________________________ Response Object The ASP Response object is used to send output to the user from the server. Its collections, properties, and methods are described below: Collections Collection Description Cookies Sets a cookie value. If the cookie does not exist, it will be created, and take the value that is specified Properties Property Description Buffer Specifies whether to buffer the page output or not CacheControl Sets whether a proxy server can cache the output generated by ASP or not Charset Appends the name of a character-set to the content-type header in the Response object ContentType Sets the HTTP content type for the Response object Expires Sets how long (in minutes) a page will be cached on a browser before it expires ExpiresAbsolute Sets a date and time when a page cached on a browser will expire IsClientConnected Indicates if the client has disconnected from the server Pics Appends a value to the PICS label response header Status Specifies the value of the status line returned by the server Methods Method Description AddHeader Adds a new HTTP header and a value to the HTTP response AppendToLog Adds a string to the end of the server log entry BinaryWrite Writes data directly to the output without any character 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 ASP Cookies Collection ________________________________________ The Cookies collection is used to set or get cookie values. If the cookie does not exist, it will be created, and take the value that is specified. Note: The Response.Cookies command must appear before the tag. Syntax Response.Cookies(name)[(key)|.attribute]=value variablename=Request.Cookies(name)[(key)|.attribute] Parameter Description name Required. The name of the cookie value Required for the Response.Cookies command. The value of the cookie attribute Optional. Specifies information about the cookie. Can be one of the following parameters: • Domain - Write-only. The cookie is sent only to requests to this domain • Expires - Write-only. The date when the cookie expires. If no date is specified, the cookie will expire when the session ends • HasKeys - Read-only. Specifies whether the cookie has keys (This is the only attribute that can be used with the Request.Cookies command) • Path - Write-only. If set, the cookie is sent only to requests to this path. If not set, the application path is used • Secure - Write-only. Indicates if the cookie is secure key Optional. Specifies the key to where the value is assigned ________________________________________ Examples The "Response.Cookies" command is used to create a cookie or to set a cookie value: <% Response.Cookies("firstname")="Alex" %> In the code above, we have created a cookie named "firstname" and assigned the value "Alex" to it. It is also possible to assign some attributes to a cookie, like setting a date when a cookie should expire: <% Response.Cookies("firstname")="Alex" Response.Cookies("firstname").Expires=#May 10,2002# %> Now the cookie named "firstname" has the value of "Alex", and it will expire from the user's computer at May 10, 2002. The "Request.Cookies" command is used to get a cookie value. In the example below, we retrieve the value of the cookie "firstname" and display it on a page: <% fname=Request.Cookies("firstname") response.write("Firstname=" & fname) %> Output: Firstname=Alex A cookie can also contain a collection of multiple values. We say that the cookie has Keys. In the example below, we will create a cookie-collection named "user". The "user" cookie has Keys that contains information about a user: <% Response.Cookies("user")("firstname")="John" Response.Cookies("user")("lastname")="Smith" Response.Cookies("user")("country")="Norway" Response.Cookies("user")("age")="25" %> The code below reads all the cookies your server has sent to a user. Note that the code checks if a cookie has Keys with the HasKeys property: <% dim x,y for each x in Request.Cookies response.write(" ") if Request.Cookies(x).HasKeys then for each y in Request.Cookies(x) response.write(x & ":" & y & "=" & Request.Cookies(x)(y)) response.write(" " next %> %> Output: firstname=Alex user:firstname=John user:lastname=Smith user: country=Norway user: age=25 Properties: ASP Buffer Property The Buffer property specifies whether to buffer the output or not. When the output is buffered, the server will hold back the response to the browser until all of the server scripts have been processed, or until the script calls the Flush or End method. Note: If this property is set, it should be before the tag in the .asp file Syntax response.Buffer[=flag] Parameter Description flag A boolean value that specifies whether to buffer the page output or not. False indicates no buffering. The server will send the output as it is processed. False is default for IIS version 4.0 (and earlier). Default for IIS version 5.0 (and later) is true. True indicates buffering. The server will not send output until all of the scripts on the page have been processed, or until the Flush or End method has been called. Examples Example 1 In this example, there will be no output sent to the browser before the loop is finished. If buffer was set to False, then it would write a line to the browser every time it went through the loop. <%response.Buffer=true%> <% for i=1 to 100 response.write(i & " ") next %> Example 2 <%response.Buffer=true%> I write some text, but I will control when the text will be sent to the browser. The text is not sent yet. I hold it back! OK, let it go! <%response.Flush%> Example 3 <%response.Buffer=true%> This is some text I want to send to the user. No, I changed my mind. I want to clear the text. <%response.Clear%> ASP CacheControl Property The CacheControl property sets whether a proxy server can cache the output generated by ASP or not. By default, a proxy server will not keep a cache copy. Syntax response.CacheControl[=control_header] Parameter Description control_header A cache control header that can be set to "Public" or "Private". Private is default and indicates that only private caches may cache this page. Proxy servers will not cache pages with this setting. Public indicates public caches. Proxy servers will cache pages with this setting. Examples <%response.CacheControl="Public"%> or <%response.CacheControl="Private"%> ASP Charset Property The Charset property appends the name of a character-set to the content-type header in the Response object. Default character set is ISO-LATIN-1. Note: This property will accept any string, regardless of whether it is a valid character set or not, for the name. Syntax response.Charset(charsetname) Parameter Description charsetname A string that specifies a character set for the page Examples If an ASP page has no Charset property set, the content-type header would be: content-type:text/html If we included the Charset property: <%response.Charset="ISO-8859-1"%> the content-type header would be: content-type:text/html; charset=ISO-8859-1 ASP ContentType Property ________________________________________ The ContentType property sets the HTTP content type for the response object. Syntax response.ContentType[=contenttype] Parameter Description contenttype A string describing the content type. For a full list of content types, see your browser documentation or the HTTP specification. Examples If an ASP page has no ContentType property set, the default content-type header would be: content-type:text/html Some other common ContentType values: <%response.ContentType="text/HTML"%> <%response.ContentType="image/GIF"%> <%response.ContentType="image/JPEG"%> <%response.ContentType="text/plain"%> <%response.ContentType="image/JPEG"%> This example will open an Excel spreadsheet in a browser (if the user has Excel installed): <%response.ContentType="application/vnd.ms-excel"%>
1 2 3 4
5 6 7 8
ASP Expires Property The Expires property sets how long (in minutes) a page will be cached on a browser before it expires. If a user returns to the same page before it expires, the cached version is displayed. Syntax response.Expires[=number] Parameter Description number The time in minutes before the page expires Examples Example 1 The following code indicates that the page will never be cached: <%response.Expires=-1%> Example 2 The following code indicates that the page will expire after 1440 minutes (24 hours): <%response.Expires=1440%> ASP ExpiresAbsolute Property ________________________________________ The ExpiresAbsolute property sets a date and time when a cached page on a browser will expire. If a user returns to the same page before this date/time, the cached version is displayed. Syntax response.ExpiresAbsolute[=[date][time]] Parameter Description date Specifies the date on which the page will expire. If this parameter is not specified, the page will expire at the specified time on the day that the script is run. time Specifies the time at which the page will expire. If this parameter is not specified, the page will expire at midnight of the specified day. Examples The following code indicates that the page will expire at 4:00 PM on October 11, 2009: <%response.ExpiresAbsolute=#October 11,2009 16:00:00#%> ASP IsClientConnected Property ________________________________________ The IsClientConnected property indicates if the client has disconnected from the server. Syntax response.IsClientConnected Examples <% If response.IsClientConnected=true then response.write("The user is still connected!") else response.write("The user is not connected!") end if %> ASP PICS Property ________________________________________ The PICS property appends a value to the PICS label response header. Note: This property will accept any string value, regardless of whether it is a valid PICS label or not. What is PICS? The PICS (Platform for Internet Content Selection) rating system is used to rate the content in a web site. It looks something like this: PICS-1.1 "http://www.rsac.org/ratingsv01.html" by "your@name.com" for "http://www.somesite.com" on "2002.10.05T02:15-0800" r (n 0 s 0 v 0 l 0) Part Description PICS-1.1 PICS version number "http://www.rsac.org/ratingsv01.html" Rating organization by "your@name.com" Author of the label for "http://www.somesite.com" The URL or the document that has been rated on "2002.10.05T02:15-0800" Expiration date r (n 0 s 0 v 0 l 0) Rating One of the most popular rating system is RSACi (Recreational Software Advisory Council on the Internet). RSACi rating system uses four categories: violence, nudity, sex, and language. A number between 0 to 4 is assigned to each category. 0 means that the page does not contain any potentially offensive content and 4 means that the page contains the highest levels of potentially offensive content. Level Violence Rating Nudity Rating Sex Rating Language Rating 0 None of the below or sports related None of the below None of the below or innocent kissing; romance None of the below 1 Injury to human being Revealing attire Passionate kissing Mild expletives 2 Destruction of realistic objects Partial nudity Clothed sexual touching Moderate expletives or profanity 3 Aggressive violence or death to humans Frontal nudity Non-explicit sexual acts Strong language or hate speech 4 Rape or wanton, gratuitous violence Frontal nudity (qualifying as provocative display) Explicit sexual acts or sex crimes Crude, vulgar language or extreme hate speech There are two ways you can obtain rating for your site. You can either rate your site yourself or use a rating provider, like RSACi. They'll ask you fill out some questions. After filling out the questions, you will get the rating label for your site. Microsoft IE 3.0 and above and Netscape 4.5 and above support the content ratings. You can set the ratings in IE 5, by selecting Tools and Internet Options. Select the Content tab and click the Enable. When the rating exceeds the defined levels the Content Advisor will block the site. You can set the ratings in Netscape 4.7, by selecting Help and NetWatch. We can use the META tag or the response.PICS property to add a rating to our site. Syntax response.PICS(picslabel) Parameter Description picslabel A properly formatted PICS label Examples For an ASP file that includes: Note: Because PICS labels contain quotes, you must replace quotes with " & chr(34) & ". <% response.PICS("(PICS-1.1 by " & chr(34) & "your@name.com" & chr(34) & " for " & chr(34) & "http://www.somesite.com" & chr(34) & " on " & chr(34) & "2002.10.05T02:15-0800" & chr(34) & " r (n 2 s 0 v 1 l 2))") %> the following header is added: PICS-label:(PICS-1.1 by "your@name.com" for "http://www.somesite.com" on "2002.10.05T02:15-0800" r (n 2 s 0 v 1 l 2)) ASP Status Property ________________________________________ The Status property specifies the value of the status line returned by the server. Tip: Use this property to modify the status line returned by the server. Syntax response.Status=statusdescription Parameter Description statusdescription A three-digit number and a description of that code, like 404 Not Found. Note: Status values are defined in the HTTP specification. Examples <% ip=request.ServerVariables("REMOTE_ADDR") if ip<>"194.248.333.500" then response.Status="401 Unauthorized" response.Write(response.Status) response.End end if %> Methods: ASP AddHeader Method ________________________________________ The AddHeader method adds a new HTTP header and a value to the HTTP response. Note: Once a header has been added, it cannot be removed. Note: In IIS 4.0 you have to call this method before any output is sent to the browser. In IIS 5.0 you can call the AddHeader method at any point in the script, as long as it precedes any calls to the response.Flush method. Syntax response.AddHeader name,value Parameter Description name Required. The name of the new header variable (cannot contain underscores) value Required. The initial value of the new header variable ________________________________________ Examples <%Response.AddHeader "WARNING","Error message text"%> ASP AppendToLog Method ________________________________________ The AppendToLog method adds a string to the end of server log entry for this request. You can call this method multiple times in a script. Each time it is called it will append the specified string to the log entry. Syntax response.AppendToLog string Parameter Description string Required. The text to append to the log file (cannot contain any comma characters) ________________________________________ Examples <%Response.AppendToLog "My log message"%> ASP BinaryWrite Method ________________________________________ The BinaryWrite method writes data directly to the output without any character conversion. Tip: This method is used to write image data (BLOB) from a database to a browser. Syntax response.BinaryWrite data Parameter Description data Required. The binary information to be sent ________________________________________ Example If you have an object that generates an array of bytes, you can use BinaryWrite to send the bytes to an application: <% Set objBinaryGen=Server.CreateObject("MyComponents.BinaryGenerator") pic=objBinaryGen.MakePicture response.BinaryWrite pic %> ________________________________________ ASP Clear Method ________________________________________ The Clear method clears any buffered HTML output. Note: This method does not clear the response headers, only the response body. Note: If response.Buffer is false, this method will cause a run-time error. Syntax response.Clear Examples <% response.Buffer=true %> This is some text I want to send to the user. No, I changed my mind. I want to clear the text. <% response.Clear %> Output: (nothing) ASP End Method ________________________________________ The End method stops processing a script, and returns the current result. Note: This method will flush the buffer if Response.Buffer has been set to true. If you do not want to return any output to the user, you should call Response.Clear first. Syntax Response.End Examples I am writing some text. This text will never be <% Response.End %> finished! It's too late to write more! Output: I am writing some text. This text will never be ASP Flush Method ________________________________________ The Flush method sends buffered HTML output immediately. Note: If response.Buffer is false, this method will cause a run-time error. Syntax Response.Flush Example <% Response.Buffer=true %> I write some text, but I will control when the text will be sent to the browser. The text is not sent yet. I hold it back! OK, let it go! <% Response.Flush %> Output: I write some text, but I will control when the text will be sent to the browser. The text is not sent yet. I hold it back! OK, let it go! ASP Redirect Method ________________________________________ The Redirect method redirects the user to a different URL. Syntax Response.Redirect URL Parameter Description URL Required. The URL that the user (browser) is redirected to Examples <% Response.Redirect "http://www.w3schools.com" %> ASP Write Method ________________________________________ The Write method writes a specified string to the output. Syntax Response.Write variant Parameter Description variant Required. The data to write ________________________________________ Examples Example 1 <% Response.Write "Hello World" %> Output: Hello World Example 2 <% name="John" Response.Write(name) %> Output: John Example 3 <% Response.Write("Hello World") %> Output: Hello World Try it Yourself – Examples 1)Write text with ASP- How to write text with ASP. <% response.write("Hello World!") %> 2) Format text with HTML tags in ASP- How to combine text and HTML tags with ASP. <% response.write("

You can use HTML tags to format the text!

") %> <% response.write("
This text is styled with the style attribute!
") %> 3) Redirect the user to a different URL -How to redirect the user to a different URL. <% if Request.Form("select")<>"" then Response.Redirect(Request.Form("select")) end if %>
Server Example Text Example
4)Show a random link-How to create a random link. <% randomize() r=rnd() if r>0.5 then response.write("W3Schools.com!") else response.write("Refsnesdata.no!") end if %> This example demonstrates a link, each time you load the page, it will display one of two links: W3Schools.com! OR Refsnesdata.no! There is a 50% chance for each of them. 5)Controlling the buffer-How to control the buffer. <% Response.Buffer=true %> This text will be sent to your browser when my response buffer is flushed. <% Response.Flush %> 6) Clear the buffer-How to clear the buffer. <% Response.Buffer=true %> This is some text I want to send to the user. No, I changed my mind. I want to clear the text. <% Response.Clear %> 7) End a script in the middle of processing and return the result-How to end a script in the middle of processing. I am writing some text. This text will never be <% Response.End %> finished! It's too late to write more! 8) Set how many minutes a page will be cached in a browser before it expires -How to specify how many minutes a page will be cached in a browser before it expires. <%Response.Expires=-1%> This page will be refreshed with each access! 9)Set a date/time when a page cached in a browser will expire-How to specify a date/time a page cached in a browser will expire. <% Response.ExpiresAbsolute=#May 05,2001 05:30:30# %> This page will expire on May 05, 2001 05:30:30! 10) Check if the user is still connected to the server-How to check if a user is disconnected from the server. <% If Response.IsClientConnected=true then Response.Write("The user is still connected!") else Response.Write("The user is not connected!") end if %> 11) Set the type of content-How to specify the type of content. <% Response.ContentType="text/html" %> This is some text 12) Set the name of the character set-How to specify the name of the character set. <% Response.Charset="ISO8859-1" %> This is some text 2.ASP Request Object The Request object is used to get information from a visitor. ________________________________________ Request Object When a browser asks for a page from a server, it is called a request. The Request object is used to get information from a visitor. Its collections, properties, and methods are described below: Collections Collection Description ClientCertificate Contains all the field values stored in the client certificate Cookies Contains all the cookie values sent in a HTTP request Form Contains all the form (input) values from a form that uses the post method QueryString Contains all the variable values in a HTTP query string ServerVariables Contains all the server variable values Properties Property Description TotalBytes Returns the total number of bytes the client sent in the body of the request Methods Method Description BinaryRead Retrieves the data sent to the server from the client as part of a post request and stores it in a safe array Collections: ASP Cookies Collection ________________________________________ The Cookies collection is used to set or get cookie values. If the cookie does not exist, it will be created, and take the value that is specified. Note: The Response.Cookies command must appear before the tag. Syntax Response.Cookies(name)[(key)|.attribute]=value variablename=Request.Cookies(name)[(key)|.attribute] Parameter Description name Required. The name of the cookie value Required for the Response.Cookies command. The value of the cookie attribute Optional. Specifies information about the cookie. Can be one of the following parameters: • Domain - Write-only. The cookie is sent only to requests to this domain • Expires - Write-only. The date when the cookie expires. If no date is specified, the cookie will expire when the session ends • HasKeys - Read-only. Specifies whether the cookie has keys (This is the only attribute that can be used with the Request.Cookies command) • Path - Write-only. If set, the cookie is sent only to requests to this path. If not set, the application path is used • Secure - Write-only. Indicates if the cookie is secure key Optional. Specifies the key to where the value is assigned ________________________________________ Examples The "Response.Cookies" command is used to create a cookie or to set a cookie value: <% Response.Cookies("firstname")="Alex" %> In the code above, we have created a cookie named "firstname" and assigned the value "Alex" to it. It is also possible to assign some attributes to a cookie, like setting a date when a cookie should expire: <% Response.Cookies("firstname")="Alex" Response.Cookies("firstname").Expires=#May 10,2002# %> Now the cookie named "firstname" has the value of "Alex", and it will expire from the user's computer at May 10, 2002. The "Request.Cookies" command is used to get a cookie value. In the example below, we retrieve the value of the cookie "firstname" and display it on a page: <% fname=Request.Cookies("firstname") response.write("Firstname=" & fname) %> Output: Firstname=Alex A cookie can also contain a collection of multiple values. We say that the cookie has Keys. In the example below, we will create a cookie-collection named "user". The "user" cookie has Keys that contains information about a user: <% Response.Cookies("user")("firstname")="John" Response.Cookies("user")("lastname")="Smith" Response.Cookies("user")("country")="Norway" Response.Cookies("user")("age")="25" %> The code below reads all the cookies your server has sent to a user. Note that the code checks if a cookie has Keys with the HasKeys property: <% dim x,y for each x in Request.Cookies response.write("") if Request.Cookies(x).HasKeys then for each y in Request.Cookies(x) response.write(x & ":" & y & "=" & Request.Cookies(x)(y)) response.write(" " next %> %> Output: firstname=Alex user:firstname=John user:lastname=Smith user: country=Norway user: age=25 ASP Form Collection ________________________________________ The Form collection is used to retrieve the values of form elements from a form that uses the POST method. Syntax Request.Form(element)[(index)|.Count] Parameter Description element Required. The name of the form element from which the collection is to retrieve values index Optional. Specifies one of multiple values for a parameter. From 1 to Request.Form(parameter).Count. ________________________________________ Examples Example 1 You can loop through all the values in a form request. If a user filled out a form by specifying two values - Blue and Green - for the color element, you could retrieve those values like this: <% for i=1 to Request.Form("color").Count Response.Write(Request.Form("color")(i) & " ") next %> Output: Blue Green Example 2 Consider the following form:
First name: Last name: Your favorite color:
The following request might be sent: firstname=John&lastname=Dove&color=Red Now we can use the information from the form in a script: Hi, <%=Request.Form("firstname")%>. Your favorite color is <%=Request.Form("color")%>. Output: Hi, John. Your favorite color is Red. If you do not specify any element to display, like this: Form data is: <%=Request.Form%> the output would look like this: Form data is: firstname=John&lastname=Dove&color=Red ASP QueryString Collection ________________________________________ The QueryString collection is used to retrieve the variable values in the HTTP query string. The HTTP query string is specified by the values following the question mark (?), like this: Link with a query string The line above generates a variable named txt with the value "this is a query string test". Query strings are also generated by form submission, or by a user typing a query into the address bar of the browser. Note: If you want to send large amounts of data (beyond 100 kb) the Request.QueryString cannot be used. Syntax Request.QueryString(variable)[(index)|.Count] Parameter Description variable Required. The name of the variable in the HTTP query string to retrieve index Optional. Specifies one of multiple values for a variable. From 1 to Request.QueryString(variable).Count ________________________________________ Examples Example 1 To loop through all the n variable values in a Query String: The following request is sent: http://www.w3schools.com/test/names.asp?n=John&n=Susan and names.asp contains the following script: <% for i=1 to Request.QueryString("n").Count Response.Write(Request.QueryString("n")(i) & " ") next %> The file names.asp would display the following: John Susan Example 2 The following string might be sent: http://www.w3schools.com/test/names.asp?name=John&age=30 this results in the following QUERY_STRING value: name=John&age=30 Now we can use the information in a script: Hi, <%=Request.QueryString("name")%>. Your age is <%= Request.QueryString("age")%>. Output: Hi, John. Your age is 30. If you do not specify any variable values to display, like this: Query string is: <%=Request.QueryString%> the output would look like this: Query string is: name=John&age=30 ASP ServerVariables Collection ________________________________________ The ServerVariables collection is used to retrieve the server variable values. Syntax Request.ServerVariables (server_variable) Parameter Description server_variable Required. The name of the server variable to retrieve Server Variables Variable Description ALL_HTTP Returns all HTTP headers sent by the client. Always prefixed with HTTP_ and capitalized ALL_RAW Returns all headers in raw form APPL_MD_PATH Returns the meta base path for the application for the ISAPI DLL APPL_PHYSICAL_PATH Returns the physical path corresponding to the meta base path AUTH_PASSWORD Returns the value entered in the client's authentication dialog AUTH_TYPE The authentication method that the server uses to validate users AUTH_USER Returns the raw authenticated user name CERT_COOKIE Returns the unique ID for client certificate as a string CERT_FLAGS bit0 is set to 1 if the client certificate is present and bit1 is set to 1 if the cCertification authority of the client certificate is not valid CERT_ISSUER Returns the issuer field of the client certificate CERT_KEYSIZE Returns the number of bits in Secure Sockets Layer connection key size CERT_SECRETKEYSIZE Returns the number of bits in server certificate private key CERT_SERIALNUMBER Returns the serial number field of the client certificate CERT_SERVER_ISSUER Returns the issuer field of the server certificate CERT_SERVER_SUBJECT Returns the subject field of the server certificate CERT_SUBJECT Returns the subject field of the client certificate CONTENT_LENGTH Returns the length of the content as sent by the client CONTENT_TYPE Returns the data type of the content GATEWAY_INTERFACE Returns the revision of the CGI specification used by the server HTTP_ Returns the value stored in the header HeaderName HTTP_ACCEPT Returns the value of the Accept header HTTP_ACCEPT_LANGUAGE Returns a string describing the language to use for displaying content HTTP_COOKIE Returns the cookie string included with the request HTTP_REFERER Returns a string containing the URL of the page that referred the request to the current page using an tag. If the page is redirected, HTTP_REFERER is empty HTTP_USER_AGENT Returns a string describing the browser that sent the request HTTPS Returns ON if the request came in through secure channel or OFF if the request came in through a non-secure channel HTTPS_KEYSIZE Returns the number of bits in Secure Sockets Layer connection key size HTTPS_SECRETKEYSIZE Returns the number of bits in server certificate private key HTTPS_SERVER_ISSUER Returns the issuer field of the server certificate HTTPS_SERVER_SUBJECT Returns the subject field of the server certificate INSTANCE_ID The ID for the IIS instance in text format INSTANCE_META_PATH The meta base path for the instance of IIS that responds to the request LOCAL_ADDR Returns the server address on which the request came in LOGON_USER Returns the Windows account that the user is logged into PATH_INFO Returns extra path information as given by the client PATH_TRANSLATED A translated version of PATH_INFO that takes the path and performs any necessary virtual-to-physical mapping QUERY_STRING Returns the query information stored in the string following the question mark (?) in the HTTP request REMOTE_ADDR Returns the IP address of the remote host making the request REMOTE_HOST Returns the name of the host making the request REMOTE_USER Returns an unmapped user-name string sent in by the user REQUEST_METHOD Returns the method used to make the request SCRIPT_NAME Returns a virtual path to the script being executed SERVER_NAME Returns the server's host name, DNS alias, or IP address as it would appear in self-referencing URLs SERVER_PORT Returns the port number to which the request was sent SERVER_PORT_SECURE Returns a string that contains 0 or 1. If the request is being handled on the secure port, it will be 1. Otherwise, it will be 0 SERVER_PROTOCOL Returns the name and revision of the request information protocol SERVER_SOFTWARE Returns the name and version of the server software that answers the request and runs the gateway URL Returns the base portion of the URL ________________________________________ Examples Example 1 You can loop through all of the server variables like this: <% for each x in Request.ServerVariables response.write(x & " ") next > Example 2 This example demonstrates how to find out the visitor's browser type, IP address, and more: You are browsing this site with: <%Response.Write(Request.ServerVariables("http_user_agent"))%> Your IP address is: <%Response.Write(Request.ServerVariables("remote_addr"))%> The DNS lookup of the IP address is: <%Response.Write(Request.ServerVariables("remote_host"))%> The method used to call the page: <%Response.Write(Request.ServerVariables("request_method"))%> The server's domain name: <%Response.Write(Request.ServerVariables("server_name"))%> The server's port: <%Response.Write(Request.ServerVariables("server_port"))%> The server's software: <%Response.Write(Request.ServerVariables("server_software"))%> Properties ASP TotalBytes Property ________________________________________ The TotalBytes property is a read-only property that returns the total number of bytes the client sent in the body of the request. Syntax varbytes=Request.Totalbytes Example The following code sets the variable a equal to the total number of bytes sent in the body of the request: <% dim a a=Request.TotalBytes %> ASP BinaryRead Method ________________________________________ The BinaryRead method is used to retrieve the data sent to the server from the client as part of a POST request. It will store the data in a safe array (an array that stores information about the number of dimensions and the bounds of its dimensions). Note: A call to Request.Form after a call to BinaryRead, and vice-versa, will cause an error. Syntax Request.BinaryRead(count) Parameter Description count Required. Specifies how many bytes to read from the client Examples The following example uses the BinaryRead method to place the content of a request into a safe array: <% dim a,b a=Request.TotalBytes b=Request.BinaryRead(a) %> 3) ASP Application Object A group of ASP files that work together to perform some purpose is called an application. The Application object is used to tie these files together. ________________________________________ Application Object An application on the Web may consists of several ASP files that work together to perform some purpose. The Application object is used to tie these files together. The Application object is used to store and access variables from any page, just like the Session object. The difference is that ALL users share ONE Application object (with Sessions there is ONE Session object for EACH user). The Application object holds information that will be used by many pages in the application (like database connection information). The information can be accessed from any page. The information can also be changed 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 Contents Contains all the items appended to the application through a script command StaticObjects Contains all the objects appended to the application with the HTML tag Methods Method Description Contents.Remove Deletes an item from the Contents collection Contents.RemoveAll() Deletes all items from the Contents collection Lock Prevents other users from modifying the variables in the Application object Unlock Enables other users to modify the variables in the Application object (after it has been locked using the Lock method) Events Event Description Application_OnEnd Occurs when all user sessions are over, and the application ends Application_OnStart Occurs before the first new session is created (when the Application object is first referenced) Collections: ASP Contents Collection ________________________________________ The Contents collection contains all the items appended to the application/session through a script command. Tip: To remove items from the Contents collection, use the Remove and RemoveAll methods. Syntax Application.Contents(Key) Session.Contents(Key) Parameter Description key Required. The name of the item to retrieve ________________________________________ Examples for the Application Object Example 1 Notice that both name and objtest would be appended to the Contents collection: <% Application("name")="W3Schools" Set Application("objtest")=Server.CreateObject("ADODB.Connection") %> Example 2 To loop through the Contents collection: <% for each x in Application.Contents Response.Write(x & "=" & Application.Contents(x) & " ") next %> or: <% For i=1 to Application.Contents.Count Response.Write(i & "=" & Application.Contents(i) & " ") Next %> Example 3 <% Application("date")="2001/05/05" Application("author")="W3Schools" for each x in Application.Contents Response.Write(x & "=" & Application.Contents(x) & " ") next %> Output: date=2001/05/05 author=W3Schools ________________________________________ Examples for the Session Object Example 1 Notice that both name and objtest would be appended to the Contents collection: <% Session("name")="Hege" Set Session("objtest")=Server.CreateObject("ADODB.Connection") %> Example 2 To loop through the Contents collection: <% for each x in Session.Contents Response.Write(x & "=" & Session.Contents(x) & " ") next %> or: <% For i=1 to Session.Contents.Count Response.Write(i & "=" & Session.Contents(i) & " ") Next %> Example 3 <% Session("name")="Hege" Session("date")="2001/05/05" for each x in Session.Contents Response.Write(x & "=" & Session.Contents(x) & " ") next %> Output: name=Hege date=2001/05/05 ASP StaticObjects Collection ________________________________________ The StaticObjects collection contains all the objects appended to the application/session with the HTML tag. Syntax Application.StaticObjects(Key) Session.StaticObjects(Key) Parameter Description key Required. The name of the item to retrieve ________________________________________ Examples for the Application Object Example 1 To loop through the StaticObjects collection: <% for each x in Application.StaticObjects Response.Write(x & " ") next %> Example 2 In Global.asa: In an ASP file: <% for each x in Application.StaticObjects Response.Write(x & " ") next %> Output: MsgBoard AdRot ________________________________________ Examples for the Session Object Example 1 To loop through the StaticObjects collection: <% for each x in Session.StaticObjects Response.Write(x & " ") next %> Example 2 In Global.asa: In an ASP file: <% for each x in Session.StaticObjects Response.Write(x & " ") next %> Output: MsgBoard AdRot Methods: ASP Contents.Remove Method ________________________________________ The Contents.Remove method deletes an item from the Contents collection. Syntax Application.Contents.Remove(name|index) Session.Contents.Remove(name|index) Parameter Description name The name of the item to remove index The index of the item to remove ________________________________________ Examples for the Application Object Example 1 <% Application("test1")=("First test") Application("test2")=("Second test") Application("test3")=("Third test") Application.Contents.Remove("test2") for each x in Application.Contents Response.Write(x & "=" & Application.Contents(x) & " ") next %> Output: test1=First test test3=Third test Example 2 <% Application("test1")=("First test") Application("test2")=("Second test") Application("test3")=("Third test") Application.Contents.Remove(2) for each x in Application.Contents Response.Write(x & "=" & Application.Contents(x) & " ") next %> Output: test1=First test test3=Third test Examples for the Session Object Example 1 <% Session("test1")=("First test") Session("test2")=("Second test") Session("test3")=("Third test") Session.Contents.Remove("test2") for each x in Session.Contents Response.Write(x & "=" & Session.Contents(x) & " ") next %> Output: test1=First test test3=Third test Example 2 <% Session("test1")=("First test") Session("test2")=("Second test") Session("test3")=("Third test") Session.Contents.Remove(2) for each x in Session.Contents Response.Write(x & "=" & Session.Contents(x) & " ") next %> Output: test1=First test test3=Third test ASP Contents.RemoveAll Method ________________________________________ The Contents.RemoveAll method deletes all items from the Contents collection. Syntax Application.Contents.RemoveAll() Session.Contents.RemoveAll() Example for the Application Object <% Application.Contents.RemoveAll() %> Example for the Session Object <% Session.Contents.RemoveAll() %> ASP Lock and Unlock Methods ________________________________________ Lock Method The Lock method prevents other users from modifying the variables in the Application object (used to ensure that only one client at a time can modify the Application variables). Unlock Method The Unlock method enables other users to modify the variables stored in the Application object (after it has been locked using the Lock method). Syntax Application.Lock Application.Unlock Example The example below uses the Lock method to prevent more than one user from accessing the variable visits at a time, and the Unlock method to unlock the locked object so that the next client can increment the variable visits: <% Application.Lock Application("visits")=Application("visits")+1 Application.Unlock %> This page has been visited <%=Application("visits")%> times! Events: ASP Application_OnStart and Application_OnEnd Events ________________________________________ Application_OnStart Event The Application_OnStart event occurs before the first new session is created (when the Application object is first referenced). This event is placed in the Global.asa file. Note: Referencing to a Session, Request, or Response objects in the Application_OnStart event script will cause an error. Application_OnEnd Event The Application_OnEnd event occurs when the application ends (when the web server stops). This event is placed in the Global.asa file. Note: The MapPath method cannot be used in the Application_OnEnd code. Syntax ________________________________________ Examples Global.asa: To display the number of current visitors in an ASP file: There are <%response.write(Application("visitors"))%> online now! 4)ASP Session Object A Session object stores information about, or change settings for a user session. ________________________________________ Session Object When you are working with an application on your computer, 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 open the application and when you close it. However, on the internet there is one problem: the web server does not know who you are and what you do, because the HTTP address doesn't maintain state. ASP solves this problem by creating a unique cookie for each user. The cookie is sent to the user's computer and it contains information that identifies the user. This interface is called the Session object. The Session object stores information about, or change settings for a user session. Variables stored in a Session object hold 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 Contents Contains all the items appended to the session through a script command StaticObjects Contains all the objects appended to the session with the HTML tag Properties Property Description CodePage Specifies the character set that will be used when displaying dynamic content LCID Sets or returns an integer that specifies a location or region. Contents like date, time, and currency will be displayed according to that location or region SessionID Returns a unique id for each user. The unique id is generated by the server Timeout Sets or returns the timeout period (in minutes) for the Session object in this application Methods Method Description Abandon Destroys a user session Contents.Remove Deletes an item from the Contents collection Contents.RemoveAll() Deletes all items from the Contents collection Events Event Description Session_OnEnd Occurs when a session ends Session_OnStart Occurs when a session starts Collections: ASP Contents Collection ________________________________________ The Contents collection contains all the items appended to the application/session through a script command. Tip: To remove items from the Contents collection, use the Remove and RemoveAll methods. Syntax Application.Contents(Key) Session.Contents(Key) Parameter Description key Required. The name of the item to retrieve ________________________________________ Examples for the Application Object Example 1 Notice that both name and objtest would be appended to the Contents collection: <% Application("name")="W3Schools" Set Application("objtest")=Server.CreateObject("ADODB.Connection") %> Example 2 To loop through the Contents collection: <% for each x in Application.Contents Response.Write(x & "=" & Application.Contents(x) & " ") next %> or: <% For i=1 to Application.Contents.Count Response.Write(i & "=" & Application.Contents(i) & " ") Next %> Example 3 <% Application("date")="2001/05/05" Application("author")="W3Schools" for each x in Application.Contents Response.Write(x & "=" & Application.Contents(x) & " ") next %> Output: date=2001/05/05 author=W3Schools ________________________________________ Examples for the Session Object Example 1 Notice that both name and objtest would be appended to the Contents collection: <% Session("name")="Hege" Set Session("objtest")=Server.CreateObject("ADODB.Connection") %> Example 2 To loop through the Contents collection: <% for each x in Session.Contents Response.Write(x & "=" & Session.Contents(x) & " ") next %> or: <% For i=1 to Session.Contents.Count Response.Write(i & "=" & Session.Contents(i) & " ") Next %> Example 3 <% Session("name")="Hege" Session("date")="2001/05/05" for each x in Session.Contents Response.Write(x & "=" & Session.Contents(x) & " ") next %> Output: name=Hege date=2001/05/05 ASP StaticObjects Collection ________________________________________ The StaticObjects collection contains all the objects appended to the application/session with the HTML tag. Syntax Application.StaticObjects(Key) Session.StaticObjects(Key) Parameter Description key Required. The name of the item to retrieve ________________________________________ Examples for the Application Object Example 1 To loop through the StaticObjects collection: <% for each x in Application.StaticObjects Response.Write(x & " ") next %> Example 2 In Global.asa: In an ASP file: <% for each x in Application.StaticObjects Response.Write(x & " ") next %> Output: MsgBoard AdRot ________________________________________ Examples for the Session Object Example 1 To loop through the StaticObjects collection: <% for each x in Session.StaticObjects Response.Write(x & " ") next %> Example 2 In Global.asa: In an ASP file: <% for each x in Session.StaticObjects Response.Write(x & " ") next %> Output: MsgBoard AdRot Properties: ASP CodePage Property ________________________________________ The CodePage property specifies the character set that will be used when displaying dynamic content. Example of some code pages: • 1252 - American English and most European languages • 932 - Japanese Kanji Syntax Session.CodePage(=Codepage) Parameter Description codepage Defines a code page (character set) for the system running the script engine Examples <% Response.Write(Session.CodePage) %> Output: 1252 ASP LCID Property ________________________________________ The LCID property sets or returns an integer that specifies a location or region. Contents like date, time, and currency will be displayed according to that location or region. Syntax Session.LCID(=LCID) Parameter Description LCID A locale identifier Examples <% response.write(" ") response.write("Default LCID is: " & Session.LCID & " ") response.write("Date format is: " & date() & " ") response.write("Currency format is: " & FormatCurrency(350)) response.write(" ") Session.LCID=1036 response.write(" ") response.write("LCID is now: " & Session.LCID & " ") response.write("Date format is: " & date() & " ") response.write("Currency format is: " & FormatCurrency(350)) response.write(" ") Session.LCID=3079 response.write(" ") response.write("LCID is now: " & Session.LCID & " ") response.write("Date format is: " & date() & " ") response.write("Currency format is: " & FormatCurrency(350)) response.write(" ") Session.LCID=2057 response.write(" ") response.write("LCID is now: " & Session.LCID & " ") response.write("Date format is: " & date() & " ") response.write("Currency format is: " & FormatCurrency(350)) response.write(" ") %> Output: Default LCID is: 2048 Date format is: 12/11/2001 Currency format is: $350.00 LCID is now: 1036 Date format is: 11/12/2001 Currency format is: 350,00 F LCID is now: 3079 Date format is: 11.12.2001 Currency format is: öS 350,00 LCID is now: 2057 Date format is: 11/12/2001 Currency format is: £350.00 ASP SessionID Property ________________________________________ The SessionID property returns a unique id for each user. The unique id is generated by the server. Syntax Session.SessionID Examples <% Response.Write(Session.SessionID) %> Output: 772766038 ASP Timeout Property ________________________________________ The Timeout property sets or returns the timeout period for the Session object for this application, in minutes. If the user does not refresh or request a page within the timeout period, the session will end. Syntax Session.Timeout[=nMinutes] Parameter Description nMinutes The number of minutes a session can remain idle before the server terminates it. Default is 20 minutes Examples <% response.write(" ") response.write("Default Timeout is: " & Session.Timeout) response.write(" ") Session.Timeout=30 response.write(" ") response.write("Timeout is now: " & Session.Timeout) response.write(" ") %> Output: Default Timeout is: 20 Timeout is now: 30 Methods: ASP Abandon Method ________________________________________ The Abandon method destroys a user session. Note: When this method is called, the current Session object is not deleted until all of the script on the current page have been processed. This means that it is possible to access session variables on the same page as the call to Abandon, but not from another Web page. Syntax Session.Abandon Examples File1.asp: <% Session("name")="Hege" Session.Abandon Response.Write(Session("name")) %> Output: Hege File2.asp: <% Response.Write(Session("name")) %> Output: (none) ASP Contents.Remove Method ________________________________________ The Contents.Remove method deletes an item from the Contents collection. Syntax Application.Contents.Remove(name|index) Session.Contents.Remove(name|index) Parameter Description name The name of the item to remove index The index of the item to remove ________________________________________ Examples for the Application Object Example 1 <% Application("test1")=("First test") Application("test2")=("Second test") Application("test3")=("Third test") Application.Contents.Remove("test2") for each x in Application.Contents Response.Write(x & "=" & Application.Contents(x) & " ") next %> Output: test1=First test test3=Third test Example 2 <% Application("test1")=("First test") Application("test2")=("Second test") Application("test3")=("Third test") Application.Contents.Remove(2) for each x in Application.Contents Response.Write(x & "=" & Application.Contents(x) & " ") next %> Output: test1=First test test3=Third test Examples for the Session Object Example 1 <% Session("test1")=("First test") Session("test2")=("Second test") Session("test3")=("Third test") Session.Contents.Remove("test2") for each x in Session.Contents Response.Write(x & "=" & Session.Contents(x) & " ") next %> Output: test1=First test test3=Third test Example 2 <% Session("test1")=("First test") Session("test2")=("Second test") Session("test3")=("Third test") Session.Contents.Remove(2) for each x in Session.Contents Response.Write(x & "=" & Session.Contents(x) & " ") next %> Output: test1=First test test3=Third test ASP Contents.RemoveAll Method ________________________________________ The Contents.RemoveAll method deletes all items from the Contents collection. Syntax Application.Contents.RemoveAll() Session.Contents.RemoveAll() Example for the Application Object <% Application.Contents.RemoveAll() %> Example for the Session Object <% Session.Contents.RemoveAll() %> Events: ASP Session_OnStart and Session_OnEnd Events ________________________________________ Session_OnStart Event The Session_OnStart event occurs when the server creates a session. This event is placed in the Global.asa file. Session_OnEnd Event The Session_OnEnd event occurs when the session ends (abandoned or times out). This event is placed in the Global.asa file. Note: The MapPath method cannot be used in the Session_OnEnd code. Syntax ________________________________________ Examples Global.asa: To display the number of current visitors in an ASP file: There are <%response.write(Application("visitors"))%> online now! 5) ASP Server Object The Server object is used to access properties and methods on the server. ________________________________________ Server Object The ASP Server object is used to access properties and methods on the server. Its properties and methods are described below: Properties Property Description ScriptTimeout Sets or returns the maximum number of seconds a script can run before it is terminated Methods Method Description CreateObject Creates an instance of an object Execute Executes an ASP file from inside another ASP file GetLastError() Returns an ASPError object that describes the error condition that occurred HTMLEncode Applies HTML encoding to a specified string MapPath Maps a specified path to a physical path Transfer Sends (transfers) all the information created in one ASP file to a second ASP file URLEncode Applies URL encoding rules to a specified string Properties: ASP ScriptTimeout Property ________________________________________ The ScriptTimeout property sets or returns the maximum number of seconds a script can run before it is terminated. Syntax Server.ScriptTimeout[=NumSeconds] Parameter Description NumSeconds The maximum number of seconds a script can run before the server terminates it. Default is 90 seconds Examples Example 1 Set the script timeout: <% Server.ScriptTimeout=200 %> Example 2 Retrieve the current value of the ScriptTimeout property: <% response.write(Server.ScriptTimeout) %> Methods: ASP CreateObject Method ________________________________________ The CreateObject method creates an instance of an object. Note: Objects created with this method have page scope. They are destroyed when the server are finished processing the current ASP page. To create an object with session or application scope, you can either use the tag in the Global.asa file, or store the object in a session or application variable. Syntax Server.CreateObject(progID) Part Description progID Required. The type of object to create ________________________________________ Example 1 This example creates an instance of the server component MSWC.AdRotator: <% Set adrot=Server.CreateObject("MSWC.AdRotator") %> Example 2 An object stored in a session variable is destroyed when the session ends. However, you can also destroy the object by setting the variable to Nothing or to a new value: <% Session("ad")=Nothing %> or <% Session("ad")="a new value" %> Example 3 You cannot create an instance of an object with the same name as a built-in object: <% Set Application=Server.CreateObject("Application") %> ASP Execute Method ________________________________________ The Execute method executes an ASP file from inside another ASP file. After executing the called .asp file, the control is returned to the original .asp file. Syntax Server.Execute(path) Parameter Description path Required. The location of the ASP file to execute Example File1.asp: <% response.write("I am in File 1! ") Server.Execute("file2.asp") response.write("I am back in File 1!") %> File2.asp: <% response.write("I am in File 2! ") %> Output: I am in File 1! I am in File 2! I am back in File 1! Also look at the Server.Transfer method to see the difference between the Server.Execute and Server.Transfer methods. ASP GetLastError() Method (ASP 3.0) ________________________________________ The GetLastError method returns an ASPError object that describes the error condition that occurred. By default, a Web site uses the file \iishelp\common\500-100.asp for processing ASP errors. You can either use this file, or create your own. If you want to change the ASP file for processing the 500;100 custom errors you can use the IIS snap-in. Note: A 500;100 custom error will be generated if IIS encounters an error while processing either an ASP file or the application's Global.asa file. Note: This method is available only before the ASP file has sent any content to the browser. Syntax Server.GetLastError() Examples Example 1 In the example an error will occur when IIS tries to include the file, because the include statement is missing the file parameter: <% response.write("sometext") %> Example 2 In this example an error will occur when compiling the script, because the "next" keyword is missing: <% dim i for i=1 to 10 ........ nxt %> Example 3 In this example an error will occur because the script attempts to divide by 0: <% dim i,tot,j i=0 tot=0 j=0 for i=1 to 10 tot=tot+1 next tot=tot/j %> ASP HTMLEncode Method ________________________________________ The HTMLEncode method applies HTML encoding to a specified string. Syntax Server.HTMLEncode(string) Parameter Description string Required. The string to encode Example The following script: <% response.write(Server.HTMLEncode("The image tag: ")) %> Output: The image tag: <img> Web browser output: The image tag: ASP MapPath Method ________________________________________ The MapPath method maps a specified path to a physical path. Note: This method cannot be used in Session.OnEnd and Application.OnEnd. Syntax Server.MapPath(path) Parameter Description path Required. A relative or virtual path to map to a physical path. If this parameter starts with / or \, it returns a path as if this parameter is a full virtual path. If this parameter doesn't start with / or \, it returns a path relative to the directory of the .asp file being processed Examples Example 1 For the example below, the file test.asp is located in C:\Inetpub\Wwwroot\Script. The file Test.asp (located in C:\Inetpub\Wwwroot\Script) contains the following code: <% response.write(Server.MapPath("test.asp") & " ") response.write(Server.MapPath("script/test.asp") & " ") response.write(Server.MapPath("/script/test.asp") & " ") response.write(Server.MapPath("\script") & " ") response.write(Server.MapPath("/") & " ") response.write(Server.MapPath("\") & " ") %> Output: c:\inetpub\wwwroot\script\test.asp c:\inetpub\wwwroot\script\script\test.asp c:\inetpub\wwwroot\script\test.asp c:\inetpub\wwwroot\script c:\inetpub\wwwroot c:\inetpub\wwwroot Example 2 How to use a relative path to return the relative physical path to the page that is being viewed in the browser: <% response.write(Server.MapPath("../")) %> or <% response.write(Server.MapPath("..\")) %> ASP Transfer Method ________________________________________ The Transfer method sends (transfers) all the state information (all application/session variables and all items in the request collections) created in one ASP file to a second ASP file. When the second ASP page completes its tasks, it will NOT return to the first ASP page (like the Execute method). Note: The Transfer method is an efficient alternate for the Response.Redirect. A redirect forces the Web server to handle an extra request while the Server.Transfer method transfers execution to a different ASP page on the server, and avoids the extra round trip. Syntax Server.Transfer(path) Parameter Description path Required. The location of the ASP file to which control should be transferred Example File1.asp: <% response.write("Line 1 in File 1 ") Server.Transfer("file2.asp") response.write("Line 2 in File 1 ") %> File2.asp: <% response.write("Line 1 in File 2 ") response.write("Line 2 in File 2 ") %> Output: Line 1 in File 1 Line 1 in File 2 Line 2 in File 2 Also look at the Server.Execute method to see the difference between the Server.Transfer and Server.Execute methods. ASP URLEncode Method ________________________________________ The URLEncode method applies URL encoding rules to a specified string. Syntax Server.URLEncode(string) Parameter Description string Required. The string to encode Example <% response.write(Server.URLEncode("http://www.w3schools.com")) %> Output: http%3A%2F%2Fwww%2Ew3schools%2Ecom 6) ASP ASPError Object The ASPError object displays information about errors in scripts. ________________________________________ The ASPError Object The ASPError object was implemented in ASP 3.0 and is available in IIS5 and later. The ASPError object is used to display detailed information of any error that occurs in scripts in an ASP page. Note: The ASPError object is created when Server.GetLastError is called, 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): Properties Property Description ASPCode Returns an error code generated by IIS ASPDescription Returns a detailed description of the error (if the error is ASP-related) Category Returns the source of the error (was the error generated by ASP? By a scripting language? By an object?) Column Returns the column position within the file that generated the 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 Source Returns the actual source code of the line where the error occurred ASP ASPError Object Properties ________________________________________ ASPCode The ASPCode property returns an error code generated by IIS. ASPDescription The ASPDescription property returns a detailed description of the error. Category The Category property returns the source of the error (Was the error generated by IIS? A scripting language? Or a component?). Column The Column property returns the column position within the ASP file that generated the error. Description The Description property returns a short description of the error. File The File property returns the name of the ASP file that generated the error. Line The Line property returns the number of the line within the ASP file that generated the error. Number The Number property returns the standard COM error code for the error. Source The Source property returns the actual source code of the line where the error occurred. Syntax ASPError.ASPCode() ASPError.ASPDescription() ASPError.Category() ASPError.Column() ASPError.Description() ASPError.File() ASPError.Line() ASPError.Number() ASPError.Source() Example <% dim objErr set objErr=Server.GetLastError() response.write("ASPCode=" & objErr.ASPCode) response.write(" ") response.write("ASPDescription=" & objErr.ASPDescription) response.write(" ") response.write("Category=" & objErr.Category) response.write(" ") response.write("Column=" & objErr.Column) response.write(" ") response.write("Description=" & objErr.Description) response.write(" ") response.write("File=" & objErr.File) response.write(" ") response.write("Line=" & objErr.Line) response.write(" ") response.write("Number=" & objErr.Number) response.write(" ") response.write("Source=" & objErr.Source) %> 7) ASP FileSystemObject Object The FileSystemObject object is used to access the file system on a server. ________________________________________ The FileSystemObject Object The FileSystemObject object is used to access the file system on a server. This object can manipulate files, folders, and directory paths. It is also possible to retrieve file system information with this object. The following code creates a text file (c:\test.txt) and then writes some text to the file: <% dim fs,fname set fs=Server.CreateObject("Scripting.FileSystemObject") set fname=fs.CreateTextFile("c:\test.txt",true) fname.WriteLine("Hello World!") fname.Close set fname=nothing set fs=nothing %> The FileSystemObject object's properties and methods are described below: Properties Property Description Drives Returns a collection of all Drive objects on the computer Methods Method Description BuildPath Appends a name to an existing path CopyFile Copies one or more files from one location to another CopyFolder Copies one or more folders from one location to another CreateFolder Creates a new folder CreateTextFile Creates a text file and returns a TextStream object that can be used to read from, or write to the file DeleteFile Deletes one or more specified files DeleteFolder Deletes one or more specified folders DriveExists Checks if a specified drive exists FileExists Checks if a specified file exists FolderExists Checks if a specified folder exists GetAbsolutePathName Returns the complete path from the root of the drive for the specified path GetBaseName Returns the base name of a specified file or folder GetDrive Returns a Drive object corresponding to the drive in a specified path GetDriveName Returns the drive name of a specified path GetExtensionName Returns the file extension name for the last component in a specified path GetFile Returns a File object for a specified path GetFileName Returns the file name or folder name for the last component in a specified path GetFolder Returns a Folder object for a specified path GetParentFolderName Returns the name of the parent folder of the last component in a specified path GetSpecialFolder Returns the path to some of Windows' special folders GetTempName Returns a randomly generated temporary file or folder MoveFile Moves one or more files from one location to another MoveFolder Moves one or more folders from one location to another OpenTextFile Opens a file and returns a TextStream object that can be used to access the file Properties: ASP Drives Property ________________________________________ The Drives property returns a collection of all Drive objects on the computer. Syntax [drivecoll=]FileSystemObject.Drives Methods: ASP BuildPath Method ________________________________________ The BuildPath method appends a name to an existing path. Syntax [newpath=]FileSystemObject.BuildPath(path,name) Parameter Description path Required. The path to append a name to name Required. The name to append to the path Example <% dim fs,path set fs=Server.CreateObject("Scripting.FileSystemObject") path=fs.BuildPath("c:\mydocuments","test") response.write(path) set fs=nothing %> Output: c:\mydocuments\test ASP CopyFile Method ________________________________________ The CopyFile method copies one or more files from one location to another. Syntax FileSystemObject.CopyFile source,destination[,overwrite] Parameter Description source Required. The file or files to copy (wildcards can be used} destination Required. Where to copy the file or files (wildcards cannot be used} overwrite Optional. A Boolean value that specifies whether an existing file can be overwritten. True allows existing files to be overwritten and False prevents existing files from being overwritten. Default is True ________________________________________ Example <% dim fs set fs=Server.CreateObject("Scripting.FileSystemObject") fs.CopyFile "c:\mydocuments\web\*.htm","c:\webpages\" set fs=nothing %> ASP CopyFolder Method ________________________________________ The CopyFolder method copies one or more folders from one location to another. Syntax FileSystemObject.CopyFolder source,destination[,overwrite] Parameter Description source Required. The folder or folders to copy (wildcards can be used) destination Required. Where to copy the folder or folders (wildcards cannot be used) overwrite Optional. A Boolean value that indicates whether an existing folder can be overwritten. True allows existing folders to be overwritten and False prevents existing folders from being overwritten. Default is True Examples <% 'copy all the folders in c:\mydocuments\web 'to the folder c:\webpages dim fs set fs=Server.CreateObject("Scripting.FileSystemObject") fs.CopyFolder "c:\mydocuments\web\*","c:\webpages\" set fs=nothing %> <% 'copy only the folder test from c:\mydocuments\web 'to the folder c:\webpages dim fs set fs=Server.CreateObject("Scripting.FileSystemObject") fs.CopyFolder "c:\mydocuments\web\test","c:\webpages\" set fs=nothing %> ASP CreateFolder Method ________________________________________ The CreateFolder method creates a new folder. Syntax FileSystemObject.CreateFolder(name) Parameter Description name Required. The name of the folder to create Example <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateFolder("c:\asp") set f=nothing set fs=nothing %> ASP CreateTextFile Method ________________________________________ The CreateTextFile method creates a new text file in the current folder and returns a TextStream object that can be used to read from, or write to the file. Syntax FileSystemObject.CreateTextFile(filename[,overwrite[,unicode]]) FolderObject.CreateTextFile(filename[,overwrite[,unicode]]) Parameter Description filename Required. The name of the file to create overwrite Optional. A Boolean value that indicates whether an existing file can be overwritten. True indicates that the file can be overwritten and False indicates that the file can not be overwritten. Default is True unicode Optional. A Boolean value that indicates whether the file is created as a Unicode or an ASCII file. True indicates that the file is created as a Unicode file, False indicates that the file is created as an ASCII file. Default is False ________________________________________ Example for the FileSystemObject object <% dim fs,tfile set fs=Server.CreateObject("Scripting.FileSystemObject") set tfile=fs.CreateTextFile("c:\somefile.txt") tfile.WriteLine("Hello World!") tfile.close set tfile=nothing set fs=nothing %> Example for the Folder object <% dim fs,fo,tfile Set fs=Server.CreateObject("Scripting.FileSystemObject") Set fo=fs.GetFolder("c:\test") Set tfile=fo.CreateTextFile("test.txt",false) tfile.WriteLine("Hello World!") tfile.Close set tfile=nothing set fo=nothing set fs=nothing %> ASP DeleteFile Method ________________________________________ The DeleteFile method deletes one or more specified files. Note: An error will occur if you try to delete a file that doesn't exist. Syntax FileSystemObject.DeleteFile(filename[,force]) Parameter Description filename Required. The name of the file or files to delete (Wildcards are allowed) force Optional. A Boolean value that indicates whether read-only files will be deleted. True indicates that the read-only files will be deleted, False indicates that they will not be deleted. Default is False Example <% dim fs Set fs=Server.CreateObject("Scripting.FileSystemObject") fs.CreateTextFile("c:\test.txt",True) if fs.FileExists("c:\test.txt") then fs.DeleteFile("c:\test.txt") end if set fs=nothing %> ASP DeleteFolder Method ________________________________________ The DeleteFolder method deletes one or more specified folders. Note: An error will occur if you try to delete a folder that does not exist. Syntax FileSystemObject.DeleteFolder(foldername[,force]) Parameter Description foldername Required. The name of the folder or folders to delete (Wildcards are allowed) force Optional. A Boolean value that indicates whether read-only folders will be deleted. True indicates that read-only folders will be deleted, False indicates that they will not be deleted. Default is False Example <% dim fs set fs=Server.CreateObject("Scripting.FileSystemObject") if fs.FolderExists("c:\temp") then fs.DeleteFolder("c:\temp") end if set fs=nothing %> ASP DriveExists Method ________________________________________ The DriveExists method returns a Boolean value that indicates whether a specified drive exists. It returns True if the drive exists and False if not. Syntax FileSystemObject.DriveExists(drive) Parameter Description drive Required. A drive letter or a complete path specification Example <% dim fs set fs=Server.CreateObject("Scripting.FileSystemObject") if fs.DriveExists("c:")=true then response.write("Drive c: exists!") else response.write("Drive c: does not exist.") end If set fs=nothing %> ASP FileExists Method ________________________________________ The FileExists method returns a Boolean value that indicates whether a specified file exists. It returns True if the file exists and False if not. Syntax FileSystemObject.FileExists(filename) Parameter Description filename Required. The name of the file to check if exist ________________________________________ Example <% dim fs set fs=Server.CreateObject("Scripting.FileSystemObject") if fs.FileExists("c:\asp\introduction.asp")=true then response.write("File c:\asp\introduction.asp exists!") else response.write("File c:\asp\introduction.asp does not exist!") end if set fs=nothing %> 8.ASP TextStream Object The TextStream Object The TextStream object is used to access the contents of text files. The following code creates a text file (c:\test.txt) and then writes some text to the file (the variable f is an instance of the TextStream object): <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateTextFile("c:\test.txt",true) f.WriteLine("Hello World!") f.Close set f=nothing set fs=nothing %> To create an instance of the TextStream object you can use the CreateTextFile or OpenTextFile methods of the FileSystemObject object, or you can use the OpenAsTextStream method of the File object. The TextStream object's properties and methods are described below: Properties Property Description AtEndOfLine Returns true if the file pointer is positioned immediately before the end-of-line marker in a TextStream file, and false if not AtEndOfStream Returns true if the file pointer is at the end of a TextStream file, and false if not Column Returns the column number of the current character position in an input stream Line Returns the current line number in a TextStream file Methods Method Description Close Closes an open TextStream file Read Reads a specified number of characters from a TextStream file and returns the result ReadAll Reads an entire TextStream file and returns the result ReadLine Reads one line from a TextStream file and returns the result Skip Skips a specified number of characters when reading a TextStream file SkipLine Skips the next line when reading a TextStream file Write Writes a specified text to a TextStream file WriteLine Writes a specified text and a new-line character to a TextStream file WriteBlankLines Writes a specified number of new-line character to a TextStream file Properties ASP AtEndOfLine Property ________________________________________ The AtEndOfLine property returns a Boolean value. True indicates that the file pointer is positioned immediately before the end-of-line marker in a TextStream file. Otherwise, it returns False. Note: This property will only work on a TextStream object that are open for reading. Syntax TextStreamObject.AtEndOfLine Example <% dim fs,f,t,x set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateTextFile("c:\test.txt") f.write("Hello World!") f.close set t=fs.OpenTextFile("c:\test.txt",1,false) do while t.AtEndOfLine<>true x=t.Read(1) loop t.close Response.Write("The last character is: " & x) %> Output: The last character of the first line in the text file is: ! ASP AtEndOfStream Property ________________________________________ The AtEndOfStream property returns True if the file pointer is at the end of a TextStream file, and False if not. Note: This property will only work on a TextStream object that are open for reading. Syntax TextStreamObject.AtEndOfStream Example <% dim fs,f,t,x set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateTextFile("c:\test.txt") f.write("Hello World!") f.close set t=fs.OpenTextFile("c:\test.txt",1,false) do while t.AtEndOfStream<>true x=t.Read(1) loop t.close Response.Write("The last character is: " & x) %> Output: The last character in the text file is: ! ASP Column Property ________________________________________ The Column property returns the column number of the current character position in an input stream. Note: This property is 1 after a new line character is written (even before any other character is written). Syntax TextStreamObject.Column Example <% dim fs,f,t,x,y set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateTextFile("c:\test.txt") f.write("Hello World!") f.close set t=fs.OpenTextFile("c:\test.txt",1,false) do while t.AtEndOfStream<>true x=t.Read(1) y=t.Column-1 loop t.close Response.Write("The last character in the text file is: " & x) Response.Write(" at character position: " & y) %> Output: The last character in the text file is: ! at character position: 12 ASP Line Property ________________________________________ The Line property returns the current line number in a TextStream file (starting at 1). Syntax TextStreamObject.Line Example <% dim fs,f,t set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateTextFile("c:\test.txt",true) f.WriteLine("Hello World!") f.WriteLine("How are you today?") f.WriteLine("Goodbye!") f.close Set t=fs.OpenTextFile("c:\test.txt",1) do while t.AtEndOfStream=false Response.Write("Line " & t.Line & ": ") Response.Write(t.ReadLine) Response.Write(" ") loop t.Close %> Output: Line 1: Hello World! Line 2: How are you today? Line 3: Goodbye! Methods: ASP Close Method ________________________________________ The Close method closes an open TextStream file. Syntax TextStreamObject.Close Example <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateTextFile("c:\test.txt",true) f.WriteLine("Hello World!") f.Close set f=nothing set fs=nothing %> ASP Read Method ________________________________________ The Read method reads a specified number of characters from a TextStream file and returns the result as a string. Syntax TextStreamObject.Read(numchar) Parameter Description numchar Required. The number of characters to read from the file Example <% dim fs,f,t,x set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateTextFile("c:\test.txt") f.write("Hello World!") f.close set t=fs.OpenTextFile("c:\test.txt",1,false) x=t.Read(5) t.close Response.Write("The first five characters are: " & x) %> Output: The first five characters are: Hello ASP ReadAll Method ________________________________________ The ReadAll method reads an entire TextStream file and returns the result as a string. Note: This method is not suitable for large files (it wastes memory resources). Syntax TextStreamObject.ReadAll Example <% dim fs,f,t,x set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateTextFile("c:\test.txt") f.write("Hello World!") f.close set t=fs.OpenTextFile("c:\test.txt",1,false) x=t.ReadAll t.close Response.Write("The text in the file is: " & x) %> Output: The text in the file is: Hello World! ASP ReadLine Method ________________________________________ The ReadLine method reads one line from a TextStream file and returns the result as a string. Syntax TextStreamObject.ReadLine Example <% dim fs,f,t,x set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateTextFile("c:\test.txt") f.writeline("Line 1") f.writeline("Line 2") f.writeline("Line 3") f.close set t=fs.OpenTextFile("c:\test.txt",1,false) x=t.ReadLine t.close Response.Write("The first line in the file ") Response.Write("contains this text: " & x) %> Output: The first line in the file contains this text: Line 1 ASP Skip Method ________________________________________ The Skip method skips a specified number of characters when reading a TextStream file. Syntax TextStreamObject.Skip(numchar) Parameter Description numchar Required. The number of characters to skip Example <% dim fs,f,t,x set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateTextFile("c:\test.txt") f.write("Hello World!") f.close set t=fs.OpenTextFile("c:\test.txt",1,false) t.Skip(7) x=t.ReadAll t.close Response.Write("The output after skipping some characters: " & x) %> Output: The output after skipping some characters: orld! ________________________________________ ASP SkipLine Method ________________________________________ The SkipLine method skips a line when reading a TextStream file. Syntax TextStreamObject.SkipLine Example <% dim fs,f,t,x set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateTextFile("c:\test.txt") f.writeline("Line 1") f.writeline("Line 2") f.writeline("Line 3") f.close set t=fs.OpenTextFile("c:\test.txt",1,false) t.SkipLine x=t.ReadAll t.close Response.Write("Output after skipping the first ") Response.Write(" line in the file: " & x) %> Output: Output after skipping the first line in the file: Line 2 Line 3 ASP Write Method ________________________________________ The Write method writes a specified text to a TextStream file. Note: This method write text to the TextStream file with no spaces or line breaks between each string. Syntax TextStreamObject.Write(text) Parameter Description text Required. The text to write to the file Example <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateTextFile("c:\test.txt",true) f.write("Hello World!") f.write("How are you today?") f.close set f=nothing set fs=nothing %> The file test.txt will look like this after executing the code above: Hello World!How are you today? ASP WriteLine Method ________________________________________ The WriteLine method writes a specified text and a new-line character to a TextStream file. Syntax TextStreamObject.WriteLine(text) Parameter Description text Optional. The text to write to the file. If you do not specify this parameter, a new-line character will be written to the file Example <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateTextFile("c:\test.txt",true) f.WriteLine("Hello World!") f.WriteLine("How are you today?") f.WriteLine("Goodbye!") f.close set f=nothing set fs=nothing %> The file test.txt will look like this after executing the code above: Hello World! How are you today? Goodbye! ASP WriteBlankLines Method ________________________________________ The WriteBlankLines method writes a specified number of new-line characters to a TextStream file. Syntax TextStreamObject.WriteBlankLines(numlines) Parameter Description numlines Required. The number of new-line characters to write to the file Example <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateTextFile("c:\test.txt",true) f.WriteLine("Hello World!") f.WriteBlankLines(2) f.WriteLine("How are you today?") f.close set f=nothing set fs=nothing %> The file test.txt will look like this after executing the code above: Hello World! How are you today? 9.ASP Drive Object The Drive object is used to get information about a local disk drive or a network share. ________________________________________ The Drive Object The Drive object is used to return information about a local disk drive or a network share. The Drive object can return information about a drive's type of file system, free space, serial number, volume name, and more. Note: You cannot return information about a drive's content with the Drive object. For this purpose you will have to use the Folder object. To work with the properties of the Drive object, you will have to create an instance of the Drive object through the FileSystemObject object. First; create a FileSystemObject object and then instantiate the Drive object through the GetDrive method or the Drives property of the FileSystemObject object. The Drive object's properties are described below: Properties Property Description AvailableSpace Returns the amount of available space to a user on a specified drive or network share DriveLetter Returns one uppercase letter that identifies the local drive or a network share DriveType Returns the type of a specified drive FileSystem Returns the file system in use for a specified drive FreeSpace Returns the amount of free space to a user on a specified drive or network share IsReady Returns true if the specified drive is ready and false if not Path Returns an uppercase letter followed by a colon that indicates the path name for a specified drive RootFolder Returns a Folder object that represents the root folder of a specified drive SerialNumber Returns the serial number of a specified drive ShareName Returns the network share name for a specified drive TotalSize Returns the total size of a specified drive or network share VolumeName Sets or returns the volume name of a specified drive ASP AvailableSpace Property ________________________________________ The AvailableSpace property returns the amount of available space to a user on the specified drive or network share. Note: The value returned is often equal to the value returned by the FreeSpace property. Syntax DriveObject.AvailableSpace Example <% Dim fs,d Set fs=Server.CreateObject("Scripting.FileSystemObject") Set d=fs.GetDrive("c:") Response.Write("Drive " & d) Response.Write(" Available space in bytes: " & d.AvailableSpace) set d=nothing set fs=nothing %> Output: Drive c: Available space in bytes: 884465152 ________________________________________ ASP DriveLetter Property ________________________________________ The DriveLetter property returns one uppercase letter that identifies the local drive or a network share. Syntax DriveObject.DriveLetter Example <% dim fs,d set fs=Server.CreateObject("Scripting.FileSystemObject") set d=fs.GetDrive("c:") Response.Write("The drive letter is: " & d.driveletter) set d=nothing set fs=nothing %> Output: The drive letter is: C ASP DriveType Property ________________________________________ The DriveType property returns a value that indicates the type of a specified drive. This property can return one of the following values: • 0 = unknown • 1 = removable • 2 = fixed • 3 = network • 4 = CD-ROM • 5 = RAM disk Syntax DriveObject.DriveType Example <% dim fs,d set fs=Server.CreateObject("Scripting.FileSystemObject") set d=fs.GetDrive("a:") Response.Write("The drive type is: " & d.DriveType) set d=nothing set fs=nothing %> Output: The drive type is: 1 ASP FileSystem Property ________________________________________ The FileSystem property returns the file system in use for a specified drive. This property will return one of the following: • FAT - for removable drives • CDFS - for CD-ROM drives • FAT, FAT32 or NTFS - for hard disks on Windows 2000 or Windows NT • FAT or FAT32 - for hard disks on Windows 9x Syntax DriveObject.FileSystem Example <% dim fs,d set fs=Server.CreateObject("Scripting.FileSystemObject") set d=fs.GetDrive("c:") Response.Write("The file system in use is: " & d.FileSystem) set d=nothing set fs=nothing %> Output: The file system in use is: NTFS ASP FreeSpace Property ________________________________________ The FreeSpace property returns the amount of free space to a user on the specified drive or network share. Note: The value returned is often equal to the value returned by the AvailableSpace property. Syntax DriveObject.FreeSpace Example <% dim fs,d set fs=Server.CreateObject("Scripting.FileSystemObject") set d=fs.GetDrive("c:") Response.Write("Drive " & d) Response.Write(" Free space in bytes: " & d.FreeSpace) set d=nothing set fs=nothing %> Output: Drive c: Free space in bytes: 884465664 ASP IsReady Property ________________________________________ The IsReady property returns true if a specified drive is ready and false if not. Syntax DriveObject.IsReady Example <% dim fs,d,n set fs=Server.CreateObject("Scripting.FileSystemObject") set d=fs.GetDrive("a:") n = "The " & d.DriveLetter if d.IsReady=true then n=n & " drive is ready!" else n=n & " drive is not ready!" end if Response.Write(n) set d=nothing set fs=nothing %> Output: The A drive is not ready! ASP Path Property ________________________________________ The Path property is used to return the path for a specified drive, file, or folder. Syntax DriveObject.Path FileObject.Path FolderObject.Path Example for the Drive object <% dim fs,d set fs=Server.CreateObject("Scripting.FileSystemObject") set d=fs.GetDrive("c:") Response.Write("The path is " & d.Path) set d=nothing set fs=nothing %> Output: The path is C: Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\asp\test\test.asp") Response.Write("The path is: " & f.Path) set f=nothing set fs=nothing %> Output: The path is: C:\asp\test\test.asp Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\asp\test") Response.Write("The path is: " & fo.Path) set fo=nothing set fs=nothing %> Output: The path is: C:\asp\test ASP RootFolder Property ________________________________________ The RootFolder property returns a Folder object that represents the root folder of a specified drive. Syntax DriveObject.RootFolder Example <% dim fs,d set fs=Server.CreateObject("Scripting.FileSystemObject") set d=fs.GetDrive("c:") Response.Write("The root folder is: " & d.RootFolder) set d=nothing set fs=nothing %> Output: The root folder is: C:\ ASP SerialNumber Property ________________________________________ The SerialNumber property returns the serial number of a specified drive. Syntax DriveObject.SerialNumber Example <% dim fs,d set fs=Server.CreateObject("Scripting.FileSystemObject") set d=fs.GetDrive("c:") Response.Write("The serial number is: " & d.SerialNumber) set d=nothing set fs=nothing %> Output: The serial number is: 474680516 ASP ShareName Property ________________________________________ The ShareName property returns the network share name for a specified drive. Syntax DriveObject.ShareName Example <% dim fs,d set fs=Server.CreateObject("Scripting.FileSystemObject") set d=fs.GetDrive("c:") Response.Write("The sharename is: " & d.ShareName) set d=nothing set fs=nothing %> ASP TotalSize Property ________________________________________ The TotalSize property returns the total size, in bytes, of a specified drive or network share. Syntax DriveObject.TotalSize Example <% dim fs,d set fs=Server.CreateObject("Scripting.FileSystemObject") set d=fs.GetDrive("c:") Response.Write("The total size in bytes is: " & d.TotalSize) set d=nothing set fs=nothing %> Output: The total size in bytes is: 4293563392 ASP VolumeName Property ________________________________________ The VolumeName property sets or returns the volume name of a specified drive. Syntax DriveObject.VolumeName[=newname] Parameter Description newname Optional. Sets the new name of the specified drive Example <% dim fs,d set fs=Server.CreateObject("Scripting.FileSystemObject") set d=fs.GetDrive("c:") Response.Write("The volume name is: " & d.VolumeName) set d=nothing set fs=nothing %> 10.ASP File Object The File object is used to return information about a specified file. ________________________________________ The File Object The File object is used to return information about a specified file. To work with the properties and methods of the File object, you will have to create an instance of the File object through the FileSystemObject object. First; create a FileSystemObject object and then instantiate the File object through the GetFile method of the FileSystemObject object or through the Files property of the Folder object. The following code uses the GetFile method of the FileSystemObject object to instantiate the File object and the DateCreated property to return the date when the specified file was created: Example <% Dim fs,f Set fs=Server.CreateObject("Scripting.FileSystemObject") Set f=fs.GetFile("c:\test.txt") Response.Write("File created: " & f.DateCreated) set f=nothing set fs=nothing %> The File object's properties and methods are described below: Properties Property Description Attributes Sets or returns the attributes of a specified file DateCreated Returns the date and time when a specified file was created DateLastAccessed Returns the date and time when a specified file was last accessed DateLastModified Returns the date and time when a specified file was last modified Drive Returns the drive letter of the drive where a specified file or folder resides Name Sets or returns the name of a specified file ParentFolder Returns the folder object for the parent of the specified file Path Returns the path for a specified file ShortName Returns the short name of a specified file (the 8.3 naming convention) ShortPath Returns the short path of a specified file (the 8.3 naming convention) Size Returns the size, in bytes, of a specified file Type Returns the type of a specified file Methods Method Description Copy Copies a specified file from one location to another Delete Deletes a specified file Move Moves a specified file from one location to another OpenAsTextStream Opens a specified file and returns a TextStream object to access the file Properties: ASP Attributes Property ________________________________________ The Attributes property is used to set or return the attribute or attributes of a specified file or folder. Syntax FileObject.Attributes[=newattributes] FolderObject.Attributes[=newattributes] Parameter Description newattributes Optional. Specifies the attribute value for the file or folder. Can take any of the following values or a combination of the following values: 0 = Normal file 1 = Read-only file 2 = Hidden file 4 = System file 16 = Folder or directory 32 = File has changed since last backup 1024 = Link or shortcut 2048 = Compressed file Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") Response.Write("The attributes of the file are: ") Response.Write(f.Attributes) set f=nothing set fs=nothing %> Output: The attributes of the file are: 32 Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("The attributes of the folder are: ") Response.Write(fo.Attributes) set fo=nothing set fs=nothing %> Output: The attributes of the folder are: 16 ASP DateCreated Property ________________________________________ The DateCreated property is used to return the date and time when a specified file or folder was created. Syntax FileObject.DateCreated FolderObject.DateCreated Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") Response.Write("File created: ") Response.Write(f.DateCreated) set f=nothing set fs=nothing %> Output: File created: 9/19/2001 10:01:19 AM Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("Folder created: ") Response.Write(fo.DateCreated) set fo=nothing set fs=nothing %> Output: Folder created: 9/19/2001 10:01:19 AM ASP DateLastAccessed Property ________________________________________ The DateLastAccessed property is used to return the date and time when a specified file or folder was last accessed. Syntax FileObject.DateLastAccessed FolderObject.DateLastAccessed Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") Response.Write("File last accessed on: ") Response.Write(f.DateLastAccessed) set f=nothing set fs=nothing %> Output: File last accessed on: 10/29/2001 10:21:23 AM Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("Folder last accessed on: ") Response.Write(fo.DateLastAccessed) set fo=nothing set fs=nothing %> Output: Folder last accessed on: 9/19/2001 10:01:19 AM ASP DateLastModified Property ________________________________________ The DateLastModified property is used to return the date and time when a specified file or folder was last modified. Syntax FileObject.DateLastModified FolderObject.DateLastModified Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") Response.Write("File last modified on: ") Response.Write(f.DateLastModified) set f=nothing set fs=nothing %> Output: File last modified on: 1/10/2001 10:01:19 AM Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("Folder last modified on: ") Response.Write(fo.DateLastModified) set fo=nothing set fs=nothing %> Output: Folder last modified on: 9/19/2001 10:01:19 AM ASP Drive Property ________________________________________ The Drive property is used to return the drive letter of the drive where the specified file or folder resides. Syntax FileObject.Drive FolderObject.Drive Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") Response.Write("File resides on drive: ") Response.Write(f.Drive) set f=nothing set fs=nothing %> Output: File resides on drive: c: Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("Folder resides on drive: ") Response.Write(fo.Drive) set fo=nothing set fs=nothing %> Output: Folder resides on drive: c: ASP Name Property ________________________________________ The Name property is used to set or return the name of a specified file or folder. Syntax FileObject.Name[=newname] FolderObject.Name[=newname] Parameter Description newname Optional. Specifies the name of the file or folder Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") Response.Write("The file's name: ") Response.Write(f.Name) set f=nothing set fs=nothing %> Output: The file's name: test.txt Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("The folder's name: ") Response.Write(fo.Name) set fo=nothing set fs=nothing %> Output: The folder's name: test ASP ParentFolder Property ________________________________________ The ParentFolder property is used to return the folder object for the parent of the specified file or folder. Syntax FileObject.ParentFolder FolderObject.ParentFolder Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\asp\test\test.asp") Response.Write("The file test.asp is in the folder: ") Response.Write(f.ParentFolder) set f=nothing set fs=nothing %> Output: The file test.asp is in the folder: C:\asp\test Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\asp\test") Response.Write("The folder test is in the folder: ") Response.Write(fo.ParentFolder) set fo=nothing set fs=nothing %> Output: The folder test is in the folder: C:\asp ASP Path Property ________________________________________ The Path property is used to return the path for a specified drive, file, or folder. Syntax DriveObject.Path FileObject.Path FolderObject.Path Example for the Drive object <% dim fs,d set fs=Server.CreateObject("Scripting.FileSystemObject") set d=fs.GetDrive("c:") Response.Write("The path is " & d.Path) set d=nothing set fs=nothing %> Output: The path is C: Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\asp\test\test.asp") Response.Write("The path is: " & f.Path) set f=nothing set fs=nothing %> Output: The path is: C:\asp\test\test.asp Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\asp\test") Response.Write("The path is: " & fo.Path) set fo=nothing set fs=nothing %> Output: The path is: C:\asp\test ASP ShortName Property ________________________________________ The ShortName property is used to return the short name of a specified file or folder (the 8.3 naming convention). Syntax FileObject.ShortName FolderObject.ShortName Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\hitcounterfile.txt")) Response.Write("Name: " & f.Name) Response.Write(" ShortName: " & f.ShortName) set f=nothing set fs=nothing %> Output: Name: hitcounterfile.txt ShortName: HITCOU~1.TXT Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\asp_test_web") Response.Write("Name: " & fo.Name) Response.Write(" ShortName: " & fo.ShortName) set fo=nothing set fs=nothing %> Output: Name: asp_test_web ShortName: ASP_TE~1 ASP ShortPath Property ________________________________________ The ShortPath property is used to return the short path of the specified file or folder (the 8.3 naming convention). Syntax FileObject.ShortPath FolderObject.ShortPath Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\asp_test_web\hitcounterfile.txt") Response.Write("Path: " & f.Path) Response.Write(" ShortPath: " & f.ShortPath) set f=nothing set fs=nothing %> Output: Path: C:\asp_test_web\hitcounterfile.txt ShortPath: C:\ASP_TE~1\HITCOU~1.TXT Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\asp_test_web") Response.Write("Path: " & fo.Path) Response.Write(" ShortPath: " & fo.ShortPath) set fo=nothing set fs=nothing %> Output: Path: C:\asp_test_web ShortPath: C:\ASP_TE~1 ASP Size Property ________________________________________ The Size property is used to return the size, in bytes, of the specified file or folder. Syntax FileObject.Size FolderObject.Size Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.asp") Response.Write("The size of test.asp is: ") Response.Write(f.Size & " bytes.") set f=nothing set fs=nothing %> Output: The size of test.asp is: 10556 bytes. Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("The size of the folder test is: ") Response.Write(fo.Size & " bytes.") set fo=nothing set fs=nothing %> Output: The size of the folder test is: 123456 bytes. ASP Type Property ________________________________________ The Type property is used to return the type of the specified file or folder. Syntax FileObject.Type FolderObject.Type Examples for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:test.txt") Response.Write("The file test.txt is of type: ") Response.Write(f.Type) set f=nothing set fs=nothing %> Output: The file test.txt is of type: Text Document <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:test.asp") Response.Write("The file test.asp is of type: ") Response.Write(f.Type) set f=nothing set fs=nothing %> Output: The file test.asp is of type: Active Server Document Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("The folder test is of type: ") Response.Write(fo.Type) set fo=nothing set fs=nothing %> Output: The folder test is of type: File Folder Methods; ASP Copy Method ________________________________________ The Copy method copies the specified file or folder from one location to another. Syntax FileObject.Copy(destination[,overwrite]) FolderObject.Copy(destination[,overwrite]) Parameter Description destination Required. Where to copy the file or folder. Wildcard characters are not allowed overwrite Optional. A Boolean value indicating whether an existing file or folder can be overwritten. True indicates that the file/folder can be overwritten, false indicates that the file/folder cannot be overwritten. Default is true. ________________________________________ Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") f.Copy("c:\new_test.txt",false) set f=nothing set fs=nothing %> Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") fo.Copy("c:\new_test",false) set fo=nothing set fs=nothing %> ASP Delete Method ________________________________________ The Delete method deletes a specified file or folder. Syntax FileObject.Delete[(force)] FolderObject.Delete[(force)] Parameter Description force Optional. A Boolean value that indicates whether a read-only file or folder are to be deleted. True indicates that a read-only file/folder will be deleted and false indicates that it will not be deleted. Default is false. Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") f.Delete set f=nothing set fs=nothing %> Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") fo.Delete set fo=nothing set fs=nothing %> ASP Move Method ________________________________________ The Move method moves the specified file or folder from one location to another. Syntax FileObject.Move(destination) FolderObject.Move(destination) Parameter Description destination Required. Where to move the file or folder. Wildcard characters are not allowed Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") Set f=fs.GetFile("c:\test.txt") f.Move("c:\test\test.txt") set f=nothing set fs=nothing %> Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") fo.Move("c:\asp\test") set fo=nothing set fs=nothing %> ASP OpenAsTextStream Method ________________________________________ The OpenAsTextStream method opens the specified file and returns a TextStream object to access the file. Syntax FileObject.OpenAsTextStream(mode,format) Parameter Description mode Optional. How to open the file. • 1 = ForReading - Open a file for reading. You cannot write to this file • 2 = ForWriting - Open a file for writing • 8 = ForAppending - Open a file and write to the end of the file format Optional. The format of the file. • 0 = TristateFalse - Default. Open the file as ASCII • -1 = TristateTrue - Open the file as Unicode • -2 = TristateUseDefault - Open the file using the system default Example <% dim fs,f,ts set fs=Server.CreateObject("Scripting.FileSystemObject") Set f=fs.GetFile("c:\test.txt") Set ts=f.OpenAsTextStream(ForWriting) ts.Write("Hello World!") ts.Close Set ts=f.OpenAsTextStream(ForReading) Response.Write(ts.ReadAll) ts.Close set ts=nothing set f=nothing set fs=nothing %> Output: Hello World! 11.ASP Folder Object The Folder Object is used to return information about a specified folder. ________________________________________ The Folder Object The Folder object is used to return information about a specified folder. To work with the properties and methods of the Folder object, you will have to create an instance of the Folder object through the FileSystemObject object. First; create a FileSystemObject object and then instantiate the Folder object through the GetFolder method of the FileSystemObject object. The following code uses the GetFolder method of the FileSystemObject object to instantiate the Folder object and the DateCreated property to return the date when the specified folder was created: <% Dim fs,fo Set fs=Server.CreateObject("Scripting.FileSystemObject") Set fo=fs.GetFolder("c:\test") Response.Write("Folder created: " & fo.DateCreated) set fo=nothing set fs=nothing %> Output: Folder created: 10/22/2008 10:01:19 AM The Folder object's collections, properties, and methods are described below: Collections Collection Description Files Returns a collection of all the files in a specified folder SubFolders Returns a collection of all subfolders in a specified folder Properties Property Description Attributes Sets or returns the attributes of a specified folder DateCreated Returns the date and time when a specified folder was created DateLastAccessed Returns the date and time when a specified folder was last accessed DateLastModified Returns the date and time when a specified folder was last modified Drive Returns the drive letter of the drive where the specified folder resides IsRootFolder Returns true if a folder is the root folder and false if not Name Sets or returns the name of a specified folder ParentFolder Returns the parent folder of a specified folder Path Returns the path for a specified folder ShortName Returns the short name of a specified folder (the 8.3 naming convention) ShortPath Returns the short path of a specified folder (the 8.3 naming convention) Size Returns the size of a specified folder Type Returns the type of a specified folder Methods Method Description Copy Copies a specified folder from one location to another Delete Deletes a specified folder Move Moves a specified folder from one location to another CreateTextFile Creates a new text file in the specified folder and returns a TextStream object Collections: ASP Files Collection ________________________________________ The Files collection returns a collection of all the files in a specified folder. Syntax FolderObject.Files Example <% dim fs,fo,x set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test\") for each x in fo.files 'Print the name of all files in the test folder Response.write(x.Name & " ") next set fo=nothing set fs=nothing %> Output: test_adv.txt guestbook.txt links.txt links2.txt textads.txt textfile.txt ASP SubFolders Collection ________________________________________ The SubFolders collection returns a collection of all subfolders in a specified folder. Syntax FolderObject.SubFolders Example <% dim fs,fo,x set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test\") for each x in fo.SubFolders 'Print the name of all subfolders in the test folder Response.write(x.Name & " ") next set fo=nothing set fs=nothing %> Output: html css asp vbscript Properties: ASP Attributes Property ________________________________________ The Attributes property is used to set or return the attribute or attributes of a specified file or folder. Syntax FileObject.Attributes[=newattributes] FolderObject.Attributes[=newattributes] Parameter Description newattributes Optional. Specifies the attribute value for the file or folder. Can take any of the following values or a combination of the following values: 0 = Normal file 1 = Read-only file 2 = Hidden file 4 = System file 16 = Folder or directory 32 = File has changed since last backup 1024 = Link or shortcut 2048 = Compressed file Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") Response.Write("The attributes of the file are: ") Response.Write(f.Attributes) set f=nothing set fs=nothing %> Output: The attributes of the file are: 32 Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("The attributes of the folder are: ") Response.Write(fo.Attributes) set fo=nothing set fs=nothing %> Output: The attributes of the folder are: 16 ASP DateCreated Property ________________________________________ The DateCreated property is used to return the date and time when a specified file or folder was created. Syntax FileObject.DateCreated FolderObject.DateCreated Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") Response.Write("File created: ") Response.Write(f.DateCreated) set f=nothing set fs=nothing %> Output: File created: 9/19/2001 10:01:19 AM Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("Folder created: ") Response.Write(fo.DateCreated) set fo=nothing set fs=nothing %> Output: Folder created: 9/19/2001 10:01:19 AM ASP DateLastAccessed Property ________________________________________ The DateLastAccessed property is used to return the date and time when a specified file or folder was last accessed. Syntax FileObject.DateLastAccessed FolderObject.DateLastAccessed Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") Response.Write("File last accessed on: ") Response.Write(f.DateLastAccessed) set f=nothing set fs=nothing %> Output: File last accessed on: 10/29/2001 10:21:23 AM Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("Folder last accessed on: ") Response.Write(fo.DateLastAccessed) set fo=nothing set fs=nothing %> Output: Folder last accessed on: 9/19/2001 10:01:19 AM ASP DateLastModified Property ________________________________________ The DateLastModified property is used to return the date and time when a specified file or folder was last modified. Syntax FileObject.DateLastModified FolderObject.DateLastModified Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") Response.Write("File last modified on: ") Response.Write(f.DateLastModified) set f=nothing set fs=nothing %> Output: File last modified on: 1/10/2001 10:01:19 AM Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("Folder last modified on: ") Response.Write(fo.DateLastModified) set fo=nothing set fs=nothing %> Output: Folder last modified on: 9/19/2001 10:01:19 AM ASP Drive Property ________________________________________ The Drive property is used to return the drive letter of the drive where the specified file or folder resides. Syntax FileObject.Drive FolderObject.Drive Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") Response.Write("File resides on drive: ") Response.Write(f.Drive) set f=nothing set fs=nothing %> Output: File resides on drive: c: Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("Folder resides on drive: ") Response.Write(fo.Drive) set fo=nothing set fs=nothing %> Output: Folder resides on drive: c: ASP IsRootFolder Property ________________________________________ The IsRootFolder property returns true if the specified folder is the root folder and false if not. Syntax FolderObject.IsRootFolder Example <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\asp\test") if fo.IsRootFolder=true then Response.Write("The folder is the root folder!") else Response.Write("The folder is not the root folder!") end if set fo=nothing set fs=nothing %> Output: The folder is not the root folder! ASP Name Property ________________________________________ The Name property is used to set or return the name of a specified file or folder. Syntax FileObject.Name[=newname] FolderObject.Name[=newname] Parameter Description newname Optional. Specifies the name of the file or folder Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") Response.Write("The file's name: ") Response.Write(f.Name) set f=nothing set fs=nothing %> Output: The file's name: test.txt Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("The folder's name: ") Response.Write(fo.Name) set fo=nothing set fs=nothing %> Output: The folder's name: test ASP ParentFolder Property ________________________________________ The ParentFolder property is used to return the folder object for the parent of the specified file or folder. Syntax FileObject.ParentFolder FolderObject.ParentFolder Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\asp\test\test.asp") Response.Write("The file test.asp is in the folder: ") Response.Write(f.ParentFolder) set f=nothing set fs=nothing %> Output: The file test.asp is in the folder: C:\asp\test Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\asp\test") Response.Write("The folder test is in the folder: ") Response.Write(fo.ParentFolder) set fo=nothing set fs=nothing %> Output: The folder test is in the folder: C:\asp ASP Path Property ________________________________________ The Path property is used to return the path for a specified drive, file, or folder. Syntax DriveObject.Path FileObject.Path FolderObject.Path Example for the Drive object <% dim fs,d set fs=Server.CreateObject("Scripting.FileSystemObject") set d=fs.GetDrive("c:") Response.Write("The path is " & d.Path) set d=nothing set fs=nothing %> Output: The path is C: Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\asp\test\test.asp") Response.Write("The path is: " & f.Path) set f=nothing set fs=nothing %> Output: The path is: C:\asp\test\test.asp Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\asp\test") Response.Write("The path is: " & fo.Path) set fo=nothing set fs=nothing %> Output: The path is: C:\asp\test ________________________________________ ASP ShortName Property ________________________________________ The ShortName property is used to return the short name of a specified file or folder (the 8.3 naming convention). Syntax FileObject.ShortName FolderObject.ShortName Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\hitcounterfile.txt")) Response.Write("Name: " & f.Name) Response.Write(" ShortName: " & f.ShortName) set f=nothing set fs=nothing %> Output: Name: hitcounterfile.txt ShortName: HITCOU~1.TXT Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\asp_test_web") Response.Write("Name: " & fo.Name) Response.Write(" ShortName: " & fo.ShortName) set fo=nothing set fs=nothing %> Output: Name: asp_test_web ShortName: ASP_TE~1 ASP ShortPath Property ________________________________________ The ShortPath property is used to return the short path of the specified file or folder (the 8.3 naming convention). Syntax FileObject.ShortPath FolderObject.ShortPath Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\asp_test_web\hitcounterfile.txt") Response.Write("Path: " & f.Path) Response.Write(" ShortPath: " & f.ShortPath) set f=nothing set fs=nothing %> Output: Path: C:\asp_test_web\hitcounterfile.txt ShortPath: C:\ASP_TE~1\HITCOU~1.TXT Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\asp_test_web") Response.Write("Path: " & fo.Path) Response.Write(" ShortPath: " & fo.ShortPath) set fo=nothing set fs=nothing %> Output: Path: C:\asp_test_web ShortPath: C:\ASP_TE~1 ASP Size Property ________________________________________ The Size property is used to return the size, in bytes, of the specified file or folder. Syntax FileObject.Size FolderObject.Size Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.asp") Response.Write("The size of test.asp is: ") Response.Write(f.Size & " bytes.") set f=nothing set fs=nothing %> Output: The size of test.asp is: 10556 bytes. Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("The size of the folder test is: ") Response.Write(fo.Size & " bytes.") set fo=nothing set fs=nothing %> Output: The size of the folder test is: 123456 bytes. ASP Type Property ________________________________________ The Type property is used to return the type of the specified file or folder. Syntax FileObject.Type FolderObject.Type Examples for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:test.txt") Response.Write("The file test.txt is of type: ") Response.Write(f.Type) set f=nothing set fs=nothing %> Output: The file test.txt is of type: Text Document <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:test.asp") Response.Write("The file test.asp is of type: ") Response.Write(f.Type) set f=nothing set fs=nothing %> Output: The file test.asp is of type: Active Server Document Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") Response.Write("The folder test is of type: ") Response.Write(fo.Type) set fo=nothing set fs=nothing %> Output: The folder test is of type: File Folder Methods: ASP Copy Method ________________________________________ The Copy method copies the specified file or folder from one location to another. Syntax FileObject.Copy(destination[,overwrite]) FolderObject.Copy(destination[,overwrite]) Parameter Description destination Required. Where to copy the file or folder. Wildcard characters are not allowed overwrite Optional. A Boolean value indicating whether an existing file or folder can be overwritten. True indicates that the file/folder can be overwritten, false indicates that the file/folder cannot be overwritten. Default is true. ________________________________________ Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") f.Copy("c:\new_test.txt",false) set f=nothing set fs=nothing %> Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") fo.Copy("c:\new_test",false) set fo=nothing set fs=nothing %> ASP Delete Method ________________________________________ The Delete method deletes a specified file or folder. Syntax FileObject.Delete[(force)] FolderObject.Delete[(force)] Parameter Description force Optional. A Boolean value that indicates whether a read-only file or folder are to be deleted. True indicates that a read-only file/folder will be deleted and false indicates that it will not be deleted. Default is false. Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test.txt") f.Delete set f=nothing set fs=nothing %> Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") fo.Delete set fo=nothing set fs=nothing %> ASP Move Method ________________________________________ The Move method moves the specified file or folder from one location to another. Syntax FileObject.Move(destination) FolderObject.Move(destination) Parameter Description destination Required. Where to move the file or folder. Wildcard characters are not allowed Example for the File object <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") Set f=fs.GetFile("c:\test.txt") f.Move("c:\test\test.txt") set f=nothing set fs=nothing %> Example for the Folder object <% dim fs,fo set fs=Server.CreateObject("Scripting.FileSystemObject") set fo=fs.GetFolder("c:\test") fo.Move("c:\asp\test") set fo=nothing set fs=nothing %> ASP CreateTextFile Method ________________________________________ The CreateTextFile method creates a new text file in the current folder and returns a TextStream object that can be used to read from, or write to the file. Syntax FileSystemObject.CreateTextFile(filename[,overwrite[,unicode]]) FolderObject.CreateTextFile(filename[,overwrite[,unicode]]) Parameter Description filename Required. The name of the file to create overwrite Optional. A Boolean value that indicates whether an existing file can be overwritten. True indicates that the file can be overwritten and False indicates that the file can not be overwritten. Default is True unicode Optional. A Boolean value that indicates whether the file is created as a Unicode or an ASCII file. True indicates that the file is created as a Unicode file, False indicates that the file is created as an ASCII file. Default is False ________________________________________ Example for the FileSystemObject object <% dim fs,tfile set fs=Server.CreateObject("Scripting.FileSystemObject") set tfile=fs.CreateTextFile("c:\somefile.txt") tfile.WriteLine("Hello World!") tfile.close set tfile=nothing set fs=nothing %> Example for the Folder object <% dim fs,fo,tfile Set fs=Server.CreateObject("Scripting.FileSystemObject") Set fo=fs.GetFolder("c:\test") Set tfile=fo.CreateTextFile("test.txt",false) tfile.WriteLine("Hello World!") tfile.Close set tfile=nothing set fo=nothing set fs=nothing %> 12.ASP Components ASP AdRotator Componentents The ASP AdRotator component creates an AdRotator object 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") %> ________________________________________ ASP AdRotator Example Assume that we have the following text file, named "ads.txt": REDIRECT banners.asp * w3s.gif http://www.w3schools.com Free Tutorials from W3Schools 50 xmlspy.gif http://www.altova.com XML Editor from Altova 50 The lines below the asterisk in the text file above specifies the name of the images (ads) to be displayed, the hyperlink addresses, the alternate text (for the images), and the display rates (in percent). The first line in the text file above specifies what to happen when a visitor clicks on one of the images. The redirection page (banners.asp) will receive a querystring with the URL to redirect to. Tip: To specify the height, width, and border of the image, you can insert the following lines under REDIRECT: REDIRECT banners.asp WIDTH 468 HEIGHT 60 BORDER 0 * w3s.gif ... The "banners.asp" file looks like this: Example <% url=Request.QueryString("url") If url<>"" then Response.Redirect(url) %> <% set adrotator=Server.CreateObject("MSWC.AdRotator") response.write(adrotator.GetAdvertisement("textfile.txt")) %> That's all!! ________________________________________ ASP AdRotator Properties Property Description Example Border Specifies the size of the borders around the advertisement <% set adrot=Server.CreateObject("MSWC.AdRotator") adrot.Border="2" Response.Write(adrot.GetAdvertisement("ads.txt")) %> Clickable Specifies whether the advertisement is a hyperlink <% set adrot=Server.CreateObject("MSWC.AdRotator") adrot.Clickable=false Response.Write(adrot.GetAdvertisement("ads.txt")) %> TargetFrame Name of the frame to display the advertisement <% set adrot=Server.CreateObject("MSWC.AdRotator") adrot.TargetFrame="target='_blank'" Response.Write(adrot.GetAdvertisement("ads.txt")) %> ASP AdRotator Methods Method Description Example GetAdvertisement Returns HTML that displays the advertisement in the page <% set adrot=Server.CreateObject("MSWC.AdRotator") Response.Write(adrot.GetAdvertisement("ads.txt")) %> ________________________________________ ASP Browser Capabilities Component ASP Browser Capabilities Component The ASP Browser Capabilities component creates a BrowserType object that determines the type, capabilities and version number of a visitor's browser. When a browser connects to a server, a User Agent header is also sent to the server. This header contains information about the browser. The BrowserType object compares the information in the header with information in a file on the server called "Browscap.ini". If there is a match between the browser type and version number in the header and the information in the "Browsercap.ini" file, the BrowserType object can be used to list the properties of the matching browser. If there is no match for the browser type and version number in the Browscap.ini file, it will set every property to "UNKNOWN". Syntax <% Set MyBrow=Server.CreateObject("MSWC.BrowserType") %> ________________________________________ ASP Browser Capabilities Example The example below creates a BrowserType object in an ASP file, and displays some of the capabilities of your browser: Example <% Set MyBrow=Server.CreateObject("MSWC.BrowserType") %>
Client OS<%=MyBrow.platform%>
Web Browser<%=MyBrow.browser%>
Browser version<%=MyBrow.version%>
Frame support?<%=MyBrow.frames%>
Table support?<%=MyBrow.tables%>
Sound support?<%=MyBrow.backgroundsounds%>
Cookies support?<%=MyBrow.cookies%>
VBScript support?<%=MyBrow.vbscript%>
JavaScript support?<%=MyBrow.javascript%>
Output: Client OS WinNT Web Browser IE Browser version 5.0 Frame support? True Table support? True Sound support? True Cookies support? True VBScript support? True JavaScript support? True ________________________________________ The Browscap.ini File The "Browsercap.ini" file is used to declare properties and to set default values for browsers. This section is not a tutorial on how to maintain "Browsercap.ini" files, it only shows you the basics; so you get an idea what a "Browsercap.ini" file is all about. The "Browsercap.ini" file can contain the following: [;comments] [HTTPUserAgentHeader] [parent=browserDefinition] [property1=value1] [propertyN=valueN] [Default Browser Capability Settings] [defaultProperty1=defaultValue1] [defaultPropertyN=defaultValueN] Parameter Description comments Optional. Any line that starts with a semicolon are ignored by the BrowserType object HTTPUserAgentHeader Optional. Specifies the HTTP User Agent header to associate with the browser-property value statements specified in propertyN. Wildcard characters are allowed browserDefinition Optional. Specifies the HTTP User Agent header-string of a browser to use as the parent browser. The current browser's definition will inherit all of the property values declared in the parent browser's definition propertyN Optional. Specifies the browser properties. The following table lists some possible properties: • ActiveXControls - Support ActiveX® controls? • Backgroundsounds - Support background sounds? • Cdf - Support Channel Definition Format for Webcasting? • Tables - Support tables? • Cookies - Support cookies? • Frames - Support frames? • Javaapplets - Support Java applets? • Javascript - Supports JScript? • Vbscript - Supports VBScript? • Browser - Specifies the name of the browser • Beta - Is the browser beta software? • Platform - Specifies the platform that the browser runs on • Version - Specifies the version number of the browser valueN Optional. Specifies the value of propertyN. Can be a string, an integer (prefix with #), or a Boolean value defaultPropertyN Optional. Specifies the name of the browser property to which to assign a default value if none of the defined HTTPUserAgentHeader values match the HTTP User Agent header sent by the browser defaultValueN Optional. Specifies the value of defaultPropertyN. Can be a string, an integer (prefix with #), or a Boolean value A "Browsercap.ini" file might look something like this: ;IE 5.0 [IE 5.0] browser=IE Version=5.0 majorver=#5 minorver=#0 frames=TRUE tables=TRUE cookies=TRUE backgroundsounds=TRUE vbscript=TRUE javascript=TRUE javaapplets=TRUE ActiveXControls=TRUE beta=False ;DEFAULT BROWSER [*] browser=Default frames=FALSE tables=TRUE cookies=FALSE backgroundsounds=FALSE vbscript=FALSE javascript=FALSE ASP Content Linking ComponentThe ASP Content Linking component is used to create a quick and easy navigation system! The Content Linking component returns a Nextlink object that is used to hold a list of Web pages to be navigated. Syntax <% Set nl=Server.CreateObject("MSWC.NextLink") %> ________________________________________ ASP Content Linking Example First we create a text file - "links.txt": asp_intro.asp ASP Intro asp_syntax.asp ASP Syntax asp_variables.asp ASP Variables asp_procedures.asp ASP Procedures The text file above contains the pages to be navigated. The pages must be listed in the same order you want them to be displayed, and it must also contain a description for each file name (use the tab key to separate file name from description). Note: If you want to add a page, or change the order of the pages in the list; you only have to modify the text file! The navigation will automatically be corrected! Then we create an include file, "nlcode.inc". The .inc file creates a NextLink object to navigate between the pages listed in "links.txt". "nlcode.inc": <% dim nl Set nl=Server.CreateObject("MSWC.NextLink") if (nl.GetListIndex("links.txt")>1) then Response.Write("Previous Page") end if Response.Write("Next Page") %> In each of the .asp pages listed in the text file "links.txt", put one line of code: . This line will include the code in "nlcode.inc" on every page listed in "links.txt" and the navigation will work. ________________________________________ ASP Content Linking Component's Methods Method Description Example GetListCount Returns the number of items listed in the Content Linking List file <% dim nl,c Set nl=Server.CreateObject("MSWC.NextLink") c=nl.GetListCount("links.txt") Response.Write("There are ") Response.Write(c) Response.Write(" items in the list") %> Output: There are 4 items in the list GetListIndex Returns the index number of the current item in the Content Linking List file. The index number of the first item is 1. 0 is returned if the current page is not in the Content Linking List file <% dim nl,c Set nl=Server.CreateObject("MSWC.NextLink") c=nl.GetListIndex("links.txt") Response.Write("Item number ") Response.Write(c) %> Output: Item number 3 GetNextDescription Returns the text description of the next item listed in the Content Linking List file. If the current page is not found in the list file it returns the text description of the last page on the list <% dim nl,c Set nl=Server.CreateObject("MSWC.NextLink") c=nl.GetNextDescription("links.txt") Response.Write("Next ") Response.Write("description is: ") Response.Write(c) %> Next description is: ASP Variables GetNextURL Returns the URL of the next item listed in the Content Linking List file. If the current page is not found in the list file it returns the URL of the last page on the list <% dim nl,c Set nl=Server.CreateObject("MSWC.NextLink") c=nl.GetNextURL("links.txt") Response.Write("Next ") Response.Write("URL is: ") Response.Write(c) %> Next URL is: asp_variables.asp GetNthDescription Returns the description of the Nth page listed in the Content Linking List file <% dim nl,c Set nl=Server.CreateObject("MSWC.NextLink") c=nl.GetNthDescription("links.txt",3) Response.Write("Third ") Response.Write("description is: ") Response.Write(c) %> Third description is: ASP Variables GetNthURL Returns the URL of the Nth page listed in the Content Linking List file <% dim nl,c Set nl=Server.CreateObject("MSWC.NextLink") c=nl.GetNthURL("links.txt",3) Response.Write("Third ") Response.Write("URL is: ") Response.Write(c) %> Third URL is: asp_variables.asp GetPreviousDescription Returns the text description of the previous item listed in the Content Linking List file. If the current page is not found in the list file it returns the text description of the first page on the list <% dim nl,c Set nl=Server.CreateObject("MSWC.NextLink") c=nl.GetPreviousDescription("links.txt") Response.Write("Previous ") Response.Write("description is: ") Response.Write(c) %> Previous description is: ASP Variables GetPreviousURL Returns the URL of the previous item listed in the Content Linking List file. If the current page is not found in the list file it returns the URL of the first page on the list <% dim nl,c Set nl=Server.CreateObject("MSWC.NextLink") c=nl.GetPreviousURL("links.txt") Response.Write("Previous ") Response.Write("URL is: ") Response.Write(c) %> Previous URL is: asp_variables.asp ________________________________________ ASP Content Rotator Component (ASP 3.0) The ASP Content Rotator component creates a ContentRotator object that displays a different content string each time a visitor enters or refreshes a page. A text file, called the Content Schedule File, includes the information about the content strings. The content strings can contain HTML tags so you can display any type of content that HTML can represent: text, images, colors, or hyperlinks. Syntax <% Set cr=Server.CreateObject("MSWC.ContentRotator") %> ________________________________________ ASP Content Rotator Example The following example displays a different content each time a visitor views the Web page. First, create a text file named "textads.txt" and place it in a subfolder called "text". "textads.txt": %% #3

This is a great day!!

%% #3 %% #4 Visit W3Schools.com Notice the #number at the beginning of each content string. This number is an optional parameter that indicates the relative weight of the HTML content string. In the text file above, the Content Rotator will display the first and second content string three-tenth of the time, and the third string four-tenths of the time. Then, create an ASP file, and insert the following code: Example <% set cr=server.createobject("MSWC.ContentRotator") response.write(cr.ChooseContent("text/textads.txt")) %> ________________________________________ ASP Content Rotator Component's Methods Method Description Example ChooseContent Gets and displays a content string <% dim cr Set cr=Server.CreateObject("MSWC.ContentRotator") response.write(cr.ChooseContent("text/textads.txt")) %> Output: GetAllContent Retrieves and displays all of the content strings in the text file <% dim cr Set cr=Server.CreateObject("MSWC.ContentRotator") response.write(cr.GetAllContent("text/textads.txt")) %> Output: This is a great day!! Visit W3Schools.com

No comments:

Post a Comment