ASP Tutorial
ASP Tutorial
An ASP file can contain text, HTML tags and scripts. Scripts in an ASP file are executed on the server.
If you want to study these subjects first, find the tutorials on our Home page.
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
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"
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
Anup Kumar
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
Note: Because ASP scripts are executed on the server, the browser that displays the ASP file does not need to support scripting at all!
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
Windows 7 (all editions) come with IIS 7.5 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
Anup Kumar
After you have installed IIS, make sure you install all patches for bugs and security problems. (Run Windows Update).
After you have installed IIS, make sure you install all patches for bugs and security problems. (Run Windows Update).
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.
Anup Kumar
2. If the wizard is not displayed, go to Administrative Tools, and select Manage Your Server 3. In the wizard, click Add or Remove a Role, click Next 4. Select Custom Configuration, click Next 5. Select Application Server role, click Next 6. Select Enable ASP.NET, click Next 7. Now, the wizard may ask for the Server 2003 CD. Insert the CD and let it run until it is finished, then click the Finish button 8. The wizard should now show the Application Server role installed 9. Click on Manage This Application Server to bring up the Application Server Management Console (MMC) 10. Expand the Internet Information Services (IIS) Manager, then expand your server, and then the Web Sites folder 11. You should see the Default Web Site, and it should not say (Stopped) 12. IIS is running! 13. In the Internet Information Services (IIS) Manager click on the Web Service Extensions folder 14. Here you will see that Active Server Pages are Prohibited (this is the default configuration of IIS 6) 15. Highlight Active Server Pages and click the Allow button
Example
<!DOCTYPE html> <html> <body> <% response.write("Hello World!") %>
Anup Kumar
</body> </html> There is also a shorthand method for the response.write command. The following example also sends the text "Hello World" to the browser:
Example
<!DOCTYPE html> <html> <body> <% ="Hello World!" %> </body> </html>
Anup Kumar
Note: 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
Declare a variable Variables are used to store information. This 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. This 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.
Anup Kumar
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
<!DOCTYPE html> <html> <head> <% sub vbproc(num1,num2) response.write(num1*num2) end sub %> </head> <body> <p>Result: <%call vbproc(3,4)%></p> </body> </html> Show example Insert the <%@ language="language" %> line above the <html> tag to write the procedure/function in another scripting language:
Example
<%@ language="javascript" %> <!DOCTYPE html> <html> <head> <% function jsproc(num1,num2) { Response.Write(num1*num2) } %> </head>
Anup Kumar
Anup Kumar
Anup Kumar
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 Cookies 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 CacheControl Charset ContentType Expires ExpiresAbsolute IsClientConnected Pics Status Description Specifies whether to buffer the page output or not Sets whether a proxy server can cache the output generated by ASP or not Appends the name of a character-set to the content-type header in the Response object Sets the HTTP content type for the Response object Sets how long (in minutes) 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 Indicates if the client has disconnected from the server Appends a value to the PICS label response header Specifies the value of the status line returned by the server
Methods
Method AddHeader AppendToLog BinaryWrite Clear End Flush Redirect Write Description Adds a new HTTP header and a value to the HTTP response Adds a string to the end of the server log entry Writes data directly to the output without any character conversion Clears any buffered HTML output Stops processing a script, and returns the current result Sends buffered HTML output immediately Redirects the user to a different URL Writes a specified string to the output
10
Anup Kumar
11
Anup Kumar
Other Examples
Get the server variables How to get the visitor's browser type, IP address, and more. Create a welcome cookie How to create a Welcome Cookie. Find the total number of bytes the user sent How to find the total number of bytes the user sent in the Request object.
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 ClientCertificate Cookies Form QueryString ServerVariables Description Contains all the field values stored in the client certificate Contains all the cookie values sent in a HTTP request Contains all the form (input) values from a form that uses the post method Contains all the variable values in a HTTP query string Contains all the server variable values
Properties
Property TotalBytes Description Returns the total number of bytes the client sent in the body of the request
Methods
Method BinaryRead Description Retrieves the data sent to the server from the client as part of a post request and stores it in a safe array
12
Anup Kumar
A form with radio buttons How to interact with the user, through radio buttons, with the Request.Form command.
User Input
The Request object can be used to retrieve user information from forms.
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: <body> Welcome <% response.write(request.querystring("fname")) response.write(" " & request.querystring("lname")) %> </body> The browser will display the following in the body of the document: Welcome Bill Gates
13
Anup Kumar
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: <body> Welcome <% response.write(request.form("fname")) response.write(" " & request.form("lname")) %> </body> The browser will display the following in the body of the document: Welcome Bill Gates
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.
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.
14
Anup Kumar
15
Anup Kumar
Response.Cookies("user")("age")="25" %>
16
Anup Kumar
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: <form method="post" action="welcome.asp"> First Name: <input type="text" name="fname" value=""> Last Name: <input type="text" name="lname" value=""> <input type="submit" value="Submit"> </form> Retrieve the values in the "welcome.asp" file like this: <% fname=Request.form("fname") lname=Request.form("lname") response.write("<p>Hello " & fname & " " & lname & "!</p>") response.write("<p>Welcome to my Web site!</p>") %>
A Session object stores information about, or change settings for a user session.
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 <object> tag to instantiate an object with session scope
18
Anup Kumar
<% 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!
19
Anup Kumar
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() %>
Collections
Collection Contents StaticObjects Description Contains all the items appended to the session through a script command Contains all the objects appended to the session with the
20
Anup Kumar
Properties
Property CodePage LCID SessionID Timeout Description Specifies the character set that will be used when displaying dynamic content 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 Returns a unique id for each user. The unique id is generated by the server Sets or returns the timeout period (in minutes) for the Session object in this application
Methods
Method Abandon Contents.Remove Contents.RemoveAll() Description Destroys a user session Deletes an item from the Contents collection Deletes all items from the Contents collection
Events
Event Description Session_OnEnd Occurs when a session ends Session_OnStart Occurs when a session starts
21
Anup Kumar
<% dim i dim j j=Session.Contents.Count Response.Write("Session variables: " & j) For i=1 to j Response.Write(Session.Contents(i) & "<br>") Next %> Result: Session variables: 2 Donald Duck 50
Application Object
An application on the Web may consist 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).
22
Anup Kumar
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.
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).
23
Anup Kumar
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 Contents StaticObjects Description Contains all the items appended to the application through a script command Contains all the objects appended to the application with the HTML <object> tag
Methods
Method Contents.Remove Contents.RemoveAll() Lock Unlock Description Deletes an item from the Contents collection Deletes all items from the Contents collection Prevents other users from modifying the variables in the Application object Enables other users to modify the variables in the Application object (after it has been locked using the Lock method)
Events
Event Application_OnEnd Application_OnStart Description Occurs when all user sessions are over, and the application ends Occurs before the first new session is created (when the Application object is first referenced)
24
Anup Kumar
Application events
25
Anup Kumar
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 usersession 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: <script language="vbscript" runat="server"> sub Application_OnStart 'some code end sub sub Application_OnEnd 'some code end sub sub Session_OnStart 'some code end sub sub Session_OnEnd 'some code
26
Anup Kumar
end sub </script> Note: Because we cannot use the ASP script delimiters (<% and %>) to insert scripts in the Global.asa file, we put subroutines inside an HTML <script> element.
<object> Declarations
It is possible to create objects with session or application scope in Global.asa by using the <object> tag. Note: The <object> tag should be outside the <script> tag!
Syntax
<object runat="server" scope="scope" id="id" {progid="progID"|classid="classID"}> .... </object> Parameter scope id ProgID Description Sets the scope of the object (either Session or Application) Specifies a unique id for the object An id associated with a class id. The format for ProgID is [Vendor.]Component[.Version] Either ProgID or ClassID must be specified. Specifies a unique id for a COM class object. Either ProgID or ClassID must be specified.
ClassID
Examples
The first example creates an object of session scope named "MyAd" by using the ProgID parameter: <object runat="server" scope="session" id="MyAd" progid="MSWC.AdRotator"> </object> The second example creates an object of application scope named "MyConnection" by using the ClassID parameter: <object runat="server" scope="application" id="MyConnection" classid="Clsid:8AD3067A-B3FC-11CF-A560-00A0C9081C21"> </object> The objects declared in the Global.asa file can be used by any script in the application:
27
Anup Kumar
GLOBAL.ASA: <object runat="server" scope="session" id="MyAd" progid="MSWC.AdRotator"> </object> You could reference the object "MyAd" from any page in the ASP application: SOME .ASP FILE: <%=MyAd.GetAdvertisement("/banners/adrot.txt")%>
TypeLibrary Declarations
A TypeLibrary is a container for the contents of a DLL file corresponding to a COM object. By including a call to the TypeLibrary in the Global.asa file, the constants of the COM object can be accessed, and errors can be better reported by the ASP code. If your Web application relies on COM objects that have declared data types in type libraries, you can declare the type libraries in Global.asa.
Syntax
<!--METADATA TYPE="TypeLib" file="filename" uuid="id" version="number" lcid="localeid" --> Parameter file uuid version lcid Description Specifies an absolute path to a type library. Either the file parameter or the uuid parameter is required Specifies a unique identifier for the type library. Either the file parameter or the uuid parameter is required Optional. Used for selecting version. If the requested version is not found, then the most recent version is used Optional. The locale identifier to be used for the type library
Error Values
The server can return one of the following error messages: Error Code ASP 0222 ASP 0223 ASP 0224 ASP 0225 Description Invalid type library specification Type library not found Type library cannot be loaded Type library cannot be wrapped
28
Anup Kumar
Note: METADATA tags can appear anywhere in the Global.asa file (both inside and outside <script> tags). However, it is recommended that METADATA tags appear near the top of the Global.asa file.
Restrictions
Restrictions on what you can include in the Global.asa file:
You cannot display text written in the Global.asa file. This file can't display information 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
29
Anup Kumar
<script language="vbscript" runat="server"> sub Application_OnStart getcustomers end sub sub getcustomers set conn=Server.CreateObject("ADODB.Connection") conn.Provider="Microsoft.Jet.OLEDB.4.0" conn.Open "c:/webdata/northwind.mdb" set rs=conn.execute("select name from customers") Application("customers")=rs.GetRows rs.Close conn.Close end sub </script>
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: <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
30
Anup Kumar
</script> To display the number of current visitors in an ASP file: <!DOCTYPE html> <html> <head> </head> <body> <p>There are <%response.write(Application("visitors"))%> online now!</p> </body> </html>
31
Anup Kumar
Properties
Property ScriptTimeout Description Sets or returns the maximum number of seconds a script can run before it is terminated
Methods
Method CreateObject Execute GetLastError() HTMLEncode MapPath Transfer URLEncode Description Creates an instance of an object Executes an ASP file from inside another ASP file Returns an ASPError object that describes the error condition that occurred Applies HTML encoding to a specified string Maps a specified path to a physical path Sends (transfers) all the information created in one ASP file to a second ASP file Applies URL encoding rules to a specified string
32
Anup Kumar
33
Anup Kumar
34
Anup Kumar
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" %> <!--#include file="<%fname%>"--> You cannot open or close a script delimiter in an INC file. The following script will NOT work: <% 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 %>
35
Anup Kumar
36
Anup Kumar
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 %>
37
Anup Kumar
38
Anup Kumar
ASP Examples
Basic Write text using ASP Format text with HTML tags Variables Create a variable Create an array Looping through HTML headers Time-based greeting using VBScript Time-based greeting using JavaScript Date/Time Functions (VBScript) Date and time Get the name of a day Get the name of a month Get todays' day and month Countdown to year 3000 Calculate the day which is n days from today Format date and time Is this a date? Some Other Functions (VBScript) Uppercase or lowercase a string Trim a string How to reverse a string? How to round a number? A random number Return a specified number of characters from left/right of a string Replace some characters in a string Return a specified number of characters from a string Procedures Call a procedure using VBScript in ASP Call a procedure using JavaScript in ASP Call a JavaScript procedure and a VBScript procedure using VBScript in ASP Forms Interact with a user in a form that uses the "get" method Interact with a user in a form that uses the "post" method Interact with a user in a form with radio buttons
39
Anup Kumar
Cookies Create a welcome cookie Response Object Write text using ASP Format text with HTML tags Redirect the user to another URL Random links Controlling the buffer Clear the buffer End a script in the middle of processing Set how many minutes a page will be cached in a browser before it expires Set a date/time when a page cached in a browser will expire Check if the user is still connected Set the type of content Set the name of character set Request Object Send extra information within a link A QueryString collection in its simplest use How to use information from forms More information from a form A form collection in its simplest use How to use information from forms More information from a form A form with radio buttons A form with checkboxes How to find the visitors' browser type, IP address and more List all servervariables you can ask for Welcome cookie Total number of bytes the user sent Session Object Return session id number for a user Get a session's timeout Server Object When was a file last modified? Open a textfile for reading Home made hit counter
40
Anup Kumar