Export (0) Print
Expand All

Using ASP.NET in Visual Studio .NET with Visual FoxPro 7.0 

 

Cathi Gero, Prenia Corporation
Andy Kramek, Tightline Computers

April 2002

Summary: Learn the key technologies involved in using Visual Studio .NET to create Web Forms using ASP.NET and ADO.NET. Four fully documented examples illustrating how Visual FoxPro 7.0 can be used in this environment are included. (29 printed pages)

Contents

Introduction
What is .NET?
The .NET Framework and Visual Studio .NET
Overview of Visual Studio .NET
Overview of ASP.NET
Overview of ADO.NET
The Visual FoxPro 7.0 OLE DB Provider
Using Visual FoxPro with ASP.NET
   Example 1: Accessing Visual FoxPro Data Using OLE DB
   Example 2: Accessing a Visual FoxPro COM Component
   Example 3: Accessing a Visual FoxPro 7.0 XML Web Service
   Example 4: Accessing Visual FoxPro Data From an ASP.NET Web Service
Conclusion

Introduction

Some of the most obvious changes included in Microsoft® Visual Studio® .NET are in the extensions to Active Server Pages (ASP) technology implemented as ASP.NET. ASP.NET is the underlying technology behind two of the major advances introduced by the Microsoft .NET Framework: Web Forms and XML Web services.

Web Forms are used for front-end Web development. The new Web Forms Designer in Visual Studio .NET offers a common user interface that is usable by all .NET languages and provides access to a wide variety of object-oriented, server-side controls.

The concept of service driven software is central to the .NET philosophy. XML Web services make it easy to expose services across an intranet or over the Internet.

Although not part of Visual Studio .NET, Microsoft Visual FoxPro® 7.0 can be integrated into applications developed with ASP.NET in various ways, some of which are illustrated in the four examples shown in this article. Each of these examples illustrates how easily and seamlessly Visual FoxPro 7.0 can be integrated into Web Form-based applications.

What is .NET?

Microsoft® .NET Framework is the Microsoft XML Web services platform and is made up of four elements:

  • Clients

    These are the operating systems that power personal computers and mobile and embedded devices. Microsoft Windows® XP, Windows XP Embedded, and Windows CE .NET are examples of the new generation of software clients that implement the .NET Framework.

  • Services

    These let applications share data and invoke capabilities from other applications without regard to how those applications were built, what operating system or platform they run on, and what devices are used to access them.

  • Servers

    These host and deploy XML Web services and the .NET platform. Microsoft .Windows Server System™, Windows 2000 Server family, and the upcoming Windows Server 2003 family feature built-in security and support for XML and scalability.

  • Developer Tools

    These are used to create the XML Web services at the core of the .NET platform. Visual Studio .NET provides a framework for application development in four core languages: Microsoft Visual Basic®, Microsoft Visual C++®, Microsoft Visual C#™, and Microsoft JScript®. Although not part of Visual Studio .NET, Visual FoxPro 7.0 can be used to create XML Web services and therefore is also a valid developer tool for the .NET Framework.

For more information, see Microsoft .NET: What is .NET?.

The .NET Framework and Visual Studio .NET

The Microsoft .NET Framework is the programming model of the .NET platform for building, deploying, and running XML Web services and all types of applications, both desktop and Web-based. It provides a productive, standards-based environment for integrating existing developer investment with next-generation applications and services, as well as the agility to solve the challenges of deployment and operation of Internet-scale applications.

Figure 1. The .NET Framework

Figure 1 illustrates the structure of the .NET Framework, and shows how Visual Studio .NET integrates the components into a single easy-to-use development environment.

The .NET Framework consists of the following components:

  • Languages

    Four languages comprise Visual Studio .NET itself: Visual Basic, Visual C++, Visual C#, and JScript. However, the modular nature of the .NET Framework means that other languages authored by third parties can integrate into Visual Studio .NET. There are more than 20 such languages, including Perl, Component Pascal, SmallScript, and Smalltalk.

  • The Common Language Specification

    This specification underlies all of the languages that implement the .NET Framework and defines standards for a common type system, and functionality, that all languages must implement. This is how third-party languages can integrate with the Framework.

  • Windows Forms

    All languages share a common Windows Forms engine. The Form designer is consistent across all languages so all languages can access the same intrinsic controls that expose the same properties and methods. Interfaces have the same look and feel even when developed in different languages.

  • ASP.NET

    This is the underlying technology behind both Web Forms and XML Web services. Web Forms are used for front-end Web development and XML Web services expose functionality across either an intranet or the Internet.

  • Data Management

    ADO.NET, which replaces ADO as the data-handling mechanism in the .NET Framework, is a highly scaleable technology that uses XML for data transfer.

  • Base Class Library

    These are classes that provide a consistent and easy-to-use means of accessing information (for example, system information, user information, and so on) that previously required special components, or an API.

  • Common Language Runtime (CLR)

    The CLR provides a managed execution environment and compilation services to compilers. CLR compilers compile the source code into an intermediate language (IL), which is then executed in a just-in-time (JIT) manner. All source languages share the CLR (and compile to the same IL).

