You are on page 1of 60

Active Server Pages (ASP

)
MCA Sem III

MCA Sem III

1

Introduction
• ASP is a powerful tool for making dynamic and interactive Web pages. • Example: • <html> <body> <% response.write("My first ASP script!") %> </body> </html>

• An ASP file can contain text, HTML tags and scripts. Scripts in an ASP file are executed on the server. •

MCA Sem III

2

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
MCA Sem III 3

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 MCA Sem III 4 .ASP Compatibility • To run IIS you must have Windows NT 4.

What is an ASP File? • An ASP file is just the same as an HTML file • An ASP file can contain text. XML. HTML. and scripts • Scripts in an ASP file are executed on the server • An ASP file has the file extension ".asp" MCA Sem III 5 .

Finally. and executes the scripts in the file.How Does ASP Differ from HTML? • When a browser requests an HTML file. The ASP engine reads the ASP file. line by line. the ASP file is returned to the browser as plain HTML • MCA Sem III 6 . the server returns the file • When a browser requests an ASP file. IIS passes the request to the ASP engine.

since ASP code cannot be viewed from the browser • Clever ASP programming can minimize the network traffic MCA Sem III 7 . change.What can ASP do for you? • Dynamically edit. are those of simplicity and speed • Provide security . 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.

• MCA Sem III 8 . and Windows 7. • IIS comes with Windows 2000.IIS . XP. • IIS is easy to install and ideal for developing and testing web applications.Internet Information Server • IIS is a set of Internet-based services for servers created by Microsoft for use with Microsoft Windows. Vista. It is also available for Windows NT.

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

Windows Web Server Versions • • • • • • • • • • • • • Windows 7 (all editions) come with IIS 7.1 Windows XP Home Edition does not support IIS or PWS Windows 2000 Professional comes with IIS 5. 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.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 MCA Sem III 10 .5 Windows Vista Business.

statements.write Command • The response. just like an HTML file.write command is used to write output to a browser. surrounded by the delimiters <% and %>. or operators valid for the scripting language you prefer to use. and can contain any expressions. • The response. an ASP file can also contain server scripts. However.ASP Basic Syntax Rules • Writing Output to a Browser : • An ASP file normally contains HTML tags. • Server scripts are executed on the server. The following example sends the text "Hello World" to the browser: MCA Sem III 11 . procedures.

• Example • <html> <body> <% response.write("Hello World!") %> </body> </html> MCA Sem III 12 .

shorthand method for the response.write command • Example: • <html> <body> <% ="Hello World!" %> </body> </html> MCA Sem III 13 .

the default scripting language is VBScript: • <html> <body> <% response.write("Hello World!") %> </body> </html> MCA Sem III 14 .Using VBScript in ASP • You can use several scripting languages in ASP. However.

Write("Hello World!") %> </body> </html> MCA Sem III 15 .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"%> <html> <body> <% Response.

Variables in ASP : • <html> <body> <% dim name name="Donald Duck" response.write("My name is: " & name) %> </body> </html> MCA Sem III 16 .

Arrays in ASP :
• <html> <body>

<% Dim famname(5),i famname(0) = "Jan Egil" famname(1) = "Tove" famname(2) = "Hege" famname(3) = "Stale" famname(4) = "Kai Jim" famname(5) = "Borge"
For i = 0 to 5 response.write(famname(i) & "<br />") Next %> </body> </html>
MCA Sem III 17

Example:
• <html> <body> <% dim i for i=1 to 6 response.write("<h" & i & ">Heading " & i & "</h" & i & ">") next %> </body> </html>
MCA Sem III 18

Example:
• <html> <body> <% response.write("<h2>You can use HTML tags to format the text!</h2>") %> <% response.write("<p style='color:#0000ff'>This text is styled with the style attribute!</p>") %> </body> </html>
MCA Sem III 19

Typically information stored in session variables are name. and are available to all pages in one application. • A variable declared inside a procedure is created and destroyed every time the procedure is executed.Lifetime of Variables • A variable declared outside a procedure can be accessed and changed by any script in the ASP file. declare them as session variables or application variables. Application variables are used to store information about ALL users in one specific application. id. • Application Variables • Application variables are also available to all pages in one application. • To declare variables accessible to more than one ASP file. No scripts outside the procedure can access or change the variable. and preferences. • Session Variables • Session variables are used to store information about ONE single user. • MCA Sem III 20 .

num2) response.write(num1*num2) end sub %> </head> <body> <p>Result: <%call vbproc(3.4)%></p> </body> </html> MCA Sem III 21 .• • • • ASP Procedures Procedures The ASP source code can contain procedures and functions: Example <html> <head> <% sub vbproc(num1.

Write(num1*num2) } %> </head> <body> <p>Result: <%jsproc(3.num2) { Response.• Insert the <%@ language="language" %> line above the <html> tag to write the procedure/function in another scripting language: • Example • <%@ language="javascript" %> <html> <head> <% function jsproc(num1.4)%></p> </body> </html> MCA Sem III 22 .

always use parentheses after the procedure name. the parentheses are optional. If the procedure has no parameters.Differences Between VBScript and JavaScript • When calling a VBScript or a JavaScript procedure from an ASP file written in VBScript. If you omit the "call" keyword. you can use the "call" keyword followed by the procedure name. the parameter list must be enclosed in parentheses when using the "call" keyword. the parameter list must not be enclosed in parentheses. • MCA Sem III 23 . • When calling a JavaScript or a VBScript procedure from an ASP file written in JavaScript. If a procedure requires parameters.

QueryString and Request.ASP Forms and User Input • The Request. MCA Sem III 24 .Form commands are used to retrieve user input from forms.Form command. • User Input • The Request object can be used to retrieve user information from forms. • Example HTML form • <form method="get" action="simpleform.QueryString or Request.asp"> First Name: <input type="text" name="fname" /><br /> Last Name: <input type="text" name="lname" /><br /><br /> <input type="submit" value="Submit" /> </form> • User input can be retrieved with the Request.

• 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.w3schools.Request.write(" " & request.QueryString • The Request.asp" contains the following ASP script: • <body> Welcome <% response.com/simpleform.write(request.asp?fname=Bill&lname=Ga tesAssume that "simpleform.QueryString command is used to collect values in a form with method="get". the URL sent to the server would look like this: • http://www.querystring("lname")) %> </body> The browser will display the following in the body of the document: • Welcome Bill Gates MCA Sem III 25 .querystring("fname")) response.

Form command is used to collect values in a form with method="post". the URL sent to the server would look like this: • http://www.Form • The Request. • If a user typed "Bill" and "Gates" in the HTML form above.write(" " & request.com/simpleform.form("lname")) %> </body> The browser will display the following in the body of the document: • Welcome Bill Gates MCA Sem III 26 . • Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.Request.asp" contains the following ASP script: • <body> Welcome <% response.form("fname")) response.write(request.aspAssume that "simpleform.w3schools.

• 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.Form Validation • User input should be validated on the browser whenever possible (by client scripts). The user will then get the error messages on the same page as the form. This makes it easier to discover the error. MCA Sem III 27 . Browser validation is faster and reduces the server load.

• The Application object is used to store and access variables from any page. and the changes will automatically be reflected on all pages.ASP Application Object • A group of ASP files that work together to perform some purpose is called an application. • The Application object holds information that will be used by many pages in the application (like database connection information). • MCA Sem III 28 . The information can also be changed in one place. • Application Object • An application on the Web may consists of several ASP files that work together to perform some purpose. The information can be accessed from any page. The Application object is used to tie these files together. The difference is that ALL users share ONE Application object (with Sessions there is ONE Session object for EACH user). just like the Session object.

asa" like this: • <script language="vbscript" runat="server"> Sub Application_OnStart application("vartime")="" application("users")=1 End Sub </script> MCA Sem III 29 . • You can create Application variables in "Global.Store and Retrieve Application Variables • Application variables can be accessed and changed by any page in an application.

Write(i & "<br />") Next %>If you do not know the number of items in the Contents collection.• The Contents collection contains all application variables.Contents Response.Write(Application. You can loop through the Contents collection. to see what's stored in it: • <% dim i For Each i in Application. you can use the Count property: • <% dim i dim j j=Application.Contents.Contents(i) & "<br />") Next %> Loop Through the Contents Collection MCA Sem III 30 .Count For i=1 to j Response.

The #include Directive • You can insert the content of one ASP file into another ASP file before the server executes it.inc"--></p> <h3>The time is:</h3> <p><!--#include file="time. with the #include directive. • How to Use the #include Directive • Here is a file called "mypage. or elements that will be reused on multiple pages. headers.inc"--></p> </body> </html> MCA Sem III 31 . footers. • The #include directive is used to create functions.asp": • <html> <body> <h3>Words of Wisdom:</h3> <p><!--#include file="wisdom.

"</p> <h3>The time is:</h3> <p>11:33:42 AM</p> </body> </html> MCA Sem III 32 .inc" file: • "One should never increase. the number of entities required to explain anything.• Here is the "wisdom.inc" file: • <% Response. the number of entities required to explain anything. beyond what is necessary.Write(Time) %> • If you look at the source code in a browser.“ • Here is the "time. beyond what is necessary. it will look something like this: • <html> <body> <h3>Words of Wisdom:</h3> <p>"One should never increase.

Syntax for Including Files • To include a file in an ASP page. the following line would insert the contents of "header.inc": • <!-. • If a file named "header.inc" --> MCA Sem III 33 .inc" resides in a virtual directory named /html.#include virtual ="/html/header. place the #include directive inside comment tags: • <!--#include virtual="somefilename"--> or <!--#include file ="somefilename"-->The Virtual Keyword • Use the virtual keyword to indicate a path beginning with a virtual directory.

and the file "header. • If you have a file in the html directory. A relative path begins with the directory that contains the including file.• The File Keyword • Use the file keyword to indicate a relative path.inc" resides in html\headers.inc" in your file: • <!-.#include file ="headers\header. If the file containing this #include statement is not in the html directory. MCA Sem III 34 .inc" -->Note that the path to the included file (headers\header.inc) is relative to the including file. the following line would insert "header. the statement will not work.

asa file is an optional file that can contain declarations of objects.asa file must be stored in the root directory of the ASP application. VBScript.) can be used within Global. and each application can only have one Global. PerlScript.asa file • The Global.asa file can contain only the following: • Application events • Session events • <object> declarations • TypeLibrary declarations • the #include directive • Note: The Global.asa file.asa. etc. and methods that can be accessed by every page in an ASP application. variables.The Global. • All valid browser scripts (JavaScript. JScript. • The Global. MCA Sem III 35 .

• Application_OnEnd . • Session_OnEnd .Events in Global. like delete records or write information to text files. A user-session ends after a page has not been requested by the user for a specified time (by default this is 20 minutes). The "Session_OnStart" event occurs immediately after this event.asa file is edited.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. Typically.asa • Application_OnStart .This event occurs EVERY time a NEW user requests his or her first page in the ASP application. MCA Sem III 36 . this event occurs when a Web server stops.This event occurs after the LAST user has ended the session.Session_OnStart .This event occurs EVERY time a user ends a session. This procedure is used to clean up settings after the Application stops.

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 end sub </script> MCA Sem III 37 .• A Global.

Version]Either ProgID or ClassID must be specified..]Component[.asa by using the <object> tag. MCA Sem III 38 . </object> ParameterDescriptionscopeSets the scope of the object (either Session or Application)idSpecifies a unique id for the objectProgIDAn id associated with a class id.Either ProgID or ClassID must be specified...<object> Declarations • It is possible to create objects with session or application scope in Global. • ClassIDSpecifies a unique id for a COM class object. • Note: The <object> tag should be outside the <script> tag! • Syntax • <object runat="server" scope="scope" id="id" {progid="progID"|classid="classID"}> . The format for ProgID is [Vendor.

id. This interface is called the Session object. and are available to all pages in one application. on the internet there is one problem: the web server does not know who you are and what you do. you open it. It knows when you open the application and when you close it. or change settings for a user session. • • • • MCA Sem III 39 . Variables stored in a Session object hold information about one single user. The server creates a new Session object for each new user. and destroys the Session object when the session expires. The Session object: When you are working with an application on your computer. The Session object stores information about. Common information stored in session variables are name. However. do some changes and then you close it. The computer knows who you are. or change settings for a user session. This is much like a Session. and preferences. ASP solves this problem by creating a unique cookie for each user.Session Object • • • A Session object stores information about. The cookie is sent to the user's computer and it contains information that identifies the user. because the HTTP address doesn't maintain state.

asa file uses the <object> tag to instantiate an object with session scope • MCA Sem III 40 . and the Global.asa file includes a Session_OnStart procedure • A value is stored in a Session variable • A user requests an ASP file.A session starts when: • A new user requests an ASP file. and the Global.

this is 20 minutes. • Example: • <% Session. • If you want to set a timeout interval that is shorter or longer than the default.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. use the Timeoutproperty.Timeout=15 %> MCA Sem III 41 .

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%> MCA Sem III 42 .Write(Session("username"))%>The line above returns: "Welcome Ronaldo”. • You can also store user preferences in the Session object.How to 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 “Ronaldo " and the Session variable age to “70": • <% Session("username")=“Ronaldo " Session("age")=70 %>When the value is stored in a session variable it can be reached from ANY page in the ASP application: • Welcome <%Response.

Remove("sale") End If %>To remove all variables in a session.Contents. use the RemoveAll method: • <% Session. • The example below removes the session variable "sale" if the value of the session variable "age" is lower than 18: • <% If Session.RemoveAll() %> MCA Sem III 43 . • It is possible to remove a session variable with the Remove method.Contents.Contents("age")<18 then Session.Remove Session Variables • The Contents collection contains all session variables.

Loop Through the StaticObjects Collection • You can loop through the StaticObjects collection.StaticObjects Response. to see the values of all objects stored in the Session object: • <% dim i For Each i in Session.Write(i & "<br />") Next %> MCA Sem III 44 .

The difference is that ALL users share ONE Application object (with Sessions there is ONE Session object for EACH user).Application Object • A group of ASP files that work together to perform some purpose is called an application. The information can also be changed in one place. • An application on the Web may consists of several ASP files that work together to perform some purpose. The information can be accessed from any page. just like the Session object. • The Application object is used to store and access variables from any page. and the changes will automatically be reflected on all pages. The Application object is used to tie these files together. • The Application object holds information that will be used by many pages in the application (like database connection information). • MCA Sem III 45 .

Store and Retrieve Application Variables • Application variables can be accessed and changed by any page in an application.asa" like this: • <script language="vbscript" runat="server"> Sub Application_OnStart application("vartime")="" application("users")=1 End Sub </script> MCA Sem III 46 . • You can create Application variables in "Global.

you can use the Count property: • <% dim i dim j j=Application.Count For i=1 to j Response.Write(i & "<br />") Next %>If you do not know the number of items in the Contents collection.Write(Application.Contents(i) & "<br />") Next %> MCA Sem III 47 . to see what's stored in it: • <% dim i For Each i in Application. You can loop through the Contents collection.Contents Response.Contents.Loop Through the Contents Collection • The Contents collection contains all application variables.

StaticObjects Response.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.Write(i & "<br />") Next %> MCA Sem III 48 .

Lock 'do some application object operations Application. When an application is locked.Lock and Unlock • You can lock an application with the "Lock" method. the users cannot change the Application variables (other than the one currently accessing it).Unlock %> MCA Sem III 49 . You can unlock an application with the "Unlock" method. This method removes the lock from the Application variable: • <% Application.

MCA Sem III 50 . Its properties and methods are described below: • Properties • PropertyDescriptionScriptTimeoutSets or returns the maximum number of seconds a script can run before it is terminatedMethods • MethodDescriptionCreateObjectCreates an instance of an objectExecuteExecutes an ASP file from inside another ASP fileGetLastError()Returns an ASPError object that describes the error condition that occurredHTMLEncodeApplies HTML encoding to a specified stringMapPathMaps a specified path to a physical pathTransferSends (transfers) all the information created in one ASP file to a second ASP fileURLEncodeApplies URL encoding rules to a specified string.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.

GetLastError is called. • The ASPError object's properties are described below (all properties are read-only): • MCA Sem III 51 . so the error information can only be accessed by using the Server.0 and is available in IIS5 and later. • The ASPError Object • The ASPError object was implemented in ASP 3.GetLastError method.ASPError Object • The ASPError object displays information about errors in scripts. • 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.

txt".Close set fname=nothing set fs=nothing %> MCA Sem III 52 . It is also possible to retrieve file system information with this object. • This object can manipulate files. • The following code creates a text file (c:\test. and directory paths.The FileSystemObject Object • The FileSystemObject object is used to access the file system on a server.WriteLine("Hello World!") fname.FileSystemObject") set fname=fs.CreateObject("Scripting.txt) and then writes some text to the file: • <% dim fs.true) fname. folders.CreateTextFile("c:\test.fname set fs=Server.

Properties : Property ASPCode ASPDescription Description Returns an error code generated by IIS Returns a detailed description of the error (if the error is ASPrelated) Returns the source of the error (was the error generated by ASP? By a 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 ASP file that generated the error MCA Sem III 53 Returns the line number where the Category Column Description File Line .

FileSystemObject") set f=fs.f set fs=Server.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. MCA Sem III 54 .true) f.TextStream Object • The TextStream Object • The TextStream object is used to access the contents of text files.txt) and then writes some text to the file (the variable f is an instance of the TextStream object): • <% dim fs.CreateObject("Scripting. • The following code creates a text file (c:\test.txt".CreateTextFile("c:\test.WriteLine("Hello World!") f. or you can use the OpenAsTextStream method of the File object.

• Note: You cannot return information about a drive's content with the Drive object. MCA Sem III 55 . you will have to create an instance of the Drive object through the FileSystemObject object. create a FileSystemObject object and then instantiate the Drive object through the GetDrive method or the Drives property of the FileSystemObject object. • To work with the properties of the Drive object. and more. free space. The Drive object can return information about a drive's type of file system. volume name. serial number. First. For this purpose you will have to use the Folder object.Drive Object • The Drive Object • The Drive object is used to return information about a local disk drive or a network share.

• To work with the properties and methods of the File object. First.CreateObject("Scripting. 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. you will have to create an instance of the File object through the FileSystemObject object.f Set fs=Server.Write("File created: " & f.txt") Response.File Object • The File Object • The File object is used to return information about a specified file.FileSystemObject") Set f=fs.GetFile("c:\test.DateCreated) set f=nothing set fs=nothing %> MCA Sem III 56 . • 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.

Write("Folder created: " & fo.DateCreated) set fo=nothing set fs=nothing %> Output: Folder created: 10/22/2008 10:01:19 AM • • MCA Sem III 57 . 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. To work with the properties and methods of the Folder object.fo Set fs=Server. First.FileSystemObject") Set fo=fs. create a FileSystemObject object and then instantiate the Folder object through the GetFolder method of the FileSystemObject object.GetFolder("c:\test") Response.Folder Object • • • The Folder Object The Folder object is used to return information about a specified folder.CreateObject("Scripting. you will have to create an instance of the Folder object through the FileSystemObject object.

the remaining items will automatically shift up Dictionaries cannot be multidimensional.Add "gr". however. The Dictionary object might seem similar to Arrays.CreateObject("Scripting."Green" d.Item("gr")) %> Output: The value of key gr is: Gre MCA Sem III 58 . adds some key/item pairs to it."Blue" d. Comparing Dictionaries and Arrays: Keys are used to identify the items in a Dictionary object You do not have to call ReDim to change the size of the Dictionary object When deleting an item from a Dictionary.Dictionary") d. Arrays can Dictionaries have more built-in functions than Arrays Dictionaries work better than arrays on accessing random elements frequently Dictionaries work better than arrays on locating items by their content The following example creates a Dictionary object.Add "bl".Write("The value of key gr is: " & d. the Dictionary object is a more desirable solution to manipulate related data.Dictionary Object • • • • • • • • • • • • The Dictionary Object The Dictionary object is used to store information in name/value pairs (referred to as key and item). and retrieves the item value for the key gr: <% Dim d Set d=Server."Red" d.Add "re"."Pink" Response.Add "pi".

Connectivity of Database • • • • • • • • • • • • • • • • ADO can be used to access databases from your web pages. Accessing a Database from an ASP Page The common way to access a database from inside an ASP page is to: Create an ADO connection to a database Open the database connection Create an ADO recordset Open the recordset Extract the data you need from the recordset Close the recordset Close the connection What is ADO? ADO is a Microsoft technology ADO stands for ActiveX Data Objects ADO is a Microsoft Active-X component ADO is automatically installed with Microsoft IIS ADO is a programming interface to access data in a database MCA Sem III 59 .

Accessing a Database from an ASP Page : • The common way to access a database from inside an ASP page is to: • Create an ADO connection to a database • Open the database connection • Create an ADO recordset • Open the recordset • Extract the data you need from the recordset • Close the recordset • Close the connection What is ADO? • ADO is a Microsoft technology • ADO stands for ActiveX Data Objects • ADO is a Microsoft Active-X component • ADO is automatically installed with Microsoft IIS • ADO is a programming interface to access data in a database MCA Sem III 60 .ADO : • can be used to access databases from your web pages.