www.tamertolba.4t.com

 

 Chapter 7

Working with ActiveX Server Components

 

This section provides an overview of some of the tasks you can accomplish with the ActiveX server components included with Active Server Pages (ASP).

 

ActiveX server components, formerly known as Automation servers, are designed to run on your Web server as part of a Web-based application. Components package common dynamic features, such as database access, so that you do not have to create and recreate these features.

 

Components are typically invoked from .asp files. However, you can invoke components from other sources as well, such as an ISAPI application, another server component, and other OLE-compatible languages.

 

IIS3 includes five installed ActiveX server components:

 

Browser Capabilities component

Ad Rotator component

                         Database Access component

File Access component

          Content Linking component

 

7.1- Creating an Instance of a Component:

You can create an instance of an ActiveX server component with a single statement. Once you have created an instance of a component, you can use the methods associated with that component, or set and read the component’s properties.

 

The following script uses the Server.CreateObject method to create an instance of the Browser Capabilities component and assigns it to the variable bc:

 

<% Set bc = Server.CreateObject("MSWC.BrowserType") %>

 

You can also use the <OBJECT> tag to create a component instance. This example

creates an instance of the Ad Rotator Component:

 

<OBJECT RUNAT=Server ID=MyAd PROGID="MSWC.AdRotator"></OBJECT>

 

Note : Typically, you use the extended <OBJECT> tag in the Global.asa file to create session-scope or application-scope component instances.

 

7.2- Determining Browser Capability:

Not all browsers support the rapidly expanding array of features available in the

hypermedia world: Frames, background sounds, Java applets, and tables are

examples of features that some browsers support and others do not. You can

use the Browser Capabilities component to present content in formats that are

appropriate for the capabilities of specific browsers. For example, if a browser

does not support tables, the Browser Capabilities component can display the

data in an alternate form such as text. You can use the Browser Capability component to do this.

The script below demonstrates the most commonly used property of the Browser Capabilites component.

 

<html><head>

<TITLE>bc.asp</TITLE>

</head><body bgcolor="#FFFFFF">

<% Set bc = Server.CreateObject("MSWC.BrowserType") %>

Browser Name: <%=bc.browser %><p>

Browser Version: <%=bc.version%><p>

<% if (bc.frames = TRUE) then %>

I  noticed you do frames<p>

<% else %>

I  noticed you are frame challenged<p>

<% end if %>

<% if (bc.tables = TRUE) then %>

I  noticed you do tables<p>

<% else %>

I  noticed you can't do tables<p>

<% end if %>

<% if (bc.BackgroundSounds = TRUE)then %>

I  noticed you allow me to play music<p>

<% else %>

I  noticed you aren't a music listener<p>

<% end if %>

<% if (bc.vbscript = TRUE) then %>

I  noticed you are VBscript capable<p>

<% else %>

I  noticed you can't understand VB Script<p>

<% end if %>

<% if (bc.javascript = TRUE) then %>

I  noticed you understand JScript<p>

<% else %>

I  noticed you don't understand JScript<p>

<%

end if

set bc=nothing

%>

</body></html>

 

Note :  The file Browscap.ini (found in C:\Winnt\system32\inetsrv\ASP\ Cmpnts by default) contains the data necessary for the Browser Capabilities component to recognize a browser and its capabilities. You will need to add new data to this file as new browsers are developed, or if you are using browser-dependent features that are not listed in the default Browscap.ini file.

 

7.3- Displaying Advertisements on a Page:

Internet Web sites often provide advertising space. To keep sites visually

interesting and to display ads from several advertisers in limited space, you

might want to cycle through different advertisements.You can use the Ad Rotator component to display and alternate a series of images, as well as to provide a link from the displayed image to another URL The Ad Rotator component automates the rotation of advertisement images on a Web page. Each time a user opens or reloads the Web page, the Ad Rotator component displays a new advertisement based on the information you specify in a Rotator Schedule File. You can record how many users click each advertisement by setting the REDIRECT parameter in the Rotator Schedule file. When you specify this parameter, each jump to an advertiser's URL is recorded in the Web server activity logs.

File Names

 

Adrot.dll                          The Ad Rotator component.

Advertisement Logical Page The asp page in which the advertisement is

