Creating ActiveX Components

In this section, we'll create an ActiveX server-side component using Visual Basic 6.0 and then create an ASP Web page to call the component. The example component that we'll create will be used for the Loan Calculator in our VI-Bank sample application. The Loan Calculator calculates the monthly payment on a loan given the annual percentage rate, the principal amount of the loan, and the term of the loan in number of months.

Creating an ActiveX Component

First run Visual Basic 6.0 and choose to create an ActiveX DLL project from the New Project dialog box, as shown in Figure 18-1. Next enter the code in Figure 18-2 into the class module.

click to view at full size.

Figure 18-1. The New Project dialog box within Visual Basic 6.0 showing an ActiveX DLL project.

Figure 18-2. The financial.cls class module within the VI-Bank.vbp project. The Payment method determines the monthly payment on a loan.

' Filename: Financial.cls (VI-Bank.vbp) ' ' Description: Financial Class ' ' This file is provided as part of the "Programming Visual ' InterDev 6.0" CD-ROM ' ' THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT ' WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, ' INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES ' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR ' PURPOSE. ' ' Copyright (C) 1998 Microsoft Corporation, All rights reserved Option Explicit Private Const APP_ERROR = -2147467008 Public Function Payment(ByVal NumMonths As Integer, _     APR As Double, Principal As Double)     Dim strResult As String          On Error GoTo ErrorHandler              ' Check for zeros     If NumMonths = 0 Then         Err.Raise Number:=APP_ERROR, Description:= _             "Please enter a non-zero value for the number of months"     End If     If APR = 0 Then         Err.Raise Number:=APP_ERROR, Description:= _             "Please enter a non-zero value for the APR."     End If     If Principal = 0 Then         Err.Raise Number:=APP_ERROR, Description:= _             "Please enter a non-zero value for principal."     End If          ' Convert APR from a percentage to a decimal     APR = APR / 100#          ' Convert APR to a monthly percentage rate     APR = APR / 12#     ' Check that we don't divide by zero     If (((1 + APR) ^ NumMonths) - 1) = 0 Then         Err.Raise Number:=APP_ERROR, Description:= _             "Division by zero. Please retry with different inputs."     Else         Payment = Principal * (APR * ((1 + APR) ^ NumMonths)) / _             (((1 + APR) ^ NumMonths) - 1)     End If      Exit Function ErrorHandler:          Payment = -1 ' indicate that an error occurred          Err.Raise Err.Number, "VIBank.Financial.Payment", _         Err.Description      End Function 

Alternatively, you can access the code for this example on the CD-ROM under the VI-Bank/VB98 folder in a Visual Basic 6.0 project named VI-Bank.vbp. After opening this project file and selecting the Financial class module, you should see a screen similar to that shown in Figure 18-3.

click to view at full size.

Figure 18-3. The Visual Basic 6.0 development environment showing the financial.cls class module within the VI-Bank.vbp project.

The code in the financial.cls class module shown in Figure 18-2 defines a function called Payment. Payment is a simple function that takes three parameters as input (the principal, the APR, and the term of the loan) and calculates the monthly payment on the loan. This is a simple example that could easily be extended by adding more functions into the same class module. By doing this, you would have a powerful financial component with a variety of functions that can be reused across multiple applications.

If you are creating your own Visual Basic 6.0 ActiveX DLL project, you'll also want to go into the Project Properties dialog box (by choosing Properties from the Project menu) and mark the project for Unattended Execution, as shown in Figure 18-4. In the case of our example project, this setting is already stored in the project file on the CD-ROM. To compile an ActiveX DLL for your project, simply choose Make from the File menu.

Figure 18-4. The Project Properties dialog box within Visual Basic 6.0 showing the Unattended Execution check box.

After compiling the project to make an ActiveX DLL (vibank.dll), you'll want to stage it on your Web server. If you are simply developing on a single machine and your copy of Visual Basic is on the same machine as your Web server, you won't need to stage the component—having compiled the component inside Visual Basic will have already registered the component on your machine for you. If you want to stage the component on another machine, see the "Deploying ActiveX Components" section later in this chapter.

Calling the ActiveX Component from ASP

To call an ActiveX component from an ASP Web page, simply use the Server.CreateObject syntax to instantiate the object and then reference its methods. Here is an example:

 <% Dim oFinancial Set oFinancial = Server.CreateObject("VIBank.Financial") MonthlyPayment = oFinancial.Payment(36, 7.5, 10000) Response.Write "Monthly Payment is '" + _     FormatCurrency(MonthlyPayment) + "'.<p>" %> 

This code instantiates the Financial object of the VIBank component and then executes the Payment method. The resulting value from the method is stored in the MonthlyPayment variable. Finally, the value of the MonthlyPayment variable is converted to currency format using the FormatCurrency function and is then output to the browser using the Response.Write syntax.

Instead of using Server.CreateObject, you can also use an <OBJECT> tag in which you specify the attribute RUNAT=SERVER. Creating an <OBJECT> tag allows you to reference the object in any server script on the page and adds the object and its members to the Microsoft IntelliSense statement completion drop-down list. For example, the following creates an object reference to the Financial object:

 <OBJECT RUNAT="Server" ID=oFinancial     PROGID="VIBank.Financial"> </OBJECT> 

In your script, you can reference this object by using the name you assigned in the ID attribute. The following statement uses the object defined in the <OBJECT> block:

 MonthlyPayment = oFinancial.Payment(36, 7.5, 10000) 

