<%@ Language=VBScript EnableSessionState=False %> <% ComponentPref = Request.Form("ComponentPref") If ComponentPref = "" Then ComponentPref = Request.Cookies("ComponentPreference") Select Case ComponentPref Case "VB5" VB5Checked = "Checked" Case "JavaComp" JavaChecked = "Checked" Case Else VB5Checked = "Checked" ComponentPref = "VB5" End Select Response.Cookies("ComponentPreference") = ComponentPref Response.Cookies("ComponentPreference").Expires = "January 1, 2020" Response.Cookies("ComponentPreference").Path = "/" Response.Expires = 0 LessonFile = Request.ServerVariables("SCRIPT_NAME") ScriptLanguagePreference = Request.Cookies("ScriptLanguagePreference") If ScriptLanguagePreference = "" Then ScriptLanguagePreference = Request.QueryString("ScriptLanguagePreference") If ScriptLanguagePreference = "" Then Response.Redirect "/iishelp/iis/htm/asp/iiselect.asp?LessonFile=" & Server.URLEncode(LessonFile) End If End If 'Determine the physical path for the current page and then remove the 'name of the file from the path (leaving just the directory). MainPath = Request.ServerVariables("PATH_TRANSLATED") Length = Len(MainPath) i = 0 Do Until (i = 2) Do While (Mid(MainPath, Length, 1) <> "\") Length = Length - 1 Loop i = i + 1 MainPath = left(MainPath, (Length-1)) Loop FilePath = left(MainPath, Length) + "\tutorial" 'Determine the virtual path for the current page and then remove the 'name of the file from the path (leaving just the directory). MainPath = Request.ServerVariables("PATH_INFO") Length = Len(MainPath) i = 0 Do Until (i = 2) Do While (Mid(MainPath, Length, 1) <> "/") Length = Length - 1 Loop i = i + 1 MainPath = left(MainPath, (Length-1)) Loop VirtFilePath = left(MainPath, Length) + "/tutorial" %> Module 3: Writing Your Own Components

Module 3: Writing Your Own Components

Choose a scripting language for this lesson.

In Module 2 you familiarized yourself with the components Active Server Pages (ASP) provides, now it's time to think about creating your own components, components that meet your specific needs.

Suppose you want create an ASP application that provides users with access to specific financial functions through your Web site. ASP does not explicitly provide such functionality, but getting it is as easy as creating your own Java or ActiveX component, which you will do in this module.

To get started, use the following form to select a component that you would like to learn how to create and implement:


Select a component to create for this lesson:

>Visual Basic 5.0 ActiveX Component
>Visual J++ 1.1 Java™ Component


Important   

  1. To save and view your work in this module, you require the following:
    • Write and Script Web server permissions for the <%= VirtFilePath %> virtual directory on the <%= Request.ServerVariables("SERVER_NAME")%> Web server (with Active Server Pages installed). For more information, see Setting Web Server Permissions.
    • Your Windows NT account must have Windows NT File System (NTFS) permissions that enable you to read, write, and run programs in the <% If ComponentPref = "JavaComp" Then %> DriveLetter:\Winnt\Java directory and its subdirectories, where DriveLetter is the letter mapped to the appropriate drive of the <%= Request.ServerVariables("SERVER_NAME")%> Web server.
    • <%Else%>DriveLetter:\Winnt\System32\Inetsrv\ where you replace DriveLetter with the letter mapped to the appropriate drive of the <%= Request.ServerVariables("SERVER_NAME")%> Web server. (If you did not accept the default installation directory, substitute the name of your installation directory for \Winnt\System32.) <% End If %>
  2. To complete this module, on the <%= Request.ServerVariables("SERVER_NAME") %> Web server you must have installed:
  3. If you have disabled your Web browser's ability to run Java programs, enable this feature before proceeding with the tutorial.

Lesson 1: Creating the <% If ComponentPref = "JavaComp" Then %>Java <%Else%>ActiveX <% End If %> Finance Component

<% If ComponentPref = "JavaComp" Then%>

A component should contain a set of related methods (functions) that provide added value beyond what is in the scripting language that will be calling it. Because <%= ScriptLanguagePreference %> does not provide financial functions, you must explicitly create a finance function. Specifically, for this tutorial you will learn how to create a function that computes the future value of an investment, which returns an annuity based on a fixed interest rate and periodic, fixed payments.

Start Visual J++

  1. Click Start, point to Programs, then point to Microsoft Visual J++ 1.1
  2. Click Microsoft Developer Studio in the submenu to run the design environment.

Start and Name a Project

  1. Click File.
  2. Select New.
  3. Click the Project tab.
  4. Select Java Project.
  5. In the Project Name box, type Finance, then click OK.

Add the Finance Class to the Project

  1. In the Insert menu, choose New Class.
  2. In the Name box, type Finance, then click OK. The following should appear in the text editor:
  3. class Finance {
    
    
    }
    

    Note   The Class name must be the same as the Project name for a Java server component.

Add the CalcFV Function to the Finance Class

  1. Select the ClassView tab (selected by default).
  2. Expand the Finance Classes item in the tree control.
  3. Right-click Finance class and select Add Method.
  4. In the Return Type box, type public double.
  5. In the Method declaration box, copy and paste the following:
  6. CalcFV(double dblRate, double dblNPer, double dblPMT, double dblPv, boolean bType)

    With this declaration, you define the a finance function, belonging to the Finance class, that computes the future value of an investment.

  7. Click OK. The following appears in the Visual J++ text editor:
  8. class Finance {
    	public double CalcFV(double dblRate, 
    			   double dblNPer, 
    			   double dblPMT, 
    			   double dblPv, 
    			   boolean bType) {     
    
    
    	}
        }
    
  9. Within the innermost set of brackets, copy and paste the following Java code into the text editor:
  10.   double	dblRet, dblTemp, dblTemp2, dblTemp3;
    
    	    if (dblRate == 0.0) {
    	        dblRet = -dblPv - dblPMT * dblNPer;
    	    } else {
    	        dblTemp = (bType ? 1.0 + dblRate : 1.0);
    	        dblTemp3 = 1.0 + dblRate;
    	        dblTemp2 = Math.pow(dblTemp3, dblNPer);  
    	        dblRet = -dblPv * dblTemp2 - dblPMT * dblTemp * (dblTemp2 - 1.0) / dblRate;
    	       }
    
    	    return dblRet;
    

    Don't be intimidated by this code, it simply defines the mathematical equation (in Java's syntax) necessary for computing the future value of an investment. If you are interested, you can find information about this commonly used equation in almost any financial mathematics or accounting text book.

    Note   Java is case sensitive, so if you decide to type the previous lines of code into the text editor, be sure to type Java syntax and variables exactly as shown.

