Session E-ASP

Using Active Server Pages
 and Visual FoxPro

Rod Paddock
Dash Point Software, Inc.

This material is adapted from Application Developers Training Company's
Visual Interdev Class and is used with their permission.


Introduction

In this section you will learn about one of the newest and more powerful web technologies. Active Server Pages (ASP). ASP is a server side technology that gives developers the chance to develop web sites that are browser independent and highly scalable.

In this section you will learn:

What Is Active Server Pages ?

Recently Microsoft introduced a new technology known as Active Server Pages (ASP). Active server pages allows developers to embed scripting code into their web pages which will then be processed at the web server instead of at the browser. Active Server Pages can be found on your Visual Interdev CD and requires on of the following web servers

Why Do You Want To Use ASP ?

When you develop web sites you need to worry about two sides of the web connection. The client side and the server side. As a web developer you have no control over which client a user may have, but you do have control over your server. Active Server Pages allows you to create some very powerful and browser independent solutions as all of the scripting code is processed at the server. Another benefit of ASP is that the scripting code is processed at the server and cannot be seen by the browser.

Understanding ASP

There are three sets of components that comprise Active Serve Pages. These components are:

Server Side Scripting

The first component of active server pages is the server side scripting component. This component allows you to embed VBScript code into your web pages which in turn will be processed by the server. This scripting code is embedded into your Active Server Page (file with extension .ASP) with a new set of HTML tags. These tags are:

<% <VB Script Code Goes Here%>

and

<%= <Expression to be returned to web page goes here %>

The following HTML code demonstrates returning the time from the web server to the users browser.

<TITLE> ADTC Intermediate Class ASP Example 1</TITLE>

<H1>The current date and time are: <%=Now%>.</H1>

</HTML>

The example above demonstrated a single expression that was processed and returned to the users web browser. This was done by embedding the <%= %> tags into the HTML code. This method processed a single line of VB code. If you want to process multiple line of code you can use the <% %> tags. The following code demonstrates processing multiple lines of VB Script code.

<HTML>

<TITLE> ADTC Intermediate Class ASP Example 2</TITLE>

<%   

x = 100

y = 200

z = 300

myTotal = x * y * z

%>

The total amount is <%=myTotal%>

</HTML>

Server Side Objects

The second component of Active Server Pages is a set of server side objects. These objects provide extrap functionality that developers can use to create more robust web pages. These objects are very similar to OLE Objects as they present developers with sets of properties and methods that can be accessed from your scripts.

Server Side Components

Included with the five server side objects are a set of components that expand the abilities of developers. These components are:

"Now that you understand the components that are available to your scripts you
can being using the capabilities of these objects. The following sections show
how you can use the Request and Response objects to simplify the process of
web development.

Creating Active Server Pages

One of the most basic aspects of creating web sites is the idea of data entry forms. These forms allows users to input data that will then be processed by a web server. Commonly processing web forms has been the domain of the Common Gateway Interface (CGI). Active Server Pages steps into the place of CGI and provides a simpler mechanism for processing web data. Active Server Pages provides two objects that participate in the processing of web forms. These objects are the Request and Response objects.  The request object allows gives developers the ability to read information passed to a web page and process it accordingly. The response object gives developers the ability to manipulate a web page being returned to a user.

Using the Request Object

As said earlier the request object gives developers the ability to read information from a web form. There are two items that make this work. The first item is an HTML page that allows users to input data for processing by the web server. This web page's <FORM Action> tag must point to another active server page. The second item is the code in the active server page specified by the <FORM Action> tag. This page will use the request  object to read data from the passed in page.

The following HTML demonstrates a user name and password entry form. The contents of this form are then processed by the GETPASS.ASP file and returned to the browser.

<HTML>
<CENTER><H1>Enter Your User Name and Password </H1></CENTER>
<FORM action="getpass.asp" method = "post">
<TABLE>
<TR>
<TD align=right nowrap>User Name:</TD>
<TD><input type="text" value="" name="username" size=10></TD>
</TR>
<TR>
<TD align=right nowrap>Password:</TD>
<TD><input type="password" value="" name="password" size=10></TD>
</TR>
<TR><td><input type="submit" value="Login" name="login"></TD>
<TD><input type="reset" value="Reset" name="reset"></TD>
</TR>
</FORM>
</TABLE>
</HTML>

