Using Microsoft® Component Object Model (COM) components in your ASP pages can dramatically extend the power that ASP already offers. COM components are pieces of compiled code that can be called from ASP pages. COM components are secure, compact, reusable objects that are compiled as DLLs and can be written in Microsoft Visual C++®, Microsoft Visual Basic®, or any language that supports COM. For example, Microsoft ActiveX® Data Objects (ADO), which are used in Module 1 of this tutorial, provides you with methods and properties to efficiently query databases. By using ADO, you don't have to write your own complex data access code because ADO objects are built using COM components.
In this module, you use COM components that are included with ASP, and you also have a chance to write one of your own. This module shows how to develop an ASP page that delivers services useful in e-commerce and includes the following lessons:
Advertising is big business on the Web. This lesson describes how to use the Ad Rotator component, installed with IIS, to rotate advertisements on your Web pages. The Ad Rotator component selects an advertisement for your Web page each time the user loads or refreshes the Web page. Furthermore, if you want to change an advertisement, you only need to change it in the redirection and rotation schedule files, instead of changing all the ASP files that contain the advertisement. This saves development time if the advertisement appears on numerous pages within your Web site.
Two files are required to set up the Ad Rotator component: a redirection file, which contains URL links to ads, and a rotation schedule file, which contains display data. By setting up these two files, the Ad Rotator component can be called by any ASP page on your Web site.
In this lesson you perform the following tasks:
A rotation schedule file is used to catalog information about the ads you want to display, including redirection information after the advertisement is clicked on, the size of the displayed advertisement, the image to display, a comment for the advertisement, and a number that indicates how often a particular advertisement is chosen. When methods of the Ad Rotator component are called in an ASP page, the component uses this file to select an advertisement to display.
The rotation schedule file is divided into two sections that are separated by an asterisk (*). The first section provides information common to all the ads, and the second section lists specific data for each ad. To test the rotation schedule file, you will use some images from Microsoft.com for your ad images. The following list outlines the structure of the rotation schedule file:
You need to complete the following for each advertisement:
Copy and paste the following code in your text editor, and save the file as MyAdRot.txt in the x:\Inetpub\Wwwroot\Tutorial directory.
REDIRECT AdRotRedirect.asp
WIDTH 250
HEIGHT 60
BORDER 0
*
http://www.microsoft.com/windows/images/bnrWinfam.gif
http://www.microsoft.com/windows
Microsoft Windows
2
http://www.microsoft.com/office/images/office_logo.gif
http://www.microsoft.com/office
Office 2000
3
When a user clicks on an advertisement, an Ad Rotator redirection file written in ASP can capture some information before showing the advertisement and write that information to a file.
For this to work, the x:\InetPub\Wwwroot\Tutorial folder must give Read/Write access to the IUSR_ComputerName and IWAM_ComputerName accounts. Alternatively, you can write this information to a Microsoft Access database using the code from Lesson 3 in Module 1 of this tutorial.
Copy and paste the following code in your text editor, and save the file as AdRotRedirect.asp in the x:\Inetpub\Wwwroot\Tutorial directory.
<%@ Language=VBScript %>
<html>
<head>
<title>AdRotRedirect file</title>
</head>
<body>
<%
'Create some variables.
dim strLogFile
'Get the physical path of this Web directory so that we know the path exists.
'The ASP Server object has many useful methods.
strLogFile = Server.MapPath(".") &
"\AdRotLog.txt"
'Set some constants for working with files.
Const cForAppending = 8
Const
cTristateUseDefault = -2
'Create a FileSystemObject object,
' which gives you access to files and folders on the system.
Set fsoObject =
Server.CreateObject("Scripting.FileSystemObject")
'Open a
handle to the file.
'True means that the file will be created
if it doesn't already exist.
Set tsObject =
fsoObject.OpenTextFile(strLogFile, cForAppending, True)
'Record the data for the user who has just clicked on an advertisement.
'We have used the Write method of the ASP Request object.
'The ServerVariables collection of the ASP Request object holds vast
' amounts of data for
each request made to a Web server.
tsObject.WriteLine "--------------------"
tsObject.WriteLine
Date & ", " & Time
tsObject.WriteLine
Request.ServerVariables("LOGON_USER")
tsObject.WriteLine
Request.ServerVariables("REMOTE_ADDR")
tsObject.WriteLine
Request.QueryString("url")
tsObject.WriteLine
Request.ServerVariables("HTTP_REFERER")
tsObject.WriteLine
Request.ServerVariables("HTTP_USER_AGENT")
tsObject.Close
'Redirect to the Advertiser's Web site using the Redirect
method
' of the ASP Response object.
'When the
AdRotator component calls AdRotRedirect.asp, it
'
automatically passes in the advertiser's URL in the QueryString.
Response.Redirect Request.QueryString("url")
%>
</body>
</html>
Include files are used to store any code that will be used by more than one ASP or HTML file. It makes sense to put your Ad Rotator code into a simple function in an include file. With an Ad Rotator include file, you need to make only one function call from any ASP or HTML file when you want to display an advertisement. Alternatively, you can put the code from the include file in every ASP file where you plan to show an advertisement. However, if you want to change that code, you have to make the change in every ASP file instead of in one include file.
In this example, you create an Ad Rotator include file containing a function named GetAd. This function randomly selects ads to display on your ASP pages.
Copy and paste the following code in your text editor, and save the file as AdRotatorLogic.inc in the x:\Inetpub\Wwwroot\Tutorial directory.
<%
Function GetAd()
dim objLoad
'Create an instance of the AdRotator component.
Set
objLoad = Server.CreateObject("MSWC.AdRotator")
'Set the TargetFrame property, if any. If you have a Web
' page using frames, this is the frame where the
URL opens.
'If the HTML page does not find the
TARGET name,
' the URL will be opened in a new
window.
objLoad.TargetFrame = "TARGET=new"
'Set one of the other AdRotator properties.
objLoad.Border = 1
'Get a random advertisement from the text file.
GetAd = objLoad.GetAdvertisement("MyAdRot.txt")
End
Function
%>
To test the application you have built on the Ad Rotator component, you need an ASP page that calls the function in the Ad Rotator include file you created.
Copy and paste the following code in your text editor, and save the file as DisplayAds.asp in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your browser by typing http://localhost/Tutorial/DisplayAds.asp in the address bar.
<%@ Language=VBScript %>
<html>
<head>
<title>Display an Advertisement</title>
</head>
<body>
<font
face="MS Gothic">
<h2>Display an Advertisement</h2>
<comment>Include the file you created to get an
advertisement.</comment>
<!-- #include File =
"AdRotatorLogic.inc" -->
<comment>Call the Function in
the include file.</comment>
<%=GetAd()%>
</font>
</body>
</html>
In the browser, you should see the following:
Display an Advertisement
Click the Refresh button in your browser about 20 times to watch the advertisement change. Click the advertisement to see how AdRotRedirect.asp redirects you to the advertiser's Web site. Open AdRotLog.txt to see what was recorded when you clicked on an advertisement.
It may be useful to know how many times someone requests, or hits, your Web pages. Sites with high traffic may attract more advertising revenue for you. Some Web sites use this data to charge advertisers a flat fee per hit. Traffic information also indicates how customers are navigating through your site and where ads should be placed. And pages that never seem to be hit might indicate that design changes are needed.
The PageCounter component uses an internal object to record Web page hits on the server. At regular intervals, PageCounter saves all information to a text file so that no counts are lost due to power loss or system failure. The PageCounter component uses three methods, as follows:
Copy and paste the following code in your text editor, and save the file as PageCounter.asp in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your browser by typing http://localhost/Tutorial/PageCounter.asp in the address bar.
<%@ Language=VBScript %>
<html>
<head>
<title>Page Counter Example</title>
</head>
<body>
<font face="MS
Gothic">
<H3>Page Counter Example</H3>
<p>
<FORM NAME="PageCounter" METHOD="GET"
ACTION="PageCounter.asp">
<INPUT TYPE="CHECKBOX" NAME="reset"
VALUE="True">Reset the Counter for this page?<BR>
<INPUT
TYPE="SUBMIT" VALUE="Submit">
</FORM>
</p>
<%
'Instantiate the PageCounter object.
Set MyPageCounter = Server.CreateObject("MSWC.PageCounter")
'Increment the counter for this page.
MyPageCounter.PageHit
If Request.QueryString("reset") =
"True" Then
'Reset the counter for this page.
MyPageCounter.Reset("/Tutorial/PageCounter.asp")
End If
%>
Hits to this page =
<%=MyPageCounter.Hits %><BR>
</font>
</body>
</html>
In the browser, you should see the following:
Hits to this page = 1 Page Counter Example
Click the Refresh button in your browser or the Submit button on the page to watch the hit count grow. Check the box if you want to reset the counter.
In this lesson, you use Visual Basic to create a simple COM object, which you can call from an ASP page. This example requires Visual Basic with the ActiveX Wizard, and it is not supported on 64-bit platforms until the Visual Basic runtime is developed for 64-bit platforms. You create a 32-bit COM object that runs on a 64-bit platform, but you must call the 32-bit COM object from a 32-bit application. Because IIS is a 64-bit application on 64-bit platforms, it cannot call 32-bit objects.
Suppose you want to create a Web application that needs functionality VBScript does not have. In this case, you must create a custom procedure that is called, as needed, from any ASP page in your application.
Normally, this approach is an adequate solution for encapsulating custom functionality. However, imagine that you are creating a Web application intended to service thousands of users and that your procedure encapsulates proprietary functions you do not want other people to see. In this case, encapsulating your functionality in the form of a COM component is a superior approach. Components provide better security and performance than scripts because they are compiled code. Components also allow you to use functionality provided by Visual Basic, C++, Java, or any of the other COM-compliant languages.
The ActiveX DLL Wizard of Visual Basic is the easiest way to create a COM component. You can also use Microsoft Visual C++ to create a COM component, either by using the Active Template Library (ATL) or by writing all the code yourself. This example uses Visual Basic.
In this lesson, you learn how to create and encapsulate a Visual Basic function as a component. Visual Basic includes many financial functions not available to VBScript. This example computes the future value of an investment based on a fixed interest rate and periodic, fixed payments.
Option Explicit
'Declare the
global variables that will be set by the Property functions.
Dim
gAnnualIntRate As Double
Dim gNumPayPeriods As Integer
Dim gPayment As
Double
Dim gPresentSavings As Variant 'Optional
Dim gWhenDue As Variant
'Optional
Public Function CalcFutureValue() As Double
'The global variables you pass to the FV function are set
'when user
sets the properties in the ASP page.
'You could pass variables into
the CalcFutureValue() function
'if you wanted to avoid using
properties.
'CalcFutureValue becomes a method in your
component.
Dim IntRatePerPeriod As Double
Dim
FullFutureValue As Double
If (gAnnualIntRate = Null) Or
(gNumPayPeriods = Null) Or (gPayment = Null) Then
CalcFutureValue = 0
Else
IntRatePerPeriod =
gAnnualIntRate / 100 / 12
FullFutureValue =
FV(IntRatePerPeriod, gNumPayPeriods, gPayment, gPresentSavings,
gWhenDue)
CalcFutureValue = Round(FullFutureValue,
2)
End If
End Function
Public Property Get
AnnualIntRate() As Double
'Get functions return the value of the
global variables
'as if they were properties.
'In your
ASP page, you might say x = oASPTut.Rate.
AnnualIntRate =
gAnnualIntRate
End Property
Public Property Let AnnualIntRate(ByVal
vAnnualIntRate As Double)
'Let functions set the global variables
when your ASP page
'makes a call such as oASPTut.Rate = 5.
gAnnualIntRate = vAnnualIntRate
End Property
Public Property Get
NumPayPeriods() As Integer
NumPayPeriods = gNumPayPeriods
End
Property
Public Property Let NumPayPeriods(ByVal vNumPayPeriods As
Integer)
gNumPayPeriods = vNumPayPeriods
End
Property
Public Property Get Payment() As Double
Payment =
gPayment
End Property
Public Property Let Payment(ByVal vPayment As
Double)
gPayment = -(vPayment)
End Property
Public
Property Get PresentSavings() As Variant
PresentSavings =
gPresentSavings
End Property
Public Property Let
PresentSavings(ByVal vPresentSavings As Variant)
gPresentSavings =
-(vPresentSavings)
End Property
Public Property Get WhenDue() As
Variant
WhenDue = gWhenDue
End Property
Public Property
Let WhenDue(ByVal vWhenDue As Variant)
gWhenDue = vWhenDue
End
Property
This example ASP page uses a form to read in user data, creates an instance of your object, and calculates the future value of your savings plan.
Copy and paste the following code in your text editor, and save the file as CalculateFutureValue.asp in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your browser by typing http://localhost/Tutorial/CalculateFutureValue.asp in the address bar.
<%@ Language=VBScript %>
<%
Response.Expires = 0
Payment = Request.Form("Payment")
AnnualIntRate = Request.Form("AnnualIntRate")
NumPayPeriods =
Request.Form("NumPayPeriods")
WhenDue =
Request.Form("WhenDue")
PresentSavings =
Request.Form("PresentSavings")
%>
<HTML>
<HEAD><TITLE>Future Value
Calculation</TITLE></HEAD>
<BODY>
<FONT
FACE="MS Gothic">
<H2 align=center>Calculate the Future
Value of a Savings Plan</H2>
<FORM METHOD=POST
ACTION="calculatefuturevalue.asp">
<TABLE cellpadding=4
align=center>
<TR>
<TD>How much do you
plan to save each month?</TD>
<TD><INPUT TYPE=TEXT
NAME=Payment VALUE=<%=Payment%>> (Required)</TD>
</TR><TR>
<TD>Enter the annual interest
rate.</TD>
<TD><INPUT TYPE=TEXT NAME=AnnualIntRate
VALUE=<%=AnnualIntRate%>> (Required)</TD>
</TR><TR>
<TD>For how many months will you
save?</TD>
<TD><INPUT TYPE=TEXT NAME=NumPayPeriods
VALUE=<%=NumPayPeriods%>> (Required)</TD>
</TR><TR>
<TD>When do you make payments in the
month? </TD>
<TD><INPUT TYPE=RADIO NAME=WhenDue VALUE=1
<%If 1=WhenDue Then Response.Write"CHECKED"%>>Beginning
<INPUT TYPE=RADIO NAME=WhenDue VALUE=0 <%If 0=WhenDue Then
Response.Write"CHECKED"%>>End </TD>
</TR><TR>
<TD>How much is in this savings
account now?</TD>
<TD><INPUT TYPE=TEXT
NAME=PresentSavings VALUE=<%=PresentSavings%>> </TD>
</TR>
</TABLE>
<P align=center><INPUT
TYPE=SUBMIT VALUE=" Calculate Future Value ">
</FORM>
<%
If ("" = Payment) Or ("" =
AnnualIntRate) Or ("" = NumPayPeriods) Then
Response.Write "<H3 align=center>No valid input entered
yet.</H3>"
ElseIf (IsNumeric(Payment)) And
(IsNumeric(AnnualIntRate)) And (IsNumeric(NumPayPeriods))
Then
Dim FutureValue
Set oASPTut
= Server.CreateObject("ASPTut.Finance")
oASPTut.AnnualIntRate = CDbl(AnnualIntRate)
oASPTut.NumPayPeriods = CInt(NumPayPeriods)
oASPTut.Payment = CDbl(Payment)
If Not "" = PresentSavings
Then oASPTut.PresentSavings = CDbl(PresentSavings)
oASPTut.WhenDue = WhenDue
FutureValue =
oASPTut.CalcFutureValue
Response.Write "<H3
align=center>Future value = $" & FutureValue &
"</H3>"
Else
Response.Write
"<H3 align=center>Some of your values are not
numbers.</H3>"
End If
%>
</FONT>
</BODY>
</HTML>
In the browser, you should see the following:
Calculate the Future Value of a Savings Plan
No valid input entered yet.
In this lesson, you use Microsoft® Visual J++® to create a COM object which does the same thing as the Visual Basic component in Lesson 3. This step requires Visual J++ 6.0 or later.
public class
ASPTut
{
}
public double CalcFutureValue(
double
dblAnnualIntRate,
double dblNumPayPeriods,
double
dblPayment,
double dblPresentSavings,
boolean
bWhenDue)
{
double dblRet, dblTemp, dblTemp2, dblTemp3,
dblIntRate;
if (dblAnnualIntRate == 0.0)
{
dblRet = -dblPresentSavings - dblPayment *
dblNumPayPeriods;
}
else
{
dblIntRate = dblAnnualIntRate / 100 / 12;
dblPayment =
-dblPayment;
dblPresentSavings =
-dblPresentSavings;
dblTemp = (bWhenDue ? 1.0 +
dblIntRate : 1.0);
dblTemp3 = 1.0 +
dblIntRate;
dblTemp2 = Math.pow(dblTemp3,
dblNumPayPeriods);
dblRet = -dblPresentSavings *
dblTemp2 - dblPayment * dblTemp * (dblTemp2 - 1.0) / dblIntRate;
}
return dblRet;
}
This example ASP page uses a form to read in user data, creates an instance of your object, and calculates the future value of your savings plan. This example uses JScript, but you can call a Java component from VBScript as well.
Copy and paste the following code in your text editor, and save the file as CalculateFutureValueJava.asp in the x:\Inetpub\wwwroot\Tutorial directory. View the example with your browser by typing http://localhost/Tutorial/CalculateFutureValueJava.asp in the address bar.
<%@ Language=JScript
%>
<%
Response.Expires = 0;
Payment =
Request.Form("Payment");
AnnualIntRate =
Request.Form("AnnualIntRate");
NumPayPeriods
= Request.Form("NumPayPeriods");
WhenDue =
Request.Form("WhenDue");
PresentSavings =
Request.Form("PresentSavings");
%>
<HTML>
<HEAD><TITLE>Future Value Calculation -
Java</TITLE></HEAD>
<BODY>
<FONT FACE="MS
Gothic">
<H2
align=center>Calculate the Future Value of a Savings
Plan</H2>
<FORM
METHOD=POST
ACTION="calculatefuturevaluejava.asp">
<TABLE cellpadding=4
align=center>
<TR>
<TD>How much
do you plan to save each month?</TD>
<TD><INPUT TYPE=TEXT NAME=Payment
VALUE=<%=Payment%>> (Required)</TD>
</TR><TR>
<TD>Enter the annual interest
rate.</TD>
<TD><INPUT
TYPE=TEXT NAME=AnnualIntRate VALUE=<%=AnnualIntRate%>>
(Required)</TD>
</TR><TR>
<TD>For how many months will you
save?</TD>
<TD><INPUT
TYPE=TEXT NAME=NumPayPeriods VALUE=<%=NumPayPeriods%>>
(Required)</TD>
</TR><TR>
<TD>When do you make payments in the month?
</TD>
<TD><INPUT TYPE=RADIO
NAME=WhenDue VALUE=1 <%if (1==WhenDue)
Response.Write("CHECKED")%>>Beginning
<INPUT TYPE=RADIO NAME=WhenDue VALUE=0 <%if (0==WhenDue)
Response.Write("CHECKED")%>>End </TD>
</TR><TR>
<TD>How much is in this savings account
now?</TD>
<TD><INPUT
TYPE=TEXT NAME=PresentSavings VALUE=<%=PresentSavings%>>
</TD>
</TR>
</TABLE>
<P
align=center><INPUT TYPE=SUBMIT VALUE=" Calculate Future Value
">
</FORM>
<%
if (("" == Payment)
|| ("" == AnnualIntRate) || ("" == NumPayPeriods)) {
Response.Write("<H3 align=center>No valid input
entered yet.</H3>");
} else
{
AnnualIntRate =
parseFloat(AnnualIntRate)
NumPayPeriods = parseFloat(NumPayPeriods)
Payment = parseFloat(Payment)
if ("" != PresentSavings) PresentSavings =
parseFloat(PresentSavings);
if
((isNaN(Payment)) || (isNaN(AnnualIntRate)) || (isNaN(NumPayPeriods)))
{
Response.Write("<H3
align=center>Some of your values are not
numbers.</H3>");
} else
{
var FutureValue,
Cents;
var oASPTut =
Server.CreateObject("MS.ASPTut.Java");
FutureValue = oASPTut.CalcFutureValue(AnnualIntRate, NumPayPeriods,
Payment, PresentSavings, WhenDue);
Response.Write("<H3 align=center>Future value = $" +
parseInt(FutureValue) + "</H3>");
}
}
%>
</FONT>
</BODY>
</HTML>
In the browser, you should see the following content, which should be identical to the display generated using the Visual Basic component in Lesson 3 of this module:
Calculate the Future Value of a Savings Plan
No valid input entered yet.