Build the Finance Component

  1. In the Build menu, Select Build Finance.
  2. In the Build window (located below the ClassView and text editing windows) make sure the build process has not generated any errors or warnings.

Copy the Finance Component to the Trustlib directory

  1. Click the Windows Start button, point to Programs, then click Windows Explorer.
  2. Copy the Finance.class component from the Program Files\DevStudio\MyProjects\Finance\ directory to the <%= Request.ServerVariables("SERVER_NAME") %> Web server's Winnt\Java\Trustlib directory.

Register the Finance Java Class

You must register the Finance Java class to make it callable by JScript and all of the other OLE-compatible languages on your computer.

  1. Open a command-prompt window.
  2. Type cd Drive Letter:\<%= Request.ServerVariables("SERVER_NAME")%>\Program Files\DevStudio\VJ\Bin\ at the command prompt, where DriveLetter is the letter mapped to the appropriate drive on your computer. (If you did not accept the default installation directory, substitute the name of your installation directory for \Program Files\DevStudio\VJ\Bin\.)
  3. Press the Enter key.
  4. Type javareg /register /class:Finance /progid:MS.Finance.Java.
  5. Press the Enter key.
  6. Click the OK button when a dialog box appears that says Successfully Registered Java class "Finance" as CLSID.
  7. Close the command-prompt window.
<%Else%>

A component should contain a set of related methods (functions) that provide added value beyond what is in the scripting language that will be calling it. Because <%= ScriptLanguagePreference %> does not provide financial functions, you must give access to the Visual Basic finance functions through your Finance server component. This server component could expose all of the Visual Basic finance functions including the DDB function (double-declining balance), FV function (future value), IPmt function (interest payment), IRR function (internal rate of return), and others. However, for this tutorial you will only the implement the FV function, which returns an annuity based on a fixed interest rate and periodic, fixed payments.

Start Visual Basic

  1. Click Start, point to Programs, then point to Microsoft Visual Basic 5.0
  2. Click Visual Basic 5.0 in the submenu to run the design environment.

Start and Name a Project

  1. In the New Project dialog box, double-click ActiveX DLL.
  2. On the Project menu, click Project1 Properties.
  3. On the General property sheet, in the Project Name box, type MS.
  4. Select Unattended Execution.
  5. Note   Selecting this option indicates that the project is intended to run without user interaction and should have no user interface elements.

  6. Click OK.

