You are on page 1of 336

PowerDynamo Users Guide

PowerDynamo
Version 3.5
MC00341
Last revised: October 1999
Copyright © 1989-1999 by Sybase, Inc. All rights reserved.
This publication pertains to Sybase database management software and to any subsequent release until otherwise indicated in new
editions or technical notes. Information in this document is subject to change without notice. The software described herein is furnished
under a license agreement, and it may be used or copied only in accordance with the terms of that agreement.

To order additional documents, U.S. and Canadian customers should call Customer Fulfillment at (800) 685-8225, fax (617) 229-9845.
Customers in other countries with a U.S. license agreement may contact Customer Fulfillment via the above fax number. All other
international customers should contact their Sybase subsidiary or local distributor. Upgrades are provided only at regularly scheduled
software release dates. No part of this publication may be reproduced, transmitted, or translated in any form or by any means, electronic,
mechanical, manual, optical, or otherwise, without the prior written permission of Sybase, Inc.

Sybase, the Sybase logo, ADA Workbench, Adaptable Windowing Environment, Adaptive Component Architecture, Adaptive Server,
Adaptive Server Anywhere, Adaptive Server Enterprise, Adaptive Server Enterprise Monitor, Adaptive Server Enterprise Replication,
Adaptive Server Everywhere, Adaptive Server IQ, Adaptive Warehouse, AnswerBase, Anywhere Studio, Application Manager,
AppModeler, APT Workbench, APT-Build, APT-Edit, APT-Execute, APT-FORMS, APT-Translator, APT-Library, Backup Server,
ClearConnect, Client-Library, Client Services, Data Pipeline, Data Workbench, DataArchitect, Database Analyzer, DataExpress,
DataServer, DataWindow, DB-Library, dbQueue, Developers Workbench, Direct Connect Anywhere, DirectConnect, Distribution
Director, E-Anywhere, E-Whatever, Embedded SQL, EMS, Enterprise Application Server, Enterprise Application Studio, Enterprise
Client/Server, Enterprise Connect, Enterprise Data Studio, Enterprise Manager, Enterprise SQL Server Manager, Enterprise Work
Architecture, Enterprise Work Designer, Enterprise Work Modeler, EWA, Gateway Manager, ImpactNow, InfoMaker, Information
Anywhere, Information Everywhere, InformationConnect, InternetBuilder, iScript, Jaguar CTS, jConnect for JDBC, KnowledgeBase,
MainframeConnect, Maintenance Express, MAP, MDI Access Server, MDI Database Gateway, media.splash, MetaWorks, MySupport,
Net-Gateway, Net-Library, NetImpact, ObjectConnect, ObjectCycle, OmniConnect, OmniSQL Access Module, OmniSQL Toolkit,
Open Client, Open ClientConnect, Open Client/Server, Open Client/Server Interfaces, Open Gateway, Open Server, Open
ServerConnect, Open Solutions, Optima++, PB-Gen, PC APT Execute, PC DB-Net, PC Net Library, Power++, power.stop, PowerAMC,
PowerBuilder, PowerBuilder Foundation Class Library, PowerDesigner, PowerDimensions, PowerDynamo, PowerJ, PowerScript,
PowerSite, PowerSocket, Powersoft, PowerStage, PowerStudio, PowerTips, Powersoft Portfolio, Powersoft Professional, PowerWare
Desktop, PowerWare Enterprise, ProcessAnalyst, Report Workbench, Report-Execute, Replication Agent, Replication Driver,
Replication Server, Replication Server Manager, Replication Toolkit, Resource Manager, RW-DisplayLib, RW-Library, S Designor, S-
Designor, SDF, Secure SQL Server, Secure SQL Toolset, Security Guardian, SKILS, smart.partners, smart.parts, smart.script, SQL
Advantage, SQL Anywhere, SQL Anywhere Studio, SQL Code Checker, SQL Debug, SQL Edit, SQL Edit/TPU, SQL Everywhere, SQL
Modeler, SQL Remote, SQL Server, SQL Server Manager, SQL SMART, SQL Toolset, SQL Server/CFT, SQL Server/DBM, SQL
Server SNMP SubAgent, SQL Station, SQLJ, STEP, SupportNow, Sybase Central, Sybase Client/Server Interfaces, Sybase Financial
Server, Sybase Gateways, Sybase MPP, Sybase SQL Desktop, Sybase SQL Lifecycle, Sybase SQL Workgroup, Sybase User Workbench,
SybaseWare, Syber Financial, SyberAssist, SyBooks, System 10, System 11, System XI (logo), SystemTools, Tabular Data Stream,
Transact-SQL, Translation Toolkit, UNIBOM, Unilib, Uninull, Unisep, Unistring, URK Runtime Kit for UniCode, Viewer, Visual
Components, VisualSpeller, VisualWriter, VQL, WarehouseArchitect, Warehouse Control Center, Warehouse Studio, Warehouse
WORKS, Watcom, Watcom SQL, Watcom SQL Server, Web Deployment Kit, Web.PB, Web.SQL, WebSights, WebViewer, WorkGroup
SQL Server, XA-Library, XA-Server and XP Server are trademarks of Sybase, Inc. 9/99

Unicode and the Unicode Logo are registered trademarks of Unicode, Inc.

All other company and product names used herein may be trademarks or registered trademarks of their respective companies.

Use, duplication, or disclosure by the government is subject to the restrictions set forth in subparagraph (c)(1)(ii) of DFARS 52.227-
7013 for the DOD and as set forth in FAR 52.227-19(a)-(d) for civilian agencies.

Sybase, Inc., 6475 Christie Avenue, Emeryville, CA 94608.


Chapter

iii
iv
Contents

About This Book ......................................................................................................................... xiii

C H APTE R 1 Databases and the Internet ............................................................ 1


Basic Web concepts......................................................................... 2
Storing, locating, and transmitting information on the Web ....... 2
Databases and the Web................................................................... 5
Gateways between Web servers and databases ...................... 5
Static and dynamic Web pages................................................. 6
Storing and accessing Web information in a database ............. 8
A glance at PowerDynamo............................................................... 9
The interpreter ........................................................................... 9
Web-site management ............................................................ 10
HTML templates and scripts.................................................... 10
The data store ......................................................................... 13
The template repository........................................................... 13
How the pieces fit together ...................................................... 13

C H APTE R 2 Getting Started with PowerDynamo ............................................ 15


Overview ........................................................................................ 16
Before you begin ..................................................................... 16
Installing the sample database ................................................ 17
Starting Dynamo programs ..................................................... 18
Creating the sample Web site ................................................. 19
Looking at the sample Web site ..................................................... 20
Connecting from Sybase Central to the sample Web site ....... 20
Navigating the sample Web site .............................................. 21
Creating a template ........................................................................ 22
How dynamic content is held in HTML templates ................... 23
Creating a script ............................................................................. 25
Viewing template output in a browser ............................................ 27
Accessing the Web site locally ................................................ 27
Accessing the Web site over a network .................................. 29

v
Contents

CH APT ER 3 Working with Dynamo Web Sites................................................. 31


Working with Web sites .................................................................. 32
Web site architecture............................................................... 32
Before you begin ..................................................................... 33
Creating a Web site [Adaptive Server Anywhere] ................... 33
Creating a Web site [Adaptive Server Enterprise]................... 35
Creating a dynamic file-based Web site.................................. 36
Creating a connection profile for your Web site ...................... 38
Regenerating a Web site......................................................... 40
Deleting a Web site ................................................................. 40
The Utilities folder .......................................................................... 41
Starting the utilities .................................................................. 41
Working with folders and documents in your Web site .................. 42
Creating folders ....................................................................... 42
Moving or copying folders and documents.............................. 42
Deleting folders and documents.............................................. 43
Renaming folders and documents........................................... 43
Linking folders to directories on disk ....................................... 43
Working with templates .................................................................. 46
Creating a template ................................................................. 46
Viewing and editing templates................................................. 48
Embedding instructions in a template ..................................... 50
Passing variables from one document to another ................... 52
Importing and exporting documents ............................................... 55
Importing documents into a Web site ...................................... 55
Exporting documents from a Web site .................................... 56
Scheduling actions ......................................................................... 57
Removing a scheduled action ................................................. 58
Working with connections .............................................................. 60
The connection pool ................................................................ 60
Connection definitions ............................................................. 62
Creating, deleting, modifying and testing User connections ... 62
Working with permanent and temporary connections ............. 64
Managing the connection pool ................................................ 67
Copying a Web-site database [Adaptive Server Anywhere] .......... 69
Using the Performance Monitor ..................................................... 70

CH APT ER 4 Configuring Web Servers and Web sites .................................... 71


The Personal Web Server.............................................................. 72
Accessing a Web site using the Personal Web Server ........... 72
Preparing to use the Personal Web Server............................. 73
Starting the Personal Web Server........................................... 73
Viewing a local Dynamo document ......................................... 74
Configuring a Dynamo Web site .................................................... 76

vi
Contents

Configuring Web servers during installation ............................ 77


Configuring Web Servers manually......................................... 77
Configuring an ISAPI server........................................................... 79
Step 1: Edit the System Path in the System Properties window 79
Step 2: Install the Application Server ..................................... 79
Step 3: Create an ODBC System Data Source Name (DSN) 81
Step 4: Create a connection profile ......................................... 83
Step 5: Configure the Application Server ................................ 83
Configuring an ISAPI 4.0 server..................................................... 85
Configuring the IIS 4.0 Server ................................................. 85
Configuring an NSAPI server ......................................................... 86
Step 1: Edit the system path in the System Properties window 86
Step 2: Install the Application Server ...................................... 87
Step 3: Create an ODBC System Data Source Name (DSN) 91
Step 4: Create a connection profile ......................................... 92
Step 5: Configure the Application Server ................................ 93
Configuring a CGI or WIN-CGI server............................................ 94
Step 1: Edit the System Path in the System Properties window 94
Step 2: Install the Application Server ..................................... 94
Step 3: Create an ODBC System Data Source Name (DSN) 97
Step 4: Create a connection profile ......................................... 98
Step 5: Configure the Application Server ................................ 99
Configuring Web sites .................................................................. 100
Accessing the Dynamo Configuration folder ......................... 100
Setting Dynamo mappings .................................................... 100
How mapping information is stored.............................................. 105
Changing Dynamo configuration settings .................................... 106
Setting Dynamo MIME types........................................................ 109

C HA PTER 5 Dynamo Tags Tutorial ................................................................ 111


Overview of Dynamo Tags........................................................... 112
Tags tutorial ................................................................................. 113
Using the SQL tag ................................................................. 113
Using the FORMATTING tag ................................................ 115
Using the error checking tags................................................ 118
Using the INCLUDE tag ........................................................ 121
Using the SQL_INSERT tag .................................................. 123
The SCRIPT tag .................................................................... 125

C HA PTER 6 Writing DynaScripts.................................................................... 127


Overview of scripts....................................................................... 128
Script tutorials .............................................................................. 130
Embedding a Script in HTML ................................................ 130
Contents

Using variables and expressions........................................... 132


Using control statements....................................................... 133
Using functions...................................................................... 134
Using simple objects ............................................................. 135
Using arrays .......................................................................... 137
Passing variables from one document to another ................. 138
Using object inheritance ........................................................ 140

CH APT ER 7 PowerDynamo and Java ............................................................. 145


An introduction to Java................................................................. 146
Object-oriented and procedural languages ........................... 146
A Java glossary ..................................................................... 151
Java error handling................................................................ 152
Dynamo and Java ........................................................................ 155
Configuring Dynamo to use Java ................................................. 156
Using Java in a PowerDynamo script .......................................... 158
Arrays in Java........................................................................ 161
Method overloading and type conversion.............................. 162
Calling Jaguar components................................................... 163

CH APT ER 8 Working with XML Documents ................................................... 165


Dynamo and XML ........................................................................ 166
An introduction to XML ................................................................. 167
Valid and well-formed XML documents................................. 167
XML syntax............................................................................ 168
Creating XML documents............................................................. 170
Creating XML documents from the query object ................... 170
Creating custom XML documents from query result sets...... 172
Creating XML documents from queries using the FORMATTING
tag................................................................................... 172
Creating XML from DynaScript objects ................................. 174
Introduction to the Document Object Model................................. 177
What you can do with DOM................................................... 177
The DOM view of documents ................................................ 177
Using nodes to work with XML documents ........................... 179
The object interface to XML documents................................ 180
Error checking XML-handling scripts..................................... 181
Document Object Model examples .............................................. 182
Converting XML to HTML for sending to a browser .............. 182
Inserting data from XML into a database .............................. 184
Creating the DOMDocument object ............................................. 187
Working with elements ................................................................. 189
Using the DOMNode object to work with elements ............... 189

viii
Contents

Using the DOMElement object to work with elements .......... 190


Working with attributes................................................................. 191
Using the DOMNode object to work with attributes............... 191
Using the DOMAttribute object to work with attributes .......... 192
Working with text.......................................................................... 193
Obtaining all the text inside an element ................................ 194
Working with CDATA sections .............................................. 194
Escaping text with xmlEscape............................................... 195
Working with entities .................................................................... 196
Working with internal entities................................................. 197
Working with external entities................................................ 197
Working with other XML objects................................................... 199
Using the DOM interface to create and edit XML documents ...... 200
Creating a DOM document object ......................................... 200
Adding objects to DOM documents....................................... 200
Removing and replacing objects in DOM documents ........... 201

C HA PTER 9 PowerDynamo Mail Support ...................................................... 203


About PowerDynamo’s mail support ............................................ 204
Requirements for using PowerDynamo mail objects............. 204
Sending mail ................................................................................ 206
To send a mail piece ............................................................. 206
Receiving mail.............................................................................. 208
To retrieve mail from PowerDynamo ..................................... 208
Deleting mail ................................................................................ 210
Forwarding and replying to mail ................................................... 211
Forwarding mail..................................................................... 211
Replying to mail..................................................................... 212
A simple mail application.............................................................. 213

C HA PTER 10 Achieving Optimum Performance with PowerDynamo ........... 217


Performance requirements........................................................... 218
Processing of scripts ............................................................. 218
Minimizing the calls to the database ..................................... 219
Working with Connections to increase performance ............. 220
Designing your Web site .............................................................. 221
Increasing the performance of your Web site .............................. 222
Optimizing your document cache ................................................. 223
Setting a document cache size ............................................. 224
Setting a cachedOutputTimeOut value ................................. 225
The relationship between cache size and cachedOutputTimeOut
values ............................................................................. 226
Scheduling your scripts ................................................................ 228
Enhancing performance for non-cacheable documents ........ 229
Writing cacheable documents ...................................................... 230
Expensive methods and properties .............................................. 234
Load balancing ............................................................................. 235
Load balancing across processors ........................................ 235
Load balancing across servers .............................................. 236
Converting an inefficient Web site to an efficient Web site........... 237
Working with documents........................................................ 237
Working with connections ...................................................... 238
Summary ...................................................................................... 240

CH APT ER 11 Setting Up a Mobile Intranet....................................................... 241


SQL Remote replication technology ............................................. 242
Web site replication ............................................................... 242
Requirements for a mobile intranet .............................................. 243
Replicating a Web site.................................................................. 244
Setting up publications and subscriptions.............................. 244
Setting up remote users......................................................... 245
A Replication Tutorial ................................................................... 246
The database......................................................................... 246
Setting up SQL Remote using Sybase Central...................... 248
Setting up the consolidated database.................................... 250
Setting up the remote database............................................. 254
Replicating data ..................................................................... 255

CH APT ER 12 Calling Jaguar Component Methods from PowerDynamo...... 261


How do Jaguar and PowerDynamo work together? ..................... 262
What does Jaguar bring to PowerDynamo applications?............. 264
The benefits of using Jaguar CTS components with PowerDynamo
264
MASP method calls versus ActiveX or Java objects ............. 265
Setting up PowerDynamo as a client............................................ 266
Setting up PowerDynamo to use Jaguar components through
ActiveX............................................................................ 266
Setting up PowerDynamo to use Jaguar components through Java
267
Setting up PowerDynamo to use MASP ................................ 267
Using an ODBC data source to connect to Jaguar................ 268
Using an Open Client connection to connect to Jaguar......... 269
Calling Jaguar components from a PowerDynamo script............. 271
The Dynamo SQL tag (MASP) .............................................. 271
The Dynamo COMPONENT tag............................................ 272
The connection.CreateQuery method (MASP) ...................... 274

x
Chapter

The connection.CreateComponent method (MASP) ............. 274


The java.CreateComponent method...................................... 275
GetHomeInterface method .................................................... 277
GetUserTransaction method.................................................. 278
The PowerDynamo CreateObject method............................. 281
Working with ADO record sets as PowerDynamo query objects.. 284
Working with Tabular Results....................................................... 286

A PP EN DIX A Setting Up the Adaptive Server Anywhere Database Server as a


Service 289
Why use the Adaptive Server Anywhere server? ......................... 290
Why run the Adaptive Server Anywhere database server as a
service?........................................................................... 290
Setting up the Adaptive Server Anywhere database server for
PowerDynamo ................................................................ 292
Start the Adaptive Server Anywhere server as a service ..... 292
Set up the ODBC System DSN ............................................. 292
Set up the Connection Profile ................................................ 294
Connect to PowerDynamo..................................................... 294

A PP EN DIX B Language Support....................................................................... 297


Language support......................................................................... 298
Adaptive Server Anywhere language support ....................... 298
Adaptive Server Enterprise language support ....................... 299
Dynamic file site language support........................................ 300
Usage of multi-byte characters..................................................... 301

xi
xii
About This Book

Subject This manual describes PowerDynamo, a suite of tools for building and
managing database-hosted Web sites and for enabling intranets for a
mobile workforce.
Audience This manual is for users who want to build Web sites with dynamic
content. For reference type information, see the PowerDynamo Reference.
Before you begin This manual assumes that you are moderately familiar with HTML,
ECMAScript (the standardized version of JavaScript) and the operations
of Web browsers and servers.

Introducing PowerDynamo
You can use PowerDynamo to store, manage, and access both static
HTML and dynamic database data. You can then make that information
available over the Internet for not only information delivery but also for
use by Web-hosted client/server applications.
You can combine PowerDynamo with Sybase SQL Remote replication
technology to replicate Web templates and dynamic content onto a laptop
computer for offline use.
SQL Remote allows data and HTML templates to be replicated in both
directions, so you can run client/server applications offline and SQL
Remote can update your changes to the central server.

New Features
This release of PowerDynamo has several major new features:
•Java You can access Java classes from within Dynamo scripts. For
information see “PowerDynamo and Java” on page 145.

xiii
About this book

•XML PowerDynamo now supports XML You can create queries that
generate output in either HTML or XML. For more information see
“Working with XML Documents” on page 165.
•Mail Several objects have been added to PowerDynamo that enable the
sending, receiving, and manipulation of mail from within a PowerDynamo
Web site. For more information see “PowerDynamo Mail Support” on
page 203.
•FTP Several objects have been added to PowerDynamo that provide FTP
functionality to PowerDynamo Web sites. These objects are documented
in “DynaScript Predefined Objects” in the PowerDynamo Reference.
•ECMAScript compatible PowerDynamo is now ECMAScript
compatible. The ECMAScript objects are documented in “DynaScript
Predefined Objects” in the PowerDynamo Reference.
•Invoking Jaguar CTS components PowerDynamo clients can access
Jaguar components through Java, ActiveX, SQL queries or PowerDynamo
tags. For information on PowerDynamo and Jaguar see “Calling Jaguar
Component Methods from PowerDynamo” on page 261.
•UNIX Dynamo is now available on AIX with NSAPI, CGI, and the
Personal Web Server. CGI and the Personal Web Server are now available
on Solaris (NSAPI is supported from previous Dynamo releases).

New objects, properties and methods


The following objects (along with their methods and properties) are new to
PowerDynamo:
• Java object
• Incoming mail object
• Outgoing mail object
• Mail list object
• Attachment object
• Recipient object
• FTP object
• DOMAttribute object
• DOMCDATASection object

xiv
About this book

• DOMCharacterData object
• DOMComment object
• DOMDocument object
• DOMDocumentFragment object
• DOMDocumentType object
• DOMElement object
• DOMEntity object
• DOMEntityReference object
• DOMImplementation object
• DOMNamedNodeMap object
• DOMNode object
• DOMNodeList object
• DOMNotation object
• DOMProcessingInstruction object
• DOMText object
The following properties and methods are new to PowerDynamo
• java.CreateObject( )
• java.GetHomeInterface()
• java.GetUserTransaction()
• query.cursorType
• query.stripTrailingBlanks
• query.ResultsToXMLString( )

PowerDynamo built-in functions


The following built-ins have been added to PowerDynamo:
• xmlEscape( )
• toXMLString( )

xv
About this book

PowerDynamo tags
The following tags have been added to PowerDynamo:
• COMPONENT
• ENDIF
• ELSE
• ELSEIF
• FORMAT_AS (attribute on FORMATTING tag)
• IF
• MAILPIECE
• STRIP_TRAILING_BLANKS (attribute on FORMATTING tag)
• USE_CDATA (attribute on FORMATTING tag)

Other New Features


• You can set event handlers for 404 (not found) messages.
• New ability to test if a connection is valid from within Sybase Central.
• From within Sybase Central you can:
• Test whether a connection is valid.
• Change the directory to which a linked folder refers.
You can use relative paths in Dynamo.
You can execute a script before a user session times out.

Printed and online documentation


The PowerDynamo Users Guide is available in both printed and online
formats. The PowerDynamo Reference is provided in online format only unless
ordered separately. The online documentation is available in two formats:
• As Windows Help.
• In HTML format which you can import into a PowerDynamo Web site.

xvi
About this book

Online documentation more complete and timely


Online documentation is more up to date and may be more complete than
printed documentation: in case of differences between the two, you should
follow the online documentation.

Syntax conventions
The following conventions are used for syntax diagrams in this manual:

Type Symbol Syntax Convention


Keywords SCRIPT SQL keywords and HTML tags are shown in
uppercase.
Placeholders name Items that the user must replace with appropriate
identifiers or expressions are shown in italics.
Options | Options are separated by vertical bars. Any one
of the items is allowed.
Continuation ... Lines beginning with ... are a continuation of
the statements from the previous line.
Lists ",..." Lists are shown with a list element followed by
",...". This means that one or more list
elements are allowed and if more than one is
specified, they must be separated by commas.
Optional [ ] Optional portions of a statement are enclosed by
portions square brackets. For example, FORMATTING
[ MAXROWS = num ] indicates that the
MAXROWS = num is optional. Alternative
optional parts of a statement are sometimes listed
within the brackets separated by vertical bars.
For example, [ ASC | DESC ] indicates
that ASC or DESC are optional. Do not type the
square bracket.
Alternatives { } When one of the options must be chosen, the
alternatives are enclosed in curly braces. For
example [ QUOTES { ON | OFF } ]
indicates that if the QUOTES option is chosen,
one of ON or OFF must be provided. Do not
include the braces.

PowerDynamo Web sites work with either Adaptive Server Enterprise or


Adaptive Server Anywhere databases. In this book, sections that apply to only
one of these databases are marked by [Adaptive Server Anywhere] or
[Adaptive Server Enterprise] at the beginning of the appropriate section.

xvii
About this book

This book uses “PowerDynamo” and “Dynamo” interchangeably when


referring to PowerDynamo.

xviii
CH A PTE R 1 Databases and the Internet

About this chapter This chapter introduces basic Internet and World Wide Web concepts, and
describes the increasingly important role of databases on the Internet. It
also provides an overview of the pieces that make up PowerDynamo.
Contents
Topic Page
Basic Web concepts 2
Databases and the Web 5
A glance at PowerDynamo 9

1
Basic Web concepts

Basic Web concepts


This section describes the essential concepts for working with PowerDynamo.

Storing, locating, and transmitting information on the Web


Figure 1-1: Accessing information on the Web

As Figure 1-1 illustrates, information is stored at Web sites. Access to the


information is managed by a Web server for the site. Users access the
information using Web clients, which are also called browsers.
Information on the Web is stored in documents, using a language called
HTML (HyperText Markup Language). Web clients must interpret HTML to
be able to display the documents to a user. The protocol that governs the
exchange of information between the Web server and Web client is named
HTTP (HyperText Transfer Protocol).

2
CHAPTER 1 Databases and the Internet

How information is To move from one page of a document to another page, or to another document
located: the URL on the same or another Web site, the user clicks a hyperlink (usually just called
a link) in the document shown in their Web client. Documents and locations
within documents are identified by an address, defined as a Uniform Resource
Locator, or URL. The following URL illustrates the general form:
http://www.sybase.com/productsl
or
http://www.sybase.com/inc/corpinfo/mkcreate.html
URLs contain information about which server the document is on, and may
also specify a particular document available to that server, and even a position
within the document. In addition, a URL may carry other information from a
Web client to a Web server, including the values entered into fields in an HTML
form.
For more information about URLs and addresses on the Web, see the material
on the World Wide Web Consortium pages, at the following address:
http://www.w3.org/pub/WWW/Addressing/
When a user clicks a link on a document on their Web client, the URL is sent
to the server of the indicated Web site. The Web server locates the document,
and sends the HTML to the Web client across the network.
External data in HTML HTML documents can include graphics or other types of data by referencing
documents an external file (for example, a GIF or JPEG file for a graphic). Not all these
external formats are supported by all Web clients. When the document contains
such data, the Web client can send a request to the Web server to provide the
relevant graphic. If the Web client does not support the format, it does not
request the information from the server.
Problems with file- In a file-based Web site, each resource is a separate file. For large Web sites,
based Web sites this leads to management problems. For example, maintaining current copies
of hundreds or thousands of different resources in separate files is difficult
enough; maintaining the links between these resources is even more
challenging.
Another problem is that many Web sites contain information that is dynamic–
pricing information, for example, or employee information on an
organization's Intranet. Maintaining such information in HTML files in
addition to the database where it resides is a huge task.

3
Basic Web concepts

For these and other reasons, linking databases to the Web is increasingly the
solution of choice for management of large Web sites and management of
dynamic content. Database storage of Web information can either replace or
complement file storage of Web resources.

4
CHAPTER 1 Databases and the Internet

Databases and the Web


This section describes how databases can connect to the Internet using a
application server, or gateway. It also describes the information commonly
stored in databases.

Gateways between Web servers and databases


Figure 1-2: Accessing data through an application server

For a Web server to retrieve information from a database, an intermediary


application server or gateway is required between the Web server and the
database management system (DBMS). Such an intermediary must have an
interface to the Web server, and an interface to the DBMS. The most common
Web server interface is named CGI. Each DBMS has a native interface; open
interfaces such as ODBC and Open Client are also available.

5
Databases and the Web

Web server interfaces CGI (Common Gateway Interface) is a standard Web server interface. When a
Web server receives a URL corresponding to a CGI resource, it starts a CGI
program (such as a perl script, or the PowerDynamo Application Server)
which connects to the DBMS, queries the database, and returns the information
to the Web server to be handed on to the Web client.
CGI is a standard for interfacing any external application with a Web server,
not just a DBMS. CGI applications may also simply process files. The output
of the CGI program or script is returned to the Web server. This output can be
an HTML document, an image, a reference to another document, or any other
form of information understood by the Web server.
CGI is an industry-standard Web server interface. Some Web server vendors
also provide proprietary interfaces to their servers: NSAPI (Netscape
Application Programming Interface) and Microsoft ISAPI (Internet Server
Application Programming Interface) are two examples supported by
PowerDynamo.

Static and dynamic Web pages


An HTML document stored in a file is an example of a static Web page; its
content does not change unless the file itself is edited.
With application servers, you can create dynamic Web pages, which are
generated each time they are accessed. Dynamic pages have features not found
in static Web pages:
• They can respond to input from the Web client, returning data requested in
some way (such as by filling in a form on a Web page) by the client.
• They can be customized for each user. For example, once a user has filled
in preferences when visiting a site (areas of interest, level of expertise, and
so on), information sent to the user can be tuned to those preferences.
• They can be customized for the display capabilities of the Web client.
• The accuracy of time-sensitive information can be guaranteed.
Templates and data A dynamic Web page can any combination of:
• Static HTML text, displayed every time the page is displayed
• Embedded queries and programmatic instructions
• Data from the database that is filled in when the page is generated

6
CHAPTER 1 Databases and the Internet

Figure 1-3: Static and dynamic Web page components

The static components of the page are stored in an HTML document called a
template. The template consists of the static HTML text (which is passed on to
the Web client without change) together with the query or other instruction
defining the dynamic component of the page, and the layout instructions
governing the display of the data.
The query tags are interpreted by the application server and replaced by a result
set when the document is generated. The application connecting the database
to the Web server replaces the query with its data, formatted according to the
instructions, and sends the resulting page to the Web server for relay to the Web
client.

7
Databases and the Web

Storing and accessing Web information in a database


This section describes some of the types of data that can be stored in a database
for Internet access. This information falls into two broad categories:
• Data you already keep in a database, and don't want to duplicate separately
in HTML files (pricing information and so on).
• Data that you create specifically for the Internet, and want to use a
database to manage, such as HTML documents.
Accessing existing Existing data in a database can be accessed from the Internet using an
data application server. In this case the application server merges an HTML
document (which may exist inside or outside the database) with information
stored in the database, and sends the resulting HTML document to the Web
server.
For example, a dynamically generated Web page might display pictures and
descriptions of a product line, which are stored in HTML files, but fill in the
prices, contact information, and other information from the database.
HTML documents HTML documents themselves may be stored in a database. At its simplest, the
task of the application server is then to execute a query that retrieves the HTML
document from the database and passes it on without change to the Web server.
Images and other Images and other non-HTML information may be stored in a database instead
external data of being stored in a file. When the image is requested, the application server
retrieves it from the database and hands it on to the Web server.
All of the above An application server can retrieve an HTML document from the database, fill
in part of the document from data stored elsewhere in the database, and also
provide images and other external resources associated with the document
from the database.

8
CHAPTER 1 Databases and the Internet

A glance at PowerDynamo
PowerDynamo includes Web-site management features and mobile Intranet
capabilities.
Building Web With PowerDynamo, you can embed instructions into any Web page, and
applications and process these instructions when providing HTML to a Web client for viewing
managing Web sites
or interaction. PowerDynamo supports the following kinds of embedded
instructions:
•Tags You can embed SQL statements and manipulate returned data within
a document.
•SQL statements You can place up-to-date database query results into a
Web page.
•Scripts You can include programmatic control (conditional execution,
looping, and so on) in your Web pages.
•Text replacement and host variable macros You can respond to HTML
forms and other variables supplied by a Web client.
The Web-site management utility, Sybase Central, manages all aspects of
dynamic Web content:
• Authoring
• Site management
• Application servers for deployment on a Web site managed by some other
Web server.
• A Personal Web Server for offline access to data and Web documents, and
for developing Web site content.

The interpreter
At the core of PowerDynamo is an interpreter which processes specially tagged
instructions embedded in the HTML pages or other documents, and serves the
resulting output together with static HTML to an application such as a Web
server.
The PowerDynamo interpreter is built into several components:
• The Web-site management tool, for managing a database-hosted Web site
• Application servers that link your database and your Web server

9
A glance at PowerDynamo

• The Personal Web Server, for working offline with dynamic Web content

Web-site management
PowerDynamo includes a Web site management tool for managing HTML
templates and connections. PowerDynamo focuses on combining HTML
documents with database data, and the Web-site management utility plugs in to
the Sybase Central database management utility, bringing management of both
technologies under the single roof of Sybase Central, using a consistent
interface.
PowerDynamo provides tools for the following management tasks:
• Wizard-based HTML template creation.
• Folder-based arrangement of HTML templates to map onto a file-based
Web site's directory structure.
• Syntax-highlighting editor. HTML tags, embedded SQL, and scripts are
all highlighted.
• Browsing and syntax highlighting of output HTML.
• Scheduled processing of scripts and templates. This process is particularly
useful for pages that would take a long time to generate.
Sybase Central requires either the Windows 95 or the Windows NT operating
system.
The Web-site management utility is a plug-in to the Sybase Central database
management tool, so that you manage your data and your Web site from the
same Sybase Central interface.

HTML templates and scripts


Dynamo can work with static Web documents and two types of dynamic Web
pages: HTML templates and scripts.
Templates can include not only static HTML, but instructions that are
interpreted when a document is requested by a Web client. The client then sees
the results of those instructions.
The PowerDynamo executes SQL statements against a database, interprets
scripts internally, and can use text replacement and host variables to provide
client/server interactions.

10
CHAPTER 1 Databases and the Internet

Scripts are ECMAScript that generate HTML. ECMAScript is a standardized


version of Javascript. JavaScript is a compact, object-based scripting language
for developing client and server Internet applications.
For more flexibility over template content, PowerDynamo provides the
DynaScript language. DynaScript is a JavaScript compatible language. You
can embed DynaScripts in templates, but they can also be stored as standalone
scripts, with no container HTML document.
For information about JavaScript, see the Netscape JavaScript Authoring
Guide at the following URL:
http://home.netscape.com/eng/mozilla/3.0/handbook/
javascript/

Script language imposes no restrictions on Web client


JavaScript was developed by Netscape primarily for interpretation at the Web
client, not at the Web server, and consequently JavaScript has been tied to the
Netscape Navigator browser. In PowerDynamo, appropriately tagged
DynaScript scripts are interpreted at the server, and only the output HTML is
sent to the Web client. The PowerDynamo inclusion of a JavaScript-based
language as its scripting language places no restrictions on the Web clients that
can use the system.

Embedding dynamic content in a template


SQL queries in a With PowerDynamo, you can embed SQL queries in an HTML or XML
template template. This allows you to provide flexible and controlled intranet or Internet
access to your organization’s data.
For example, you might develop a template that contains a query for company
products, product descriptions, pricing and availability. Users can then see up-
to-the-minute information that is generated in response to the request for the
page.
With support for text substitution and host variables, you are not limited to
static SQL statements. Instead, SQL statements can be built in response to
input from a Web client.
For example, you could provide a Web template with a list box containing
categories of products. When the user selects one of these categories and clicks
a button, the Web client sends a request containing the selected category in the
URL. In response, the application server constructs a query limited to the
selected category and sends back a table of company products in that category.

11
A glance at PowerDynamo

Text substitution and To enable real interaction between a Web client and the Web server, an action
host variables at the client (clicking on a button after filling out a form, for example) must
send information to the Web server, and this information must be used by the
application server in formulating its response. PowerDynamo supports this
function using: text substitution macros and host variables. Both are sent to the
Web server as part of the address when a link or button in the client is clicked.
You can include a macro in an HTML template. This macro is expanded by the
interpreter when the template is processed, being replaced by its value.
The value of a macro is defined in the URL when the page is accessed. The
following example shows how text substitution works.
1 A user at a Web client fills out an HTML form to subscribe to a service.
The form includes fields for their first and last name.
2 When the form is sent to the Web server, the user’s entry is sent along with
the request in the URL. The standard form for such an inclusion is:
http://www.organization.com/template-
name?firstname=Jane&lastname=Smith
3 In the HTML template, the symbol $firstname is replaced by Jane and the
symbol $lastname by Smith wherever they appear. For example, a returned
acknowledgment may include the text:
Dear Jane Smith,
Thank you for your registration. Your registration
number is 123-456.
For more information about text substitution, see “Passing variables from one
document to another” on page 52.
For more information about text substitution with DynaScript, see “value
property” in PowerDynamo Reference.
While text substitution macros are ideal for general-purpose substitution, there
are some circumstances where a similar but alternative method has
performance advantages. Host variables can be specified in a SQL statement
and the statement could be executed repeatedly without being reparsed,
providing significant performance improvements.

12
CHAPTER 1 Databases and the Internet

The data store


Queries embedded in a template are executed against a database. This can be
any single data source, and the SQL statement must conform to the SQL
supported by the database. The queries are executed against one and only one
data source, and this may be the same or a different database than the one in
which the templates themselves are stored.

The template repository


The PowerDynamo application server allows templates to be held in a data
source that can process Transact-SQL queries or in the file system. The two
supported databases for template storage are Sybase Adaptive Server
Anywhere and Sybase Adaptive Server Enterprise. PowerDynamo can use an
ODBC connection for each of these database management systems or an Open
Client connection for the Adaptive Server Enterprise database management
system. The database need not be the same one as the one holding the data
referenced in SQL statements embedded in the templates.
Although it is held in a relational database, a database-based template
repository is organized according to a folder-based motif, which mimics a file
system organization. This structure allows easy import and export of Web sites
between the database and a file system, so that you can continue to use tools
geared to managing and working with file-based Web sites and information,
and yet gain the benefits of a database-hosted Web site.

How the pieces fit together


The application server takes an HTML template from the template repository,
processes script instructions embedded in this template, fetches data as
required from the data store, and passes a finished HTML document to the Web
server for relaying to the Web client.

13
A glance at PowerDynamo

14
CH A PTE R 2 Getting Started with
PowerDynamo

About this chapter This chapter contains a set of tutorials that introduce you to the core
features of PowerDynamo.
Contents
Topic Page
Overview 16
Looking at the sample Web site 20
Creating a template 22
Creating a script 25
Viewing template output in a browser 27

15
Overview

Overview
The tutorials in this chapter guide you through:
• Inspecting the sample Web site included in PowerDynamo, using Sybase
Central.
• Creating a dynamic HTML page containing a SQL query and viewing the
results of the query.
• Creating a template containing a script.
• Accessing the templates you have created from a Web client (browser) on
your own machine. This tutorial introduces the PowerDynamo Personal
Web Server.
• Accessing the templates you have created from a Web client elsewhere on
a network.
Topics covered in This chapter does not include how to incorporate a PowerDynamo Web site
other chapters into an existing Web site managed by a Web server – see “Configuring Web
Servers and Web sites” on page 71.
Also, this chapter does not cover development of a mobile intranet, although
many of the concepts and tools you need are covered. For more information on
mobile intranets and SQL Remote replication technology, see “Setting Up a
Mobile Intranet” on page 241.

Before you begin


Before you begin, note the following:
• Most of these tutorials can be carried out on a single computer, as long as
the sample database can be accessed from your machine.
If you are running PowerDynamo in a client/server environment against a
database server on a different machine, you need a network connection to
that machine.
• Before running the tutorials, install the sample database. See “Installing
the sample database” on page 17.
• For the tutorials involving a browser, you need a TCP/IP protocol stack,
and for the final tutorial you need a connection to a network.

16
CHAPTER 2 Getting Started with PowerDynamo

Installing the sample database


Installing the sample database is different whether you are using Adaptive
Server Anywhere or Adaptive Server Enterprise.

Installing the sample database [Adaptive Server Enterprise]


The tutorials are based on a sample Web site, which is hosted in the Powersoft
sample database. You must install the Powersoft sample database before you
can run the tutorials.
The sample database is two SQL scripts with a controlling batch file, named
psdemodb.bat. The psdemodb.bat file is installed into the
PowerDynamo\psdemo directory.
The SQL scripts carry out the following tasks to create the sample database.
Use command-line arguments to the batch file to control the settings.
1 Drops the psdemodb database from the server, if it exists.
2 Creates a 4MB device named tempdb_dev for the tempdb database on the
server.
3 Adds a 4MB log to tempdb from the new tempdb_dev device.
4 Creates a 14MB device named psdemodb_dev.
5 Creates a database named psdemodb on the server, using the
psdemodb_dev device, and fills it with data.

❖ To install the sample database:


1 Ensure that you can connect to Adaptive Server Enterprise and have a
valid user ID and password with permissions to create a database.
2 From an operating system command prompt, run the psdemodb batch file,
using these arguments:
• The tempdb device location and file name.
• The tempdb device number. You should use the first free device
number.
• The psdemodb device location and file name.
• The psdemodb device number. You should use the second free device
number.
• The server name.
• The system administrator user ID.

17
Overview

• The system administrator password.


For new Adaptive Server Enterprise installations, you can use the default
system administrator user ID, which is sa, and omit the password
argument, as the default password is empty. The default name of the server
is the name of the machine on which it is installed. For an Adaptive Server
Enterprise newly installed on a machine named my_machine, a typical
command line is (you should type this all on one line):
psdemodb c:\syb11\data\tempdb.dev 8
c:\syb11\data\psdemodb.dev 9 my_machine sa
Modify the installed PowerDynamo is able to use an ODBC interface or an Open Client connection
ODBC data source to access Adaptive Server Enterprise. The Adaptive Server Enterprise setup
creates an ODBC data source for the sample database, but you must modify it
to reflect the name of the installed server before you can access the data source.

❖ To modify the ODBC data source for the sample database:


1 Start the ODBC Administrator and select Sybase System 11 Sample from
the list of available data sources. Then click Setup.
2 Change the server name for the data source to the name of the server you
have installed. By default the server name is the name of the machine.
3 Click OK on the Driver Setup window to create the data source.
For information on how to connect to the sample database using an Open Client
connection see “Creating a connection profile for your Web site” on page 38.

Installing the sample database [Adaptive Server Anywhere]


The Adaptive Server Anywhere Setup automatically installs a sample database
named sademo.db, and creates an ODBC data source named ASA 6.0 Sample.
No further preparation is required.

Starting Dynamo programs


The Dynamo programs are installed into the Start Menu for Windows NT 4.0
and Windows 95, and are installed into a Program Manager group for Windows
NT 3.51.

18
CHAPTER 2 Getting Started with PowerDynamo

For users of Windows 95 or Windows NT 4.0, the Dynamo programs are added
to the Start Menu, under Programs | Sybase | PowerDynamo 3.5. For users of
Windows NT 3.51, the programs are added to the PowerDynamo 3.5 program
group.
PowerDynamo is accessible through Sybase Central. Sybase Central can be
started either from within the Sybase program group (Start | Programs | Sybase
| Sybase Central) or from within the PowerDynamo program group under the
heading of Manage PowerDynamo (Start | Programs | Sybase | PowerDynamo
3.5 | Manage PowerDynamo).

Creating the sample Web site


In Sybase Central, when you connect PowerDynamo to a database that does not
have a Web site stored for the user ID and database, Dynamo asks you if you
wish to create a Web site for the supplied user ID.

❖ To create the sample Web site:


1 Start Sybase Central, and select Tools | Connection Profiles.
2 Select the Dynamo Demo connection profile from the list.
3 Click Connect. Because no Web site exists on the sample database for the
user ID you have specified, Dynamo prompts you to add a Web site. Click
Yes to create a new Web site.
Check the boxes to load the documentation and samples and enter a name
for the main document folder in the site. The documentation refers to this
folder as “Site”. Click OK to create the site.
Once you have created the sample Web site, you are ready to continue with the
rest of the tutorials.

19
Looking at the sample Web site

Looking at the sample Web site


In this tutorial you connect to the Dynamo sample Web site using Sybase
Central, and survey the structure and content of that Web site. After completing
this tutorial, you should understand the components that make up a
PowerDynamo Web site.

Connecting from Sybase Central to the sample Web site


Locating Sybase If you are using Windows 95 or Windows NT 4.0, select Start | Programs |
Central on your Sybase. You can also start Sybase Central from within the PowerDynamo
desktop
program group by selecting Manage PowerDynamo.
If you are using Windows NT 3.51, Sybase Central is installed into a program
group with the other software in this package. For example, if you are using
PowerDynamo as part of Sybase Adaptive Server Anywhere Professional, you
will find Sybase Central in the Sybase Adaptive Server Anywhere Professional
program group.

❖ To connect to the sample Web site:


1 Start Sybase Central.
2 Select Tools | Connection Profiles.
3 Select Dynamo Demo from the list of connection profiles, then click
Connect to connect to the Web site.
4 If you have previously connected to this Web site, the Web site is listed in
the left pane of the Sybase Central window under the PowerDynamo icon.
If you have not previously connected to this Web site, you are prompted to
create a new site. Click Yes. Enter Site for the name of the main contents
folder, and check the boxes to import the samples and documentation.
Click OK to create the Web site.

20
CHAPTER 2 Getting Started with PowerDynamo

Navigating the sample Web site


Sybase Central has an Explorer-like interface. The left pane is a tree view of
containers. The top-level containers are the various products that Sybase
Central can manage (Adaptive Server Anywhere, Adaptive Server Enterprise,
PowerDynamo, and so on). Within each of these product containers is a set of
database servers or Web sites. The contents of each of these servers or sites is
contained hierarchically within the container.

❖ To display the structure and contents of the sample Web site:


1 Open your Web site container in the left pane. You can do this by clicking
the + icon next to the folder or double-clicking the folder itself.
Two folders are displayed: Connections and Site. The Site folder is also
called the main contents folder.
2 Open the Site folder to explore the contents of the Web site.
The contents of the The Site folder contains the HTML templates and scripts for the Web site.
sample Web site Although this main content folder is named Site in the sample site, it may have
a different name for each site.
If you open the main content folder (in this case Site), you will see folders
named app, doc, images, and system.
• The app folder contains a sample application, which contains many
examples of useful techniques for using PowerDynamo.
• The doc folder contains HTML documentation for PowerDynamo.
• The images folder contains the images for PowerDynamo.
• The system folder contains a set of PowerDynamo scripts that are
automatically built into each new Web site to control the Sybase Central
environment. Do not alter system scripts unless you are an advanced user
wanting to customize your Web site administration environment.
The contents of the Connections folder are used to provide access to the
database data that is queried or accessed from the Web clients. In some cases,
and in this set of tutorials, the database containing the site is the same as that
containing the data.
In summary, a Web site consists of documents, held in a main content folder,
and data that may be in the same or different data sources, which is accessed
using the connections in the Connections folder.

21
Creating a template

Creating a template
In this tutorial you create an HTML template that includes a SQL query. A Web
client accessing this template will receive the formatted results of the SQL
query.

❖ To add a template to your Web site:


1 From Sybase Central, connect to the Dynamo Demo Web site.
2 In the left pane, click the Site folder. You may have to expand the Web site
container to do this.
3 In the right pane, double-click Add Template.
4 Enter a name for the template; for example, Products. Do not use any
spaces. Click Next.
5 Enter a description, for example, A test template. Click Next.
6 If you have more than one connection type you will be asked to pick a
connection.
7 On the Add SQL Query page, click Select. The SQL Query Editor is
displayed. The SQL Query Editor is a tab window that allows you to
manipulate and enter clauses of the SELECT statement. The Test tab
allows you to Test the query before continuing.
• On the Table tab, add product to the list of selected tables.
• On the Columns tab, add name, description, size, color, and unit_price
to the list of selected columns.
• On the Sort tab, add name, size, and color to the Sort By list.
• Select the Test tab, check the SQL statement, and click Test. The
results of the query display in the lower window. Verify that the
results are correct, and click OK.
• Click Next to complete the query.
8 Select HTML as the document type.
9 Select Table with Headings from the list of supplied formats.
10 Click Finish to add the template to the Web site.
You can display the HTML in the Sybase Central syntax-highlighting editor.
The editor color-codes HTML tags, SQL syntax, and script syntax, making
editing and viewing of templates easier.

22
CHAPTER 2 Getting Started with PowerDynamo

Templates are created with default extensions of .stm. We recommend that you
keep this extension for all your templates.
The query and formatting instructions are included in the HTML as specially
formatted HTML comments.

❖ To view the template output:


1 Right-click on the template.
2 Select View Output from the pop-up menu to display the results of the
query in the Sybase Central syntax-highlighting editor.
The output displays the formatted results of the query instead of the query and
the formatting instructions.
You can also send the output to your browser by selecting Browse Output from
the pop-up menu. For more information see “Viewing template output in a Web
browser” on page 49.

❖ To edit the template using the Sybase Central editor:


1 Double-click on the template to display it in the Sybase Central
highlighting editor.
2 Add a paragraph in front of the table. For example, you could enter the
following text after the </H1> tag that marks the end of the heading:
Table of Products
3 Click the database icon on the toolbar to save the script to the database.

Save templates to a database


Make sure that you do not save the template to a file, but save it to the database.

How dynamic content is held in HTML templates


Dynamic content is embedded in an HTML template as HTML comments.
This allows you to use Web page authoring tools to refine the static
components of your Web pages without interfering with the dynamic content.
An HTML comment is marked by the following delimiters:
<!--

-->

23
Creating a template

A SQL statement is identified by a special comment marker, as follows:


<!--SQL
select prodname, price
from product
-->
A SQL statement with formatting instructions is embedded as follows:
<!--SQL
select prodname, price from product -->
<!--FORMATTING-->
( table instructions here )
<!--/FORMATTING-->
A script is embedded as follows:
<!--SCRIPT
document.WriteLn ( "Hello world" ) ;
-->
For more information see the chapter “Dynamo Tags” in the PowerDynamo
Reference.

24
CHAPTER 2 Getting Started with PowerDynamo

Creating a script
In this tutorial you create an HTML template that includes a script. Scripts
provide programmatic control over the content of the HTML page. For
example, they can be used to respond to forms filled out and submitted from a
Web client.

❖ To add a script to your Web site:


1 From Sybase Central, connect to the PowerDynamo sample site.
2 In the left pane, click the Site folder. You may have to expand the Web site
container to do this.
3 In the right pane, double-click Add Script.
4 Enter a name for the script, for example, Test. Do not include any spaces.
Click Next.
5 Enter a description; for example, “A test script”.
Click Finish. A script icon named test.ssc is added to the right pane of
Sybase Central.
6 Double-click test.ssc to edit the script. The Sybase Central editor displays
an empty script template:
<!--SCRIPT test.ssc
/* A test script*/

-->
7 Add lines to the script, so it reads as follows:
<!--SCRIPT test.ssc
/* A test script*/
document.Write ( "<HTML><BODY>" ) ;
document.Write ( "<H1>A first heading</H1>") ;
document.Write ( "</BODY></HTML>" ) ;
-->
These instructions write text into the document produced by the script.
For information about the Dynamo script language, see “The DynaScript
Language” in PowerDynamo Reference.
8 Click the database icon to save the script.

❖ To view the script output:


1 From Sybase Central, right-click on test.ssc.

25
Creating a script

2 Select Execute from the pop-up menu. The output displays in the Sybase
Central syntax-highlighting editor.

26
CHAPTER 2 Getting Started with PowerDynamo

Viewing template output in a browser


You can access a PowerDynamo Web site in several ways:
• During development, you can access the site locally (on the same
machine) or across a client/server connection (on the same machine) using
Sybase Central.
• You can access the site locally using a Web client and the PowerDynamo
Personal Web Server.
• You can access the site across the Internet or other network from any
browser or Web client, using the Personal Web Server as the Web server
for the site.
• You can access the site across the Internet or other network from a Web
client, using a third party Web server and a PowerDynamo Application
server to link the PowerDynamo Web site to the Web server.
In previous tutorials, we have been using Sybase Central to access the site
locally. In this tutorial we first use a Web browser and the Personal Web Server
to access the site locally, and then use a Web browser and the Personal Web
Server to access the site across a local-area network.

Browser and TCP/IP required


You must have a Web browser or other Web client to run this tutorial.
Web browsers require a TCP/IP protocol stack to communicate with a Web
server, even if the server is on the same machine and there is no intervening
network. You must have TCP/IP installed to use PowerDynamo.

Accessing the Web site locally


Web clients generally access data across the Internet or other network. They
exchange information with a Web server, which relays the information in the
addressed document to the Web client. In this tutorial, the Web server is on the
same computer as the browser or other Web client.

❖ To access data in the PowerDynamo sample Web site from a browser or


other Web client:
1 Start the Personal Web Server.
• Open the Utilities folder in the left pane of Sybase Central.

27
Viewing template output in a browser

• Double-click the Personal Web Server icon in the right pane of Sybase
Central.
• The Personal Web Server will be displayed as a small “tray icon” at
the opposite end of the taskbar from the Start menu when it is running.
The software installation configures the Personal Web Server to access the
PowerDynamo sample Web site, so that no further configuration is
needed.
2 Start your browser or other Web client.
3 Type the following URL into the address field of your browser or Web
client:
http://localhost/Site/products.stm

The products template output, including the results of a query, is processed


by the Web server and displayed in your browser.
Notes • The http:// part of the URL defines the protocol to use when exchanging
information.
• The localhost part of the URL directs the Web client to access data from a
Web server on the local machine. In our case, this Web server is the
PowerDynamo Personal Web Server.
If you are not connected to a network, localhost may not be recognized. If
this is the case, you can either:
• Substitute localhost with your machine's IP address, or
• Modify your hosts file to map the host name localhost to the 127.0.0.1
address.
127.0.0.1 localhost

• The Site part of the URL directs the Personal Web Server to access data in
a PowerDynamo Web according to the information specified for the “Site”
mapping. For more information about mappings, see “Configuring Web
sites” on page 100.
• products.stm directs the Personal Web Server to access the products.stm
template from the Web site, process it, and return the output to the browser.

28
CHAPTER 2 Getting Started with PowerDynamo

Accessing the Web site over a network


Although the Personal Web Server is designed primarily for testing and
development work, and for same-machine (local) access to Web data, it can be
used as a normal Web server and accessed from other machines on a local
network or over the Internet.
With its small footprint, and its simplicity, the Personal Web Server is suited
for use for an Intranet site server for workgroups. Workgroups can use Intranet
sites as a place to share information. If the workgroup grows to the point that
the 10 connection limit of the Personal Web Server is no longer sufficient, a
third party web server should be used.
This tutorial shows how to access Web information on a Personal Web Server
across a local-area TCP/IP network.

Required facilities: You require a local-area TCP/IP network and a Web


browser to follow this tutorial.

❖ To access Web information on a Personal Web Server across a network:


1 Ensure your Personal Web Server is running (there should be a small “tray
icon” at the opposite end of the taskbar from the Start menu if the Personal
Web Server is running).
2 Take note of the IP address or the name of the machine on which the
Personal Web Server is running. A typical IP address is of the following
form: 123.45.67.220. If you are using domain name services, you can use
the machine name instead of the TCP/IP address.
3 Start a Web browser on another machine on the network.
4 Enter the following URL in the browser:
http://ip-number/Site/products.stm
or
http://machine name/Site/products.stm
The products template output, including the results of a query, is processed
by the Personal Web Server and relayed across the network to be displayed
in your browser.
Notes • The ip-number part of the URL directs the Web client to access data from
a Web server on the specified machine. If you are using network directory
services, you could use the machine name instead of the IP address.

29
Viewing template output in a browser

• The Site part of the URL directs the Personal Web Server to access data in
a PowerDynamo Web site according to the information specified for the
“Site” mapping.
For more information about mappings, see “Configuring Web sites” on
page 100.
products.stm directs the Personal web Server to access the products.stm
template from the Web site, process it, and return the output across the
network to the browser.

30
CH A PTE R 3 Working with Dynamo Web Sites

About this chapter This chapter describes some basic elements of managing PowerDynamo
Web sites.
For information on Web server configuration issues, see “Configuring
Web Servers and Web sites” on page 71.
Contents
Topic Page
Working with Web sites 32
The Utilities folder 41
Working with folders and documents in your Web site 42
Working with templates 46
Scheduling actions 57
Working with connections 60
Copying a Web-site database [Adaptive Server Anywhere] 69
Using the Performance Monitor 70

31
Working with Web sites

Working with Web sites


You create and work with Web sites using Sybase Central. Because
PowerDynamo plugs into Sybase Central you can manage both your databases
and your Web sites from within Sybase Central.
What is a Dynamo A Dynamo Web site consists of:
Web site?
• A set of documents stored in a database or in files on disk, together with a
connection specification (including user ID) for a database.
• A set of data referenced by SQL statements included in the templates. This
data is stored in an ODBC or Open Client database.
• A set of connections used by the PowerDynamo Application Server to
access the data.

Web site architecture


How documents are Dynamo Web sites include:
stored
•Documents These may be templates, scripts, or HTML documents.
•Database data The data that fills out queries in templates.
•Connections To access the data.
Web site documents are usually stored in an Adaptive Server Enterprise or
Adaptive Server Anywhere relational database in a set of tables. However, the
structure of these tables is hidden from the user by the PowerDynamo
application server. Web sites may also be hosted in the file system.
The data may be contained in an Adaptive Server Enterprise or Adaptive
Server Anywhere database, or in some other ODBC or Open Client data
source.
Hierarchical views of Sybase Central provides a hierarchical view of a Web site, just like a directory
documents structure. A hierarchical architecture has advantages for a Web site:
• The URL, the address of documents on the World Wide Web, uses a
hierarchical model. A hierarchical structure is required for URL access to
the documents.
• You can import whole directory trees of HTML files into a Dynamo Web
site database, and maintain hypertext links from one document to another,
as long as these links are coded as relative addresses, not absolute.

32
CHAPTER 3 Working with Dynamo Web Sites

Storing documents on Not all the documents in a site need be held in a database. Web sites can also
disk contain documents stored in folders on disk.
For information about creating dynamic file-based Web sites see “Creating a
dynamic file-based Web site” on page 36
For more information about storing documents on disk and linking these into a
database-hosted Web site, see “Linking folders to directories on disk” on page
43.

Before you begin


You should be familiar with the basics of using Sybase Central for managing
databases. For assistance with using Sybase Central, see the Sybase Central
online help for Dynamo.

Creating a Web site [Adaptive Server Anywhere]


You create Dynamo Web sites from Sybase Central, the management tool
included in Dynamo, Adaptive Server Anywhere, and Adaptive Server
Enterprise.
Web site created at Sybase Central is a client application. You can use Sybase Central to create a
the server database-hosted Web site on a database residing anywhere on the network.
There is no requirement for Sybase Central to run on the same machine as the
database server.

❖ To create a Web site from Sybase Central [Adaptive Server Anywhere]:


1 If you do not wish to use an existing database to hold the Web site, create
a database to hold the Web site. You can do this using the Create Database
utility, which is in the Sybase Adaptive Server Anywhere container in
Sybase Central.
For more information about creating a database, see the Sybase Central
online help and “Working with Database Objects” in the Adaptive Server
Anywhere User’s Guide.
2 Start Sybase Central.
3 Create an ODBC data source definition for this database. Use the ODBC
Administrator from the Utilities folder in Sybase Central.

33
Working with Web sites

For more information about creating an ODBC data source, see


“Connecting to a Database” in the Adaptive Server Anywhere User’s
Guide.
4 Create a connection profile for your Web site.
1 Select Tools | Connect Profiles.
2 Click New. In the Create New Profile window, enter the name of the
profile (this name is used to identify the Web site in Sybase Central)
and select PowerDynamo as the type. Click OK.
3 Fill in the fields in the Connection Profile window. If you are creating
an ODBC connection profile, you would:
• Select the data source you have created from the drop-down list
of ODBC data sources,
• Enter a valid user ID. Adaptive Server Anywhere databases are
created with a single user, with DBA authority. The user ID is
DBA and the password is SQL.
4 When you have filled in all fields, click OK.
For information on creating File connection profiles, see “Creating a
connection profile for your Web site” on page 38.
5 From the Connection Profile window, highlight the connection profile you
just created and click Connect.
6 If no Web site exists for the user ID you have specified on the database,
Dynamo prompts you to add a Web site.
• Enter a name for the site. This is the name of the main contents folder
on the site.
• Select the appropriate boxes if you want to load the PowerDynamo
documentation and samples into the Web site. Click OK to create the
site.
7 To configure this Web site to be accessible from a Web server, see
“Configuring Web sites” on page 100.
Notes • Only one Web site per user can be created in a database; for example, DBA
can create only one Web site in the sample database. A new user; for
example DBA2, can create another Web site in the same sample database.

34
CHAPTER 3 Working with Dynamo Web Sites

• The connection information (database, user ID, and so on) that you fill in
when you first connect to the Web site serves two functions. It is the owner
of the tables containing the template and script data, and it is provided as
a connection called <default> which can be used for data referenced in
queries in templates.

Creating a Web site [Adaptive Server Enterprise]


You create Dynamo Web sites from Sybase Central, the management tool
included with Adaptive Server Enterprise.
Web site created at Sybase Central is a client application. You can use Sybase Central to create a
the server database-hosted Web site on a database residing anywhere on the network.
There is no requirement for Sybase Central to run on the same machine as the
database server.

❖ To create a Web site from Sybase Central [Adaptive Server Enterprise]:


1 From Sybase Central, connect to the Adaptive Server where you want to
create the Web site, or create a new database.
2 Now you need to connect to the database as a Web site. To do this, you
must connect using a Dynamo connection, not an Adaptive Server
Enterprise connection, within Sybase Central.
3 Create a connection profile for your Web site.
1 Select Tools | Connect Profiles.
2 Click New.
3 In the Create New Profile window, enter the name of the profile and
select PowerDynamo as the type. Click OK.
4 Change the connection type to Open Client.
5 Fill in the fields in the Connection window:
• Enter a descriptive name in the Connection Name field, such as
My First Site. This name is used to identify the Web site in
Sybase Central. You can use spaces in the name if you wish.
• Enter the names of the server and database to connect to. These
names are case sensitive.
• Enter a valid user ID and password for this database. The user ID
must have the permissions necessary to create tables.

35
Working with Web sites

When you have filled in all fields, click OK.


For information on creating ODBC and File connection profiles, see
“Creating a connection profile for your Web site” on page 38.
4 Highlight the connection profile you just created and click Connect.
5 If no Web site exists for the user ID you have specified on the database,
Dynamo prompts you to add a Web site.
• Enter a name for the site. This is the name of the main contents folder
on the site.
• Select the appropriate boxes to load the PowerDynamo
documentation and samples into the Web site. Click OK to create the
site.
6 To configure this Web site to be accessible from a Web server, see
“Configuring Web sites” on page 100.
Notes • Only one Web site per user can be created in a database; for example, DBA
can create only one Web site in the sample database. A new user; for
example, DBA2, can create another Web site in the same sample database.
• The connection information (database, user ID, and so on) that you fill in
when you first connect to the Web site serves two functions. It is the owner
of the tables containing the template and script data, and it is provided as
a connection called <default> which can be used for data referenced in
queries in templates.

Creating a dynamic file-based Web site


You can use Sybase Central to create a file-based Web site that resides on any
drive that is accessible (locally or via a network) from the machine where
Sybase Central is running. File-based sites dynamically connect to a database
and retrieve data.

Caution
All files in the target directory will be deleted when creating a dynamic file-
based Web site. If there are read-only files in this directory the Web site will
not be created.

❖ To create a file-based Web site from Sybase Central:


1 Create a directory for store your Web site.

36
CHAPTER 3 Working with Dynamo Web Sites

2 From Sybase Central, select Tools | Connect.


3 In the connection profile window:
• Select a connection type of Dynamic File.
• Enter the name of the connection that you are making.
• Enter the path to the file-based site.
Click OK.
4 If no Web site exists in the directory, Dynamo prompts you to add a Web
site.
5 Select the appropriate boxes to load the PowerDynamo documentation and
samples into the Web site, and click OK to create the site.
6 To configure this Web site to be accessible from a Web server, see
“Configuring Web sites” on page 100.
Notes Caution
File-based Web sites store database passwords as plain text which makes them
accessible through the file system.

Retrieving data from a database with a dynamic file-based Web site


After you have created a dynamic file-based Web site, you must create a
connection to the database and specify the connection name in the root folder
of the file-based Web site.

❖ To retrieve data from a database:


1 Use Sybase Central to connect to your file-based Web site.
2 Open the Connections folder of the Web site.
3 Create a connection to the database you want to retrieve data.
4 Right-click on the root folder of your file-based Web site and select
Properties.
5 Select the connection that you just created from the pull down menu of the
Connection field.
6 Click OK.
Alternatively, you can create DynaScript connections in your Web documents
to connect to a database and retrieve data. The following script uses the
connection myConn (connects to the sample database) to execute a SQL query.

37
Working with Web sites

<HTML>
<TITLE>testthis.stm</TITLE>
<BODY>
<H1></H1>
<!--SCRIPT
myConn = site.GetConnection("Conn1");
if( myConn == null ) {
myConn = site.CreateConnection("Conn1", "My test
connection", "Adaptive Server Anywhere 5.0 Sample",
"dba", "sql");
}
-->
<!--SQL CONNECTION_OBJECT=myConn
SELECT contact.last_name, contact.first_name,
contact.title
FROM DBA.contact contact

-->
<TABLE BORDER>
<TR>
<TH>last_name</TH>
<TH>first_name</TH>
<TH>title</TH>
</TR>
<!--formatting--><TR>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>
</TR><!--/formatting-->
</TABLE>
</BODY>
</HTML>

Creating a connection profile for your Web site


You should create a connection profile for your Web site from Sybase Central.
When you create a connection profile, the connection information is stored in
the registry in encrypted form. This information is used not only in Sybase
Central, but also by the Dynamo application server as database provider
profiles.
There are three types of connection profiles that you may create:
•ODBC connection profile Used for connecting to Adaptive Server
Anywhere or Adaptive Server Enterprise Web sites.

38
CHAPTER 3 Working with Dynamo Web Sites

•Open Client connection profile Used for connecting to Adaptive Server


Enterprise Web sites.
•Dynamic File connection profile Used for connecting to Web sites that
are hosted on disk.

Consistency with connections


A Web site should always be connected to with the same type of connection as
was used for the original creation of the site. For example, if the sample Web
site was created with an ODBC connection, it should not later be connected to
with an Open Client connection

❖ To create a connection profile:


1 From Sybase Central, select Tools | Connection Profiles. The Connection
Profiles window is displayed.
2 Click New. The Create New Profile window is displayed.
3 Enter a name for the connection profile, and select PowerDynamo from
the list of available types. Click OK. The Connection window displays.
4 Select a connection type.
• For ODBC:
a Fill in the fields in the Connection window, and click OK to
create the profile.
• For Open Client:
a Enter the name of the server to which you wish to connect.
b Enter the name of the database to which you wish to connect.
c Fill in your user ID and password, and click OK to create the
profile.
• For Dynamic File:
a Enter the path to the File-based site, and click OK to create the
profile.

39
Working with Web sites

The Select Method


When you are creating an ODBC data source for an Adaptive Server Enterprise
database the Select Method must be set to 0 - Cursor for Dynamo to work. The
Select method setting is located within the ODBC Administrator | ODBC
Sybase | Driver Setup | Performance Tab.

Regenerating a Web site


When you regenerate a Web site, the existing content of the Web site is deleted,
and a new Web site is created.

❖ To regenerate a Web site:


1 With the right mouse button, click the Web site icon in the left pane of
Sybase Central, and select Regenerate from the menu.
2 Enter a name for the main contents folder in the Web site setup window,
and select the appropriate options to include the Dynamo documentation
and sample application in the site. Click OK to regenerate a clean Web site.

Caution
Regenerating a Web site deletes the entire content of the Web site. This action
cannot be undone.

Deleting a Web site


When you delete a Web site, the existing content of the Web site is deleted. If
the database containing your Web site has other data, it is not affected by the
deletion of the Web site. Also, the database itself is not deleted.
With the right mouse button, click the Web site icon in the left pane of Sybase
Central, and select Delete from the menu.

Caution
Deleting a Web site deletes the entire content of the Web site. This action
cannot be undone.

40
CHAPTER 3 Working with Dynamo Web Sites

The Utilities folder


The Dynamo Utilities folder contains several utilities used for creating,
maintaining, and configuring Web sites. These utilities include:
•ODBC Administrator Used to create and administer ODBC connections.
•Personal Web Server Used for testing and developing applications. For
more information see “The Personal Web Server” on page 72.
•Helper Application for CGI Used in conjunction with CGI or WIN-CGI
Web servers.
•Configuration folder Includes folders that allow you to configure certain
aspects of your Web sites, for example, cookie time-outs, and port
numbers. For more information see “Configuring Web sites” on page 100.

Starting the utilities


❖ To start one of the utilities from Sybase Central:
1 Click on the Utilities folder in the left pane of Sybase Central.
2 Double click on the icon in the right pane of Sybase Central for the utility
you want to start.

41
Working with folders and documents in your Web site

Working with folders and documents in your Web site


When you create a Web site, two folders are automatically placed into the Web
site:
•Connections The connections folder holds user-defined connections. You
can create new connections from this folder by double-clicking the Add
Connection wizard, which is contained in this folder.
•Main contents folder You specify the name of the main contents folder
when you create your Web site. You should place all the content you wish
to create inside this folder. The main contents folder may contain the App,
Doc, Images, and System folders, depending on the options you select
when creating your Web site. The System folder contains scripts used for
site management purposes. Do not alter or execute directly scripts
contained in the system folder unless you are an experienced user of
PowerDynamo.
Once you start adding content to your Web site, you may want to create
additional folders.

Creating folders
To add a folder to a Web site:
1 Use Sybase Central to connect to a Web site.
2 Open the folder within which you want to create a new folder.
3 Double-click Add Folder in the right pane.
4 Enter a name for your folder, and click Next. Do not use spaces, as not all
Web servers and browsers handle spaces correctly.
5 If your Web site has more than one connection, select the connection for
the documents in this folder to use as a default. For more information
about connections, see “Working with connections” on page 60.
6 Enter an optional description of the folder, and click Finish.

Moving or copying folders and documents


To move or copy a folder or document within a Web site:

42
CHAPTER 3 Working with Dynamo Web Sites

1 From Sybase Central, open the Web site folders until you see the folder or
document you want to move or copy.
2 To move the folder or document, drag the icon to the desired location. To
copy it, press the Ctrl key while you drag the icon.

Deleting folders and documents


To delete a folder or document from a Web site:
1 Use Sybase Central to open the Web site folders until the folder or
document you want to delete is displayed.
2 Right-click the folder or document, and select Delete from the menu to
delete the folder.

Caution
Deleting a folder deletes all the contents of that folder and cannot be undone.

Renaming folders and documents


To rename a folder or document:
1 Use Sybase Central to connect to a Web site.
2 Open the Web site folders until you see the folder or document you want
to rename.
3 Right-click the folder or document and select Properties from the menu.
4 Replace the current name with a new name, and click OK to make the
change.

Linking folders to directories on disk


You can store documents that are part of a Web site either in a database or as
files in a directory tree. While holding information in a database has many
advantages, you may wish to hold some of the material in your database-based
Web site as files. PowerDynamo allows you to do this using linked folders. A
linked folder is a folder in a database-based Web site that provides access to
files stored in a directory on a disk.

43
Working with folders and documents in your Web site

Linking vs. importing


Linking a folder to a directory leaves the Web documents stored physically in
the file system; it does not physically import them into the database. Importing
a directory or a set of files physically copies the documents into the database.

❖ To create a linked folder:


1 Use Sybase Central to open the Web site folders in the left pane until you
see the folder where you want to create the linked folder.
2 Double-click Add Linked Folder in the right pane.
3 Follow the instructions in the wizard to create the linked folder.

Linked Folders
You cannot create a linked folder inside a linked folder.
Linked folders are applicable only to database-based Web sites.

Working with linked folders


You should be aware of the following behavior when working with the contents
of a linked folder:
• When you add a folder within a linked folder, a new subdirectory is made
on your disk.
• When you delete a folder within a linked folder, the corresponding
subdirectory is deleted from your disk.
• When you create or delete a document (template or script) inside a linked
folder, a corresponding file is created or deleted on your disk.
• If you delete the linked folder itself from the Web site, the corresponding
directory is not deleted on your disk.
• If you move a document from a linked folder to an unlinked folder in the
Web site, the corresponding file is deleted from your disk.
• If you move a document or folder to a linked folder, a corresponding
subdirectory or file is created on your disk.

44
CHAPTER 3 Working with Dynamo Web Sites

SQL Remote cannot replicate linked folders


SQL Remote replication technology replicates database content only. It cannot
replicate the files stored in a linked folder.

45
Working with templates

Working with templates


Templates in a PowerDynamo Web site are HTML documents that may include
embedded instructions. This section describes how to create, edit, and delete
Dynamo templates.
For information about scripts, which are the other kind of dynamic Web
content managed by PowerDynamo, see “Writing DynaScripts” on page 127.

Creating a template
This section describes how to add a template to your Web site. The example
describes a template displaying a table of information about current products
sold by the company.

❖ To create a template:
1 Use Sybase Central to connect to a Web site.
2 In the left pane, select the folder where you want to create the new
template. You may have to expand the Web site container to do this.
3 In the right pane, double-click Add Template.
4 On the first page of the wizard enter a name for the template, for example,
Products. Do not use spaces. Click Next.
5 Enter an optional description for the template and click Next.
6 If your Web site has more than one connection, select a default connection
for this template. For more information about connections, see “Working
with connections” on page 60.
7 On the Add SQL Query page, click Select and enter the query using the
query tab window. You can enter a query manually if you wish.
8 Select HTML or XML as the type of document to create.
9 Specify the type of formatting you would like. These options are different
depending on the choice you made in the previous step.
If you chose HTML as the document output, you must provide the type of
HTML format you wish to use for the output.
If you chose XML as the document output you are asked to provide tags
for the output or to select existing tags.
10 Click Finish to add the template to the Web site.

46
CHAPTER 3 Working with Dynamo Web Sites

You can view the contents of the template in several ways, as described in
“Viewing and editing templates” on page 48.
Selecting an HTML The Add Template wizard provides you with a list of formats to choose from.
output format for your
template •Tables Tables, with or without headings, are useful for queries returning
several columns of results.
The default table has a border to separate the data fields. After you have
completed the wizard, you can customize the attributes of the table using
a Web authoring tool or Sybase Central.
•Definition List A definition list displays queries with two columns, as a
list. Each list item has a term and a description. For example, you might
use a definition list for a glossary:
<DL>
<DT>Otley
<DD>A market town in Wharfedale
<DT>Wharfedale
<DD>A valley in Yorkshire, U.K.
</DL>
If you use the definition list format for a query with more than two
columns, any extra columns are concatenated into the description.
•Ordered and unordered lists These types of lists are useful primarily for
queries that return a single column. Markings for an ordered and
unordered list are dependent on the browser but in most cases an
unordered list is marked by bullets and an ordered list is marked by
numbers.
•Detail This is useful for queries with any number of columns. Each field
is shown on a separate line.
•Link This is most useful for three-column queries. An unordered list of
links is created such that column 1 is the link’s URL, column 2 is the text
that gets displayed for the link (the part that is usually underlined in the
browser), and column 3 (and onward) become the text that is displayed
after the link.
•Paragraph This is useful primarily for single column queries: each row of
the result set is placed in a separate paragraph.

47
Working with templates

Viewing and editing templates


You can view and edit templates in several ways from within Sybase Central
and from a Web client:
• You can inspect and alter the template source—the HTML together with
the embedded instructions—in the Sybase Central syntax-highlighting
editor.
• You can view the output of a document in the Sybase Central editor.
• You can use a Web client together with the personal Web server to view
the template as users will see it.
• You can export the template to a file and use an HTML editor to alter it,
and then import the file back into the database.

Viewing template source in the Sybase Central editor


❖ To view or alter the source of a template:
1 Use Sybase Central to connect to a Web site.
2 In the left pane, open the appropriate folders until you see the template you
want to work with in the right pane of Sybase Central.
3 In the right pane, right-click on the template, and select Open. The
template source displays in the Sybase Central syntax highlighting editor.
4 Make any changes to the template, then save it.

Viewing template output in the Sybase Central editor


You can check that your query result contains the data you expect by viewing
the output in the Sybase Central editor.

❖ To view the output HTML of a template:


1 Use Sybase Central to connect to a Web site.
2 In the left pane, click the Site folder. You may have to expand the Web site
container to do this.
3 In the right pane, right-click on a Template, and select View Output from
the menu. The Sybase Central editor displays the HTML of the document
as it would be received by a Web client.

48
CHAPTER 3 Working with Dynamo Web Sites

The instructions embedded in the template are not present in the output
HTML document. Instead, the results of those instructions are displayed
along with the HTML tags.

Viewing template output in a Web browser


You can check that your query result contains the data you expect without
leaving Sybase Central, and check the formatting of a template, by viewing the
output in your Web browser.

❖ To view template output in a browser:


1 Use Sybase Central to connect to a Web site.
2 In the left panel, open the appropriate folders until you see the required
template in the right pane.
3 In the right pane, right-click on a template, and select Browse Execution
Output from the menu. The document output is displayed in the browser
as it would be received by a Web client.
The instructions embedded in the template are not present in the output
HTML document. Instead, the results of those instructions and HTML are
displayed.

Limitations of browsing output


The document output is sent to a file, which is then loaded into your Web
browser. Consequently, any links to relative addresses will not work, and any
graphics that are given relative addresses are not displayed. It is recommended
to use relative addresses and tolerate the discrepancies in output appearance
when accessed in this manner. To view output exactly as it would appear to a
user, use the Personal Web Server with a browser.

Using a Web authoring tool with PowerDynamo


Web authoring tools (HTML editors) work with HTML files, while
PowerDynamo templates are stored in a database. However, you can edit
PowerDynamo templates using a Web authoring tool.
This tutorial shows you how to customize the formatting of the template that
you generated in the previous tutorial. You must have a Web authoring tool
other than the Sybase Central editor.

49
Working with templates

❖ To edit a template using a Web authoring tool or text editor:


1 Use Sybase Central to locate the template you want to edit.
2 Right-click the template and select Export from the menu.
3 Enter a file name for the exported template.
4 Open the file in your Web authoring tool or text editor.
5 Make any changes to the template. Save it, and close your Web authoring
tool or text editor.
6 From Sybase Central, right-click the folder where your template resides
and select Import from the menu to bring the file back into the database.
7 From Sybase Central, right-click the template and select View Output
from the popup menu. This shows the HTML output of the template,
including the changes you have made.
When you open the template in a Web authoring tool, the query is not
shown. PowerDynamo stores queries in HTML templates as specially
marked HTML comments. Storing queries in this manner allows editing
by any HTML editor, without interfering with the query.
When you open the template in a Web authoring tool, only the headings
and one empty row of the table is shown. PowerDynamo uses specially
marked HTML comments to indicate formatting information, and these
comments are ignored by Web authoring tools. The single row containing
apparently empty cells actually contains the following HTML comment:
<!--data-->
Storing formatting in this manner allows editing by any HTML editor,
including formatting of the table containing the output.

Embedding instructions in a template


Instructions are embedded in a template as HTML comments rather than as
HTML tags.

Embedding SQL in a template


A SQL statement is contained inside an HTML comment. HTML comments
are of the following form:
<!-- this is a commment -->

50
CHAPTER 3 Working with Dynamo Web Sites

All material inside the angle brackets is ignored by an HTML parser such as
that included inside a Web client. Thus, a Web client can view a template, and
it will ignore the material inside the comment tags. If you edit the template
using an HTML authoring tool it will ignore the embedded instructions. Of
course, the SQL statements are not seen by a Web client, as they are interpreted
and executed by the PowerDynamo Application Server.
SQL statements are embedded in an HTML document as follows:
<!--SQL
sql-statement
-->
The SQL statement itself can continue over several lines. It should start on a
separate line from the SQL comment tag.
Example The following HTML fragment contains a simple query.
<!--SQL
SELECT name, color, size, unit_price
FROM "dba".product
-->
Naming a SQL You can provide an identifying name for an embedded query. This is useful, for
statement example, if you have more than one SQL statement in a template.
To name a SQL statement, provide a name for a SQL statement as the NAME
attribute for the SQL comment tag. The following SQL statement has a name
of ProductQuery:
<!--SQL NAME=ProductQuery
SELECT name, color, size, unit_price
FROM "dba".product
-->
The SQL statement itself must start on a separate line from the NAME
attribute.
Formatting query If the embedded SQL statement is a query, then the Application Server inserts
results the results of the query into the output document. PowerDynamo allows you to
describe the formatting of a query using a formatting comment tag.
The HTML tags for formatting instructions are slightly different from the tags
used for SQL statements. To allow an HTML editor to modify and refine the
actual formatting, the formatting description is not inside a comment. Instead,
comment tags are used for placeholders for the data, which are replaced on
processing by the actual data.

51
Working with templates

Start and end All data placeholders must be between formatting start and end comment tags.
formatting comment The formatting start comment tag is of the form
tags
<!--FORMATTING-->
The formatting end comment tag is of the form
<!--/FORMATTING-->

Formatting using scripts


In addition to using formatting comment tags, you can use embedded scripts to
format output. The flexibility of scripts allows more varied formatting than the
formatting comment tags.
For more information on formatting using scripts, see the chapter “Writing
DynaScripts” on page 127.

As these are HTML comments, there is no restriction on the HTML that can be
included between the tags. The formatting comment tags have no effect on
HTML that occurs between them; they affect just the embedded instructions.
For more information on Dynamo Tags, see the chapter “Dynamo Tags” in
PowerDynamo Reference.

Passing variables from one document to another


You can use text replacement macros, or text substitution macros, to include
values provided by a Web client in document output. For example, a document
in your Web site may ask a user to enter their name in an HTML form. Their
name can then be used in documents returned from the Web server.
Example This example includes the following:
• A sample form asking the user to enter their first and last names, and
submitting them to the Web server.
• A reply document that uses the supplied names to address the user.

❖ To create the documents for the example:


1 In Sybase Central, connect to the sample Web site and move to the main
contents folder.
2 Create a new template named form.stm, without entering any query. Then
edit the document so that it has the following content:
<HTML>

52
CHAPTER 3 Working with Dynamo Web Sites

<HEAD>
<TITLE>
Test of text substitution
</TITLE>
</HEAD>
<BODY>
<FORM ACTION="reply.stm" NAME="log" METHOD="GET">
<p>Please enter your name.
<ul>
<li>First name:
<INPUT TYPE="text" NAME="firstname" SIZE="15">
<li>Last name:
<INPUT TYPE="text" NAME="lastname" SIZE="15">
</ul>
<p><Center>
<INPUT TYPE="Submit" VALUE="Register">
</Center></p>
</FORM>
</BODY>
</HTML>
This HTML document contains a form, but contains no Dynamo-specific
instructions. The <FORM> tag tells the browser to retrieve reply.stm when
the user clicks Register.
3 Create a new template named reply.stm, without entering any query. Then
edit the document so that it has the following content:
<HTML>
<HEAD>
<TITLE>Test of text substitution</TITLE>
</HEAD>
<BODY>
<p>Dear $firstname $lastname,</p>
<p>Thank you for using our text substitution
facility.
<p>
Yours
<p>
TextSub Corporation.
</BODY>
</HTML>
The $firstname and $lastname entries are text substitution macros. They
are replaced by the values entered in the form when reply.stm is processed.

53
Working with templates

❖ To run the example:


1 Start the Personal Web Server from the Utilities folder in Sybase Central.
You will see the Personal Web Server tray icon at the end of your start bar
once it is running.
2 Start your browser, and open the URL for the HTML form. If you created
the form in the main contents folder of the sample Web site, the address is
as follows:
http://localhost/Site/form.stm
3 Enter your first and last names into the fields, and click Register. The entry
is sent to the Web server in the URL in the following form:
http://localhost/Site/reply.stm?firstname=first-
name&lastname=last-name
4 The reply.stm document is returned, with the proper values placed in for
the name. If you entered a name of Simon James, the reply would be:
Dear Simon James,
Thank you for using our text substitution facility.
Yours
TextSub Corporation.
Text replacement Text replacement macros can be accessed inside scripts, but are accessed in a
macros in scripts different manner. The argument is a property of the document object, which is
a predefined object. The actual value of an argument named firstname can be
accessed inside a script as:
document.value.firstname
For information about using text replacement macros in scripts, see “Passing
variables from one document to another” on page 138.

54
CHAPTER 3 Working with Dynamo Web Sites

Importing and exporting documents


PowerDynamo manages Web documents using a hierarchical motif, just like a
file system. You can make folders, add documents to a folder, and move or
copy documents from one folder to another.
You can also export documents to a file, or import a file into the Web site
database. This section describes how to import and export files.
There are several reasons why you may want to move documents between your
Web site database and the file system:
• To import HTML documents generated using some other tool. For
example, the documentation included with the sample Web site is
imported into Dynamo from text files.
• To export documents for editing by Web authoring tools, and to import the
modified documents.

Importing documents into a Web site


You can import one or more files or folders into a Web site. In this section we
describe how to import a set of files.

❖ To import a set of files into a Web site:


1 From Sybase Central, connect to your Web site.
2 Open the Web site so that a folder into which you wish to import the files
is displayed. For example, you may wish to import documentation files
into a folder named doc.
3 Right-click on the folder, and select Import from the popup menu. The
Import Files window is displayed.
4 Use the browse options or enter a file name or a directory name in the File
text box. Click Add to add this to the Import List.
5 Add other file names or directory names as required. Then click OK to
import the files.

55
Importing and exporting documents

Dynamo storage efficiency


The disk space taken up in a Dynamo database file may not be the same as the
space the files take up on disk. Although storage efficiency depends on the
particular files you are importing, storing data in Dynamo generally takes less
space than storing the same information on disk.

Exporting documents from a Web site


You can export a document from a Web site as a file or as a folder.
When you export a template or script, the instructions are not executed; the
exported file has the same content as the document stored in the database.

❖ To export a document from a Web site:


1 Use Sybase Central to connect to your Web site.
2 Open the Web site so that a document you wish to export to disk is
displayed.
3 Right-click on the document, and select Export from the menu. The Export
Files window is displayed.
4 Enter the location to which you want to export the document and click OK.

56
CHAPTER 3 Working with Dynamo Web Sites

Scheduling actions
With PowerDynamo you can schedule a script or template to be executed
periodically.
Scheduling script and template execution provides an alternative way of
quickly providing to users the results of queries that take a long time to run. It
allows the results to be kept up to date, while allowing quick and efficient
access from Web clients.
The output of a scheduled script is stored in the Web site and available to users.

For scheduling to take effect:


For scheduling to take effect, the Load at startup and Enable
scheduling options must both be selected for the mapping representing this
site. These options are visible after clicking the Browse button in the mapping
property window.
If the Personal Web server or the Dynamo application server you are using is
already running, it must be restarted in order for scheduling to take effect.

❖ To schedule a script:
1 Use Sybase Central to locate the script or template you want to schedule.
2 Right-click the script or template and select Schedule from the menu. This
will start the schedule wizard.
3 Select the appropriate time interval from the pull down menu in the
wizard.
4 The second screen of the wizard allows you to enter a time interval, at
which the document is to be generated. If you do not enter the time interval
exactly as specified in the following table default values will be used.
You must use a 24 hour clock to enter time intervals. Time interval values
are not case sensitive.

Time Time Interval


Interval Format
(Window 1) (Window 2) Example Default
Hourly MM 30 00
Daily HH:MM 21:30 00:00
Weekly Day HH:MM Saturday 21:30 Sunday 00:00
Monthly DD HH:MM 02 12:00 01 00:00

57
Scheduling actions

Time Time Interval


Interval Format
(Window 1) (Window 2) Example Default
Yearly Month DD June 15 18:00 January 00 00:00
HH:MM

File replaced with its The file containing the script or template is modified to instead contain the
output output of the document. In this manner, you can change a script or template
from on-demand processing to scheduled processing without changing the
URL.
Original file saved to a The contents of the original script or template are saved in a file with the same
different location name but a changed extension. The extension for script source is sss, while the
extension for template source is sts. The source is saved in the same directory
as the original script.
The contents of the ssc or stm file are altered to indicate that the contents are
pre-generated from a scheduled script or template.
The schedule.ssc document in the system directory is altered to add a call to
site.Schedule(). This call adds the scheduled document to the list of
scheduled documents. The schedule.ssc document is imported by autoexec.ssc.

Scheduling with ISAPI or NSAPI servers


Scheduling begins when the first request for a script has been made to the Web
server. ISAPI and NSAPI Web servers do not load the Dynamo plug-in until it
is needed – such as when the first scheduled script is requested.

Removing a scheduled action


You can unschedule previously scheduled documents. This replaces the pre-
generated document with the original script or template. The script is then
processed on demand, rather than according to a schedule.

❖ To remove a scheduled action:


1 Use Sybase Central to locate the script or template you want to
unschedule.
2 Right-click the script or template and select Unschedule from the menu.
The script contents are restored to the original document name, and the source
document that was produced when the document was scheduled is deleted.
Also, the site.Schedule() line is removed from the schedule.ssc document.

58
CHAPTER 3 Working with Dynamo Web Sites

Scheduled actions and SQL Remote


Adaptive Server Anywhere users employing SQL Remote should ensure that
the Personal Web Server at each remote database is configured so that
scheduled actions are not executed. If scheduled actions take place at both
consolidated and remote databases, replication errors may occur.

59
Working with connections

Working with connections


PowerDynamo uses a connection pool to store connections, once they have
been created, for later use. By storing connections in a connection pool instead
of re-creating them each time a connection is required, the processing time
required to execute a request is reduced. A small number of connections can
service a large number of users.
PowerDynamo has two kinds of connections. User Connections are used to
connect to the database to extract data, and Dynamo connections are used to
connect to a database-hosted Web site to extract Web documents. Each
PowerDynamo connection profile represents a Dynamo connection.
• There are two different types of User connections:
•Permanent types Permanent connections are held in the connection
pool until they are requested or timed out. You can find a list of user
connections in the Connections folder in Sybase Central. User
connection objects may be created within a script with the use of the
connection object.
•Temporary Temporary connections are closed and removed when
they are no longer required. Create temporary connections using the
x = new connection (name, description,
datasource [,userName, password, ODBC,
connectParameters]);
constructor.
Permanent user connection definitions should be used when a connection will
be requested repeatedly. Temporary connections are available for instances
where user-specific credentials are required. Because temporary connections
are not stored in the connection pool, they are not as performance friendly as
permanent connections. The proper use of connections allows you to limit the
size of the connection pool and control the load of the database server.
For an example of how to use temporary connections, see “Using a temporary
connection with the session object” on page 64.

The connection pool


Creating database user connections can be one of the most performance costly
processes required by a Web site. To minimize this performance cost,
PowerDynamo stores user connections in a connection pool, which allows user
connections to be re-used for a specified period of time.

60
CHAPTER 3 Working with Dynamo Web Sites

Each time a browser requests a PowerDynamo script, a user connection is


either created or retrieved from the connection pool to process the request. If a
PowerDynamo script is requested simultaneously by many different browsers,
each request requires its own user connection.
Instead of creating a new user connection each time, which would use up
valuable processing time, connections are retrieved from the connection pool.
User connections are held in the connection pool to wait for the next
connection request. If no free connections are available from the connection
pool at the time of a request, a new connection is created. Once the new
connection is released it too is held in the connection pool – as long as the
maximum number of connections has not been reached – to wait for the next
request. Once the maximum number of connections have been gathered in the
connection pool, no more connections will be added to the connection pool
until the number of connections residing in the connection pool decreases.
User connections remain in the connection pool until they time out (in other
words, have resided in the connection pool without being requested for a set
period of time).
The number of connections in the connection pool decreases when connections
time out. For example, if a connection has a time out value of five minutes,
once that connection has been idle in the connection pool for five minutes it is
closed and removed from the connection pool. Each time a connection is
retrieved and then returned to the connection pool the inactive counter will be
restarted. This means that a connection with a time out value of five minutes
might remain in the connection pool for several hours if it is constantly being
retrieved from and returned to the connection pool.
For information on setting connection defaults see “Changing Dynamo
configuration settings” on page 106.

Populating the connection pool


When you first start PowerDynamo there are no connections in the connection
pool. The connection pool is populated through regular Web activity and
connection creation. Once the minimum number of connections in the
connection pool has been met or exceeded, the number of connections will not
drop below the set default minimum.
The minimum and maximum number of user connections is set per definition.
Each user-defined connection (myConnection1 and myConnection2 in the
following list), <default>, and <inherited> are all user connection definitions.
For example, if you had the following connections in your connection folder:

61
Working with connections

• <default>
• myConnection1
• myConnection2
and you set the minimum number of user connections to five, five of each of
the above connection definitions would be held in the connection pool. In other
words, once the connection pool was fully populated, there would never be less
than fifteen connections.
For information on setting connection defaults see “Changing Dynamo
configuration settings” on page 106.

Connection definitions
Each folder, template, and script object has a connection definition associated
with it, and all SQL statements within that object are executed using that
connection. The connection definition is assigned when the object is created.
You can override the default connection definition by getting another
connection (site.GetConnection) or by using the attributes on a SQL tag. For
example, if your data is stored in a different database than your Web site
content, you may wish to execute SQL statements using another connection.
There are four user connection definitions:
•<default> The connection specified when you create a database-based
Web site.
•<inherited> The first specified connection, other than <inherited>, as you
go up the hierarchy of the Sybase Central tree.
•<no connection> The connection specified when you create a file-based
Web site, or for scripts or templates without SQL statements.
•user-defined A user connection created by the user. Each instance of a
user-defined connection represents another connection definition.

Creating, deleting, modifying and testing User connections


You can use Sybase Central to create, delete, modify, and test user connections.

❖ To create a user defined User connection in Sybase Central:


1 Connect to a Web site.

62
CHAPTER 3 Working with Dynamo Web Sites

2 In the left pane, click the Connections folder. You may have to expand the
Web site container to do this.
3 In the right pane, double-click Add Connection.
4 Follow the instructions in the wizard to create a new connection.
If you have more than one connection, you are prompted for a connection name
whenever you create a new template, script, or folder.

❖ To change the connection definition associated with a document:


1 Use Sybase Central to connect to a Web site.
2 Open the Web site root folder.
3 From the right pane, right click on the document for which you want to
change the connection information. Select Properties.
4 Select the appropriate connection from the drop-down menu.
5 Click OK.

❖ To delete a connection definition:


1 Use Sybase Central to connect to a Web site.
2 In the left pane, click the Connections folder. You may have to expand the
Web site container to do this.
3 In the right pane, right click on the connection that you want to delete.
4 Select Delete then click Yes to permanently remove the connection.

❖ To test a connection definition:


1 Use Sybase Central to connect to a Web site.
2 In the left pane, click the Connections folder. You may have to expand the
Web site container to do this.
3 In the right pane, right click on the connection to test.
4 Select Test. A message indicates whether or not the connection is still
valid.

63
Working with connections

Working with permanent and temporary connections


Create permanent and temporary connections by including the appropriate
instructions directly into your Dynamo script. This section describes how to
associate and use the correct connection definition with each Dynamo script.

❖ To create a permanent user connection definition from within a


document:
• To create an ODBC connection within a document, use:
site.CreateConnection(connName, description, datasource [, userName,
password, ODBC, connectParameters])
The connection is added to the Connection folder in Sybase Central. In most
cases, permanent connection should be created through the Sybase Central
connection wizard as described previously.
• To create an Open Client connection within a document, use:
site.CreateConnection(connName, description, server, userName,
password, Open Client [, database])

❖ To create a temporary user connection from within a document:


• To create a temporary ODBC connection within a document, use:
x = new Connection(connName, description, datasource [, userName,
password, ODBC, connectParameters]);
• To create a temporary Open Client connection within a document, use:
x = new Connection(connName, description, server, userName,
password, Open Client [, database]);

Note Remember, temporary connections are deleted when the session ends.

For more information, see “The connection object” in the PowerDynamo


Reference.

Using a temporary connection with the session object


The most efficient way to work with temporary connections that require user
credentials is to create a temporary connection and associate it with the session
object. By associating a connection with the session object, the temporary
connection is not closed after a script has finished processing but is instead
available for the next script that the user accesses. The connection remains
available for as long as the user's session is active or until it is timed out. You
can also close a session object by setting it to null within the script.

64
CHAPTER 3 Working with Dynamo Web Sites

The following example asks a user to log in to a site. Once the login
information is provided a connection is created using the user’s ID and
password. The connection is associated with a session object which is then
used by Web site scripts. If the session times out, the user is directed back to
the login page.
Contents of logon.ssc:
<HTML>
<H1>Logon to temporary connection sample</H1>
<FORM METHOD=POST ACTION="tempConnection.ssc">
<INPUT TYPE="text" NAME="id" value="id" CHECKED>Enter
your user ID<BR>
<INPUT TYPE="text" NAME="password"
value="password">Enter your password<BR>
<P><INPUT TYPE="submit"></p>
<P><INPUT TYPE="RESET" VALUE="Clear Form"></P>
</FORM>
</HTML>
tempConnection.ssc
<HTML>
<BODY>
<!--SCRIPT tempConnection.ssc
/* Creates connection from login */
var password = document.value.password;
var id = document.value.id;

if( exists( session.persistentConn ) ) {


// session already exists
document.WriteLn( "Connection already exists" );
} else {
tempConn = new Connection ("TempConn", "temporary
connection for session object", "dyn_conn_60", id,
password, "ODBC", "");

if( tempConn==null ) {
//error creating connection
document.writeln( "Temporary connection was not
created");
document.writeln( "Error Code: " +
site.GetErrorCode() );
document.writeln( "Error Message: " +
site.GetErrorInfo() );
document.writeln( "Error State: " +
site.GetState() );

65
Working with connections

document.WriteLn("id = "+ id);


document.WriteLn("password = "+ password);

} else {
session.persistentConn=tempConn;
document.WriteLn( session.persistentConn);
}
}
-->
<A HREF="useConnection.ssc" >Click here to access a new
script that used the existing temporary connection</A>
</BODY>
</HTML>
useConnection.ssc
<HTML>
<BODY>
<H1>Contacts for ACME Corp. </H1>
<!--SCRIPT useConnection.ssc
/* Uses temp connection associated with */
/* session object */
if ( !exists (session.persistentConn) ) {
document.redirect="logon.ssc";
} else {
conn = session.persistentConn;
query = conn.CreateQuery ("select last_name,
first_name, phone from contact" );
colCount = query.GetColumnCount();
while (query.MoveNext() ) {
for( i=1; i <= colCount; i++) {
document.WriteLn("<BR>" + query.GetValue(
i ) );
}
}
}
if( query == null ) {
document.WriteLn("The query did not work; query
object not created");
} else {
if( query.GetErrorCode() != 0 ) {
document.Write("The query did not work; ");
document.WriteLn( query.GetErrorInfo() );
}
}

-->

66
CHAPTER 3 Working with Dynamo Web Sites

</BODY>
</HTML>

Managing the connection pool


This section describes how to manage the connection pool to ensure the
optimum performance of the site.

Setting a connection timeout


The connection timeout value sets the number of minutes that a connection
must be inactive before it is released from the connection pool.
You can use connection timeout values to control the number of connections in
the pool as Web site activity fluctuates. This is more efficient than setting the
minimum number of connections to the highest number of necessary
connections or to creating new connections each time the minimum number of
connections in the connection pool is exceeded.
By having the number of connections in the connection pool roughly match the
number of connections being used by the Web site, performance will be
increased for two reasons. The processing time required to create the
connections is not being repeated for each individual request and there are no
excess connections in the connection pool.
Use the Default General Settings folder in Sybase Central to set connection
timeout values.

Setting maximum and minimum number of connections


You can set the values for the maximum and minimum number of connections
being held in the connection pool for both user connections and Dynamo
connections.
Limiting the number of The minimum number of user connections identifies the number of
User connections connections that are to be held in the connection pool of that definition. These
connections are not affected by the connection timeout setting. If you were to
set the default minimum number of connections to three, three connections for
each definition would always remain in the connection pool ready for use,
assuming that at some point the connections had been created.

67
Working with connections

The maximum number of user connections identifies the maximum number of


connections of that definition that are to be allowed to connect at any one time.
Any connection requests beyond this number results in a null connection object
being returned to the script.
Limiting the number of The minimum number of Dynamo connections identifies the minimum number
Dynamo connections of Dynamo connections in total that are to be held in the connection pool.
These connections are not affected by the connection timeout setting. If you
were to set the default minimum number of connections to three, three
connections would always remain in the connection pool ready for use,
assuming that at some point three connections had been created.
The maximum number of Dynamo connections stored in the connection pool
should be set to the highest supportable number of connections required by
your Web site during its highest time of throughput. The maximum number of
connections value sets a limit on the number of Dynamo connections to the
Web site, eliminating the chance of performance degradation due to too many
connections being created at once.

Using <no connection>


You create a script or template with a Dynamo wizard, must specify the
connection definition to be used for that document. Use <no connection> when
a Web document does not require any connections to a database to complete
execution. By specifying <no connection>, no connection object is created
during the execution of that document. You can specify <no connection> for
individual documents or for entire trees.
Once you have created a script or template, you can change the User
connection associated with that document by using the document’s property
sheet.
For specific information on how to set User connection defaults, see
“Changing Dynamo configuration settings” on page 106.

68
CHAPTER 3 Working with Dynamo Web Sites

Copying a Web-site database [Adaptive Server


Anywhere]
When you copy a Web-site database to a new computer, the ODBC data source
name is copied to the new machine as well. To connect to the Web site on the
new machine, the connection’s ODBC data source name must be known on that
machine. For example, if you create a Web site on machine 1 with an ODBC
data source name of “mysite1” and copy the Web site database to machine 2,
the ODBC data source name on machine 2 is still “mysite1”. To connect to the
Web site on machine 2, you can either:
• On machine 2, open the Connections folder, select the “default”
connection, open the Properties window, and select an existing ODBC
data source name from the drop-down list.
• On machine 2, create a new ODBC data source name on machine 2 of
“mysite1.” The “default” connection will recognize “mysite1” as a known
ODBC data source name and connect to the Web site properly.

69
Using the Performance Monitor

Using the Performance Monitor


The Performance Monitor is a Windows NT tool that provides feedback on the
performance of the following Dynamo-related items:
•Cache Hit Ratio Number of times a document is found in the cache
versus the number of times the cache is searched.
•Cache Used Percentage of the document cache in use.
•Database Queries/Sec Number of queries per second being performed
on the database.
•Documents in Cache Number of documents currently stored in the
cache.
•Dynamo Connections Current number of Dynamo connections.
•Scripts Run Total number of scripts that have been run.
•Scripts/sec Number of scripts being run per second.
•Total Database Queries Total number of database queries performed.
•Total URL Requests Total number of URL requests processed by
Dynamo.
•URL Requests/Sec Number of URL requests being processed per
second.
•User Connections Current number of user connections.

❖ To run the Performance Monitor:


1 Connect to the Web site you want to monitor. You can monitor multiple
Web sites at the same time if they are each connected.
2 From the NT Desktop, Select Start | Programs | Administrative Tools |
Performance Monitor.
3 From the Performance Monitor select Edit | Add to Chart.
4 From the Add to Chart dialog window, select PowerDynamo as the Object.
The Instance field displays the Web sites to which you are connected. You
can display information in the instance field for a maximum of ten
connected Web sites.
5 Select the first counter you want to monitor, and the appropriate Web site
from the Instance field. Click Add.
Repeat this step for each counter you wish to display.
For more information, see the Performance Monitor online documentation.

70
CH A PTE R 4 Configuring Web Servers and
Web sites

About this chapter You can access a PowerDynamo Web site from a browser or other Web
client either by:
• Using the PowerDynamo Personal Web Server, or
• Using a third party Web server and a PowerDynamo Application
Server. The Application Server communicates with the Web server
using one of the ISAPI, NSAPI, CGI or WIN-CGI interfaces.
Contents
Topic Page
The Personal Web Server 72
Configuring a Dynamo Web site 76
Configuring an ISAPI server 79
Configuring an ISAPI 4.0 server 85
Configuring an NSAPI server 86
Configuring a CGI or WIN-CGI server 94
Configuring Web sites 100
How mapping information is stored 105
Changing Dynamo configuration settings 106
Setting Dynamo MIME types 109

71
The Personal Web Server

The Personal Web Server


The Personal Web Server runs as an application on your computer. Once you
start it, it runs in the background, automatically handling your Web browser’s
requests for local Web pages (and supplying database content for any pages
produced with Dynamo).

Accessing a Web site using the Personal Web Server


Your Web browser normally goes out onto the Internet (or your organization’s
intranet) to get Web pages. When you run the Personal Web Server, your
browser can get Web pages from your own computer as well.
These local pages can be either static documents or Dynamo documents, since
the Personal Web Server automatically generates Web pages from Dynamo
templates and scripts.

Testing Web sites When you are creating or changing a Web site that contains Dynamo content,
you may find it easiest to create all or part of the site on your own computer.
The site is stored in your own Dynamo database or in the file system.
Using the Personal Web Server, you can then point your Web browser to this
local site and test your changes, without disrupting your organization’s
production Web site.
For Dynamo sites that are stored in an Adaptive Server Anywhere database,
moving a site to a server platform is a simple matter of copying the appropriate
database and log file to the new location. For file-based Web sites, simply copy
the files.
Using the Web offline To use the Web, normally you must be online—that is, you must have a live
Internet connection for your Web browser. If you are offline, normally, there is
no Web server to supply your browser with Web content. This is not the case
with PowerDynamo.
If you have some Web content already stored on your computer, you can point
your browser to this content by using the Personal Web Server. You can then
navigate these local pages as you would normally navigate the Web if you were
online.

72
CHAPTER 4 Configuring Web Servers and Web sites

Your offline Web content can be a mixture of static and Dynamo documents
stored on your computer. It can be stored as conventional files copied from the
Internet, or stored as part of a Dynamo database replicated automatically from
an Adaptive Server Enterprise or Adaptive Server Anywhere central database
using SQL Remote. The Personal Web Server handles these details and
presents the results to your Web browser.

Preparing to use the Personal Web Server


❖ To use the Personal Web Server:
1 For a database-hosted Web site, create an ODBC Data Source Name (this
step is not necessary if you are using an Open Client connection to connect
to the database).
For information on creating an ODBC Data Source Name see “Creating a
Web site [Adaptive Server Anywhere]” on page 33 or “Creating a Web site
[Adaptive Server Enterprise]” on page 35.
2 For a database-hosted Web site, use Sybase Central to create a connection
profile. See “Creating a connection profile for your Web site” on page 38.
3 Configure the Application Server by defining mappings from a URL to a
Dynamo site.
For information about configuring the Personal Web Server, see
“Configuring Web sites” on page 100.

TCP/IP required
Web browsers require a TCP/IP protocol stack to communicate with a Web
server, even if it is on the same machine with no intervening network. You must
have TCP/IP installed to use the Personal Web Server.

Starting the Personal Web Server


❖ To start the Personal Web Server on your computer:
1 To start the Personal Web Server from Sybase Central, click on the
Utilities folder in the left pane of Sybase Central.
2 Double-click on the Personal Web Server icon in the right pane.

73
The Personal Web Server

The Personal Web Server on the desktop


Under Windows 95 and Windows NT 4.0, the Personal Web Server appears
only as a small “tray icon” at the opposite end of the taskbar from the Start
menu.

Figure 4-1: Personal Web server icon

Viewing a local Dynamo document


From a browser, you must identify, by means of the server part of a URL, that
a document is to be found using a Web server running on your machine. The
server part of a URL identifies a particular computer, and the Web server
running on that computer can then receive and process the request. You can
identify your own machine in a URL in one of the following ways:
• Use the special name localhost for the server part of the URL. For
example, the following URL accesses a document on the local machine:
http://localhost/Site/sample.stm
This is the recommended method.
• Use the IP number of your machine. For example:
http://123.45.54.211/Site/sample.stm
• Use the name of your machine. For example:
http://test_machine/Site/sample.stm
Figure 4-2: URL format

74
CHAPTER 4 Configuring Web Servers and Web sites

Web content may be on other machines


The Personal Web Server connects to a database-hosted Web site via an ODBC
client/server connection. The documents you access using the Personal Web
Server may be located on an Adaptive Server Enterprise or Adaptive Server
Anywhere database on a different machine on the network.

75
Configuring a Dynamo Web site

Configuring a Dynamo Web site


If you have a live Internet connection you do not need to use the Personal Web
Server to access Dynamo Web content on a Web site. In this case, you use one
of the application servers (or gateways) provided as part of PowerDynamo to
serve Dynamo Web site content to the site Web server.
Figure 4-3: Web servers and application servers

76
CHAPTER 4 Configuring Web Servers and Web sites

Supported Web PowerDynamo includes an Application Server for each of these interfaces:
servers
•CGI For integration with CGI-compatible Web servers.
•WIN-CGI For integration with Windows CGI-compatible Web servers.
•ISAPI For integration with Microsoft Internet Information Server or other
ISAPI Web server.
•NSAPI For integration with a Netscape Web server or other NSAPI Web
server.

Configuring Web servers during installation


If you have a Web server installed on your machine, the installation program
allows you to configure the server to work with PowerDynamo. The
installation program will add the appropriate DLLs to your system path, and
install the PowerDynamo Application Server software on the Web server
machine. This eliminates the need for steps 1 and 2 listed below. You must still
complete steps 3 through 5 for PowerDynamo to work properly.
If you install a Web server after installing PowerDynamo, you can use the
setup -webserver command to reexecute the installation program.

Configuring Web Servers manually


The following procedure is an overview of the steps required to configure a
Dynamo Web site. Detailed instructions specific to each of the supported server
interfaces follow.

Note Ensure that PowerDynamo has been installed on the Web server machine
before beginning configuration. For future administration use, it is
recommended that all PowerDynamo components remain installed on the Web
server machine. You must confirm that you are properly licensed to use
PowerDynamo and Adaptive Server Anywhere or Adaptive Server Enterprise
on your Web site before configuring your Web site.

❖ To configure a Dynamo Web site:


1 Edit your computer’s path to include the Application Server DLLs. If the
Web server was detected and configured during the PowerDynamo
installation, this step is not necessary.

77
Configuring a Dynamo Web site

2 Install the PowerDynamo Application Server software on the Web Server


machine if it is not already.
3 For database-based Web sites, create an ODBC System Data Source Name
(DSN). If you are using an Open Client connection, this step is not
necessary.
4 For database-based Web sites, create a Sybase Central connection profile.
5 Configure the Application Server by defining mappings from a URL to a
Dynamo site.

Important
The above steps rely on tools available from PowerDynamo.

78
CHAPTER 4 Configuring Web Servers and Web sites

Configuring an ISAPI server


This section provides a detailed explanation of how to set up an ISAPI server
to run with PowerDynamo.

IIS 4.0
If you have the Internet Information Server NT 4.0 option pack, see
“Configuring an ISAPI 4.0 server” on page 85.

Steps 1 and 2 are part of the PowerDynamo installation procedure. These steps
are not necessary if the Web server was detected and configured during
installation. Steps 3 through 5 must still be completed.
For more information on configuring Web servers during installation see
“Configuring Web servers during installation” on page 77.

Step 1: Edit the System Path in the System Properties window


In Step two, you will copy DLLs to the InetPub\scripts directory of the ISAPI
Web server. For the Microsoft server to find these DLLs, you must edit your
computer's system path to include the directory containing the DLLs.

Windows 95
If you are running Windows 95, edit the path to include the directory
containing the new DLLs.

The DLL directory is added to the system path, not the user path. ISAPI servers
run as Windows NT services on the NT operating system.

Step 2: Install the Application Server


You must install the Application Server software into a directory defined as
executable by the Web server. Microsoft presets the InetPub\scripts directory
as being executable. For this reason, we recommend that you copy the
appropriate DLLs to this directory.

79
Configuring an ISAPI server

Installing the required software


• If you haven't done so already, install PowerDynamo onto the Web server
machine using the standard software installation. This provides you with
tools such as Sybase Central and the Dynamo Configuration folder.
• Copy the required DLLs into the InetPub\scripts directory on the Web
Server machine.
Required DLLs for The PowerDynamo Application Server for ISAPI Web servers includes the
ISAPI servers following files:

• dyisa03.dll
• dyhtml03.dll
• dydom03.dll
• dyscr03.dll
• dydbg03.dll (optional)
• dyxdb03.dll
• dyxdfl03.dll
• dys03ent.dll
• dycom03.dll (optional)
• dycls03.dll
• dyzip03.dll
• dyperf03.dll (optional)
• mthr110.dll
• plbr110.dll
• clbr110.dll
The following required Power++ runtime libraries are automatically installed
into your Windows SYSTEM directory or your Windows NT system32
directory.

80
CHAPTER 4 Configuring Web Servers and Web sites

Using the ISAPI filter


The dyisa03.dll provides translation capabilities so that users can enter a
standard URL call (http://localhost/Site/Contents.stm) instead of the longer
ISAPI call (http://localhost/Scripts/dyisa03.dll/Site/Contents.stm).
To load dyisa03.dll properly, you must create an IIS virtual directory, and set
the ISAPI filter for PowerDynamo.

❖ To create an IIS virtual directory


1 Start the Microsoft Internet Service Manger.
2 Right-click in the left pane of the Management Console, underneath the
Default Web Site and select New →Virtual Directory.
3 Enter “Sybase” as the alias. Click Next.
4 Enter or browse to the path of your Dynamo win32 directory.
5 Select Allow Execute Access as the permission type and clear all the other
boxes.
The virtual directory is now set.

❖ To set the ISAPI filter DLL:


1 From the Management Console, right-click on your machine (directly
beneath the Internet Information Server folder) and select Properties.
Click Edit.
2 Select the ISAPI Filter tab, then click Add.
3 Enter “PowerDynamo” as the Filter Name, then enter the path to
dyisa03.dll.
4 Restart the Microsoft IIS Server for these changes to take effect.

Step 3: Create an ODBC System Data Source Name (DSN)


An ODBC System DSN is the same as an ODBC DSN except that the System
DSN is available to all users on a machine, including services.

Note
If you are connecting to a file-based Web site, or using an Open Client
connection, this step is not necessary. If you are using Windows 95, create a
data source; you do not need a system DSN.

81
Configuring an ISAPI server

❖ To create an ODBC System Data Source Name:


1 Start the ODBC Administrator from the Utilities folder in Sybase Central.
2 Select the System DSN tab. Click Add.
3 From the Create New Data Source window, select the appropriate ODBC
driver; for example, Adaptive Server Anywhere 6.0. Click Finish.
4 Enter the:
• Data Source Name
• User Id
• Password
• Database name
• Database file
Click OK.

Creating an ODBC data source to connect to an Adaptive Server


Enterprise database
When you are creating an ODBC data source for an Adaptive Server Enterprise
database the Select Method must be set to 0 - Cursor for Dynamo to work. The
Select method setting is located within the ODBC Administrator → ODBC
Sybase Driver Setup → Performance Tab

❖ To ensure that the ODBC data source is available:


1 If you are using Adaptive Server Enterprise as the data server, ensure the
appropriate client library software and ODBC driver have been installed.
2 If you are using Adaptive Server Anywhere as the data server, copy the
Web site database file and transaction log file into an appropriate directory
on the Web server machine and ensure that the database engine together
with the Adaptive Server Anywhere ODBC driver and its attendant
libraries are accessible on the machine.
3 If you are using the Adaptive Server Anywhere network server as the data
server, install the Adaptive Server Anywhere client together with the
Adaptive Server Anywhere ODBC driver and its attendant libraries on the
Web server machine.

82
CHAPTER 4 Configuring Web Servers and Web sites

Step 4: Create a connection profile


You should create a connection profile for your Web site to store connection
information in the registry in encrypted form. This information is used by
Sybase Central, the Personal Web Server, and the Dynamo Application
Servers.

Note
If you are connecting to a file-based Web site, or using an Open Client
connection, see “Creating a connection profile for your Web site” on page 38.

❖ To create an ODBC connection profile for your Web site:


1 From Sybase Central, select Tools →Connection Profiles.
2 Click New.
3 Enter a name for the connection profile, and select PowerDynamo from
the list of available types. Click OK.
4 Select an ODBC data source from the drop-down list. If appropriate, enter
a user ID and password, and any additional parameters and descriptions.
Click OK to create the connection profile.

Step 5: Configure the Application Server


Once the site Web server receives an URL from a Web client, it passes it to the
Dynamo Application Server, which locates and processes the document. You
must add a mapping to the Application Server so it can locate the path to the
document.
Dynamo configuration

❖ To add a new mapping using the Dynamo Configuration folder:


1 In the left pane of Sybase Central, open the Utilities folder.
2 In the right pane of Sybase Central, open the Configuration folder.
3 Double-click the Mappings folder.
4 Double-click Add Mapping.
5 Enter a URL prefix, the Dynamo site type, the resource to access on your
machine and the maximum size of the document cache.
6 Restart the server for these changes to take effect.

83
Configuring an ISAPI server

For a more detailed description of how to configure the Dynamo sites using
Sybase Central and the Configuration folder, see “Configuring Web sites” on
page 100.

84
CHAPTER 4 Configuring Web Servers and Web sites

Configuring an ISAPI 4.0 server


If IIS 4.0 is detected during installation, the procedures in this section occur
automatically. To configure the IIS 4.0 manually follow the instructions in this
section.

Installing IIS 4.0


When installing the Internet Server NT 4.0, ensure that the Internet Service
Manager is selected as one of the components under the Personal Web Server.
This is not a default selection and the manager is necessary for starting and
stopping the server.

Configuring the IIS 4.0 Server


If you have installed IIS 4.0 on a machine that was already configured for
PowerDynamo to work with an ISAPI server, you should already have a virtual
directory and filter path set. If you are configuring ISAPI for the first time,
follow the instructions for creating an IIS virtual directory and setting the
ISAPI filter DLL starting on page 81.

Starting and stopping the IIS service


Whenever a change is made to a PowerDynamo mapping or within the Sybase
Central configuration folder, the server must be stopped and restarted in order
for the changes to take effect.

❖ To stop the IIS Admin Service:


1 From your Control Panel, open the Services utility.
2 Select IIS Admin Service and click Stop. This will stop both the IIS Admin
Service and the World Wide Web Publishing Service.

❖ To start the IIS Admin Service:


1 From your Control Panel, open the Services utility.
2 Select World Wide Web Publishing Service and click Start. This will start
both the World Wide Web Publishing Service and the IIS Admin Service.

85
Configuring an NSAPI server

Configuring an NSAPI server


This section provides a detailed explanation for setting up an NSAPI server to
run with PowerDynamo.
Steps 1 and 2 are part of the PowerDynamo installation procedure. These steps
are not necessary if you configured the Web server during installation. You
must still complete steps 3 through 5.
For more information, see “Configuring Web servers during installation” on
page 77.

Step 1: Edit the system path in the System Properties window


In Step two of Configuring an NSAPI Server, you will be copying DLLs to the
Netscape\server\plugins\dynamo directory of the NSAPI Web server (you will
have to create the dynamo directory). For the server to find these DLLs, you
must edit your computer's system path to include the directory containing the
DLLs.

Note The DLL directory must be added to the system path, not the user path.
NSAPI servers are run as Windows NT services from an NT operating system.

Figure 4-4: System Properties window

86
CHAPTER 4 Configuring Web Servers and Web sites

Step 2: Install the Application Server


If you haven’t done so already, install PowerDynamo onto the Web server
machine using the standard software installation. This provides you with tools
such as Sybase Central and the Dynamo Configuration folder that are
necessary in later stages of the configuration.

Installing the required software


The PowerDynamo Application Server for NSAPI Web servers includes the
following files, which are loaded during installation:
• dy2ns03.dll (for Netscape version 2.0)
• dy3ns03.dll (for Netscape version 3.0 or higher with SSL)
• dyhtml03.dll
• dyscr03.dll

87
Configuring an NSAPI server

• dydbg03.dll (optional)
• dydom03.dll
• dyxdb03.dll
• dyxdfl03.dll
• dys03ent.dll
• dycom03.dll (optional)
• dycls03.dll
• dyzip03.dll
• dyperf03.dll (optional)
The following Powersoft Power++ runtime libraries are installed into your
Windows SYSTEM directory or your Windows NT system32 directory:
• mthr110.dll
• plbr110.dll
• clbr110.dll

Configuring an NSAPI server


Netscape Web servers use the NSAPI interface to communicate with the
Dynamo Application Server.
For full details on configuring Netscape servers, see your Web server
documentation.

❖ To configure Netscape Web servers for use with Dynamo:


1 Make the appropriate changes to the Netscape Web server configuration
file obj.conf. This is a plain text file located in the CONFIG directory of
each server configuration.
Instruct the server to load the dy2ns03.dll or the dy3ns03.dll Application
Server. The following is an example line in the obj.conf file. The first line
must be typed on a single line, it is wrapped here for display reasons only.
The last line Init fn=_dynamo_init should be written on a new line.
Init fn=load-modules shlib=path/dy2ns03.dll
funcs="_dynamo_ntrans,_dynamo_fn,_dynamo_pathcheck,
_dynamo_init"

Init fn=_dynamo_init

88
CHAPTER 4 Configuring Web Servers and Web sites

• _dynamo_pathcheck,_dynamo_init should be written without any


spaces.
• In the above example, path is where the filter DLL can be found. For
example,
Shlib=c:/netscape/server/plugins/dynamo
• Ensure that you have specified the correct DLL for your Netscape
server. If you are using Netscape Server 2.0, specify dy2ns03.dll; if
you are using Netscape Server 3.0 or higher, specify dy3ns03.dll.
2 At the top of the NameTrans list, enter:
NameTrans fn=_dynamo_ntrans
3 At the top of the PathCheck list, enter:
PathCheck fn=_dynamo_pathcheck
4 Add the following section to the end of the file:
<Object name=PowerDynamo>
Service fn=_dynamo_fn
</Object>
The following is a sample configuration file. Some long lines are wrapped for
display reasons. Each separate line in the file is separated by a blank line in this
listing.
# Use only forward slashes in pathnames

# backslashes can cause

# problems.

Init fn=flex-init access="c:/Netscape/Server/


https-steverd/logs/access" format.access=
"%Ses->client.ip% - %Req->vars.auth-user% [%SYSDATE%]
\"%Req->reqpb.clf-request%\" %Req->
srvhdrs.clf-status% %Req->srvhdrs.content-length%"

Init fn=load-types mime-types=mime.types

Init fn=load-modules
shlib=c:/Netscape/Server/Plugins/dynamo/dy2ns03.dll
funcs="_dynamo_ntrans,_dynamo_fn,_dynamo_pathcheck,
_dynamo_init"

Init fn=_dynamo_init

89
Configuring an NSAPI server

<Object name=default>

NameTrans fn=_dynamo_ntrans

NameTrans fn=pfx2dir from=/ns-icons


dir="c:/Netscape/Server/ns-icons"

NameTrans fn=pfx2dir from=/mc-icons


dir="c:/Netscape/Server/ns-icons"

NameTrans fn=document-root
root="c:/Netscape/Server/docs"

PathCheck fn=_dynamo_pathcheck

PathCheck fn=nt-uri-clean

PathCheck fn=find-pathinfo

PathCheck fn=find-index index-


names="index.html,home.html"

ObjectType fn=type-by-extension

ObjectType fn=force-type type=text/plain

Service method=(GET|HEAD) type=


magnus-internal/imagemap fn=imagemap

Service method=(GET|HEAD) type=


magnus-internal/directory fn=index-common

Service method=(GET|HEAD) type=*~magnus-internal/*


fn=send-file

AddLog fn=flex-log name="access"

</Object>

<Object name=cgi>

ObjectType fn=force-type type=magnus-internal/cgi

Service fn=send-cgi

90
CHAPTER 4 Configuring Web Servers and Web sites

</Object>

<Object name=PowerDynamo>

Service fn=_dynamo_fn

</Object>
A document named test.stm in the Dynamo Web site folder would then have
the following URL:
http://server-name/Site/test.stm
The URL contains the server name, followed by the URL prefix defined in the
Application Server mapping: in this case /Site. This mode of addressing is
exactly the same as for the Personal Web Server.

Step 3: Create an ODBC System Data Source Name (DSN)


Creating a System DSN is the same as creating a DSN except a System DSN
is available to all users on a machine as well as services.

Note
If you are connecting to a file-based Web site, or using an Open Client
connection, this step is not necessary. If you are using Windows 95, create a
data source; you do not need a system DSN.

❖ To create an ODBC System Data Source Name:


1 Start the ODBC Administrator from the Utilities folder in Sybase Central.
2 Select the System DSN tab. Click Add.
3 From the Create New Data Source window, select the appropriate ODBC
driver; for example, Adaptive Server Anywhere 6.0. Click Finish.
4 Enter the:
• Data Source Name
• User Id
• Password
• Database name
• Database file

91
Configuring an NSAPI server

Click OK.

Creating an ODBC data source to connect to an Adaptive Server


Enterprise database
When you are creating an ODBC data source for an Adaptive Server Enterprise
database the Select Method must be set to 0 - Cursor for Dynamo to work. The
Select method setting is located within the ODBC Administrator → ODBC
Sybase Driver Setup → Performance Tab

❖ To ensure that the ODBC data source is available:


1 If you are using Adaptive Server Enterprise as the data server, ensure the
appropriate client library software and ODBC driver have been installed.
2 If you are using Adaptive Server Anywhere as the data server, copy the
Web site database file and transaction log file into an appropriate directory
on the Web server machine and ensure that the database engine together
with the Adaptive Server Anywhere ODBC driver and its attendant
libraries are accessible on the machine.
3 If you are using the Adaptive Server Anywhere network server as the data
server, install the Adaptive Server Anywhere client together with the
Adaptive Server Anywhere ODBC driver and its attendant libraries on the
Web server machine.

Step 4: Create a connection profile


You should create a connection profile for your Web site to store connection
information in the registry in encrypted form. This information is used by
Sybase Central, the Personal Web Server, and the Dynamo Application
Servers.

Note
If you are connecting to a file-based Web site, or using an Open Client
connection, see “Creating a connection profile for your Web site” on page 38.

❖ To create an ODBC connection profile for your Web site:


1 From Sybase Central, select Tools →Connection Profiles.
2 Click New.

92
CHAPTER 4 Configuring Web Servers and Web sites

3 Enter a name for the connection profile, and select PowerDynamo from
the list of available types. Click OK.
4 Select an ODBC data source from the drop-down list. If appropriate, enter
a user ID and password, and any additional parameters and descriptions.
Click OK to create the connection profile.

Step 5: Configure the Application Server


Once the site Web server receives an URL from a Web client, it passes it to the
Dynamo Application Server, which locates and processes the document. You
must add a mapping to the Application Server so it can locate the document.
Use the Configuration folder found within the Utilities folder of Sybase Central
to add a mapping to the Application Server.
Dynamo configuration

❖ To add a new mapping using the Dynamo Configuration folder:


1 In the left pane of Sybase Central, open the Utilities folder.
2 In the right pane of Sybase Central, open the Configuration folder.
3 Double-click the Mappings folder.
4 Double-click Add Mapping.
5 Enter a URL prefix, the Dynamo site type, the resource to access on your
machine and the maximum size of the document cache.
6 Restart the server for these changes to take effect.
For a more detailed description of how to configure the Dynamo sites using
Sybase Central and the Configuration folder, see “Configuring Web sites” on
page 100.

93
Configuring a CGI or WIN-CGI server

Configuring a CGI or WIN-CGI server


This section provides a detailed explanation for setting up a CGI or WIN-CGI
server to run with PowerDynamo.
Steps 1 and 2 are part of the PowerDynamo installation procedure. These steps
are not necessary if you configured the Web server during installation. You
must still complete steps 3 through 5.
For more information, see “Configuring Web servers during installation” on
page 77.

Step 1: Edit the System Path in the System Properties window


In Step two of Configuring a CGI or WIN-CGI server, you will be copying
DLLs to the directory of the CGI or WIN-CGI Web server. For the server to
find these DLLs, you must edit your computer's system path to include the
directory containing the DLLs. Figure 4-4 on page 86 shows the System
Properties window.

Note The DLL directory must be added to the system path, not the user path.

Step 2: Install the Application Server


Each Web server has a method for defining directories where programs
executable by the Web server are located. You must install the Application
Server software into a directory defined as executable by the Web server.

Installing the required software


• If you haven't done so already, install PowerDynamo onto the Web server
machine using the standard software installation. This provides you with
tools such as the Personal Web Server and Sybase Central that are
necessary in later stages of the configuration.
• Copy the required DLLs into the directory of the Web server machine.
Required files for CGI The PowerDynamo Application Server for CGI Web servers includes the
servers following files:

94
CHAPTER 4 Configuring Web Servers and Web sites

• dycsrv03.exe
• dycgi03.exe
• dyhtml03.dll
• dyscr03.dll
• dydbg03.dll (optional)
• dydom03.dll
• dys03ent.dll
• dyu03ent.dll
• dyxdfl03.dll
• dyxdb03.dll
• dycom03.dll (optional)
• dycls03.dll
• dyzip03.dll
• dyperf03.dll (optional)
The following Powersoft Power++ runtime libraries are installed into your
Windows SYSTEM directory or your Windows NT system32 directory:
• mthr110.dll
• plbr110.dll
• clbr110.dll
Required files for The PowerDynamo Application Server for WIN-CGI Web servers includes the
WIN-CGI servers following files:
• dycsrv03.exe
• dycwin03.exe
• dyhtml03.dll
• dyscr03.dll
• dydbg03.dll (optional)
• dydom03.dll
• dys03ent.dll
• dyu03ent.dll

95
Configuring a CGI or WIN-CGI server

• dyxdfl03.dll
• dyxdb03.dll
• dycom03.dll (optional)
• dycls03.dll
• dyzip03.dll
• dyperf03.dll (optional)
The following Powersoft Power++ runtime libraries are installed into your
Windows SYSTEM directory or your Windows NT system32 directory:
• mthr110.dll
• plbr110.dll
• clbr110.dll

Configuring a CGI or WIN-CGI server


For more information on setting up your CGI or WIN-CGI directory, consult
your Web server documentation. It is important that the directory is set up for
the correct type of server.
CGI Web servers allow you to describe a set of executable directories. Each
directory has an alias, which is an URL prefix corresponding to that directory.
The default alias for most CGI Web servers is /cgi-bin.
CGI Web servers support one of two types of CGI:
• CGI
• WIN-CGI
Determine which type of CGI your Web server uses.

CGI Helper
In order for a Web site to interface with PowerDynamo through CGI you must
run the Dynamo CGI Helper along with the Web site server itself.
You can start the CGI Helper from the Dynamo Utilities folder.

This is a sample URL call for a CGI server:


http://server/cgi-bin/dycgi03.exe/Site/Contents.stm
This is a sample URL call to a WIN-CGI server:

96
CHAPTER 4 Configuring Web Servers and Web sites

http://server/cgi-win/dycwin03.exe/Site/Contents.stm

Step 3: Create an ODBC System Data Source Name (DSN)


Creating a System DSN is the same as creating a DSN except a System DSN
is available to all users on a machine as well as services.

Note
If you are connecting to a file-based Web site, or using an Open Client
connection, this step is not necessary. If you are using Windows 95, create a
data source; you do not need a system DSN.

❖ To create an ODBC System Data Source Name:


1 Start the ODBC Administrator from the Utilities folder in Sybase Central.
2 Select the System DSN tab. Click Add.
3 From the Create New Data Source window, select the appropriate ODBC
driver; for example, Adaptive Server Anywhere 6.0. Click Finish.
4 Enter the:
• Data Source Name
• User Id
• Password
• Database name
• Database file
Click OK.

Creating an ODBC data source to connect to an Adaptive Server


Enterprise database
When you are creating an ODBC data source for an Adaptive Server Enterprise
database the Select Method must be set to 0 - Cursor for Dynamo to work. The
Select method setting is located within the ODBC Administrator → ODBC
Sybase Driver Setup → Performance Tab

97
Configuring a CGI or WIN-CGI server

❖ To ensure that the ODBC data source is available:


1 If you are using Adaptive Server Enterprise as the data server, ensure the
appropriate client library software and ODBC driver have been installed.
2 If you are using Adaptive Server Anywhere as the data server, copy the
Web site database file and transaction log file into an appropriate directory
on the Web server machine and ensure that the database engine together
with the Adaptive Server Anywhere ODBC driver and its attendant
libraries are accessible on the machine.
3 If you are using the Adaptive Server Anywhere network server as the data
server, install the Adaptive Server Anywhere client together with the
Adaptive Server Anywhere ODBC driver and its attendant libraries on the
Web server machine.

Step 4: Create a connection profile


You should create a connection profile for your Web site to store connection
information in the registry in encrypted form. This information is used by
Sybase Central, the Personal Web Server, and the Dynamo Application
Servers.

Note
If you are connecting to a file-based Web site, or using an Open Client
connection, see “Creating a connection profile for your Web site” on page 38.

❖ To create an ODBC connection profile for your Web site:


1 From Sybase Central, select Tools →Connection Profiles.
2 Click New.
3 Enter a name for the connection profile, and select PowerDynamo from
the list of available types. Click OK.
4 Select an ODBC data source from the drop-down list. If appropriate, enter
a user ID and password, and any additional parameters and descriptions.
Click OK to create the connection profile.

98
CHAPTER 4 Configuring Web Servers and Web sites

Step 5: Configure the Application Server


Once the site Web server receives an URL from a Web client, it passes it to the
Dynamo Application Server, which locates and processes the document. You
must add a mapping to the Application Server so it can locate the document.
Use the Configuration folder found within the Utilities folder of Sybase Central
to add a mapping to the Application Server.
Dynamo configuration

❖ To add a new mapping using the Dynamo Configuration folder:


1 In the left pane of Sybase Central, open the Utilities folder.
2 In the right pane of Sybase Central, open the Configuration folder.
3 Double-click the Mappings folder.
4 Double-click Add Mapping.
5 Enter a URL prefix, the Dynamo site type, the resource to access on your
machine and the maximum size of the document cache.
6 Restart the server for these changes to take effect.
For a more detailed description of how to configure the Dynamo sites using
Sybase Central and the Configuration folder, see “Configuring Web sites” on
page 100.

99
Configuring Web sites

Configuring Web sites


Regardless of the server you are using to access your Web site there are some
aspects of Web site behavior that you can configure.

Configuration is machine specific


Any settings you make in the Dynamo Configuration folder apply to all Web
sites accessed from the current machine, whether they are accessed by a
Personal Web Server or by a Dynamo Application Server attached to a third
party Web server. The configuration information is stored in the Windows 95
or Windows NT registry.

Accessing the Dynamo Configuration folder


You can access the Configuration folder from Sybase Central.
1 In the left pane of Sybase Central, open the Utilities folder.
2 In the right pane of Sybase Central, open the Configuration folder.
3 Select the folder you want to work with.
There are three types of information you can configure:
•Mappings Associate URL prefixes with Dynamo sites. See “Setting
Dynamo mappings” on page 100.
•MIME Associate file extensions with applications. See “Defining
mappings for database-hosted sites” on page 102.
•Default Settings Default settings for the Web site. See “Changing
Dynamo configuration settings” on page 106.

Setting Dynamo mappings


This section describes the elements that make up a Dynamo mapping, and how
to set the mappings using the Dynamo Configuration folder.

❖ To add a new mapping using the Dynamo Configuration folder:


1 In the left pane of Sybase Central, open the Utilities folder.
2 In the right pane of Sybase Central, open the Configuration folder.
3 Double-click the Mappings folder.

100
CHAPTER 4 Configuring Web Servers and Web sites

4 Double-click Add Mapping.


5 Enter an URL prefix, a Dynamo site type, the site you want to access and
the maximum size of the document cache. Each of these elements of a
mapping is described below.
6 Restart the server for your changes to take effect.
Figure 4-5: Site Properties window

The elements of a mapping


Dynamo mappings include these elements:
URL prefix In Dynamo, URL prefix means any part of an URL
immediately following the server name. For example, in the following address,
/this is a URL prefix.
http://www.sybase.com/this/that/other.stm
The remainder of the URL ( /that/other.stm ) refers to the position of the
document that is mapped to the URL prefix /this.
If you are using ISAPI Web servers, you can use the above URL format or you
can use the longer version displayed below, which directly calls dyisa03.dll.
http://server/alias/dyisa03.dll/this/that/other.stm

101
Configuring Web sites

For more information, see “Using the ISAPI filter” on page 81.
Dynamo site type The type of document to which the URL prefix refers.
There are three Dynamo site types:
•Database site Documents are held in a database-hosted Web site. You
can process templates and scripts containing DynaScript.
•Dynamic file site Documents are held on disk. Templates and scripts
containing DynaScript can be processed.
•Static file site Documents are held on disk. Sends back static HTML. You
cannot process queries or templates containing DynaScript.
For more information, see “Defining mappings for database-hosted sites” on
page 102 and “Defining a mapping for file-based sites” on page 103.
Site location The location of the site corresponding to the URL prefix.
The site location for a database hosted Web site is the name of a Sybase Central
connection profile. Connection information is stored in the Registry.
The site location for a file-based Web site is a folder name on a drive available
to the Web site machine.
Document cache size The maximum amount of memory to reserve for
your document cache.
Java cache size The maximum amount of memory to reserve for your
Java cache.
Java classpath Class files that are stored in a database must have their
class path specified in Sybase Central for the class file to be found. Database
class paths may be set per mapping from the Configuration folder in Sybase
Central.
The mapping and Dynamo site name must be the same.
Class files that are stored in a file-based Web site can also use this field to set
the Java classpath.

Defining mappings for database-hosted sites


❖ To define a mapping for a database-hosted site:
1 Use Sybase Central to create a PowerDynamo connection profile for the
Web site.
For more information, see “Creating a connection profile for your Web
site” on page 38.

102
CHAPTER 4 Configuring Web Servers and Web sites

2 From the Utilities folder, open the Dynamo Configuration folder.


3 Open the Mappings folder and double-click Add Mapping.
4 In the URL prefix field, enter the name to use for URLs to access the site.
For example, if you want the index.html document to be addressed as:
http://server-name/db_site/index.html
then enter /db_site as the URL prefix.
5 Select Database from the list of Dynamo site types.
6 To define the resource, click Browse, and select the profile from the list of
available Sybase Central profiles.
7 Enter the desired cache size for your documents.
8 Enter the desired cache size for your Java classes.
9 If you have Web sites that access Java class files from within a database
enter the classpath for the mapping. Dynamo cannot find the class files
unless the location is specified here.
10 Restart the server.

Defining a mapping for file-based sites


❖ To define a mapping for a file-based site:
1 Open the Dynamo Configuration folder from the Sybase Central Utilities
folder.
2 From the Mappings folder, double-click Add Mapping.
3 In the URL prefix field, enter the name for URLs to access the site. For
example, if you want the index.html document to be addressed as:
http://server-name/file_site/index.html
then enter /file_site as the URL prefix.
4 Select Dynamo site types. Chose Dynamic if you want Dynamo to produce
dynamic content from templates and scripts. Chose Static to return static
HTML documents.
5 To define the resource, click Browse, and select the folder containing the
documents from the expandable list. Click OK twice to save the mapping.
6 Enter the desired cache size for your documents.
7 Enter the desired cache size for your Java classes.

103
Configuring Web sites

8 If you have Web sites that access Java class files from within a database
enter the classpath for the mapping. Dynamo cannot find the class files
unless the location is specified here.
9 Restart the server.
To edit a mapping, double-click on the mapping and make the necessary
changes. Click OK to save the changes.
To delete a mapping, right-click the mapping and select Delete.

104
CHAPTER 4 Configuring Web Servers and Web sites

How mapping information is stored


The mapping information is stored in the Windows or Windows NT Registry.
• The Dynamo mappings are stored in:
HKEY_LOCAL_MACHINE\SOFTWARE\Sybase\PowerDynamo\
Mappings
• Encrypted Sybase Central connection profile information is stored in:
HKEY_LOCAL_MACHINE\SOFTWARE\Sybase\Sybase
Central\Profiles
This registry folder contains a set of folders. Each folder has the name of
a profile, and contains the name of the associated ODBC data source, as
well as the user ID and password used to access the data source.
• The ODBC data source, which you may have created using the ODBC
Administrator, is held in:
HKEY_CURRENT_USER\SOFTWARE\ODBC\ODBC.INI
• If you are running your Web server as a Windows NT service, it does not
use a login ID, and consequently has no access to the CURRENT_USER
registry. In this case, you must create your ODBC data source as a System
DataSource Name (System DSN). System DSN descriptions are held in
the LOCAL_MACHINE registry.
• The ODBC driver used to access the data source is part of the data source
definition. The available ODBC drivers are listed in:
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI

105
Changing Dynamo configuration settings

Changing Dynamo configuration settings


The Dynamo configuration settings govern some aspects of Dynamo server
behavior.

❖ To change the settings for your Dynamo server:


1 In the left pane of Sybase Central, open the Utilities folder.
2 In the right pane of Sybase Central, open the Configuration folder.
3 Open one of these folders:
•Default CGI Settings
•Maximum number of CGI clients Sets the maximum number of CGI
clients that are allowed to connect at one time.
•Default General Settings
•Application to launch when debugging The application you would
like to use when debugging.
•Cookie timeout When information is exchanged between a browser
and a Web server, such as when a sequence of forms is filled out at a
browser, Dynamo uses a cookie to maintain information about the
session. After the specified timeout period, this information is
discarded. The default setting is five minutes.
•Java VM This default sets the Java VM for the Web site. Dynamo
supports the Microsoft Java VM, the Sun Java VM and the Sun Debug
Java VM. If using Jaguar, this must be set to the SUN VM.
•Connection timeout This default value causes connections in the
connection pool to expire or be disconnected, once the specified
amount of time of inactivity has elapsed. A value of 0 indicates that
connections within the pool should not be expired.
For more information, see “The connection pool” on page 60.
•Maximum number of Dynamo connections per mapping This sets
the maximum number of Dynamo connections to be stored in the
database connection pool.
•Maximum number of user connections per connection type
Specifies the maximum number of user connections per connection
type to be stored in the connection pool.

106
CHAPTER 4 Configuring Web Servers and Web sites

•Minimum number of Dynamo connections per mapping Sets the


minimum number of Dynamo connections to be stored in the
connection pool.
•Minimum number of user connections per connection type Sets
the minimum number of User connections per connect type to be
stored in the connection pool. This number of connections will never
expire.
•SMTP host Specifies the SMTP host to be used for outgoing mail.
The smtpHost property of the outgoing MailPiece object takes
precedence over this setting. A SMTP host must be set from this field
or the smtpHost property in order for the mail to be sent.
•Trace The trace option, when set to yes, creates a dynamo.log file in
the Dynamo installation directory that captures logging and error
information that may be useful for debugging.
•URL arguments case sensitive Indicates whether case sensitivity
is used for your URLs.
•Default ISAPI Settings The default settings for ISAPI Web servers.
•ISAPI filter directory alias Location of the ISAPI filter.
•Maximum number of pending requests Maximum number of URL
requests that can be maintained in the queue for future processing.
•Maximum number of worker threads Maximum number of worker
threads in the pool. Each worker thread can process one task URL
request at a time. Once a task has been completed by a worker thread
it is released. If there are other tasks waiting to be processed by a
worker thread the next is selected for processing.
•Default Jaguar Settings The default settings for working with the Jaguar
Component Transaction Server. Settings that you specify here apply to
Jaguar Managers that have not been specifically set up in the Manager
Settings folder.
•Orb Class The ORB class that represents the Java object.
•Proxy Host Specifies the machine name or the IP address of an SSL
proxy
•Proxy Port Specifies the port number of the SSL proxy.
•Retry Count The number of times that connecting to the server
should be attempted.

107
Changing Dynamo configuration settings

•Retry Delay The number of milliseconds to wait between attempts to


connect to the server.
•Manager Settings The configuration settings for specific Jaguar
Managers. Each setting allows you to set the same properties as are
found in the Default Jaguar settings. If for some reason you cannot
make a connection with the settings from here, the defaults specified
in the Default Jaguar Settings folder are used. For more information,
see the Jaguar documentation.
•Default PWS Settings The default settings for the PowerDynamo
Personal Web Server.

•Default document for static file sites When a URL without an


explicit document name is supplied, the default document for the site
is returned to the Web client. For the sample Web site, the default
document is contents.html.

Must be a known MIME type


The extension of the default document (contents.html) must be
registered to Dynamo as a known MIME type, if not, the content type
will be returned as “octet/stream” (binary) and be unreadable.

•Port number Each Internet service is assigned to a logical port


number. The usual port number for HTTP servers such as the Dynamo
Personal Web Server is 80. You need change this value only if some
other service on your machine is already using port number 80. Port
numbers are ignored on UNIX machines.
To modify any of these entries, double-click on the entry, make the appropriate
changes and click OK to save.

Changes take effect the next time the server is started


You must restart the server for changes made to the Configuration folder to take
effect.

108
CHAPTER 4 Configuring Web Servers and Web sites

Setting Dynamo MIME types


Information of many different types can be exchanged between a Web client
and a Web server. HTML documents, text files, and images are only a few. The
way each set of information is handled is described using MIME types. You
can configure the MIME type definitions for your Dynamo server using the
Dynamo configuration utility: the server then informs clients receiving the data
of the proper type.
Each MIME type definition is an association between a file extension and a
mime type.

❖ To set the MIME types for your Dynamo server:


1 Open the Dynamo Configuration folder.
2 Open the MIME folder.
3 Click Add MIME Type or double-click on the MIME type you want to
edit.
4 Make changes.
5 Click OK to save the changes.
To remove an existing MIME type, right-click on it and select Delete.

Changes take effect the next time the server is started


You must restart the server for changes made to the Configuration folder to take
effect.

109
Setting Dynamo MIME types

110
CH A PTE R 5 Dynamo Tags Tutorial

About this chapter This chapter introduces Dynamo tags, which are HTML-like tags used for
simple manipulation of PowerDynamo Web site documents.
The tutorials in this chapter introduce you to the most commonly used
Dynamo tags. Several other tags are also explored that allow you to
manipulate data within your Web site possible without using a scripting
language such as DynaScript or JavaScript.
Contents
Topic Page
Overview of Dynamo Tags 112
Tags tutorial 113

111
Overview of Dynamo Tags

Overview of Dynamo Tags


Dynamo tags are extensions to the regular HTML tags that are used for creating
Web documents. The main difference between Dynamo tags and HTML tags
is the location from which the tags are processed. Dynamo tags are processed
at the Web server while HTML tags are processed at the browser. Dynamo tags
also provide extended Web site capabilities that are not available through the
regular set of HTML tags. Normally, a scripting language such as DynaScript
or JavaScript is required to gain the functionality that is provided with the
Dynamo tags.
Dynamo tags appear as HTML comments, which allow you to use your
favorite HTML editor to enter them. Once all Dynamo tags have been
processed by the server, the resulting page is returned to the browser.
PowerDynamo tags have the following characteristics:
• Each Dynamo tag begins with an HTML comment tag (<!--).
• Each tag is closed with the end HTML comment tag (-->).
• Dynamo tags are not case sensitive.
• Some Dynamo tags have attributes that enable specific document and data
manipulation.

112
CHAPTER 5 Dynamo Tags Tutorial

Tags tutorial
These tutorials teach you how to use the most commonly used Dynamo tags.
• SQL
• FORMATTING
• The error checking tags
• INCLUDE
• SQL_INSERT

Using the SQL tag


Use the SQL Tag to embed SQL queries within HTML. You can then display
the output in a variety of formats by using additional Dynamo tags.
This example shows how to embed a SQL query in HTML. This query requests
the ID, first name, last name, and phone number of the customers in the
customer table. The SQL block of information between the start SQL tag (<!-
-SQL) and the end SQL tag (-->) is processed by the Dynamo application
server. The document is then passed on to the browser to be processed; the
results display in HTML format.
<HTML>
<TITLE>SQL_tag.stm</TITLE>
<BODY>
<H1>Customer Information</H1>
<!--SQL
SELECT customer.id, customer.lname, customer.fname,
customer.phone
FROM DBA.customer customer

-->
There are two ways to create a document with an embedded SQL query:
• Use the Add Template wizard in Sybase Central. This automatically
generates the SQL template for you.
• Use the Sybase Central code editor to enter the SQL query.

❖ Using the Add Template wizard:


1 Use Sybase Central to connect to the sample Web site.

113
Tags tutorial

2 Open the root folder of the Web site.


3 In the right pane of Sybase Central, double-click Add Template.
4 Enter a name for the document you are creating, and click Next.
5 You may enter a description of the document. The description you enter is
displayed as an HTML H1 element. Click Next.
6 If you have more than one connection, select the connection to use for this
document. Select <inherited> unless you want to connect to a database
other than the one where your Web site is stored. Click Next.
7 Click Select. The SQL Query Editor opens.
8 From the Tables tab, double-click on the customer table. The customer
table appears under the selected table panel.
9 Select the Columns tab. Double-click on the following columns in the
order given.
• Id
• Fname
• Lname
• phone
10 Click OK once you have completed the SQL query. This closes the editor
and returns you to the wizard. Click Next.
11 Select HTML as the type of document you wish to create. Click Next.
12 Select “Table with headings” as the format to display your SQL query.
Click Finish.
You can also create a document with an embedded SQL query by using the Add
a Script wizard to create a script and then using the Sybase Central code editor
to add the SQL tags and query by hand.

❖ Using the Sybase Central code editor


1 Use Sybase Central to connect to the sample Web site.
2 Double-click the document to edit.
3 The document opens in the code editor ready for editing.
The document you just created contains a simple embedded SQL query.
Next, we’ll add a FORMATTING tag to display the results of the query.

114
CHAPTER 5 Dynamo Tags Tutorial

Using the FORMATTING tag


Use the FORMATTING tag to display rows in the form of a table or a list.
When you perform a query, you usually do not know how many rows will be
returned.
To display the output as a simple table with no borders, headings or titles, enter:
<!--SQL
SELECT customer.id, customer.lname, customer.fname,
customer.phone
FROM DBA.customer customer
-->
<!--formatting--><TR>

<!--/formatting-->
The template you created with the Add Template wizard automatically inserted
FORMATTING tags. Your template should look something like this:
<HTML>
<TITLE>SQL_tag.stm</TITLE>
<BODY>
<H1>Customer Information</H1>
<!--SQL
SELECT customer.id, customer.lname, customer.fname,
customer.phone
FROM DBA.customer customer

-->
<TABLE BORDER>
<TR>
<TH>id</TH>
<TH>lname</TH>
<TH>fname</TH>
<TH>phone</TH>
</TR>
<!--formatting--><TR>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>
</TR><!--/formatting-->
</TABLE>
</BODY>
</HTML>

115
Tags tutorial

The <!--formatting--> tag indicates that the tags following it provide


information on the formatting of the query. The <!--DATA--> tags represent
data in a column. This example has four <!--DATA--> tags; one for each
column being returned.
To assign column headings of the database table to the output, enter:
<TR>
<TH>id</TH>
<TH>lname</TH>
<TH>fname</TH>
<TH>phone</TH>
</TR>
You can use the Sybase Central code editor to edit formatting tags.

❖ To alter a table heading with the Sybase Central code editor:


1 From Sybase Central, double-click on the template you created. The
template opens in the code editor.
2 Change the line:
<TH>id</TH>
to
<TH>Customer ID</TH>
3 Change the line:
<TH>lname</TH>
to
<TH>Last Name</TH>
4 Change the line:
<TH>fname</TH>
to
<TH>First Name</TH>
5 Select File→ Save to Database or click the Save to Database icon to save
the changes you have made to the file.
You have now altered the table headings of your query. To view the template
with these changes, right-click on the template within Sybase Central, and
select Browse Output.

116
CHAPTER 5 Dynamo Tags Tutorial

The LABEL tag Yet another way to alter the formatting of your output is by using the LABEL
tag. LABEL allows you to return the column name along with the column data.
For example, you could set up a query to return output in this format:
id: 101
lname: Devlin
fname: Michael
phone: 2015558966

id: 102
lname: Reiser
fname: Beth
phone: 2125558725

id: 103
lname: Niedringhaus
fname: Erin
phone: 2155556513

❖ To use the LABEL tag to format the output of a SQL query:


1 Use the code editor to open the template you created previously.
2 Delete the text between the <!--formatting--> and <!--/formatting--> tags
so that your template contains only the following lines:
<HTML>
<TITLE>SQL_tag1.stm</TITLE>
<BODY>
<H1>Customer Information</H1>
<!--SQL
SELECT customer.id, customer.lname, customer.fname,
customer.phone
FROM DBA.customer customer

-->

<!--formatting-->

<!--/formatting-->

</BODY>
</HTML>
3 To assign a label to each unit of data that is returned by the query, enter this
line four times between the formatting tags:
<!--LABEL-->: <!--data--><BR>

117
Tags tutorial

Using HTML tags with Dynamo tags


You can use normal HTML tags with the Dynamo tag to format the output.
In this example we are using the break (<BR>) tag to format the output in
a single column.

4 Save the changes you just made. Your template should now look like this:
<HTML>
<TITLE>SQL_tag.stm</TITLE>
<BODY>
<H1>Customer Information</H1>
<!--SQL
SELECT customer.id, customer.lname, customer.fname,
customer.phone
FROM DBA.customer customer

-->

<!--formatting-->
<!--LABEL-->: <!--data--><BR>
<!--LABEL-->: <!--data--><BR>
<!--LABEL-->: <!--data--><BR>
<!--LABEL-->: <!--data--><BR>
<BR>
<!--/formatting-->

</BODY>
</HTML>
5 To view these changes, right-click on the template within Sybase Central,
and select Browse Output.

Using the error checking tags


Queries and manipulations against a database may sometimes generate errors.
When errors occur, it is more useful to display a message to the user rather than
an empty table of results. Dynamo includes several error-checking tags.
The next example first queries the product table from the Sample database,
then adds error checking to ensure that no errors occur while the output is
generated.

118
CHAPTER 5 Dynamo Tags Tutorial

❖ To use error checking tags in your template:


1 Create a Dynamo template called error_check.stm that contains the
following code:
<HTML>
<TITLE>error_check.stm</TITLE>
<BODY>
<H1>Error Checking Example</H1>
<!--SQL
select name, quantity, unit_price, (quantity *
unit_price) as total from product
-->

<TABLE BORDER>
<TR>
<TH>Product Name</TH>
<TH>Quantity</TH>
<TH>Unit_price</TH>
<TH>Total</TH>
</TR>
<!--formatting--><TR>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>
</TR><!--/formatting-->
</TABLE>
</BODY>
</HTML>
The output from this query list all inventory items, and the quantity, price,
and total value of each item.
2 Use the SQL_ON_NO_ERROR tag to ensure that the output is error-free.
Add the SQL_ON_NO_ERROR tags at the beginning and end of the
portion of the file you want error-checked. Your template should look like
this:
<HTML>
<TITLE>error_check.stm</TITLE>
<BODY>
<H1>Error Checking example</H1>
<!--SQL
select name, quantity, unit_price, (quantity *
unit_price) as total from product
-->
<!--SQL_ON_NO_ERROR-->

119
Tags tutorial

<TABLE BORDER>
<TR>
<TH>Product Name</TH>
<TH>Quantity</TH>
<TH>Unit_price</TH>
<TH>Total</TH>
</TR>
<!--formatting--><TR>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>
</TR><!--/formatting-->
</TABLE>
<!--/SQL_ON_NO_ERROR-->
</BODY>
</HTML>
3 You can use the SQL_ON_ERROR tag to add a comment that displays
only if an error is encountered.
The default behavior of the SQL tag in the event of an error is to abort
processing. For this reason, you must add the NO_SQL_ERROR to the
SQL tag. This will allow the template to continue executing even if an
error is encountered. For example:
<HTML>
<TITLE>error_check.stm</TITLE>
<BODY>
<H1>Error Checking example</H1>
<!--SQL NO_SQL_ERROR
select name, quantity, unit_price, (quantity *
unit_price) as total from product
-->
<!--SQL_ON_NO_ERROR-->
<TABLE BORDER>
<TR>
<TH>Product Name</TH>
<TH>Quantity</TH>
<TH>Unit_price</TH>
<TH>Total</TH>
</TR>
<!--formatting--><TR>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>

120
CHAPTER 5 Dynamo Tags Tutorial

</TR><!--/formatting-->
</TABLE>
<!--/SQL_ON_NO_ERROR-->
<!--SQL_ON_ERROR-->
<P>An error has occurred. Contact your system
administrator.</P>
<!--/SQL_ON_ERROR-->
</BODY>
</HTML>
4 View the output of your template. You should see the output of your query
in table format as expected.
5 Change the SQL query so that it has an error in it. Add a spelling mistake
to the table that is being queried, for example:
select name, quantity, unit_price, (quantity *
unit_price) as total from prodduct
Save your changes.
6 View the output of your template. Once the error in the query is
encountered, the formatting instructions surrounded by the
SQL_ON_NO_ERROR tags stop and the SQL_ON_ERROR tags take
effect. The text indicating that an error has been encountered is displayed.
See the SQL_ERROR_CODE, SQL_ERROR_INFO, and SQL_STATE tags in
“Dynamo Tags” in PowerDynamo Reference for information on how to display
errors returned by the database.

Using the INCLUDE tag


Use the INCLUDE tag to incorporate generated output from a document into
the current document. This can be useful when an identical SQL query is used
by several different documents. Instead of maintaining and updating the query
in each document, you can create one template containing the common query.
Let’s say that you have an internal Web site that requires a the same list of
customer contacts on several different Web pages. The easiest way to handle
this is to create one template that queries the customer table for a list of contacts
and then to include that template within all the Web pages that required that
data.

121
Tags tutorial

❖ To include the output of a document within another document:


1 Create a template that performs the required query. For example, the
following template customer.stm queries the customer table for a list of all
customer contacts and displays the results in table format:
<!--SQL
SELECT customer.company_name, customer.lname,
customer.fname, customer.phone
FROM DBA.customer customer

-->
<TABLE BORDER>
<TR>
<TH>company_name</TH>
<TH>lname</TH>
<TH>fname</TH>
<TH>phone</TH>
</TR>
<!--formatting--><TR>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>
</TR><!--/formatting-->
</TABLE>

2 Create a second template that lists expectations for Sales reps. For
example:
<HTML>
<H1>Customer List</H1>
<H2>Expectations</H2>
<P>Each sales rep is expected to contact the
customers on their contact list a
minimum of once every two weeks. For a list of the
customers that you are
responsible for please talk to you supervisor.</P>
</HTML>
3 This example would benefit from displaying a list of customer contacts as
well as the expectations. To do this, you need only add one line to the
example, which includes the generated output from the customer list. After
the “Customer List” heading, add this line:
<!--INCLUDE name="customer.stm"-->
Your example should look like this:

122
CHAPTER 5 Dynamo Tags Tutorial

<HTML>
<BODY>
<H1>Customer List</H1>
<!--INCLUDE name="customer.stm"-->
<H2>Expectations</H2>
<P>Each sales rep is expected to contact the
customers on their contact list a
minimum of once every two weeks. For a list of the
customers that you are
responsible for please talk to you supervisor.</P>
</BODY>
</HTML>
4 Save the template and view the output.

Using the SQL_INSERT tag


Use SQL_INSERT to create a Web page that updates data in a database.
For example, let’s say you want to create an internal Web page for the sales
group that allows the sales staff to add new customers to the contact table.

❖ To create a Web page that updates the database:


1 Create a template called NewCustomer.stm that looks like this:
<HTML>
<TITLE>newCustomer.stm</TITLE>
<BODY>
<H1>New Customer</H1>
<P>Enter the following information</P>
<FORM METHOD=POST ACTION="insertCust.ssc">
<OL>
<LI><INPUT TYPE="text" NAME="id" >ID of the
customer<BR>
<LI><INPUT TYPE="text" NAME="last_name" >Last name
of the customer<BR>
<LI><INPUT TYPE="text" NAME="first_name" >First name
of the customer<BR>
<LI><INPUT TYPE="text" NAME="title" >Customer
title<BR>
<LI><INPUT TYPE="text" NAME="street" >Street<BR>
<LI><INPUT TYPE="text" NAME="city" >City<BR>
<LI><INPUT TYPE="text" NAME="state" >State<BR>
<LI><INPUT TYPE="text" NAME="zip" >Zip Code<BR>
<LI><INPUT TYPE="text" NAME="phone" >Phone

123
Tags tutorial

number<BR>
<LI><INPUT TYPE="text" NAME="fax" >Fax number<BR>
</OL>
<P><INPUT TYPE="submit"></p>
<P><INPUT TYPE="RESET" VALUE="Clear Form"></P>
</FORM>
</BODY>
</HTML>
In a browser, this template would look like Figure 5-1:
Figure 5-1: NewCustomer.stm template

2 The NAME tags must match the appropriate column in the table that the
information is being inserted into. For example, the field that requests the
customer’s first name has a NAME tag of first_name. This matches the
first_name column in the contact table.

124
CHAPTER 5 Dynamo Tags Tutorial

3 Save the template.


4 Create a template called insertCust.ssc. To take the data that is entered in
the NewCustomer.ssc template and add it to the database. It should look
like this:
<HTML>
<TITLE>insertCust.ssc</TITLE>
<BODY>
<H1>New Customer</H1>
<!--SQL_INSERT TABLE="contact" -->
<P>Click here <a HREF=NewCustomer.ssc>here </a> if
you would like to add another customer</P>
<P>Click here <a HREF=Customer.stm>here </a> if you
would like a listing of all customers</P>
</BODY>
</HTML>
5 Save the template.
6 Display the NewCustomer.ssc page in your browser and add a new
customer as requested (make sure you enter a unique customer ID).
7 You have now added data to the contact table of the database.

The SCRIPT tag


Use the SCRIPT tag to embed Dynamo script language within documents. The
format:
<!--SCRIPT
DynaScript
-->
lets Web editing tools know that they should ignore all text between the start
tag (<!--SCRIPT) and end tags (-->) while also letting the Dynamo application
server know that there is DynaScript present that requires processing.
For more information on the SCRIPT tag and DynaScript, see “The DynaScript
Language” in PowerDynamo Reference.

125
Tags tutorial

126
CH A PTE R 6 Writing DynaScripts

About this chapter This chapter introduces DynaScript, which is the PowerDynamo server-
side language that provides programmable control over the content
returned to a Web client.
Contents
Topic Page
Overview of scripts 128
Script tutorials 130

127
Overview of scripts

Overview of scripts
You can embed scripts in HTML templates to control the information that the
template provides to the user. The PowerDynamo script language, DynaScript,
uses a syntax much like JavaScript. DynaScripts are interpreted by the
application server, and the results of that interpretation are passed on to the
Web server.
Script language DynaScript has the following characteristics:
summary
• Scripts are usually embedded in an HTML template. You can also
maintain a script as a separate file in the site, and include it in other scripts
or templates, allowing for code reuse throughout the site.
• Because DynaScript is processed at the application server, before the
content is passed back to the client, no client support for scripting is
required.
• Script statements and variables are case-sensitive.
• You do not need to declare variables.
• Scripts can use the following datatypes:
• numeric
• logical (Boolean) true or false
• string
• null
• function
• object (methods and properties)
• Variables do not have a fixed datatype. Datatype assignment occurs as
needed when expressions are evaluated.
• Control statements such as if, while, do-while and for have a syntax
similar to C and Java.
• You can create objects and define their properties and methods.
• DynaScript includes several built-in object types for working with
databases, SQL, and HTML documents.
Using a server-side Scripting languages for the Internet are interpreted at either the Web client or
language the Web server.

128
CHAPTER 6 Writing DynaScripts

DynaScript is a server-side language that follows the ECMAScript standard


(the standardized version of JavaScript). DynaScript has a syntax much like
JavaScript. There are many uses for a server-side scripting language:
• Maintaining information through a series of client accesses.
• Detailed control over formatting of SQL queries.
• Error-checking for SQL statements. For example, you can use scripts to
check the success or failure of a delete statement, and to send an
appropriate message to the Web client.
• Client-independent form validation. It is quicker to validate entries in an
HTML form at the Web client, but validation at the server makes an
HTML form client-independent.
• Server-side scripts can reduce the amount of data being sent to the client.
There are some tasks that can be better performed (or only performed) at the
client side. For example, you cannot direct HTML to different frames in a
window from the server side.
Why a JavaScript- There are several languages commonly used for Web-related tasks, including
based language? Java, JavaScript, and Perl. An ECMAScript compatible language provides
several advantages in PowerDynamo:
• While the strict typing and mandatory variable declaration of Java are
desirable for large-scale application development, they can cause
unnecessary overhead when developing small scripts attached to a single
Web page.
• The object-based structure of ECMAScript allows more readable and
maintainable code than languages with many special features, such as Perl.
Implementing scripts You can implement DynaScript in several ways:
• You can embed Scripts in HTML templates. This is the most
straightforward way of using scripts, and how most of the examples in this
chapter are presented.
• You can write a script that generates an entire document (complete with
HTML tags and queries). The Web client can request the script itself
(rather than a separate HTML document), and the application server
interprets the script to generate both the HTML and the query output to
return to the client.
• You can group common functions or class definitions into a separate
script. You can then import this script into any other script or template that
requires those functions or classes.

129
Script tutorials

Script tutorials
This section presents some simple scripts that introduce you to DynaScript.

Embedding a Script in HTML


Writing HTML with The following example shows how to embed a script into an HTML template.
scripts This script simply writes Hello world to the HTML document that is
generated for the Web client.

❖ To create this script:


1 In Sybase Central, connect to a Web site.
2 In the left pane, click the Site folder (inside the site database).
3 In the right panel, double-click Add Template.
4 On the first page of the wizard, enter the template name as
first_template
Click Next.
5 Enter a description if you wish. For example:
A test template containing a simple script
Click Next.
6 Do not enter anything on the Add SQL Query page; click Next to move to
the next page.
7 Select <default> from the list of supplied formats.
8 Click Finish.
This adds first_template.stm to the Web site.
9 Double-click the template to open it in the code editor It should look like
this:
<HTML>
<TITLE>first_template</TITLE>
<BODY>
<H1>A test template containing a simple script</H1>
</BODY>
</HTML>

130
CHAPTER 6 Writing DynaScripts

10 After the <BODY> tag, enter:


<!--SCRIPT
document.Write( "Hello world" );
-->
11 Click File→ Save Script. This saves your updated template in the Dynamo
site.

❖ To display the source code of this script:


• In the right pane, right-click first_template and click Open in the pop-up
menu. As a shortcut, you can double-click the script icon instead.

❖ To execute the script against the application server:


• In the right pane, right-click first_template and click View Output in the
pop-up menu.
You see:
<HTML>
<TITLE>first_template</TITLE>
<BODY>
Hello world
</BODY>
</HTML>
When this script is executed from the Web site, the Web server returns this to
the Web client, which in turn interprets the HTML for the user:
Hello world
Scripts are embedded The script is embedded as a comment in the body of a minimal HTML
in HTML templates document. An HTML comment is marked by a tag like this:
<!-- anything in here is a comment -->
DynaScript is comments use the SCRIPT tag, so that the application server can
recognize it:
<!--SCRIPT insert script comment here
-->

JavaScript vs. Dynamo


Be careful not to confuse JavaScript SCRIPT tags with DynaScript SCRIPT
tags; the syntax is very similar.
JavaScript uses this syntax:

131
Script tutorials

<SCRIPT LANGUAGE="JavaScript">
DynaScript uses this syntax:
<!--SCRIPT Comments can be included here -->

The parts of the script The body of the script consists of a single instruction:
document.Write( "Hello world" );
Here, document is a predefined object that refers to the HTML document
being executed.
The statement optionally ends with a semicolon.
Objects have methods associated with them. A method is a function that
carries out actions on an object. Write is a method of the document object.
An object method can take arguments and carries out actions, like a function or
subroutine in other programming languages. In this case, the argument to the
method is the character string "Hello world". The Write method inserts this
string into the HTML document that is sent to the client when the template is
requested.

Using variables and expressions


The following example script illustrates how scripts use variables and how
expressions are evaluated and assigned to variables:
<!--SCRIPT
quote = "Colorless green ideas" ;
quote = quote + " sleep furiously" ;
document.Write(quote) ;
-->
To try this script out, you can use the Sybase Central editor to replace the script
in the template you created in the previous section.
The output from this script is:
Colorless green ideas sleep furiously
Declaration and You do not have to declare variables (although it is good practice to declare
assignment of variable them anyway). Note how the first line of this script creates a variable called
values
quote and assigns it the value of the string "Colorless green ideas".

132
CHAPTER 6 Writing DynaScripts

The + operator concatenates the two strings, and the resulting expression is
assigned to the variable quote. The last line sends the value of the variable as
a string to the HTML output.
Variable types and Unlike variables in many compiled programming languages, Dynascript
operators variables do not have fixed datatypes. The datatype of a variable is set
whenever the variable is assigned a value. You can change the datatype of a
variable by assigning it an expression of a different type.
While this is convenient for small scripts, it does require that you take care
when working with variables.
The same applies to operators. For example, the meaning of the + operator
depends on the expressions it is operating on. In the previous example + was
used to concatenate two strings, but if it is operating on integer expressions
rather than string expressions, it adds rather than concatenates the expressions.
Consider the following script:
<!--SCRIPT
sum = 123 ;
sum = sum + 456 ;
document.Write(sum) ;
-->
The output from this script is the following HTML string:
579
The value of sum is set to the integer 123 in the first line. In the second line the
+ operator acts on the two integers, and so adds them to produce the value 579.
In the final line, this integer is converted to a string for output.

Using control statements


You can use the following control statements to allow looping or conditional
execution of statements:
• if-else

• for

• while

• do-while

These statements use standard C syntax.

133
Script tutorials

A script using the The following example illustrates the use of the while statement:
while statement
<!--SCRIPT
var i = 0;
while ( i < 3 ) {
svar = "This is paragraph " ;
svar += (i + 1) + "<P>" ;
document.WriteLn(svar) ;
i++ ;
}
-->
This script prints the following HTML:
This is paragraph 1<P>
This is paragraph 2<P>
This is paragraph 3<P>
Notes Notice the way that the + operator acts in this script:
• In the expression (i + 1) it adds two integers.
• The other two + operators recognize a string, and combine the other
variable with the string by concatenation.

Using functions
You can define and use functions in scripts, which allows you to encapsulate a
set of instructions once in a document, and use it several times throughout the
document.
The following example shows how to provide consistent custom formatting
across headings in an HTML document:
<HTML>
<TITLE>Function testing</TITLE>

<BODY>
<!--SCRIPT

function h1( headingString) {


heading = "<H1><FONT SIZE=5><FONT COLOR=’000080’>" +
headingString + "</FONT></H1>" ;
document.Write( heading ) ;
}

h1( "This heading formatted by a script" ) ;

134
CHAPTER 6 Writing DynaScripts

-->
</BODY>
</HTML>
Notes Note the following in this example:
• The h1 function is defined before it is invoked.
• The h1 function does not return a value to the calling script, so it is called
using a simple statement. You can also return a value from a function using
the return statement, in which case you typically call the function as part
of an assignment statement.
• Simple variables such as strings and numbers are passed to functions by
value, while objects (including arrays) are passed by reference.

Using simple objects


DynaScript is object-oriented. An object can have properties (data) associated
with it, as well as methods (functions that act on the properties). You can use
the predefined objects included with Dynamo, or create your own custom
objects.
For example, you could create a class of object called product. You can add
properties to store all the information about a product (such as the product ID,
name, color, size, description, price, and quantity in stock). You can also add
methods that carry out typical actions on the product, such as ordering a certain
quantity.
Using an object There are two steps to using an object:
1 Declare the structure of the object using a function or class statement.
This defines the name of the class, and its properties and methods. Inside
the class definition, the properties and methods identify themselves as
class members by using the prefix this.
2 Create an instance of the class using the new operator.
For example, the following class statement defines the product class:
class product(id, name, size, color,
quantity, price) {
this.id = id ;
this.name = name ;
this.size = size ;
this.color = color ;

135
Script tutorials

this.quantity = quantity ;
this.price = price ;
}

To create currentProduct, which is an actual object (or instance) of the


product class, use new with the appropriate property values:
var currentProduct = new product(600, "Sweatshirt",
"Large", "Green", 39, 24.00 ) ;

Using objects In practice, you could have an application that takes an ID


from an HTML form filled out at a Web client, and use that ID together with a
SQL query to fill out the properties of the currentProduct object.
Combining scripts with SQL queries and responding to user input are discussed
in later sections.

Defining methods for So far, the product class has properties, but no methods to act on those
an object properties. To add a method to an object, you must:
1 Define a function that carries out the actions you want.
You can define the function inside the class definition, or as a global
definition (outside the class definition).
2 Assign the function to the class.
For example, you could define an order method for the product class, which
carries out the proper actions when a product is ordered:
function order ( orderQuantity ) {
// order returns true if the order is successful,
// false if stock is too low
if ( this.quantity >= orderQuantity ) {
this.quantity -= orderQuantity ;
return ( true ) ;
} else {
return ( false ) ;
}
}
Since we’ve declared order as a global function in our script, its definition
must precede the definition of the product class. We can then make the order
function a method of product by adding a line to the class definition:
class product( id, name, size, color,
quantity, price ) {
this.id = id ;

136
CHAPTER 6 Writing DynaScripts

this.name = name ;
this.size = size ;
this.color = color ;
this.quantity = quantity ;
this.price = price ;
this.order = order ;
}
Since we haven’t added any new properties, creating a new instance of the
product class is the same as it was before:
var currentProduct = new product(600, "Sweatshirt",
"Large", "Green", 39, 24.00 ) ;
You could then use the order method in a template as follows:
<!--SCRIPT
var orderQuantity = 20 ;
status = currentProduct.order( orderQuantity ) ;
if (status) {
document.WriteLn( "Your order for " +
orderQuantity + " " + currentProduct.name
+ "s succeeded.") ;
document.WriteLn( "Now in stock: " +
currentProduct.quantity + ".") ;
} else {
document.WriteLn( "Your order for " +
orderQuantity + " " + currentProduct.name
+ "s failed.") ;
document.WriteLn( "We only have " +
currentProduct.quantity + " in stock.") ;
}
-->

Using arrays
Arrays are useful for keeping track of a collection of objects. Typically, you
index a variable using integers, as in this example of three prices:
price = new Array(3);
price[0] = 19.95;
price[1] = 42.99;
price[2] = 0.02;
A common programming construct is a loop that performs some action on each
element of an array. The loop variable iterates over the index of the array, as in
the following example:

137
Script tutorials

for ( i = 0 ; i < price.length; i++ ) {


document.WriteLn("Price of item #" +
i + " = " + price[ i ] );
}
This produces the following output:
Price of item #0 = 19.95
Price of item #1 = 42.99
Price of item #2 = 0.02

Passing variables from one document to another


Some functions must be able to receive and act on user input from the Web
client. This information is sent by the Web client when a form is filled out as
part of the Uniform Resource Locator (URL) that retrieves the form.
For example, suppose the Web client displays a form containing a list box, a
text box, and an Order button. The user selects a particular product from the
list, enters the desired quantity in the text box, then clicks the button to order
the product.
The Order button points to an order-processing template that has a URL of
http://www.sybase.com/products/order.html. When the Order button is
clicked, the Web client sends the URL along with arguments that specify the
order information. For example, if the user orders 25 of product #600, the
complete URL would be:
http://www.sybase.com/products/order.html?id=600&quant
ity=25
The question mark separates the address of the document from the arguments
supplied to the document. An ampersand separates each of the arguments in the
list. In this example, the two arguments id and quantity are sent, with values
600 and 25 respectively.
Referring to You can fill in the value of a supplied argument in the HTML part of a
arguments in the document by preceding the value with a dollar sign. For example:
document
<HTML>
<TITLE>Displaying variables</TITLE>
<BODY>
The value of argument quantity is $quantity.
</BODY>
</HTML>
If this template is called with this URL:

138
CHAPTER 6 Writing DynaScripts

http://address?quantity=25
the following HTML is returned to the Web client:
<HTML>
<TITLE>Displaying variables</TITLE>
<BODY>
The value of argument quantity is 25.
</BODY>
</HTML>
Using arguments in You can also use arguments inside scripts. The argument is a property of the
scripts document, which is a predefined object. The actual value of an argument
named quantity can be accessed inside a script as:
document.value.quantity
The following script responds to user input for an order:
<!--SCRIPT
var currentProduct = new product(600, "Sweatshirt",
"Large", "Green", 39, 24.00 ) ;
var orderQuantity = document.value.quantity ;
var retval = currentProduct.order(orderQuantity) ;
if (retval) {
document.WriteLn( "Your order for " +
orderQuantity + " " + currentProduct.name +
"s succeeded.") ;
document.WriteLn( "Now in stock: " +
currentProduct.quantity + ".") ;
} else {
document.WriteLn( "Your order for " +
orderQuantity +
" " + currentProduct.name + "s failed.") ;
document.WriteLn( "We have only " +
currentProduct.quantity + " in stock.") ;
}
-->
For information on passing values of a multiple selection list see “value
property” in PowerDynamo Reference.

139
Script tutorials

Using object inheritance


DynaScript extends JavaScript to include inheritance, which is the ability to
create a new class of object that extends an existing class. The new class
inherits all of the properties and methods of the parent class, and adds its own
properties and methods.
This is tremendously useful when you are dealing with objects that share
characteristics. Instead of defining each object separately, you can identify the
information and behavior that is common to them, then define the objects
themselves as extensions of the common material.
Without inheritance For example, suppose that Acme Widgets has some employees that are paid a
salary, while others are paid by the hour. You could define two separate classes,
salariedEmployee and hourlyEmployee, with their own sets of properties
and methods. Here’s a simple version:
class salariedEmployee(name, title, managerName,
salary)
this.name = name;
this.title = title;
this.managerName = managerName;
this.salary = salary;
function PrintNameAndTitle() {
document.WriteLn("Name, title: " + this.name
+ ", " + this.title); }
this.PrintNameAndTitle = PrintNameAndTitle;
function PrintAllInfo() {
document.WriteLn("Name: " + this.name);
document.WriteLn("Title: " + this.title);
document.WriteLn("Reports to: " +
this.managerName);
document.WriteLn("Salary: " + this.salary); }
this.PrintAllInfo = PrintAllInfo;
}
class hourlyEmployee(name, title, managerName, wage)
this.name = name;
this.title = title;
this.managerName = managerName;
this.wage = wage;
function PrintNameAndTitle() {
document.WriteLn("Name, title: " + this.name
+ ", " + this.title); }
this.PrintNameAndTitle = PrintNameAndTitle;
function PrintAllInfo() {
document.WriteLn("Name: " + this.name);
document.WriteLn("Title: " + this.title);

140
CHAPTER 6 Writing DynaScripts

document.WriteLn("Reports to: " +


this.managerName);
document.WriteLn("Hourly wage: " + this.wage); }
this.PrintAllInfo = PrintAllInfo;
}
With inheritance Because there is a lot of duplication between the two classes of employees,
you’ll be maintaining two nearly identical sets of code. Suppose instead that we
take the common items (name, title, managerName, and
PrintNameAndTitle) and move them into a new generic class called
employee:
class employee(name, title, managerName) {
this.name = name;
this.title = title;
this.managerName = managerName;
function PrintNameAndTitle() {
document.WriteLn("Name, title: " + this.name
+ ", " + this.title); }
this.PrintNameAndTitle = PrintNameAndTitle;
}
We can then change salariedEmployee and hourlyEmployee to use this
new employee class as their common parent. To do this, we use the extends
clause of the class statement:
class salariedEmployee(name, title, managerName,
salary)
extends employee(name, title, managerName) {
this.salary = salary;
function PrintAllInfo() {
document.WriteLn("Name: " + this.name);
document.WriteLn("Title: " + this.title);
document.WriteLn("Reports to: " +
this.managerName);
document.WriteLn("Salary: " + this.salary);
}
this.PrintAllInfo = PrintAllInfo;
}
class hourlyEmployee(name, title, managerName, wage)
extends employee(name, title, managerName) {
this.wage = wage;
function PrintAllInfo() {
document.WriteLn("Name: " + this.name);
document.WriteLn("Title: " + this.title);
document.WriteLn("Reports to: " +
this.managerName);

141
Script tutorials

document.WriteLn("Hourly wage: " +


this.wage);
}
this.PrintAllInfo = PrintAllInfo;
}
We can then try out the redefined classes by creating salaried and hourly
employees, then printing their information:
var salaryEmp = new salariedEmployee("Ned Simpson",
"Technical Writer", "Barney Burns", 80000);
salaryEmp.PrintNameAndTitle();
salaryEmp.PrintAllInfo();
document.WriteLn("");
var hourlyEmp = new hourlyEmployee("Marge Flanders",
"Contractor", "Barney Burns", 25);
hourlyEmp.PrintNameAndTitle();
hourlyEmp.PrintAllInfo();
This produces the following output:
Name, title: Ned Simpson, Technical Writer
Name: Ned Simpson
Title: Technical Writer
Reports to: Barney Burns
Salary: 80000
Name, title: Marge Flanders, Contractor
Name: Marge Flanders
Title: Contractor
Reports to: Barney Burns
Hourly wage: 25
There are several things to note here:
• The salariedEmployee and hourlyEmployee classes do not have
their own PrintNameAndTitle methods, so they automatically use the
PrintNameAndTitle method of the employee parent class.
If required, these classes could define their own PrintNameAndTitle
methods, which would be used instead of the parent class's
PrintNameAndTitle method. This is called overriding a parent
method.

142
CHAPTER 6 Writing DynaScripts

• The PrintAllInfo method is polymorphic; that is, you can call


PrintAllInfo for instances of salariedEmployee and
hourlyEmployee, and they each respond in their own way. This is
especially handy when looping through arrays of objects, since you can
use the same method call on each object (instead having to use if
statements to call methods like PrintAllSalariedInfo,
PrintAllHourlyInfo, and so on).
• Once you have defined salariedEmployee and hourlyEmployee, we
would not ordinarily create instances of the parent class employee – it is
designed as an abstract class that simply collects the common properties
and behavior.
To handle a third kind of employee who was neither salaried or hourly,
simply create a new class derived from employee and add the appropriate
properties and methods (including a PrintAllInfo method.

143
Script tutorials

144
CH A PTE R 7 PowerDynamo and Java

About this chapter This chapter provides an introduction to Java and an example of using
Java within a PowerDynamo script.
Contents
Topic Page
An introduction to Java 146
Dynamo and Java 155
Configuring Dynamo to use Java 156
Using Java in a PowerDynamo script 158

145
An introduction to Java

An introduction to Java
This section introduces key Java concepts. After reading this section you
should be able to examine Java code, such as a simple class definition or the
invocation of a method, and understand what is taking place.

Object-oriented and procedural languages


This section explains some of the key similarities and differences between
procedural and object-oriented languages.
Java is based on The main structural unit of code in Java is a class. A Java class is a collection
classes of procedures and variables that have been grouped together because they all
relate to a specific, identifiable category.
The manner in which classes get used is what sets object oriented languages
apart from procedural languages. When an application written in a procedural
language is executed, it is typically loaded into memory once and takes the user
down a predefined course of execution.
In object-oriented languages such as Java, classes are used like templates, in
other words, a definition of potential program execution. Multiple copies of a
class can be created and loaded dynamically, as needed, with each instance of
the class capable of containing its own data, values, and course of execution.
Each loaded class can be acted on or executed independently of any other class
loaded into memory.
A class that is loaded into memory for execution is said to have been
instantiated. An instantiated class is called an object – it is an application
derived from the class that is prepared to hold unique values or have its
methods executed in a manner independent of other class instances.
For example, you could design an Invoice class to mimic a paper invoice and
include certain information, like line-item details, who is being invoiced, the
date of the invoice, the payment amount, and when payment is due. This
information is contained in an instance of an Invoice class.
In addition to just holding data, a class is capable of calculations and logical
operations. For example, you could also define the Invoice class to calculate
the tax on a list of line items, and add it to the subtotal to produce a final total.
You could define every Invoice object to do this without user intervention.
Such a class could also ensure all essential pieces of information are added to
the invoice and even indicate when payment is overdue or partially paid.

146
CHAPTER 7 PowerDynamo and Java

A class combines the ability to hold information and perform computational


operations.
Example The code below declares a class called Invoice. This class declaration would
be stored in a file named Invoice.java. It could then be compiled into a Java
class, using a Java compiler.

A note about compiling Java classes


Compiling a Java class declaration creates a new file with the same name but
a different extension. Compiling Invoice.java creates a file called Invoice.class
that could be used in a Java application and executed by a Java VM.
The Sun JDK tool for compiling class declarations is javac.exe.

public class Invoice {


// So far, this class does nothing and knows nothing
}
The class keyword is followed by the name of the class. There is an opening
and closing brace: everything declared between the braces, such as fields and
methods, becomes a part of the class.
No Java code exists outside class declarations. Even the Java procedure that a
Java interpreter runs automatically to create and manage other objects — the
main method that is often the start of your application—is located within a
class declaration.

Java classes and objects


A class is the template for what can be done–it defines what an object is
capable of doing just as an invoice form defines the information the invoice
should contain.
Information is not held in a class. An object is created based on the class and
the object is used to hold data or perform calculations or other operations.
An object is said to be of type JavaClass, where JavaClass is the name of the
class upon which the object is based. An Invoice object is an instance of the
Invoice class. The class defines what the object is capable of but the object
gives the class meaning and usefulness.
This is similar to the invoice example. The invoice form defines what all
invoices based on that form can accomplish. There is one form and zero or
many invoices based on the form. The form contains the definition but the
invoice does the work.

147
An introduction to Java

Similarly it is the Invoice object that gets created, stores information, is stored,
retrieved, edited, updated, and so on.
Just as one invoice template is used to create many separate and distinct
invoices, many objects can be generated from one class.
Methods and fields A method is the part of the class that performs a calculation or interacts with
other objects. Methods can accept arguments, and return a value to the calling
function. If no return value is needed, a method can return void. Classes can
have any number of methods.
A field is the part of a class that ends up holding information. When an object
of type JavaClass is created, the fields in JavaClass are available to be passed
values unique to that object.
Examples To declare a field in a class, state its type and name, followed by a semicolon.
Such a variable is a field if it is declared in the body of the class and not within
a method. Declaring a variable within a method makes it a part of the method,
not the class.
public class Invoice {

// Fields are things an Invoice object knows


public String lineItem1Description;
public int lineItem1Cost;

public String lineItem2Description;


public int lineItem2Cost;

Adding methods
You might want to include a method in the Invoice class. Declare a method by
stating its return type, its name, and what parameters it takes (in this case,
none). Like a class declaration, the method uses an opening and closing brace
to identify the body of the method where the code goes.
public class Invoice {

// Fields
public String lineItem1Description;
public double lineItem1Cost;

public String lineItem2Description;


public double lineItem2Cost;

148
CHAPTER 7 PowerDynamo and Java

// A method
public double totalSum() {
double runningsum;

runningsum = lineItem1Cost + lineItem2Cost;


runningsum = runningsum * 1.15;

return runningsum;
}
}
Within the body of the totalSum method, a variable named runningsum is
declared. This is used first to hold the subtotal of the first and second line item
cost. This subtotal is then multiplied by the rate of taxation to determine the
total sum.
The local variable (as it is known within the method body) is then returned to
the calling function. When the totalSum method is invoked, it returns the
sum of the two line item cost fields plus the cost of tax on those two items.

Instance methods and class methods


Most methods are used with an instance of a class. For example, a totalSum
method in the Invoice class can calculate and add the tax, and return the sum
of all costs, but is useful only if called in conjunction with an Invoice object
that has values for its line item costs. The calculation can only be performed
for an object, since the object, not the class, contains the line items of the
invoice. The class only defines the capability of the object to have line items.
Only the object has the data needed to perform such a calculation.
Java methods are divided into two categories:
•Instance methods The totalSum method is an example of an instance
method that can only be used in a conjunction with an object and object
data.
•Class methods Class methods are also called static methods. A class
method can be invoked without an object. Only the name of the class and
method is required to invoke a class method.
Similar to instance methods, class methods accept arguments and return
values. Typically, class methods perform some sort of utility or
information function related to the overall functionality of the class.

149
An introduction to Java

The parseInt method of the java.lang.Integer class, which is supplied


with Adaptive Server Anywhere, is one example of a class method. When
given a string argument, the parseInt method returns the integer version of
the string.
For example given the string value “1,” the parseInt method returns 1, the
integer value, without requiring an instance of the java.lang.Integer class
to first be created as illustrated by this Java code fragment.
String num = "1";
int i = java.lang.Integer.parseInt( num );
Fields can also be declared using the static Java keyword, which makes them
into class fields. A static class variable is like a global variable in procedural
languages, except that its value is predetermined and cannot be changed. A
field whose name is all in capital letters is often a static variable (class field).
Examples The following version of the Invoice class now includes both an instance
method and a class method. The class method rateOfTaxation returns the
rate of taxation used by the class to calculate the total sum of the invoice.
The advantage of making rateOfTaxation a class method (as opposed to an
instance method or field) is that other classes and procedures can use the value
returned by this method without having to create an instance of the class first.
Only the name of the class and method is required to return the rate of taxation
used by this class.
It allows the application developer to change how the rate is calculated without
adversely effecting any objects, applications, or procedures that use its return
value. rateOfTaxation can be changed without affecting other methods that
use its return value.
public class Invoice {

// Fields
public String lineItem1Description;
public double lineItem1Cost;

public String lineItem2Description;


public double lineItem2Cost;

// An instance method
public double totalSum() {
double runningsum;
double taxfactor = 1 + Invoice.rateOfTaxation();

runningsum = lineItem1Cost + lineItem2Cost;

150
CHAPTER 7 PowerDynamo and Java

runningsum = runningsum * taxfactor;

return runningsum;
}

// A class method
public static double rateOfTaxation() {
double rate;
rate = .15;

return rate;
}
}

A Java glossary
The following items outline some details regarding Java classes that may aid
in the use of Java classes in PowerDynamo.
Public versus private The visibility of a field, method, or class to other Java objects and operations
is determined by what is known as an access modifier — essentially the
public, private, or protected keyword used in front of any declaration.
Fields and methods can be declared private or public, meaning, respectively,
their values are available to code within the object, or to code/classes/objects
both inside and outside the object.
Fields or methods declared as private cannot be manipulated or accessed by
methods outside the class. Public fields or methods can be directly accessed by
other classes and methods.
Packages and the Protected fields or methods are accessible only:
protected modifier
• Within their class
• Within subclasses that inherit from their class
• Within the package of which the class is a part
A package is a grouping of classes that share a common purpose or category.
Members of a package have special privileges to access data and methods in
other members of the package, hence the protected access modifier.
A package is the Java equivalent of a library. It is a collection of classes, that
can be made available using the import statement. The following Java
statement imports the utility library from the Java API:

151
An introduction to Java

import java.util.*
Packages are typically held in Java archive (Jar) files, which have the extension
.jar or .zip.
Constructors A constructor is a special method of a Java class that creates an instance of the
class and returns a reference to the newly-created Java object.
Classes can define their own constructors, including multiple, overriding
constructors. Which constructor is used is determined by the arguments used
to create the object. When the type, number, and order of arguments used to
create an instance of the class match one of the class’s constructors, that
constructor is used to create the object.
Destructors There is no such thing as a destructor method in Java (as there is in C++). Java
classes can define a finalize method for clean-up operations when an object
is discarded, but there is no guarantee that this method will get called.
An object that has no references to is automatically removed by a “garbage
collection” process.
Other C++ differences Everything related to a class is contained within the boundaries of the class
declaration, including all methods and fields.
Classes can inherit from only one class. Java uses interfaces instead of
multiple-inheritance. A class can implement multiple interfaces. Each interface
defines a set of methods and method profiles that must be implemented by the
class in order for the class to compile.
An interface is similar to an abstract class; it defines what methods and static
fields the class must declare. The implementation of the methods and fields
declared in an interface is located within the class that uses the interface. The
interface defines what the class must declare, and it is up to the class to
determine how it is implemented.

Java error handling


Java error handling code is separate from the code for normal processing.
When an error occurs, an exception object representing the error is generated.
This is called throwing an exception. A thrown exception will terminate a Java
program unless it is caught and handled properly at some level of the
application.

152
CHAPTER 7 PowerDynamo and Java

Both Java API classes and custom-created classes can throw exceptions. In
fact, users can create their own exceptions classes, which can be thrown by
their own custom-created classes.
If there is no exception handler in the method where the exception occurred,
the search for an exception handler continues up the call stack. If the top of the
call stack is reached and no exception handler has been found, the default
exception handler of the Java interpreter running the application is called and
the program terminates.
Error types in Java All errors in Java are derived from two types of error classes: Exception and
Error. Usually, exception errors are handled by error-handling code in your
method body. Error type errors are reserved for internal and resource
exhaustion errors inside the Java runtime system.
Exception class errors are thrown and caught. Exception handling code is
characterized by try, catch, and finally code blocks.
A try block executes code that may generate an error. A catch block will
execute if an error is generated (thrown) during the execution of a try block.
A finally block defines code executes regardless of whether an error was
generated and caught and is typically used for clean-up operations. It is used
for code that, under no circumstances, can be omitted.
Exception errors are divided into runtime exceptions and those that are not
runtime exceptions.
Errors generated by the runtime system are known as implicit exceptions,
because they do not have to be explicitly handled as part of every class or
method declaration.
For example, an array out of bounds exception can occur whenever an array is
used, but the error does not have to be part of the declaration of the class or
method that uses the array.
All other exceptions are explicit. If the method being invoked can throw an
error, it must be explicitly caught by the class using the exception throwing
method, or this class must explicitly throw the error itself by identifying the
exception it may generate in its class declaration.
A method must declare all the explicit errors it throws, or catch all the explicit
errors that may be potentially thrown.
Non-runtime exceptions are checked at compile time. Runtime exceptions are
usually caused by errors in programming. Java catches many such errors
during compilation, before the code is run.

153
An introduction to Java

Every Java method is given an alternative path of execution so that all Java
methods complete, even if they are unable to complete normally. If the type of
error that is thrown is not caught, it’s passed to the next code block or method
in the stack.

154
CHAPTER 7 PowerDynamo and Java

Dynamo and Java


PowerDynamo supports Java classes in PowerDynamo scripts.
You can create Java classes using PowerJ or any other Java development tool.
These classes are then deployed to one of two places for Dynamo scripts to
have access to them:
• A PowerDynamo Web site (database-hosted or file-hosted)
• The file system of the PowerDynamo host machine
Before you can write Dynamo scripts that use Java objects, you must first
configure PowerDynamo to recognize these classes.
You should restart Dynamo whenever changes are made to the Java class that
is being instantiated.

155
Configuring Dynamo to use Java

Configuring Dynamo to use Java


You must configure your Web site to use Java class objects within your Web
site. You should be aware of the following configuration options in the
Configuration folder of Sybase Central if you wish to create and use instances
of Java class objects within your Dynamo scripts.

❖ Java VM
Dynamo provides Java support only if you have selected a Java VM in the
Sybase Central Configuration folder.
1 From the Configuration folder, open the Default General Settings folder.
2 In the right pane, double-click the Java VM setting.
3 Select the Java VM option from the drop-down list and click OK.
4 Restart PowerDynamo if you change the Java VM.

Note
If using the Sun VM you must have JDK 1.1.6 or higher installed. For
information, see http//java.sun.com/jdk/1.1. If using the Microsoft VM, you
must have msjava.dll (version 5) installed. For information, see
http//www.microsoft.com/java/download.htm.

❖ Java class cache


To improve performance, information about the methods and properties of Java
classes is cached. To set the Java class cache:
1 From the Configuration folder, open the Mappings folder.
2 In the right pane, double-click the URL prefix to modify.
3 Enter the maximum size of the java cache and click OK. The default value
is 2048KB.
4 If you change your cache size, you must restart PowerDynamo.

❖ Classpath for the mapping


Class files that are stored in a database-hosted Web site must have their class
path specified in Sybase Central. If class files in the file system are being
called, you do not need to set this classpath. To set the Classpath:
1 From the Configuration folder, open the Mappings folder.
2 In the right pane, double-click the URL prefix to modify.

156
CHAPTER 7 PowerDynamo and Java

3 Enter the classpath for this mapping in the field provided and click OK.
4 If you change your classpath, you must restart PowerDynamo.

Executing scripts from within Sybase Central


To execute scripts that use the Java objects from within Sybase Central, the
mapping and Dynamo site name must be identical. If you are running your
scripts exclusively through a server such as the Personal Web Server, this is not
necessary.

Check he following PATH and CLASSPATH environment variables:


• If using the MS VM, ensure that your PATH variable points to
msjava.dll.
• If using the SUN VM, ensure that your PATH variable points to
javai.dll or java.dll.
• If using the SUN DebugVM, ensure that your PATH variable points
to javai_g.dll or java_g.dll.
• Ensure that your CLASSPATH variable contains the path to the
system classes for the VM that you are using (typically these classes
are contained in a file called classes.zip).

157
Using Java in a PowerDynamo script

Using Java in a PowerDynamo script


Java classes can be stored either in the PowerDynamo Web site, a dynamic
Web site, or somewhere on the file system. Importing a Java class into a
PowerDynamo Web site is the same as importing any other file. Once the Java
class is in an accessible location, you are ready to use the class in a Dynamo
script.
Java classes can be accessed from within a database or within the file system.
Depending on which of these locations you will be accessing your Java class
from, you will have to perform certain steps. Generally, you should store Java
classes within a database when you want to replicate the classes along with the
database. If you don’t need the Java classes stored in the database, you should
probably store them in the file system for performance reasons.

❖ To call Java classes stored in the file system:


1 Write and compile your Java code.
2 Set the required Java VM from within the Sybase Central Configuration
folder.
3 Modify the CLASSPATH environment variable to point to the location of
the Java class in the file system.
4 Restart PowerDynamo.
5 Write your PowerDynamo script.
6 Execute.

❖ To call Java classes stored in a Dynamo Web site:


1 Write and compile your Java code.
2 Import the Java class into the database.
3 Set the required Java VM from within the Sybase Central Configuration
folder.
4 Modify the Dynamo CLASSPATH in the Sybase Central Configuration
folder to point to the imported Java class.
5 Restart PowerDynamo.
6 Write your PowerDynamo script.
7 Execute.

158
CHAPTER 7 PowerDynamo and Java

File-hosted Web site


A Web site that is hosted in the file system can use either of these methods but
storing Java classes in the file system probably produces more efficient results.

Here is a simple example of a Java class that performs basic string


manipulation. Let’s assume that the following Java class has been imported into
our database-hosted Web site.
public class testclass {
public String str;
public testclass( String str1 ) { str = str1; }
public testclass() { str = "";}
public String getstr() { return str; }
public void setstr( String newstr ) { str = newstr; }
public String Upper() {
return Upper( str );
}
public String Upper( String str1 ) {
return str1.toUpperCase();
}
}
Let’s also assume that we have chosen our Java VM and set the CLASSPATH
variable using Sybase Central.
In our script we will use the Java.CreateObject method. The Java object
manipulates Java classes within PowerDynamo scripts. The CreateObject
method is just one of the Java objects methods and is used to instantiate a Java
class so that it can be used as an object within your PowerDynamo script. The
syntax for this method is:
java.CreateObject( class_name [, list of constructor parameters] )
The Java class we are going to use in our script is called testclass. It does not
take any parameters. The proper syntax to instantiate testclass in our script is:
cls1 = java.CreateObject( "testclass" );

159
Using Java in a PowerDynamo script

The Java class that we are instantiating has properties and methods associated
with it. To use those properties within our Dynamo script, the Java class must
contain both get and set functions for this property. For example, testclass has
a property called str. When this property is used within a Dynamo script to
display the value of the str property ( document.WriteLn( cls1.str );
) in actuality, the getstr function from the Java class is called. The same holds
true for setting a property; the setstr function would be called. If you look at
the testclass code you will see that the str property has both get and set
functions.
Working with methods of an instantiated Java class is the same as working with
any DynaScript method.

Methods that take a Java class parameter


If you have a method that takes another Java class parameter, that class must
be instantiated within the script before it can be used.

For further information about the Java object and its methods see “The java
object” in PowerDynamo Reference.
The following is a Dynamo script that provided two strings for manipulation
by the testclass object:
<!--SCRIPT

string1 = "This is my very long test string ";


string2 = "that I am using"

// The Java class is instantiated


cls1 = java.CreateObject( "testclass" );
if( cls1 == null ) {
document.writeln( site.GetErrorInfo() );
return;
}

// The str property is read - uses the getstr method


document.writeln( "1 " + cls1.str );

// Assigns a property to a Java class - uses the


// setstr method
cls1.str = string1 + string2;
document.writeln( "2 " + cls1.str );

// Instantiates a Java class with parameters


cls2 = java.CreateObject( "testclass", string2 );
if( cls2 == null ) {

160
CHAPTER 7 PowerDynamo and Java

document.writeln( site.GetErrorInfo() );
return;
}

// A method is invoked
document.writeln( "3 " + cls1.Upper() );

// A method is invoked that takes parameters


document.writeln( "4 " + cls2.Upper( "this is all
upper" ) )
-->
The output for this script would look something like this:
1
2 This is my very long test string that I am using
3 THIS IS MY VERY LONG TEST STRING THAT I AM USING
4 THIS IS ALL UPPER
As you can see, once you have instantiated the Java class within your script,
you work with the Java object in the same manner that you would work with
any other object within a Dynamo script.

Arrays in Java
PowerDynamo does not support array indexing in Java. Use the Java class
java.lang.reflect.Array if you require array manipulation. For example:
<!--SCRIPT
// First create the class we want an array of
String_Class = java.CallStaticMethod(
"java/lang/Class", "forName", "java.lang.String" );
// Create the array with the class and a length
strarray = java.CallStaticMethod(
"java/lang/reflect/Array","newInstance", String_Class,
10 );
// Use the various set and get methods to access the
// created array
java.CallStaticMethod( "java/lang/reflect/Array",
"set", strarray, 1, "hello" );
y = java.CallStaticMethod(
"java/lang/reflect/Array", "get", strarray, 1 );
document.writeln(y.toString());
-->

161
Using Java in a PowerDynamo script

CallStaticMethod
This example uses the CallStaticMethod method of the Java object, which
enables users to access static methods without creating (java.CreateObject) an
instance of the object within the script.

Method overloading and type conversion


Method overloading in Java may occasionally cause problems in Dynamo.
In most cases, PowerDynamo can handle overloading. There are a few cases,
however, where this is not the case. For example, take the following methods:
My_method( long, string, bool, int );
My_method( int, string, bool, int );
Lets assume that the following method call is being made:
Obj.My_method( 4, "hello", true, 7 );
Although Dynamo strings and Java strings are not exactly the same, Dynamo
is able to recognize the difference and make the conversion. The same is true
for converting Java Booleans to Dynamo Booleans and Java ints to Dynamo
ints.
The problem arises for the above example because Dynamo does not know
which method to use. The variables hello, true, and 7 are all easily identified.
The variable 4, however, could be either an integer or a long so either method
could be the correct one to use. At this point an error message indicating an
ambiguous method call displays.
If the My_method was instead overloaded in the following manner:
My_method( string, string, bool, int );
My_method( int, string, bool, int );
There would be no problem with the method call, Dynamo can discern that 4
is an int and not a string.

162
CHAPTER 7 PowerDynamo and Java

Calling Jaguar components


You can use PowerDynamo to call Java components through Jaguar CTS. This
process is explained in “Calling Jaguar Component Methods from
PowerDynamo” on page 261. For complete information on Jaguar CTS, see the
Jaguar documentation.

163
Using Java in a PowerDynamo script

164
CH A PTE R 8 Working with XML Documents

About this chapter XML is becoming a standard framework for exchanging data over the
Web. This chapter describes how you can use Dynamo to manipulate
XML documents and data.
Contents
Topic Page
Dynamo and XML 166
An introduction to XML 167
Creating XML documents 170
Introduction to the Document Object Model 177
Document Object Model examples 182
Creating the DOMDocument object 187
Working with elements 189
Working with text 193
Working with entities 197
Working with other XML objects 199
Using the DOM interface to create and edit XML documents 200

165
Dynamo and XML

Dynamo and XML


XML stands for eXtensible Markup Language. It is a framework for creating
markup languages. Each XML markup language is a set of tags (or elements),
and a set of rules about where each element can occur.
HTML is an example of a markup language. It contains elements such as
headings, lists, tables, and so on. There are rules governing where these
elements can occur.
XML provides a framework for data exchange. An XML document can hold
many kinds of data, including file formats, relational database data, and
information transmitted from Web browsers to Web servers.
For example, you can use XML to describe a sales transaction exchanged
between two applications or to describe the contents of a Web page. For the
remainder of this chapter, the word document is used to mean any XML
document.
Dynamo and XML Dynamo provides several tools for working with XML.
• DynaScript functions and tags that let you take information from a
database, and provide it to a Web browser in XML form.
For information, see “Creating XML documents” on page 170.
• A DynaScript function to parse XML documents (process them into a
form understandable by the application).
For information, see “Creating the DOMDocument object” on page 187.
• A set of DynaScript objects to access individual pieces of a parsed
document.
For information, see “Introduction to the Document Object Model” on
page 177.
• A set of DynaScript objects to create and modify XML documents.
For information, see “Using the DOM interface to create and edit XML
documents” on page 200.
• A utility function (xmlEscape) to aid in escaping data for XML.
For information, see “Escaping text with xmlEscape” on page 195.

166
CHAPTER 8 Working with XML Documents

An introduction to XML
XML is a framework for creating markup languages. It has been designed
specifically for use on the Web.
Example Here is an example XML document:
<?xml version="1.0"?>
<Example>
<Computer>
<Name>Toshiba</Name>
<Processor>Pentium</Processor>
<Memory units="MB">96</Memory>
</Computer>
</Example>
Any complete XML document starts with an XML declaration (the first line in
the example above).
Other attributes can be added to this declaration, as described in any XML
book.

Valid and well-formed XML documents


An XML document must be valid, well-formed, or both. The following
sections discuss each type of document.
Valid documents To define a set of tags for use in a particular application, XML uses a separate
document named a document type definition (DTD). A DTD states what tags
are allowed in an XML document and defines rules for how those tags can be
used in relation to each other. It defines the elements that are allowed in the
language, the attributes each element can have, and the type of information
each element can hold. Documents can be verified against a DTD to ensure that
they follow all the rules of the language. A document that satisfies a DTD is
said to be valid.
The DTD for documents like the example given above might look something
like this:
<!DOCTYPE Example [
<!ELEMENT Computer (Name, Processor, Memory)>
<!ELEMENT Name (#PCDATA)>
<!ELEMENT Processor (#PCDATA)>
<!ELEMENT Memory (#PCDATA)>
<!ATTLIST Memory units #REQUIRED>
]>

167
An introduction to XML

If a document uses a DTD, the DTD must immediately follow the declaration.
Well-formed The second way to specify XML syntax is to assume that a document is using
documents its language properly. XML provides a set of generic syntax rules that must be
satisfied, and as long as a document satisfies these rules, it is said to be well-
formed. All valid documents must be well-formed.
Processing well-formed documents is faster than processing valid documents
because the parser does not have to verify against the DTD. When valid
documents are transmitted, the DTD must also be transmitted if the receiver
does not already possess it. On the other hand, well-formed documents can be
sent without other information.
XML documents should conform to a DTD if they are going to be used by more
than one application. If they are not valid, there is no way to guarantee that
various applications will be able to understand each other.
In this chapter, most examples use well-formed documents with no DTD, for
simplicity.

XML syntax
There are a few more restrictions on XML than HTML, which make parsing
simpler. Unlike in HTML, you cannot omit tags. This guarantees that parsers
know where elements end. The following example is acceptable HTML, but
not XML:
<table>
<tr>
<td>Dog</td>
<td>Cat
<td>Mouse
</table>
To make this well-formed XML, you need to add all the missing end tags:
<table>
<tr>
<td>Dog</td>
<td>Cat</td>
<td>Mouse</td>
</tr>
</table>

168
CHAPTER 8 Working with XML Documents

Empty elements cannot be represented in XML the same way they are in
HTML. An empty element is one that is not used to markup data, so in HTML
there will not be an end tag. There are two ways to handle empty elements. The
first is to place a dummy tag immediately after the start tag. For example:
<img href="picture.jpg"></img>
The second method is to use a slash character at the end of the initial tag:
<img href="picture.jpg"/>
This tells a parser that the element consists only of one tag.
XML is case sensitive, which allows XML to be used with non-Latin
alphabets. You must ensure that letter case matches in start and end tags:
<MyTag> and </Mytag> belong to two different elements.
White space within tags in XML is unchanged by parsers.
All elements must be All XML elements must be properly nested. All child elements must be closed
nested before their parent elements close.

169
Creating XML documents

Creating XML documents


In PowerDynamo, an XML document is any string that contains a valid XML
document. Once you have created an XML document, you can send it to a
browser, or parse it and process it using the DynaScript DOM objects.
You can create XML documents in PowerDynamo from a variety of sources:
•DynaScript query object From a query object, using the
ResultsToXMLString method.
•Dynamo SQL and FORMATTING tags From a query, using the
FORMATTING tag with the FORMAT_AS attribute set to XML.
•DynaScript objects From any DynaScript object, using the
toXMLString function.
•Sybase Central From the Add Template wizard, which provides XML
output options.
•DynaScript By writing scripts to output XML documents in a custom
fashion, adding tags as required.
•Import By importing an XML file into your Web site.
The built-in methods for producing XML documents are discussed in this
section.

Creating XML documents from the query object


If you use the DynaScript query object to execute a SQL query against your
database, you can use the ResultsToXMLString method to wrap the results
in XML tags.
For an alternative approach using tags, see “Creating XML documents from
queries using the FORMATTING tag” on page 172.
Example The following script illustrates how to use ResultsToXMLString:
myConn = site.GetConnection( "myConn" ); //1
myQuery = myConn.CreateQuery(
"SELECT id, name, unit_price FROM product" ); //2
xmlString = myQuery.ResultsToXMLString(
"Products",
"Product",
"ID Name Price" ); //3
document.writeln( xmlString ); //4

170
CHAPTER 8 Working with XML Documents

•Line 1 Create a connection object from the current connection.


•Line 2 Create a query object from the connection object and executes the
query. The query retrieves some columns from the product table in the
demo database.
•Line 3 Format the query results into an XML string.
ResultsToXMLString takes between zero and four parameters. For
details, see “ResultsToXMLString method” in PowerDynamo Reference.
•Line 4 Write out the XML string. The string contains tags around the
individual results rather than providing a DTD. The output string has no
white space. Here it is, with white space added for readability:
<Products>
<Product>
<ID>600</ID>
<Name>Sweatshirt</Name>
<Price>24.00</Price>
</Product>
<Product>
<ID>601</ID>
<Name>Sweatshirt</Name>
<Price>24.00</Price>
</Product>
</Products>
The entire result set constitutes a Products element. Each row is a Product
element, and contains ID, Name, and Price elements.
Notes There are several points of interest in the above example.
•Error checking The example script does not include any error checking.
In a real application, you should verify that each individual step succeeds.
Check the method return values or use the GetErrorCode method of the
object carrying out the step. Many methods return null when they fail.
•White space White space outside tags, including new line and carriage
return characters, is significant in XML. It is added in the sample above
for readability, but in fact changes the document. You must be careful
about extraneous white space in your XML documents.
•XML header For the example script to be a complete XML document, you
must add a proper XML header, such as the following:
<?xml version=’1.0’ encoding=’ISO-8859-1’?>

171
Creating XML documents

•Default tags The default result set tag is SYBRESULTSET. The default
row tag is SYBROW. If you do not supply any tags in the arguments to
ResultsToXMLString, the name of the column is used as the tag for
each tag. If you supply a single tag, it is used for all columns. If you supply
more than one tag, but not as many as there are columns, then the
remaining columns tags default to the column labels.
•Validation The XML output string is not validated. To validate the XML,
you must do so independently of Dynamo.
•Applying attributes The ResultsToXMLString method provides a
convenient way of supplying simple XML. To specify attributes for XML
tags in your output, see “Creating custom XML documents from query
result sets” on page 172.

Creating custom XML documents from query result sets


You can customize the XML you obtain from the result set of a query object by
building an XML string explicitly, instead of using ResultsToXMLString.
For example:
xmlString = "<Products>";
while ( myQuery.MoveNext() ){
xmlString += "<Product>";
xmlString += "<ID>" + myQuery.GetValue(1) + "</ID>" ;
xmlString += "<Name>" + myQuery.GetValue(2) +
"</Name>";
xmlString += ’<Price units="DOLLARS">’ +
myQuery.GetValue(3) + "</Price>";
xmlString += "</Product>";
}
xmlString += "</Products>";

Creating XML documents from queries using the FORMATTING tag


The FORMATTING tag provides a way of writing out the results of queries as
XML.
The following template illustrates how to use the FORMATTING tag with
XML output. You must enter the FORMATTING tag, like any tag, all on one
line in a Dynamo template:
<!--SQL

172
CHAPTER 8 Working with XML Documents

SELECT description, color


FROM product
WHERE unit_price > 15
-->
<!--FORMATTING FORMAT_AS="XML"
RESULTSET_TAG="Products" ROW_TAG="Product"
COLUMN_TAG="Description Color"-->
<!--/FORMATTING-->
The output of this template is the following. Line wrapping occurs in the
printed document but is not present in the actual output string:
<Products>
<Product>
<Description>Hooded Sweatshirt</Description>
<Color>Green</Color>
</Product>
<Product>
<Description>Zipped Sweatshirt</Description>
<Color>Blue</Color>
</Product>
</Products>
Notes •Attributes The attributes of the FORMATTING tag are as follows:
•FORMAT_AS attribute Can have values of HTML or XML. HTML
is the default.
•RESULTSET_TAG attribute Provides the element name for the tag
that surrounds the entire result set. In the example, Products.
•ROW_TAG attribute Provides the element name for the tag that
surrounds each row. In the example, Product.
•COLUMN_TAG attribute If no COLUMN_TAG attribute is
provided, the column’s label is used. Multiple column tags can be
specified in a space-delimited string. If a single column tag is
provided, this tag is used to mark all columns. If multiple column tags
are provided, but not as many as there are columns, then the
remaining columns tags will default to the column labels.
•Only applies to default formatting The attributes apply only if there is
nothing between the FORMATTING tag and its end tag. If you add
<!--data--> tags, then the attributes do not apply.
•Validation The XML output string is not validated. To validate the XML,
you must do so independently of Dynamo.

173
Creating XML documents

•Applying attributes The FORMATTING tag provides a convenient way


of supplying simple XML. To specify attributes for any of the XML tags
in your output, see “Creating custom XML documents from query result
sets” on page 172.

Creating XML from DynaScript objects


You can create XML from any DynaScript object using the toXMLString
function.
This function accepts 1, 2, or 3 arguments:
• Argument 1 is the DynaScript object for which an XML representation is
requested.
• Argument 2 (optional) specifies whether to build a CDATA section to
escape special XML characters. The default value is false.
• Argument 3 (optional) specifies a set of tags to use when unnamed
members of the object are encountered. The toXMLString function
returns null if a non-object argument is passed as the first argument, or if
the object passed has no enumerable members. Otherwise it returns a
string.
Examples The following set of scripts illustrate how to use toXMLString:
• Create a simple object and write it out as an XML string. The property
names are used as tags.
<!--SCRIPT
myObj = null;
myObj.a = 2;
myObj.b = 3;
x = toXMLString( myObj );
document.writeln(x);
-->
The output for the script is as follows:
<a>2</a><b>3</b>
• Create a nested object and write it out as an XML string. The structure of
the document reflects the structure of the object.
<!--SCRIPT
//Create a nested object
myObj = null;
myObj.a = 2;

174
CHAPTER 8 Working with XML Documents

myObj.b.b1 = 3;
myObj.b.b2 = 4;
x = toXMLString( myObj );
document.writeln(x);
-->
The output for the script is as follows:
<a>2</a><b><b1>3</b1><b2>4</b2></b>
• Use the ampersand character to escape text. The toXMLString function
changes the < and > characters to the XML entities &lt; and &gt;.
<!--SCRIPT
// Using ’&’ character escaping" )
myObj = null;
myObj.a = 2;
myObj.b = "&<encoding needed>&";
x = toXMLString( myObj );
document.writeln(x);
-->
The output for the script is as follows:
<a>2</a><b>&amp;&lt;encoding needed&gt;&amp;</b>
• Use CDATA escaping of text that contains special characters, by adding a
second argument to toXMLString.
<!--SCRIPT
document.writeln( "***** Using CDATA character
escaping" );
myObj = null;
myObj.a = 2;
myObj.b = "&<encoding needed>&";
x = toXMLString( myObj, true );
document.writeln(x);
-->
The output for the script is as follows:
<a>2</a><b><![CDATA[&<encoding needed>&]]></b>
• Write an XML string from an object with indexed members, with no tags
specified.
<!--SCRIPT
// Indexed members with no tags specified"
myObj = null;
myObj[0] = 2;
myObj[1] = 3;

175
Creating XML documents

x = toXMLString( myObj, false );


document.writeln(x);
-->
The output for the script is as follows:
<0>2</0><1>3</1>
• Write an XML string from an object with indexed members. This time,
supply tags for the output.
<!--SCRIPT
// Indexed members, with tags specified" );
myObj = null;
row0 = null;
row1 = null;
row0[0] = "shirt";
row0[1] = "blue";
row1[0] = "hat";
row1[1] = "green";
myObj[0] = row0;
myObj[1] = row1;
x = toXMLString( myObj, false, "ROW COL" );
document.writeln(x);
-->
The output for the script is as follows:
<ROW><COL>shirt</COL><COL>blue</COL></ROW><ROW><COL
>hat</COL><COL>green</COL></ROW>

176
CHAPTER 8 Working with XML Documents

Introduction to the Document Object Model


Dynamo provides a set of DynaScript objects for navigating and manipulating
XML documents. These objects implement the Document Object Model
(DOM) core Level 1 features. The DOM is a W3C recommendation (REC-
DOM-Level-1-19981001).

What you can do with DOM


With the DOM interface, you can access and modify the content and structure
of XML documents from DynaScript. Tasks that you can carry out using DOM
including:
•Parsing XML documents The toDOMDocument function parses a string
that contains XML data. It builds an internal representation of the XML
document so that it can be manipulated and acted on.
•Converting XML to other formats For example, you can convert XML
to HTML for sending to a browser.
•Selectively displaying pieces of a document The DOM interface
allows you to navigate through a document and locate specific pieces. If
an XML document contains a SUMMARY element, you can select just
that piece and send it to the application.
•Change XML documents In addition to processing an existing
document, the DOM interface allows you to develop applications that
create and edit XML documents.

The DOM view of documents


The DOM interface presents XML documents to your application as a tree.
Consider the following simple XML document, shown with indented lines for
readability:
<?xml version=’1.0’ ?>
<Customer>
<FName>Jessie</FName>
<LName>Gagliardo</LName>
<Address>
<Street>2800 Park Avenue</Street>
<City>Hull</City>
<Region Type=Province>PQ</Region>

177
Introduction to the Document Object Model

</Address>
</Customer>
The tree representation of this document is shown in Figure 8-1.
Figure 8-1: Tree representation of XML document

The node interface to In a DOM representation of this document, each element is a node. You can
DOM navigate the document using the relationships among these nodes:
•Each node has at most one parent The parent of City is Address. The
parent of LName is Customer, and the parent of Customer is a special node
named the document node. The document node does not have a parent
node. No node can have more than one parent, and only certain classes of
node (such as the document node) can have zero parents.
In the DOM representation, each node has a parentNode property that
takes you to the parent of the current node.
•Nodes have zero, one, or more child nodes For example, the children
of Customer are FName, LName, and Address.
In the DOM representation, each node has a childNodes property that
provides you with a list of all children of the current node. It also provides
a firstChild and lastChild node to take you to those specific child
nodes. These nodes are ordered, and each has a previousSibling
property and a nextSibling property that enable you to loop through the
current node.

178
CHAPTER 8 Working with XML Documents

•Not all nodes are elements Some nodes represent text, such as the text
nodes shaded gray in the above diagram. Other nodes represent attributes,
entity references, comments, and so on.
For example, the Region element has a single attribute. This attribute is a
node, with a name of Type and a value of Province. Attribute nodes have
some differences from element and text nodes.
For more information on attribute nodes, see “Working with attributes” on
page 191.
•Some nodes contain text and other nodes Character data, or text, in a
node, is also considered to be a separate node. Thus the child of the FName
node is a node that has a nodeType of Text and a nodeValue of
Gagliardo.

In the following example:


<Sentence>The cat was <Em>very</Em> black</Sentence>
the Sentence node contains three children. The first is a text node (with a
value of “The cat was” ), the second is an Em element, and the third is
another text node (with a value of “black”).

Using nodes to work with XML documents


The DOMNode object is the primary object for the DOM model of documents.
It has a set of properties that you can use to obtain information about the node:
•Characteristics The nodeName, nodeType, and nodeValue properties
give information about the node. For example, nodeType tells you
whether the node represents an element, attribute, text, or some other node
type.
•Position You can use the parentNode, previousSibling,
nextSibling, firstChild, and lastChild properties to take you to
related nodes. You can use the hasChildNodes() method to determine
if a node has children, and if it does, the childNodes property returns a
whole list of children nodes.
•Modification You can use insertBefore, replaceChild,
removeChild, appendChild, and cloneNode to add or remove related
nodes.
•Element attributes If the node represents an element, the attributes
property returns a list of the XML attributes of the element.

179
Introduction to the Document Object Model

Node types The properties of nodes depend on what piece of an XML document they
represent. The node types and their corresponding values are:
nodeType value XML Comments
1 Element Many nodes are XML elements.
2 Attribute Attributes of an XML element.
3 Text Text can occur in elements, or in the
values of attributes.
4 CDATASection Typically used for including blocks
of text that contain characters that
would otherwise be regarded as
markup (such as <, >).
5 EntityReference A reference to an XML entity.
6 Entity An XML entity.
7 ProcessingInstruction An XML processing instruction.
8 Comment An XML comment: all the
characters between <!-- and -->.
9 Document The document with which the node
is associated.
10 DocumentType The document type definition
(DTD) of the document.
11 DocumentFragment A piece of a document, primarily
used for editing purposes.
12 Notation An XML notation.

The object interface to XML documents


While you can access all parts of a document as nodes, the DOM interface also
provides explicit objects for elements (DOMElement), attributes (DomAttr),
and other node types. These objects inherit properties from the DOMNode object
and provide some additional functionality of their own. The properties and
methods of each of these objects reflect the features of the XML object they
represent.
The following sections describe both the DOMNode approach and the object
interface. Although you can mix these approaches, most developers will want
to use one method per task, for consistency.

180
CHAPTER 8 Working with XML Documents

Performance tip
It is generally more efficient to use the explicit objects instead of the generic
node interface to XML documents.

Error checking XML-handling scripts


To assist in developing reliable scripts Dynamo provides:
•prettyPrint method The DOMNode object provides a prettyPrint()
method that returns the XML tree starting at the current node. This method
is an extension to the DOM recommendation, and takes no arguments. You
can use it in a statement such as:
document.writeln( myNode.prettyPrint() );
•returned object is null Many methods return an object. For example, the
DOMNode.appendChild() returns the child node. On failure, the return
value is null. You can compare the return value to null to check for the
success of a method.
•Check that the document parses correctly If the XML document is not
well-formed, the call to toDOMDocument returns null. You can use
site.GetErrorInfo() to provide information on where the document
is incorrect. The following code fragment illustrates how to do this.
domDoc = toDOMDocument( xmlString );
if( domDoc == null ) {
document.writeln( site.GetErrorInfo() );
}
else {
...
}

181
Document Object Model examples

Document Object Model examples


This section contains two examples illustrating XML applications of Dynamo.
Subsequent sections describe the techniques employed in these examples.

Converting XML to HTML for sending to a browser


This section provides an overview of how applications can use the DOM
interface. It uses the DOMNode object to process an XML document.
The document The document below is shown with white space for readability. To reproduce
this example, delete the white space between the tags.
<?xml version=’1.0’ ?>
<Customer>
<FName>Jessie</FName>
<LName>Gagliardo</LName>
<Address>
<Street>2800 Park Avenue</Street>
<City>Hull</City>
<Region Type="Province">PQ</Region>
</Address>
</Customer>
The script This script converts the customer information to HTML and sends it to a Web
browser. The line numbers are added in comments, and are referenced in the
description following the script:
<!--SCRIPT Customer.ssc //1
domDoc = toDOMDocument(document.value.xmlData );
//2
if( domDoc == null ) { //3
document.writeln( site.GetErrorInfo() );
//4
} else { //5
domElement = domDoc.documentElement; // Customer
node //6
document.writeln( "<P>Name: ");
//7
domElement = domElement.firstChild;
//8
document.writeln( domElement.firstChild.nodeValue
); //9
domElement = domElement.nextSibling;
//10
document.writeln( " " +

182
CHAPTER 8 Working with XML Documents

domElement.firstChild.nodeValue );//11
domElement = domElement.nextSibling;
//12
document.writeln( "<P>Address: ");
//13
for( i = 0; i < domElement.childNodes.length ; i ++
){ //14
document.writeln(
domElement.childNodes.item(i).firstChild.nodeValue
); //15
} //16
} //17
-->
The output is as follows:
<P>Name:
Jessie
Gagliardo
<P>Address:
2800 Park Avenue
Hull
PQ
How the script works The script works as follows:
•Line 2 An XML document is received by Dynamo, as a document value
named xmlData. It is parsed to provide a DOM document object.
You can create document objects from several sources, including files on
disk, documents stored in a Dynamo Web site, query results, or arguments
passed in from a URL.
For more information, see “Creating the DOMDocument object” on page
187.
•Line 6 The node corresponding to the top element of the DOM document
is accessed. Each XML document has a single top-level element that
includes all other content: in this case, it is the Customer element.
•Lines 8 and 9 The firstChild of the Customer element is FName. The
firstChild of FName is a text node. The nodeValue of the text node is
the string Jessie.
For information on navigating the document tree, see “Using nodes to
work with XML documents” on page 179.
•Lines 10 and 11 The nextSibling of FName is LName. Line 12 writes
out the string in the text node of LName (Gagliardo).

183
Document Object Model examples

•Lines 14 to 16 These lines loop over the members of the childNodes


list of the Address element, writing out the text values of each.
It is actually more efficient to use firstChild followed by
nextSibling methods to loop over the children of a node than to loop
over the members of the childNodes list.

Inserting data from XML into a database


XML applications can insert data from an XML document into a database. For
example, you may design a Web page to contain a form that, when a button is
clicked, constructs an XML document (perhaps using JavaScript) and posts it
to PowerDynamo.
This section describes how to construct an INSERT statement from an XML
document.
The following XML document (which has had white space added for
readability) contains information for a new product, to be added to the
database:
<?xml version=’1.0’?>
<Products>
<Product>
<Name>Cricket Cap</Name>
<Description>Cotton Cap</Description>
<Size>One size fits all</Size>
<Color>Blue</Color>
<Quantity>30</Quantity>
<Unit_Price>10</Unit_Price>
</Product>
</Products>
The following DynaScript code takes a DOMDocument that has been
constructed from this, and creates an INSERT statement from it:
function SQLVar( prod, elemname ){
//1
return prod.getElementsByTagName( elemname
).item(0).firstChild.nodeValue;//2
}
//3
function InsertProduct(){
//4
var i, prod, name, desc, size, color;
//5

184
CHAPTER 8 Working with XML Documents

var quantity, unit_price, id,


//6
var docElem, domDoc, xmlDoc;
//7
domDoc = toDOMDocument(document.value.xmlData);
//8
docElem = domDoc.documentElement ;
//9
sql = connection.CreateQuery();
//10
id=1000; // Not a recommended way of generating ID
numbers //11
// loop over individual product elements -- only one
in this example //12
for( i = 0 ; i < docElem.childNodes.length ; i ++ ){
//13
id += 1;
//14
prod = docElem.childNodes.item(i);
//15
name = SQLVar( prod , "Name" );
//16
desc = SQLVar( prod , "Description" );
//17
size = SQLVar( prod , "Size" );
//18
color = SQLVar( prod , "Color" );
//19
quantity = SQLVar( prod , "Quantity" );
//20
unit_price = SQLVar( prod , "Unit_Price" );
//21
sql.SetSQL( "INSERT INTO DBA.Product "
//22
+ "VALUES ( "
+ id + ", ’" + name + "’, ’" + desc + "’, ’"
+ size + "’, ’" + color + "’, " + quantity + ", "
+ unit_price + " )" );
if( !sql.Execute() ){
//23
document.writeln( sql.GetErrorInfo() );
//24
}
//25
}
//26

185
Document Object Model examples

}
//27
Notes •Lines 1 to 3 The SQLVar function gets the value of the named element.
For information on the getElementsByTagName method, see “Using the
DOMElement object to work with elements” on page 190.
•Lines 8 to 9 These lines parse the document and locate the document
element.
For information on the toDOMDocument function, see “Creating the
DOMDocument object” on page 187.
•Lines 15 to 21 These lines call SQLVar to construct variables containing
the quantities that need to be inserted in the database.
•Line 22 The INSERT statement is constructed and executed.
•Lines 23 to 25 These lines check that the INSERT was carried out
successfully.

186
CHAPTER 8 Working with XML Documents

Creating the DOMDocument object


When you process an XML document, the first step is to create a
DOMDocument object. You do this using the toDOMDocument function, which
takes a string as an argument and returns a DOMDocument object.
The following lines create a DOMDocument object from an XML document
named mydoc.xml stored in a Web site:
xmlDoc = site.GetDocument( "mydoc.xml" );
domDoc = toDOMDocument( xmlDoc.source );
The first line creates a document object, the second line creates a
DOMDocument object, taking a string as an argument.
You can create DOMDocuments from several other sources. For information
on generating XML documents, see “Creating XML documents” on page 170.
You can also create an empty DOMDocument object and add elements to it
using the DOM interface. For more information, see “Using the DOM interface
to create and edit XML documents” on page 200.
Parser does not The toDOMDocument function parses the XML document and builds a
validate representation of the entire document tree in memory. The XML parser is not
a validating parser: that is, it does not confirm that the structure of the
document conforms to any DTD referenced in the document.
On the other hand, if the document is not well formed, then it cannot be built
into a proper tree structure, and the function call fails, returning null. You can
call site.GetErrorInfo to display specific error information.
In this example, the error is handled by writing a message and stopping the
application:
domDoc = toDOMDocument( xmlDoc.source );
if( domDoc == null ){
document.writeln( site.GetErrorInfo() );
exit;
}
Performance tip Parsing large documents with toDOMDocument can be an expensive task.
Consider designing your site so that it is carried out as infrequently as possible.
You can avoid unnecessary parsing of the document by attaching the
DOMDocument object to the session object, using a script such as:
function getSessionDocument(){
if ( !exists(session.domDoc) ) {
xmlDoc = site.GetDocument( "xmldoc.xml" );

187
Creating the DOMDocument object

session.domDoc = toDOMDocument( xmlDoc.source );


}
return session.domDoc
}
If you call this function whenever you need the DOM representation of the
XML document, it is regenerated when necessary, but not if it already exists in
the session object.

188
CHAPTER 8 Working with XML Documents

Working with elements


Many applications that process XML documents need to locate or manipulate
various elements of the document by using the tree structure.
The DOM interface provides two ways of working with elements:
•DOMNode object You can use the DOMNode object and test to see if the
node you are addressing is an element node.
•DOMElement object You can explicitly use the DOMElement object,
which provides some additional properties and methods that reflect the
features of XML elements.

Using the DOMNode object to work with elements


The element nodes of a document have all the properties (parents, siblings,
children) that you need to navigate a document. These nodes provide one way
of accessing the properties of elements.
Example Here is a script that writes out the names of all elements in a document:
function displayElementName( domElement ){ //1
var i; //2
var domChild; //3
if( domElement.nodeType == 1){ //4
document.writeln( domElement.nodeName ); //5
} //6
for( i=0; i < domElement.childNodes.length ; i++ ){//7
domChild = domElement.childNodes.item(i); //8
displayElementName( domChild ); //9
} //10
} //11
displayElementName( domDoc.documentElement ); //12
Notes •Lines 2 and 3 When calling a function recursively, as in this example,
you must declare variables inside the function to ensure a new copy is
made each time.
•Lines 4 to 6 Only write out the names of nodes that are elements
(nodeType = 1).
•Lines 7 to 10 Loop over all the child nodes of the current node, calling
displayElementName on each.
•Line 12 Invoke displayElementName with the document element of a
DOM document. The function must be defined before it is used.

189
Working with elements

Characteristics of Nodes that correspond to elements have the following characteristics:


nodes that represent
elements •nodeType The nodeType of a node that is an element is 1.
•nodeName This is the tag name of the element.
•nodeValue The nodeValue of a node that is an element is null.
•attributes The attributes of an element. These are made available as a
DOMNamedNodeMap object.
For more information about attributes, see “Working with attributes” on
page 191.

Using the DOMElement object to work with elements


The DOMElement object corresponds to an element of an XML document.
DOMElement inherits all the properties and methods from the DOMNode object.
In addition, it supports some properties and methods specific to elements.
Getting elements by You can retrieve and process all elements with a given name from a document
tag name as follows:
elemlist = domObj.getElementsByTagName(tag_name);
for(i=0; i < elemlist.length ; i++){
document.writeln( elemlist.item(i).tagName);
}
where domObj is a DOMDocument object or a DOMElement object, and
tag_name is the case-sensitive name of the tag you want to retrieve. If domObj
is a DOMElement object, only those elements contained in domObj are
retrieved (descendants of domObj).
This is usually more effective than traversing the entire document tree looking
for a particular element.
For a list of DOMElement properties and methods, see “The DOMElement
object” in PowerDynamo Reference.

190
CHAPTER 8 Working with XML Documents

Working with attributes


You can access the attributes of an element in the following ways:
•DOMNode interface From the element node’s attributes property.
•Object interface From the getAttribute or getAttributeNode
methods of the DOMElement object.

Using the DOMNode object to work with attributes


The following example writes out the names and values of the attributes of an
element.
function displayAttributes( node ){ //1
var i; //2
var attnode; //3
if( node.nodeType == 1){ //4
for( j=0; j < node.attributes.length; j++){ //5
attnode = node.attributes.item(j) //6
document.writeln( attnode.nodeName ); //7
document.writeln( attnode.firstChild.nodeValue );
}
}
}
If the supplied element has a start tag of this form:
<Region Type="Province">
Then the output is:
Type
Province
In this example, the attribute node has a child that is a text object. The
nodeValue of this text object can also be used to retrieve the attribute value.
Attribute nodes • Attributes do not occupy a place in the document tree. A DOMNode object
that represents an attribute has no parents and no siblings. Any attempt to
access these properties returns null.
• You can access an attribute node of an XML element using the
attributes property of the element node. This property returns a
DOMNamedNodeMap object. You can access the individual attributes either
by index (as in the sample code above) or by name. The following
statement sets attnode to the Type attribute of the element:

191
Working with attributes

attnode = node.attributes.getNamedItem( "Type" );

Using the DOMAttribute object to work with attributes


The DOMAttribute object corresponds to an attribute of an XML element.
The DOMAttribute object inherits all the properties and methods from the
DOMNode object. In addition, it supports some properties and methods specific
to attributes.
You can access the attributes of an element in the following ways:
•Get the value of an attribute with a given name The following sample
code takes a list of elements as input (elemList), and lists the value of all
the Type attributes:
for( i = 0 ; i < elemList.length ; i ++ ){
elem = elemList.item(i);
document.writeln( elem.getAttribute( "Type" ) );
}
•Get the DOMAttribute object for an attribute The following sample
code lists the value of each Type attribute for a list of elements:
for( i = 0 ; i < elemList.length ; i ++ ){
elem = elemList.item(i);
att = elem.getAttributeNode( "Type" );
document.writeln( att.name + " = " + att.value );
}
The DOMAttribute object also has methods and properties that you can use to
alter XML documents. For more information, see “Using the DOM interface to
create and edit XML documents” on page 200.

192
CHAPTER 8 Working with XML Documents

Working with text


This section includes a description of how to access and work with the text that
is contained in XML documents.
Text occurs in the following places:
•Inside elements This is where most text in XML documents resides:
<Street>2800 Park Avenue</Street>
•As attribute values The following is an example:
<Region Type="Province">
Simple cases When an element or attribute has no child nodes apart from a single text node,
you can access the text content of an element or attribute using the nodeValue
of the element’s child.
If an element contains no other elements or other non-text pieces, the only child
of the element is a text node. The nodeValue of this text node is a string. The
following example writes out the text of an element:
document.writeln( elemnode.firstChild.nodeValue )
For an attribute node, the following example writes out the value of the node:
document.writeln( attnode.nodeValue )
More complicated Some elements contain several text nodes among their children. Consider the
cases following cases:
•Text mixed with entities The following Names element has three child
nodes:
<Names>Sammy &amp; Rosie</Names>
The first child is a text node with value "Sammy ". The second child is an entity
node representing the ampersand character. The third child is a text node with
value " Rosie".
•Text mixed with elements The following Warning element has three
child nodes:
<Warning>Do <emphasis>not</emphasis> walk on the
grass</Warning>
The first child is a text node with value "Do ". The second is an element
node. The third child is a text node with value " walk on the grass".
For more information, see “Working with entities” on page 196.

193
Working with text

Obtaining all the text inside an element


If you want to obtain all the text inside an element, including its children, you
can use the getElementsByTagName method of the root element, with the
special value "*", which means all tags. The following function demonstrates
this technique.
function listTextOfAllElements(rootelement){
var elemlist, elem, child, i, j ;
elemlist = rootelement.getElementsByTagName( "*" );
for( i = 0 ; i < elemlist.length ; i ++ ){
elem = elemlist.item(i);
for( j = 0 ; j < elem.childNodes.length ; j ++ ){
child = elem.childNodes.item(j);
if( child.nodeType == 3) { // 3 is a text node
document.writeln( child.nodeValue );
}
}
}
}

Working with CDATA sections


CDATA sections provide a way of including blocks of text in XML documents
even if the text contains characters that would otherwise be recognized as
markup. CDATA sections start with <![CDATA. All characters inside a CDATA
section, including angle brackets and ampersands, are seen as text data until the
marker for the end of the section, which is ]]>, is reached.
Here are some examples of CDATA sections:
• Text containing an ampersand can be included:
<![CDATA [Jane & John Doe]]>
In the above example, the ampersand is treated as a text rather than as
starting an entity reference.
• Text containing tags can be included:
<![CDATA [<title>Working with CDATA
sections</title>]]>
In the above example, <title> and </title> are treated as text rather than as
tags.

194
CHAPTER 8 Working with XML Documents

The text content of a CDATA section is the nodeValue of the object. For
example, the following fragment writes out the content of a node if it is a
CDATA section node:
if (child.nodeType == 4 ){ //CData Section
document.writeln( child.nodeValue ) ;
}

Escaping text with xmlEscape


Dynamo includes the xmlEscape function to assist with preparing text for use
in XML documents. The prototype is as follows:
string xmlEscape( input_string [, use_CDATA ] )
This function encodes ‘&’, ‘<‘, and ‘>’ characters in a string and returns the
encoded string. The input_string parameter is the string to be encoded. The
optional use_CDATA parameter dictates whether a CDATA section will be
used to encode the characters. If not provided, this parameter defaults to false.
If use_CDATA is false, then characters are encoded using the 'ampersand'
method of encoding.
Examples The following script:
document.writeln( xmlEscape( "<MyTag>Hello!</MyTag>"
));
produces the following output
&lt;MyTag&gt;Hello!&lt;/MyTag&gt;
The following script:
document.writeln( xmlEscape( "Calvin & Hobbs", true ) );
produces the following output:
<![CDATA[Calvin & Hobbs]]>

195
Working with entities

Working with entities


In an XML document, an entity is a holder for some information. To use
entities, you must first declare them, and then reference them. You declare
entities in the DTD. The entities section of the XML document may be held
separately or placed at the beginning of the document. Here is a simple DTD
that specifies the two entities PQ and Logo.
<?xml version=’1.0’ encoding=’ISO-8859-1’?>
<!DOCTYPE Customers [
<!ENTITY PQ "Province of Quebec">
<!ENTITY Logo SYSTEM "nautilus.gif" NDATA GIF>
]>
<Customers><Customer><FName>Jess...
There are two kinds of entity declared here: PQ is a simple text replacement,
and Logo is a reference to a graphic, held in a GIF file.
Entity types The following kinds of entity can occur in XML documents:
•Internal entities These entities hold replacement text that is defined in an
entity declaration.
The following is an internal entity declaration:
<!ENTITY PQ "Province of Quebec">
You can reference this entity as follows in the content of an element:
<Region type="Province">&PQ;</Region>
XML supports a small set of predefined internal entities, which do not
need to be defined. This set includes:
•amp The ampersand character (&)
•lt The left angle bracket character, or less-than sign (<)
•gt The right angle bracket character, or greater-than sign (>)
•apos The apostrophe character (’)
•quot The quotation mark character (")
•External entities that can be parsed These allow you to incorporate
XML content from other files. You declare them as follows:
<!ENTITY chap1 SYSTEM "chapter1.xml">
<!ENTITY chap2 SYSTEM "chapter2.xml">
The string chapter1.xml is called the system identifier of the entity. You
can reference this entity from within the content of an element as follows:

196
CHAPTER 8 Working with XML Documents

<BOOK>
&chap1;
&chap2;
</BOOK>
•External entities that cannot be parsed These allow you to incorporate
material that is not XML content, such as images, into an XML document.
You declare them as follows:
<!ENTITY Logo SYSTEM "emblem.gif" NDATA gif>
NDATA states that the entity is not XML data and should not be parsed.
To include an external entity of this kind in a document, you must
reference it in an attribute of an element:
<GRAPHIC entity="Logo">

Working with internal entities


You can include references to internal entities in the text. For example, the
following element includes a predefined internal entity:
<Names>Sammy &amp; Rosie</Names>
The Names element has three children, the first being a text node, the second
being an entity reference node, and the third being another text node. The
firstChild of the entity reference node is a text node, and the nodeValue
of this text object is the replacement text.
The entity definitions of predefined entities are also available from the
entities property of the DOMDocument object’s doctype property.

Working with external entities


The following is a complete XML document that defines and references an
external entity:
<?xml version=’1.0’ encoding=’ISO-8859-1’?>
<!DOCTYPE DOC [
<!NOTATION gif SYSTEM "GIF">
<!ENTITY Logo SYSTEM "nautilus.gif" NDATA gif>
]><DOC><GRAPHIC ENTITY="Logo"/></DOC>

197
Working with entities

The following DynaScript function takes the DOMDocument object as its


argument, and displays the nautilus.gif file that holds the Logo image:
function displayGraphic( domDoc){
dtd = domDoc.doctype;
entlist = dtd.entities;

elemlist = domDoc.getElementsByTagName( "GRAPHIC" );


elem = elemlist.item(0);
gif = elem.getAttribute( "ENTITY" );
ent = entlist.item( gif );
sysid = ent.systemId;
document.writeln( ’<img src="’ + sysid + ’>’);
}
Notes • To access the entity declarations, you use the DOMDocumentType object,
which is accessible as the doctype property of the DOMDocument object.
The entities property of DOMDocumentType returns a list of entities.
• The application must know which attributes are entities, as the DOM
interface does not makes this information available. Here, the ENTITY
attribute of the GRAPHIC element is an entity name.
• The systemID property of the DOMEntity object returns the path to the
file.
• If you use an entity to refer to another document, you need to pay attention
to the path to that document. In particular, the path may differ depending
on whether the reference is resolved on the client or by Dynamo.
To resolve entities on the server you must use the full path.
Although Dynamo recognizes the home directory (~) in a path, you should
not use ~ in an img tag to a browser, as the browser does not recognize the
home directory.
Conversely, although browsers recognize standard URLs of the form
http://address, you should not use these if you expect Dynamo itself to
obtain information from the address, as Dynamo is not a Web client.

198
CHAPTER 8 Working with XML Documents

Working with other XML objects


In addition to elements, attributes, entities, and text, there are several other
items that can occur in an XML document. These include the following:
•Processing instructions These contain instructions for applications.
The first line of any XML document is a processing instruction with a
name of xml. For example:
<?xml version=’1.0’?>
For information on handling processing instructions, see “The
DOMProcessingInstruction object” in PowerDynamo Reference.
•Comments A comment embedded in an XML document contains text
that is not part of the document’s character data. For example:
<!-- This is a comment -->
For information on handling comments, see “The DOMComment object”
in PowerDynamo Reference.
•Notations A notation is a declaration for the supported types of external
entities that are not parsed. For example:
<!NOTATION IMAGE SYSTEM "GIF">
For information on handling notations, see “The DOMNotation object” in
PowerDynamo Reference.
•Document type information The DTD is held in the DOMDocumentType
object. This object has properties that hold the name of the DTD, as well
as listings of the entities and notations declared within the DTD.
The Document Object Model, Level 1, does not specify access to any other
information in the DTD.
For information on handling notations, see “The DOMDocumentType
object” in PowerDynamo Reference.

199
Using the DOM interface to create and edit XML documents

Using the DOM interface to create and edit XML


documents
This section describes how to use the DOM interface to create and edit XML
documents.
You can output XML data from a database using standard string functions. The
DOM interface lets you construct or modify the DOM representation of an
XML document. To do anything with this document, you must process it using
the DOM interfaces described in the other sections of this chapter.

Creating a DOM document object


The DOMDocument object has a constructor that allows you to create an
empty DOM document.

❖ To create a DOMDocument object:


• Use the following statement:
domDoc = new DOMDocument();
Standards The DOM Level 1 specification does not provide a standard method for
creating a DOM document object. The DOMDocument() constructor is an
extension to the standard.

Adding objects to DOM documents


To add elements to a DOM document, create the elements or other object you
want to add, and then insert them in the proper place in the tree.
Creating objects You can create an element or other object using methods of the DOMDocument
object. These methods are:
• createAttribute
• createCDATASection
• createComment
• createDocumentFragment
• createElement
• createEntityReference

200
CHAPTER 8 Working with XML Documents

• createProcessingInstruction
• createTextNode
The following fragment creates an FName element (elem), and a text node
(tnode) with content “Ann T. Dote” in a DOMDocument object named
domDoc:
elem = domDoc.createElement( "FName" );
tnode = domDoc.createTextNode( "Ann T. Dote" );
These nodes currently have no place in the document, and the FName element
has no content.
Adding objects to You can add objects to a node using one of these methods of the DOMNode
documents object:
• The appendChild method
• The insertBefore method
• The replaceChild method
This fragment expands on the previous one to add the elements into a
document. The FName element is a child of a node named cust, and the text
node is a child of the FName element:
elem = domDoc.createElement( "FName" );
text = domDoc.createTextNode("Ann T. Dote" );
el = cust.appendChild( elem );
el.appendChild( text );
For more information, see “insertBefore method” and “replaceChild method”
in PowerDynamo Reference.

Removing and replacing objects in DOM documents


The DOM interface provides a set of methods for deleting and replacing
objects in the document tree. There is not a method on a DOMNode object to
delete the object itself. Instead, you delete a node by a method on its parent.
The removeChild method deletes a child node, and the replaceChild
method replaces a child node with a new node.
For more information, see “removeChild method” in PowerDynamo
Reference, and “replaceChild method” in PowerDynamo Reference.

201
Using the DOM interface to create and edit XML documents

Removing and For attributes and other unordered objects (not elements) you can also use
replacing attributes methods defined on the collection of attributes. This collection, which is
unordered, is represented by a DOMNamedNodeList object, and you can use
the removeNamedItem method and the setNamedItem method to carry out
the operations.
For more information, see “removeNamedItem method” and “setNamedItem
method” in PowerDynamo Reference.

202
CH A PTE R 9 PowerDynamo Mail Support

About this chapter This chapter looks at how to send, receive, monitor and edit mail from a
PowerDynamo Web site.
For reference information on the PowerDynamo mail objects see
“DynaScript Predefined Objects” in PowerDynamo Reference.
Contents
Topic Page
About PowerDynamo’s mail support 204
Sending mail 206
Receiving mail 208
Deleting mail 210
Forwarding and replying to mail 211
A simple mail application 213

203
About PowerDynamo’s mail support

About PowerDynamo’s mail support


You can use DynaScript to send, receive, and monitor e-mail from
PowerDynamo. PowerDynamo includes the following predefined objects,
which allow users to send mail through a SMTP mail server or receive mail
through a POP3 mail server:
• the outgoing mail object
• the incoming mail object
• the recipient object
• the attachment object
There is also one Dynamo tag called MAILPIECE that can be used for sending
mail from a Dynamo document.
The PowerDynamo mail objects are extremely flexible and can be made as
simple or as complex as required by the application. For example, you might
want to simply send and receive basic mail pieces or, you might want to create
an application that filters incoming tech support questions and routes them to
the appropriate tech support staff.

Requirements for using PowerDynamo mail objects


The PowerDynamo mail objects fully support the SMTP and POP3 Internet
mail transfer protocols.
To use the PowerDynamo mail objects within your Dynamo scripts you must
have access to an SMTP server to send mail and a POP3 server to receive mail.
Mail sent from a PowerDynamo script does not necessarily have to be read
through a POP3 mail server. Other mail programs such as Lotus Notes and
Exchange may be used to read mail that has been sent from a Dynamo script.
Figure 9-1: SMTP and POP3 servers

204
CHAPTER 9 PowerDynamo Mail Support

205
Sending mail

Sending mail
To send mail with PowerDynamo use the outgoing mail piece object. The
outgoing mail piece object has many different methods and properties to help
manipulate the way you want your outgoing mail piece to perform.
Some of the options that may be useful when sending mail through
PowerDynamo are as follows:
• Attachments You can send attachments such as files and documents
along with a mail piece. The attachment object allows the recipients of the
mail piece to manipulate the attachment as required.
• Error checking Use the GetErrorCode and GetErrorInfo methods to
monitor the status of a mail piece that is being sent.
• Multiple addresses You can send a single mail piece to many
people.
• Sender property You can specify a sender property. The sender
property represents the person that sent the mail piece. The from property
represents the person from whom the mail piece originated. For example,
if an assistant was sending a mail piece for their supervisor, the assistant's
name would be represented by the sender property while the supervisor's
name would be represented by the from property.

To send a mail piece


To send a mail piece from Dynamo you need:
• An SMTP host name
• The address of the person you are sending the mail to
• The address from which the mail piece is being sent

❖ To create and send a mail piece from within a Dynamo script:


1 Specify an SMTP host in the Default General Setting folder of Sybase
Central.
2 Create an empty Dynamo script within Sybase Central.
3 Open the script for editing.
4 Enter:
<!--SCRIPT

206
CHAPTER 9 PowerDynamo Mail Support

mp = new MailPiece();
mp.from = "your@address.com";
mp.AddRecipient( "recipient@address.com" );
mp.subject = "My first mail piece";
mp.body = "This mail piece was sent from a Dynamo
script.";
mp.Send();
-->
This code creates a mail piece called mp. Properties and methods are used
to define the sender, recipient, subject, and actual content of the mail piece.
The Send method actually sends the mail piece.
5 Replace your@address.com with your own address.
6 Replace recipient@address.com with the address of the recipient.
7 Save the script.
8 Execute the script.
9 To verify that the mail piece was sent, replace the line:
mp.Send();
with:
if( !mp.Send() ) {
document.writeln( mp.GetErrorCode() );
document.writeln( mp.GetErrorInfo() );
}
For additional information, see “The mail piece object (outgoing)” in
PowerDynamo Reference.

207
Receiving mail

Receiving mail
You can receive mail through Dynamo using a POP3 server, the DynaScript
mail list, and incoming mail piece objects.

To retrieve mail from PowerDynamo


To retrieve mail from PowerDynamo you need:
• The name of the POP3 server
• A user ID and password to connect to the POP3 server
The most efficient way to retrieve mail is to generate a list of the mail pieces
that are waiting at the POP3 server, then select the mail pieces you want to
download. Generally this will be done all in one script.

❖ To generate and retrieve a mail list from a Dynamo script


1 Create an empty Dynamo script within Sybase Central.
2 Open the script for editing.
3 Enter this code, which creates a mail list object and a connection to the
POP3 mail server. Replace mail.sybase.com with the name of your POP3
server:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"secret", "elmo@mail.sybase.com");
document.WriteLn(mlist);
-->
4 You may request all your mail or you may select individual pieces of mail
based on size or subject matter.
To retrieve all your mail from a Dynamo mail list, modify the code so that
it looks like this:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"secret", "elmo@mail.sybase.com");
num = mlist.count
document.WriteLn("There are " + num + " messages
in the mail box");
for (i in mlist) {
inPiece=mlist[i];
if (inPiece.subject == "Bug Report") {

208
CHAPTER 9 PowerDynamo Mail Support

inPiece.Retrieve();
document.WriteLn( "body: " + inPiece.body );
document.WriteLn( "sender: " +
inPiece.sender );
}
}
mlist.Disconnect();
-->
This script checks each mail piece to see if the subject line is “Bug
Report.” If it is, the contents of the mail piece and the sender display.
5 Save the script.
6 Execute the script.

209
Deleting mail

Deleting mail
You can use either the Delete method of the Retrieve method to delete mail
objects.
The Delete method allows you to delete a specific mail piece from the server,
while the Retrieve method marks a mail piece for deletion as soon as it has been
retrieved from the server. In either case the deletion occurs when you
disconnect from the POP3 server.
This example retrieves all mail pieces from the mail server and marks them for
deletion.
<!--SCRIPT
mlist = new MailList ("mailsrc.sybase.com", "dynamo7",
"dynamo", "dynamo7@mailsrc.sybase.com");
num = mlist.count
document.WriteLn("There are " + num + " messages in the
mail box");
for (i in mlist) {
inPiece=mlist[i];
inPiece.Retrieve(true);
document.WriteLn( "body: " + inPiece.body );
document.WriteLn( "sender: " + inPiece.sender );
}
mlist.Disconnect();
-->

210
CHAPTER 9 PowerDynamo Mail Support

Forwarding and replying to mail


You can forward, reply to, or redirect incoming mail in the same way as you
would with most other mail applications.

Forwarding mail
You can either include your own message along with the forwarded mail piece
or you may forward a mail piece as it is with no additional text.
Select the mail piece you want to forward. For example:
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistitem = mlist[0];
mlistitem.Retrieve();
Specify that you want to forward the mail and the address to where you want
to forward it. For example:
forwardmp= mlistitem.Forward("sam@sybase.com")
The body of the original mail piece is now held in forwardmp.body. To add
your own text to the mail piece you would do something like:
forwardmp.body = ( "Please review this mail piece " +
forwardmp.body );
The full script looks similar to the following:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistitem = mlist[0];
mlistitem.Retrieve();
forwardmp= mlistitem.Forward("sam@sybase.com")
document.writeln( forwardmp.GetErrorCode() );
document.writeln( forwardmp.GetErrorInfo() );
document.writeln(forwardmp.body);
forwardmp.body = ( "Please review this mail piece " +
forwardmp.body );
forwardmp.Send();
-->

211
Forwarding and replying to mail

Replying to mail
Select the mail piece you want to reply to. For example:
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistitem = mlist[0];
mlistitem.Retrieve();
Indicate that you want to use the Reply method and the address to which to
respond. For example, to respond to all recipients including the sender and
include the original mail piece in the body of the outgoing mail piece, enter:
replymp=mlistitem.Reply( "all", true );
To add your own text to the mail piece you enter something like:
forwardmp.body = ( "I have read the attached document
and all the changes look correct. " + replymp.body );
The mail piece is then sent in the normal fashion. The full script would look
similar to:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistitem = mlist[8];
mlistitem.Retrieve();
replymp=mlistitem.Reply( "all", true );
forwardmp.body = ( "I have read the attached document
and all the changes look correct. " + replymp.body );
replymp.Send();
-->

212
CHAPTER 9 PowerDynamo Mail Support

A simple mail application


In this section you will create a simple mail application which may be used to
send and view mail for a number of users. To use this simple application, you
must have access to a POP3 mail server and a SMTP host.
Create the following templates in your PowerDynamo Web site:
mailMain.stm
<HTML>
<TITLE>mailMain.stm</TITLE>
<BODY>
<H1>Dynamo 3.5 Mail</H1>
<a href=mailComp.stm>Compose a piece of mail</a><BR>
<a href=mailListMain.stm>List mail in the mail box</a>
</BODY>
</HTML>
Notes • This is the starting page for the application. To access it from a browser
the URL would look something like http://localhost/Site/mailmain.stm.
• Links to other parts of the mail application allow the user to decide
whether to compose a new mail piece or view existing mail pieces.
mailComp.stm <HTML>
<TITLE>mailcomp.stm</TITLE>
<BODY>
<h1>Sending an email
<form action=mailSend.stm>
<table>
<tr><th align=left>From:</th>
<td><input type=input name=from size=30
maxlength=30 value=elmo@sybase.com></td></tr>
<tr><th align=left>To:</th>
<td><input type=input name=to size=30
maxlength=30
value=george@mailsrv.sybase.com></td></tr>
<tr><th align=left>Host:</th>
<td><input type=input name=host size=30
maxlength=40 value=boot.sample.com></td></tr>
<tr><th align=left>Subject:</th>
<td><input type=input name=subject size=50
maxlength=60 value=’testing stuff’></td></tr>
<tr><th align=left>Body:</th>
<td><textarea name=body rows=5 cols=50> Enter
your message here... </textarea></td></tr>
</table>

213
A simple mail application

<input type=submit value=Send>


<input type=submit value=Cancel>

</form>
</BODY>
</HTML>

Notes • This page enables a mail piece to be composed and sent.


• Ensure that a valid host has been specified either in the template you
create, or via Sybase Central.
For more information on setting the host see the “smtpHost property” in
PowerDynamo Reference.
For more information on the outgoing mail, see “The mail piece object
(outgoing)” in PowerDynamo Reference.
mailSend.stm <HTML>
<TITLE>mailsend.stm</TITLE>
<BODY>
<H1>Dynamo 3.5 Mail</H1>
<!--script
var parm = document.value;
if (parm.action="Send") {
var mp = new MailPiece();
mp.subject = parm.subject;
mp.from = parm.from;
mp.body = parm.body;
mp.smtpHost=parm.host;
mp.AddRecipient( parm.to, "to" );
if ( !mp.Send() ) {
document.writeln( mp.GetErrorCode() );
document.writeln( mp.GetErrorInfo() );
} else {
document.writeln("Sent!");
}
}
-->
<a href="mailMain.stm">click here to return to the mail
menu</a>
</BODY>
</HTML>
Notes • This file sends the mail piece and checks for errors.
For more information on error checking, see “The mail piece object
(outgoing)” in PowerDynamo Reference.

214
CHAPTER 9 PowerDynamo Mail Support

mailListMain.stm <HTML>
<TITLE>mailListMain.stm</TITLE>
<BODY>
<H1>Dynamo 3.5 display of mail in the mailbox</H1>
<form action=’mailList.stm’ method=post>
<table>
<tr><th align=left>Mail Server:</th>
<td><input type=text name=mailServer
size=30 value=mailsrv.sybase.com></td></tr>
<tr><th align=left>User Name:</th>
<td><input type=text name=username size=30
value=george></td></tr>
<tr><th align=left>Password:</th>
<td><input type=password name=passwd
size=30 value=dynamo></td></tr>
</table>
<input type=submit name=action value=Logon>
</form>

</BODY>
</HTML>
Notes • This page requests the name of the mail server that is to be used as well as
the user name and password for the mail pieces that are to be viewed.
• Only the mail that has been sent to the user name provided will display.
mailList.stm <HTML>
<TITLE>mailList.stm</TITLE>
<BODY>
<H1>Dynamo 3.5 Mail</H1>
<!--script
var parm = document.value;
var mlist = new MailList (parm.mailServer,
parm.username, parm.passwd,
parm.username+’@’+parm.mailServer, false);

if (mlist.GetErrorCode()>899) {
document.writeln(mlist.GetErrorCode());
document.writeln(mlist.GetErrorInfo());
} else {
var num = mlist.count
document.WriteLn("There are " + num + " messages
in the mail box<br>");
document.writeln("\n&
<table border>\n&

215
A simple mail application

<tr><th>From</th><th>Subject</th><th>Body</th></tr>");

for (i in mlist) {
mlist[i].Retrieve();
document.writeln("\n&
<tr><td>"+mlist[i].from+"</td>\n&
<td>"+mlist[i].subject+"</td>\n&
<td>"+mlist[i].body+"</td></tr>");
}
document.writeln("\n&
</table>");

}
mlist.Disconnect();
-->
<BR>
<a href=mailMain.stm>Return to the main menu</a>
</BODY>
</HTML>

Notes • This page displays all the mail messages that have been sent to the user
(specified in mailListMain.stm).
For information on the incoming mail piece and its methods see “The mail
piece object (incoming)” in PowerDynamo Reference.
Once you have created these files, you can start your mail application by
opening mainMail.stm in a browser.

216
CH A PTE R 1 0 Achieving Optimum Performance
with PowerDynamo

About this chapter This chapter describes how to design a PowerDynamo Web site to ensure
maximum productivity and performance.
Contents
Topic Page
Performance requirements 218
Increasing the performance of your Web site 222
Optimizing your document cache 223
Scheduling your scripts 228
Writing cacheable documents 230
Expensive methods and properties 234
Load balancing 235
Converting an inefficient Web site to an efficient Web site 237
Summary 240

217
Performance requirements

Performance requirements
PowerDynamo includes features that have been specially designed to make the
creation and optimization of high volume Web sites practically effortless.
Dynamo Web sites that are designed without thought to performance or site
specifications generally experience a slow down due to one or all of the
following reasons:
• Slow or excessive processing of scripts
• Exorbitant calls to the database
• Expensive use of connections

Processing of scripts
Web sites that are required to support large volumes of traffic must contain
documents that have been created with the criterion of the Web site in mind.
As a general rule, a Web document should take no longer to execute than the
time between requests to the Web site. For example, if a Web site has an
average of one request every three seconds, each Web document should be
written so that no document takes longer than three seconds to execute from
start to finish.

The ideal script design


This section describes the ideal design where each script is the only request
being processed at any time. In reality, multiple requests will arrive for
processing by the Web site. PowerDynamo's multithreaded architecture allows
for efficient processing of these scripts.

If only one Web document is being executed by PowerDynamo, 100% of


Dynamo's CPU time may be available for the processing of that document.
This results in the shortest possible execution time of a document. When two
or more documents are being processed concurrently, CPU time is shared. The
sharing of CPU time increases the time required to complete the request. If the
average volume of requests is once every two seconds and the average
document takes three seconds to execute, a backlog is created as each
subsequent request takes longer to execute.
Figure 10-1 illustrates how the length of time required to execute a script
increases as the load on the Web server increases.

218
CHAPTER 10 Achieving Optimum Performance with PowerDynamo

Figure 10-1: Relationship between load and processing time

For more information on minimizing the processing time of your scripts, see
“Writing cacheable documents” on page 230 and “Scheduling your scripts” on
page 228.
For more information about running PowerDynamo on a multiple processor
system, see “Load balancing” on page 235.

Minimizing the calls to the database


Yet another cause for performance degradation is the time required to execute
queries against the database. PowerDynamo does not have control over the
time required to issue a query, but it does provide ways to control the number
of times a database is accessed.
Setting an efficient document cache size as well as defining
cachedOutputTimeOut values where appropriate can significantly minimize
the number of calls to a database. Further improvements can be made to the
efficiency of a Web site by scheduling certain documents to execute on a
special time frame.
If you do not optimize scripts and minimize database calls when you create a
high-volume Web site, you may experience the time lag demonstrated in the
first time line in Figure 10-2.

219
Performance requirements

Figure 10-2: Optimizing scripts

For more information about minimizing calls to your database, see


“Optimizing your document cache” on page 223.

Working with Connections to increase performance


The third most common cause of performance degradation is the creation and
use of connections within a Web site. Connections are the link between users
and the information that they request from a Web site. Each time a user makes
a request to a dynamic Web site, connections are created. Creating connections,
while necessary, requires costly processing time.
With minimal effort from the Web author, PowerDynamo is able to optimize
its connections and work with them in such a way that required processing time
for creating connections need not be an issue to the performance of the Web
site.
For more information about working with connections, please see “Working
with connections” on page 60.

220
CHAPTER 10 Achieving Optimum Performance with PowerDynamo

Designing your Web site


When you create a dynamic Web application site, you should plan and design
the site to provide optimum performance. A Web site can work only as fast as
its design allows.
You should consider these factors when designing a dynamic Web site:
• What is the expected volume to be hitting the Web site?
• How often will the data being queried change?
• What can you afford to set your cache size to?
• How essential is the timing of the information being delivered? For
example, does the data need to be updated every minute or is once an hour
sufficient?
Once you have evaluated these factors you can decide how to best optimize
your Web site. For example, if you are creating a dynamic Web site with high
volume throughput, you’d probably want to take these steps:
• Set the proper CachedOutputTimeout value.
• Set a maximum cache size.
• Schedule documents that can be.
• Create the proper type of connection for each query.
• Queries should be as specific as possible to support caching.
The following sections describe in more detail the features that are available to
optimize PowerDynamo to its greatest possible performance.

221
Increasing the performance of your Web site

Increasing the performance of your Web site


There are many factors that determine the speed of a Web site. For high
throughput Web sites that rely on dynamically driven data, it is essential that
Web sites be appropriately streamlined to handle the required volume.
PowerDynamo delivers to users the ability to fine-tune their own Web sites
according to the level of performance they require and the individual
characteristics of their Web site application.
There are four key areas that you can manipulate to increase the performance
of a dynamic Web site:
•Document cache Memory used to hold recently accessed documents so
that subsequent requests of the same document do not require re-retrieving
the document from the database or file system.
•Scheduling The act of scheduling a document to execute at a certain time
on a regular basis. The generated output is stored in a document and
returned to all subsequent requests for the scheduled document. Data is
updated each time a scheduled document is executed.
•Scripts and templates The documents that hold the HTML and database
queries that are used to generate dynamic content.
•Connections PowerDynamo uses two kinds of connections – Dynamo
connections, which are used to extract documents from a database-hosted
Web site, and User connections, which are used to extract data from a
database.

222
CHAPTER 10 Achieving Optimum Performance with PowerDynamo

Optimizing your document cache


To achieve optimum performance, it is crucial that you understand how the
document cache works with your PowerDynamo Web site.
The document cache stores document source and output, for a duration of time,
to minimize unnecessary processing of that document.
Figure 10-3 demonstrates a dynamic PowerDynamo Web document from a
database-hosted Web site.
Figure 10-3: Dynamic PowerDynamo Web document

223
Optimizing your document cache

Once a request for a document has been made, three basic paths are possible.
They are listed here in order of the most to the least efficient:
•Doc source and output held in cache The output is retrieved from the
cache and returned.
•Doc source held in cache The document is executed and the appropriate
information is stored in the cache and the output is returned.
•Doc source not held in cache A connection must be made to the Web site
to retrieve the document source. The document in executed and the
appropriate information is stored in the cache and the output is returned.
The most efficient path is requests for documents that have been written in such
a way as to support cached output.
For more information about writing documents with cacheable output, see
“Writing cacheable documents” on page 230.

Setting a document cache size


All documents that are executed in a PowerDynamo Web site have their source
(and optionally their output) stored in the cache. This ensures that subsequent
requests for the same data can be readily processed without the original
expenditure of processing time to create connections, retrieve the source and
execute the script. You set the storage size in Sybase Central.
The specified cache size determines the number (size) of documents that can
be stored in the cache before the least recently requested documents begin to
be released to make room for more recently requested documents.
The result of caching documents greatly reduces the processing time for
repeated requests for a document. For this reason, the more documents that can
reside in the cache at any one time the better.

Setting the cache size


Do not set your document cache size higher than your machine's available
memory.

❖ To set the document cache size:


1 In Sybase Central, select Utilities | Configuration | Mappings folder.
2 Right-click on the mapping for which you want to set the cache size and
select Properties.

224
CHAPTER 10 Achieving Optimum Performance with PowerDynamo

3 Enter the desired document cache size.


4 Click OK.
5 Restart the Web server for these changes to take effect.

Setting a cachedOutputTimeOut value


CachedOutputTimeOut is a property of the DynaScript document object that
sets the duration of time for which the generated output of a document will be
cached.
Setting a cachedOutputTimeOut value in a document allows the Web author to
store the generated output of the document, after execution, for a
predetermined amount of time. If a second request is then made to the same
script within the allocated amount of time, the output in the cache is returned
without execution of the document being required. This is much more efficient
than the document executing again and possibly repeating the same database
calls that were just made.
The following example sets a cachedOutputTimeOut of three minutes for the
document:
<!--SCRIPT
document.WriteLn( "This is my output that will be cached
for 3 minutes." );
document.cachedOutputTimeOut = 3;
-->
or you can use the Dynamo tag method:
<!--DOCUMENT CACHED_OUTPUT_TIMEOUT = 3 -->
When you set a cachedOutputTimeOut value, ensure that you are not
compromising the validity of your Web site to increase performance. For
example, while storing output for an extended period of time increases the
performance of your Web site, it may also diminish accuracy if you store the
generated output for too long. You should ensure output is regenerated with a
frequency that is appropriate for the Web site data.

225
Optimizing your document cache

The relationship between cache size and cachedOutputTimeOut


values
There are two pieces of information that can be stored in the document cache
for each Web document.
• The document source, which is automatically stored in the document
cache
• The document output, which is stored in the document cache if a
cachedOutputTimeOut value is set in the Web document.
What is the The output of documents without a cachedOutputTimeOut value must still be
difference? generated but the source is available without a call to the database or file
system. Documents that have a cachedOutputTimeOut value specified have
their output stored in the cache as well as the source.
When it is possible, you should create documents with cachedOutputTimeOut
values.
Stored in the
Type of caching cache Conditions
Database-hosted, dynamic Generated output • Data need not be
Web site document with a and source refreshed every time a
cachedOutputTimeOut value request is made.
specified.
Database-hosted, dynamic Source • Data must be refreshed
Web site document with no each time a request is
cachedOutputTimeOut value made
specified.
Database-hosted, dynamic Source (will be • source and data must be
Web site document with an flushed from the refreshed each time a
insufficient document cache cache before being request is made
size. of any use
performance wise)

The size of the cache The size of the document cache may affect how documents with specified
cachedOutputTimeOut values are cached.
If a document has a cachedOutputTimeOut value of 10 minutes, it will remain
in the cache for the full 10 minutes only if there is room for it along with the
subsequent documents that are called during those 10 minutes. When the cache
is full and a new document is requested, the document that was least recently
used is flushed to make room for the new document regardless of how long the
cachedOutputTimeOut value is set to.

226
CHAPTER 10 Achieving Optimum Performance with PowerDynamo

Cache is flushed
The entire document cache is flushed if you modify or create documents
outside a Web server environment; for example, in Sybase Central.

227
Scheduling your scripts

Scheduling your scripts


PowerDynamo allows you to schedule documents to be executed hourly, daily,
weekly, monthly or yearly. Once a scheduled document executes, subsequent
requests of that document can receive the output without requiring processing
time or User connections. Scheduling documents can significantly cut
processing time and the number of database calls.
If a document called sample.stm were scheduled to run once every hour, here’s
what would happen:
1 sample.stm is moved to a new file called sample.sts.
2 If you selected to pregenerate the output, sample.stm holds the generated
output resulting from executing sample.sts. If you did not select to
pregenerate the data, sample.stm remains empty until the first scheduled
execution. In either case, the output is available as a static source file,
which makes a cachedOutputTimeOut value in scheduled documents
unnecessary.
3 An entry is added to the schedule.ssc file in the system directory to let
Dynamo know that a document had been scheduled to run at the specified
time.
4 Subsequent requests for sample.stm returns the data being held in
sample.stm. No execution of the document is required as the data remains
available for subsequent retrievals until the next scheduled execution.
When the next execution occurs, sample.stm is updated with new output.
For data that does not need to be updated more than once an hour, scheduling
documents for slow times or at regular intervals can greatly increase the
performance of a Web site.

❖ To schedule a document:
1 In Sybase Central, locate the script or template to schedule.
2 Right-click on the script or template and select Schedule from the pop-up
menu to start the Schedule wizard.
3 Select the time interval from the drop-down list in the wizard.
4 Enter a time, within the specified time interval, at which the document is
to be generated.
For more information about scheduling documents, see “Scheduling actions”
on page 57.

228
CHAPTER 10 Achieving Optimum Performance with PowerDynamo

Documents that take parameters


Do not schedule or assign a cacheOutputTimeOut value to documents that
require users to enter parameters. This kind of document depends on the
parameters provided by the users; therefore, you cannot cache output.

For information on writing cacheable documents, see “Writing cacheable


documents” on page 230.

Enhancing performance for non-cacheable documents


For documents that would benefit from being scheduled but require user input
you might want to separate the script into multiple documents. Create one main
document with as many side documents as required to meet the main
document's requirements. For example, if a main document allowed the user
the option of choosing between A, B, C, or D, you might create four separate
documents for each one. If the user chose option A, the applicable document
would be called (docA.stm) from the main document. Because the content of
docA.stm does not require user input, you can schedule it or assign a
cachedOutputTimeOut value so data is already available for users that select A
from the main document.
For more information, see “Writing cacheable documents” on page 230.

229
Writing cacheable documents

Writing cacheable documents


One of the most expensive tasks of a Web site is generating the output of a
dynamic document. Caching a document’s output with the
cachedOutputTimeOut property can significantly reduce the time required by
a Web site to respond to a request.
You should write Web documents so as many as possible use cacheable output
and have a cachedOutputTimeOut value assigned.
The following Web documents do not produce cacheable output:
• Documents that require information from the user
• Documents without a cachedOutputTimeOut value
Output that use variables given by the user are a good example of non-
cacheable output. The first script, multiIntro.stm, displays a list of radio buttons
for users to select the price range of products that they would like displayed.
Notes • The documents choice1.stm, choice2.stm and choice3.stm all have
cacheable output since each performs a specific query and requires no
parameters.
• If choice1.stm, choice2.stm and choice3.stm and the output generated by
each remain in the cache a request for mulchoice.stm does not require any
queries against the product table.
<HTML>
<TITLE>multiIntro.stm</TITLE>
<BODY>
<H1>Product List</H1>
<P>The following items are available from the sample
database</P>
<!--SQL
SELECT name
FROM product
-->
<TABLE BORDER>
<TR>
<TH>name</TH>
</TR>
<!--formatting--><TR>
<TD><!--data--></TD>
</TR><!--/formatting-->
</TABLE>
<P>Enter the price range you would like displayed</P>
<FORM METHOD=POST ACTION="mulchoice.stm" MULTIPLE

230
CHAPTER 10 Achieving Optimum Performance with PowerDynamo

SIZE="5">
<OL>
<INPUT TYPE="radio" NAME="choice" value="less10">Less
than $10<BR>
<INPUT TYPE="radio" NAME="choice" value="less20">Less
than $20, more than $10<BR>
<INPUT TYPE="radio" NAME="choice" value="less30">Less
than $30, more than $20<BR>
</OL>
<P><INPUT TYPE="submit" VALUE="Submit List"></P>
<P><INPUT TYPE="RESET" VALUE="Clear Form"></P>
</FORM>
</BODY>
</HTML>
multiIntro.stm calls the following script, which in turn calls one of three scripts
depending on the parameter being passed:
mulchoice.stm <HTML>
<TITLE>Selected Products</TITLE>
<BODY>
<!--SCRIPT

if( document.value.choice == "less10" ){


x=site.Include(’choice1.stm’);
document.WriteLn(x);
}
if( document.value.choice == "less20" ){
x=site.Include(’choice2.stm’);
document.WriteLn(x);
}
if( document.value.choice == "less30" ){
x=site.Include(’choice3.stm’);
document.WriteLn(x);
}
-->
</BODY>
</HTML>
choice1.stm <H1>The following items are under $10.00 in price</H1>
<!--SQL
SELECT product.name, product.color, product.unit_price
FROM DBA.product product
WHERE product.unit_price <= 10.00
-->
<TABLE BORDER>
<TR>
<TH>name</TH>

231
Writing cacheable documents

<TH>color</TH>
<TH>unit_price</TH>
</TR>
<!--formatting--><TR>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>
</TR><!--/formatting-->
</TABLE>
<!—DOCUMENT CACHED_OUTPUT_TIMEOUT = 10 -->
choice2.stm <H1>The following items are $10.00 to $20.00 in
price</H1>
<!--SQL
SELECT product.name, product.color, product.unit_price
FROM DBA.product product
WHERE product.unit_price <= 20.00 and
product.unit_price >= 10.00

-->
<TABLE BORDER>
<TR>
<TH>name</TH>
<TH>color</TH>
<TH>unit_price</TH>
</TR>
<!--formatting--><TR>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>
</TR><!--/formatting-->
</TABLE>
<!—DOCUMENT CACHED_OUTPUT_TIMEOUT = 10 -->
choice3.stm <H1>The following items are $20.00 to $30.00 in
price</H1>
<!--SQL
SELECT product.name, product.color, product.unit_price
FROM DBA.product product
WHERE product.unit_price <= 30.00 and
product.unit_price >= 20.00

-->
<TABLE BORDER>
<TR>
<TH>name</TH>
<TH>color</TH>

232
CHAPTER 10 Achieving Optimum Performance with PowerDynamo

<TH>unit_price</TH>
</TR>
<!--formatting--><TR>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>
</TR><!--/formatting-->
</TABLE>
<!—DOCUMENT CACHED_OUTPUT_TIMEOUT = 10 -->

233
Expensive methods and properties

Expensive methods and properties


DynaScript consists of several objects made up of methods and properties. In
general, methods or properties that cause a connection to a database to be
created or a document to be loaded are expensive to execute. When possible,
you should avoid excessive use of the more expensive methods and properties
in Web sites that hold performance at a premium.
For example, suppose you wanted to display the URL of the parent of your
current document. Using the parent property is an expensive way of doing this.
<!--SCRIPT
document.WriteLn( document.parent.location );
-->
document.parent may require that the parent document be loaded from the
database or file system. This may in turn, bump a document out of the
document cache if the cache is full. A more resourceful way of obtaining the
same information is to use document.location with the substring method to
extract the parent’s URL from the current URL. This is less expensive since the
current document is already loaded.
<!--script
index=document.location.lastIndexOf("/");
document.writeln( document.location.substring( 0,index
) );
-->
The more expensive DynaScript methods and properties include:
• connection.simulateCursors with databases (such as Adaptive Server
Enterprise) that do not support backward movement through result sets.
• query.GetRowCount with databases (such as Adaptive Server Enterprise)
that do not support row counts.
• new Connection constructor this kind of connection does not make use of
the connection pool.

234
CHAPTER 10 Achieving Optimum Performance with PowerDynamo

Load balancing
Load balancing – that is, running PowerDynamo on systems with multiple
processors or across multiple server machines – can be extremely effective for
improving PowerDynamo performance.

Load balancing across processors


The multithreaded design of PowerDynamo makes the use of a multiple
processor system an excellent candidate for improving the performance of a
PowerDynamo Web site.
Each request to a PowerDynamo application is received on an individual thread
(worker threads). Because of this, PowerDynamo requests are evenly spread
among the available processors.
Figure 10-4: Distributing PowerDynamo requests to worker threads

235
Load balancing

Load balancing across servers


Another setup for improving the performance of a Web site by load balancing
is the using PowerDynamo with multiple Web servers. The use of
PowerDynamo with a load balancing mechanism such as the Cisco
LocalDirector enables TCP/IP traffic to be distributed across multiple low-cost
servers.
Figure 10-5: Load balancing Web servers

Further information on the Cisco LocalDirector can be found at the following


URL: http://www.cisco.com/warp/public/751/lodir/index.html.

236
CHAPTER 10 Achieving Optimum Performance with PowerDynamo

Converting an inefficient Web site to an efficient Web


site
Let's say that the high-volume Web site “Hockey” has an average of one
request every two seconds, 24 hours a day. Half the data being accessed
changes at most once a day (statistics, player info etc.) while the other half is
constantly changing (game scores, penalties etc.).
For a Web site such as this, each area of the site must be looked at and
inefficient or unnecessary processing eliminated.
We’ll look at four key areas to ensure that the Web site is operating as
efficiently as possible.
• The Web documents
• The document cache
• The use of scheduling
• The connections
If you use Windows NT, you can use the Performance Monitor to monitor your
Web site's performance. For more information see “Using the Performance
Monitor” on page 70.

Working with documents


Any document that takes longer than two seconds to execute can slow down
the system. Wherever possible, documents must be as specific as possible so
queries can execute as quickly and take no longer than the time between
requests to complete. Ideally, each request should receive 100% CPU time. If
this goal is attained, requests are processed at maximum efficiency.
Another practice that leads to performance degradation is putting multiple
queries in one script. Again, each document should be as specific as possible.
It is far more efficient to have many specific documents than to have fewer
general documents. More specific documents allow you to take advantage of
output caching.
Categorize your By categorizing your documents and setting them up accordingly, much
documents processing time can be eliminated. Categorizing automatically uses caching
and scheduling to enhance performance. You can categorize each document
into one of the following three categories:

237
Converting an inefficient Web site to an efficient Web site

• Data that changes less than once an hour or documents that take a long
time to execute – Schedule these documents to run on a regular basis. This
makes the output readily available for subsequent requests.
• Data that changes once an hour or more often – Assign appropriate
cachedOutputTimeOut values to these documents.
Refer to “Setting a cachedOutputTimeOut value” on page 225 for more
information.
• Data that is constantly changing and must be accurate to the minute and
documents that take parameters – do not set cachedOutputTimeOut values
for these documents or schedule them with the scheduling wizard. Ensure
that the cache size is set high enough to hold their source so those requests
can be processed as quickly as possible.
A cache size should be set that is appropriate for the Web site that will be
utilizing it. It is important that the size of the cache is large enough to hold
all the active documents for at least a brief duration of time. If a cache size
is too small, the stored document output and source may be flushed to
make room for more recent documents before they have a chance to be re-
used before being unloaded.

Working with connections


There are several ways for a Web author to control the way connections work
within a Web site:
• Setting a connection timeout
• Setting maximum and minimum number of connections
• Creating permanent or temporary connections.
Connection timeout The first value you should set to increase performance is the connection
value timeout value. The default connection timeout value of 0 indicates that all
connections remain in the connection pool. Because of the fluctuating traffic
that our Web site receives, this is not what we are looking for. For the best
performance for this Web site, we will set the connection timeout value to 15,
which holds a connection in the pool for 15 minutes after the last time it was
active. The number of connections stored in the connection pool fluctuates
with the Web site volume. This produces better performance than constantly
creating new connections or keeping enough connections in the pool to always
cover the peak times of volume.

238
CHAPTER 10 Achieving Optimum Performance with PowerDynamo

Next, we will look at the maximum and minimum number of User connections
for our Hockey Web site.
User connections At peak times our Web site uses a maximum of 20 User connections. Since this
is manageable without slowing down the overall performance of the Web site,
we can set the maximum number of User connections to 20.

Number of User connections


Caching document output and scheduling documents may greatly reduce the
required number of User connections for your Web site.

During the slow times, there is a minimum of four User connections per
definition being used at any one time. By setting the minimum number of User
connections to four, we ensure that four connections will always remain in each
connection pool ready for use.
Dynamo connections The minimum and maximum connections for User connections applies per
definition. The minimum and maximum number of connections for Dynamo
connections is a total since each Web site has only one Dynamo connection.
For example, suppose there are two User connections defined in the
connections folder of Sybase Central; “sales_db” and “marketing_db”, setting
a minimum number of user connections to four would mean that eight
connections would be held in the connection pool, once created.
Our Hockey Web site requires a slightly smaller number of Dynamo
connections than User connections. The maximum number of Dynamo
connections will be set to fifteen and the minimum number of Dynamo
connections will be set to five.
Use of permanent and Finally, let's look at whether our Web site is using temporary or permanent
temporary connections within its scripts. We need to ensure that temporary User
connections
connections are used only in the appropriate instances. Scripts that use
temporary User connections that are reused in day to day Web use should be
changed to permanent User connections to minimize the processing required to
create a new connection each time.
For more information on connections see “Working with connections” on page
60.

239
Summary

Summary
Ways to increase performance:
Set an appropriate cache size
Set a cachedOutputTimeOut value in the appropriate documents
Create the most efficient type of connections in your documents
Set connection minimum and maximum defaults that are correct for your
Web site
Set an appropriate connection time out value
Schedule all possible documents for minimal processing time
Ensure that your scripts are specific and efficient
Limit the time of processing per document to use the CPU time the most
efficiently

240
CH A PTE R 11 Setting Up a Mobile Intranet

About this chapter This chapter describes how to set up a mobile intranet using
PowerDynamo and SQL Remote replication technology.
PowerDynamo allows you to browse both static and dynamic Web pages,
and enter data using HTML forms. SQL Remote provides message-based
replication technology. Together, these two applications enable you to set
up a mobile intranet that can be used on laptop computers without
requiring constant network connections.
Contents
Topic Page
SQL Remote replication technology 242
Requirements for a mobile intranet 243
Replicating a Web site 244
A Replication Tutorial 246

241
SQL Remote replication technology

SQL Remote replication technology


SQL Remote is an established message-based database replication technology.
When combined with a database-hosted Web site it, enables your intranet
applications and documents to be deployed on laptop computers.
SQL Remote is a transaction-based replication technology that provides:
• Replication between a central consolidated database server and hundreds
or even thousands of occasionally-connected remote databases.
• A loose concurrency among all components of the dispersed database, and
transactional integrity of your database.
• Updates to occur via e-mail or file sharing.
• A publish-and-subscribe model that allows your users to receive only the
data they need.
• The ability to place a full transaction-processing relational database on a
notebook computer.
• Replication of updates that occur at either consolidated or remote
databases.
• Centralized task via Sybase Central.
For complete information about SQL Remote, see the Data Replication with
SQL Remote manual.

Web site replication


The components of a PowerDynamo Web site are HTML templates, other
embedded objects (images, sound, video, and so on), and the data that adds
content to the HTML templates.
Because these objects are all stored in a relational database, such as Adaptive
Server Enterprise or Adaptive Server Anywhere, they can be replicated using
SQL Remote. The databases against which the queries run can also be
replicated, so that all the relevant portions of the Web site, including its
dynamic content, can be replicated to mobile users.
As SQL Remote allows bidirectional replication, changes can be made to the
data from a Web client and can be replicated back to the consolidated server.
You can manage replication of both the Web site and of the data using Sybase
Central.

242
CHAPTER 11 Setting Up a Mobile Intranet

Requirements for a mobile intranet


At the central location for your mobile intranet, you must have:
• PowerDynamo, for developing your Web site.
• A central server for your intranet data. This can be either Sybase Adaptive
Server Anywhere or Sybase Adaptive Server Enterprise.
• A central server for your Web site documents. This can also be either
Adaptive Server Anywhere or Adaptive Server Enterprise.

Note You can use the same server for both data and Web site storage.

• Sybase SQL Remote, to manage replication.


Each remote machine requires:
• TCP/IP networking software. This is required for browser to Web server
communication, even if the machine is never connected to a TCP/IP
network.
• A browser or other Web client software.
• The PowerDynamo Personal Web Server.
• A Sybase Adaptive Server Anywhere standalone database engine, to hold
the local copies of the data and the Web site templates.
• The Sybase SQL Remote Replication Agent, to carry out replication of
data and Web site documents to and from the central site.

Confirm licensing before deployment Before you deploy this software,


you must confirm that you are abiding by your software license agreements.

243
Replicating a Web site

Replicating a Web site


To replicate a Web site you need to make the database tables containing the
Web site information available as a SQL Remote publication, they ensure that
users have subscriptions to both the publication and the relevant data referred
to in the templates.
You can use Sybase Central to replicate Dynamo Web sites.
To replicate a Web site:
• Define the publications and subscriptions for the data to be replicated.
• Configure each remote user's machine for Web site access and SQL
Remote replication.

Setting up publications and subscriptions


Publications and subscriptions define the data that is to be replicated, and the
locations to where replication occurs.

❖ To subscribe users to your Web site:


1 Use Sybase Central to connect to the database where the Web site
templates and scripts are stored. The connection should be an Adaptive
Server Anywhere or Adaptive Server Enterprise connection, rather than a
PowerDynamo connection.
2 Open the SQL Remote folder.
3 Create a publication containing all the Web tables:
• WebConnection
• WebData
• WebDocumentType
• WebSynchronize
• WebTemplate
• WebVersion
4 Create subscriptions for users to this publication.
For a full description of how to create publications and subscriptions, see the
SQL Remote User’s Guide.

244
CHAPTER 11 Setting Up a Mobile Intranet

Setting up remote users


Once you have defined subscriptions in the central database, you can set up
remote machines to handle SQL Remote replication.

❖ To set up remote machines for mobile Intranet use:


1 Install the necessary software onto the remote user’s machine.
2 Ensure the user is subscribed to the database containing the Web site and
the database containing the data accessed by the templates, if it is different.
3 For the remote user, extract an initial copy of the database or both
databases, if they are different.
4 If necessary, set up the required ODBC data source for the database (or
databases) on the remote machine.
5 Configure the Personal Web Server mappings to point to the correct
connection profiles.
6 Ensure that the Web client can access the Intranet site on the local machine
when the Personal Web Server is running.

245
A Replication Tutorial

A Replication Tutorial
This section includes a tutorial in which you set up a simple SQL Remote
replication system between an Adaptive Server Enterprise consolidated
database and a remote Adaptive Server Anywhere database to replicate a
Dynamo Web site along with accompanying data.
In the tutorial you act as the system administrator of a consolidated Enterprise
database, and set up a simple replication system. The replication system
consists of a sales database with two tables, and a Web site.
The consolidated database holds all of the database and Web site, while the
remote database has the entire Web site, all of one table, and some of the rows
in the other table.
The goals of the replication design are to provide each sales representative
with:
• The complete SalesRep table
• Those customers assigned to them
• A Web site for querying and updating their data
The tutorial describes how to meet this goal using SQL Remote and the Sybase
Central management utility.
The tutorial takes you through:
• Creating a consolidated database on your Adaptive Server Enterprise.
• Connecting to the consolidated database through Dynamo to create your
Web site.
• Creating a file-sharing replication system with a single Adaptive Server
Anywhere remote database.
• Replicating the Web site between the two databases.

The database
The tutorial uses a database that contains two tables and a Dynamo Web site
that performs queries on the tables. One table holds information about sales
representatives, and the other about customers.
Database schema The database schema for the tutorial is illustrated in Figure 11-1.

246
CHAPTER 11 Setting Up a Mobile Intranet

Figure 11-1: Database schema

Each sales representative is represented by one row in the SalesRep table, and
each customer is represented by one row in the customer table.
Each customer is assigned to a single Sales representative, and this assignment
is built in to the database as a foreign key from the Customer table to the
SalesRep table. The relationship between the Customer table and the SalesRep
table is many-to-one.
The tables in the The tables are described in more detail as follows:
database
Table Description
SalesRep The SalesRep table has the following columns:
• rep_key An identifier for each sales representative. This is
the primary key.
• name The name of each sales representative.
The SQL statement creating this table is as follows:
CREATE TABLE SalesRep (
rep_key CHAR(5) NOT NULL,
name CHAR(40) NOT NULL,
PRIMARY KEY (rep_key)
)
Customer One row for each customer that does business with the company.
The Customer table includes the following columns:
• cust_key An identifier for each customer. This is the
primary key.
• name The name of each customer.
• rep_key An identifier for the sales representative in a sales
relationship. This is a foreign key to the SalesRep table.
The SQL statement creating this table is as follows:
CREATE TABLE Customer (
cust_key CHAR(12) NOT NULL,
name CHAR(40) NOT NULL,
rep_key CHAR(5) NOT NULL,
FOREIGN KEY ( rep_key )
REFERENCES SalesRep ( rep_key ),
PRIMARY KEY (cust_key)
)

247
A Replication Tutorial

Setting up SQL Remote using Sybase Central


The first part of the tutorial describes how to set up a simple SQL Remote
replication system using Sybase Central. You do not need to enter SQL
statements if you are using Sybase Central to administer SQL Remote.
Create a login name You must have system administrator privileges on an Adaptive server. The
and password tutorial assumes that your login name is sa and that the password is sysadmin.
Create a database Create a 20MB database named hq on your Adaptive Server Enterprise.
1 Connect to the Adaptive Server Enterprise from Sybase Central.
2 Open the Databases folder, and double-click Add database in the right
pane.
3 Enter hq on the first page of the wizard.
4 Follow the instructions in the wizard.
For information on how to create databases and assign space to them, see your
Adaptive Server Enterprise documentation. Install SQL Remote into the hq
database.
Create the Web site Create a Dynamo Web site in the Adaptive Server Enterprise database:
1 Connect to the hq Adaptive Server Enterprise database from Dynamo.
When asked if you would like to create a Web site, select Yes.
2 Enter a name for the Web site and select the check boxes if you would like
to include the Dynamo samples and documentation.
3 The following Dynamo tables are created in your hq database:
• WebConnection
• WebDocumentType
• WebSynchronize
• WebTemplate
• WebData
• WebVersion
4 Later, you will connect to this Web site through a remote database. To be
able to do this, you must modify the connection settings in your
consolidated database so they do not hold specific database information
such as data source names and passwords of the consolidated database.

248
CHAPTER 11 Setting Up a Mobile Intranet

From the Web site’s system folder, open the connect.ssc file. Modify the
<default> connection so there is no information specific to the
consolidated database. Your <default> connection should look like this:
site.LoadConnection( "<default>", "", "", "", "", "",
"" );
Save the file.
Install SQL Remote Install SQL Remote into the HQ database:
1 Open the hq database container in the left pane of Sybase Central.
2 Open the SQL Remote folder, double-click Setup SQL Remote, and
follow the instructions. For the tutorial, install the stable queue in the hq
database.
If your TEMPDB database is too small, you may have to add space to it.
For a full description of how to install SQL Remote, see the Data Replication
with SQL Remote manual.
Create directories for Make a directory for the files created in this tutorial. For example:
messages
mkdir c:\tutorial
Under this directory, create a directory for each of the two users of the
replication system:
mkdir c:\tutorial\hq
mkdir c:\tutorial\field
Add tables The next step is to add two user-defined tables to the consolidated database:
1 Connect to the hq database from Sybase Central.
2 Click the User Tables folder of the hq database.
3 Double-click Add Table, and use the Table Editor to create a table named
SalesRep with the following columns:

Key Column Data Type Size/Prec


Primary key rep_key char 5
name char 40

You do not need to use the Advanced Properties window. By default, the
columns do not allow NULL.
4 Double-click Add Table again, and use the Table Editor to create a table
named Customer with the following columns:

249
A Replication Tutorial

Key Column Data Type Size/Prec


Primary key cust_key char 10
name char 40
rep_key char 5

Again, you do not need to use the Advanced Properties window. By


default, the columns do not allow NULL.
5 Open the Foreign Keys folder of the Customer table container, and double-
click Add Foreign Key. Using the wizard, add a foreign key to the rep_key
column of the SalesRep table. Use the default settings for this foreign key.

Setting up the consolidated database


This section of the tutorial describes how to prepare the consolidated database
of a simple replication system, including:
1 Creating a message type to use for replication.
2 Granting PUBLISH permissions to a user ID to identify the source of
outgoing messages.
3 Granting REMOTE permissions to all user IDs that will receive messages.
4 Creating a publication describing the data to be replicated.
5 Creating subscriptions describing who is to receive the publication.
You should have system administrator authority to carry out these tasks.

Add a SQL Remote message type


All messages sent as part of replication use a message type. A message type
description has two parts:
• A message link supported by SQL Remote.
• An address for this message link, which identifies the source of outgoing
messages.
Adaptive Server Anywhere databases have predefined message types, but you
need to supply an address for the message type you will use. To add an address
to a message type:
1 From Sybase Central, open the hq database container.

250
CHAPTER 11 Setting Up a Mobile Intranet

2 Click the SQL Remote folder on the left panel.


3 Double-click the Message Types folder on the right pane.
4 Double-click the file message type.
5 Enter hq as the publisher address. This provides a return address for
remote users; the directory you created to hold messages for the
consolidated database.
The address (hq) for a file link is a directory relative to the SQLRemote
environment variable or registry entry. Because you have not set this
value, the address is relative to the directory from which the Message
Agent is run. You should run the Message Agent from your tutorial
directory for the addresses to be interpreted properly.
6 Click OK to save the message type.

Create the necessary users and permissions


In this tutorial, the following are required for the SQL Remote installation:
• A publisher user name
• A remote user or subscriber
This section describes how to create each user and assign them the necessary
permissions.
To create the publisher:
1 From Sybase Central, open the container for the hq database.
2 Open the Users folder, and double-click Add User.
3 Create a user named hq_user. Map the login name to an available login
name on your server. The tutorial uses hq_pwd as the password.
4 Make this user the publisher of the hq database. Open the SQL Remote
folder, and double-click Set Publisher. Select hq_user from the list of
users to set it as the publisher.
A database can have only one publisher. You can find out who the publisher is
at any time by opening the SQL Remote folder.
Add a remote user Each remote database is identified in the consolidated database by a user ID
with REMOTE permissions. Whether the remote database is a single-user
database engine or a database server with many users, it needs a single user ID
to represent it to the consolidated database.

251
A Replication Tutorial

In a mobile workgroup setting, remote users may already be users of the


consolidated database. If this is the case, you may not have to add any new
users, but you do need to set existing users as remote users.
When a remote user is added to a database, the message system they use and
their address for that message system are stored along with their database user
ID.
To add a remote user:
1 Double-click the SQL Remote folder in the left pane, then click the
Remote Users folder.
2 If you do not have a login name to use for the remote user, open the Logins
folder directly under the server container, and add a login. The name is
unimportant.
Double-click Add Remote User in the right pane. The New Remote User
wizard is displayed.
3 Create a remote user named field_user. Select FILE as the message type,
then select the corresponding address you are using for this user (such as
field).
As with the publisher address, the address of the remote user (field) is a
directory relative to the SQLRemote environment variable or registry
entry and may not be set appropriately for the tutorial. Run the Message
Agent from your tutorial directory for the addresses to be interpreted
properly.
For information about setting the SQLRemote enviroment variable, see
the Data Replication with SQL Remote manual.
4 Next, ensure that the Send Then Close option is checked.
5 When you have finished all the entries, click Finish to create the remote
user.

Create the publication and subscription


This section describes how to add a publication to a database, and how to add
a subscription to that publication for a user. The publication replicates the full
Dynamo Web site as well as all rows in the table SalesRep and some of the
rows of the Customer table.
The first step is to mark the Web site tables as well as the SalesRep and
Customer tables for SQL Remote replication. Marking a table for SQL
Remote replication enables it to be included in publications.

252
CHAPTER 11 Setting Up a Mobile Intranet

1 Open the SQL Remote folder in the hq database.


2 Open the Remote Tables folder, and double-click Add Remote Table.
3 Select WebConnection from the list of tables. Leave the Conflict
Resolution fields are they are and click Apply to mark the table for SQL
Remote replication. Repeat this step for all the other Web site tables:
• WebDocumentType

• WebSynchronize

• WebTemplate
• WebData

• WebVersion

4 Select SalesRep from the list of tables. You can leave the Conflict
Resolution fields as they are. Click Apply to mark the table for SQL
Remote replication.
5 Select Customer from the list of tables. Again, you can leave the Conflict
Resolution fields as they are. Click OK to mark the table for SQL Remote
replication.
To add a publication:
1 Click the Publications folder in the SQL Remote folder.
2 Double-click Add Publication.
3 On the first page of the wizard, name the publication SalesRepData.
4 On the next page, click Add Table and select SalesRep from the list.
Leave All Columns selected, and press OK to add the table. Do the same
for all the Dynamo Web tables:
• WebConnection

• WebDocumentType

• WebSynchronize

• WebTemplate

• WebData

• WebVersion

253
A Replication Tutorial

Click Add Table again, and select Customer from the list. Again, leave
All Columns selected. Click the Subscribe Restriction tab, and choose to
Subscribe by the column rep_key. Click OK to add the table to the
publication.
5 Complete the wizard to create the publication.
Add a subscription Each user ID that is to receive updates to a publication must have a
subscription to that publication. You need to add a subscription to the
SalesRepData publication for the remote database user field_user:
1 Double-click the Publications folder, which is in the SQL Remote folder,
so that the SalesRepData publication is displayed in the left pane.
2 Click the Remote Users folder so that remote users are displayed in the
right pane.
3 Drag field_user from the right pane onto the SalesRepData publication
in the left pane. In the Create Subscription window, enter rep1 in the With
Value box. This value represents the rep_key value for field_user in the
SalesRep table.
You have now set up the consolidated database.
No data will be exchanged until you start the database extraction utility.

Setting up the remote database


This section of the tutorial describes how to create and configure the remote
database to send and receive messages and participate in a SQL Remote setup.
Here’s what happens when you extract (create) the remote database:
• Creates a publisher (in this case, the field_user user ID) to identify the
source of outgoing messages.
• Creates the hq_user as a user with consolidated permissions.
• Creates the SalesRepData publication and a subscription for the hq_user
user ID.
• Synchronizes the remote database with the consolidated database so that a
current copy of the data is available.
The database extraction utility performs these steps to create a remote database
complete with subscriptions and required user IDs.

254
CHAPTER 11 Setting Up a Mobile Intranet

You need to extract a database from the consolidated database for remote user
field_user:
1 Click the Remote Users folder, which is in the SQL Remote folder.
2 Right-click field_user, and select Extract Database from the pop-up
menu.
3 In the Extraction wizard, enter the user ID and password that you used to
create the tables and users in the database.
4 On the next page, select Start Subscriptions Automatically. Also, check
Create New Remote Database. Adaptive Server Anywhere must be
installed for Create New Remote Database to be available.
5 Create the database as file c:\tutorial\field.db and specify a transaction log
in the same directory.
6 Extract all parts of the schema (the default). Leave the other options at
their default settings, and create the remote database.
You should connect to the field database as DBA and confirm that all the
database objects are created:
1 From Sybase Central, choose Tools | Connect | Sybase Adaptive Server
Anywhere.
2 Enter DBA as the user and SQL as the password. Use upper case, as the
database was created as case sensitive. Select field.db, and Connect.
3 Open the database container, and confirm that the tables and user names
are present.
In a real-life SQL Remote setup, you would load the remote database field onto
the computer using it, together with an Adaptive Server Anywhere engine and
any required client applications. For the tutorial, we leave the database where
it is and use isql to input and replicate data.
The system is now ready for replication.

Replicating data
In this section of the tutorial, we’ll replicate data from the consolidated
database to the remote database, and from the remote to the consolidated
database.

255
A Replication Tutorial

Enter data at the consolidated database


To enter data at the Adaptive Server Enterprise database:
1 Use isql to connect to the Enterprise server:
isql -S server-name -U sa -P sysadmin
2 Verify that you are using the hq database, and enter a series of rows:
use hq
go
insert into SalesRep (rep_key, name)
values (’rep1’, ’Field User’)
go
insert into SalesRep (rep_key, name)
values (’rep2’, ’Another User’)
go
insert into Customer (cust_key, name, rep_key)
values (’cust1’, ’Ocean Sports’, ’rep1’)
go
insert into Customer (cust_key, name, rep_key)
values (’cust2’, ’Sports Plus’, ’rep2’)
go
commit
go
These commands assign the customer Ocean Sports to the sales rep Field
User, and Sports Plus to Another User. You must commit the changes,
as SQL Remote replicates only committed changes.
Next, you send the relevant rows to the remote Adaptive Server Anywhere
database.

Send data from the consolidated database


The Message Agent, which, for the tutorial, is called SSremote, populates the
remote database with the rows you added in the previous section. To send the
rows to the remote database, you must run the Message Agent at the
consolidated database.

❖ To replicate the data from Adaptive Server Enterprise:


1 Enter the following statement (on a single line) at the command line to run
the Message Agent against the consolidated database:
ssremote -c "eng=server-
name;dbn=hq;uid=sa;pwd=sysadmin"

256
CHAPTER 11 Setting Up a Mobile Intranet

2 Click Shutdown on the Message Agent window to stop the Message Agent
when the messages have been sent.

Receive data at the remote database


The Message Agent first receives a message from hq, and then sends a
message. This return message contains confirmation of successful receipt of
the replication update; such confirmations are part of the SQL Remote message
tracking system that ensures message delivery even in the event of message
system errors.
To receive the insert statement at the remote database, you must run the
Message Agent, dbremote, at the remote database:
1 With the database engine running, enter:
dbremote -c "eng=field;dbn=field;uid=DBA;pwd=SQL"
2 Click Shutdown on the Message Agent window to stop the Message Agent
when the messages have been processed.
The Message Agent window displays status information while running. In a
production setup, you will probably send this information to a log file for
record keeping.
To verify that the data has arrived at the remote database, connect to the remote
field database and inspect the SalesRep and Customer tables, to see which
rows have been received:
1 Connect to the field database using isql.
2 Inspect the SalesRep table by typing:
SELECT * FROM SalesRep
You see that the SalesRep table contains both rows entered at the
consolidated database. This is because the SalesRepData publication
included all the data from the SalesRep table.
3 Inspect the Customer table by typing:
SELECT * FROM Customer
You see that the Customer table contains only one row (Ocean Sports)
entered at the consolidated database. This is because the SalesRepData
publication included only those customers assigned to the subscribed sales
rep.

257
A Replication Tutorial

Create a template in your remote Web site that queries the data
In this section, we create a template that performs a query from the Adaptive
Server Anywhere remote database. This template queries data that has been
replicated from the consolidated database to the Adaptive Server Anywhere
remote database.
1 From Sybase Central, create a ODBC Data Source name to connect to
field.db.
2 Create a connection profile for field.db.
3 Connect to field.db.
4 In the left pane of Sybase Central, open the Site folder.
5 In the right pane, double-click Add Template.
6 On the first page of the wizard, enter a name for the template, for example,
RepProducts. Do not use spaces. Click Next.
7 Enter an optional description for the template and click Next again.
8 Use the default connection.
9 On the Add SQL Query page, click Select and enter a query to display the
cust_key, name, and rep_key columns.
10 Select one of the supplied formats from the list.
11 Click Finish.
You can view the output by right-clicking on the template and selecting
Browse Output.

Creating a Template Wizard - tab editor


If the user-defined tables were created from the consolidated database with a
user name of DBO, the tab editor needs to be set to display system tables.
Adaptive Server Anywhere considers all tables created under DBO as system
tables. They will not be visible to the tab editor if table type is set to table.

Replicate from the remote database to the consolidated database


You should now try entering data at the remote database and sending it to the
consolidated database:
1 Use isql to connect to the field database.
2 Insert a row at the remote database. For example:

258
CHAPTER 11 Setting Up a Mobile Intranet

INSERT INTO Customer (cust_key, name, rep_key)


VALUES (’cust3’, ’North Land Trading’, ’rep1’)
3 Commit the row:
COMMIT;
4 With the field.db database running, run dbremote to send this message to
the consolidated database.
dbremote -c "eng=field;dbn=field;uid=DBA;pwd=SQL"
5 Run ssremote to receive the message at the consolidated database:
ssremote -c "eng=server-
name;dbn=hq;uid=sa;pwd=sysadmin"
6 From Sybase Central, connect to the Web site in the consolidated database
and browse the RepProducts template, which has three rows:
cust_key name rep_key
cust1 Ocean Sports rep1
cust2 Sports Plus rep2
cust3 North Land Trading rep1

In this example, there is no protection against duplicate entries of primary key


values, however SQL Remote does provide for such protection. For
information, see the Data Replication with SQL Remote manual.

259
A Replication Tutorial

260
CH A PTE R 1 2 Calling Jaguar Component
Methods from PowerDynamo

About this chapter Jaguar CTS makes it possible for multiple clients, whether Java,
PowerBuilder, Visual Basic or PowerDynamo, to execute methods from a
Jaguar component. Jaguar eliminates the need to write application logic
toward specific platforms or a specific client. Jaguar allows methods to be
created once, installed on a Jaguar server, and accessed from multiple
clients from a variety of platforms.
This chapter looks at how you can use PowerDynamo and Jaguar together
to serve up applications that require dynamic Web pages as well and
access components (Java/JavaBeans, CORBA C++, ActiveX, and C) that
run in Jaguar.
Contents
Topic Page
How do Jaguar and PowerDynamo work together? 262
What does Jaguar bring to PowerDynamo applications? 264
Setting up PowerDynamo as a client 266
Calling Jaguar components from a PowerDynamo script 271
Working with ADO record sets as PowerDynamo query objects 284
Working with Tabular Results 286

261
How do Jaguar and PowerDynamo work together?

How do Jaguar and PowerDynamo work together?


Dynamo is an application server that dynamically generates HTML pages
which are in turn delivered to Web browsers through an HTTP protocol.
Jaguar, on the other hand, is a component transaction server that can serve up
components to any client that makes MASP, Java, CORBA C++, ActiveX or C
method calls. Jaguar components contain business logic that is completely
independent of the client or clients accessing the component. In addition, you
can configure Jaguar to host your Dynamo Web pages, making them accessible
from a Web browser. See the Jaguar CTS System Administration Guide for
information about hosting Dynamo Web pages.
The combination of PowerDynamo and Jaguar CTS allows you to create pure
HTML applications that dynamically make use of business logic from Jaguar
CTS components.
Figure 12-1 demonstrates a scenario in which a Dynamo client connects to
Jaguar to process a Dynamo script that contains a Method as a Stored
Procedure (MASP) call to a Jaguar component.
Figure 12-1: Dynamo client calling Jaguar component

262
CHAPTER 12 Calling Jaguar Component Methods from PowerDynamo

These steps correspond to the numbers in the diagram:


1 A browser requests a Web page, which is a PowerDynamo script that
contains HTML, SQL queries, and a MASP call to a Jaguar component.
2 The Web server passes the request to Dynamo.
3 The script is retrieved from the Web site (not shown in graphic). The
HTML in the Dynamo script and the SQL query begin to be processed.
4 An ODBC or Open Client connection is made to a database to retrieve the
necessary information for the SQL query.
5 The data is returned to PowerDynamo. Processing continues until the
Jaguar component call is encountered.
6 Because a MASP call is being made, an ODBC or Open Client connection
is made to Jaguar CTS to access the Jaguar component and called method.
7 The component method is executed. If the method requires database
access, a connection is made to a database to retrieve the appropriate data.
8 The data is returned to Jaguar CTS through an ODBC, Open Client, or
JDBC connection.
9 The results from the Jaguar function are returned to PowerDynamo
through an ODBC or Open Client connection.
10 PowerDynamo passes the results, in HTML format, back to the Web
server.
11 The results are passed back to the client through an HTTP connection.
Notes • Jaguar and Dynamo can access several different databases even though the
diagram displays only one database.
• Jaguar components can access data from many different (non-Sybase)
types of databases.
• The client, PowerDynamo, and Jaguar can either all reside on one machine
or on separate machines.
A Web author may embed calls to Jaguar components within a Dynamo script
or template. The Dynamo script executes in the regular manner until the call to
the Jaguar component is encountered. At this point, a connection (through
PowerDynamo) is made to the Jaguar server, the appropriate method will be
executed and the results are returned to PowerDynamo. PowerDynamo
processes the information and returns pure HTML.

263
What does Jaguar bring to PowerDynamo applications?

What does Jaguar bring to PowerDynamo


applications?
Jaguar is a platform-independent component transaction server that allows you
to develop component-based applications that can be accessed by thousands of
clients simultaneously. Jaguar brings flexibility to PowerDynamo scripts by
allowing you to create a component, deploy it to the Jaguar server, and share it
among remote sites using PowerDynamo scripts that call the Jaguar
component.
PowerDynamo also brings flexibility to Jaguar by providing a means for
accessing Jaguar components and their business logic through an ultra-thin
intranet or Internet client.

The benefits of using Jaguar CTS components with PowerDynamo


Jaguar components can be:
• Java/Enterprise JavaBeans
• CORBA C++
• ActiveX (nonvisual)
• C
• PowerBuilder NVO
You can call these components from within a Dynamo script as stored
procedures or as ActiveX or Java objects. The type of component being
accessed is irrelevant to the client.
The main benefits to using Jaguar components in Dynamo scripts include:
• Business logic stored in one Jaguar component becomes available to many
presentation-independent clients.
• Jaguar makes powerful native code components such as C and C++
available for execution by Dynamo scripts that would otherwise not have
access to methods written in those languages. There are few limitations on
the languages Dynamo scripts can use.

264
CHAPTER 12 Calling Jaguar Component Methods from PowerDynamo

• Components can be updated in one location. Without Jaguar, changes to a


component or a stored procedure would be required at each client. Setting
up Dynamo to access Jaguar components can be as simple as creating a
connection to the Jaguar CTS server or installing the ActiveX proxy
server.
The way that Jaguar components are accessible by Dynamo is advantageous
because there are no restrictions on how Dynamo can manipulate the
component results. The component results, in the form of HTML pages, are
wholly controlled by Dynamo.
A brief summary on setting up clients to access Jaguar CTS is given in the next
section. For detailed information on setting up clients that require Jaguar
access, see the Jaguar CTS Programmer’s Guide.

MASP method calls versus ActiveX or Java objects


There are a few benefits to using ActiveX or Java objects against a Jaguar
component instead of MASP method calls:
• ActiveX or Java objects exist until they go out of scope, whereas MASP
calls create an instance of the component, execute it, and destroy it
immediately.
• ActiveX or Java objects can give any type of return. MASP calls, from
PowerDynamo, can return only a result set.
• ActiveX or Java objects are treated like normal DynaScript objects, while
MASP calls (except the connection.CreateComponent method)
require that you enter a full string each time you make a call.
If a script requires repeated use of a Jaguar component, creating an ActiveX
object or Java stub is the preferred method of working with a Jaguar component
and its methods. ActiveX, however, is a Microsoft technology, which means it
is only available on Microsoft operating systems. Java, on the other hand, is
platform-independent, which means that Java objects can run anywhere.

265
Setting up PowerDynamo as a client

Setting up PowerDynamo as a client


For PowerDynamo to access Jaguar as a client, the machine on which
PowerDynamo is installed must be set up properly. This setup depends on the
type of calls that the Dynamo client will be making to Jaguar:
• If the Dynamo client will be performing ActiveX calls to Jaguar, follow
the steps in “Setting up PowerDynamo to use Jaguar components through
ActiveX” on page 266.
• If the Dynamo client will be performing Java calls to Jaguar, follow the
steps in Setting up PowerDynamo to use Jaguar components through Java.
• If the Dynamo client will be performing only MASP calls to Jaguar, follow
the steps for setting up the Dynamo client in “Setting up PowerDynamo to
use MASP” on page 267.

Jaguar client software


To call Jaguar components from PowerDynamo, you must install the client
software (select Runtime), when installing Jaguar.

Setting up PowerDynamo to use Jaguar components through


ActiveX
To access a Jaguar component with ActiveX objects:
1 Install Jaguar Manager on the Dynamo machine.
2 Install the ActiveX Proxy Automation Server using the Client Installation
Program (JagClient.exe) on the Dynamo machine.
3 From Jaguar Manager, connect to the Jaguar server that contains the
required components.
4 Generate TLB/REG files for the package. This generates ActiveX proxy
objects that you can then use to create instances and invoke methods on
remote Jaguar components.
5 Register the package.
You are now ready to run the Dynamo application.
For detailed information on setting up an ActiveX client, see the Jaguar
Programmer’s Guide.

266
CHAPTER 12 Calling Jaguar Component Methods from PowerDynamo

Setting up PowerDynamo to use Jaguar components through Java


To create Java objects to access a Jaguar component:
1 Install Jaguar Manager on the Dynamo machine.
2 From Jaguar Manager, generate stubs for the desired package using these
options:
• generate stubs
• Java stubs
• JDK 1.1
3 Ensure that the Java Code Base path is in your class path.
4 Compile the generated Java files as instructed in the Jaguar Programmer’s
Guide.
5 Configure Dynamo for Java support. See “Configuring Dynamo to use
Java” on page 156.
6 Set your default Jaguar settings. For information about the default Jaguar
settings, see “Changing Dynamo configuration settings” on page 106.

Setting up PowerDynamo to use MASP


To set up Dynamo as a client machine to use MASP method calls you need only
to create a connection to the Jaguar server.
For detailed information on accessing Jaguar MASP methods, see the Jaguar
Programmer’s Guide.
There are two types of connections that may be created to access Jaguar from
PowerDynamo.
• Sybase System 11 ODBC data source connection
• Open Client connection

267
Setting up PowerDynamo as a client

ActiveX and Java object calls


If you are creating instances of either ActiveX or Java objects within a script
and no MASP method calls are involved, a connection to the Jaguar server as
described here is not required. For ActiveX objects, a connection is made
through the ActiveX proxy server that you install on your machine as explained
in “Setting up PowerDynamo as a client” on page 266. For Java objects, a
connection is made through the Object Request Broker (ORB). See the Jaguar
Programmer’s Guide for more information on ORBs.

Using an ODBC data source to connect to Jaguar


To create an ODBC data source connection:
1 Register Jaguar in the Dynamo machine's sql.ini file.
2 Create an ODBC data source.
3 Create a permanent user connection to Jaguar. If you do not require
connection pooling you can create a temporary user connection instead of
a permanent user connection.

❖ To register Jaguar in the Sybase\sql.ini file:


1 On the machine running Jaguar, open <Jaguar CTS>\ini\sql.ini.
2 From the Jaguar machine, copy <Jaguar CTS>\ini\sql.ini file to the
Dynamo machine; for example, Sybase\ini\sql.ini.
The file should look something like this. If you have configured the Jaguar
TDS listener to something other than localhost, replace localhost with this
value.
[Jaguar]
master=NLWNSCK,localhost,7878
query=NLWNSCK,localhost,7878
http=NLWNSCK,localhost,8080
iiop=NLWNSCK,localhost,9000

❖ To create an ODBC data source for Jaguar:


1 Start the ODBC Administrator.
2 Click Add.
3 Select the Sybase System 11 driver and click Finish.

268
CHAPTER 12 Calling Jaguar Component Methods from PowerDynamo

4 On the General tab, enter an ODBC data source name (for example,
Jaguar_dsn), and a Server name (for example, Jaguar).
5 Click OK to create the data source.

❖ To create a permanent user connection to Jaguar:


1 Start the Jaguar server.
2 Use Sybase Central to connect to the Dynamo Web site that contains the
scripts requiring a connection to Jaguar.
3 Open the Connection folder.
4 Click Add Connection.
5 Give the connection a name. Click Next.
6 Enter a description for the connection. Click Next.
7 Select ODBC as the connection type. Click Next.
8 Select the data source for the connection, which is the name of the ODBC
data source that you created in the previous procedure. Click Next.
9 Enter a user ID for this connection. The Jaguar samples use jagadmin as
the user ID. Click Next.
10 Enter a password for this connection. The Jaguar samples use a blank
password. Click Next.
11 Click Finish.
Your permanent user connection should now be visible from the connection
folder in Sybase Central. To use this connection for scripts that require a Jaguar
connection, right-click on the script, select Properties, and choose the new
connection. You can also do this at the folder level. If you set the connection to
at the folder level any scripts within that folder with a connection type set to
<inherited> will use the Jaguar connection as their default connection.
You can also access the Jaguar connection using the DynaScript method
site.GetConnection or the Dynamo SQL tag and attributes.

Using an Open Client connection to connect to Jaguar


If an Open Client connection is required, you must:
1 Register Jaguar in the sql.ini file.
2 Create a permanent user connection to Jaguar.

269
Setting up PowerDynamo as a client

❖ To register Jaguar in the Sybase\sql.ini file:


1 Open the sql.ini file that resides in <Jaguar CTS>\ini\.
2 Copy the contents of the sql.ini file to the sql.ini file on the Dynamo
machine. For example, Sybase\ini\sql.ini.
The content being copied should look something like the following. If the
Jaguar TDS listener has been configured to something other than
localhost, for example the machine name, replace localhost with this
value.
[Jaguar]
query=NLWNSCK,localhost,7878

❖ To create a permanent user connection to Jaguar:


1 Start the Jaguar server.
2 Use Sybase Central to connect to the Dynamo Web site containing the
scripts that require a connection to Jaguar.
3 Open the Connection folder.
4 Click Add Connection.
5 Give the connection a name. Click Next.
6 Enter a description for the connection. Click Next.
7 Select Open Client as the type of connection you want to create. Click
Next.
8 Enter the Jaguar Server name. Click Next.
9 Leave the database name blank. Click Next.
10 Enter a user ID for the connection. The Jaguar sample uses jagadmin as a
user ID. Click Next.
11 Enter a password for this connection. The Jaguar samples use a blank
password. Click Finish.
Your permanent user connection should now be visible from the connection
folder. To use this connection for scripts that require a Jaguar connection, right-
click on the script, select Properties and choose the new connection. You can
also do this at the folder level. Any scripts in the folder you select that have a
connection type of <inherited> will use the Jaguar connection as their default
connection.
You can also access the Jaguar connection using the DynaScript method
site.GetConnection or the Dynamo SQL tag and attributes.

270
CHAPTER 12 Calling Jaguar Component Methods from PowerDynamo

Calling Jaguar components from a PowerDynamo


script
You can call Jaguar components from within a PowerDynamo script by using:
• The Dynamo SQL tag (must return a result set)
• The Dynamo COMPONENT tag (may return a result set)
• The connection.CreateQuery method (must return a result set)
• The connection.CreateComponent method (must return a result set)
• The java.CreateComponent method (no restriction on the return)
• The java.GetUserTransaction method (allows access to the
UserTransaction object of Jaguar components participating in a
transaction)
• The java.GetHomeInterface method (allows access to EJB home interface
of Jaguar components)
• An ActiveX object through the PowerDynamo CreateObject method (no
restriction on the return)
The SQL tag, COMPONENT tag, connection.CreateQuery method and the
connection.CreateComponent methods allow Dynamo to call Jaguar
components as though they were Methods As Stored Procedures (MASP).
Each MASP invocation creates an instance of the component, invokes the
method and then destroys the component instance.

Jaguar client software


If you will be calling Jaguar components from PowerDynamo, ensure that you
have installed the client software (select Runtime), when installing Jaguar.

For more information on MASP, see the Jaguar Programmer’s Guide.

The Dynamo SQL tag (MASP)


Description You can use the PowerDynamo SQL tag to make Methods As Stored
Procedures (MASP) calls. You can use the normal SQL tag attributes when
calling a MASP with the SQL tag. For a list of these attributes, see “The SQL
tag” in PowerDynamo Reference.
Syntax <!--SQL

271
Calling Jaguar components from a PowerDynamo script

exec packageName.componentName.methodName [parameters]


-->
Example The following example makes a MASP method call to the SVUEnrollment
component, which resides in the SVU package. The method being called is
getMajors. No parameters are being passed in.
<!--SQL
exec SVU.SVUEnrollment.getMajors
-->
<!--FORMATTING-->
<!--/FORMATTING-->
The SVUEnrollment component contains several methods, one of which is
getMajors. These methods can all be called as MASP methods by the SQL
tag. The only restriction on calling a MASP with the SQL tag is that the return
must be a result set. If the component method contains inout or output
parameters, the output of these parameters will not be available.
The MASP being called in the following example requires that parameters be
passed in order for the method to execute. In this case, a first and last name are
required as well as a phone number.
<!--SQL
exec Demo_Components.PhoneList.addPhoneList Tammy,
Black, (519)873-2243
-->
These examples assume that the connection for the script has been set to the
Jaguar server.
For more information on the SQL tag, see “The SQL tag” in PowerDynamo
Reference.

The Dynamo COMPONENT tag


Description Using the Dynamo COMPONENT tag is similar to the way in which the SQL
tag is used to call Jaguar components except that the package, component, and
method are clearly labeled. The attributes normally associated with the SQL
tag can also be used with the COMPONENT tag. For a list of these attributes,
see “The COMPONENT tag” in PowerDynamo Reference.
Although you can use the COMPONENT tag for ActiveX and Java access, the
instance of that component exists only until the end of the COMPONENT tag.

272
CHAPTER 12 Calling Jaguar Component Methods from PowerDynamo

COMPONENT name for the returned value


The default name of the returned value when using the COMPONENT tag is
COMPONENT, in the same way that the default name of the query object is
SQL when using the SQL tag.

Syntax For SQL access (MASP):


<!--COMPONENT ACCESS_METHOD= SQL PKG=packagename
COMPONENT_NAME=componentname METHOD=methodname
parameter(s)
-->
For ActiveX access (no restriction on the return):
<!--COMPONENT ACCESS_METHOD= ACTIVEX PKG=packagename
COMPONENT_NAME=componentname METHOD=methodname
HOST=hostname
parameter(s)
-->
For Java access (no restriction on the return):
<!--COMPONENT ACCESS_METHOD= JAVA PKG=packagename
COMPONENT_NAME=componentname METHOD=methodname
MANAGER_URL=url USERID=id PASSWORD=password
NARROW_INTERFACE=narrowinterface
parameter(s)
-->
Example Here is an example of a MASP being called from within a Dynamo script using
the Dynamo COMPONENT tag. You can use the FORMATTING tags to move
through the result set:
<!--COMPONENT PKG=SVU COMPONENT_NAME=SVUEnrollment
METHOD=getMajors
-->
<!--FORMATTING NAME=COMPONENT-->
<!--/FORMATTING-->
For more information on the COMPONENT tag, see “The COMPONENT tag”
in PowerDynamo Reference.

273
Calling Jaguar components from a PowerDynamo script

The connection.CreateQuery method (MASP)


Description The connection.CreateQuery method executes a MASP and returns a
query object that you can use to move through the result set. This is a method
of the DynaScript scripting language.
Syntax <!--SCRIPT
queryObjectName = connection.CreateQuery( "exec
packageName.ComponentName.methodName" );
-->
Example The following example uses the connection.CreateQuery method to call
a Jaguar MASP:
<!--SCRIPT
queryObject = connection.CreateQuery( "exec
SVU.SVUEnrollment.getMajors" );
-->
<!--FORMATTING NAME=queryObject-->
<!--/FORMATTING-->
This example uses connection.CreateQuery to call a MASP that adds new
users to a phone list:
<!--SCRIPT
connection.CreateQuery("exec
Demo_Components.PhoneList.addPhoneList Nicole LaChance
(519)873-2243");
-->
For more information, see “CreateQuery method” in PowerDynamo Reference.

The connection.CreateComponent method (MASP)


Description The connection.CreateComponent method executes a MASP and returns
a component object. You can then call methods of the component object that
will return a query object.
Syntax <!--SCRIPT
componentObject = connection.CreateComponent( "packageName",
"componentName" );
componentObject.methodName (parameters);
-->

274
CHAPTER 12 Calling Jaguar Component Methods from PowerDynamo

Example This example uses the connection.CreateComponent method to create an


instance of the SVUEnrollment Jaguar component and to then call the
getMajors method of that component:
<!--SCRIPT
myJagComponent = connection.CreateComponent( "SVU",
"SVUEnrollment" );
queryObject = myJagComponent.getMajors();
-->
<!--FORMATTING NAME=queryObject-->
<!--/FORMATTING-->
The following example uses connection.CreateComponent to call a
MASP that adds a new user to the phone list:
<!--SCRIPT
myComp = connection.CreateComponent( "Demo_Components",
"PhoneList" );
myComp.addPhoneList ( "Zachary", "Graham", "(519)873-
2763" );
-->
For more information, see “CreateComponent method” in PowerDynamo
Reference.

The java.CreateComponent method


Description You can use the PowerDynamo java.CreateComponent method to create an
instance of a Java object. Once you have created a Java object, you can call its
methods in the same manner as a normal DynaScript object.
Syntax <!--SCRIPT
javaObj = java.CreateComponent( component_name [, manager_url, id,
password, narrowing_component] )
-->
Example The following example creates an instance of the SVU/SVUEnrollment
component called comp. Once the object is created, its method getMajors is
called and the Record Set is displayed:
<!--SCRIPT
comp = java.CreateComponent( "SVU/SVUEnrollment" );
RecordSet = comp.getMajors();
query = java.CallStaticMethod(
"com.sybase.CORBA.jdbc11.SQL", "getResultSet",
RecordSet );

275
Calling Jaguar components from a PowerDynamo script

received = query.next();
i = 0;
while( received ) {
metadata = query.getMetaData();
document.writeln( "*****" );
columns = metadata.getColumnCount();
for( j = 1; j <= columns; j++ ) {
value = query.getString( j );
document.writeln( value );
}
received = query.next();
i++;
}
-->
</HTML>
For more information, see “CreateComponent method” in PowerDynamo
Reference.
This example creates an instance of the SVU/SVUEnrollment component
called comp from a machine called testMachine. Once the object is created, its
method getMajors is called and the Record Set is displayed:
<!--SCRIPT
comp = java.CreateComponent( "SVU/SVUEnrollment",
"iiop://testMachine:9000", "guest", "" );

RecordSet = comp.getMajors();
query = java.CallStaticMethod(
"com.sybase.CORBA.jdbc11.SQL", "getResultSet",
RecordSet );
received = query.next();
i = 0;
while( received ) {
metadata = query.getMetaData();
document.writeln( "*****" );
columns = metadata.getColumnCount();
for( j = 1; j <= columns; j++ ) {
value = query.getString( j );
document.writeln( value );
}
received = query.next();
i++;
}
-->
For information on tabular results see, “Working with Tabular Results” on page
286.

276
CHAPTER 12 Calling Jaguar Component Methods from PowerDynamo

GetHomeInterface method
Description Allows access to the EJBHome interface for a Jaguar component.
Syntax java.GetHomeInterface(component_name [, provider_url, user_id,
password] )
The parameters are:
•component_name The name of the component to instantiate.
Component names are composed as follows:
[<server-context>]<package>/<comp>
• server-context – The root naming context for the server where the
component is installed. server-context is optional and necessary only
if a root naming context has been set for the server. The root naming
context can also be given as the initial context in the provider_url.
• package – The Jaguar package to which the component belongs, as
displayed in Jaguar Manager.
• component – The component name, as displayed in Jaguar Manager.
You can view and edit this setting using the Naming Service tab of the
Server Properties window from Jaguar Manager. The default for a new
server is “/”. If you specified an initial name context in
GetHomeInterface()'s provider_url parameter, then the server context is
assumed to be relative to this initial name context. For example, if the
provider_url parameter is set to iiop://localhost:9000/USA/Sybase, and
your server's root context is USA/Sybase/Engineering, then you can
resolve component names as Engineering/package/component.
•provider_url The provider_url is optional and defaults to
“iiop://localhost:9000”. If used, it identifies the URL of the JNDI name
server. This parameter should be of the form iiop://<hostname>[:<iiop-
port>][/<initial-context>] where:
• hostname Is the host machine name for the Jaguar server that serves
as the name server for your application.
• iiop-port Is the IIOP port number for the server.
• initial-context Is the optional initial naming context, which can be
used to set a default prefix for name resolution. For example, if you
specify USA/Sybase/, then the component_name parameter is
assumed to be relative to this location in the name hierarchy. When
specifying the initial context, the trailing slash is optional; it is added
automatically if you do not specify an initial context that ends with a
slash.

277
Calling Jaguar components from a PowerDynamo script

•user_id The user name for the Jaguar session. If authorization is enabled for
your Jaguar server, this parameter is used to authorize access to Jaguar
components.
The user_id parameter is optional and defaults to “guest”.
•password The password for the Jaguar session. If authorization is enabled
for your Jaguar server, the password is used to authorize access to Jaguar
components.
The password parameter is optional and default is no password.

Note The Dynamo methods GetHomeInterface and GetUserTransaction


enable access to EJB interfaces of Jaguar components.
To access EJB interfaces of Jaguar components, Dynamo requires a Jaguar
client zip file, jagclient.zip, from a Jaguar CTS installation version 3.5 or
above. Refer to PowerDynamo installation instructions for your platform and
ensure that this file is included in your JAGUARCLASSES (Solaris) or
CLASSPATH (NT) variable.

Example Use java.GetHomeInterface to create an instance of the EJBHome


interface for the component Test/Cart. Then use the Home interface to
create an actual instance of Test/Cart.
carthomeObj =
java.GetHomeInterface("CartPackage/Cart")
cartObj = carthomeObj.create("John", "7506");
cartObj.addItem(66)
cartObj.addItem(22)
cartObj.purchase()
carthomeObj.remove(...)
See also The PowerDynamo Reference Manual.

GetUserTransaction method
Description Allows access to the EJB UserTransaction object.
Syntax java.GetUserTransaction( [ <provider_url>, <user_id>, <password>] )
The parameters are:

278
CHAPTER 12 Calling Jaguar Component Methods from PowerDynamo

•provider_url The provider_url is optional and defaults to


“iiop://localhost:9000”. It identifies the URL of the JNDI name server.
This parameter should be of the form iiop://<hostname>[:<iiop-
port>][/<initial-context>] where:
• hostname Is the host machine name for the Jaguar server that serves
as the name server for your application.
• iiop-port Is the IIOP port number for the server.
• initial-context Is the optional initial naming context, which can be
used to set a default prefix for name resolution. For example, if you
specify USA/Sybase/, all names that you resolve with the context are
assumed to be relative to this location in the name hierarchy. When
specifying the initial context, the trailing slash is optional; it is added
automatically if you do not specify an initial context that ends with a
slash.
•user_id The user name for the Jaguar session. If authorization is enabled for
your Jaguar server this optional parameter, which defaults to “guest”, is
used to authorize access to Jaguar components.
•password The password for the Jaguar session. If authorization is enabled
for your Jaguar server, this optional parameter, which defaults to no
password, is used to authorize access to Jaguar components.

Note The Dynamo methods GetHomeInterface and GetUserTransaction


enable access to EJB interfaces of Jaguar components.
To access EJB interfaces of Jaguar components, Dynamo requires a Jaguar
client zip file, jagclient.zip, from a Jaguar CTS installation version 3.5 or
above. Refer to PowerDynamo installation instructions for your platform and
ensure that this file is included in your JAGUARCLASSES (Solaris) or
CLASSPATH (NT) variable.

Comments The components that participate in the transaction managed with the
UserTransaction object must be in the same server as the UserTransaction
object, which cannot be assumed if a Jaguar cluster is used to ensure that this
requirement is met:
1 Use the same name server to create the UserTransaction object that was
used when creating the component instances. That is, supply the same
provider_url to GetUserTransaction() and GetHomeInterface(),
CreateComponent(). The initial-context values of the URLs can differ.

279
Calling Jaguar components from a PowerDynamo script

2 Get the UserTransaction object and begin the transaction before creating
any component instances.
3 In addition, follow the same restrictions as other Java clients when using
the UserTransaction object. Refer to the Jaguar CTS Programmer’s Guide
and Jaguar CTS Reference Manual for details.
The UserTransaction interface defines exceptions that are thrown when errors
occur. For example, TransactionRolledbackException is thrown when
commit() is called after setRollbackOnly() has already been called for a
transaction.
As many of the methods in the UserTransaction interface for example, return
void, begin(), commit(), rollback(), these exceptions are the only way
to detect errors.
In DynaScript, exceptions are passed to the user through the
site.GetErrorInfo() method. That is, the exception is converted to an
error string. For example:
ut.begin()
...
ut.commit()
errMsg = site.GetErrorInfo();
if ((errMsg != null) && (errMsg != ""))
{
/* the transaction was not committed */
}
The UserTransaction.getStatus() method returns an integer value
indicating the status of the current transaction. Dynamo users can include the
script ~/system/utils/usertran.ssc to get the definitions of variables that map to
the integer values returned by getStatus().
import "~/system/utils/usertran.ssc"
...

ut = java.GetUserTransaction(...);
ut.begin()
status = ut.getStatus();
if (status != UserTran.STATUS_ACTIVE)
{
/* the transaction was not started */
}

...

280
CHAPTER 12 Calling Jaguar Component Methods from PowerDynamo

Example Use java.GetUserTransaction to get the UserTransaction object,


instantiate the components that will participate in the transaction, begin the
transaction, perform the operations required in the transaction, and commit the
transaction.
ut = java.GetUserTransaction("iiop://my-host:9000")
acctHome = java.GetHomeInterface("Bank/Account",
"iiop://my-host:9000")
acct1 = acctHome.create("John", "Doe", "111-11-1111")
acct2 = acctHome.create("Jane", "Doe", "222-22-2222")
acct3 = = java.CreateComponent("Bank/Account",
"iiop://my-host:9000")
ut.begin();
errMsg = site.GetErrorInfo();
if ((errMsg != null) && (errMsg != ""))
{
/* handle error, the transaction did not begin return
}
acct1.withdraw(100);
acct2.deposit(50);
acct3.deposit(50);
ut.commit();
errMsg = site.GetErrorInfo();
if ((errMsg != null) && (errMsg != ""))
{
/* handle error, the transaction did not commit
return
}
See also The PowerDynamo Reference Manual.

The PowerDynamo CreateObject method


Description You can use the PowerDynamo CreateObject method to create an instance of
an ActiveX object. Once an ActiveX object has been created, its methods may
be called in the same manner as a normal DynaScript object. An ActiveX
object exists until it goes out of scope or until the ActiveX variable is assigned
a new value.
Syntax <!--SCRIPT
objectName=CreateObject("packageName.componentName");
[objectName.Host("machineName:portNumber");
objectName.UserName="jagadmin";
objectName.Password="";

281
Calling Jaguar components from a PowerDynamo script

objectName.Name="packageName_1/componentName_1"]
objectName.Initialize();
output=objectName.methodName(parameter);
-->
The Host, UserName, and Password are all optional properties, depending on
the scenario in which you are creating your instance of an ActiveX object.
•Host By default, host is set to localhost:9000. If the Jaguar server is
running on a different machine or the port number is a value other than
9000, you must set this property accordingly.
•UserName and Password The user name and password are optional
properties unless you are working with components that have had
component level security specified using Roles.
•Name The name property is optional if the package name is the same as
the module name and the component name is the same as the interface
name.
For more information on working with ActiveX and Jaguar, see the Jaguar
Programmer’s Guide.
Example This example creates an instance of an ActiveX object called comp. Once the
object is created, its method getMajors is called and the Record Set is
displayed:
<!--SCRIPT
comp = CreateObject( "SVU.SVUEnrollment" );
comp.Initialize();
RecordSet = comp.getMajors();
RecordSet.MoveFirst();
while( !RecordSet.EOF ) {
document.writeln( "*****" );
fields = RecordSet.Fields;
columns = fields.Count;
for( j = 0; j < columns; j++ ) {
field = fields.Item(j);
document.writeln( field.Value );
}
RecordSet.MoveNext();
}
-->
This example creates an instance of an ActiveX object called comp that resides
on a machine called testMachine. Once the Object is created, its method
getMajors is called and the Record Set is displayed:

282
CHAPTER 12 Calling Jaguar Component Methods from PowerDynamo

<!--SCRIPT
comp = CreateObject( "SVU.SVUEnrollment" );
comp.Host = "testMachine:9000";
comp.Initialize();
RecordSet = comp.getMajors();
RecordSet.MoveFirst();
while( !RecordSet.EOF ) {
document.writeln( "*****" );
fields = RecordSet.Fields;
columns = fields.Count;
for( j = 0; j < columns; j++ ) {
field = fields.Item( j );
document.writeln( field.Value );
}
RecordSet.MoveNext();
}
-->
For more information about the CreateObject method, see “Built-in functions”
in PowerDynamo Reference.
For information on ADO record sets see “Working with ADO record sets as
PowerDynamo query objects” on page 284.

283
Working with ADO record sets as PowerDynamo query objects

Working with ADO record sets as PowerDynamo query


objects
When a Dynamo script calls a Jaguar component through ActiveX and that
component returns a result set, an ADO record set is returned. ADO record sets
have different properties and methods than the Dynamo query object. Dynamo
includes a script called adoqry.ssc that is installed in the system/utils folder of
the Dynamo Web site. This script implements a class called ADOQuery which
takes as a parameter an ADO record set object sent by Jaguar, and returns a
class that has methods mimicking those of a Dynamo query object.
Scripts that call a Jaguar component through ActiveX and do not make use of
the ADOQuery class look something like this:
comp = CreateObject( "SVU.SVUEnrollment" );
comp.Initialize();
// returns ADO RecordSet-like object
query = comp.getMajors();
query.MoveFirst();
columns = query.Fields.Count;
document.writeln( "There are " + columns + " columns" );
while( !query.EOF ) {
fields = query.Fields;
for( j = 0; j < columns; j++ ) {
field = fields.Item(j);
value = field.Value;
document.writeln( value );
}
query.MoveNext();
}
With the ADOQuery class, you could instead do this:
import ~/system/utils/adoqry.ssc;

comp = CreateObject( "SVU.SVUEnrollment" );


comp.Initialize();
// returns ADO RecordSet-like object
query = comp.getMajors();
// wrap up the ADO RecordSet to mimic a Dynamo query
// object
dynQuery = new ADOQuery( query );
columns = dynQuery.GetColumnCount();
document.writeln( "There are " + columns + " columns" );
while( dynQuery.MoveNext() ) {
for( j = 1; j <= columns; j++ ) {
value = dynQuery.GetValue(j);

284
CHAPTER 12 Calling Jaguar Component Methods from PowerDynamo

document.writeln( value );
}
}

285
Working with Tabular Results

Working with Tabular Results


When a Dynamo script calls a Jaguar component through Java, results are
returned as Tabular ResultSets. Tabular ResultSets have different properties
and methods than the Dynamo query object. Dynamo includes a script called
javaqry.ssc that is installed in the system/utils folder of the Dynamo web site.
This script implements a class called JavaQuery which takes as a parameter a
TabularResults Set object sent by Jaguar and returns a class that has methods
mimicking those of a Dynamo query object.
Scripts that call a Jaguar component through Java and do not make use of the
JavaQuery class look something like this:
comp = java.CreateComponent( "SVU/SVUEnrollment" );
prequery = comp.getMajors();
query = java.CallStaticMethod(
"com.sybase.CORBA.jdbc11.SQL","getResultSet",prequery
);
received = query.next();
metadata = query.getMetaData();
columns = metadata.getColumnCount();
document.writeln( "There are " + columns + " columns" );
while( received ) {
fields = query.Fields;
for( j = 0; j < columns; j++ ) {
value = query.getString( j )
document.writeln( value );
}
received = query.next();
}
Using the JavaQuery class, you could use:
import ~/system/utils/javaqry.ssc;

comp = java.CreateComponent( "SVU/SVUEnrollment" );


// returns Tabular ResultSet object
query = comp.getMajors();
// wrap up the Tabular ResultSet to mimic a Dynamo query
//object
dynQuery = new JavaQuery( query );
columns = dynQuery.GetColumnCount();
document.writeln( "There are " + columns + " columns" );
while( dynQuery.MoveNext() ) {
for( j = 0; j <= columns; j++ ) {
value = dynQuery.GetValue(j);
document.writeln( value );

286
CHAPTER 12 Calling Jaguar Component Methods from PowerDynamo

}
}

287
Working with Tabular Results

288
A P PE N DI X A Setting Up the Adaptive
Server Anywhere Database
Server as a Service

About this appendix This appendix explains how to set up PowerDynamo to run with the
Adaptive Server Anywhere database server.

Adaptive Server Anywhere required


This chapter applies only to those users that are running PowerDynamo
with an Adaptive Server Anywhere database.

Contents
Topic Page
Why use the Adaptive Server Anywhere server? 290
Setting up the Adaptive Server Anywhere database server for 292
PowerDynamo

289
Why use the Adaptive Server Anywhere server?

Why use the Adaptive Server Anywhere server?


The Adaptive Server Anywhere personal server has a limit of ten connections.
While this limit is appropriate for developing a Web site, it is not sufficient for
a “live” site that will get any number of calls at one time. Every request from a
browser counts as one connection. For example, a Web page containing three
graphics and one OLE control, can generate five connections to the database.
Comparison of the
personal server and Personal Database Server Network server
the network server No network connection Network connections
Ten-connection limit Connection limit based on license
Can run as an NT service Can run as an NT service
Can be automatically started through Cannot automatically start a remote
ODBC server ODBC
Can be automatically started if set up as Can be automatically started if set up
a service as a service
Can be automatically stopped Cannot be automatically stopped

For more information on running Adaptive Server Anywhere, see the Adaptive
Server Anywhere documentation.

Check your license agreement


You must confirm that you are properly licensed to use PowerDynamo and
Adaptive Server Anywhere before using your Web site.

Why run the Adaptive Server Anywhere database server as a


service?
There are several advantages to running the Adaptive Server Anywhere
database server as a service for PowerDynamo:
• Users can log out of NT without connections being lost or losing their own
connection to the server.
• The server console is secure as users must use normal NT security to log
in.
• A new user logging in will already be set up with both the database server
and the Web server as they both run as a service.
• Users can log in and out of NT while the database server continues to run
and accept connections.

290
APPENDIX A Setting Up the Adaptive Server Anywhere Database Server as a Service

• A service can be configured to start automatically when the NT computer


is started, before a user logs on.

291
Setting up the Adaptive Server Anywhere database server for PowerDynamo

Setting up the Adaptive Server Anywhere database


server for PowerDynamo
The following section explains the required steps for setting up an Adaptive
Server Anywhere database server to run as an NT service. They are:
1 Start the Adaptive Server Anywhere server as a service
2 Set up the ODBC System DSN
3 Set up the Connection Profile
4 Connect to PowerDynamo

Start the Adaptive Server Anywhere server as a service


Configure the Adaptive Server Anywhere server as an NT service by opening
the Services folder in the Sybase Central, then clicking Add Service in the right
pane.
Follow the instructions in the wizard to define the new service.
The path you specify in the wizard should point to dbsrv50.exe for 5.5.04 or
earlier versions of SQL Anywhere. For versions 6.0 or later, the path should
point to dbsrv6.exe.
You must also specify the server name and the database to which
PowerDynamo will be connecting.
For more information on services, see the Sybase Adaptive Server Anywhere
User’s Guide.

Set up the ODBC System DSN


You must next create an ODBC System DSN, which stores information about
how to connect to a data provider. By defining a System DSN rather than a User
DSN, the information is accessible to any user on the local machine.

❖ To create an ODBC System Data Source Name:


1 Start the ODBC Administrator.
2 Select the System DSN tab. The System Data Source window will open.
Click Add.

292
APPENDIX A Setting Up the Adaptive Server Anywhere Database Server as a Service

3 In the Create New Data Source window, select the appropriate ODBC
driver and click OK.
4 In the SQL Anywhere ODBC configuration window, enter the data source
name, the server name, and the database name. Click OK.
Start-up options for If you are using SQL Anywhere 5.5.04 or earlier, you should set some start-up
SQL Anywhere 5.5.04 commands in the ODBC configuration window.
or earlier
If you are using Adaptive Server Anywhere 6.0 or later, you do not need to set
these start-up commands.
Click Options from the SQL Anywhere ODBC configuration window.
Figure A-1 illustrates how your start-up options should be set if you are using
SQL Anywhere 5.5.04 or lower.
Figure A-1: Startup Options window

If you are connecting to a remote database server, specify this start command:
c:\sqlany50\win32\dbclient.exe
If you are connecting to a database server on the same machine as the Web
server and DBCLIENT has been specified, the Agent should be Not Specified.
This does not start the DBCLIENT application, but allows access to the
database server.
Selecting Client as the Agent would cause the DBCLIENT application to start
unnecessarily, causing the local connection to be made through the network
which would cause a decline in performance. Select Client as the Agent only
if the database server is running on a different machine than the Web server.

293
Setting up the Adaptive Server Anywhere database server for PowerDynamo

Set up the Connection Profile


To connect to the appropriate database, create a PowerDynamo connection
profile that calls the appropriate ODBC data source name.
1 In Sybase Central, select Tools -> Connection Profiles.
2 Click New.
3 Enter a connection name and select PowerDynamo as the profile type from
the drop-down list. Click OK.
4 Select the appropriate ODBC data source from the drop-down list.
5 Enter your user ID and password. Click OK.
Figure A-2: Connection Profile window

Connect to PowerDynamo
Once you have completed your connection profile, you can connect to
PowerDynamo.
1 In Sybase Central, select Tools -> Connection Profiles.

294
APPENDIX A Setting Up the Adaptive Server Anywhere Database Server as a Service

2 Select the connection profile you want to connect with and click Connect.

295
Setting up the Adaptive Server Anywhere database server for PowerDynamo

296
A P PE N DI X B Language Support

About this appendix This appendix explains the language support that Dynamo provides for
double-byte and multi-byte character sets.
Contents
Topic Page
Language support 298
Usage of multi-byte characters 301

297
Language support

Language support
In many languages, each letter and number can be represented by a single-byte
character set. Each character is represented by an 8 bit byte. At most, 256
characters can be represented.
For many languages such as Japanese or Taiwanese 256 characters is not
sufficient. In cases such as these, a double-byte character set is necessary to
represent the large number of characters that make up the language. In a few
languages even double-byte character sets are not sufficient, in which case a
multi-byte character set is used.

Multi-byte characters and PowerDynamo


PowerDynamo supports multi-byte character sets up to 4 bytes in length.

Collation Sequence Each character set has its own collation sequence (sorting order) for characters
in a character set. The collation sequence is important when doing queries and
compares such as:
<!--SQL
SELECT emp_lname, emp_fname
from EMPLOYEE
where emp_lname > ’S’
-->
The collation sequence enables the database to determine if J is greater than or
less than S in this example.

One language is supported per Dynamo Web Server


The first site you connect to through a Web server sets the collation sequence
for all PowerDynamo Web sites on that server. All subsequent databases being
connected to must use the same collation sequence.

Adaptive Server Anywhere language support


The collation sequence used by an Adaptive Server Anywhere database is
selected when the database is created. If no collation sequence is specified, a
default collation sequence is used.
The collation sequence used by the PowerDynamo scripting engine is specified
in the host database. If no collation sequence was specified for the database at
the time of creation, the collation sequence from the PowerDynamo language
DLL is used.

298
APPENDIX B Language Support

The Japanese language DLL (dys03jpt.dll) sets the collation sequence to sjis
(Japanese Shift-JIS Encoding).
The English language DLL (dys03ent.dll) sets the collation sequence to
cp437, ASCII, United States.
To change the collation sequence used by PowerDynamo, create a new
database and specify the appropriate collation sequence for the required
language. Store the PowerDynamo Web site in the newly created database. The
Web site will have the same collation sequence as that specified for the new
database.

Individual collation sequence


PowerDynamo and Adaptive Server Anywhere have individual collation
sequences. They are not necessarily the same.

For more information about collation sequences, see the Sybase Adaptive
Server Anywhere User’s Guide.

Adaptive Server Enterprise language support


The character set used by an Adaptive Server Enterprise server is set when it is
created. If no collation sequence is specified, the default collation sequence is
used.
The character set used by the PowerDynamo scripting engine is determined by
the character set specified in the host server. PowerDynamo reads the character
set from the Enterprise server and then maps it to the appropriate
PowerDynamo character set by means of the table shown here.
Adaptive Server Enterprise Dynamo
“cp437” “437”
“cp850” “850”
“cp852” “852”
“cp855” “855CYR”
“cp857” “857TRK”
“cp860” “860”
“cp866” “866RUS”
“cp869” “869ELL”
“eucb5” “EUC_TAIWAN”
“eucgb” “EUC_CHINA”

299
Language support

Adaptive Server Enterprise Dynamo


“eucjis” “EUC_CHINA”
“eucksc” “EUC_KOREA”
“iso_1” “ISO_1”
“sjis” “SJIS_2”
“utf8” “UTF8”

Dynamic file site language support


For a dynamic file site to use a collation sequence other than the default, you
must specify a character set in the registry:
1 From your system’s Registry Editor, open the following file:
HKEY_LOCAL_MACHINE\SOFTWARE\Sybase\PowerDynamo
2 Create a new string value called Character Set with a string value of
the desired character set, for example “cp437”.
The following string values are valid:
“cp437”
“cp850”
“cp852”
“cp855”
“cp855”
“cp860”
“cp866”
“cp869”
“eucb5”
“eyecup”
“eucjis”
“eucksc”
“iso_1”
“sjis”
“utf8”
3 Restart the Web server.

300
APPENDIX B Language Support

Usage of multi-byte characters


You can use multi-byte characters in PowerDynamo templates and scripts in
these areas:
• DynaScript queries and comparisons
• DynaScript variables
• SQL queries and comparisons
• SQL variables
• HTML (depending on support from the browser being used)

301
Usage of multi-byte characters

302
Index

A B
abstract classes 143 browsers
access modifiers viewing Dynamo documents 27, 29
Java 151 viewing local Dynamo documents 27
accessing existing data 8
ActiveX
in Jaguar 265
using in Jaguar 266 C
ActiveX proxy automation server 266 cache
Adaptive Server Anywhere database server 289 document 223
ADO record sets 284 setting the size of 224
ADOQuery class 284 size 102, 226
agents cache size 102
and mappings 101 cacheable documents
database 102 writing 230
file 103 cachedOutputTimeOut
answering mail 211 setting a value 225
App folder 21 caching the generated output of a document 225
Application Servers CallStaticMethod method (java object) 277, 278
about 80, 94 case sensitive 106
application servers Dynamo tags 112
about 77, 79, 83, 87, 93, 94, 99, 128, 129 XML 169
configuring 83, 93, 99 catch block
application to launch when debugging 106 Java 153
arguments CDATA sections
scripts 139 about 194
URLs 138 CGI
arrays about 6, 96
Java 161 configuration 94, 96
tutorial 137 helper 96
attributes helper application 41
using 191 maximum number of connections 106
XML 191 support for 77
authoring tools System DSN 97
using with PowerDynamo 49 system path 94
character data
XML 193
class methods
about 149

1
Index

class path 102 using the same connection type 38


Java 102 connection pool
setting for Java 156 about 60, 67
class statements permanent connections 60
about 135, 140 populating 61
classes connection profiles
about 143 creating 38, 83, 92, 98, 294
compiling 147 creating a File-based connection profile 39
instances 146 creating an ODBC connection profile 38
Java 146 creating an Open Client connection profile 39
clbr110.dll 80, 94 connection timeout 106
clients setting a value for 67
about 128 connections
code editor about 60
editing a template 23 CGI 106
collation sequence 298, 299 changing 60
comments creating 60
HTML 131 creating for Jaguar 268
XML 199 creating permanent 64
comparison creating temporary 64
DBENG50 and DBSRV50 290 creating through Sybase Central 62
COMPONENT (Dynamo tag) default 60
Jaguar 271, 272 definitions 60
components 264 deleting through Sybase Central 62
Jaguar 266 dynamic file sites 37
configuration Dynamo connections 60
application server 83, 93, 99 expensive use of 218
CGI servers 94, 96 folder 21
connection timeout 106 increasing performance 60, 220
cookies 106 inherited 60
default settings 106 Jaguar 267
ISAPI 4.0 servers 85 limits 290
ISAPI servers 79 local 292
Java 156 modifying through Sybase Central 62
mappings 100 multi 13
Netscape servers 88 network 292
NSAPI servers 86 performance 222
Web servers 96 permanent 60
configuration settings 106 pool 60
Configuration Utility services 290
starting 41 setting defaults 106
configuring temporary 60
about Web sites 71 testing 62
Jaguar 106 User 60
connecting to a Web site Connections folder
sample 20 about 42

2
Index

working with 60 databases


consolidated databases connecting to the internet 5
setting up 250 copying 69
constructors minimizing calls to 219
DOMDocument object 187 remote 254
Java 152 software 82, 92, 97
control statements storing data 8
tutorial 133 XML and 184
conventions XML from 170, 172
syntax xvii datatypes for variables 133
cookies DBCLIENT 293
configuring 106 DBENG50 290
timeout 106 dbremote 256, 257
copying a database 69 message agent 255
CreateComponent method DBSRV50 290
Jaguar 274, 275 debugging 106
CreateComponent method (connection object) default application to launch 106
Jaguar 271 DOM 181
CreateComponent method (java object) declaration
Jaguar 271 variables 132
CreateObject method XML 167
Jaguar 281 declaring entities 196
CreateQuery method default
Jaguar 274 configuring 106
CreateQuery method (connection object) connections 60
Jaguar 271 general settings 106
creating ISAPI settings 106
an ODBC connection profile 38 PWS settings 108
an Open Client connection profile 39 deleting
DOMDocument objects 187 connections 62
file connection profile 39 deployment
file-based Web site 36 about 76, 77
multiple Web sites 34, 36 application server 83, 93, 99
publications 252 installation 79, 80, 87, 94
subscriptions 254 overview 77
templates 22 steps 77
user connections 62 designing your Web site 221
Web sites 19, 33 desktop
XML documents 170, 200 locating Dynamo programs 18
destructors
Java 152
disk
D storing documents on 32
data sources disk space
installing 82, 92, 97 storage efficiency 56
registry 105 Doc folder 21

3
Index

document cache replacing objects 201


how does it work? 223 DOMElement object
optimizing 223 XML elements 189, 190
performance 222 DOMNode object
setting the size of 224 XML 179
size 102, 226 double-byte characters set 298, 299
Document Object Model usage 301
about 177 do-while statements
document type definitions about 133
XML 167 DTD
documentation XML 167, 199
in HTML form 21 dycgi03.exe 94
online xvi dycsrv03.exe 94
documents dydbg03.dll 80, 94
accessing 57, 58 dyhtml03.dll 80, 94
arguments 138 DYISA03.DLL 81
copying 42 dyisa03.dll 80
creating XML 170 dynamic content
default 108 HTML tags 23
deleting 43 local viewing 27
exporting 55, 56 SQL queries 22
hierarchical storage 32 templates 22
importing 55 viewing 27, 29
moving 42 dynamic file sites
renaming 43 connections 37
storing 32 creating 36
storing on disk 32 language support 300
XML 166 dynamic Web pages 6
DOM requirements 6
about 177 Dynamo
creating documents 200 deployment 76
creating DOMDocument objects 187 script language 128
debugging 181 Dynamo and Jaguar
document trees 177 benefits of 264
examples 182 how they work together 262
features 177 Dynamo Configuration folder
interfaces 180 mappings 100
node types 180 Dynamo connections 60
nodes 179 limiting 67
DOMAttribute object Dynamo interpreter
XML elements 191, 192 about 9
DOMDocument object Dynamo tags
adding to 200 about 112
constructor 200 tutorial 113
creating 187 DynaScript
removing objects 201 about 128

4
Index

implementing 129 expressions


server-side 128 tutorial 132
tutorial 130 extensible markup language 166
dys03ent.dll 80, 94 external entities 196
dyscr03.dll 80, 94 using 197
dyxdb03.dll 80, 94

F
E fields
ECMAScript Java 148
about 128 private 151
editing protected 151
XML documents 200, 201 public 151
editing script source 131 file-based Web sites 36
elements connections 37
DOM 189 files
DOMAttribute object 191, 192 and folders 43
DOMElement object 189, 190 creating a connection profile 39
DOMNode object and 189, 191 exporting 55, 56
getElementsByTagName function 190 importing 55
nodeType value 190 storing Web pages as 43
XML 189 filter
embedding instructions ISAPI 81
about 9 finally block
supported types 9 Java 153
entities flushing the cache 226
declaring 196 folders
external 196, 197 about 42
internal 196, 197 adding 42
referencing 196 App 21
types of 196 Configuration 41
XML 196 Connections 21, 42
error checking connections 60
Java 152 copying 42
using dynamo tags 118 creating 42
XML 181 deleting 43
escaping text Doc 21
XML 195 Helper Application for CGI 41
evaluating performance 70 linked 43, 44
examples linking with directories 43
DOM 182 main contents 42
exceptions moving 42
Java 152 ODBC administrator 41
executing scripts 131 Personal Web Server 41
expensive methods and properties 234 renaming 43

5
Index

Site 21, 42 using with PowerDynamo 49


Utilities 41 HTML forms
working with 41, 42 processing 52
for statements HTML headers for functions 135
about 133 HTML template
FORMATTING (Dynamo tag) using 115 viewing output 23
formatting HTML comment tags 51 hyperlink 3
FORMATTING tag
XML 172
forms
processing 52 I
forwarding mail 211 if-else statements
function statements about 133
about 135 images
functions storing in a database 8
tutorial 134 import statement
Java 151
import statements 129
INCLUDE (Dynamo tag)
G using 121
gateways 5 inheritance
getElementsByTagName method 190 tutorial 140
GetHomeInterface method 277, 278 inherited
connections 60
inserting data
SQL_INSERT tag 123
H installation
high volume Web sites 218 Application Server 80, 94
host variables 12 installing
HTML application server 79, 87, 94
comments 131 sample database 17
content 3 Web servers 77
dynamic content 23 instance methods
embedded scripts 131 about 149
formatting tags 51 instances
generating from scripts 129 creating 136
queries in 23 Java classes 146
query tags 50, 51 instantiated
scripts in 23 definition 146
Template wizard 46 interfaces
tutorial 130 Java 152
XML converted to 182 internal entities 196
HTML documents using 197
retrieving 8 Internationalization 298, 299
storing in a database 8 interpreter
HTML editors about 9

6
Index

components of 9 about 129


ISAPI an example 158
configuration 79 arrays 161
DLL files 80, 94 cache size 102
filter 81 catch block 153
ODBC System DSN 81 classes 146
registry entries 81 classpath 102
support for 77 compiling classes 147
system path 79 configuring PowerDynamo 156
ISAPI 4.0 constructors 152
configuration 85 default VM 106
ISAPI filter directory destructors 152
default 106 Dynamo 155
error handling 152
fields 148
finally block 153
J in Jaguar 265
Jaguar interfaces 152
about 262 introduction 146
accessing components 266 method overloading 162
COMPONENT tag 272 methods 148
components 264 objects 147
connecting from Dynamo 267 try block 153
CreateComponent method (connection object) using in Jaguar 267
274 using Jaguar 163
CreateComponent method (java object) 275 Java class cache
CreateObject method 281 setting 156
CreateQuery method 274 Java VM
creating ActiveX objects 265 default 106
creating Java objects 265 setting 156
defaults 106 JavaQuery class 286
MASP method calls 265 JavaScript
ODBC connections 268 about 11
Open Client connections 269 compatible syntax 128
PowerDynamo as a client 266 tags 131
record sets 284, 286
setting a VM 106
SQL tag 271
Jaguar and Dynamo L
how they work together 262 LABEL (Dynamo tag)
Jaguar components using 117
calling from PowerDynamo 271 language
Japanese support 298, 299 summary 128
JAR files tutorials 130
Java 151 language support 298, 299
Java dynamic file sites 300

7
Index

laptop computers registry information 105


intranet access 242 storage of 105
limiting user connections 67 URL 100, 101
link 3 MASP
linked folders using in Jaguar 267
about 43, 44 MASP method calls
and replication 44 Jaguar 265
creating 43 maximum number of connections
load balancing performance 67
across processors 235 maximum number of Dynamo connections
across servers 236 setting default 106
performance 235 maximum number of pending requests
local path setting default 106
and mappings 101 maximum number of worker threads
database 102 setting default 106
file 103 Message Agent 255, 256, 257
localhost using 256
server name 74 messages
URL 74 receiving 257
sending 256
method overloading
Java 162
M methods
macros about 132, 135
text replacement 52 class 149
tutorial 138 defining 136
mail expensive use of 234
a simple application 213 instance 149
about 204 Java 148
forwarding 211 overriding 142
getting started 204 private 151
objects 204 protected 151
receiving 208 public 151
replying 211 static 149
retrieving 208 writing 148
sending 206 MIME types
SMTP host 106 configuring 109
mail list minimizing calls to the database 219
generating 208 minimizing processing time 218
main contents folder minimum number of connections
about 42 performance 67
mappings minimum number of Dynamo connections
database 102 setting default 106
defining 102, 103 mobile intranet
elements of 101 about 241, 242
file 103 capabilities 9

8
Index

requirements 243 methods 132, 136


software 243 polymorphism 143
mthr110.dll 80, 94 tutorial 135, 140
multi-byte character set 298, 299 types 147
usage 301 ODBC
multiple processors 235 about 5
multiple servers 235 creating a connection profile 38
multi-threaded data source 294
PowerDynamo 235 data sources 105
ODBC Administrator
starting from Sybase Central 41
ODBC configuration
N options 293
NAME ODBC data source
HTML comment tag 51 executing against 13
Netscape ODBC System DSN
server configuration 88 creating 292
Netscape JavaScript Authoring Guide 11 Open Client
new features xiii about 5
documentation xvi creating a connection profile 39
new operators Open Client data source
about 135 executing against 13
NO_SQL_ERROR (Dynamo tag) optimizing
using 119 document cache 223
nodes output
DOM 179 storing 225
elements 190 overloading
types of 180 methods 162
notations
XML 199
NSAPI
configuration 86, 88 P
support for 77, 88 packages
System DSN 91 Java 151
system path 86 parser
XML 177
parsing
XML 187
O passing variables 135
object-oriented programming passing vriables
Java 146 tutorial 138
objects pending requests
abstract classes 143 setting default 106
arrays 137 performance
creating 136 causes of poor performance 218
Java 147 connection pool 60

9
Index

connection timeout 67 processing of a Web site 223


connections 60 processing of scripts 218
DOM 180 profiles
example 237 and mappings 102
expensive methods and properties 234 programs
factors 222 on the desktop 18
load balancing 235 properties
scheduling 228 about 132, 135
Performance Monitor expensive use of 234
about 70 protected
statistics 70 Java access 151
Perl Java keyword 151
about 129 providers
permanent connections 60 about 100
Personal Web Server public
about 27, 29, 71, 72 Java access 151
configuration 71 publications
mappings 100 creating 252
prefixes 100 Web sites 244, 245
preparing to use 73
providers 100
requirements 73
starting 41, 73 Q
URL 74 queries
uses of 72 about 50
using 71, 72 formatting 47, 51
plbr110.dll 80, 94 in HTML 50, 51
polymorphism naming 51
about 143 pre-generation of results 57, 58
port number selecting a data source 13
configuring 108 XML from 170, 172
setting default 108 query object
PowerDynamo XML 170, 172
getting started 16 query tags 7
summary 13
PowerDynamo and Jaguar
benefits of 264
prefixes R
about 100 receiving messages 257
pregenerating output 228 record sets
prettyPrint method Jaguar 284, 286
debugging 181 referencing entities 196
private regenerating
Java access 151 Web sites 40
processing instructions registry
XML 199 data sources in 105

10
Index

Dynamo mappings 105 creating 25, 130


mappings 105 designing 218
remote databases editing source 131
setting up 254 embedded in HTML 11, 130, 131
replacing excessive processing of 218
variables 138 executing 131
replication implementing 129
Intranet 244 importing 129
intranet 241, 244, 245 maintaining 128
tutorial 246 scheduling 57, 58
Web site 244, 245 tags 131
ResultsToXMLString method tutorials 130
query object 170, 172 viewing output 25
return statements scripts and templates
about 135 performance 222
sending messages 256
Server
database 292
S Services 290
sample database advantages 290
creating a Web site 19 connections 290
installing 17 NT 105, 289
schedules starting 292
about 57, 58 sessions
removing 58 cookies 106
scheduling actions 57 setting up
scheduling a remote database 254
performance 222, 228 the consolidated database 250
scope Web server 77
Java 151 single-byte character set 298, 299
script language Site folder
arrays 137 about 42
control statements 133 SJIS 298, 299
functions 134 SMTP host
inheritance 140 default 106
objects 135 source code for scripts 131
passing variables 138 spaces
server-side 128 XML 169
summary 128 SQL (Dynamo tag)
tags 131 Jaguar 271
variables and expressions 132 using 113
scripts SQL as HTML comment tags 50
about 10, 50, 128 SQL formatting as HTML comment tags 51
arguments 139 SQL naming statements 51
cacheable 230 SQL queries
connections 60 in a template 11

11
Index

SQL Remote starting 18


and the mobile intranet 241, 242 Sybase Central editor 23
creating publications 252 syntax conventions xvii
dbremote 255, 256, 257 syntax of script language 128
Message Agent 255, 256, 257 System DSN
setting up 248 CGI 97
setting up a consolidated database 250 NSAPI 91
setting up a remote database 254 system folder
ssremote 256 about 42
tutorial 246 system path
SQL_INSERT (Dynamo tag) CGI 94
using 123 ISAPI 79
SQL_ON_ERROR (Dynamo tag) NSAPI 86
using 119
SQL_ON_NO_ERROR (Dynamo tag)
using 119
ssremote 256 T
starting tabular result sets 286
PowerDynamo 18 tags
Sybase Central 18 HTML comments 50
start-up options 293 JavaScript vs DynaScript 131
statements scripts 131
flow control 133 TCP/IP
objects 135 and the mobile intranet 243
static methods required for PowerDynamo 73
about 149 templates
statistics about 7, 10, 22, 46, 50
Performance Monitor 70 adding 46
storage adding to a Web site 22
efficiency 56 browsing 23, 49
of documents 32 cacheable 230
storing output 225 connections 60
scheduling 228 creating 11, 22, 46, 130
subscriptions editing 23, 48, 49
creating 254 embedding instructions 50
to Web sites 244, 245 excessive processing of 218
summary exporting 55, 56
PowerDynamo 13 formatting 47
Sybase Central importing 55
connecting to a Web site 20 previewing 48
connection profiles 38, 83, 92, 98 repository 13
creating a file-based Web site 36 scheduling 57, 58
creating an Adaptive Server Anywhere Web site 33 SQL queries 22
creating an Adaptive Server Enterprise Web site 35 viewing 48
navigating a Web site 21 viewing output 23, 48
Services 292 viewing output in a browser 49

12
Index

viewing source 48 U
wizard 11
UNIX
working with 46
port number 108
templates and scripts
URL
performance 222
about 3, 74, 138
temporary connections 60
accessing the sample Web site 28
testing
and the Personal Web Server 74
connections 62
case sensitive 106
text
mapping 100
replacement 12
prefixes 100
substitution 12
URL prefix
XML 193
and database mappings 102
XML elements 194
and file mappings 103
text replacement
and mappings 101
about 52
User connections 60
timeout
creating 62
connection 106
limiting 67
cookies 106
ltno connectiongt 68
toDOMDocument function
Utilities folder 41
using 187
application to launch when debugging 106
toXMLString function
connection timeout 106
using 174
cookie timeout 106
trace
Dynamo defaults 106
setting default 107
port number 108
tree
DOM documents 177
try block
Java 153 V
tutorials
arrays 137 valid documents
control statements 133 XML 167
Dynamo tags 113 variables
functions 134 data types 133
getting started with PowerDynamo 16 declaration 132
object inheritance 140 passing 52
passing variables 138 passing by value and reference 135
replication 246 replacing 138
scripts 130 tutorial 132
simple objects 135 void
variables and expressions 132 Java methods 148
writing HTML 130
type
objects 147
typing of variables 133
W
W3C standards
Document Object Model 177
wcmdpa24.dll 80, 94

13
Index

Web authoring tools about 133


using with PowerDynamo 49 white space
Web clients XML 169
about 128 WIN CGI, support for 77
Web pages wizards
dynamic 6 scheduling 228
static 6 worker threads 235
Web server interfaces setting maximum 106
about 5 writing cacheable documents 230
Web servers
about 77, 128
CGI 96
configuring 77, 96 X
Netscape 88 XML
supported interfaces 77 about 165
Web sites attributes 191
about 32 case sensitivity 169
accessing 71 CDATA sections 194
adding a template 22 character data 193
and SQL Remote 244, 245 comments 199
configuring 71 converting to HTML 182
connecting to 20, 32 creating documents 170, 200
connection profiles 38, 83, 92, 98 databases and 170, 172
contents 32 definition 166
creating file-based 36 document declaration 167
creating for Adaptive Server Anywhere 33 Document Object Model (DOM) 177
creating for Adaptive Server Enterprise 35 document type definitions 167
deleting 40 DTD 167
deploying 71, 76 Dynamo features overview 166
designing 221 DynaScript objects and 174
file-based 3 editing documents 200, 201
folders 42 elements 189, 191
management tools 10 entities 196
navigating 21 entity types 196
one per user per database 34, 36 error-checking 181
regenerating 40 escaping 195
replication of 244, 245 example 168
sample 20, 21 examples 182
structure 32 inserting into a database 184
Sybase Central 33, 35, 36 interfaces to 180
templates 22, 46 introduction 167
viewing 27 nesting of elements 169
working with 32 notations 199
well-formed documents parser 177, 187
XML 167, 168 parsing 187
while statements processing instructions 199

14
Index

queries and 170, 172


Template wizard 46
text 193
valid documents 167
well-formed documents 167, 168
white space 169
xmlEscape function
using 195

Z
zip files
Java 151

15
16

You might also like