displayed.

Redirection File               An optional file that implements redirection

and enables the Ad Rotator component to record how many users click on each  advertisement.

Rotator Schedule File      A text file that contains the display schedule

and file information for advertisements. This file must be available on a Web server virtual path.

 

Properties

 

Border              Specifies the size of the border around the advertisement.

Clickable          Specifies whether the advertisement is a hyperlink.

TargetFrame    Specifies the name of the frame in which to display the

     advertisement.

 
Methods

 

GetAdvertisement            Gets the specifications for the next scheduled advertisement from the data file and formats it as HTML.

 

The following example displays a different advertisement each time a user views the Web page.

<%  Set ad = Server.CreateObject("MSWC.AdRotator") %>  

<%= ad.GetAdvertisement("/ads/adrot.txt") %> 

The adrot.txt which is the file containing advertisment data. For each ad, this includes the images to use, the URL to which to go when a user clicks the ad (after going to Adredir.asp, in this example), the text associated with the image, and the percentage of time this ad is to be displayed:

 

redirect /aspsamp/advworks/adredir.asp

width 460

height 60

border 1

*

/advertisement/images/ad_1.gif

http://www.microsoft.com

My Company

20

 

/advertisement/images/ad_2.gif

http://www.netscape.com

Software  Company

40

 

The adredir.asp file this script enables you to track ad popularity.

<%

response.buffer = true

dim url

url = request.querystring("url")

response.redirect(url)

%>

Such an example  might produce the following HTML.

<A HREF= "http://www.msn.com/scripts/adredir.asp?url=http://www.company.com/">

<IMG SRC="http://msnnt3web/ads/homepage/chlogo_lg.gif"

ALT="Check out the new Technology Center" WIDTH=440 HEIGHT=60 BORDER=1></A>

 

7.4- Retrieving Data from a Database:

 

You can use the Database Access component to provide access to a database from within your Web application. You can then display the entire contents of a table, allow users to construct queries, and perform other database operations from Web pages ( This topic will be discussed in details in a latter chapter )

 

7.5- File Access component:

The File Access component exposes methods and properties you can use to access a computer's file system. You can use the File Access Component to create a FileSystemObject  object (FSO) which provides the methods properties and collections you use to access the file system.

The FSO object model gives your server-side applications the ability to create, alter, move, and delete folders, or to detect if particular folders exist, and if so, where. You can also find out information about folders, such as their names, the date they were created or last modified, and so forth.

The FSO object model also makes it easy to process files. When processing files, the primary goal is to store data in a space- and resource-efficient, easy-to-access format. You need to be able to create files, insert and change the data, and output (read) the data. Since storing data in a database, such as Access or SQL Server, adds a significant amount of overhead to your application, storing your data in a binary or text file may be the most efficient solution. You may prefer not to have this overhead, or your data access requirements may not require all the extra features associated with a full-featured database.

FileSystemObject Objects

The FileSystemObject (FSO) object model contains the following objects and collections.

Object/Collection

Description

FileSystemObject

Main object. Contains methods and properties that allow you to create, delete, gain information about, and generally manipulate drives, folders, and files. Many of the methods associated with this object duplicate those in other FSO objects; they are provided for convenience.

Drive

Object. Contains methods and properties that allow you to gather information about a drive attached to the system, such as its share name and how much room is available. Note that a "drive" isn't necessarily a hard disk, but can be a CD-ROM drive, a RAM disk, and so forth. A drive doesn't need to be physically attached to the system; it can be also be logically connected through a network.

Drives

Collection. Provides a list of the drives attached to the system, either physically or logically. The Drives collection includes all drives, regardless of type. Removable-media drives need not have media inserted for them to appear in this collection.

File

Object. Contains methods and properties that allow you to create, delete, or move a file. Also allows you to query the system for a file name, path, and various other properties.

Files

Collection. Provides a list of all files contained within a folder.

Folder

Object. Contains methods and properties that allow you to create, delete, or move folders. Also allows you to query the system for folder names, paths, and various other properties.

Folders

Collection. Provides a list of all the folders within a Folder.

TextStream

Object. Allows you to read and write text files.

 

Programming the FileSystemObject