Figure 18-5 shows the IntelliSense statement completion drop-down list for the Payment method.

click to view at full size.

Figure 18-5. The Visual InterDev 6.0 IDE showing an ASP Web page with IntelliSense statement completion for the Payment method of the Financial object.

To continue our ActiveX component example, we'll look at the entire ASP Web page that calls the Payment method. The ASP Web page presents the user with a form for entering three values for principal, annual percentage rate, and number of months for a loan. It is also a self-posting ASP Web page so that when the user clicks the Calculate button, the page is reloaded, the monthly loan payment amount is calculated (by calling the component), and the results are presented to the user on the same page. The code in Figure 18-6 shows the relevant page, named loan.asp, which is in the VI-Bank/VIntDev98 folder on the CD-ROM.

Figure 18-6. The loan.asp page, which calls the Payment method of the Financial object. The page is a self-posting ASP Web page that both captures input values and displays results.

 <html> <head> <meta NAME="GENERATOR" Content="Microsoft Visual Studio 6.0"> <title>VI-Bank - Loan Calculator</title> <LINK REL="stylesheet" TYPE="text/css"      HREF="_Themes/blueprnt/THEME.CSS"      VI6.0THEME="Blueprint"> <LINK REL="stylesheet" TYPE="text/css"      HREF="_Themes/blueprnt/GRAPH0.CSS"      VI6.0THEME="Blueprint"> <LINK REL="stylesheet" TYPE="text/css"      HREF="_Themes/blueprnt/COLOR0.CSS"      VI6.0THEME="Blueprint"> <LINK REL="stylesheet" TYPE="text/css"      HREF="_Themes/blueprnt/CUSTOM.CSS"      VI6.0THEME="Blueprint"></head> <body> <table> <tr valign=top> <td width=125> <!--#INCLUDE FILE="menu.htm"--> </td> <td> <h2><FONT COLOR="navy">     <I>VI-Bank - Loan Calculator</I> </FONT></h2> <hr color=navy> <p> <form METHOD="post" ACTION="loan.asp"> <table border="1" cellPadding="3" cellSpacing="1" width="350"> <tr> <td><font face ="" size="2">Number of Months:</font></td> <td><font face ="" size="2">     <input id="NumMonths" name="NumMonths" size="15"> </font></td> </tr> <tr> <td><font face ="" size="2">Annual Percentage Rate (APR): </font></td> <td><font face ="" size="2">     <input id="APR" name="APR" size="15"> </font></td> </tr> <tr> <td><font face ="" size="2">Principal:</font></td> <td>><font face ="" size="2">     <input id="Principal" name="Principal" size="15"> </font></td> </tr> </table> <P> <table width="350"> <tr><td> <div align="center"><input id="submit" name="submit"      type="submit" value="Calculate"></div> </td></tr> </table> </form> <hr> <%  RequestMethod = Request.ServerVariables("REQUEST_METHOD") If RequestMethod = "POST" THEN %> <OBJECT id=oFinancial RUNAT=server PROGID=VIBank.Financial> </OBJECT> <% MonthlyPayment = oFinancial.Payment(CInt(Request.Form("NumMonths")),     CDbl(Request.Form("APR")), CDbl(Request.Form("Principal")))  %> <p> <table BORDER="1" width="350"> <tr><td> <font face ="" size="2"> On a loan for <%=FormatCurrency(Request.Form("Principal"))%> , at <%=Request.Form("APR")%> %, for <%=Request.Form("NumMonths")%> months...  </font> <p> <i>Your monthly payment would be <b> <%=FormatCurrency(MonthlyPayment)%></b></i> </p></FONT> </td></tr> </table> <p> <hr>     <% End If %> </td> </tr> </table> </body> </html> 

Figure 18-7 shows the loan.asp page when it is first loaded into the browser. The REQUEST_METHOD HTTP environment variable is used to determine whether the page has been submitted. The value of this variable is stored in the RequestMethod variable. At this stage, the form has not been posted, so the ASP and HTML code enclosed within the If statement is not executed.

click to view at full size.

Figure 18-7. The loan.asp page shown within the browser prior to the Calculate button being clicked.

After the Calculate button has been clicked, the page calls itself and the RequestMethod variable evaluates to POST. Now the Financial object is instantiated, its Payment method is passed the values collected in the HTML form, and the results are output to the screen. Figure 18-8 shows the resulting output. Notice that HTML tables have been used to format the elements on the page and a theme has been applied to the page to give it more visual appeal. More important, notice that the values collected on the HTML form have been converted to the appropriate data types prior to being passed to the Payment method. The Payment method takes the NumMonths variable as an Integer and the APR and Principal variables as Doubles. The Microsoft VBScript (Visual Basic, Scripting Edition) functions CInt and CDbl have been used to perform this data type conversion. The FormatCurrency VBScript function has been used to present the resulting output from the Payment method to the user.

click to view at full size.

Figure 18-8. The loan.asp page shown within the browser after the Calculate button has been clicked.

As you can see from the code in Figure 18-6, the amount of code necessary to instantiate a server-side component and execute its methods is just a couple of lines. Most of the code in the listing is used to collect the input values from the end user and to format the results. Additional code could be added to this example to provide more robust error handling. Specifically, client-side scripting could be used to ensure that the input values are of the correct data type and range.



Programming Microsoft Visual InterDev 6. 0
Programming Microsoft Visual InterDev 6.0
ISBN: 1572318147
EAN: 2147483647
Year: 2005
Pages: 143

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net