Scripting Support in Web Connection

Scripting support in Web Connection provides the ability to move the display formatting of pages to external files rather than having your Fox code generate the user interface. In typical Web applications, these external script files become your user interface layer of the application. Moving files externally:

Web Connection supports three scripting mechanisms of which the first is a special case:

Scripting 101

Scripts are little programs that are based on VFP's TEXTMERGE mechanism. Web Connection converts the scripts you create into a real runnable PRG file that outputs into a TEXTMERGE file which is captured and returned to the Web browser.

Here's a simple example script page:

<html>
<body style="font:normal normal 10pt Verdana">
<h1>Customer Table Display</h1>
<hr>
<%
SELECT * FROM TT_CUST INTO Cursor TQuery 
lnReccount = RECCOUNT()
%>
Customer Table has <%= Reccount() %> records.<p>

<table border=1 style="font:normal normal 8pt Tahoma">
<%
SCAN
%>
<tr><td><%= TQuery.Company %></td><td><%= TQuery.Address %></td></tr>
<% ENDSCAN %>
</table>

</body></html>

To run this page save it to a .WCS (Web Connection Script) extension and call it via Web URL:

http://localhost/wconnect/CustomerTable.wcs

Notice that you use <% %> for blocks of script code that run like a program, and <%= %> to output expressions that return a value. <%= %> should only be used with a single expression while <% %> can host multiple commands (translated into TEXTMERGE terms <%= %> are TextMerge expressions, while <% %> is considered pure code. Anything else (the static HTML) is what goes between TEXT...ENDTEXT directives).

If you have an error in your code the page will bring back an error. For example if I misspell Reccount() above as Recount() you get a Scripting Error Page that says:

Error:  File 'recount.prg' does not exist. 
Code: Recount() 
Error Number: 1 
Line No: 9 

If you're in debug mode (DEBUGMODE .T. in wconnect.h) Web Connection will also try to find the line of code that caused the error and position the cursor on it. This is not always possible due to the nature of the error, but in most cases and especially those were a simple typo occurred you can edit the change save and re-run the request immediately.

Fixing up the example
Let's change the example around a little more to allow a little more flexibility. Let's fix up the display by adding the WestWind stylesheet, clean up the table display and add another field (phone) and finally support for asking the user which records he wants to see:

<html>
<head>
<title>Customer Table Scripting Demo</title>
<LINK rel="stylesheet" type="text/css" href="westwind.css">
</head>
<body>
<h1>Customer Table Display</h1>
<hr>
<%
lcCompany = UPPER(Request.Form("txtCompany"))
lcWhere = ""
IF !EMPTY(lcCompany)
   lcWhere = "WHERE UPPER(company) = lcCompany"
ENDIF


SELECT * FROM TT_CUST &lcWhere ;
   INTO Cursor TQuery ;
   ORDER BY Company
   
lnReccount = RECCOUNT()
%>

<form method="POST" action="customertable.wcs">
Company Filter: <input type="text" name="txtCompany" value="<%= lcCompany %>">
<input type="Submit" value=" Get Customers">
</form>

<hr>
Selected  <b><%= Reccount() %></b> records.<p>

<table border="1">
<tr bgcolor="#EEEEEE"><th>Company</th><th>Address</th><th>Phone</th></tr>
<% SCAN %>
<tr>
	<td  valign="top"><%= TQuery.Company %></td>
    <td><%= IIF(EMPTY(TQuery.Address),[<br>],DisplayMemo(TQuery.Address)) %></td>
    <td><%= IIF(EMPTY(TQuery.Phone),[<br>],DisplayMemo(TQuery.Phone)) %></td>
</tr>
<% ENDSCAN %>
</table>
<hr>
<HR>
</body>
</html>

Note that this form has now become both an input and output form at the same time because we're using the form field (txtCompany) in a <FORM> tag to ask the user to enter the company filter for the list to create. On each request we then retrieve the user's input using the Request.Form method into a variable (which must be PRIVATE not LOCAL in order to be visible anywhere but in the current <% %> block) lcCompany. We use the variable to also echo it back in the edit box by using <%= lcCompany %> to set the VALUE= attribute of the txtCompany field. This way the field always displays the user's last choice.

Script Modes
Web Connection's scripting engine can use 2 modes to run scripts:

Objects available in scripts
Scripts have the following Web Connection objects available:


These objects are the standard Web Connection objects and you can look up their properties and methods separately in the various class references.


For additional examples of how to use scripting see the scripting samples on the Web Connection Demo page.

Templates 101

This topic is incomplete
Templates are similar to Scripts using very similar ASP like syntax with <% %> and <%= %> tags. The main difference between scripts and templates is that templates are not programs but as the name implies templates that are evaluated. Web Connection uses a set of MergeText functions to walk through the document top to bottom and evaluate each expression or codeblock. Each codeblock or expression is evaluated exactly once which means you can't create blocks like the following:

<% scan %>
Some HTML <%= datafield %>
<% endscan %>

Since each expression is evaluated once the SCAN and ENDSCAN would be interpreted as individual commands and would cause an error. A template can however run complex code - it just has to happen in a single script block.

You can however use any combination of expressions, UDF calls, object properties and methods and any PRIVATE variables that are in scope from the calling code.