For more information, see Defining the Basic Elements of .NET.

Overview of Visual Studio .NET

Visual Studio .NET offers a rich set of development tools that hide a lot of the complexity inherent in working with the .NET Framework. This reduces time spent both learning the product and developing applications. When Visual Studio .NET is installed, the CLR and the .NET Framework classes are also installed. Visual Studio .NET defines four different types of applications that can be built on the .NET Framework:

  • Console

    These are command line applications that are built without a graphical user interface (GUI) and which can be executed from, and interact with, a DOS Window. In addition to their intrinsic value, they can be particularly useful for testing sections of code to ensure proper functionality.

  • Windows Forms

    These are rich-client applications that are built around a GUI similar to desktop applications written using Visual FoxPro 7.0. New features for client applications developed in the .NET Framework include visual inheritance, code-free resizing, automatic control updates, and new controls.

  • Web Forms

    These are browser-based applications that are built around a GUI with special controls. Web form applications are written using ASP.NET.

  • XML Web services

    These are applications that define XML Web services that can be consumed by other XML Web services or applications either on a local network or exposed on the Internet. Because they are based on HTTP and XML, the information they transfer can be passed through firewalls.

Visual FoxPro 7.0 can be integrated into applications developed using Visual Studio .NET in one of three ways:

  • By using Visual FoxPro 7.0 to develop and deploy a COM component that can be instantiated from, and provide services to, a .NET application.
  • By using Visual FoxPro 7.0 to create and expose a Web service that can be consumed by a .NET application. Of course, a Visual FoxPro 7.0 application can also consume XML Web services that have been developed using Visual Studio .NET.
  • By having the new Visual FoxPro 7.0 OLE DB provider allow Visual Studio .NET applications to access data held in Visual FoxPro 7.0 databases and tables.

The examples covered in this article provide an illustration of all three of these possibilities: using COM, creating and consuming a Web service, and exposing data using the OLE DB provider.

For more information, see the Visual Studio Home Page.

Overview of ASP.NET

ASP.NET is used to create programmable Web pages as part of Web form applications. Not only can ASP.NET produce dynamic Web pages, but it can also tailor them to the browser being used by the user. Development in ASP.NET is much easier because it contains a wide range of object-oriented server-side controls ready for use in applications. ASP.NET actually supports four different types of control:

  • HTML server controls

    These are programmable HTML elements that are exposed to the server. HTML server controls expose an object model that maps very closely to the HTML elements that they render.

  • Web server controls

    These controls have more built-in features than HTML server controls. Web server controls include not only form-type controls, such as buttons and text boxes, but also special-purpose controls, such as a calendar. Web server controls are more abstract than HTML server controls in that their object model does not necessarily reflect HTML syntax.

  • Validation controls

    These are controls that incorporate logic and that can be attached to an input control to test what the user enters. Some validation controls check for a required field, a specific value or pattern of characters, that a value falls within a specified range, and so on.

  • User controls

    These are custom controls created as Web Forms pages. Web Forms user controls can be embedded in other Web Forms pages and provide an easy way to create menus, toolbars, and other reusable elements.

For more details on ASP.NET Controls, see ASP.NET Server Controls.

ASP.NET also implements an event-driven programming model that is very similar to Visual FoxPro 7.0 so that custom code can be attached to events and executed when the event fires. Every time a Web page (which is an object itself) is called, a series of stages are run through: initializing, processing, and disposing of information. One key difference between the event sequence in ASP.NET and Visual FoxPro 7.0 is that the Page_Init event comes before Page_Load in ASP.NET.

For more details on ASP.NET Events, see ASP.NET Server Control Event Model.

One of the greatest benefits of ASP.NET over classic ASP is that ASP.NET reduces the amount of coding needed to write an application. With the introduction of server-side controls, it is no longer necessary to write the complex HTML and scripts that were necessary to render the pages on different browsers. In addition, ASP.NET can automatically keep track of the state between Web pages, without all the tedious programming necessary in classic ASP. Tests have shown that rendering pages using ASP.NET is typically 2-3 times faster than using classic ASP.

