Приглашаем посетить
Дружинин (druzhinin.lit-info.ru)

16.2 ASP objects and their applications on the Web

Table of Contents

Previous Next

16.2 ASP objects and their applications on the Web

16.2.1 The structure of ASP

Basically, ASP is an environment that allows you to write Web pages using a variety of scripting languages. In fact, you can use several scripting languages within a single ASP page to enhance the functionalities via scripting library scenarios. Since server scripts are read and processed on the server before being sent back to the browser, there is no client requirement for ASP. As a server page inside the server, an ASP page (or document) requires a new file extension .asp to distinguish it from the usual XHTML document.

By default, ASP uses VBScript and JScript as the processing languages. If you want to use another scripting language, you may need to install the appropriate scripting engine, which is a program that can process commands and statements written in a particular language. For every installation of ASP, VBScript and JScript are provided. We will show you how to install another scripting engine called PerlScript in the next section. A structure diagram of ASP is shown in Fig. 16.3.

Figure 16.3. Calling an ASP page

graphics/16fig03.gif


To use the multiple languages feature of ASP and related objects, let's consider some examples in the discussion below.

16.2.2 Creating ASP pages with different scripting languages

In this section, we will show you how to use different languages with ASP. Simple examples of three scripting languages are introduced, namely, VBScript, JScript, and PerlScript. They all have their own language syntax and style and work in the ASP environment as family members.

Another characteristic of ASP is that it is object based. System objects will work closely with your choice of scripting languages. That means you can use your favorite language syntax and style such as VBScript, JScript (a variant of ECMAScript), or PerlScript to call ASP objects to perform the function you want.

As a simple example, consider the following ASP page written in VBScript:



Example: ex16-02.asp - ASP With VBScript

 1: <%@ Language=VBScript%>
 2: <?xml version="1.0" encoding="iso-88591"?>
 3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 4:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 5: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 6: <head><title> ASP With VBScript - ex1602.asp</title></head>
 7: <body style="font-family:arial;font-weight:bold">
 8: <% dim ii
 9: For ii=20 to 26
10: Response.Write("<div style='font-size:" & ii & "px;color:#000000'>")
11: Response.Write("style font-size = " & ii & " px -- Hello World! </div >")
12: Next
13: %>
14: </body>
15: </html>

The first line is to indicate that this is an ASP page using VBScript as the primary language. This means that statements inside the delimiters <% and %> (lines 813) will be processed by the VBScript engine installed in ASP. By default, VBScript is the primary language for ASP. Insider the delimiters, there is a for-loop in VBScript style. Consider the statement in line 10:



Response.Write("<div style='font-size:" & ii & "px;color:#000000'>")

The keyword Response is an object provided by ASP. With this object, you can call the member function (or method) Write() to output something to the browser screen. Inside the parentheses, the ampersand "&" is a VBScript symbol to concatenate two strings.

The JScript version of this example is listed below:



Example: ex16-03.asp - ASP With JScript

 1: <%@ Language=JScript%>
 2: <?xml version="1.0" encoding="iso-88591"?>
 3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 4:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 5: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 6: <head><title> ASP With JScript - ex1603.asp</title></head>
 7: <body style="font-family:arial;font-weight:bold"><br /><br />
 8: <% var ii
 9: for( ii=20;ii <=26; ii++)
10: {
11: Response.Write("<div style='font-size:" + ii + "px;color:#000000'>")
12: Response.Write("style font-size = " + ii + " px -- Hello World! </div >")
13: }
14: %>
15: </body>
16: </html>

The process directive in line 1 indicates that the primary language is JScript (JScript is a version of JavaScript developed by Microsoft; for this reason, JScript is very similar to ECMAScript discussed in this book). The for-loop (lines 913) inside the delimiters is written in JScript (or ECMAScript) style. The plus "+" symbol is used to concatenate strings. No matter what kind of language you are using, you call the same method



Response.Write()

to output something to the screen.

If you want to use another scripting language such as PerlScript on ASP, a PerlScript engine is available from ActiveState Perl (www.activestate.com). It has a Perl version with a Microsoft installer so that the installation and configuration on various Microsoft systems are fully automatic. When you install Active Perl, you will have a working version of the Perl interpreter and a PerlScript engine for ASP at the same time.

If you have a PerlScript engine already installed on your system, you can convert the example above into a PerlScript version as follows:



Example: ex16-04.asp - ASP With PerlScript

 1: <%@ Language=PerlScript%>
 2: <?xml version="1.0" encoding="iso-88591"?>
 3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 4:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 5: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 6: <head><title> ASP With PerlScript - ex1604.asp</title></head>
 7: <body style="font-family:arial;font-weight:bold"><br /><br />
 8: <%
 9: for( $ii=20; $ii <=26; $ii++)