Pressing the Login button from this form will then send the contents of this form to the ASP file names GETPASS.ASP. The following code demonstrates how the GETPASS.ASP file will then read the contents of the ADTC3.ASP file and print them to the active server page.

<HTML>
<H1> The value you entered are:</H1>
<H1>User Name:<%=request.form("UserName")%></H1>
<H1>Password:<%=request.form("Password")%></H1>
</HTML>

As you can see the Active Server Page from above reads information from the web page by using the Request. object. The page accessed the data by using the Request.Form() collection. You can access the elements of this collection by using either the objects ordinal position in the collection or by using the NAME parameter of the form object. To access the data found in the user name field you would use the following syntax Request.Form("UserName").This syntax will read the value found in the UserName object passed to the GETPASS.ASP web page.

Using The Response Object

Where the Request object reads information from a passed in web page the response object allows developers to manipulate the results being returned to a web page. The following HTML shows how you can use the Request and Response objects together to route invalid passwords to another web page.

<HTML>
<%If request.Form("UserName") = "Mickey" and request.Form("Password") = "Mouse" Then
    Response.Write("<H1>Successful Login!!!</H1>")
    Response.Write("<H1>User Name:" & request.form("UserName") & "</H1>")
    Response.Write("<H1>Password:" & request.form("PassWord") & "</H1>")
  Else
    Response.Write("<H1>Invalid password or username!!!</H1>")
  End If
%>
</HTML>

Using The Browser Capabilities Component

One of the most difficult aspects of web development is the differences between different browsers. All browsers support different technologies. Some of the technologies they may or may not support include: frames, Java, VB Script, tables and HTML 3.2. Active Server Pages includes a special object that helps determine whether a browser supports various web technologies. This object is known as the Browser Capabilities component.  The following code demonstrates how to use the Browser Capabilities component:

<HTML>
<%Set myBrowse = Server.CreateObject("MSWC.BrowserType")%> 
ActiveXControls <%= mybrowse.activexcontrols %><br>
Backgroundsounds <%= mybrowse.backgroundsounds %><br>
Beta <%= mybrowse.beta %><br>
Browser <%= mybrowse.browser %><br>
Cookies <%= mybrowse.cookies %><br>
Frames <%= mybrowse.frames %><br>
Javascript <%= mybrowse.javascript %><br>
Platform <%= mybrowse.platform %><br>
Tables <%= mybrowse.tables %><br>
Vbscript <%= mybrowse.vbscript %><br>
Version <%= mybrowse.version %><br>
</HTML>

Note: This component reads information from a file called BROWSCAP.INI. This file contains a listing of browsers and capabilities found in each browser. If you find a new browser you may need to add it to this file.

Global Features

Another feature found in Active Server Pages are mechanisms for processing global code and setting up template HTML files These two mechanisms are known as:

GLOBAL.ASA

The first global feature to be examined is the GLOBAL.ASA file. This is a file that is processed at four different times. When an application begins or ends and when a user session begins or ends. You can process global code whenever one of these items begins. The format of the GLOBAL.ASA file is:

<SCRIPT RUNAT=Server Language=VBScript>

Sub Application_OnStart
End Sub

Sub Application_OnEnd
End Sub

Sub Session_OnStart
End Sub

Sub Session_OnEnd
End Sub

</SCRIPT>

To process code all you need to do is add code between the respective Sub/End Sub program lines.

Server Side Includes

The second technology that can be used globally is the idea of a set template files. These template files are known as Server Side Includes. To include a template file in your active server pages you use the following tag:

<!--#include file="inc.txt"-->

This tag will insert the text from the inc.txt file into the web pages. What would you use this construct for ? Some ideas include:

Using Active Server Components from ASP

Introduction

In the last sections you learned how to create basic Active Server Pages. You learned how to use the built in objects and components, how to configure ODBC and how to use Active Data Objects. In this chapter you will learn how to further extend your ASP sites with Active Servers. In this section you will learn:

What Are Active Servers ?