The project is now named MS. Later, you will reference the Finance server component as MS.Finance from an ASP script.

Add the Finance Class to the Project

In Visual Basic, to create a component with a set of functionality you can call, you define a class. A class groups methods and properties. In your project, it will be the place within which you specify your finance methods.

  1. Press F4 to open the Properties window for the class module, then double-click the Name property and type Function, then press ENTER.
  2. Double-click Instancing.
  3. Click the arrow, then select 5 - MultiUse.

Learn More About Visual Basic Finance Functions

The Visual Basic Help system describes available financial functions.

  1. Click Help.
  2. Select Microsoft Visual Basic Help Topics.
  3. Select the Index tab, then type financial functions as the word to look for.
  4. Double-click the financial functions index entry.
  5. Click FV Function to learn more about it.
  6. Close the Visual Basic Help dialog box when you have finished reviewing the finance functions.

Add the CalcFV Function to the Finance Class

The Finance server component does require some programming code. This code will make the Visual Basic built-in future value function available to languages making use of your component.

Copy and paste the following lines into the Finance class code window:

Public Function CalcFV(rate, nper, pmt, Optional pv, Optional whendue) 
CalcFV = FV(rate, nper, pmt, pv, whendue)
End Function

Add the Component’s Entry Point

All server components require an entry (starting) point. This is the code that will be called when the object is first made available to a language. In VBScript, when you use Server.CreateObject, an instance is created of an object. When the Server.CreateObject statement is executed, the Sub Main procedure in a server component (that is, one created with Visual Basic) is called.

Your finance component does not have to do anything special to initialize itself when it is called. For that reason, you can provide an empty (no Visual Basic statements) Sub Main procedure.

  1. In the Project menu, select Add Module.
  2. In the Module 1dialog box, double-click the module icon.
  3. In the Module 1 code window, type Sub Main.
  4. Press Enter.

This automatically enters the following code:

Sub Main()
End Sub

Save the Finance Project

When you save your work, you will be asked to save all three parts of the Visual Basic project. These include the project file, the class module, and the code module.

  1. Open the File menu.
  2. Select Save Project.
  3. In the File name text box, type Finance. Select the following path on the <%= Request.ServerVariables("SERVER_NAME")%> Web server: DriveLetter:\Winnt\System32\Inetsrv\ where DriveLetter is the letter mapped to the appropriate drive. (If you did not accept the default installation directory, substitute the name of your installation directory for \Winnt\System32.)
  4. Click the Save button.
  5. If a previous user has completed this portion of the tutorial, a message will appear stating that the file already exists. Save your version of the file in place of the older version.

  6. Double-click the value Project1 in the File name text box to select it.
  7. Type the name Finance for the Project file (.vbp).
  8. Click the Save button to save the project.
  9. If a previous user has completed this portion of the tutorial, a message will appear stating that the file already exists. Save your version of the file in place of the older version.

Make the Component an In-Process Component

Visual Basic allows you to create in-process ActiveX components (formerly called OLE Automation Servers) and out-of-process ActiveX components. An in-process ActiveX component is a dynamic-link library (file name extension .dll) that is loaded by the calling process. An out-of-process ActiveX component is an executable (file name extension .exe) that runs as a separate process from the calling application. Because in-process components are in the same process space as the calling program, they provide better performance than out-of-process components.

To make the Finance server component an in-process ActiveX component

  1. Open the File menu.
  2. Select Make Finance.dll.
  3. Click the Options button.
  4. Select the Auto Increment check box.
  5. Click OK.
  6. Type DriveLetter:\<%= Request.ServerVariables("SERVER_NAME")%>\Winnt\System32\Inetsrv\Finance where DriveLetter is the letter mapped to the appropriate drive on your computer. (If you did not accept the default installation directory, substitute the name of your installation directory for \Winnt\System32.)
    If a previous user has completed this portion of the tutorial, a message will appear stating that the file already exists. Save your version of the file in place of the older version.
  7. Exit Visual Basic.

Register the Finance Server Component

All server components must be registered. Windows NT and Windows 95 make use of the system registry to keep track of what server components are available for use. By registering the Finance server component, you make it callable by VBScript and all of the other OLE-compatible languages on your computer.

  1. Open a command-prompt window.
  2. Type cd Drive Letter:\<%= Request.ServerVariables("SERVER_NAME")%>\Winnt\System32\Inetsrv at the command prompt, where DriveLetter is the letter mapped to the appropriate drive on your computer. (If you did not accept the default installation directory, substitute the name of your installation directory for \Winnt\System32.)
  3. Press the Enter key.
  4. Type regsvr32 Finance.dll.
  5. Press the Enter key.
  6. Click the OK button when a dialog box appears that says DllRegisterServer in finance.dll succeeded.
  7. Close the command-prompt window.