10: {
11: $Response->Write("<div style=\"font-size:" . $ii . "px;color:#000000\">");
12: $Response->Write("style font-size =". $ii ."px -- Hello World! </div >")
13: }
14: %>
15: </body>
16: </html>

Again, the first line is to instruct ASP to process statements inside delimiters with PerlScript. The purpose of the for-loop is to show the calling convention when using PerlScript with ASP. Following the PerlScript syntax, all variables need to have a dollar sign in front of them. Since PerlScript uses references to call objects and functions provided by ASP, the output function is changed to $Response->Write() as illustrated in lines 11 and 12. The period symbol "." used in lines 11 and 12 is to concatenate the strings. In fact, you can put the variable $ii inside, since Perl can interpret a variable correctly even inside a string.

In ASP, the primary scripting language can call functions defined in other scripting languages. To show this feature, consider the following example:



Example: ex16-05.asp - Multiple Scripting Languages In ASP

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title>Multiple Scripting Languages - ex1605.asp</title></head>
 6: <body style="font-family:arial;font-weight:bold;background:#000088">
 7:
 8: <div style="text-align:center;color:#ffff00;font-size:16pt">
 9:  Time From VBScript: <%=Now()%><br />
10:  Time From JScript: <%Call outputDate()%><br /><br />
11:  From PerlScript Function:<br /><%Call outString()%>
12: </div>;
13:
14: <script language=JScript runat=server>
15: function outputDate()
16: {
17:  var x = new Date()
18:  Response.Write(x.toString())
19: }
20: </script>
21:
22: <script language=PerlScript runat=server>
23: sub outString
24: {
25:  for( $ii=20;$ii <=26; $ii++)
26:  {
27:  $Response->Write("<div style=\"font-size:". $ii ."px\">");
28:  $Response->Write("style font-size = ". $ii ."px -- Hello World!</div >");
29:  }
30: }
31: </script>
32: </body>
33: </html>

By default, this ASP page uses VBScript as the primary scripting language. Other scripting languages can be defined by the <script> element. For example, the following statement defines a script block (or an ASP script section) with JScript:



<script language=JScript runat=server>
...  ...  ...
</script>

Inside the script section, you can define any JScript function. The keyword runat=server is to instruct the ASP to run this section on the server. The block in lines 1420 defines a JScript function called outputDate() to display the date and time of the system. Another script block in lines 2330 defines a PerlScript subroutine called outString. This subroutine is to output some strings to the browser window.

When ASP loads this page, the ASP script section (if any) is stored and executed first. Therefore, when ASP executes the JScript statement in line 10



<%Call outputDate()%>

the JScript function outputDate() is already there and ready for execution. If you put any output statement inside the ASP script section, this statement will be executed and placed before the XHTML header. A screen shot is shown in Fig. 16.4.

Figure 16.4. Multiple scripting languages on ASP

graphics/16fig04.jpg


For the rest of this chapter, we will mainly use JScript as the primary scripting language for ASP. We make this choice simply because JScript is consistent with the standard ECMAScript and acceptable by many different platforms. To learn ASP, a basic understanding of the internal objects provided by ASP installation is necessary.

Not just multiple languages can be used in ASP: with ASP objects Web applications can be developed in other dimensions. Let's consider the ASP objects and see how to build Web pages with application- and user-specific (or session) scopes in the next section.

16.2.3 The internal objects of ASP

Basically, ASP is a combination of XHTML, your favorite scripting language, and objects provided by you, the system, and third-party vendors. For a standard ASP installation, the system framework provides the following six built-in objects:

  • Application

  • ObjectContext

  • Request

  • Response

  • Server

  • Session

Built-in objects are closely integrated into every ASP page. Unlike other components, you don't even need to create them before you can use them in your scripts. For each built-in object, there are methods (or functions), collections, and properties associated with them. For example, the function Response.Write() used in section 16.2.2 is a function inside the Response object.

From a practical point of view, the best way to learn ASP is to start with one favorite scripting language such as JScript and a basic understanding of the objects associated with ASP. Basically, there are six ASP objects, as above, and the purpose of each of them is summarized as follows:

  • The Application object is an object providing collections and utilities to share information among all users of a given application.

  • The ObjectContext object is mainly used for transactions and enables you to commit or abort a transaction in a business application.

  • The Request object is a widely used object in ASP. You can use it to gather the contents submitted from any type of Web form including the CGI get and post methods, and to read server variables or the contents of a digital client certificate.

  • The Response is widely used and responsible for sending data from the server to the user. You can use this object to send information directly to the browser, redirecting the browser to other URLs and handling cookies.

  • The Server object is to provide certain server-side functions to the users. The most important function is to create an instance of an ActiveX component with Server.CreateObject. For example, you can use it to open a file. Furthermore, the following statement can be used to instantiate an ActiveX Data Object (ADO) for database connection:

    
    

    ADOConnObj = Server.CreateObject('ADODB.Connection')
    

    We will discuss this application in detail in the coming sections.

  • The Session object enables you to associate variables with a particular user section. Information or variables stored in this object are still alive when a Web application jumps from one page to another.

