ࡱ > M O F G H I J K L 9 bjbj .h l h h h h h h h | t= t= t= t= L = | 7 | > 6 ? ? ? ? A A A ڋ ܋ ܋ ܋ ܋ ܋ ܋ ӏ ܋ h A @ A A A ܋ A h h ? ? A A A A h ? h ? ڋ A A ڋ A \ A gB h h ڋ ? > | : t= A : ڋ 0 7 A ڋ A | | h h h h Database Publishing on the Internet with Visual FoxPro By Rick Strahl HYPERLINK "http://www.west-wind.com" \t "_top" http://www.west-wind.com/ Revised session notes from my 1996 Visual FoxPro DevCon session.Updated 02/10/1997 HYPERLINK "D:\migration\whitepapers\" \l "WHY" Why build Web Applications HYPERLINK "D:\migration\whitepapers\" \l "LIMITATIONS" Limitations of Web Applications HYPERLINK "D:\migration\whitepapers\" \l "ACTIVEX" How the Active Web works HYPERLINK "D:\migration\whitepapers\" \l "START" What you need to get started Tools to Connect Visual FoxPro Data HYPERLINK "D:\migration\whitepapers\" \l "DENALI" Microsoft Active Server Pages (IIS 3.0) HYPERLINK "D:\migration\whitepapers\" \l "FOXISAPI" FoxISAPI HYPERLINK "D:\migration\whitepapers\" \l "WEBCONNECTION" West Wind Web Connection Overview This white paper will walk you through some of the tools available to build Web based applications with Visual FoxPro. Focus will be on building server side applications by introducing some of the tools that can take advantage of Visual FoxPro data and code to build high performance backends. This paper will cover the following areas: Overview of Web Technology with focus on building backend applications that connect to databases and Visual FoxPro in particular. Review the hardware and software required to build Web based applications. Using Microsoft Active Server (IIS 3.0) to access FoxPro data via ODBC. Integrating Visual FoxPro with Active Server via Visual FoxPro Automation Servers. Using FoxISAPI to build Visual FoxPro Automation servers that interface directly with Web links. Using Web Connection to simplify Web application development using a Web Application framework for Visual FoxPro. Introduction Building applications that are integrated with Internet technology and can connect databases to Web sites will likely become an important aspect in your software development in the future, if it hasn't become so already. We're just at the beginning of the move toward 'Active' Web content and while we'll surely see improvements in the tools available down the line, applications built with Visual FoxPro can provide extraordinary power, versatility and speed using standard PC hardware to drive high powered Web sites today. Internet Development is exploding People are flocking to the Internet and the World Wide Web in particular by the millions. Because of the both the hype and the actual traffic on the 'Net, the Internet is an exploding market as businesses are trying to integrate the Internet into their existing business strategies. There is tremendous demand for developers who can build the dynamic content necessary to build truly useful, distributed business applications that can run over the open Internet or the local Intranet. Active, Database Applications are in high demand Database applications are the key to building active Internet applications. Until recently static content via plain HTML pages has been the standard fare on the World Wide Web. However, for conveying lots of information the static HTML concept falls apart quickly and becomes a maintenance nightmare. The true potential of the Web lies in giving users access to data that is always up to date, allows them to see only what they chose to look at by allowing the data to be filtered and queried to display only small, appropriately sized chunks at a time. Visual FoxPro is ready for the Internet today Visual FoxPro is more than ready for this challenge. I've been involved in building several high volume Web sites that use Visual FoxPro as the database backend. Not only did Visual FoxPro perform extremely well under heavy load, but it also allowed creation of applications in record time and with a budget that was a fraction of the nearest competitors bid. Visual FoxPro provides exceptional database access speed that's unrivaled by ODBC based tools and even full blown SQL servers in many circumstances. In addition you can leverage your existing FoxPro skills and code base to build quality applications with full featured logic using the data centric and object oriented, FoxPro language. If designed properly, applications can also be scaled to handle just about any request load scaling to multiple processors or even multiple servers on separate machines across a network. Why build Web Applications? If youve read through the computer trade papers or even the mainstream computer press youve probably noticed that the Web is affecting just about every aspect of computing these days. Software developers and tool vendors alike are focusing on the Web as the next development platform. Clients are asking about Net technology and how they can take advantage of the distributed envrionment which the Web offers. For better or worse, the Web is here to stay. There are a number of very important steps forward, but at the same time a few blems that take us a step back in the area of application development. In this section and the following one Id like to point out some of the strengths and weaknesses of Web based application development. Distribute widely, administer centrally The Internet could become the ultimate client/server platform. It provides: Easy access from any network connectionWeb applications are accessible from any network connection using TCP/IP. As long as the network is not locked off intentionally with security measures, you can access the same application from anywhere within your company or even from the outside when you're on the road. Applications are maintained in one placeWhile the application can be run from any network connection the server is centrally located and maintained. The application can be updated in one place and all clients automatically see the update next time the application is run. The application also does not need to be installed on the client in any way - no making sure all the DLLs are available etc. All the thin client needs is a compatible Web browser. Clear separation of client and serverThe Web provides a typical client/server implementation where the client has no direct access to the server's functionality but converses with the server via transactions. Since all processing happens on the server and only the result returns to the client limited network bandwidth.Note: Visual FoxPro can act as a server in this type of Client/Server environment. The Web acts as the middleware that connects the client to the server. Universal Client Interface The Web Browser is quickly becoming one of the killer applications that come around and change the computing environment. The quick acceptance of this interface is driving changes in software design that is moving more and more technology towards a Web based interface. Cross Platform ClientsCross platform issues have been short-changed by software developers for the longest time. Browsers are perhaps the first tool that bring the various operating systems and environments together and allow them to run the same applications.Not only that, but you can build your application under Windows and expect people on Unix or Mac boxes to run them as is. Browsers make it possible to use whatever tool/platform you're comfortable with to build backend applications and still provide the cross platform capability. No extra development required. No hassle application updatesApplications can be updated on the server in a central location without having to touch the client machines. Application Platform of the future Web browsers have brought about drastic changes in the software development field. One look at the latest software offerings from all the major software houses shows this in evidence: Internet connectivity and output options for creating HTML are evident wherever you look. Development tools of all types are being provided with rudimentary tools to connect to the Internet. Microsoft has been previewing the next release of Internet Explorer which promises to integrate the Web browser directly into the operating system, where the desktop and integral file operations as well as access the network occur within a familiar browser interface. It's all geared towards integrating the Internet more transparently into the operating system. The hyperlinked nature of HTML (and the supporting ActiveX and Java technologies) makes it possible to transparently tie together the local machine, the interoffice workgroup or Intranet applications and the entire Internet. Welcome to the Network machine! Limitations of Web Applications There are many benefits to building an application that runs over the Web. But it's also extremely important to understand the limitations that you will face when building Web applications. They are not insurmountable, but they do require rethinking application development to some extent. Configuration Issues Web Development is definitely more involved than building a standalone application using a visual tools such as Visual FoxPro or Visual Basic. For one thing you are dealing with a larger number of entities rather than just a single environment: The Web server, a connector application of some sort and the backend application, HTML pages and code. The complexity of how many different pieces are involved varies between the various approaches to development. Typically, youll use a Browser to test your code, rather than simply running an application. You need to have a basic understanding of how the components fit together in order to make all the pieces work together. The promise of component based software is starting to materialize with the Web, but as of now, its not necessarily easy to make the components play nice. Interface limitations of HTML Although typical HTML output can be very visual, there are various limitations in HTML that require re-thinking your typical database application user interface. No data access from clientThe browser has no direct access to the data which is maintained and accessed by the server. Data access is transaction based and any updates based on data retrieved from the server typically required the HTML document containing the form data to be reloaded. Limited object model/scriptingAlthough both Microsoft and Netscape provide enhanced HTML form interfaces to their browsers via JavaScript and VBScript, the object model of these scripting engines are extremely limited compared to full blown visual tools and lack direct data access. Interface generated by the serverIf data access is required the HTML page is always loaded with data loaded from the server. Each time the data is updated on the server needs to reload the browser page and repopulate the data on the form. No easy way to print outputAll output generated is HTML and there's no graceful way to print it other than using the Browsers Print option, which also has the side effect of re-loading the current page or script. There are some third party workarounds such as using Adobe Amber, but none are natively supported. Mostly non-visual Development For the most part Web based application development is non-visual. While you can use visual HTML editors like FrontPage, Visual InterDev or WebEdit to build the HTML pages you display on browsers, the actual application code you write is usually transaction based involving mostly straight database code (queries, validations, inserts etc) and either generating the HTML via code or loading HTML pages from disk to evaluate embedded logic. Server based programming Web application request handlers are basically server scripts, which are non-interactive and transaction based. Each link, or form request generates a hit on the server which in turn runs the request handler in response. Web programming usually involves: Validating user input on forms Running queries Generating HTML (or loading and outputting scripted HTML from disk) How The Active Web works Figure 1.1 shows how Microsoft's Active architecture binds the client and server sides together. When looking at the figure keep in mind the strict separation between the client and server sides. Although some of the components like ActiveX controls and ISAPI extensions are Microsoft specific, the frameworks by Netscape and others look surprisingly similar. INCLUDEPICTURE "D:\\migration\\whitepapers\\ActiveWeb.gif" \* MERGEFORMATINET Figure 1.1 - Browser and Web Server relationship. Note the distinct line between the two. The Browser provides the Active interface The Web browser provides the interface to an application or page viewer. The browser provides the interactive, visual face of a Web application. The interface consists mostly of HTML text along with graphics and basic input forms that can be embedded inside of HTML documents. All data input is handled via HTML formatted pages that are interpreted and then displayed by the browser. Browser scripting languages like VBScript and JavaScript can be used to tie some logic to the HTML page. Scripting provides conditional output creation and an object/event model that allows manipulation of various interface and browser objects as well as responding to events fired by various form controls and form events. Keep in mind though: There is no direct data access from the client side, so you can't do data validation based on a table lookups unless all the information is somehow created into the HTML page directly. If you need data to be displayed in the browser the data needs to be generated into the HTML page at the server. ActiveX Controls and Java Applets can be used to enhance Web pages with high power add-ins or operating system specific components. The controls can be manipulated using VBScript using a typical Property, Event, Method mechanism. Web Server provides data / application connectivity On the other end of the connection sits the Web server. The Web servers main responsibility is, well, to serve content. Traditionally this has been static HTML pages that served from disk, but the Web servers role is expanding to provide the basic logic to interact with backend applications via the ISAPI interface. The Web server is responsible for providing the database access and the connectivity to the actual processing application. The Web server itself knows nothing about applications and calls helper scripts (ISAPI extensions) to do the work for it. ISAPI is the building block for server side extensions Typically the server calls an ISAPI or Common Gateway Interface (CGI) extension script which is responsible for returning HTTP compliant output. The Internet Server API (ISAPI) is a highly efficient Windows based API that allows extensions to run in the Web server's address space, which make them very fast and resource friendly. ISAPI extensions can either be self-contained and create the required output on their own or act as a connector and call another application to perform the actual request processing for it. Keep in mind that ISAPI and CGI both are interfaces only and do not comprise a specific language implementation. ISAPI can be implemented in any language that can create true Win32 DLLs. CGI can be implemented by any language that supports creation of EXE files and can read and write to and from Standard Input and Output. Whats important to remember is that Visual FoxPro never runs as an ISAPI application directly it lacks the ability to create an ISAPI extension directly! Rather an ISAPI extension interacts with Visual FoxPro via some sort of messaging mechanism (OLE Automation, DDE, file based messaging etc.). If implemented correctly this process can be extremely fast and efficient. Both FoxISAPI and Web Connection use this approach to let you use Visual FoxPro to build application logic. Figure 1.2 shows how ISAPI is the building block of most of the Web server extensions that Microsoft is creating. All the major tools provided for IIS by MS including the MS Internet Database Connector, and the ActiveX server framework are implemented via the ISAPI interface. FoxISAPI and Web Connection which will be discussed later on are also implemented using ISAPI as the connector interface and qualify as custom connector applications on the chart. INCLUDEPICTURE "D:\\migration\\whitepapers\\iis_isapi.gif" \* MERGEFORMATINET Figure 1.2 - Microsoft's Internet Server API is the building block for Web server extensions What you need to get started Here's a short list of hardware and software required to run a Web application: Fast Pentium box (133Mhz/32-64megs) While you can get by with smaller machines I would recommend this as a good baseline installation. I've run several Web sites on hardware as low as a 486-66 with 32 megs running NT 3.51 with decent results, but if your site gets more than a few thousand backend hits day the above is a good minimum. For high volume sites multiprocessor boxes are the preferred way to go. Dual processors allow the Web server and Visual FoxPro to not compete for CPU cycles as much. Also, additional memory (128megs or more) can provide dramatic improvements in database (especially Read operations) and Web server performance as NT uses the memory for disk caching. Windows NT Server (recommended) Windows NT Server is an excellent platform for running a Web server and for acting as an application server. Many Web servers will run on Windows 95 and NT Workstation, but Windows 95 Web services are noticeably slower and NT Workstation has some serious licensing limitations that make it unsuitable for public Web server use, although it provides the same performance as NT Server. Included with NT Server 4.0: TCP/IP Network ProtocolTCP/IP must be loaded on the network or local machine in order to be able to take Web requests. Note: You don't need to have a network installed in order to test Web applications locally. You can tie TCP/IP to your network adapter, or if you don't have one to your Dialup Networking service. Web Server (MS IIS)Naturally, you'll need a Web server. NT 4.0 ships with MS Internet Information Server 3.0, which is fast and powerful and hooked into Microsoft's Internet strategy. Other good servers available include Commerce Builder by the Internet Factory, Website by O'Reily and Purveyor by Process Software. All of these servers support ISAPI which will be the focus of our discussion here.Note: The following examples are for IIS. The Internet Database Connector and the Active Server Page are available only for IIS, while FoxISAPI works on all ISAPI based Web servers. Connector Interface/Application You'll also need a 'connector' application that handles tying your FoxPro data the Web server. A connector application is a script tool that provides services for accessing another application or a scripting engine via an ISAPI DLL. Active Server Pages uses an ISAPI extension to provide the interpreting of .ASP files in a specialty DLL. FoxISAPI and Web Connection both use an explicit connector DLL that is called directly of an HTML link. Web browser In order to test your application you need a Web browser. I'll be using Internet Explorer 3.0 here, but any late browser should do. Try and get one of the latest browsers from Microsoft or Netscape as they make up over 90% of the browser market and provide the most advanced features that you will encounter when cruising the Web. Basic HTML skills You knew this was coming, right? Yes, in order to build Web applications you need to have at least a passing acquaintance with HTML. While it's possible to build HTML graphically using HTML editors like FrontPage, PageMill, NetObject etc, it's often required to generate HTML that gets inserted into existing documents - in order to do that you have to know a little about the various tags associated with text formatting. It's easy and best picked up by looking at the source of existing HTML pages. Everything can run on one box! For development purposes you can set up a single machine to serve as your Web server and development platform. You don't need to be on network as you can access the Web server via its local IP address (127.0.0.1 or localhost). Active Server Pages Active Server Pages (ASP) is part of Microsoft Internet Information Server 3.0 and can be downloaded from the Microsoft Web site ( HYPERLINK "http://www.microsoft.com/iis" http://www.microsoft.com/iis). In short, Active Server Pages is a sophisticated, server side, object based scripting engine that allows mixing code and HTML in the page using (currently) Visual Basic Script or JavaScript. INCLUDEPICTURE "D:\\migration\\whitepapers\\aspobj.gif" \* MERGEFORMATINET Figure 1.3 Active Server is composed of a number of objects that are managed by the ASP.DLL ISAPI extension. Tight integration with IIS ASP is actually a part of Internet Information server and installs when you upgrade IIS 2.0 to 3.0. The integration into the server itself is very smooth by implementing an ISAPI extension with a script map to provide transparent support for interpreting any page with .ASP extension. This mechanism provides the illusion to the developer of simply editing an HTML pages and enhancing it with HTML. Great care has been taken to provide an efficient environment for Active Server. The ISAPI extension handles multi-threading of requests and connection pooling for ODBC connections to provide fast access to dynamic content. Object Based Architecture The entire Active Server framework is based on components that interact to provide access to the entire environment to the developer. Figure 1.3 shows the base components that ship with Active Server. The various components provide access to the vital pieces that are required to build sophisticated Web applications. Heres a list of the base framework components and what they do: Request ObjectThe Request object provides information about the current Web request. It returns information about form variables captured on an HTML form, information about the server and its status, and access to the HTTP header to retrieve information such as HTTP Cookies and Authentication information. Some of the collections available are Form, QueryString, Cookies and ServerVariables. Response ObjectWhere the Request object provides information about the input from the Web server, the Response object is responsible for creating output for the Web server. ASP pages interpret HTML as usual, but in addition the Reponse object allows generating output under code control. The Response.Write method allows writing output directly. You can also manipulate the HTTP header, set the HTTP Cookie collection and write entries to the IIS log.The following retrieves a few form variables from an HTML form submission and echos whether the user is a new visitor or repeat: <% lcName=Request("Name") 'Retrieve an HTML form variable lcAddress=Request("Address") 'Reading Cookies if Request.Cookies("wwVisitor") = "" then Response.Cookies("wwVisitor") = now ' and write Response.Write("New Visitor") else Response.Write("Repeat Visitor") end if %> Session/Application ObjectsThis pair of objects provides a mechanism for keeping state between requests. Web applications are typically stateless, which means that each request needs to be fully self contained. The Session and Application objects allow keeping state between requests. Active Server creates these two predefined objects and allows adding property values to them. The Session object manages a user session and has persistence for the duration of this users visit on the site. When a user hits your site a new session object is created and the Session.OnStart method is fired. From then on the session object is accessible for each request. You can add variables to the session object and reference these variables between requests. The session object is implemented via HTTP Cookies and will not work with non-Cookie capable browsers!The Application object is similar to the Session object except that the Application object is persistent for the lifetime of the application a specific Web server virtual root directory. As with the Session object the Application object has OnStart and OnEnd methods and the ability to attach properties to the Application object. Since the Application is a global and accessible from simultaneous Web requests that are multithreaded access to these global properties needs to be tightly controlled by using the Lock/Unlock methods to prevent simultaneous overwriting of values by two sessions.The following creates a new database connection or reuses an existing one based on whether a connection object was attached to the Session object: <% '*** Open the Connection - create a new object or reuse existing IF IsObject(Session("goConn")) THEN SET Conn=Session("goConn") ELSE Set Conn = Server.CreateObject("ADODB.Connection") Set Session("goConn")=Conn END IF %> Database Connectivity with Active Data Object (ADO) Active Server provides built-in database connectivity via Active Data Objects or ADO. This ODBC based server component (yes, its a COM based engine much like VBs DAO or RDO). It provides the following features: Lightweight ODBC ConnectorAlthough ADO is an OLE based component that gets created from within an Active Server page, it is a very lightweight data interface that provides excellent performance by implementing only a thin layer ontop of the native ODBC interface. ADO shares a similar interface with VBs Remote Data Objects (RDO), but provides an even leaner interface and much better performance. Make no mistake about it ADO is fast and provides good performance to FoxPro data with the VFP ODBC driver. Implements OLE DB (ODBC 3.0)ADO works with ODBC 3.0 and the new OLE DB interface specification that promises to provide access to any kind of data including non-structured, non-database data. Based on Visual Basics Remote Data ObjectADO shares a similar interface with VBs Remote Data Objects (RDO), but provides an even leaner interface and much better performance. Its fast especially when tied to a persistent connection object!Make no mistake about it even though ADO uses ODBC it is fast and provides good performance to FoxPro data with the VFP ODBC driver. Implemented as Automation ObjectAn ADO connection is created by using CreateObject and instantiating a COM based Automation object. This means that you can use ADO from within Visual FoxPro either for testing or for actual data access data through ADO. Heres an example of using ADO for logging custom log information logged into a Visual FoxPro database with one link and then retrieving the log with another: '*** ODBCLOG.ASP '*** Logging page - this page logs visitor info into ' a VFP table via ADO <% '*** If visitor doesn't have a cookie log the hit as a new visitor if Request.Cookies("wwVisitor") = "" then '*** First time hit - create a cookie for the user Response.Cookies("wwVisitor")=now '*** Open the connection to the RASLOG ODBC database Set Conn = Server.CreateObject("ADODB.Connection") Conn.Open("dsn=RasLog") sql="INSERT INTO wwPageLog (Page, TimeStamp, Browser, Referer, IP, Other)" sql=sql + "VALUES ('Default.asp'," sql=sql + "datetime()," sql=sql + "'" & Request.ServerVariables("HTTP_USER_AGENT") & "'," sql=sql + "'" & Request.ServerVariables("HTTP_REFERER") & "'," sql=sql + "'" & Request.ServerVariables("REMOTE_HOST") & "'," sql=sql + "'" & Request.Cookies("wwVisitor") & "')" ' Response.Write(sql) ' debug Conn.Execute(sql) Conn.Close SET Conn = nothing end if %>
Time | Referer | Browser | IP Address |
<% =rs("Timestamp")%> | "><% =rs("Referer")%> | <% =rs("Browser")%> | <% =rs("IP")%> |
Total number of hits: | <% =rs("TotalHits")%> |
This page has been hit: <% SET oServer = Server.CreateObject("wwWebtools.AspTools") Response.Write(oServer.IncCounter("ASPDemoCounter")) lcCompany=Request("txtCompany") %> times.
The following table was generated by Visual FoxPro:
<% =oServer.CustList( (lcCompany) )%>
This code is very straight forward. However, in order to really optimize access to Automation servers its crucial to persist servers across requests. Without this loadtime for the server is excessive and makes use of Automation servers inappropriate. To persist a server you can use the ASP Session object. Replace the CreateObject code above with: IF IsObject(Session("soServer")) THEN SET oServer = Session("oServer") ELSE SET oServer = Server.CreateObject("wwWebtools.AspTools") SET Session("oServer")= oServer END IF The server reference is now active for the duration of the users session and access speed to the server is drastically improved. Active Server Summary Pros: Tight Integration with IISBecause Active Server is tightly integrated into IIS it provides excellent performance thats tuned to the Web server and its multithreaded environment. Thread management and ODBC connection pooling is managed for you to an extent. No hassle configurationSince the code and HTML both reside in the same document, setup for building an Active page is minimal. If data acess is required only a ODBC connection needs to be configured and youre off and running. Very easy for simple active contentScripting in HTML is straightforward and VBScript is reasonably powerful to do the basics language handling. ADO provides data quick access with a minimal object model that can be picked up fairly quickly. Extensible with Automation objects Think of Active Server as the HTML driving the application Cons: Code ManagementBuilding complex logic inside of HTML pages can be tedious even when using a tool like Visual InterDev. Trying to dig through a long HTML document and finding code inside of it is no fun. Structured coding also goes out the window in many cases as code follows the HTML output more than it necessarily follows the program logic. Limited Development EnvironmentAlthough Visual InterDev provides a rich shell and a number of very useful Wizards for building Active Server Pages, development support for coding and debugging is very primitive. Theres no way to step through code and see variable values in the development environment for example. Error handling support in VBScript is a far cry from sophisticated where errors cannot be delegated but must be fully anticipated and managed at the time of error. The alternative is an ugly VBScript or ODBC runtime error message. Automation Server ScalabilityASPs ability to call external Automation servers is extremely powerful. Unfortunately, when calling Visual FoxPro servers calls to any single VFP server are serialized since VFP can only load one instance of a particular server at a time and process that request on its single application thread. True multi-threading of Automation servers is supported currently only from pure COM based servers that are built in low level languages like C++ or Delphi.What this means is that if your Web server gets busy enough to require more than one instance of your Automation server you will have no way to scale up. You can rearrange your servers to break up the request load on each server by splitting into smaller servers, but even that might not be sufficient. Scripting Language LimitationsFor building full featured applications the VBScript language is fairly limited. VBScript is a subset of VB for Applications and misses a number of that VB subsets features. Theres no access to the WinAPI or even to VBs file handling functions for many features that are commonly required in any programming language youll be required to call Automation objects to help out. With the overhead involved this might not always be a good option. ODBC Data ManagementData access via ADO to VFP tables is straightforward and speed is acceptable. However, if you need to handle maintainence tasks to your data that require Exclusive database access its next to impossible to implement these via a Web based interface. Since ODBC keeps tables open and multiple requests might hit your pages simultaneously its unlikely you can ever get an Exclusive lock on a table to say clear a file (log files can get big) or even do things as simple as APPENing data from an external file. True Exclusive access to VFP data requires shutting down the Web server and running a VFP program against the data. FoxISAPI Visual FoxPro's new capability to create OLE servers has brought about another slick option for implementing Visual FoxPro based Web applications. What if you could use an OLE server to respond to a request placed from a Web page to handle the data processing and HTML page generation? With a cool called FoxISAPI that's provided by Microsoft with Visual FoxPro you can do just that. INCLUDEPICTURE "D:\\migration\\whitepapers\\foxisapi.gif" \* MERGEFORMATINET Figure 1.5 - FoxISAPI uses an ISAPI DLL to create an instance of an OLE server and call the specified method in the server. Connect VFP OLE servers to HTML HREF or form links FoxISAPI is used by calling the FoxISAPI.dll from an HTML link or form. A typical HTML link looks like this: HREF="/scripts/foxisapi.dll/Tserver.Tclass.Tmethod?UID=1111&Name=Rick" ISAPI DLL instantiates persistent OLE Automation object FoxISAPI works by calling an ISAPI script from an HTML HREF or form link. The FoxISAPI.dll creates an object reference to the object passed as part of the URL and calls the specified method. The object is persistent so repeated access to the object is very quick as the object is never reloaded unless explicitly unloaded (more on that below). In the example above FoxISAPI parses out the ClassId and method call to instantiate the Tserver.Tclass OLE server (equivalent to doing CREATEOBJ("Tserver.Tclass") in VFP) and then goes ahead and calls the Tmethod() method (equivalent to lcResult = oServer.Tmethod(cParm1,cParm2,nParm3)). FoxISAPI expects your method to return an HTTP compliant result string - in most cases this result will be an HTML document, but could also be an HTTP request for Authentication or Redirection. Passes form variables as parameter and server variables in an INI file When FoxISAPI calls your OLE server it passes along 3 parameters to each request method that is called. Your server method that respond directly to request must support these three parameters: lcFormVar The first parameter contains any 'parameters' passed on the Query string as described in the example above or any form variables retrieved from an HTML form via an HTTP GET or POST.The format of the parameter string contains a key/value pair for each of the form variables or 'parameters' passed. The keys in the above example are UID and Name the values are 1111 and Rick. These key value pairs are what is known as URL encoded, which means they follow a specific protocol of encoding to allow passing special characters on the URL or via form variables. It works something like this: Key value pairs are separated by &. Spaces are converted to +. All 'extended' characters are converted to Hex escape codes. The escape code uses a percent sign plus a hex number to store the ASCII code of the characters. For example a carriage return (ASC(13)) is encoded as %0D. The EMPLOYEE example in your \VFP\SAMPLES\SERVERS\FOXISAPI directory includes a decoding algorithm as does the starter FoxISAPI class provided on the DevCon CD (FoxISAPI::DecodeURL). lcIniFileThis parameter contains the path to an INI file that contains all the server, browser and system variables. You can retrieve these with calls to the GetProfileString API call (or use the CDs FoxISAPI::GetCGIVar(cVarname,cSection)). lnReleaseFlagThis parameter determines whether the reference to the OLE server will be kept or released. By default it's a good idea to keep the reference to keep a connection in order to minimize load time of the server. The parameter is passed in by reference so changing it in your code will effectively0 - Keep Server Reference (default)1 - Release Server Reference Must return HTTP compliant output Once your code gets control you can use VFP as you see fit to run queries or run any other kind of transaction or logic operation using FoxPro code. The end result of each exit point of your method must be a HTTP compliant string. In most cases the output will be an HTML document, but you have to be sure to add an HTTP header to the top of it. Output should look like this: HTTP/1.0 200 OK Content-type: text/html")
THIS.SendLn("Encoded Form/URL variables: "+lcFormVars+"
")
THIS.SendLn("Decoded UserId: "+ THIS.GetFormVar("UserId")+"
")
THIS.SendLn("Decoded UserName: " +THIS.GetFormVar("UserName")+"
") *** Show the content of the FOXISAPI INI server/browser vars IF !EMPTY(lcIniFile) AND FILE(lcIniFile) CREATE CURSOR TMemo (TFile M ) APPEND BLANK APPEND MEMO TFile from (lcIniFile) THIS.SendLn("Here's the content of: "+lcIniFile+; ". You can retrieve any of these with THIS.GetCGIVar(cVarname,cSection):
") THIS.SendLn([THIS.GetCGIVar("HTTP_USER_AGENT","ALL_HTTP"): ]+; THIS.GetCGIVar("HTTP_USER_AGENT","ALL_HTTP")) THIS.Send("
") THIS.SendLn(Tmemo.Tfile) THIS.SendLn("") USE in TMemo ENDIF THIS.SendLn("
list - Optional loHTML.SetAllowHTMLTables(loCGI.IsHTML30()) *** Show entire result set as an HTML table loHTML.ShowCursor() *** Center the table loHTML.SendLn("