<% End If %>

Lesson 2: Calling the Finance Component from a Script

To test the component, you can call the component from Active Server Pages (ASP), Visual Basic, Microsoft® Office products that use Visual Basic for Applications, or any other OLE Automation controller.

To call the Finance server component from Active Server Pages by using <%=ScriptLanguagePreference%>, you can use an HTML form as input to calculate the future value of a person’s savings plan.

The HTML Form

An HTML form will be used to gather values that describe a savings plan. These values are assigned variables that are made available to an ASP script as part of the Request object. You can reference a value from an HTML form. For example, the annual percentage rate entered on a form can be referenced by a script using Request("APR"). The HTML tag <INPUT TYPE=TEXT NAME=APR> provides the input field necessary to enter a value.

To send the form to a Microsoft Web server running ASP, the user presses a Submit button. The Submit button calls the page indicated by the ACTION property of the HTML form tag. The HTML tag for the Submit button (<INPUT TYPE=SUBMIT VALUE=" Calculate Future Value ">) uses the value for ACTION from the HTML form tag (<FORM METHOD=POST ACTION="Finance<%If ScriptLanguagePreference = "JScript" Then %>j<%Else%><% End If %>.asp">) to call the ASP page Finance<% If ScriptLanguagePreference = "JScript" Then %>j<%Else%><% End If %>.asp.

We have created the form for you. Use your text editor to open the file FVform.asp in the <%= Request.ServerVariables("SERVER_NAME")%> Web server's Tutorial directory (<%= FilePath %>).

The Script

You use <%=ScriptLanguagePreference%> to call your Finance server component. The script starts by validating the inputs from the HTML form and assigning default values for any values that were not entered on the form. <% If ScriptLanguagePreference = "JScript" Then %>A custom function called IsNumeric tests whether or not a numeric (valid) value was entered for each of the boxes on the HTML form. <%Else%>The VBScript IsNumeric function tests whether or not a numeric (valid) value was entered for each of the boxes on the HTML form.

<% End If %> <% If ComponentPref = "JavaComp" Then %>

Server.CreateObject creates an instance of (that is, makes usable) your Finance component named MS.Finance.Java. After creating an instance of the component, you can make use of its methods and properties. The script line immediately following Server.CreateObject<%Else%>

Server.CreateObject creates an instance of (that is, makes usable) your Finance component named MS.Finance. After creating an instance of the component, you can make use of its methods and properties. The script line immediately following Server.CreateObject<% End If %> uses the CalcFV method to calculate a savings plan's future value. The result of this calculation appears on the the browser of the user requesting the information.

To view the script, use a text editor to open the file <% If ScriptLanguagePreference = "JScript" Then %>Financej.asp <%Else%>Finance.asp <% End If %> in the Tutorial directory (<%= FilePath %>).

Using Your Browser to Run the Test

To run the <% If ScriptLanguagePreference = "JScript" Then %>Financej.asp <%Else%>Finance.asp <% End If %> ASP page, open the FVform.asp file, which renders a form and then calls the <% If ScriptLanguagePreference = "JScript" Then %>Financej.asp<%Else%>Finance.asp<% End If %> script to calculate the future value of the savings plan specified on the form.

  1. Open FVform.htm by pointing your browser to /iishelp/iis/htm/tutorial/FVform.asp?ScriptLanguagePreference=<%=ScriptLanguagePreference%>&ComponentPref=<%=ComponentPref%>">http://<%=Request.ServerVariables("SERVER_NAME")%>/iishelp/iis/htm/tutorial/FVform.asp.
  2. Enter values for the form inputs in the Savings Plan form.
  3. Click the Calculate Future Value button. The value of your savings plan should appear.

In a relatively short time you have created a useful <% If ComponentPref = "JavaComp" Then %>Java<%Else%>ActiveX server<% End If %> component. If you need access to other financial functions, you can implement other financial functions <% If ComponentPref = "JavaComp" Then %>with Visual J++<%Else%>built into Visual Basic<% End If %> as additional methods of your Finance server component. We encourage you to experiment and come up with creative ways to utilize your own <%If ComponentPref = "JavaComp" Then%>Java<%Else%>ActiveX<% End If %> components. Soon, you will find that there is virtually no limit to the Web applications you can develop using components.


© 1997 Microsoft Corporation. All rights reserved.