Historically, classic ASP has been limited to scripting engines, notably Microsoft Visual Basic, Scripting Edition (VBScript) and JScript. However ASP.NET supports any .NET CLR language and it is possible to write components in one language, and then call them from within another. ASP.NET can also run side-by-side with existing classic ASP pages because the files use different extensions. This is an important consideration because when migrating an application to ASP.NET it is not necessary to re-write all the Web pages at once.

Web Forms using ASP.NET are created as files with an .aspx extension using either of two programming styles. The first is the classic "in-line" style in which the implementation code is entered directly into the ASPx page. The second is referred to as "code behind," in which the implementation code, instead of being entered directly into the .aspx file, is stored in a separate physical file and referenced from the ASPx page using special page directives. Code-behind files are assigned extensions that indicate the source language used (.cs for C#, .vb for Visual Basic) and must be pre-compiled and located in a sub directory named "BIN" which must be situated immediately off the application's root directory.

Note that Visual Studio .NET utilizes the code-behind model exclusively and includes functionality to simplify the creation, management, and compilation of the necessary files.

For more details on creating pages, see Web Forms Code Model.

Overview of ADO.NET

ASP.NET uses ADO.NET to implement its data handling. ADO.NET is specifically designed to optimize data access using either OLE DB or XML. The object model (see Figure 2) is similar to that of ADO and consists of a Connection Object (that provides connectivity to a data source) and a Command Object (that executes commands on the database to return or modify data, run stored procedures, and so on).

Figure 2. Simplified ADO.NET Object Model

ADO.NET can retrieve and store data in two ways: either using a DataReader (read-only), or using a DataAdapter and associated DataSet (read/write). The following table compares the characteristics of these two approaches.

Table 1. Key features of ADO.NET data objects

DataReader DataSet
Similar to ADO Recordset New with ADO.NET
Contains the results of a single query only Contains a collection of one or more DataTable objects
Forward-only Full access to any row in any table
Read-only Read/Write
Connected to data source; must be closed explicitly Disconnected from data source
Can only access one data source Can store data from multiple sources

In short, DataReaders trade functionality for performance and provide the mechanism for retrieving data that is required for display as quickly as possible. DataSets must be used if the data is to be updated in any way.

For more details on ADO.NET, see Introducing ADO.NET.

The Visual FoxPro 7.0 OLE DB Provider

In earlier versions of Visual FoxPro, the only way that developers could allow other applications access to Visual FoxPro data was by using the Open Database Connectivity (ODBC) driver. However, the Visual FoxPro ODBC Driver was not much different from that used for FoxPro V2.6 and the technology could not adequately support the newer Visual FoxPro database features (such as Stored Procedures, Triggers, and Rules). The development of OLE DB technology changed all that by allowing developers to use an object-oriented approach to data access through a series of COM objects.

The new Visual FoxPro 7.0 OLE DB provider replaces the ODBC Driver, which is currently in maintenance mode and will not be updated or enhanced unless unforeseen, serious problems develop. The OLE DB provider offers developers a number of significant benefits:

  • Faster access to data than was possible using ODBC
  • Support for the new Visual FoxPro 7.0 Database Events
  • Support for Stored Procedures, even those that require parameters
  • Access to Triggers, Rules, and Default Values in the database container

In fact, the only real limitation is that because the Object Manager is not included with the OLE DB provider, you cannot actually create objects within a stored procedure that has to be accessed by an external application. The Visual FoxPro 7.0 OLE DB provider ships with (and is only available with) a fully licensed copy of Microsoft Visual FoxPro 7.0, although it might be distributed, like any other runtime component, as part of a solution.

For more details on OLE DB, see OLE DB Programmer's Reference.

Using Visual FoxPro with ASP.NET

Note   The following examples use the database "TestData" that ships with Visual FoxPro 7.0 and which is located, by default, in the \Samples\Data subdirectory under the Visual FoxPro root. The ASP.NET samples were developed and tested using Visual Studio .NET.

Example 1: Accessing Visual FoxPro Data Using OLE DB

ASP.NET can use the Visual FoxPro 7.0 OLE DB provider to directly access data and bind it to controls so that it can be displayed and modified in a Web Form.

The form displays the basic customer information and includes an Edit button to allow users to modify the company and/or contact information.

When the Edit button is clicked, the following page is rendered, which allows for modification of the company and contact fields in the customer data. Changes can either be cancelled or saved by selecting the appropriate option.

The following screenshot shows the ASPx file for the Customer List page (VFPOLEDB.aspx) as it appears in Design view. Only two controls are needed: a Label and a Datagrid.

Figure 3. The Customer List Web Form in Design view

The following is the implementation code for this example, which was written using C#.

// Set references to class libraries. 
// Similar to SET CLASSLIB TO in Visual FoxPro 7.0.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace VFP7OLEDBExample
{
  /// <summary>
  /// Summary description for WebForm1.
  /// </summary>

// Creates the ASP.NET page object.
  public class WebForm1 : System.Web.UI.Page
  {
    // Set references to the server controls on the ASP.NET page.
    protected System.Web.UI.WebControls.DataGrid dgrCustomers;
    protected System.Web.UI.WebControls.Label lblTitle;

    // Initialize properties to store different data objects.
    protected System.Data.OleDb.OleDbDataAdapter VFP7DataAdapter;
    protected System.Data.OleDb.OleDbCommand VFP7SelectCommand;
    protected System.Data.OleDb.OleDbCommand VFP7UpdateCommand;
    protected System.Data.OleDb.OleDbConnection VFP7Connection;
    protected System.Data.DataView VFP7DataView;
    
    protected string strUpdateSelect;
Note   The specification for the OLE DB provider connection string includes a full drive and path declaration for locating the sample data that assumes the default location. If your data is located elsewhere, modify the following line accordingly.
    // Visual FoxPro 7.0 OLE DB provider string to connect to 
      the TESTDATA database.
    protected string strConnection = @"provider=VFPOLEDB.1 ;data source=
      'C:\PROGRAM FILES\MICROSOFT VISUAL FOXPRO 7
         \SAMPLES\DATA\TESTDATA.DBC';password='';user id=''";

// This method is generated by Visual Studio .NET.
    public WebForm1()
    {
      Page.Init += new System.EventHandler(Page_Init);
    }

    
// The Page_Load event is run when the ASP.NET page is first loaded 
   and every time it is refreshed.
    private void Page_Load(object sender, System.EventArgs e)
    {
      // Put user code to initialize the page here.

      // Is this the first time the page is being rendered.
      if (Page.IsPostBack == false)
      {
        // Run the method to bind Visual FoxPro 7.0 data to the 
      DataGrid on the ASP.NET page.
        BindDataGrid();
      }
    }

// This method is generated by Visual Studio .NET.
    private void Page_Init(object sender, EventArgs e)
    {
      //
      // CODEGEN: This call is required by the ASP.NET Web Form Designer.
      //
      InitializeComponent();
    }

    // This method binds the Visual FoxPro 7.0 data to the DataGrid on 
      the ASP.NET page.
    public void BindDataGrid()
    {
      // Make connection to VFP database.
      OleDbConnection VFP7Connection = new OleDbConnection();
      VFP7Connection.ConnectionString = strConnection;
      VFP7Connection.Open();

      // Create a Command object with the select statement.
      String strSelect = "SELECT * FROM customer";
      OleDbCommand VFP7SelectCommand = new 
      OleDbCommand(strSelect,VFP7Connection);

      // Create a DataAdapter.
      OleDbDataAdapter VFP7DataAdapter = new OleDbDataAdapter();
      VFP7DataAdapter.SelectCommand = VFP7SelectCommand;

      // Create a DataSet.
      DataSet VFP7DataSet = new DataSet();

      // Fill the DataSet with table information.
      VFP7DataAdapter.Fill(VFP7DataSet,"Customer");

      // Bind to the DataGrid.
      DataView VFP7DataView = new 
      DataView(VFP7DataSet.Tables["Customer"]);
      dgrCustomers.DataSource = VFP7DataView;
      dgrCustomers.DataBind();
    }

    // This method is called when the user selects Edit on 
      the ASP.NET page.
    public void DoItemEdit(object objSource, 
      DataGridCommandEventArgs objArgs)
    {
      // Sets the Edit index of the DataGrid to the selected row.
      // Starts editing mode.
      dgrCustomers.EditItemIndex = objArgs.Item.ItemIndex;
      
      // Run the method to bind the Visual FoxPro 7.0 data to 
      the DataGrid on the ASP.NET page.
      BindDataGrid();
    }

    // This method is called when the user selects Cancel on 
      the ASP.NET page.
    public void DoItemCancel(object objSource, 
      DataGridCommandEventArgs objArgs)
    {
      // Reset the Edit index of the DataGrid to -1 which exits out 
      of editing mode.
      dgrCustomers.EditItemIndex = -1;

      // Run the method to bind the Visual FoxPro 7.0 data to 
      the DataGrid on the ASP.NET page.
      BindDataGrid();
    }

    // This method is called when the user selects Update on 
      the ASP.NET page.
    public void DoItemUpdate(object objSource, 
      DataGridCommandEventArgs objArgs)
    {
      // Create objects to hold references to the edited row.
      TextBox objCompanyCtrl;
      TextBox objContactCtrl;
      Label objCustIDCtrl;

      // Assign the objects to each object in the edited row.
      objCompanyCtrl = (TextBox)objArgs.Item.FindControl("txtCompany");
      objContactCtrl = (TextBox)objArgs.Item.FindControl("txtContact");
      objCustIDCtrl = (Label)objArgs.Item.FindControl("lblCustID");
      
      // Create update select statement.
      strUpdateSelect = "UPDATE Customer SET Company='" +
        objCompanyCtrl.Text + "', " +
        "Contact='" + objContactCtrl.Text +
        "' " + "WHERE Cust_ID='" +
        objCustIDCtrl.Text + "'"; 
      
      // Create a new connection.
      OleDbConnection VFP7Connection = new OleDbConnection();
      VFP7Connection.ConnectionString = strConnection;
      VFP7Connection.Open();

      // Create a Command object with select statement.
      OleDbCommand VFP7UpdateCommand = new 
      OleDbCommand(strUpdateSelect,VFP7Connection);
      
      // Execute the command.
      VFP7UpdateCommand.ExecuteNonQuery();
      
      // Close the connection.
      VFP7Connection.Close();

      // Reset the Edit index of the DataGrid to -1 which exits out 
      of editing mode.
      dgrCustomers.EditItemIndex = -1;
      
      // Run the method to bind the Visual FoxPro 7.0 data to 
      the DataGrid on the ASP.NET page.
      BindDataGrid();
    }
       // This section of code is generated by Visual Studio .NET.
  #region Web Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
    private void InitializeComponent()
        {    
      this.Load += new System.EventHandler(this.Page_Load);
        }
    #endregion
  }
}

Example 2: Accessing a Visual FoxPro COM Component

Visual FoxPro 7.0 can be used to create a COM component to encapsulate the data access functionality and associated logic. ASP.NET is used to create a wrapper around the COM object and access its methods. The Web page allows a user to enter a Customer ID. The ASP.NET page then calls a Visual FoxPro 7.0 COM object, passing the customer ID, which the user entered. The COM object searches for the customer record and returns the customer's credit limit.

The following screenshot shows the ASPx file for the Customer Credit Limit Web page (VFP7COM.aspx) as it appears in Design view. Five controls are used; four Labels and a TextBox.

Figure 4. The Customer Credit Limit Web Form in Design View

The following is the implementation code for this example, which was written using Visual Basic .NET.

'Set references to class libraries.  Similar to SET CLASSLIB TO 
   in Visual FoxPro 7.0.
Imports System
Imports System.IO
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
'Set reference to the Visual FoxPro 7.0 COM object.
Imports vfpcomexample

'Creates the ASP.NET page object.
Public Class WebForm1
    Inherits System.Web.UI.Page

    'Set references to the server controls on the ASP.NET page.
    Protected WithEvents lblTitle As System.Web.UI.WebControls.Label
    Protected WithEvents lblCustID As System.Web.UI.WebControls.Label
    Protected WithEvents lblCreditLimit As System.Web.UI.WebControls.Label
    Protected WithEvents lblCLDesc As System.Web.UI.WebControls.Label
    Protected WithEvents txtCustID As System.Web.UI.WebControls.TextBox

'This section of code is generated by Visual Studio .NET.
#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub 
      InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As 
   System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer.
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    'The Page_Load event is run when the ASP.NET page is first 
      loaded and every time it is refreshed.
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As 
   System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here.

        'Initialize a variable to store a reference to the 
      Visual FoxPro 7.0 COM component.
        Dim oCustomer As New vfpcomexample.Customer()

        'Initialize a variable to store the credit limit return 
      from the COM object.
        Dim dCreditLimit As Decimal

        'If this is the not the first time the page is rendered.
        If (Page.IsPostBack = True) Then

            'Get the credit limit amount by running the COM method, 
         passing the customer ID entered on the ASP.NET page.
            dCreditLimit = oCustomer.GetCreditLimit(UCase(txtCustID.Text))

           'Set the server control to the amount that was returned by 
         the COM object.
          'If no customer is found then the COM object with return -1.
            If dCreditLimit = -1 Then
                lblCreditLimit.Text = "Customer not found"
            Else
        'Customer found, set credit limit label on the ASP.NET page equal 
      to the returned credit limit amount, converting it to a 
         string, formatted for currency.
                lblCreditLimit.Text = dCreditLimit.ToString("C")
            End If
        End If

    End Sub

End Class

The Visual FoxPro 7.0 code used to create the COM component was:

DEFINE CLASS Customer AS SESSION OLEPUBLIC
    FUNCTION Init()
      This.Load()
    ENDFUNC
    
  * Open database and USE the customer table.
    FUNCTION Load()
      * Open the TESTDATA database.
      LOCAL lcDatabaseLocation as Character
      LOCAL lcTableLocation as Character
      IF NOT DBUSED('testdata')
        lcDatabaseLocation = _SAMPLES + '\DATA\testdata'
        OPEN DATABASE (lcDatabaseLocation) SHARED
      ENDIF
      * Use the customer table.
      lcTableLocation = _SAMPLES + '\DATA\' + This.GetCursorName()
    USE (lcTableLocation) NODATA SHARED
    ENDFUNC

  * Find a customer record based on a customer ID passed in 
      as a parameter.
    FUNCTION Fetch()
      LPARAMETERS tcCustID as Character
      LOCAL lcAlias
      lcAlias = This.GetCursorName()
      SELECT (lcAlias)
      LOCATE FOR Cust_ID = tcCustID
      RETURN FOUND()
    ENDFUNC

  * Close the customer table.
    FUNCTION Destroy()
      LOCAL lcCursor as Character
      lcCursor = This.GetCursorName()
      USE IN (lcCursor)
    ENDFUNC
    
  * Reference to which table is being USEd.
    FUNCTION GetCursorName() as String
      RETURN "Customer"
    ENDFUNC

  * This method returns the customer's credit limit.  
   The customer ID is passed in as a parameter.
    FUNCTION GetCreditLimit(tcCustID as Character) as Currency
      LOCAL lyCredLimit as Currency
      * Try and find customer record in the customer table.
      IF This.Fetch(tcCustID)
        * Customer found.  Return the credit limit from the 
         MaxOrdAmt field in the customer table.
        lyCredLimit = EVALUATE(This.GetCursorName() + '.MaxOrdAmt')
      ELSE
        * Customer not found.  Return -1 to the calling program.
        lyCredLimit = -1
      ENDIF
      RETURN lyCredLimit
    ENDFUNC

ENDDEFINE

Example 3: Accessing a Visual FoxPro 7.0 XML Web Service

ASP.NET can be used to call a Web service created with Visual FoxPro 7.0.

FoxCentral.net (http://foxcentral.net) is a free Web site for information of interest to the FoxPro Community. This Web site, created using Visual FoxPro 7.0, exposes its functionality as a Web service described in the XML Web Services Definition Language (WSDL) file that is available at http://www.foxcentral.net/foxcentral.wsdl.

The Web service exposes a GetItems() method which can be called to return posted items that meet the various criteria that are passed to the method as parameters. The parameters are specified for the Getitems() method in the WSDL file like this:

<message name="foxcentral.GetItems">
  <part name="ldLastOn" type="xsd:dateTime" /> 
  <part name="ldTimeZone" type="xsd:int" /> 
  <part name="lnProvider" type="xsd:int" /> 
  <part name="lcType" type="xsd:string" /> 
</message>

For more information on XML Web services in Visual FoxPro 7.0, see Web Services Overview.

The following screenshot shows the ASPx file for the FoxCentral Extract Web page (FoxCentral.aspx) as it appears in Design view. Four controls are used; two Labels, one calendar control, and a DataGrid.

Figure 5. The FoxCentral Extract Web Form in Design view

The following is the implementation code for this example, which was written using C#.

// Set references to class libraries.  Similar to SET CLASSLIB TO 
   in Visual FoxPro 7.0.
using System;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
// Set reference to the Visual FoxCentral.net Web Service object.
using FoxCentralASPX.net.foxcentral.www;

namespace FoxCentralASPX
{
  /// <summary>
  /// Summary description for WebForm1.
  /// </summary>
// Creates the ASP.NET page object.
  public class WebForm1 : System.Web.UI.Page
  {
    // Set references to the server controls on the ASP.NET page.
    protected System.Web.UI.WebControls.DataGrid dgrNews;
    protected System.Web.UI.WebControls.Calendar calDate;
    protected System.Web.UI.HtmlControls.HtmlGenericControl cTitle;
    protected System.Web.UI.WebControls.Label outError;
  
// This method is generated by Visual Studio .NET.
    public WebForm1()
    {
      Page.Init += new System.EventHandler(Page_Init);
    }

// The Page_Load event is run when the ASP.NET page is first 
   loaded and every time it is refreshed.
    private void Page_Load(object sender, System.EventArgs e)
    {
      // Put user code to initialize the page here.

            // Initialize a variable to store a reference to 
         the FoxCentral.net Web Service.
      foxcentral loData = new foxcentral();

      // Initialize other objects to use in this method.
      string lcXML = "";
      string lcError = "";
      System.Data.DataSet oDS = new DataSet();
      bool lbError = false;

      // Initialize the server control label and DataGrid on 
      the ASP.NET page visible property to false to 
         hide the objects.
      outError.Text = "";
      outError.Visible = false;
      dgrNews.Visible = false;

      // If this is the first time the page is rendered.
      if (Page.IsPostBack == false)
      {
        // Set the selected date to today's date.
        calDate.SelectedDate=System.DateTime.Today;
      }

      try
      {
        // Call FoxCentral.net's GetItems method, passing the user's 
         entered date.
        lcXML = loData.GetItems(calDate.SelectedDate,0,0,"ALL");

        // If no data was returned and exception will be thrown.
        if (lcXML == "")
        {
          throw new Exception();
        }
      }
      
      catch(Exception ex)
      {
        // If an exception occurred then set the text of the error 
         label on the ASP.NET page and display it.
        lcError = "No news items to retrieve";
        outError.Text = lcError;
        outError.Visible = true;
        return;
      }

      try
      {
        // Read the XML into the DataSet.
        oDS.ReadXml(new StringReader(lcXML));
      }
      catch(Exception ex)
      {
        // If an exception occurred, then get a reference to the 
         error and set the error variable to true.
        lcError = ex.ToString();
        lbError = true;
      }

      // If an error occurred, then set the text of the error 
         label on the ASP.NET page and display it.
      if (lbError)
      {
        outError.Text = lcError;
        outError.Visible = true;
        return;
      }
    
      // Set the DataView object to the table created from the 
      XML called "News".
      DataView oDataView = new DataView(oDS.Tables["News"]);

      // Set the DataGrid source to the DataView.
      dgrNews.DataSource = oDataView;

      // Bind the DataGrid.
      dgrNews.DataBind();

      // Display the DataGrid.
      dgrNews.Visible = true;
    }
  

// This method is generated by Visual Studio .NET.
    private void Page_Init(object sender, EventArgs e)
    {
      //
      // CODEGEN: This call is required by the ASP.NET Web Form Designer.
      //
      InitializeComponent();
    }

// This section of code is generated by Visual Studio .NET.
    #region Web Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
      private void InitializeComponent()
    {    
      this.calDate.SelectionChanged += new 
      System.EventHandler(this.Page_Load);
      this.Load += new System.EventHandler(this.Page_Load);

    }
    #endregion
  }
}

Example 4: Accessing Visual FoxPro Data From an ASP.NET Web Service

You can create an ASP.NET Web service that accesses Visual FoxPro 7.0 data. The Web service defines a CustomersInCountry() method that, when passed a character string containing the name of a country, connects to the Visual FoxPro 7.0 database using the OLE DB provider. It then executes a query to retrieve details of customers in the specified country. If any data is returned, the result set is packaged up as XML and returned to the calling object.

XML Web services have no user interface, so there is no ASPx file for this example. The following is the implementation code, which was written using C#.

// Set references to class libraries.  Similar to SET CLASSLIB TO 
   in Visual FoxPro 7.0.
using System;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Diagnostics;
using System.Web;
using System.Web.Services;

namespace VFP7WebServiceExample
{
  /// <summary>
  /// Summary description for Service1.
  /// </summary>
// Creates the ASP.NET Web Service.
  public class Service1 : System.Web.Services.WebService
  {
// This method is generated by Visual Studio .NET.
    public Service1()
    {
      //CODEGEN: This call is required by the ASP.NET Web 
      Services Designer.
      InitializeComponent();
    }

// This section of code is generated by Visual Studio .NET.
    #region Component Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
      private void InitializeComponent()
    {
    }
    #endregion

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
    }

// The WebMethod attribute exposes the method as a Web Service method.
    [WebMethod]
// This method accepts a country as a parameters and returns an XML 
   formatted string of all the customer records that are from 
      the country.
    public string CustomersInCountry(string strCountry)
    {
      string cReturnString;
Note   The specification for the OLE DB provider connection string includes a full drive and path declaration for locating the sample data that assumes the default location. If your data is located elsewhere, modify the following line accordingly.
      // Make connection to Visual FoxPro database.
      String strConnection = @"provider=VFPOLEDB.1 ;data 
      source='C:\PROGRAM FILES\MICROSOFT VISUAL FOXPRO 
         7\SAMPLES\DATA\TESTDATA.DBC';password='';user id=''";
      OleDbConnection VFP7Connection = new OleDbConnection();
      VFP7Connection.ConnectionString = strConnection;
      VFP7Connection.Open();

      // Create a Command object with select statement.
      String strSelect = "SELECT * FROM customer WHERE 
      upper(country)='" + strCountry.ToUpper() + "'";
      OleDbCommand VFP7SelectCommand = new 
      OleDbCommand(strSelect,VFP7Connection);

      // Create a DataAdapter.
      OleDbDataAdapter VFP7DataAdapter = new OleDbDataAdapter();
      VFP7DataAdapter.SelectCommand = VFP7SelectCommand;

      // Create a DataSet.
      DataSet VFP7DataSet = new DataSet();

      // Fill the DataSet with table information.
      int iRecFound;
      iRecFound = VFP7DataAdapter.Fill(VFP7DataSet,"Customer");
      
      // If no customer records were found, then return a blank string.
      if (iRecFound==0)
      {
        cReturnString = "";
      }
      else
      {
        // If customer records were found, then write the DataSet 
         results into XML and return it as a string.
        StringWriter cXML = new StringWriter();
        VFP7DataSet.WriteXml(cXML);
        cReturnString = cXML.ToString();
      }

      return cReturnString;
    }

  }
}

To use this Web service from Visual FoxPro 7.0, an instance of the Web service is first created and assigned to a local object reference, as displayed in the following code.

LOCAL oCustomers as ASPDotNetWS
LOCAL loWS, lcRetStr

* Initialize the ASP.NET web service.
loWS = NEWOBJECT("Wsclient",HOME()+"ffc\_webservices.vcx")
loWS.cWSName = "ASPDotNetWS"
oCustomers = loWS.SetupClient
   ("http://localhost/VFP7WebServiceExample/VFP7WebService.asmx?WSDL",
                               "Service1", "Service1Soap")

Once we have the object reference to the Web service, its methods can be called in precisely the same way as if it were actually a native Visual FoxPro object. The Web service returns its results as XML so, in order to view (or use) the results in Visual FoxPro 7.0, we need to convert the results into a local cursor using XMLTOCURSOR() using the following code.

* Convert the XML returned from the web service into a 
* Visual FoxPro 7.0 cursor and browse it
STORE "" TO lcRetStr
lcRetStr = oCustomers.CustomersInCountry("GERMANY")
IF NOT EMPTY( lcRetStr )
  XMLTOCURSOR( lcRetStr,"CustomersGermany")
  BROWSE
ENDIF

Of course, although we have used Visual FoxPro 7.0 to access the Web service, any development tool that is capable of creating an object and handling XML data could have been used. The very essence of XML Web services is that they are language (and even platform) independent.

Conclusion

Visual Studio .NET offers developers an easy entry point for developing applications using the new Web Forms and ASP.NET technology, which are a key part of the Microsoft .NET Framework. By providing a full-featured, integrated development environment and hiding most of the complexity involved in managing the tools, Visual Studio .NET frees developers to focus on the main task of creating and deploying applications. The use of Web Forms and ASP.NET to create a front end for an application offers significant benefits to Visual FoxPro 7.0 developers in three areas:

  • It enables them to develop applications that are platform independent. Unlike native Visual FoxPro applications, ASP.NET applications are designed to run in a browser and do not require an installed Windows platform.
  • It enables them to provide remote access to FoxPro data. With a front end developed in ASP.NET, Visual FoxPro data can be exposed in a controlled environment, for review, or modification, to users across the Internet.
  • It enables them to develop applications that are device independent. ASP.NET applications natively support access by a wide range of devices, including cell phones and PDAs.

The examples in this article have shown how easily Visual FoxPro 7.0 can be integrated in different ways with Web Forms developed using ASP.NET in Visual Studio .NET. This level of integration has been made possible by the implementation of the new OLE DB provider and the enhancements to XML support that were introduced in Visual FoxPro 7.0.

However, this is by no means a one-way interaction. Visual FoxPro 7.0 can easily create data-centric XML Web services that are difficult to build with tools that do not feature the tight integration between data and language that has always been one of the hallmarks of Visual FoxPro.

Visual FoxPro 7.0 can also be used to create middle-tier components. With its full support for COM+ services, Visual FoxPro 7.0 can be used to create data-intensive COM components, which can easily be called from a Web Form. Such components can talk to either native FoxPro data, or SQL databases through OLE DB.

As this article demonstrates that, even though Visual FoxPro 7.0 is not an integral part of Visual Studio .NET, it does not mean that it cannot participate actively in, and contribute positively toward, .NET-based development.

For more information on Visual FoxPro, see the Microsoft Visual FoxPro Home Page. For more information on ASP.NET, see the Microsoft ASP.NET Home Page.

Show:
© 2014 Microsoft