<HTML>
<BODY>
<%
PUBLIC oCust
oCust = CREATE("cCustomer")
oCust.Load( VAL(Request.QueryString("PK")) )
%>

Welcome back, <%= oCust.cFirstName %>. Your credit limit is <%= oCust.GetCreditLimit() %>.

<hr>
Time created: <%= TIME() %>

<%
RELEASE oCust
%>
</BODY>
</HTML>

Notice that you can use code blocks, but because templates are not self-contained programs any variables that you want to use throughout the page must be declared as PUBLIC (oCust here). However, any regular expression can be accessed as needed.

One thing to understand about Codeblocks is that they are evaluated using Randy Pearson's CodeBlock, which basically evaluates each line of code individually. This means loops etc. are very slow. Codeblock performs a lot of checking and parsing and thus codeblocks are fairly slow. For this reason we recommend that you don't use them excessively in template pages, but rather put your business logic into Process class code and then call the template from there.

* Process method
FUNCTION CallTemplate
PRIVATE oCust
oCust = CREATE("cCustomer")
oCust.Load( VAL(Request.QueryString("PK")) )

Response.ExpandTemplate( "\inetput\wwwroot\wwdemo\CallTemplate.wc")
ENDFUNC

We'll talk more about this process at the end of this topic, but this approach is much cleaner as the business logic that deals with setting up the request now runs in a easily debuggable and efficient VFP class and separates the business logic from the User Interface in the template page.

Objects available in Templates
Templates have the following Web Connection objects available to them:


Note that the Response object is in parenthesis here! You can use the Response object, but only if and only if you use the llNoOutput flag on its various methods.
Templates are evaluated into a string and that string is then sent to output all at once after parsing is complete, so using the Response object directly would cause output sent to go before any content in the actual template.

If you need to modify the behavior of the Response object such as changing the HTTP header you need to first clear the object, and then reassign the custom header:

<%
Response.Clear()
Response.ContentTypeHeader("text/xml")
%>
<?xml version="1.0"?>
<docroot>
<test>test value</test>
<%= Response.Write("</docroot>",.T.) %>

(note the use of the .T. parameter (llNoOutput) on the Response.Write method call! Most response method include this parameter)

If you do this frequently you should consider using Process class methods to handle the header.

oHeader = CREATE("wwHTTPHeader")
oHeader.DefaultHeader()
oHeader.AddCookie("TestCookie","Rick")

Response.ExpandTemplate(Request.GetPhysicalPath(), oHeader)

Scripts like templates can use expressions simply by embedding an expression into the HTML text with <%= %>. Templates should use expressions as much as possible for optimal performance as these are simply evaluated on the fly. You can of course call UDF functions, as well as method of any class that's in scope.


Tip: Editing .wcs and .wc files in FrontPage or Visual Interdev
By default these tools don't know about .wc and .wcs and won't allow you to edit these files as HTML files. In FrontPage you can select the file and right click and use the Open With... option to open the file manually. For a permanent mapping of the extensions to the FrontPage editor use the Tools|Options|Configure Editors dialog box to attach the extensions to the FrontPage editor. Simply copy the settings for the .HTM extension. In Visual Interdev you can open the file in the editor which will come up as an unknown (text) document at first. Close the file and then go to the Project Explorer pane and select the file still in the list. Right click and select Open With... and select the HTML Editor. The dialog that pops up also has a Set As Default button which creates a permanent mapping in VI to bring up the HTML editor for the templates.

FrontPage Themes and special Bot extensions can't be used with foreign extensions. However, you can fool FrontPage, but choosing a scriptmap other than WCS or WC that it does support. Since IIS uses a number of scriptmaps that you won't need (like the old IDC/HTC extensions) you can map script or templates to those instead. All of FrontPage's features will work then correctly. The same can be applied with custom scriptmaps you create.


How to call scripts and templates

Scripts and templates can be invoked in two ways:

If you call scripts directly via scriptmap the pages must be fully self-contained and provide and handle all inputs and outputs.

But you can also run a Web Connection process method first and then from witin it call out to the script page. The advantage of this approach is that you can separate the user interface (the script page) from the business logic (the Process class method). In addition you can set up objects and create private variables that will also be in scope in the script page.

* Simple Process method that calls a template
Function CallTemplate
PRIVATE oCust


oCust = CREATE("cCust")
oCust.Load( VAL(Request.QueryString("PK")) )

... additional processing against customer object


*** Now display the template
Response.ExpandTemplate( "\inetpub\wwwroot\myapp\CallTemplate.wc" )

ENDFUNC

The template can now use the oCust object as part of the script as long as oCust was declared as PRIVATE (the default if you don't declare it).

<HTML>
<BODY>

Welcome back <%= oCust.cFirstName %>

Feel free to shop around. Your current credit-limit is: <%= oCust.CalcCreditLimit() %>

</BODY>
</HTML>

Notice that any PRIVATE variables you declare will be in scope and can be called from the template or script. Any Classes or UDF functions that are in scope or the call stack also can be called directly.

Paths for ExpandTemplate and ExpandScript
Notice that in the example above I hard coded the path of the template into the call to ExpandTemplate. In general that's a very bad idea. Instead you should do one of two things:



  Last Updated: 12/31/2005 | © West Wind Technologies, 2008