To program with the FileSystemObject (FSO) object model:

  • Use the CreateObject method to create a FileSystemObject object.

  • Use the appropriate method on the newly created object.

  • Access the object's properties.

Creating a FileSystemObject Object

First, create a FileSystemObject object by using the CreateObject method of the server object.

Dim fso
Set fso = Server.CreateObject("Scripting.FileSystemObject")

Scripting is the name of the type library and FileSystemObject is the name of the object that you want to create. You can create only one instance of the FileSystemObject object, regardless of how many times you try to create another.

Using the Appropriate Method

Second, use the appropriate method of the FileSystemObject object. For example, to create a new object, use either CreateTextFile or CreateFolder (the FSO object model doesn't support the creation or deletion of drives).

To delete objects, use the DeleteFile and DeleteFolder methods of the FileSystemObject object, or the Delete method of the File and Folder objects. You can also copy and move files and folders, by using the appropriate methods.

Note :  Some functionality in the FileSystemObject object model is redundant. For example, you can copy a file using either the CopyFile method of the FileSystemObject object, or you can use the Copy method of the File object. The methods work the same; both exist to offer programming flexibility.

Accessing Existing Drives, Files, and Folders

To gain access to an existing drive, file, or folder, use the appropriate "get" method of the FileSystemObject object:

  • GetDrive

  • GetFolder

  • GetFile

To gain access to an existing file in VBScript:

Dim fso, f1
Set fso = server.CreateObject("Scripting.FileSystemObject")
Set f1 = fso.GetFile("c:\test.txt")

Do not use the "get" methods for newly created objects, since the "create" functions already return a handle to that object. For example, if you create a new folder using the CreateFolder method, don't use the GetFolder method to access its properties, such as Name, Path, Size, and so forth. Just set a variable to the CreateFolder function to gain a handle to the newly created folder, then access its properties, methods, and events. To do this in VBScript, use the following code:

Sub CreateFolder
   Dim fso, fldr
   Set fso = Servre.bject("Scripting.FileSystemObject")
   Set fldr = fso.CreateFolder("C:\MyTest")
   Response.Write "Created folder: " & fldr.Name
End Sub

Accessing the Object's Properties

Once you have a handle to an object, you can access its properties. For example, to get the name of a particular folder, first create an instance of the object, then get a handle to it with the appropriate method (in this case, the GetFolder method, since the folder already exists).

Use this code to get a handle to the GetFolder method in VBScript:

Set fldr = fso.GetFolder("c:\")

Now that you have a handle to a Folder object, you can check its Name property. Use the following code to check this in VBScript:

Response.Write "Folder name is: " & fldr.Name

To find out the last time a file was modified, use the following VBScript syntax:

Dim fso, f1
Set fso = Server.Object("Scripting.FileSystemObject")
' Get a File object to query.
Set f1 = fso.GetFile("c:\detlog.txt")   
' Print information.
Response.Write "File last modified: " & f1.DateLastModified 

 

Working with Drives and Folders

With the FileSystemObject (FSO) object model, you can work with drives and folders programmatically just as you can in the Windows Explorer interactively. You can copy and move folders, get information about drives and folders, and so forth.

Getting Information About Drives

The Drive object allows you to gain information about the various drives attached to a system, either physically or over a network. Its properties allow you to obtain information about:

  • The total size of the drive in bytes (TotalSize property)

  • How much space is available on the drive in bytes (AvailableSpace or FreeSpace properties)

  • What letter is assigned to the drive (DriveLetter property)

  • What type of drive it is, such as removable, fixed, network, CD-ROM, or RAM disk (DriveType property)

  • The drive's serial number (SerialNumber property)

  • The type of file system the drive uses, such as FAT, FAT32, NTFS, and so forth (FileSystem property)

  • Whether a drive is available for use (IsReady property)

  • The name of the share and/or volume (ShareName and VolumeName properties)

  • The path or root folder of the drive (Path and RootFolder properties)

Working with Folders

Common folder tasks and the methods for performing them are described in the following table.

Task

Method

Create a folder.

FileSystemObject.CreateFolder

Delete a folder.

Folder.Delete or FileSystemObject.DeleteFolder

Move a folder.

Folder.Move or FileSystemObject.MoveFolder

Copy a folder.

Folder.Copy or FileSystemObject.CopyFolder

Retrieve the name of a folder.

Folder.Name

Find out if a folder exists on a drive.

FileSystemObject.FolderExists

Get an instance of an existing Folder object.

FileSystemObject.GetFolder

Find out the name of a folder's parent folder.

FileSystemObject.GetParentFolderName

Find out the path of system folders.

FileSystemObject.GetSpecialFolder

Working with Files

There are two major categories of file manipulation:

  • Creating, adding, or removing data, and reading files

  • Moving, copying, and deleting files

Creating Files

There are three ways to create an empty text file (sometimes referred to as a "text stream").

The first way is to use the CreateTextFile method. The following example demonstrates how to create a text file using this method in VBScript:

Dim fso, f1
Set fso = Servre.CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)

The second way to create a text file is to use the OpenTextFile method of the FileSystemObject object with the ForWriting flag set. In VBScript, the code looks like this example:

Dim fso, ts
Const ForWriting = 2
Set fso = Servre.CreateObject("Scripting. FileSystemObject")
Set ts = fso.OpenTextFile("c:\test.txt", ForWriting, True)

A third way to create a text file is to use the OpenAsTextStream method with the ForWriting flag set. For this method, use the following code

Dim fso, f1, ts
Const ForWriting = 2
Set fso = Server.CreateObject("Scripting.FileSystemObject")
fso.CreateTextFile ("c:\test1.txt")
Set f1 = fso.GetFile("c:\test1.txt")
Set ts = f1.OpenAsTextStream(ForWriting, True)

Adding Data to the File

Once the text file is created, add data to the file using the following three steps:

Open the text file.

Write the data.

Close the file.

To open an existing file, use either the OpenTextFile method of the FileSystemObject object or the OpenAsTextStream method of the File object.

To write data to the open text file, use the Write, WriteLine, or WriteBlankLines methods of the TextStream object, according to the tasks outlined in the following table.

Task

Method

Write data to an open text file without a trailing newline character.

Write

Write data to an open text file with a trailing newline character.

WriteLine

Write one or more blank lines to an open text file.

WriteBlankLines

 To close an open file, use the Close method of the TextStream object.

Note  The newline character contains a character or characters (depending on the operating system) to advance the cursor to the beginning of the next line (carriage return/line feed). Be aware that the end of some strings may already have such nonprinting characters.

The following VBScript example demonstrates how to open a file, use all three write methods to add data to the file, and then close the file:

Sub CreateFile()
   Dim  fso, tf
   Set fso = Server.CreateObject("Scripting.FileSystemObject")
   Set tf = fso.CreateTextFile("c:\testfile.txt", True)
   ' Write a line with a newline character.
   tf.WriteLine("Testing 1, 2, 3.") 
   ' Write three newline characters to the file.        
   tf.WriteBlankLines(3) 
   ' Write a line.
   tf.Write ("This is a test.") 
   tf.Close
End Sub

Reading Files

To read data from a text file, use the Read, ReadLine, or ReadAll method of the TextStream object. The following table describes which method to use for various tasks.

Task

Method

Read a specified number of characters from a file.

Read

Read an entire line (up to, but not including, the newline character).

ReadLine

Read the entire contents of a text file.

ReadAll

 If you use the Read or ReadLine method and want to skip to a particular portion of data, use the Skip or SkipLine method. The resulting text of the read methods is stored in a string which can be displayed in a control, parsed by string functions (such as Left, Right, and Mid), concatenated, and so forth.

The following VBScript example demonstrates how to open a file, write to it, and then read from it:

Sub ReadFiles
   Dim fso, f1, ts, s
   Const ForReading = 1
   Set fso = Server.CreateObject("Scripting.FileSystemObject")
   Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
   ' Write a line.
   Response.Write "Writing file <br>"
   f1.WriteLine "Hello World"
   f1.WriteBlankLines(1)
   f1.Close
   ' Read the contents of the file.
   Response.Write "Reading file <br>"
   Set ts = fso.OpenTextFile("c:\testfile.txt", ForReading)
   s = ts.ReadLine
   Response.Write "File contents = '" & s & "'"
   ts.Close
End Sub

Moving, Copying, and Deleting Files

The FSO object model has two methods each for moving, copying, and deleting files, as described in the following table.

Task

Method

Move a file

File.Move or FileSystemObject.MoveFile

Copy a file

File.Copy or FileSystemObject.CopyFile

Delete a file

File.Delete or FileSystemObject.DeleteFile

 

Dictionary Object
 
Description

Object that stores data key, item pairs.

Syntax

Scripting.Dictionary

Remarks

A Dictionary object is the equivalent of a PERL associative array. Items, which can be any form of data, are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually a integer or a string, but can be anything except an array.

The following code illustrates how to create a Dictionary object:

 
Dim d                   'Create a variable
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"     'Add some keys and items
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...
     Properties :
CompareMode Property

Count Property

Item Property

Key Property

             Methods:

Add Method
Exists Method
Items Method
Keys Method
Remove Method
RemoveAll Method

 

7.6- Managing Page Navigation :

The Content Linking component makes it easy for you to provide logical navigation through the .asp files in an application. Rather than maintaining URL references in a number of .asp files, you can specify the sequential organization of .asp files in a single, easy-to-edit text file.

 

The Content Linking component manages a list of URLs so that you can treat

the pages in your Web site like the pages in a book. You can use the Content

Linking component to generate and update automatically tables of contents and navigational links to previous and subsequent Web pages. This is ideal for

applications such as online newspapers and forum message listings.

 

 

The Content Linking component references a Content Linking List file that

contains the list of the linked Web pages. This list is stored on the Web server.

 

File Names
 
Nextlink.dll                     The Content Linking component.
Content Linking List       A text file that contains a list of Web pages in
the order in which they should be displayed.  This file must be available on a Web server virtual path.

 

Syntax

 

Set NextLink = Server.CreateObject("MSWC.Nextlink")

 

Methods

 

GetListCount                   Counts the number of items linked in the

                                                   Content Linking List file.

GetNextURL                   Gets the URL of the next page listed in the

                                         Content Linking List file.

GetPreviousDescription   Gets the description line of the previous page    

                                          listed in the Content Linking List file.

GetListIndex                     Returns the index of the current page in the                 

                                          Content Linking List file.

GetNthDescription            Gets the description of the Nth page listed in

                                           the Content Linking List file.

GetPreviousURL               Gets the URL of the previous pages listed in

                                           the Content Linking List file.

GetNextDescription          Gets the description of the next page listed in

                                          the Content Linking List file.

GetNthURL                      Gets the URL of the Nth page listed in the

                                          Content Linking List file.

 

 

 

 

 

The following example builds a table of contents.

 

<ol>

<%  Set NextLink = Server.CreateObject ("MSWC.NextLink") %> 

<%  count = NextLink.GetListCount ("/data/nextlink.txt") %>

<%  I = 1 %>

 

<ul>

<%  Do While (I <= count)  %> 

<li><a href=" <%= NextLink.GetNthURL ("/data/nextlink.txt", I)  %>  ">

<%= NextLink.GetNthDescription ("/data/nextlink.txt", I) %>  </a>

<%  I = (I + 1)  %> 

<%  Loop  %> 

 

</ul>

</ol>

 

 

The following script adds the next-page and previous-page buttons to an HTML

file.

 

<%  Set NextLink = Server.CreateObject ("MSWC.NextLink") %> 

<%  If (NextLink.GetListIndex ("/data/nextlink.txt") > 1) Then %>

 

<a href="  <%= NextLink.GetPreviousURL ("/data/nextlink.txt")  %>  ">

 

Previous Page</a>

<%  End If  %> 

<a href="  <%= NextLink.GetNextURL ("/data/nextlink.txt")  %>  ">Next Page</a>

 

The following example reads the link order from a text file and creates a table of contents on a single page.

 

<%

Set NextLink=Server.CreateObject("MSWC.NextLink")

count=NextLink.GetListCount("/Vroot/Nextlink.txt")

%>

<UL>

<% For i = 1 to count %>

<li><a href="<%=NextLink.GetNthUrl("/Vroot/Nextlink.txt",i) %>">

<%=NextLink.GetNthDescription("/Vroot/Nextlink.txt",i) %></a>

<% Next %>

 

 

7.7- Collaboration Data Objects for NTS Component:

 The Microsoft® CDO for NTS Library (Collaboration Data Objects for Windows NT® Server) version 1.2 exposes messaging objects for use by Microsoft® Visual Basic®, C/C++, Microsoft® Visual C++®, and Visual Basic Scripting Edition (VBScript) applications. The library lets you quickly and easily add to your application the ability to send and receive messages. You can create programmable messaging objects, then use their properties and methods to meet the needs of your application. This Object is an installed object in IIS4 and 5

 

The CDO for NTS Library is intended to run on a Microsoft® Windows NT® Server, for example from Active Server Pages (ASP) script on a Microsoft® Internet Information Server (IIS). It is not intended to run on a client process. No user dialog is invoked or supported by CDO for NT

 

Object

Purpose

AddressEntry

Specify addressing information for an individual messaging user.

 

 

Attachment

Associate an additional object with a message.

Attachments collection

Access all attachments on a message; create new attachments.

Folder

Open the default Inbox or Outbox folder in a message store.

Message

Compose, populate, send, and receive an e-mail document.

Messages collection

Access all messages in a folder; create new messages.

NewMail

Send a message without having to log on to a session.

Recipient

Specify information for a messaging user intended to receive a message.

Recipients collection

Access all recipients of a message; create new recipients.

Session

Establish a connection between an application and a messaging system.

 

NewMail Object (CDONTS Library)

The NewMail object provides for sending a message with very few lines of code.

Specified in type library:

CDONTS.DLL

First available in:

CDO for NTS Library version 1.2

Parent objects:

(none)

Child objects:

(none)

Default property:

Value

Properties

Bcc

Body

BodyFormat

Cc

ContentBase

ContentLocation

From

Importance

MailFormat

Subject

To

Value

Version

 

Methods :


Name


Parameters

AttachFile

Source as Object or String,
(optional) FileName as String,
(optional) EncodingMethod as Long

AttachURL

Source as Object or String,
ContentLocation as String,
(optional) ContentBase as String,
(optional) EncodingMethod as Long

 

 

Send

(optional) From as String,
(optional) To as String,
(optional) Subject as String,
(optional) Body as Object or String,
(optional) Importance as Long

SetLocaleIDs

CodePageID as Long

 

Remarks

The NewMail object's properties are not designed to be read back and inspected. With the sole exception of Version, they can only be written.

 Attachments and recipients, once added to the NewMail object, cannot be removed, and the NewMail object itself cannot be deleted. When the Send method completes successfully, the NewMail object is invalidated but not removed from memory. The programmer should Set the invalid object to Nothing to remove it from memory, or reassign it to another NewMail object. Attempted access to a sent NewMail object results in a return of CdoE_INVALID_OBJECT.

The NewMail object does not belong to the hierarchy encompassing the other CDO for NTS Library objects. It cannot access, nor can it be accessed from, any of the other objects. Like the Session object, it is considered a top-level object and is created directly from a Microsoft® Visual Basic® program. Its ProgID is CDONTS.NewMail. This code fragment creates a NewMail object through early binding:

 

 Dim objNewMail As CDONTS.NewMail

  Set objNewMail = CreateObject("CDONTS.NewMail")

 

The main advantage of the NewMail object is the ease and simplicity with which you can generate and send a message. You do not have to log on to a session nor deal with a folder or a messages collection. You have only to create the NewMail object, send it, and Set it to Nothing. You can supply critical information in the parameters of the Send method. In many cases you only need three lines of code:

 

  Set objNewMail = CreateObject("CDONTS.NewMail")

  objNewMail.Send("me@company.com", "you@company.com", "Hello", _

                  "I sent this in 3 statements!", 0) ' low importance

  Set objNewMail = Nothing ' canNOT reuse it for another message

 

Including an attachment can add as little as one statement to your code, because you can pass information in the parameters of the AttachFile method:

 

  Set objNewMail = CreateObject("CDONTS.NewMail")

  objNewMail.AttachFile("\\server\schedule\sched.xls", "SCHED.XLS")

  objNewMail.Send("Automated Schedule Generator", "you@company.com", 

                  "Schedule", "Here's the latest master schedule", 0)

  Set objNewMail = Nothing