In a previous life Active Servers were known as OLE Automation servers. These servers were applications that presented a set of properties and methods that could be used by developers to "drive" other applications. You would use OLE Automation servers to automate mail-merges with WinWord or create graphs with Excel. A short time ago Microsoft recharted their integration strategies into the technology known as ActiveX. This integration strategy took with it many of the capabilities developed in OLE primarily OCX controls (now known as ActiveX controls) and OLE Automation (now Active Servers).

Why do you want to use Active Servers ?

The answer to this question lies in using the best tool for the job. While the scripting languages found in the various browsers and in Active Server Pages are very powerful they may not have all the functionality you need for your application. You may need to do some very sophisticated financial analysis, or you may want to present a graph to your user or you are developing three tiered applications where the middle tiers are comprised of Active Servers. In each of these cases you will need to use some other tool than the your respective scripting languages. This is where Active Servers come in.

Active Servers give you the ability to add powerful functionality to your web site using one of the more powerful languages such as C++, VB, Delphi or Visual FoxPro. Each of these different languages is capable of creating Active Servers that can be called from your site. Take a look…

Using the Server object

Calling Active Servers from your web pages is the domain of the Server object. This object is responsible for controlling the creation of objects on the server. You can instantiate Active Servers using the Server.CreateObject() method. This method will activate the Active Server on your web server making exposing its properties and methods to your Active Server Page.

Using Server.CreateObject

As said earlier the method responsible for creating an instance of an Active Server is Server.CreateObject. The syntax for this method is:

Set oMyObj = Server.CreateObject("<Registered Of Active Server>")

You can instantiate an instance of Microsoft Excel on your web site using the following code:

Set oExcel = Server.CreateObject("Excel.Application")

Once you have instantiated an object you can manipulate its methods and properties from your applications. The following code shows how you can return the information from an Excel Spreadsheet.

<HTML>
<%
Set oExcel = Server.CreateObject("Excel.Application")
oExcel.WorkBooks.Open("c:\inetpub\wwwroot\adtcexcl.xls")
%>
<TABLE>
<TR><TD><%=oExcel.Cells(1,1).Value%></TD></TR>
<TR><TD><%=oExcel.Cells(2,1).Value%></TD></TR>
<TR><TD><%=oExcel.Cells(3,1).Value%></TD></TR>
</TABLE>
</HTML>

Running this code will generate an error from a default IIS or PWS installation. The following illustration shows the error generated. This error is generated because by default IIS and PWS cannot create what are known as out-of-process servers. This problem and its solution is explained below.

In-Process vs Out of Process Servers

There are two basic styles of Active Servers: in-process and out-of-process. These styles have to do primarily with performance and stability of your website. In-Process servers allocate memory inside the memory space of the instantiating application out-of-process servers allocate memory in their own memory spaces and are communicated with using RPC (Remote Procedure Calls). The tradeoff between these two methods is between performance and stability. Because in-process servers share an applications memory space they are faster. At the same time if the in-process server fails it takes the applictaion with it. Looking at out-of-process server you can see that there is some overhead associated with the RPC mechanism used to communicate with the out-of-process server. This overhead gives this type of Active Server better stability in the event the server goes down it does not take the application with it. It is a common practice to develop your servers first as out-of-process servers and once they have been thoroughly tested turn them into an in-process server.

The following illustration shows how an in-process server works and how an out-of-process server works:

Configuring IIS and Personal Web Server

By default IIS and PWS are setup to only create in-process servers. To change this default behavior you need to manipulate the registry settings for the respective servers. To do this:

Once you have set this key value and restarted your machine you can hit the refresh button on your web browser and the contents of the web page will show up (see below)

Creating an Active Server With Visual FoxPro

Now that you understand the process of instantiating an Active Server from your web sites you can go about the process of creating your own server using a language like Visual FoxPro.

The creation of a COM object in Visual FoxPro is simple. Enter the following code into a new program file.

Define Class myClass as Custom OLEPUBLIC

dTodaysDate = DATE()

Function GetFullDate

Return Cmonth(DATE()) + " " + Alltrim(Str(day(date()),2,0)) + "," + STR(YEAR(DATE()),4,0)

EndDefine

Add the program you created to a project file and build it. You now have a COM server that can be accessed from a web page.

Adding the Server To Your Page