From ASP 3.0 and later, an additional built-in object called ASPError has been shipped. This object is responsible for tracking down errors during the processing of an ASP page.

For each ASP built-in object, we also have collections, methods, events, and properties associated with them. Their relationships are summarized in Table 16.1.

Table 16.1. ASP built-in objects

Object

Collections

Methods

Events

Properties

Application

Contents StaticObjects

Lock Unlock

Application

N/A

ObjectContext

N/A

SetAbort SetComplete

OnTransactionAbort OnTransactionCommit

N/A

Request

ClientCertificate Cookies Form QueryString ServerVariables

BinaryRead

N/A

TotalBytes

Server

N/A

CreateObject HTMLEncode MapPath URLEncode

N/A

ScriptTimeout

Response

Cookies

AddHeader AppendToLog BinaryWrite Clear End Flush Redirect Write

N/A

Buffer CacheControl Charset ContentType Expires ExpiresAbsolute IsClientConnected PICS Status

Session

Contents StaticObjects

Abandon

Session_OnEnd Session_OnStart

CodePage LCID SessionID Timeout


One of the best ways to study ASP objects is to learn and use the methods associated with the particular object. For example, the popular Write() methods of the Response object can be called by the following ASP statement:



<% Response.Write("Some Strings")%>

This statement will output the text "Some Strings" to the browser. If you want to redirect your ASP page to another page or location, you can use the Redirect method of the Response object as



<% Response.Redirect("Page2.asp") %>

On the whole, ASP provides a rich set of tools to build Web applications. From simple data sharing for Web pages to large, complex Web programming, these objects and their features are invaluable. We will show you how to use most of them step by step. Now, let's begin with the Application object.

16.2.4 Creating ASP pages with application scope

The Application object of ASP can be used to share information among all users. For example, if you defined a welcome message



<%
Application("welcome")="Welcome To Practical Web Technologies"
%>

your other ASP pages used by other users can obtain this text by



<%
Response.Write(Application("welcome"))
%>

In fact, the message is stored in Application.Contents, which is a collection of the object (see Table 16.1). Any information in Application.Contents can be retrieved by name. Therefore, the Response.Write() statement above can output the text. Not just text, but for any variables or events the entire object can be put into the Application object and shared among all your ASP pages. This feature is known as information with application scope.

Data or information with application scope will remain available for the live time of the application. That means they are available for all users visiting the site until after a system reboot. Unlike file storage, information with application scope is not permanent but can exist for a long period of time. This feature is particularly useful for certain kinds of applications described below. But first, let's consider the two methods provided by the Application object.

Since Application is an object designed for multiple accesses at the same time, it contains two methods (or functions), Lock() and Unlock(). You can use the Lock() function to lock the system and store variables or created objects to the Contents of the object. The Applicaton.Contents is a collection of the object and all information stored in it that can be retrieved later by other Web pages. In its simplest form, you can use it to build a temporary page counter to pick up a winner based on the number of visits or page hits. For this application, you don't need to create a file and it would not affect the permanent page counts. Consider the following ASP page:



Example: ex16-06.asp - A Page Counter Using ASP Object

 1: <%@ Language=JScript%>
 2: <?xml version="1.0" encoding="iso-88591"?>
 3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 4:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 5: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 6: <head><title> A Page Counter Using ASP Object - ex1606.asp</title></head>
 7: <body style="font-family:arial;font-weight:bold;background:#000088;
 8:     color:#ffff00;font-size:16pt"><br />
 9:  An Application Scope Page Counter <br />Using ASP Object<br /><br />
10: <%
11: var winNo, countN
12:   winNo = 100
13: Application.Lock()
14:   countN = Application("Hits")
15:   if ((countN > 0) && (countN < winNo))
16:     Application("Hits") = countN +1
17:   else
18:     Application("Hits") = 1
19: Application.UnLock()
20:
21:  if (countN == winNo)
22:    Response.Write("Congratulations! <br /> You Are Visitor: "+ countN +
23:     "<br />We Have A Small Gift For You. Please Contact Us.")
24:  else
25:    Response.Write("You Are Visitor No. "+ countN +"<br />")
26: %>
27:    <br /><br />
28: </body>
29: </html>

For a busy site, it is likely that simultaneous access occurs at the same time. To avoid any counting confusion, the Lock() function in line 13 is used to lock the page for exclusive access and update. Since locking the page prevents any page updating by others, you should unlock the page as soon as you have finished the updating.

The scripting block in lines 2125 contains a simple if statement. This statement is to pick up the winner when the page hits are the same as the winning number winNo. Some screen shots of this example in action are shown in Figs 16.5a and 16.5b.

Figure 16.5a. ex16-06.asp

graphics/16fig05.jpg


Figure 16.5b. Pick up the 100th visitor

graphics/16fig05a.jpg


16.2.5 Building user scope applications with the Session object

In addition to the Application object, the Session object can be used to store information needed for a particular user session. When a user who does not already have a session requests an ASP page, the Web server automatically creates a Session object for him or her. Variables and information can be stored in this Session object dedicated to this user. This feature is usually called session scope.

You can use the same method as for the Application object to store messages for the Session object. For example, if you define the following text and store it in the Session object



<%
Session("welcome")="Welcome To Our On-line Shopping site"
%>

the string will be stored in a variable called welcome of the Session object. All visitors to this ASP page will have this message defined in an independent session. The message can be retrieved later by:



<%
Response.Write(Session("welcome"))
%>

Information stored in the Session object is not discarded when the user jumps between pages. When a user finishes his or her session or the abandon method is called, all information and objects stored in the session will be destroyed.

Also, the Session object provides a SessionID property to identify each session and user. It is a unique identifier with a long integer data type generated by the Web server. For example, the following command generates a SessionID:



<% Session.SessionID %>

Many Web sites use this feature to build user identity when the user visits the site. This identity is used to identify the user and give away free gifts, say. Consider the example below:



Example: ex16-07.asp - A Page To Claim Free Gift

 1: <%@ Language=JScript%>
 2: <?xml version="1.0" encoding="iso-88591"?>
 3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 4:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 5: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 6: <head><title> Claim Your Free Gift - ex1607.asp</title></head>
 7: <body style="font-family:arial;font-weight:bold;background:#000088;
 8:     color:#ffff00;font-size:16pt"><br />
 9:   ABC On-line Shopping Site<br /><br />
10:
11: <%
12:  Session("welcome")="Welcome To Our Shopping Site"
13: %>
14:
15: <%
16:  Response.Write(Session("welcome")+"<br />")
17:  Response.Write("Your Shopping ID is: "+Session.SessionID + "<br />")
18:  if (Session("gift") != "yes")
19:  {
20:  Response.Write("We Have A Free Gift For You"+"<br /><br />")
21:  Response.Write('<a href="ex16-07a.asp"'+
22:    ' style="color:#ffff00">Click Here To Claim Your Gift</a>')
23:  }
24:  else
25:    Response.Write("Your Free Gift is : "+Session("gift_detail"))
26: %>
27:
28:  <br /><br />
29: </body>
30: </html>

This is a simple ASP page to demonstrate the use of the Session object. Lines 1113 start a session with a simple message stored in the variable welcome. This message is later retrieved by the Session statement in line 16. The SessionID is displayed as well. Next, there is a conditional statement to give away a free gift.

Basically, we use two more session variables gift and gift_detail. If the gift variable stores the string "yes" that means the user has already claimed his or her free gift and the details of the free gift are displayed (line 25). If the user has not claimed his or her free gift, the messages in lines 2022 are displayed. In particular, the message in line 2122:



Response.Write('<a href="ex1607a.asp"'+
  ' style="color:#ffff00">Click Here To Claim Your Gift</a>')

uses an anchor element to activate the ASP page ex16-07a.asp to claim the gift.

Surprisingly, the ASP page ex16-07a.asp contains only six lines:



Example: ex16-07a.asp - The ASP Page For ex1607.asp

 1: <%@ Language=JScript%>
 2: <%
 3:  Session("gift")="yes"
 4:  Session("gift_detail")="Monitor and Keyboard Hood"
 5:  Response.Redirect("ex1607.asp")
 6: %>

Since this page is invisible to the user, it can be written as pure ASP code. In fact, this page has three statements only. The first statement is to assign a session variable called gift to the string "yes." The second statement in line 4 provides the details of the free gift. The final statement uses the Redirect function of the Response object to redirect the user back to the original page ex16-07.asp. Some screen shots of this example are shown in Figs 16.6a and 16.6b.

Figure 16.6a. ex16-07.asp

graphics/16fig06.jpg


Figure 16.6b. Claim your free gift

graphics/16fig06a.jpg


This example has session scope and every user or activation will be assigned a SessionID. Unless you have many gifts, you may also need to ask the user to fill out a claim form in order to make a claim.

    Table of Contents

    Previous Next