ASP Tutorial
ASP Tutorial
ASP Tutorial
An ASP file can contain text, HTML tags and scripts. Scripts in an ASP file are executed on the server
What is ASP?
ASP stands for Active Server Pages ASP is a program that runs inside IIS IIS stands for Internet Information Server 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
ASP is a Microsoft Technology 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
ASP Syntax
You can not view ASP code in a browser, you will only see the output from ASP which is plain HTML. This is because the scripts are executed on the server before the result is sent to the browser. In our school, every example displays the hidden ASP code. This will make it easier for you to understand how it works.
Examples
Write text How to write some text into the body of the HTML document with ASP. Text and HTML tags How to format the text with HTML tags.
VBScript
In ASP it is possible to use different scripting languages. The default language in ASP is VBScript, as in this example: <html> <body> <% response.write("Hello World!") %> </body> </html> The example above uses the response.write function to write Hello World! into the body of the HTML document.
JavaScript
To use JavaScript as the default scripting language, insert a language specification at the top of the page:
<%@ language="javascript" %> <html> <body> <% Response.Write("Hello World!") %> </body> </html> Note that - unlike VBScript - JavaScript is case sensitive. You will have to write your ASP code with uppercase letters and lowercase letters when the language requires it.
ASP Variables
A variable declared outside a procedure, can be changed by any script in the ASP file. A variable declared inside a procedure, is created and destroyed every time the procedure is executed.
Examples
Create a variable Variables are used to store information. This example demonstrates how to create a variable, assign a value to it, and insert the variable value into a text. Create an array Arrays are used to store a series of related data items. This example demonstrates how you can make an array that stores names. Looping through headers This example demonstrates how you can loop through the 6 headers in HTML. Time-based greeting using VBScript How to write VBScript syntax in ASP. This example will display a different message to the user depending on the time on the server. Time-based greeting using JavaScript How to write JavaScript syntax in ASP. 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 page in which it is declared. A variable declared inside a procedure, is created and destroyed every time the procedure is executed. No scripts outside that specific procedure can access or change that variable. To make a variable accessible to several ASP pages, declare it either as a session variable or as an application variable.
Session Variables
Session variables store information about one single user, and are available to all pages in one application. Common information stored in session variables are username and userid. To create a session variable, store it in a Session Object.
Application Variables
Application variables are also available to all pages in one application. Application variables are used to hold information about all users in a specific application. To create an application variable, store it in an Application Object.
ASP Procedures
In ASP you can call a JavaScript procedure from a VBScript and vice versa.
Examples
Call a procedure using VBScript How to call a VBScript procedure from ASP. Call a procedure using JavaScript How to call a JavaScript procedure from ASP. Call procedures using VBScript How to call a JavaScript procedure and a VBScript procedure from ASP.
Procedures
ASP code can contain procedures and functions: <html> <head> <% sub vbproc(num1,num2) response.write(num1*num2) end sub %> </head> <body> The result of the calculation is: <%call vbproc(3,4)%> </body> </html> Insert the <%@ language="language" %> line above the <html> tag if you want to write procedures or functions in a scripting language other than the default: <%@ language="javascript" %> <html> <head> <% function jsproc(num1,num2) { Response.Write(num1*num2) } %> </head> <body> The result of the calculation is: <%jsproc(3,4)%> </body> </html>
Calling a Procedure
6
When calling a VBScript or a JavaScript procedure from an ASP page 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 page written in JavaScript, always use parentheses after the procedure name.
Examples
A form that uses the "get" method This example demonstrates how to interact with the user, with the Request.QueryString command. A form that uses the "post" method This example demonstrates how to interact with the user, with the Request.Form command. A form with radio buttons This example demonstrates how to interact with the user, through radio buttons, with the Request.Form command.
User Input
To get information from forms, you can use the Request Object. A simple form example: <form method="get" action="../pg.asp"> First Name: <input type="text" name="fname"><br> Last Name: <input type="text" name="lname"><br> <input type="submit" value="Send"> </form> There are two ways to get form information: The Request.QueryString command and the Request.Form command.
Request.QueryString
The Request.QueryString command collects the values in a form as text. Information sent from a form with the GET method is visible to everybody (in the address field). Remember that the GET method limits the amount of information to send. If a user typed "Bill" and "Gates" in the form example above, the url sent to the server would look like this: http://www.w3schools.com/pg.asp?fname=Bill&lname=Gates The ASP file "pg.asp" contains the following script: <body> Welcome <% response.write(request.querystring("fname")) response.write(" ") response.write(request.querystring("lname")) %> </body>
The example above writes this into the body of a document: Welcome Bill Gates
Request.Form
To collect the values in a form with the POST method, use the Request.Form command. Information sent from a form with the POST method is invisible to others. The POST method has no limits, you can send a large amount of information. If a user typed "Bill" and "Gates" in the form example above, the url sent to the server would look like this: http://www.w3schools.com/pg.asp The ASP file "pg.asp" contains the following script: <body> Welcome <% response.write(request.form("fname")) response.write(" ") response.write(request.form("lname")) %> </body> The example above writes this into the body of a document: Welcome Bill Gates
Form Validation
The form input should be validated on the browser, by client side scripts. Browser validation has a faster response time, and reduces the load on the server. You should consider using server validation if the input from a form is inserted into a database. A good way to validate the form on a server is to post the form into 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.
ASP Cookies
A cookie is used to identify a user.
Examples
Welcome cookie How to create a Welcome cookie.
What is a Cookie?
A cookie is a small file that the server embeds in a user's browser. The cookie is used to identify the user. Each time the same browser asks for a page, it sends the cookie too. ASP scripts can both get and set the values of cookies.
Set Cookies
To set a cookie value, use the "Response.Cookies" command. If the cookie does not exist, it will be created, and take the value that is specified. In the example below, we send a cookie named "userid" with a value of "25" to the browser. This cookie only lasts during the current user session. This command must appear before the <html> tag: <% Response.Cookies("userid")=25 %> If you want to identify a user after the user has stopped and restarted the browser, you must use the "Expires" attribute for "Response.Cookies" and set the date to some date in the future: <% Response.Cookies("userid")=25 Response.Cookies("userid").Expires="May 10, 2002" %>
Get Cookies
To get a cookie value, use the "Request.Cookies" command. In the example below, we want to retrieve the value of the "userid" cookie. We retrieve 25: <% Response.Write(Request.Cookies("userid")) %>
Each cookie stored on the browser contains path information. When the browser requests a file stored in the same location as the path specified in the cookie, the browser sends the cookie to the server. By default the path of the cookie is set to the name of the application that contains the file that created the cookie. If a file, in an application called "userapp", creates a cookie, then each time a user's browser gets any file in that application, the browser will send the cookie. To specify a path for a cookie, you can use the "Path" attribute for "Response.Cookies". The example below assigns the path Sales/Customer/Profiles/ to a cookie called Zip: <% Response.Cookies("Zip")="12" Response.Cookies("Zip").Expires="January 1, 2001" Response.Cookies("Zip").Path="/Sales/Customer/Profiles/" %> Note: Make sure all addresses to .asp files have the same case to ensure that the browser sends stored cookies. The example below sets the cookie path so that the user's browser will send a cookie whenever the browser requests a file from your server, regardless of application or path: <% Response.Cookies("Zip").Path="/" %>
No Cookie Support
Not all browsers support cookies. If your application is in contact with browsers that do not support cookies, you can not use cookies. You will then have to use other methods to pass information from page to page in your application. There are two ways to do this:
11
Session object
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the 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 client and it contains information that identifies the user. This interface is called the Session object. The Session object is used to store information about, or change settings for a user session. Variables stored in the Session object holds information about one single user, and are available to all pages in one application. Common information stored in session variables are name, id, and preferences. The server creates a new Session object for each new user, and destroys the Session object when the session expires.
A new user requests an .asp file, and the Global.asa file includes a Session_OnStart procedure A user stores a value in a Session variable A user requests an .asp file, and the Global.asa file uses the <object> tag to instantiate an object with session scope
12
Note: The main problem with sessions are 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 to keep the sessions alive. Waiting too long uses up resources on the server. But if the session is deleted too fast you risk that the user is coming back and the server has deleted all the information, so the user has to start all over again. Finding the right timeout interval can be difficult. Tip: If you are using session variables, store SMALL amounts of data in them.
13
14
Application Object
An application on the Web is a group of asp files. The files work together to perform some purpose. The Application object in ASP is used to tie these files together. The Application object is used to store variables and access variables from any page, just like the Session object. The difference is that all users share ONE Application object, while with Sessions there is one Session object for each user. The Application object should hold information that will be used by many pages in the application (like database connection information). This means that you can access the information from any page. It also means that you can change the information in one place and the new information will automatically be reflected on all pages.
15
%> If you don't know how many items are stored in a "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) & "<br>") Next %>
16
17
or <!--#include file ="somefilename"--> "Somefilename" is the name of the file you want to include.
18
<% For i = 1 To n <!--#include file="count.inc"--> Next %> But this script will work: <% For i = 1 to n %> <!--#include file="count.inc" --> <% Next %>
19
Restrictions
Restrictions on what you can include in the Global.asa file:
20
You can not display text that is written in the Global.asa file. This file can't display information You can not use the #include directive in Global.asa You can only use Server and Application objects in the Application_OnStart and Application_OnEnd subroutines. In the Session_OnEnd subroutine, you can use Server, Application, and Session objects. In the Session_OnStart subroutine you can use any built-in object
Global.asa Example
In this example we will create a Global.asa file that counts the number of current visitors.
21
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: <script language="vbscript" runat="server"> Sub Application_OnStart Application("visitors")=0 End Sub Sub Session_OnStart Application.Lock Application("visitors")=Application("visitors")+1 Application.UnLock End Sub Sub Session_OnEnd Application.Lock Application("visitors")=Application("visitors")-1 Application.UnLock End Sub </script> To display the number of current visitors in an ASP file: <html> <head> </head> <body> <p> There are <%=Application("visitors")%> online now! </p> </body> </html>
22
ASP Objects
ASP Built-in Objects
Object Application Response Request Server Session Description This object is used to share information among all users of a given application This object is used to send output to the user This object is used to get information from the user This object is used to access properties and methods on the server This object is used to store information about or change settings for a user's session
23
Browser Capabilities Content Rotator Content Linking Counter Database Access File Access MyInfo Page Counter Permission Checker
Tools Status
24
Examples
Write text How to write some text into the body of the HTML document with ASP. Text and HTML tags How to format the text with HTML tags. Redirect the user to another URL This example demonstrates the Redirect method. This method redirects the user to another URL. Random link This example demonstrates a link, when you click on the link it will take you to W3Schools.com OR to W3Scripts.com. There is a 50% chance for each of them. Controlling the buffer This example demonstrates the Buffer property. When this property is set to true, the server will hold back the response until all of the scripts have been processed, or we can control manually when to send the output back to the browser. This example also demonstrates the use of the Flush method. When Response.Flush is called, ASP sends the buffered output to the client immediately. This happens whether the output is buffered or not. Clear the buffer This example demonstrates the Clear method. When Response.Clear is called, ASP empties the buffered output immediately. End a script in the middle of processing This example demonstrates the End method. This method stops processing the script, and returns the current result. The text or code that comes after the Response.End command will not be executed. Set how many minutes a page will be cached in a browser before it expires This example demonstrates the Expires property. This property sets how long a page will be cached in a browser before it expires. If the user returns to the same page before the specified number of minutes have elapsed, the cached version is displayed. If you set minutes to 0, the page will never be cached on a browser. Set a date/time when a page cached in a browser will expire This example demonstrates the ExpiresAbsolute property. This property sets a date/time when a page cached in a browser will expire. If the user returns to the same page before the specified date/time, the cached version is displayed. Check if the user is still connected This example demonstrates the IsClientConnected property. This property checks if the user is still connected to the server. Set the type of content This example demonstrates the ContentType property. This property sets the content type. Some common content types are "text/html", "image/gif", "image/jpeg", "text/plain". Set the name of character set This example demonstrates the Charset property. This property sets the name of the character set that is used.
Response Object
The Response Object is used to send output to the user from the server.
Syntax
25
Collections
Collection Cookies(name) Description Sets a cookie value. If the cookie does not exist, it will be created, and take the value that is specified
Properties
Property Buffer Description Whether to buffer the output or not. When the output is buffered, the server will hold back the response until all of the server scripts have been processed, or until the script calls the Flush or End method. If this property is set, it should be before the <html> tag in the .asp file Sets whether proxy servers can cache the output or not. When this property is set to Public, the output can be cached by a proxy server Sets the name of the character set (like "ISO8859-1") to the content type header Sets the HTTP content type. Some common content types are "text/html", "image/gif", "image/jpeg", "text/plain". The default is "text/html" Sets how long a page will be cached on a browser before it expires Sets a date and time when a page cached on a browser will expire Check to see if the client is still connected to the server Adds a value to the pics label response header. Specifies the value of the status line. You can change the status line with this property
CacheControl
Charset(charset_name) ContentType
Methods
Method AddHeader(name, value) AppendToLog string BinaryWrite(data_to_write) Clear Description Adds an HTML header with a specified value Adds a string to the end of the server log entry Writes the given information without any character-set conversion. Clears the buffered output. Use this method to handle errors. If the Response.Buffer is not set to true, this method will cause a
26
run-time error End Flush Redirect(url) Write(data_to_write) Stops processing the script, and return the current result Sends buffered output immediately. If the Response.Buffer is not set to true, this method will cause a run-time error Redirects the user to another url Writes a text to the user
27
Other Examples
Server variables This example demonstrates how to find out the visitors (yours) browser type, IP address, and more with the ServerVariables collection. Welcome cookie This example demonstrates how to create a Welcome Cookie with the Cookies Collection. Total bytes This example demonstrates how to use the TotalBytes property to find out the total number of bytes the user sent in the Request object.
28
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 the user.
Syntax
Request.collection Request.property Request.method
Collection
Collection ClientCertificate Cookies(name) Form(element_name) QueryString(variable_name) ServerVariables(server_variable) Description Holds field values stored in the client certificate Holds cookie values Holds form (input) values. The form must use the post method Holds variable values in the query string Holds server variable values
Properties
Property TotalBytes Description Holds the total number of bytes the client is sending in the body of the request
Method
Method BinaryRead Description Fetches the data that is sent to the server from the client as part of a post request
29
Application Object
The Application object is used to store variables and access variables from any page. All users share ONE Application object. The Application object should hold information that will be used by many pages in the application (like database connection information). This means that you can access the information from any page. It also means that you can change the information in one place and the new information will automatically be reflected on all pages.
Syntax
Application.collection Application.method
Collections
Collection Contents StaticObjects Description Holds the items added to the application with script commands Holds the objects added to the application with the <object> tag
Methods
Method Contents.Remove Contents.RemoveAll Lock Unlock Description Deletes an item from a collection Deletes all items from a collection Prevents other users from changing the application object properties Allows other users to change the application object properties
Events
Event OnEnd Description What to do when all user sessions are over, and the Application quits. This event will execute a script in the Global.asa file, if the script exist What to do before the Application Object is first referenced. This
OnStart
30
event will execute a script in the Global.asa file, if the script exist
31
Examples
Return session id number for a user This example demonstrates the "SessionID" property. This property returns the session id number for each user (it is a read-only property). The session id number is generated by the server. Get a session's timeout This example demonstrates the "Timeout" property. This example retrieves the timeout (in minutes) for the session. The default value for the "Timeout" property is 20 minutes.
Session Object
The Session object is used to store information about, or change settings for a user session. Variables stored in the Session object holds information about one single user, and are available to all pages in one application. Common information stored in session variables are name, id, and preferences. The server creates a new Session object for each new user, and destroys the Session object when the session expires.
Syntax
Session.collection Session.property Session.method
Collections
Collection Contents StaticObjects Description Holds the items added to the session with script commands Holds the objects added to the session with the <object> tag, and a given session
Properties
Property CodePage LCID SessionID Timeout Description Sets the code page that will be used to display dynamic content Sets the locale identifier that will be used to display dynamic content Returns the session id Sets the timeout for the session
32
Method
Method Abandon Contents.Remove(Item or Index) Contents.RemoveAll() Description Kills all objects in a session object Deletes an item from the Contents collection Deletes all items from the Contents collection
Events
Event OnEnd OnStart Description What to do when a session is over. This event will execute a script in the Global.asa file, if the script exists What to do before the start of any new session. This event will execute a script in the Global.asa file, if the script exists
33
Examples
When was a file last modified? Checks when this file was last modified. Open a textfile for reading This example opens the file "Textfile.txt" for reading. Home made hit counter This example reads a number from a file, adds 1 to the number, and writes the number back to the file.
Server Object
The Server Object is used to access properties and methods on the server.
Syntax
Server.property Server.method
Properties
Property ScriptTimeout Description Sets how long a script can run before it is terminated
Method
Method CreateObject(type_of_object) Execute(path) Description Creates an instance of an object Executes an .asp file from inside another .asp file. After executing the called .asp file, the procedural control is returned to the the original .asp file Returns an ASPError object that will describe the error that occurred Applies HTML encoding to a string Maps a relative or virtual path to a physical path Sends all of the state information to another .asp file for processing. After the transfer, procedural control is not returned to the original .asp page
34
URLEncode(string)
35
Examples
Does a specified file exist? This example demonstrates how to first create a FileSystemObject Object, and then use the FileExists method to check if the file exists. Does a specified folder exist? This example demonstrates how to use the FolderExists method to check if a folder exists. Does a specified drive exist? This example demonstrates how to use the DriveExists method to check if a drive exists. Get the name of a specified drive This example demonstrates how to use the GetDriveName method to get the name of a specified drive. Get the name of the parent folder of a specified path This example demonstrates how to use the GetParentFolderName method to get the name of the parent folder of a specified path. Get the file extension This example demonstrates how to use the GetExtensionName method to get the file extension of the last component in a specified path. Get the base name of a file or folder This example demonstrates how to use the GetBaseName method to return the base name of the file or folder, in a specified path.
Methods
Method BuildPath CopyFile CopyFolder CreateFolder CreateTextFile DeleteFile DeleteFolder DriveExists FileExists Description Appends a name to an existing path Copies a file Copies a folder Creates a folder Creates a text file Deletes a file Deletes a folder Checks if a drive exists Checks if a file exists
36
FolderExists GetAbsolutePathName GetBaseName GetDrive GetDriveName GetExtensionName GetFile GetFileName GetFolder GetParentFolderName GetSpecialFolder GetTempName MoveFile MoveFolder OpenTextFile
Checks if a folder exists Returns the complete path Returns the base name of the file or folder Returns a Drive Object corresponding to the drive in a specified path Returns the name of the drive Returns the file extension Returns a File Object corresponding to the file in a path Returns the last file name or folder that is not part of the drive specification Returns a Folder Object corresponding to the folder in a path Returns the name of the parent folder Returns the specified folder Returns a randomly generated temporary file or folder name Moves a file Moves a folder Opens a file and returns a TextStream object to access the file
Properties
Property Drives Description Returns a collection of all Drive Objects available on the machine
37
Examples
Read textfile This example demonstrates how to use the OpenTextFile method of the FileSystemObject to create a TextStream Object. The ReadAll method of the TextStream Object reads from the opened text file. Read only a part of a textfile This example demonstrates how to only read a part of a TextStream file. Read one line of a textfile This example demonstrates how to read one line from a TextStream file. Read all lines from a textfile This example demonstrates how to read all the lines from a TextStream file. Skip a part of a textfile This example demonstrates how to skip a specified number of characters when reading the TextStream file. Skip a line of a textfile This example demonstrates how to skip a line when reading the TextStream file. Return line-number This example demonstrates how to return the current line number in a TextStream file. Get column number This example demonstrates how to get the column number of the current character in a file.
Methods
Method Close Read ReadAll ReadLine Skip SkipLine Write WriteLine WriteBlankLines Description Closes an open text file Reads a number of characters from a file and returns the result Reads an entire file and returns the result Reads a line from a file and returns the result Skips a number of characters when reading a file Skips the next line when reading a file Writes some text to a file Writes some text and a new-line character to a file Writes new-line characters to a file
Properties
38
Description Returns true if the file pointer is at the end of a line in a file Returns true if the file pointer is at the end of a file Returns the column number of the current character in a file Returns the current line number in a file
39
Examples
Get the available space of a specified drive This example demonstrates how to first create a FileSystem Object, and then use the AvailableSpace property to get the available space of a specified drive. Get the free space of a specified drive This example demonstrates how to use the FreeSpace property to get the free space of a specified drive. Get the total size of a specified drive This example demonstrates how to use the TotalSize property to get the total size of a specified drive. Get the drive letter of a specified drive This example demonstrates how to use the DriveLetter property to get the drive letter of a specified drive. Get the drive type of a specified drive This example demonstrates how to use the DriveType property to get the drive type of a specified drive. Get the file system of a specified drive This example demonstrates how to use the FileSystem property to get the file system of a specified drive. Is the drive ready? This example demonstrates how to use the IsReady property to check whether a specified drive is ready. Get the path of a specified drive This example demonstrates how to use the Path property to get the path of a specified drive. Get the root folder of a specified drive This example demonstrates how to use the RootFolder property to get the root folder of a specified drive. Get the serialnumber of a specified drive This example demonstrates how to use the Serialnumber property to get the serialnumber of a specified drive.
Properties
Property AvailableSpace DriveLetter DriveType Description Returns the amount of space available Returns the drive letter Returns the type of a specified drive. 0 = unknown 1 = removable 2 = fixed
40
3 = network 4 = CD-ROM 5 = RAM disk FileSystem FreeSpace IsReady Path RootFolder SerialNumber ShareName TotalSize VolumeName Returns the type of the file system Returns the amount of free space Returns true if a specified drive is ready Returns the path Returns a Folder Object representing a root folder Returns the serial number of a specified drive Returns the network share name Returns the total space Sets or returns the volume name
41
Examples
When was the file created? This example demonstrates how to first create a FileSystem Object, and then use the DateCreated property of the File Object to get the date and time a specified file was created. When was the file last modified? This example demonstrates how to use the DateLastModified property to get the date and time a specified file was last modified. When was the file last accessed? This example demonstrates how to use the DateLastAccessed property to get the date and time a specified file was last accessed. Return the attributes of a specified file This example demonstrates how to use the Attributes property to return the attributes of a specified file.
Methods
Method Copy Delete Move OpenAsTextStream Description Copies a file Deletes a file Moves a file Opens a text file and returns a TextStream object to access the file
Properties
Property Attributes DateCreated DateLastAccessed DateLastModified Drive Name ParentFolder Description Sets or returns the attributes of a file Returns the date and time when a file was created Returns the date and time when a file was last accessed Returns the date and time when a file was last modified Returns the drive letter where a specified file resides Sets or returns the name of a file Returns the parent folder of a file
42
Returns the path for a file Returns the short name of the file (the earlier 8.3 naming convention) Returns the short path (the earlier 8.3 file naming convention) Returns the size of the file Returns the type of file
43
Methods
Method Copy Delete Move CreateTextFile Description Copies a folder Deletes a folder Moves a folder Creates a text file and returns a TextStream Object to access the file
Properties
Property Attributes DateCreated DateLastAccessed DateLastModified Drive Files IsRootFolder Name ParentFolder Path ShortName ShortPath Size SubFolders Type Description Sets or returns the attributes of a folder Returns the date and time when the folder was created Returns the date and time when the folder was last accessed Returns the date and time when the folder was last modified Returns the drive letter where a specified folder resides Returns a collection of all files in a folder Returns true if a folder is the root folder Sets or returns the name of a folder Returns the parent folder of a folder Returns the path for a folder Returns the short name of a folder (the earlier 8.3 naming convention) Returns the short path (the earlier 8.3 file naming convention) Returns the size of a folder Returns a collection of all sub folders in a folder Returns the type of a folder
44
Examples
Does a specified key exist? This example demonstrates how to first create a Dictionary Object, and then use the Exists method to check if a specified key exists. Return an array of all items This example demonstrates how to use the Items method to return an array of all the items. Return an array of all keys This example demonstrates how to use the Keys method to return an array of all the keys. Return the value of an item This example demonstrates how to use the Item property to return the value of an item. Set a key This example demonstrates how to use the Key property to set a key in a Dictionary object. Return the number of key/item pairs This example demonstrates how to use the Count property to return the number of key/item pairs.
Methods
Method Add Exists Items Keys Remove RemoveAll Description Adds a key and item pair to a Dictionary Object Returns true if a specified key exists, false if not Returns an array of all items in a Dictionary object Returns an array of all keys in a Dictionary object Removes a single key/item pair Removes all key/item pairs
Properties
Property CompareMode Count Description Sets or returns the string comparison mode for the keys. This property is unavailable in JScript Returns the number of keys/items in a Dictionary object
45
Item Key
46
Example
<html> <body> <% 'The following line creates an error dim i for i=1 to 1 next 'Call the GetLastError() to trap the error objerr=Server.GetLastError() 'The variable objerr now contains the ASPError object %> <p>ASP Code: <%Response.Write(objerr.ASPCode)%>.</p> <p>Number: <%Response.Write(objerr.Number)%>.</p> <p>Source: <%Response.Write(objerr.Source)%>.</p> <p>FileName: <%Response.Write(objerr.FileName)%>.</p> <p>LineNumber: <%Response.Write(objerr.LineNumber)%>.</p> </body> </html>
Properties
Property ASPCode ASPDescription Category Column Description File Description Returns an error code that was generated by IIS Returns a detailed description of the error (if the error is ASP-related) Returns the source of the error (was the error generated by ASP? By the scripting language? By an object?) Returns the column position within the file that generated the error Returns a short description of the error Returns the name of the file that was being processed when the error occurred
47
Returns the line number where the error was detected Returns the standard COM error code for the error Returns the actual source code of the line where the error occured
48
ASP AdRotator
Examples
Simple AdRotator Example This example shows how to use the AdRotator component to display a different advertisement image, each time a user visits or refreshes the page. AdRotator - The Images are Hyperlinks This example shows how to use the AdRotator component to display a different advertisement image, each time a user visits or refreshes the page. In addition, the images are hyperlinks.
AdRotator
The 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") %>
Example
We have a page called "banners.asp", it looks like this: <html> <body> <% set adrotator=Server.CreateObject("MSWC.AdRotator") response.write(adrotator.GetAdvertisement("textfile.txt")) %> </body> </html> The "textfile.txt" looks like this: * w3schools.gif http://www.w3schools.com/ Visit W3Schools 80 w3scripts.gif http://www.w3scripts.com/ Visit W3Scripts 20
49
The lines below the asterisk specify the image to be displayed, the hyperlink address, the alternate text (for the image), and the display rate in percent of the hits. In the text file above, the W3Schools image will be displayed for 80 % of the hits, while the W3Scripts image will be displayed for only 20 % of the hits. Note: In the text file above the hyperlinks will not work! To get the hyperlinks up and running, we will have to change the text file a bit: REDIRECT banners.asp * w3schools.gif http://www.w3schools.com/ Visit W3Schools 80 w3scripts.gif http://www.w3scripts.com/ Visit W3 Scripts 20 The redirection page (which is, in this example, the same page as we started with) receives a querystring containing a variable named URL that contains the URL to redirect to. To get the images to act as hyperlinks we also have to change the "banners.asp" file: <% url=Request.QueryString("url") If url<>"" then Response.Redirect(url) %> <html> <body> <% set adrotator=Server.CreateObject("MSWC.AdRotator") response.write(adrotator.GetAdvertisement("textfile.txt")) %> </body> </html>
Methods
Method GetAdvertisement(text_file) Description Gets information about the next advertisement in the text file, and formats it as HTML
Properties
Property Border Clickable TargetFrame Description Sets the size of the border around the advertisement Specifies whether the advertisement is a hyperlink Name of the frame to display the advertisement
50
Browser Capabilities
The Browser Capabilities component creates a BrowserType object that determines the type, capabilities and version of each browser that visits your site. An HTTP User Agent Header is sent to the server when a browser connects to it. This header identifies the browser and the browser version. The BrowserType object compares the header to entries in the Browscap.ini file. If it finds a match, the BrowserType object assumes the properties of the browser listing that matched the User Agent header. If the object does not find a match for the header in the Browscap.ini file, it sets every property to "UNKNOWN". The file "Browscap.ini" is a text file on the server that maps browser capabilities to the HTTP User Agent header.
Syntax
<% Set MyBrow = Server.CreateObject("MSWC.BrowserType") %>
51
Content Rotator
The Content Rotator component creates a ContentRotator object that displays a different HTML content string each time a user enters or refreshes a page. A text file includes information about the content string. The content strings can contain HTML tags.
Syntax
<% Set cr = Server.CreateObject( "MSWC.ContentRotator" ) response.write(cr.ChooseContent("sometextfile.txt") %>
Methods
Method Description
ChooseContent(text_file) Gets and displays a content string GetAllContent(text_file) Retrieves and displays
52
Content Linking
The Content Linking component creates a Nextlink object that holds a list of linked Web pages. This component generate and update tables of contents and navigational links. It is ideal for online newspapers and forum message listings. A text file, stored on the server, contains the list of the linked pages.
Syntax
<% Set nextlink = Server.CreateObject( "MSWC.NextLink" ) %>
Methods
Method GetListCount(text_file) GetListIndex(text_file) GetNextDescription(text_file) GetNextURL(text_file) GetNthDescription(text_file, number) GetNthURL(text_file, number) GetPreviousDescription(text_file) GetPreviousURL(text_file) Description Counts the number of items linked in the text file Gets the index of the current page in the text file Gets the description of the next page listed in the text file Gets the URL of the next page listed in the text file Gets the description of the Nth page listed in the text file Gets the URL of the Nth page listed in the text file Gets the description line of the previous page listed in the text file Gets the URL of the previous pages listed in the text file
53