Now that you have created your server you can begin accessing it from your Active Server Pages using Server.CreateObject(). The following code shows how to call your active server from your web page.

<HTML>
<TITLE> ADTC Active Server Example</TITLE>
<%
Set oMyServer = Server.CreateObject("MYSERVER.MYCLASS")
%>
<%= oMyServer.dTodaysDate %>
<%= oMyServer.GetFullDate()%>
</HTML>

Now for something you'll all like…

The following VFP code and corresponding ASP page show how you can access data in VFP and from your web pages:

Here's the FoxPro Code

*-- this code generates a payment amortization schedule.

Define class PaymentEngine as Custom OLEPUBLIC

nPrincipal = 0
nInterestRate = 0
nYears = 0
Declare aAmortTable[1]
nAmortLines = 0
Function GetPayment

Local lnConvertedInterest
lnConvertedInterest = This.nInterestRate /100

Return Payment(This.nPrincipal,lnConvertedInterest/12,This.nYears * 12)

Function Amort

*-- Get the payment
lnPayment = This.GetPayment()

*-- Get the interest
Local lnConvertedInterest
lnConvertedInterest = This.nInterestRate /100

Create cursor c_amort (payment_number i, start_balance n(15,2), interest n(15,2), applied_to_principal n(15,2), remaining_balance n(15,2), payment n(12,2))

lnBalance = This.nPrincipal

*-- Insert payments
For lnKount = 1 to This.nYears * 12
  *-- Calculate interest
  lnInterest  = Round(lnBalance * (lnConvertedInterest/12),2)

  *-- Calculate principal
  lnPrincipal = lnPayment - lnInterest

  Insert into c_amort Values (lnKount, lnBalance, lnInterest, lnPrinciPal, lnBalance - lnPrincipal,0)

  *-- Check digit

  Replace c_amort.payment with c_amort.interest + c_amort.applied_to_principal
  lnBalance = lnBalance - (lnPayment - lnInterest)
EndFor

Select * From c_amort Into Array This.aAmortTable

This.nAmortLines = Reccount("c_amort")

EndFunc

EndDefine

Here's the HTML

<HTML>
<form action="payment.asp" method = "post">
<table>
<tr>
<td align=right nowrap>Principal Borrowed:</td>
<td><input type="text" value="" name="principal" size=30></td>
</tr>
<tr>
<td align=right nowrap>Interest Rate (ex. 7.5):</td>
<td><input type="text" value="" name="interest_rate" size=5></td>
</tr>
<tr>
<td align=right>Years of Loan:</td>
<td><input type="text" value="" name="years" size=5></td>
</tr>
<tr><td><input type="submit" value="Calculate" name="submit"></td>
<td><input type="reset" value="Reset" name="reset"></td></tr>
</HTML>

Here's the ASP Code

<HTML>
<%

If request("principal") = "" or request("interest_rate") = "" or request("years") = "" then
  Response.Write("<H1>Please make sure all items are filled in.</H1>")
Else
  Set oPayment = Createobject("payment_engine.paymentEngine")
  oPayment.nPrincipal    = Clng(request("principal"))
  oPayment.nInterestRate = Clng(request("interest_rate"))
  oPayment.nYears         = Clng(request("years"))
  response.write("<H1>The Payment is:" & oPayment.Getpayment() & "</H1>")
  oPayment.Amort()
  response.write("<H2>Amort Table</H2>")
  response.Write("<TABLE Border=1>")
  response.Write("<TR><TH>Payment #</TH><TH>Start Principal</TH><TH>Interest Paid</TH><TH>Principal Paid</TH><TH>Balance</TH></TR>")
  For lnKount = 1 to oPayment.nAmortLines
    strString = "<TR>"
    For lnKount2 = 1 to 5
      strString = strString & "<TD>" & oPayment.aAmortTable(lnKount,lnKount2) & "</TD>"
    Next
    strString = strString & "</TR>"
    response.Write(strString)
  Next
  response.Write("</TABLE>")
End If
%>
</HTML>

Some of the other things you could do with this technology include:

Basically any functionality that VFP posesses you can add to your web sites

Conclusion

As you can see there are no bounds when you equip your web site with ASP site and Active Servers. In this session you learned: