PowerDynamo Reference PDF
PowerDynamo Reference PDF
PowerDynamo Reference PDF
PowerDynamo
Version 3.5
MC00331
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.
iii
Booleans.................................................................................. 37
Strings...................................................................................... 37
Variables......................................................................................... 38
Expressions .................................................................................... 40
Operators........................................................................................ 42
Arithmetic operators................................................................. 42
Conditional operator ................................................................ 43
String operators ....................................................................... 43
Comparison operators ............................................................. 43
Boolean operators ................................................................... 44
Bitwise operators ..................................................................... 44
Delete operator ........................................................................ 45
Void operator ........................................................................... 45
Typeof operator ....................................................................... 45
Statements ..................................................................................... 46
if-else statement ...................................................................... 46
for statement............................................................................ 47
while statement........................................................................ 47
do-while statement................................................................... 48
switch statement ...................................................................... 49
break statement ....................................................................... 50
continue statement .................................................................. 51
for-in statement........................................................................ 51
with statement.......................................................................... 52
class statement........................................................................ 52
this keyword............................................................................. 53
new operator............................................................................ 54
var statement ........................................................................... 54
function statement ................................................................... 55
return statement....................................................................... 56
import statement ...................................................................... 56
comment statements ............................................................... 58
exit statement .......................................................................... 58
Functions ........................................................................................ 60
Functions and the arguments object........................................ 61
Built-in functions ...................................................................... 62
Dynamo-specific built-in functions ........................................... 62
Objects ........................................................................................... 70
Properties and methods........................................................... 70
Object-oriented concepts......................................................... 72
Defining base classes.............................................................. 73
Extending existing classes by inheritance ............................... 74
Creating instances of classes .................................................. 76
Working with named and indexed members............................ 76
iv
Paths........................................................................................ 77
Wildcards ................................................................................. 77
v
Commit method ..................................................................... 105
Connect method .................................................................... 106
CreateComponent method .................................................... 106
CreateQuery method ............................................................. 106
Disconnect method ................................................................ 108
GetErrorCode method ........................................................... 108
GetErrorInfo method .............................................................. 109
GetState method.................................................................... 110
GetSupportedMoves method................................................. 110
Rollback method .................................................................... 111
Date object ................................................................................... 113
Date methods ............................................................................... 115
getDate method ..................................................................... 115
getDay method ...................................................................... 115
getFullYear method ............................................................... 116
getHours method ................................................................... 116
getMilliseconds method ......................................................... 116
getMinutes method ................................................................ 117
getMonth method................................................................... 117
getSeconds method............................................................... 117
getTime method..................................................................... 118
getTimezoneOffset method ................................................... 118
getUTCDate method.............................................................. 118
getUTCDay method ............................................................... 119
getUTCFullYear method ........................................................ 119
getUTCHours method............................................................ 120
getUTCMilliseconds method.................................................. 120
getUTCMinutes method......................................................... 120
getUTCMonth method ........................................................... 121
getUTCSeconds method ....................................................... 122
getYear method ..................................................................... 122
parse method......................................................................... 122
setDate method ..................................................................... 123
setFullYear method................................................................ 123
setHours method ................................................................... 124
setMilliseconds method ......................................................... 125
setMinutes method ................................................................ 125
setMonth method ................................................................... 126
setSeconds method ............................................................... 126
setTime method ..................................................................... 127
setUTCDate method .............................................................. 128
setUTCFullYear method ........................................................ 129
setUTCHours method ............................................................ 129
setUTCMilliseconds method .................................................. 130
vi
setUTCMinutes method ......................................................... 130
setUTCMonth method............................................................ 131
setUTCSeconds method........................................................ 132
setYear method ..................................................................... 132
toGMTString method ............................................................. 132
toLocaleString method........................................................... 133
toString method ..................................................................... 133
toUTCString method .............................................................. 133
valueOf method ..................................................................... 134
document object ........................................................................... 135
document properties..................................................................... 136
cachedOutputTimeOut property ............................................ 136
connectionId property ............................................................ 136
connectionName property...................................................... 137
contentType property............................................................. 137
description property ............................................................... 137
id property.............................................................................. 138
lastModified property ............................................................. 138
location property .................................................................... 139
name property........................................................................ 139
parent property ...................................................................... 140
redirect property..................................................................... 140
size property .......................................................................... 140
source property...................................................................... 141
status property ....................................................................... 141
type property.......................................................................... 142
value property ........................................................................ 142
document methods ....................................................................... 146
ExportTo method ................................................................... 146
GetDirectory method.............................................................. 146
GetGenerated method ........................................................... 147
GetServerVariable method .................................................... 147
ImportFrom method ............................................................... 149
IncludeGenerated method ..................................................... 149
Write method ......................................................................... 151
WriteLn method ..................................................................... 151
DOMAttribute object ..................................................................... 153
DOMAttribute properties............................................................... 154
name property........................................................................ 154
specified property .................................................................. 154
value property ........................................................................ 155
DOMAttribute methods ................................................................. 156
DOMCDATASection object .......................................................... 157
DOMCharacterData object ........................................................... 158
vii
DOMCharacterData properties..................................................... 159
data property.......................................................................... 159
length property....................................................................... 159
DOMCharacterData methods ....................................................... 160
appendData method .............................................................. 160
deleteData method ................................................................ 160
insertData method ................................................................. 161
replaceData method .............................................................. 161
substringData method............................................................ 162
DOMComment object ................................................................... 163
DOMDocument object .................................................................. 164
DOMDocument properties............................................................ 165
doctype property .................................................................... 165
documentElement property.................................................... 165
implementation property ........................................................ 165
DOMDocument methods .............................................................. 167
createAttribute method .......................................................... 167
createCDATASection method................................................ 167
createComment method ........................................................ 168
createDocumentFragment method ........................................ 168
createElement method........................................................... 169
createEntityReference method .............................................. 169
createProcessingInstruction method ..................................... 169
createTextNode method ........................................................ 170
getElementsByTagName method.......................................... 170
prettyPrint method ................................................................. 171
DOMDocumentFragment object................................................... 172
DOMDocumentType object .......................................................... 173
DOMDocumentType properties.................................................... 174
entities property ..................................................................... 174
name property........................................................................ 174
notations property .................................................................. 175
DOMElement object ..................................................................... 176
DOMElement property.................................................................. 177
tagName property .................................................................. 177
DOMElement methods ................................................................. 178
getAttribute method ............................................................... 178
getAttributeNode method....................................................... 178
getElementsByTagName method.......................................... 179
normalize method .................................................................. 179
removeAttribute method ........................................................ 180
removeAttributeNode method................................................ 180
setAttribute method................................................................ 181
setAttributeNode method ....................................................... 182
viii
DOMEntity object.......................................................................... 183
DOMEntity properties ................................................................... 184
notationName property .......................................................... 184
publicId property .................................................................... 184
systemId property .................................................................. 185
DOMEntityReference object ......................................................... 186
DOMImplementation object .......................................................... 187
DOMImplementation methods...................................................... 188
hasFeature method................................................................ 188
DOMNamedNodeMap object ....................................................... 189
DOMNamedNodeMap property.................................................... 190
length property....................................................................... 190
DOMNamedNodeMap methods ................................................... 191
getNamedItem method .......................................................... 191
item method ........................................................................... 191
removeNamedItem method ................................................... 191
setNamedItem method .......................................................... 192
DOMNode object .......................................................................... 194
DOMNode properties.................................................................... 195
attributes property.................................................................. 195
childNodes property............................................................... 195
firstChild property................................................................... 196
lastChild property................................................................... 196
nextSibling property ............................................................... 197
nodeName property ............................................................... 197
nodeType property................................................................. 198
nodeValue property ............................................................... 199
ownerDocument property ...................................................... 200
parentNode property.............................................................. 200
previousSibling property ........................................................ 201
DOMNode methods...................................................................... 202
appendChild method.............................................................. 202
cloneNode method................................................................. 202
hasChildNodes method ......................................................... 203
insertBefore method .............................................................. 203
removeChild method.............................................................. 203
replaceChild method.............................................................. 204
DOMNodeList object .................................................................... 205
DOMNodeList property................................................................. 206
length property....................................................................... 206
DOMNodeList methods ................................................................ 207
item method ........................................................................... 207
DOMNotation object ..................................................................... 208
DOMNotation properties............................................................... 209
ix
publicId property .................................................................... 209
systemId property .................................................................. 209
DOMNotation methods ................................................................. 210
DOMProcessingInstruction object ................................................ 211
DOMProcessingInstruction properties.......................................... 212
data property.......................................................................... 212
target property ....................................................................... 212
DOMProcessingInstruction methods ............................................ 213
The DOMText object .................................................................... 214
DOMText properties ..................................................................... 215
DOMText methods ....................................................................... 216
splitText method .................................................................... 216
file object ...................................................................................... 217
file properties ................................................................................ 218
eof property............................................................................ 218
errorNumber property ............................................................ 218
errorString property................................................................ 219
name property........................................................................ 220
mode property........................................................................ 220
file methods .................................................................................. 222
Close method......................................................................... 222
Delete method ....................................................................... 222
GetFilePtr method.................................................................. 222
Open method ......................................................................... 223
Read method ......................................................................... 223
ReadChar method ................................................................. 224
ReadLine method .................................................................. 224
Seek method.......................................................................... 224
Write method ......................................................................... 225
WriteLine method................................................................... 225
FTP object .................................................................................... 227
FTP methods ................................................................................ 228
ChangeCurrentDirectory method........................................... 228
Connect method .................................................................... 228
CreateDirectory method......................................................... 229
DeleteFile method.................................................................. 229
Disconnect method ................................................................ 230
GetErrorCode method ........................................................... 230
GetErrorInfo method .............................................................. 231
PutData method..................................................................... 231
PutDataWithAppend method ................................................. 232
PutDocument method ............................................................ 233
PutDocumentWithAppend method ........................................ 233
PutFile method....................................................................... 234
x
PutFileWithAppend method ................................................... 235
RemoveDirectory method ...................................................... 235
RetrieveCurrentDirectory method .......................................... 236
RenameFile method .............................................................. 236
RetrieveData method............................................................. 237
RetrieveDirectoryListing method............................................ 237
RetrieveDocument method .................................................... 238
RetrieveFile method............................................................... 239
RetrieveFileWithAppend method ........................................... 239
The Function object ...................................................................... 241
Function properties....................................................................... 242
length property....................................................................... 242
Function methods ......................................................................... 243
toString method ..................................................................... 243
java object .................................................................................... 244
java methods ................................................................................ 246
CreateComponent method .................................................... 246
CreateObject method............................................................. 248
CallStaticMethod method....................................................... 249
GetHomeInterface method .................................................... 249
GetUserTransaction method.................................................. 251
mailList object............................................................................... 255
mailList properties ........................................................................ 257
count property........................................................................ 257
mailList methods........................................................................... 258
Disconnect method ................................................................ 258
GetErrorCode method ........................................................... 258
GetErrorInfo method .............................................................. 259
mailPiece object (incoming).......................................................... 260
mail piece properties (incoming)................................................... 261
attachments property ............................................................. 261
body property......................................................................... 261
from property ......................................................................... 262
headers property.................................................................... 262
recipients property ................................................................. 263
replyTo property..................................................................... 263
sender property...................................................................... 264
size property .......................................................................... 265
subject property ..................................................................... 265
mail piece methods (incoming)..................................................... 267
Delete method ....................................................................... 267
Forward method..................................................................... 267
GetErrorCode method ........................................................... 268
GetErrorInfo method .............................................................. 269
xi
Redirect method .................................................................... 269
Reply method......................................................................... 270
Retrieve method .................................................................... 271
mailPiece object (outgoing) .......................................................... 273
mailPiece properties (outgoing).................................................... 274
body property......................................................................... 274
from property ......................................................................... 274
sender property...................................................................... 277
smtpHost property ................................................................. 278
body property......................................................................... 279
mailPiece methods (outgoing) ...................................................... 280
AddRecipient method ............................................................ 280
AddReplyTo method .............................................................. 282
AttachData method ................................................................ 283
AttachDocument method ....................................................... 284
AttachFile method.................................................................. 284
GetErrorCode method ........................................................... 285
GetErrorInfo method .............................................................. 286
Send method ......................................................................... 286
Math object ................................................................................... 288
Math properties............................................................................. 289
E property .............................................................................. 289
LN2 property .......................................................................... 289
LN10 property ........................................................................ 289
LOG2E property..................................................................... 290
LOG10E property................................................................... 290
PI property ............................................................................. 291
SQRT1_2 property................................................................. 291
SQRT2 property..................................................................... 291
Math methods............................................................................... 293
abs method ............................................................................ 293
acos method .......................................................................... 293
asin method ........................................................................... 293
atan method........................................................................... 294
atan2 method......................................................................... 294
ceil method ............................................................................ 294
cos method ............................................................................ 295
exp method ............................................................................ 295
floor method........................................................................... 295
log method ............................................................................. 296
max method ........................................................................... 296
min method ............................................................................ 296
pow method ........................................................................... 297
random method...................................................................... 297
xii
round method......................................................................... 297
sin method ............................................................................. 298
sqrt method............................................................................ 298
tan method............................................................................. 298
Number object .............................................................................. 300
Number properties........................................................................ 301
MAX_VALUE property ........................................................... 301
MIN_VALUE property ............................................................ 301
NaN property ......................................................................... 301
NEGATIVE_INFINITY property ............................................. 302
POSITIVE_INFINITY property ............................................... 302
Number methods .......................................................................... 303
toString method ..................................................................... 303
valueOf method ..................................................................... 303
Object object................................................................................. 304
Object methods ............................................................................ 305
toString method ..................................................................... 305
valueOf method ..................................................................... 305
recipient object ............................................................................. 306
recipient properties ....................................................................... 307
mode property........................................................................ 307
name property........................................................................ 307
query object .................................................................................. 309
query properties............................................................................ 311
connection property ............................................................... 311
cursorType property............................................................... 311
stripTrailingBlanks property ................................................... 312
query methods.............................................................................. 314
Close method......................................................................... 314
Execute method..................................................................... 314
GetColumnCount method ...................................................... 315
GetColumnIndex method....................................................... 315
GetColumnLabel method....................................................... 315
GetEmpty method.................................................................. 316
GetErrorCode method ........................................................... 317
GetErrorInfo method .............................................................. 317
GetRowCount method ........................................................... 317
GetState method.................................................................... 318
GetValue method................................................................... 318
Move method ......................................................................... 319
MoveFirst method .................................................................. 320
MoveLast method .................................................................. 321
MoveNext method.................................................................. 322
MovePrevious method ........................................................... 323
xiii
MoveRelative method ............................................................ 324
Opened method ..................................................................... 325
Refresh method ..................................................................... 325
ResultsToXMLString method................................................. 326
SetSQL method ..................................................................... 327
session object............................................................................... 329
session property ........................................................................... 331
timeOut property .................................................................... 331
site object ..................................................................................... 332
site properties ............................................................................... 334
type property.......................................................................... 334
site methods ................................................................................. 335
AskQuestion method ............................................................. 335
CopyDocument method ......................................................... 335
CreateConnection method..................................................... 336
CreateDocument method....................................................... 338
CreatePropertySheet method ................................................ 339
CreateWizard method............................................................ 343
DeleteConnection method ..................................................... 351
DeleteDocument method ....................................................... 351
GetConnection method.......................................................... 352
GetConnectionIdList method ................................................. 353
GetConnectionNameList method........................................... 353
GetDocument method............................................................ 354
GetErrorCode method ........................................................... 354
GetErrorInfo method .............................................................. 355
GetEventList method ............................................................. 356
GetRootDocument method .................................................... 357
GetState method.................................................................... 357
Include method ...................................................................... 358
OnEvent method.................................................................... 358
RenameDocument method.................................................... 360
ShowMessage method .......................................................... 360
String object.................................................................................. 361
String methods ............................................................................. 362
charAt method ....................................................................... 362
indexOf method ..................................................................... 362
lastIndexOf method................................................................ 362
split method ........................................................................... 363
substring method ................................................................... 363
substring method ................................................................... 364
toLowerCase method............................................................. 364
toString method ..................................................................... 364
toUpperCase method............................................................. 365
xiv
valueOf method ..................................................................... 365
system object................................................................................ 366
system properties ......................................................................... 367
errorNumber property ............................................................ 367
errorString property................................................................ 367
system methods ........................................................................... 368
Exec method.......................................................................... 368
GetCWD method ................................................................... 368
GetEnv method...................................................................... 368
SetEnv method ...................................................................... 369
xv
xvi
About This Book
Subject This manual is a reference for the PowerDynamo tags and the DynaScript
scripting language. For general information on using Dynamo tags and
DynaScript, see the PowerDynamo User’s Guide.
Audience This manual is written for people who require reference information;
syntax, returns, examples, and descriptions for PowerDynamo tags and
DynaScript.
Before you begin This manual assumes that you are familiar with HTML, ECMAScript (the
standardized version of JavaScript) and the operations of Web browsers
and servers.
Syntax conventions
The following conventions are used in this manual:
xvii
About this book
xviii
About this book
xix
About this book
xx
CH A PTE R 1 Dynamo Tags
About this chapter This chapter is a reference for the PowerDynamo tags, which are used to
provide dynamic content to a document.
For an introduction to Dynamo tags, see “Dynamo Tags Tutorial” in the
PowerDynamo User’s Guide.
Contents
Topic Page
Overview 2
Dynamo tags versus DynaScript 4
The Dynamo tags 5
1
Overview
Overview
Dynamo tags are similar to HTML tags, except Dynamo tags provide dynamic
content whereas HTML tags provide static content.
Dynamo tags are embedded in documents as HTML comments, which are
enclosed in <!-- and -->. Dynamo tags begin with an HTML comment
followed by the tag name, for example <!--SCRIPT.
Tags that are enclosed in HTML comment tags are ignored by everything
except the Dynamo Application Server.
The syntax for Dynamo tags is shown in the following table. Although all tags
begin the same way, they do not all end the same way.
2
CHAPTER 1 Dynamo Tags
Several Dynamo tags have attributes. Some attributes are optional, while
others must be specified for tags to work properly. These attributes give you
greater control over resulting output by allowing you to be more specific in
your requirements.
Server side
Dynamo tags are processed by the server as opposed to HTML tags which are
processed by the browser.
3
Dynamo tags versus DynaScript
4
CHAPTER 1 Dynamo Tags
COMPONENT
Function Use the COMPONENT tag to embed Jaguar components in HTML documents.
Syntax For SQL access:
<!--COMPONENT ACCESS_METHOD= SQL PKG=packagename
COMPONENT_NAME=componentname METHOD=methodname
parameter(s)
-->
For ActiveX access:
<!--COMPONENT ACCESS_METHOD= ACTIVEX PKG=packagename
COMPONENT_NAME=componentname METHOD=methodname
HOST=hostname
parameter(s)
-->
For Java access:
<!--COMPONENT ACCESS_METHOD= JAVA PKG=packagename
COMPONENT_NAME=componentname METHOD=methodname
MANAGER_URL=url USERID=id PASSWORD=password
NARROW_INTERFACE=narrowinterface
parameter(s)
-->
Attribute Description
ACCESS_METHOD Can be SQL, ACTIVEX, or JAVA. The default is
SQL. Determines the access method to be used for
the component.
PKG Name of the Jaguar package. This attribute is
required.
COMPONENT_NAME Name of the Jaguar component. This attribute is
required.
METHOD Name of the component method that is being
called. This attribute is required.
5
The Dynamo tags
Attribute Description
HOST The host and port name to use for the component
HOST=localhost:9000
This attribute is required when using the ACTIVEX
access method.
MANAGER_URL The URL to the Jaguar manager. This attribute is
optional. If an optional attribute is provided, you
must provide all attributes that proceed it.
USERID The ID for the Jaguar manager. This attribute is
optional. If an optional attribute is provided then
all attributes preceding it must be provided.
PASSWORD The password for the Jaguar manager. This
attribute is optional. If an optional attribute is
provided then all attributes preceding it must be
provided.
NARROW_INTERFACE The name of the component to which you would
like to narrow. This attribute is optional. If an
optional attribute is provided then all attributes
preceding it must be provided.
Description The COMPONENT tag is used to call and manipulate Jaguar components. The
same attributes associated with the SQL tag may be used with the COMPONENT
tag.
The default name of the query object when using the COMPONENT tag is
COMPONENT, in the same way that the default name of the query object is SQL
when the SQL tag is being used.
Example The following example calls the setMessage method of a Jaguar component.
$message is equal to saying document.value.message (passes in a
variable from a form in a previously accessed document):
<!--COMPONENT PKG=Demo_Components
COMPONENT_NAME=SharedMsg METHOD=setMessage
$message
-->
The following example calls the getMajors method of the SVUMetaData
component which is part of the SVU package included with Jaguar:
<HTML>
<!--COMPONENT PKG=SVU COMPONENT_NAME=SVUMetaData
METHOD=getMajors
-->
<!--formatting NAME=COMPONENT--><TR>
<!--/formatting-->
6
CHAPTER 1 Dynamo Tags
</HTML>
The following example calls the getMajors method of the SVUEnrollment
component which is part of the SVU package included with Jaguar. The access
method for this example is Java. The GetValue function is used to return the
appropriate datatype for each column. For more information on result sets, see
the Jaguar documentation.
<!--COMPONENT ACCESS_METHOD=JAVA PKG=SVU
COMPONENT_NAME=SVUEnrollment METHOD=getMajors
MANAGER_URL=iiop://localhost:9000 USERID=jagadmin
PASSWORD=""
-->
<!--SCRIPT
function GetValue(query, metadata, column ) {
type = metadata.getColumnType( column );
switch( type ) {
case 1: //CHAR
return query.getString( index );
case 2: //NUMERIC
case 3: //DECIMAL
return query.getBigDecimal( index,
this.metadata.getScale(index) ).floatValue();
case 4: //INTEGER
return query.getInt( index );
case 5: //SMALLINT
return query.getShort( index );
case 6: //FLOAT
case 7: //REAL
return query.getFloat( index );
case 8: //DOUBLE
return query.getDouble( index );
case 12: //VARCHAR
return query.getString( index );
case 0: //NULL
return null
case 1111: //OTHER
return query.getObject( index );
case 91: //DATE
return query.getDate( index );
case 92: //TIME
return query.getTime( index );
case 93: //TIMESTAMP
return query.getTimestamp( index );
default:
if( type < 0 ) {
7
The Dynamo tags
8
CHAPTER 1 Dynamo Tags
DATA
Function The DATA tag allows an undetermined number of rows to be returned from a
query.
Syntax <!--DATA [ QUERY=queryname ] [ NAME=colname ] -->
Attribute Description
QUERY Allows you to specify the name of a query from
which the data should be extracted. If you do not
provide the QUERY attribute, the QUERY name is
assumed to be “SQL”.
<!--DATA QUERY = myquery-->
NAME Allows you to specify the name of a column from
which the data should be extracted. This attribute is
optional. If you do not provide a NAME, sequential
DATA tags will correspond to the order of the
columns in the query result set.
<!--DATA NAME = city-->
Description When you use a query in a template, and the results are to be formatted as a
table or list, you do not know how many rows will be in the result set.
PowerDynamo uses data placeholders, formatted as comment tags, to describe
the formatting of each row of the query result set. The DATA tag is used in
conjunction with the FORMATTING tag.
The data placeholders are marked with comment tags:
<!--DATA-->
Only one row of placeholders is included within a FORMATTING statement.
The application server automatically expands the placeholder to as many rows
as required to hold the result set.
DATA tags must be between a FORMATTING start tag and a FORMATTING
end tag.
Example The following template fragment defines a table that holds the results of a
simple query:
<TABLE BORDER>
<TR>
<TH>name</TH>
<TH>color</TH>
</TR>
<!--FORMATTING--><TR>
9
The Dynamo tags
<TD><!--DATA--></TD>
<TD><!--DATA--></TD>
</TR><!--/FORMATTING-->
</TABLE>
</BODY>
</HTML>
See also “FORMATTING” on page 14.
“LABEL” on page 21.
DOCUMENT
Function The DOCUMENT tag allows you to set certain properties of the document,
such as the content type, status, whether or not the request should be redirected
to an alternate URL, and the duration of time, if any, the request output should
be cached.
Syntax <!--DOCUMENT [ CONTENT_TYPE = type ]
... [ REDIRECT = URL ]
... [ STATUS = statusCode ]
... [ CACHED_OUTPUT_TIMEOUT = minutes ] -->
Attribute Description
CONTENT_TYPE The MIME type of document being returned to the
browser, for example, image/gif.
<!--DOCUMENT
CONTENT_TYPE="image/gif"-->
This attribute is optional.
REDIRECT The name of the URL to which the current request
should be redirected.
This attribute is optional.
STATUS The status of a document where the first three
characters represent a three-digit status code and the
remaining characters contain a brief explanation of
the status. For example, 204 No Response.
This attribute is optional.
CACHED_OUTPUT_ Duration of time (in minutes) for which the generated
TIMEOUT output of a script or template will be cached. This
attribute is optional. The default is 0.
10
CHAPTER 1 Dynamo Tags
Example This example caches the document output for five minutes.
<HTML>
<TITLE>doctag.stm</TITLE>
<BODY>
<H1>Customer Phone Numbers</H1>
<!--SQL
SELECT customer.fname, customer.lname, customer.phone
FROM DBA.customer customer
-->
<!--DOCUMENT CACHED_OUTPUT_TIMEOUT = "5" -->
<TABLE BORDER>
<TR>
<TH>fname</TH>
<TH>lname</TH>
<TH>phone</TH>
</TR>
<!--formatting--><TR>
<TD><!--DATA--></TD>
<TD><!--DATA--></TD>
<TD><!--DATA--></TD>
</TR><!--/formatting-->
</TABLE>
</BODY>
</HTML>
ELSE
Function The ELSE tag allows you to manipulate script flow. If none of the preceding
conditions are true, the request associated with the ELSE statement is executed.
Syntax <!--ELSE -->
Example This example uses the IF tag to check if a condition (YearOfBirth=1970) is true
or false. If the condition is true the text “You are old enough to participate in
this promotion” displays. If the condition is false, the ELSE tag is used and
displays “You are not old enough to participate in this promotion.”
<HTML>
<!--SCRIPT
YearOfBirth=1970;
-->
<!--IF EXPR="YearOfBirth < 1979" -->
You are old enough to participate in this promotion.
<!--ELSE-->
You are not old enough to participate in this promotion.
11
The Dynamo tags
<!--ENDIF-->
</HTML>
ELSEIF
Function The ELSEIF tag can be used after an IF tag to check another condition if the
first condition associated with the IF tag was false.
Syntax <!--ELSEIF EXPR = expression -->
Attribute Description
EXPR The expression determines whether the execution of
the tag should continue or be passed over. If the
expression is true, execution will continue.
ENDIF
Function The ENDIF tag ends the IF block.
Syntax <!--ENDIF -->
Example The following example has two IF blocks that end with the ENDIF tag:
<HTML>
<!--SCRIPT
var num=22;
12
CHAPTER 1 Dynamo Tags
-->
<!--IF EXPR="num > 5" -->
<!--IF EXPR="num > 10" -->
num is greater than 10
<!--ELSEIF EXPR="num < 10"-->
num is greater than 5 and less than 10
<!--ELSE-->
num is 10
<!--ENDIF-->
<!--ENDIF-->
</HTML>
EVALUATE
Function The EVALUATE tag allows you to evaluate a DynaScript expression.
Syntax <!--EVALUATE EXPR = expression -->
Attribute Description
EXPR The expression to be evaluated. This attribute is
required.
EXECUTE
Function The EXECUTE tag allows you to execute a system command.
Syntax <!--EXECUTE COMMAND = commandname -->
Attribute Description
COMMAND The name of the command to be executed. This
attribute is required.
<!--EXECUTE COMMAND="mycommand"-->
13
The Dynamo tags
FORMATTING
Function Defines the output of a query.
Syntax For HTML formatting:
<!--FORMATTING [[FORMAT_AS="HTML" ][ BORDER = borderwidth ] [
LIST = listtype ][ MAXROWS = num ] [ NAME = stmtname ]
[STARTROW = rownum ][STRIP_TRAILING_BLANKS]] -->
<!--/FORMATTING -->
For XML formatting:
<!--FORMATTING [[FORMAT_AS="XML"]
[RESULTSET_TAG=restultsettagname][ROW_TAG=rowtagname][COLU
MN_TAG=columntagname][USE_CDATA ] [ MAXROWS = num ] [
NAME = stmtname ] [STARTROW = rownum ]
[STRIP_TRAILING_BLANKS]] -->
<!--/FORMATTING -->
Attribute Description
BORDER The width of the table border. A value of 0 creates a
table with no border. BORDER applies only if you use
the default formatting, that is, nothing between the
<!--FORMATTING--> and <!--/FORMATTING-
-> tags. If you specify both BORDER and LIST,
LIST takes precedence.
14
CHAPTER 1 Dynamo Tags
Attribute Description
LIST Use LIST if you want the query to display in a list.
LIST may be set to ORDERED, UNORDERED, or
DEFINITION.
LIST only applies if you use default formatting, that
is, you place nothing between the
<!--FORMATTING--> and <!--/FORMATTING-
-> tags. If you specify both BORDER and LIST,
LIST takes precedence.
<HTML>
<TITLE>format.stm</TITLE>
<BODY>
<H1></H1>
<!--SQL
SELECT customer.fname,
customer.lname
FROM DBA.customer customer
-->
<!--FORMATTING LIST=ORDERED-->
<!--/FORMATTING-->
</BODY>
</HTML>
MAXROWS The maximum number of times the content between
the start and end tag is to be repeated. This attribute
is optional.
Normally, the formatting tag causes the content
between the <!--FORMATTING--> and the <!--
/FORMATTING--> tag to be repeated for each row
in a query result. The addition of the MAXROWS
attribute causes the content between the start and end
tag to be repeated at most MAXROWS times.
NAME The name of the SQL statement to be formatted. If
the NAME attribute is not provided, the name “SQL”
is assumed.
If you have more than one SQL statement in a
template, you can ensure that your formatting
statements refer to the correct SQL statement by
referencing the name of the SQL statement in a
FORMATTING tag attribute. For example, this
statement formats the results of the SQL statement
ProductQuery:
<!--FORMATTING NAME=ProductQuery--
>
15
The Dynamo tags
Attribute Description
STARTROW Indicates the row of the result set to begin from when
displaying. Set STARTROW to an integer greater than
or equal to 0.
<!--FORMATTING STARTROW=4 BORDER=2
-->
FORMAT_AS May be set to HTML (the default) or XML. If set to
XML, the additional tags RESULTSET_TAG,
ROW_TAG and COLUMN_TAG can be used to generate
XML output. The BORDER and LIST attributes do
not apply.
The attributes NAME, MAXROWS, and STARTROW
apply for both XML and HTML.
RESULTSET_TAG Sets the tag surrounding the result set. If no
RESULTSET_TAG is specified, the default tag
SYBRESULTSET will be used.
This attribute applies only when FORMAT_AS=XML
ROW_TAG Specifies the tags to be used to define a table row. If
no ROW_TAG is specified, the default tag of SYBROW
will be used.
This attribute applies only when FORMAT_AS=XML
COLUMN_TAG Specifies the tags to be used to define a table
column. If no COLUMN_TAG is specified, the
column’s label will be used.
This attribute applies only when FORMAT_AS=XML
USE_CDATA Instructs Dynamo to encode characters using
CDATA to escape special XML characters. If you do
not specify USE_CDATA, characters are encoded
with the normal ampersand method.
This attribute applies only when FORMAT_AS=XML
STRIP_TRAILING_BL Strips trailing blanks from query data. By default,
ANKS this attribute is not used. This attribute is useful
when used with output generated from Adaptive
Server Enterprise or other databases that have
trailing blank characters.
Description When you use a query in a template, and want the results to be formatted as a
table or list, you do not know ahead of time how many rows are going to be in
the result set.
PowerDynamo uses data placeholders to describe the formatting of each row
of the query result set.
16
CHAPTER 1 Dynamo Tags
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.
All data placeholders must be between formatting start and end comment tags.
The start tag is:
<!--FORMATTING-->
The end tag is:
<!--/FORMATTING-->
There is no restriction on the HTML code that can be included between the
tags. The formatting comment tags have no effect on HTML that occurs
between them; they affect only the embedded instructions.
Examples This example defines a table that holds the results of a simple query:
<TABLE BORDER>
<TR>
<TH>name</TH>
<TH>color</TH>
</TR>
<!--FORMATTING--><TR>
<TD><!--DATA--></TD>
<TD><!--DATA--></TD>
</TR><!--/FORMATTING-->
</TABLE>
This example performs a query on a product table with more than 100 product
codes. Using the MAXROWS attribute results in only the first 3 product codes
being returned.
<!--SQL
select code from productlist
-->
<!--FORMATTING MAXROWS=3-->
Product code: <!--DATA-->
<!--/FORMATTING -->
17
The Dynamo tags
<!--SQL
select product.description, product.color
from product
order by product.description
-->
<!--FORMATTING FORMAT_AS="XML"
18
CHAPTER 1 Dynamo Tags
RESULTSET_TAG="MYRESULTSET" ROW_TAG="MYROW"
COLUMN_TAG="MYDESCRIPTION MYCOLOR"-->
<!--/FORMATTING-->
The output would look like this:
<MYRESULTSET>
<MYROW><MYDESCRIPTION>Cloth
Visor</MYDESCRIPTION><MYCOLOR>White</MYCOLOR></MYROW>
<MYROW><MYDESCRIPTION>Cotton
Cap</MYDESCRIPTION><MYCOLOR>Black</MYCOLOR></MYROW>
<MYROW><MYDESCRIPTION>Cotton
Shorts</MYDESCRIPTION><MYCOLOR>Black</MYCOLOR></MYROW>
<MYROW><MYDESCRIPTION>Crew
Neck</MYDESCRIPTION><MYCOLOR>Black</MYCOLOR></MYROW>
<MYROW><MYDESCRIPTION>Hooded
Sweatshirt</MYDESCRIPTION><MYCOLOR>Green</MYCOLOR></MY
ROW>
<MYROW><MYDESCRIPTION>Plastic
Visor</MYDESCRIPTION><MYCOLOR>Black</MYCOLOR></MYROW>
<MYROW><MYDESCRIPTION>Tank
Top</MYDESCRIPTION><MYCOLOR>White</MYCOLOR></MYROW>
<MYROW><MYDESCRIPTION>V-
neck</MYDESCRIPTION><MYCOLOR>Orange</MYCOLOR></MYROW>
<MYROW><MYDESCRIPTION>Wool
cap</MYDESCRIPTION><MYCOLOR>White</MYCOLOR></MYROW>
<MYROW><MYDESCRIPTION>Zipped
Sweatshirt</MYDESCRIPTION><MYCOLOR>Blue</MYCOLOR></MYR
OW>
</MYRESULTSET>
See also “DATA” on page 9.
“LABEL” on page 21.
IF
Function The ID tag allows for manipulation of script flow. If the condition associated
with the tag is true the text associated with the IF tag will be executed.
Syntax <!--IF EXPR=expression -->
<!--ENDIF -->
19
The Dynamo tags
Attribute Description
EXPR The expression that determines whether the execution of
the tag should continue or be passed over. If the
expression is true, execution will continue.
Example This example uses the IF tag to check if a condition (YearOfBirth < 1979) is
true or false. If the condition is true the text “You are old enough to participate
in this promotion” displays. If the condition is false, the else statement is used
and displays “You are not old enough to participate in this promotion.”
<HTML>
<!--SCRIPT
YearOfBirth=1970;
-->
<!--IF EXPR="YearOfBirth < 1979" -->
You are old enough to participate in this promotion.
<!--ELSE-->
You are not old enough to participate in this promotion.
<!--ENDIF-->
</HTML>
INCLUDE
Function Use the INCLUDE tag to include the generated output of another document.
The specified path may be a relative or an absolute path or the tilde (~)
character may be used.
For information on using the tilde character see “Paths” on page 77.
Syntax <!--INCLUDE NAME = filename -->
Argument Description
NAME Name of the document that is to have its output included
in the output of the current document.
20
CHAPTER 1 Dynamo Tags
LABEL
Function The LABEL tag allows you to return the column name or column alias (as
specified in the SQL query) for the colNum column.
Syntax <!--LABEL [ NAME = queryname ][ INDEX = columnindex ] -->
Attribute Description
NAME The name of the query. If you do not specify NAME, the
name “SQL” is assumed.
INDEX The column index. This attribute is optional.
Description You can use the LABEL tag alone or from within a formatting section. When
you use it within a formatting section for a query, each subsequent occurrence
of the LABEL tag increases the value of INDEX by one.
Example The following lines:
21
The Dynamo tags
<!--SQL
select name, color, size from product
-->
<!--FORMATTING-->
<!--LABEL-->: <!--DATA-->
<!--LABEL-->: <!--DATA-->
<!--LABEL-->: <!--DATA-->
<!--/FORMATTING-->
produce the following output:
name: Tee Shirt
color: White
size: Small
MAILPIECE
Function Use the MAILPIECE tag to send mail through a SMTP host.
Syntax <!--MAILPIECE TO = recipientAddress [ FROM = fromAddress ] [
SUBJECT = subject ] [ SMTPHOST = SMTPAddress ] -->
Body of the mail piece
<!--/MAILPIECE -->
Attribute Description
TO The address of the recipient of the mail piece. This
attribute is required.
FROM The address of the person sending the mail piece. This
attribute is optional.
SUBJECT The subject of the mail piece. This attribute is optional.
22
CHAPTER 1 Dynamo Tags
Attribute Description
SMTPHOST The SMTP host of the mail piece. This attribute is
optional. If not specified here, the SMTP host must be set
from the Default General Settings folder in Sybase
Central.
INDEX The column index. This attribute is optional.
Description Use the MAILPIECE tag to send mail from PowerDynamo using Dynamo tags
and a SMTP host. Enter the body of the mail piece between the start and end
mail piece tag. If you do not specify an SMTP host within the script, the default
SMTP host specified in Sybase Central is used. If you have not specified an
SMTP host in either of these places, an error occurs.
Example This example sends a mail piece with a subject and body. The SMTP host has
been set in Sybase Central:
<HTML>
<!--MAILPIECE TO="elmo@sybase.com"
FROM="fred@sybase.com" SUBJECT="My mail piece subject"-
->
This is the body of the mail piece.
<!--/MAILPIECE-->
</HTML>
SCRIPT
Function Use the SCRIPT tag to embed DynaScript in HTML documents.
Syntax <!--SCRIPT
DynaScript code
-->
Description All DynaScript scripts begin and end with a SCRIPT tag (<!--SCRIPT-->).
All information within a SCRIPT tag is invisible to any Web editing tool–in
other words, it is processed by the Dynamo application server.
Example • This example embeds the DynaScript method document.WriteLn in an
HTML document:
<HTML>
<TITLE>sample.stm</TITLE>
<BODY>
<H1>DynaScript Sample</H1>
<!--SCRIPT
23
The Dynamo tags
document.WriteLn("This is DynaScript");
-->
For more information, see “The DynaScript Language” on page 33.
SQL
Function Use the SQL tag to embed SQL statements are embedded in HTML
documents.
Syntax <!--SQL [ NAME = queryname ]
... [ CONNECTION_NAME = conname
... | CONNECTION_OBJECT = objname
... | DSN = datasource UID = userid- PWD = password
... | SERVER = servername DBN = databasename UID =
userid PWD = password ]
... [ NO_EXECUTE = queryname ]
[ NO_SQL_ERROR ]
SQL query
-->
Attribute Description
NAME Name of a query. This attribute is optional. If you do
not use NAME then the name “SQL” is assumed.
CONNECTION_NAME Name of the connection that the SQL query is to use.
This attribute is optional.
By default, SQL queries use the connection name
associated with the document in which they are
contained. The CONNECTION_NAME attribute enables
you to explicitly specify the connection name that you
would like a SQL query to use. The SQL
CONNECTION_NAME tag is used as follows:
<!--SQL
CONNECTION_NAME="MyConnection"
select * from product
-->
The Connections folder of Sybase Central contains a
list of PowerDynamo connection names.
24
CHAPTER 1 Dynamo Tags
Attribute Description
CONNECTION_OBJECT Name of the DynaScript connection object that the
SQL query is to use. This attribute is optional:
<!--SQL CONNECTION_OBJECT=connObj
select * from product
-->
NO_EXECUTE Allows you to prepare a query without executing it.
<!--SQL NAME=myQuery NO_EXECUTE
select * from product
-->
To execute the query you would do something like:
<!--SCRIPT
myQuery.Execute();
-->
DSN, UID, PWD The data source name that you would like a SQL query
to use. Using a data source name to connect to a
database bypasses both connections and connection
objects. No connection names are created or used. The
user ID and password are optional. For example:
<--SQL DSN="PowerDynamo Demo"
UID=dba PWD=sql
select * from product
-->
SERVER, DBN*, UID, The server name on which the SQL query should be
PWD executed. The connection made to the server will be an
Open Client connection.
The SERVER,DBN, UID, PWD attributes are used as
follows:
<!--SQL SERVER="myserver"
DBN="mydatabase" UID=dba PWD=sql
select * from product
-->
Using a server name to connect to a database bypasses
both connections and connection objects. No
connection names are created or used.
*DBN is optional. If you do not specify a database
name, the connection uses the user’s default database.
NO_SQL_ERROR Executes a script even if an error is encountered. No
error is displayed in the output. To display any
resulting errors, use the SQL_ON_ERROR tag.
25
The Dynamo tags
Description Use SQL queries to access and manipulate data that has been stored in a
database.
Example This example has a SQL query embedded in HTML.
<HTML>
<TITLE>sample.stm</TITLE>
<BODY>
<H1>DynaScript Sample</H1>
<!--SQL
SELECT Book.Title, Book.BookID, Book.Price
FROM DBA.Book Book
-->
</BODY>
</HTML>
SQL_INSERT
Function Performs an insert operation using the document’s parameters.
Syntax <!--SQL_INSERT TABLE= tableName [ NAME = queryname ]
... [ CONNECTION_NAME = conname
... | CONNECTION_OBJECT = objname
... | DSN = datasource UID = userid- PWD = password
... | SERVER = servername DBN = databasename UID =
userid PWD = password ]
... [ NO_EXECUTE = queryname ]
[ NO_SQL_ERROR ]
-->
Attribute Description
TABLE Name of the table that the data is to be inserted in. This
attribute is required.
NAME Name of a SQL query. This attribute is optional. If no
NAME is provided then the name “SQL” is assumed.
26
CHAPTER 1 Dynamo Tags
Attribute Description
CONNECTION_NAME Name of the connection that the SQL query is to use.
This attribute is optional.
By default, SQL inserts use the connection name
associated with the document in which they are
contained. The CONNECTION_NAME attribute enables
you to explicitly specify the connection name that you
would like a SQL insert to use. For example:
<!--SQL_INSERT
CONNECTION_NAME="MyConnection"
TABLE="product" -->
You can find a list of PowerDynamo connection in the
Connections folder of Sybase Central.
CONNECTION_OBJECT Name of the DynaScript connection object that the
SQL query is to use. This attribute is optional.
DSN, UID, PWD The data source name that you would like a SQL query
to use. Using a data source name to connect to a
database bypasses both connections and connection
objects. No connection names are created or used.
The user ID and password are optional. For example:
<!--SQL_INSERT DSN="PowerDynamo
Demo" UID=dba PWD=sql
TABLE="product"-->
SERVER, DBN*, UID, The server name on which the SQL query should be
PWD executed. Using a server name to connect to a database
bypasses both connections and connection objects. No
connection names are created or used. The connection
made to the server will be an Open Client connection.
The SERVER, DBN, UID, PWD attributes are used
as follows:
<!--SQL SERVER="myserver"
DBN="mydatabase" UID=dba PWD=sql
TABLE="product"-->
*DBN is optional. If you do not specify a database
name, the connection uses the user’s default database.
27
The Dynamo tags
Attribute Description
NO_EXECUTE Allows you to prepare a SQL query without executing
it.
<!--SQL_INSERT NAME=myQuery
NO_EXECUTE
TABLE="product"-->
To execute the query you would do something like:
<!--SCRIPT
myQuery.Execute();
-->
NO_SQL_ERROR Causes a script to execute even if an error is
encountered. No error is displayed in the output. To
display errors, use the SQL_ON_ERROR tag.
Description Use SQL_INSERT to enter data into a table. For example, lets’s say you have
created a form that asks a user to enter the information to add to the table. If the
names on the form match the names of the table columns, you can insert the
information into the table by calling a simple script that includes:
<!--SQL_INSERT TABLE=“tablename”-->
Example The following template allows a user to add a new product to the database. The
first document (newProduct.stm) collects the information and passes it to the
second document (insert.ssc) for insertion.
<HTML>
<TITLE>newProduct.stm</TITLE>
<BODY>
<H1>New Product</H1>
<P>Enter the following information</P>
<FORM METHOD=POST ACTION="insert.ssc">
<OL>
<LI><INPUT TYPE="text" NAME="id" >ID of the product<BR>
<LI><INPUT TYPE="text" NAME="name" >Name of the
product<BR>
<LI><INPUT TYPE="text" NAME="description"
>Description<BR>
<LI><INPUT TYPE="text" NAME="size" >Size<BR>
<LI><INPUT TYPE="text" NAME="color" > Color<BR>
<LI><INPUT TYPE="text" NAME="quantity" > Quantity<BR>
28
CHAPTER 1 Dynamo Tags
SQL condition
Function The SQL condition tags allow you to specify a certain condition that must be
fulfilled for the code between the conditional start and end tags to be executed.
Syntax <!--SQL_ON_type [ NAME = queryname ]-->
<!--/SQL_ON_type -->
Parameters type:
NO_ERROR | ERROR | NO_ROWS | ROWS
Attribute Description
NAME Name of a query. This attribute is optional. If you do not
provide a query name, “SQL” is assumed.
Description The following table lists the conditions that are supported by Dynamo. If the
condition is fulfilled, the source between the conditional start and end tag is
included in the output.
29
The Dynamo tags
You can use one or more types of tags (SQL, SCRIPT etc.) between a
conditional start and end tag.
Example This example provides output only if the SQL query does not produce an error.
<!--SQL
select Fname, Lname, accno, amount
from savings where accno = :account
-->
<!--SQL_ON_NO_ERROR-->
<!--SCRIPT
document.WriteLn("You have " + account.amount + "
in your account.");
-->
<!--/SQL_ON_NO_ERROR-->
SQL_ERROR_CODE
Function The SQL_ERROR_CODE tag allows you to return the current error code. If a
SQL instruction is carried out successfully an error code of 0 is returned.
Syntax <!--SQL_ERROR_CODE [ NAME = queryname ] -->
Attribute Description
NAME Name of a query. This attribute is optional. If you do not
provide a query name, “SQL” is assumed.
Example This example returns 0 as well as the output generated from the SQL query as
long as no errors are encountered during execution.
<!--SQL
30
CHAPTER 1 Dynamo Tags
SQL_ERROR_INFO
Function The SQL_ERROR_INFO tag allows you to return a description of the error
information.
Syntax <!--SQL_ERROR_INFO [ NAME = queryname ] -->
Attribute Description
NAME Name of a query. This attribute is optional. If you do not
provide a query name, “SQL” is assumed.
Example This example displays error information for a query named myQuery:
<!--SQL NAME=myQuery
select lname, fname from customer
-->
<!--SQL_ERROR_INFO NAME="myQuery" -->
<!--SCRIPT
while (myQuery.MoveNext()) {
document.WriteLn(myQuery.GetValue(1) + "," +
myQuery.GetValue(2));
}
myQuery.MoveFirst();
-->
31
The Dynamo tags
SQL_STATE
Function The SQL_STATE tag returns the current SQL state of a query.
Syntax <!--SQL_STATE [ NAME = queryname ] -->
Attribute Description
NAME Name of a query. This attribute is optional. If you do not
provide a query name, “SQL” is assumed.
<!—-SQL_STATE NAME="myquery"-->
32
CH A PTE R 2 The DynaScript Language
About this chapter The Dynamo script language DynaScript, is compatible with
ECMAScript (the standardized version of JavaScript) and provides most
of the same features. Dynamo adds its own language extensions and
predefined objects for supporting database-driven dynamic content.
This chapter summarizes DynaScript, and describes the Dynamo-specific
language extensions.
Contents
Topic Page
Overview 34
SCRIPT tag 35
Literals 36
Variables 38
Expressions 40
Operators 42
Statements 46
Functions 60
Objects 70
33
Overview
Overview
DynaScripts are built from the following language elements:
• SCRIPT tag
• literals
• variables
• expressions
• operators
• statements
• functions
• objects
Each of these elements is described in the following sections.
34
CHAPTER 2 The DynaScript Language
SCRIPT tag
DynaScripts are embedded in documents as HTML comments. An HTML
comment is marked by a <!-- tag. For example:
<!-- anything in here is a comment -->
A DynaScript is marked by a special tag inside the comment:
<!--SCRIPT insert DynaScript here
-->
Web editing tools interpret this tag as a comment, and ignore the contents that
fall between the start and end tags. This allows the Dynamo application server
to process the script.
JavaScript tags vs. JavaScript SCRIPT tags are very similar to DynaScript SCRIPT tags.
Dynamo tags JavaScript uses SCRIPT tags with this syntax:
<SCRIPT LANGUAGE="JavaScript">
DynaScript uses SCRIPT tags with this syntax:
<!--SCRIPT
-->
35
Literals
Literals
Literals are fixed values in your scripts. For example, the following are
literals:
• 123, 0x3F, 0123 (integers)
• 456.789, 3.2e-8 (floating-point numbers)
• true or false (Boolean)
• "The rain in Spain" (string)
Integers
Integers can be expressed as:
• decimal (base 10) – a sequence of digits (0-9) without a leading zero.
Example: 189
• octal (base 8) – a sequence of digits (0-7) with a leading zero.
Example: 0123
• hexadecimal (base 16) – a sequence of digits (0-9) and letters (A-F or a-
f), with a leading 0x (or 0X).
Example: 0x3F
Floating-point numbers
A floating-point number can have:
• a decimal integer
• a decimal point (“.”)
• a decimal fraction
• an exponent (“e” or “E” followed by an signed or unsigned integer)
Examples:
• 123.456
• -123E456
• .123e-456
36
CHAPTER 2 The DynaScript Language
Booleans
The Boolean (logical) type can be true or false.
Strings
A string is zero or more characters enclosed in single (’) or double (") quotes.
You must use the same kind of quote (single or double) to start and end a given
string.
Examples:
• 'Dave'
• “HAL”
• “9000”
• “Check out our \n new line of clothes.”
Control characters You can embed the following control characters in strings:
• \b backspace
• \f form feed
• \n new line
• \r carriage return
• \t tab
Escaping characters You can place quotes inside of strings by preceding them with a backslash (an
escape character).
For example:
document.WriteLn("He played \"Stairway To Heaven\" at
78 RPM.")
would yield:
He played "Stairway To Heaven" at 78 RPM.
You can insert a backslash itself by using two backslashes (one as the escape
character, one as the literal backslash).
37
Variables
Variables
You do not have to declare DynaScript variables or assign them to a fixed
datatype. A variable must have a value before you use it in an expression;
otherwise a runtime warning is generated.
Variable names Each variable is identified by a case-sensitive name. Variable names must start
with a lowercase or uppercase letter or an underscore character ( _ ).
Subsequent characters can be letters, underscores, or digits. No other
characters are allowed in variable names.
These are examples of valid variable names:
x
_magic
current_product
Product99
These are invalid variable names:
x 1
3magic
current!product
Product-99
R&D
Declaring variables Although you are not required to declare variables in DynaScript, Sybase
recommends that you do so. This is not only good programming style, but can
also avoid scoping problems with other global variables. Declare a variable
using the var keyword. This statement declares a variable named x and assigns
it a value of 35:
var x = 35;
For more information on the var statement, see “Statements” on page 46.
Datatypes Scripts use the following datatypes:
Table 2-1: Datatypes
Datatype Example
Undefined any variable that has not been assigned a value.
Numeric 1.23456 or 3
Boolean(logical) true or false
Strings “this is a string”
Null denotes a null value
Function writeln
Object site
38
CHAPTER 2 The DynaScript Language
For more information on the operators that work with these datatypes, see
“Operators” on page 42.
Assigning values to Assign a value to a variable using the = operator, just as in many other
variables programming languages. In DynaScripts, however, assigning a value to a
variable also sets the datatype of the variable.
For example, the following statement assigns the value 23 to the variable x:
x = 23 ;
If no variable named x exists in the current scope, one is automatically created.
You can later assign a different datatype to the variable x, using an assignment
statement like this:
x = "Now I am a string" ;
The following two statements successively assign a Boolean value of true and
then a null (unknown) value to the variable status:
status = true ;
status = null ;
Variable scope Variables have a scope: that is, they exist for part or all of a script or a template.
You can use global variables anywhere in a template, but you can use local
variables only within the current function.
If you do not explicitly declare a variable, it is created as a global variable. For
example, if the first time that the variable x is referred to is in a statement like
this:
x = 35 ;
then x is a global variable, and can be used (and will have the same value)
anywhere in the HTML template.
If you declare a local variable with the same name as an existing global
variable, references to that variable name will use the local variable.
39
Expressions
Expressions
Expressions are combinations of variables, literal values, operators, and other
expressions. The right side of an assignment statement is an expression.
The following statements illustrate various kinds of expressions:
surfaceArea = (2 * 3.14159 * radius * height ) ;
surfaceArea = surfaceArea + ( 2 * 3.14159 * radius *
radius ) ;
quote = "Full fathom five" + " thy father lies" ;
address = 10 + " Downing Street" ;
Name = "Moonunit " + 2 ;
Expressions and Every expression has a value and a datatype. The datatype is one of numeric,
datatypes string, Boolean, function, object, or null.
In some cases, the value of an expression is obvious; in others, it is not. For
example, (2 * 3) is clearly a numeric expression with value 6, and "To be
or not to be" is a character string. However, it is not quite so obvious what
the result of adding a number and a string is, as in the expression 10 + "
Downing Street".
40
CHAPTER 2 The DynaScript Language
41
Operators
Operators
This section describes the operators available in scripts.
Ternary, binary and Operators act on one or more expressions called operands. Operators can be
unary operators either ternary, binary or unary: ternary operators act on three expressions,
binary operators act on two expressions, and unary operators act on one.
For example, the addition operator is a binary operator, so the following is a
valid expression:
x + y ;
The increment operator (which adds one to a number) is a unary operator, so
the following is a valid expression:
x++ ;
Arithmetic operators
The following arithmetic operators are provided:
Operator Description Binary or unary
+ addition binary
- subtraction binary
* multiplication binary
/ division binary
% modulo binary
++ increment unary
-- decrement unary
- negation unary
Notes • Comparison operators can also operate on numbers, but the result is a
Boolean value.
• The increment and decrement operators can be used either before or after
the operand: both of the following are valid statements:
x++
++x
When the operator precedes the operand, the operand is decremented
before the expression is evaluated; if the operator follows the operand, the
operand is decremented after the expression is evaluated. The following
statements illustrate the difference:
42
CHAPTER 2 The DynaScript Language
x = 56 ;
y = x-- ; // Sets y to 56 and decrements x to 55
y = --x ; // Decrements x to 55 and sets y to 55
Conditional operator
The following conditional operator is provided:
Operator Description
? Conditional
String operators
The following string operators are provided:
Operator Description
+ Concatenation
+= Concatenation with assignment
Comparison operators can also operate on strings, but the result is a Boolean
value.
Comparison operators
The following comparison operators are provided:
Operator Description
== Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
43
Operators
Operator Description
!= Not equal to
These operators can act on numbers or strings, and return a Boolean (logical)
value of true or false.
Boolean operators
Boolean operators operate on Boolean (logical) expressions. The following
Boolean operators are provided:
Operator Name Description
&& And Returns true if both expression are true, false
otherwise.
|| Or Returns true if either expression is true.
! Not Returns true if the expression is false, and false if the
expression is true.
Bitwise operators
Bitwise operators treat their operands as a set of bits (zeros and ones), rather
than as decimal, hexadecimal, or octal numbers. Bitwise operators perform
their operations on such binary representations, but they return standard
numerical values.
The following bitwise operators are provided:
Operator Name Description
& AND Returns a one if both operands are ones.
| OR Returns a one if either operand is one.
^ XOR Returns a one if one but not both operands are one.
<< Left shift Shifts the first operand the specified number of
bits to the left. Excess bits shifted off to the left are
discarded. Zero bits are shifted in from the right.
>> Sign- Shifts the first operand the specified number of
propagating bits to the right. Excess bits shifted off to the right
Right shift are discarded. Copies of the leftmost bit are
shifted in from the left.
>>> Zero-fill Shifts the first operand the specified number of
right shift bits to the right. Excess bits shifted off to the right
are discarded. Zero bits are shifted in from the left.
44
CHAPTER 2 The DynaScript Language
Delete operator
The delete operator may be used to delete a property from an object or to delete
an element from an array. For example
delete x
Returns true if deletion is successful, false otherwise.
Void operator
The void operator may be used to prevent an expression from returning a value.
For example
void addVar
The void operator will evaluate its expression and then returned undefined.
Typeof operator
The typeof operator may be used to return the datatype of an expression. For
example
document.writeln( typeof(addVar) );
The typeof operator returns a string that can be one of number, string, Boolean,
object, function or undefined.
45
Statements
Statements
DynaScript includes statements for controlling script flow, manipulating
objects, and general programming. In general, these statements follow standard
C and Java syntax. They include:
• flow-control statements
• if-else
• for
• while, do-while
• switch
• object-manipulation statements
• for-in
• with
• miscellaneous statements
• var
• function, return
• import
• comments
• exit
Separating statements In DynamoScripts, you do not have to separate statements with semicolons.
if-else statement
The if-else statement tests a condition, then executes one set of statements
if the condition is true, and (optionally) another set of statements if it's false.
Syntax if ( condition ) {
statements }
[ else {
statements } ]
46
CHAPTER 2 The DynaScript Language
for statement
The for statement iterates over values in a loop while a condition is true.
Syntax for ( [ initial-expression ]; [ condition ]; [ increment expression ] ) {
statements } ;
First, the initial expression is evaluated (typically, this initializes the loop
counter).
Then, the condition is evaluated. If the condition is true, the statements are
executed, then the increment expression is executed. If the condition is false,
the loop ends.
Example The following loop iterates the variable i from 1 to 3:
for ( i = 1 ; i < 4 ; i++ ) {
document.WriteLn("Price of item #" +
i + " = " + price[ i ] );
}
while statement
The while statement tests a condition, and loops until it is false. The condition
is tested before the first iteration of the loop.
Syntax while ( condition ) {
statements } ;
47
Statements
First, the condition is evaluated. If the condition is true, the statements are
executed, and control passes back to the condition. If the condition is false, the
loop ends without executing the statements again.
Example The following loop iterates the variable i from 1 to 3:
var i = 0 ;
while ( i < 3 ) {
i++ ;
document.WriteLn("Price of item #" +
i + " = " + price[ i ] );
}
do-while statement
The do-while statement is a DynaScript extension (part of the C language,
not part of the ECMAScript standard). It is similar to the while statement,
except that it tests the condition after the first iteration of the loop.
Syntax do {
statements }
while ( condition ) ;
First, the statements are executed.
Then, the condition is evaluated. If the condition is true, control passes back to
the top of the loop. If the condition is false, the loop ends.
Example The following loop iterates the variable i from 1 to 3:
var i = 0 ;
do {
i++ ;
document.WriteLn("Price of item #" +
i + " = " + price[ i ] );
} while ( i < 3 ) ;
48
CHAPTER 2 The DynaScript Language
switch statement
The switch statement is similar to the if statement with an unconditional else
clause. The only difference between the DynaScript switch statement and the
C or Java implementation of the switch statement is that DynaScript does not
require the cases to be unique. In the event that there are multiple matching
cases only the first one will be executed. Break statements must be explicitly
stated within a switch statement to stop statement execution.
Syntax switch(expression) statement
Example The following example uses the switch statement to count the number of
vowels in a given phrase:
<!--SCRIPT switch.ssc
49
Statements
/* mainline */
countVowels( "Happy Birthday!" );
-->
break statement
The break statement ends a loop and transfers control to the statement
following the loop. A break can occur in a loop or within a switch statement.
Syntax break ;
Example The following loop iterates from 0 to 5, then outputs 25:
var i = 0 ;
while ( i < 10 ) {
if ( i == 5 ) {
break ;
}
i++ ;
}
document.WriteLn( i * i ) ;
50
CHAPTER 2 The DynaScript Language
continue statement
The continue statement ends execution of the block of statements in a loop,
and moves on to the next iteration of the loop. In a while loop, continue jumps
back to the condition. In a for loop, it jumps to the increment expression.
Syntax continue ;
Example The following loop iterates from 0 to 10, printing each number except 5:
var i = 0 ;
while ( i < 10 ) {
I++;
if ( i == 5 ) {
continue ;
}
document.WriteLn( i ) ;
}
for-in statement
The for-in statement is a variation of the for statement that iterates over the
properties and methods of an object, executing a block of statements for each
member.
Syntax for ( variable in object ) {
statements }
• variable A variable to be used as the loop iterator.
• object Any object.
• statements Any script statements. Multiple statements must be enclosed
in braces.
Example You can list the properties, property values, and methods of any object using
the following simple script, where objectName is the name of the particular
object:
<!--SCRIPT
for ( i in objectName ) {
document.WriteLn( i + " = " + objectName[i] ) ;
}
-->
51
Statements
with statement
Use the with statement for working with several properties or methods of a
given object. It establishes a default object for a block of statements. Within the
block, any property or methods that do not specify an object are assumed to be
for the default object.
Syntax with ( object ) {
statements }
• object Any object.
• statements Any script statements. Multiple statements must be enclosed
in braces.
Example The following script sets the name, title, and managerName of an object
called currentEmployee:
with currentEmployee {
name = "Moe Smithers" ;
title = "Bartender" ;
managerName = "Barney Burns" ;
}
class statement
The class statement is a DynaScript extension that provides a clear way of
explicitly declaring an object type (a class). It also provides an optional way of
deriving the new class from an existing class.
Syntax class newClassName ( [ param ] [ , param, ... ] ) [ extends
parentClassName ( [ parentParam ] [ , parentParam, ... ] )] {
statements } ;
• newClassName [variable] The name of the new class.
• param [variable] Parameters of the new class (typically for assigning
values to properties). If you're extending an existing class, the parameter
list typically includes new parameters (for the new class) and inherited
parameters (for the parent class).
• parentClassName [variable] The name of the existing class that the new
class is derived from.
• parentParam [variable] Parameters for the parent class. Typically these
are a subset of the param list. The parent constructor is executed using
these parameters before the constructor of the new class is executed.
52
CHAPTER 2 The DynaScript Language
this keyword
The this keyword refers to the current object (in a method, the calling object)
and is typically used as the qualifier for that object's properties and methods.
Syntax this.memberName
• memberName [variable] Any property or method of the object.
Example class product(id, name, size, color,
quantity, price) {
this.id = id ;
this.name = name ;
53
Statements
this.size = size ;
this.color = color ;
this.quantity = quantity ;
this.price = price ;
}
new operator
The new operator creates an instance of a class using the given parameters.
Syntax objectName = new className ( [ param ] [ , param, ... ] ) ;
• objectName [variable] The name of the new object instance.
• className [variable] The name of an existing class.
• param [variable | literal] A value for the corresponding class parameter.
Example var currentProduct = new product(600,
"Sweatshirt", "Large", "Green", 39, 24.00 ) ;
var statement
The var statement declares a variable, optionally assigning it an initial value.
The scope of a variable is the current function or (for variables declared outside
a function) the current script.
You do not have to declare variables using var; you can declare them
implicitly by assigning them values on the fly. However, it is good coding
practice to always use var. In addition to making your code more readable, this
can avoid scoping problems. For example, if you start using an apparently local
variable inside a function without declaring it, you could be inadvertently
referencing an existing global variable of that name, with unexpected results.
Syntax var varName [ = value ] [ ..., varName [ = value ] ] ;
• varName [variable] The name of the variable.
• value [variable | literal] A value for the variable.
Example var height = 42, width = height / 2 ;
54
CHAPTER 2 The DynaScript Language
function statement
The function statement declares a function, which is a set of instructions that
you can call from anywhere in a script.
A function can accept string, number, or object parameters.
• Simple arguments such as strings and numbers are passed to functions by
value. Any change made to the argument inside the function is not passed
back to the calling environment.
• Objects can be passed to functions, and are passed by reference, so that any
change made to an object property inside a function is passed back to the
calling environment. Since arrays are a special case of objects, they are
passed by reference.
• When the function is called, the actual parameters (arguments) are stored
in the arguments array property of the function. This array indexes all
actual parameters starting at 0. For example, you could access the third
parameter of a function called MyFunction as
MyFunction.arguments[2].
You can access the total number of actual parameters as
arguments.length.
Variable number of Functions can accept more or less parameters than are formally declared for
arguments them. Extra parameters are simply appended to the arguments array for the
function.
Returning a value The function can return a value to the caller by including a return statement.
Syntax function name ( [ param ] [ , param, ... ] ) {
statements }
• name [variable] The name of the function.
• param [variable] A name for a formal parameter.
Example 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 ) ;
}
}
55
Statements
return statement
The return statement is used inside a function to return a value to the caller
of the function.
Syntax return expression ;
• expression [expression] The value to return to the caller.
Example You could define the following order function:
function OrderItem( 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 ) ;
}
}
...then call the function in an expression:
if ( OrderItem(desiredQuantity) == true ) {
document.WriteLn("Ordered successfully");
} else {
document.WriteLn("Order failed - stock is low");
}
import statement
The import statement is a DynaScript extension that, when executed, imports
the text of another script at the statement's position in the current script. This
allows you to store common functions in a separate script, then use them in
your other scripts by importing that script.
Execution context If you do not state and context or if you specify the newContext keyword
when using the import statement, the imported script code will run in its own
execution context. Only if you specify the useContext keyword will the
imported code share the same variable space as the document into which it was
imported. For example, imported code cannot normally reference the
document or site objects, since they do not exist in its (special) execution
context. Using the useContext keyword makes theses objects available to the
imported code. Objects such as Math, Date and Number are still available to
be referenced by imported code that uses the newContext keyword.
56
CHAPTER 2 The DynaScript Language
<!--SCRIPT importee.ssc
document.writeln( "Start importee.ssc" );
var narf = "This is from importee.ssc";
document.writeln( foo );
document.writeln( "End importee.ssc" );
-->
57
Statements
End main.ssc
comment statements
Comment statements are ignored by the script interpreter.
There are two ways to indicate comment statements in scripts:
• Anything inside the character pairs /* and */ is a comment. For example:
/* This is a comment
that extends
over three lines */
• Any characters on a line following the character pair // constitute a
comment. Characters on the next line are interpreted by the script
interpreter. For example:
x = 365 ; // Explanatory remarks can be placed here.
y = x / 12 ;
exit statement
The exit statement stops processing the current document without affecting
previous output. Portions of the document following the exit statement are not
processed.
The following example template checks a user's password. If it is incorrect, it
notifies the user and exits from the script. Any output generated before the exit
statement was encountered still displays.
<HTML>
<TITLE>Secret Information</TITLE>
<BODY>
<!--SCRIPT
if( document.value.password != "halibut" ) {
document.writeln( "<H2>Invalid
password!</H2></BODY></HTML>" );
exit;
}
-->
<H1>Secret Information</H1>
<!--SQL
select color from product
-->
58
CHAPTER 2 The DynaScript Language
<!--formatting-->
<!--/formatting-->
</BODY>
</HTML>
59
Functions
Functions
You can define and use functions in scripts. This allows you to encapsulate a
set of instructions once in a document as a function, then use it several times
throughout the document (by calling the function). For example:
<!--SCRIPT
function addVar( x, y, z )
{
return x + y + z;
}
document.writeln( addVar( 1, 2, 3 ) );
-->
60
CHAPTER 2 The DynaScript Language
You can define functions inside a particular document. For more flexibility,
you can define them in a separate script, which can then be referenced by any
documents that use the function (using the import statement).
For more information on the function, return, and import statements, see
“Statements” on page 46.
document.writeln( addVar( 1, 2, 3 ) );
-->
would return
1
{ 1, 2, 3 }
6
The arguments object has a length property which contains the number of
variables passed to the function.
The arguments object also has a callee property which may be used for
recursion. The following example creates a function dynamically and then
recursively calls the same function from within the function body:
<!--SCRIPT
f = new Function ( "n", " if(n == 1) return 1; return
n * arguments.callee(n-1);" );
document.WriteLn( f(4) );
-->
61
Functions
Built-in functions
Dynamo supports the following ECMAScript built-in functions:
62
CHAPTER 2 The DynaScript Language
63
Functions
</BODY>
</HTML>
The second template, convert.stm, is called from the previous template and
creates an instance of the ActiveX Object
"SybaseDemoObject.TempConvert". This template uses the methods
of the SybaseDemoObject.TempConvert to calculate the request from
the first template.
<HTML>
<TITLE>convert.stm</TITLE>
<BODY>
<H1>Temperature</H1>
<P>Your answer is: </P>
<!--SCRIPT
var conversionType = document.value.theType;
var tempnumber = document.value.temperature;
var DemoObj =
CreateObject("SybaseDemoObject.TempConvert");
if ( conversionType == "CtoF" ){
// ConvertCtoF is a method of the
// SybaseDemoObject.TempConvert object
var c = DemoObj.ConvertCtoF(tempnumber);
document.WriteLn( "The Celsius temperature
of " + tempnumber + " is " + c + " on the Fahrenheit
scale." );
} else {
// ConvertFtoC is a method of the
// SybaseDemoObject.TempConvert object
var f = DemoObj.ConvertFtoC(tempnumber);
document.WriteLn( "The Fehrenheit temperature
of " + tempnumber + " is " + f + " on the Celsius
scale." );
}
-->
</BODY>
</HTML>
64
CHAPTER 2 The DynaScript Language
65
Functions
document.writeln( domDoc.prettyPrint() );
-->
66
CHAPTER 2 The DynaScript Language
<year>1998</year>
<color>blue</color>
<owner><name>Rick Smith<name>
<address>21 King St. Waterloo<address></owner>
<work>new brakes</new brakes>
The following example of the toXMLString built-in function sets use_CDATA
to true and specifies which tag to use if a member has not been named:
<!--SCRIPT
document.WriteLn("Parts for order");
part1.shop = "Jim & Son’s Autobody";
part1.partname = "strut";
part1.sku = "123";
parts[0] = part1;
parts[1] = part2;
x = toXMLString(parts, true, "part");
document.WriteLn( x);
-->
The output from the above example would look something like:
Parts for Order
<part>
<shop><![CDATA[Jim & Son’s Autobody]]></shop>
<partname>strut</partname>
<sku>123</sku>
</part>
<part><shop><![CDATA[Jim & Son’s Autobody]]></shop>
<partname>clutch</partname>
<sku>456</sku>
</part>
67
Functions
• “binary”
• “function”
• “null”
The following example stores multiple document values of the same name
as a DynaScript object. The typeof( ) function is used to determine
what values have been received:
<!--SCRIPT SelectMultipleAction.ssc
/* e.g. URL http://localhost/site/SelectMultiple
Action.ssc?color=Red&color=Green&color=Blue */
-->
For more information about working with multiple selection lists, see
“value property” on page 155.
68
CHAPTER 2 The DynaScript Language
69
Objects
Objects
DynaScript is object-oriented, which means it supports objects and the
fundamental object-oriented concepts of:
• encapsulation An object contains both properties and the methods that
manipulate those properties.
• polymorphism Different kinds of objects can respond to the same
message in their own ways (by using their own methods of that name).
• inheritance You can define new objects that extend the capabilities of
existing objects (by inheriting existing properties and methods and then
adding new ones).
You can define your own custom object types (also called classes). You can
then create as many instances of each class as you require.
Predefined objects DynaScript also includes a number of predefined objects that simplify the task
of developing database-driven content. For more information, see “DynaScript
Predefined Objects” on page 79.
Case-sensitive names
The names of object properties and methods are case-sensitive.
Properties A property is a variable in an object that describes some part or attribute of the
object.
A property can be any datatype. Objects can contain other objects as properties.
Property names must be unique within the scope of the class and its ancestor
classes (if any).
You can access an object property using standard dot notation:
objectName.propertyName
For example, for an object called sampleEmployee, you could assign
"Homer" as the value of its name property:
sampleEmployee.name = "Homer";
70
CHAPTER 2 The DynaScript Language
Methods A method is a function in an object that acts on one or more properties of the
object.
Name scoping depends on how the method was defined:
• If a method is defined inline (within the class definition), its name must be
unique within the scope of the class. If it has the same name as a method
in one of its ancestor classes, it overrides (redefines) that method for
instances of its own class.
• If a method is defined as a global function (outside the class definition), its
name must be unique within the scope of the current script.
You can call an object method using standard dot notation:
objectName.MethodName()
You can define objects as conventional arrays that use integer indexes. For
example:
price[0] = 19.95
price[1] = 42.99
You can also use text literals as indexes. In this case, the array notation simply
becomes an alternative to the dot notation for object properties. For example:
sampleEmployee.name
can also be referenced as
sampleEmployee["name"]
71
Objects
Object-oriented concepts
Encapsulation By using an object container to associate properties with the methods that
affect them, you can encapsulate the behavior of a conceptual object in one
place. This can make testing, maintenance, and subsequent enhancements
much easier.
You also avoid having name conflicts for your properties and methods, since
instead of being declared globally (where each name must be unique), they are
declared as part of an object (where they need be unique only within the scope
of the object itself).
Polymorphism Polymorphism is the ability of different classes of objects to respond to a
particular method call in their own ways.
For example, suppose that you define two object classes called
salariedEmployee and hourlyEmployee. Each type has its own
PrintAllInfo method that prints employee information a certain way.
To print information for an employee, you simply call the PrintAllInfo
method for the object. Depending on whether the employee is salaried or
hourly, the corresponding PrintAllInfo method will be called
automatically. If you add more classes of employees, they can redefine their
own PrintAllInfo methods. The actual code that calls PrintAllInfo does
not need to be changed to accommodate the new object types.
Polymorphism is particularly powerful when used in conjunction with
inheritance.
Inheritance ECMAScript lets you define new classes from scratch, but it does not support
inheritance – the ability to create new classes of objects that are extensions of
existing classes.
The simplest form of inheritance is single inheritance, in which a new class
can inherit properties and methods from a single parent class.
72
CHAPTER 2 The DynaScript Language
DynaScript adds single inheritance in the form of the class statement. You
can derive a new class from an existing class, adding new properties and
methods (or overriding existing properties and methods) as you require.
Inheriting objects also means that you can take better advantage of
polymorphism, since derived classes can override (redefine) existing methods
defined by their parent class, without needing to change other code that calls
these methods.
73
Objects
this.PrintAllInfo = PrintAllInfo;
}
For more information, see “function statement” on page 55.
Using the class To define a base object using the class statement, declare the class name and
statement the property names, assign the property values, and define a method that
references the function.
As in the function-declaration technique, you can define methods inline or
assign method names to existing global functions.
The following example defines the same employee class used in the function-
declaration example:
class employee(name, title, managerName) {
this.name = name;
this.title = title;
this.managerName = managerName;
function PrintAllInfo() {
document.WriteLn("Name: " + this.name);
document.WriteLn("Title: " + this.title);
document.WriteLn("Reports to: " +
this.managerName);
}
this.PrintAllInfo = PrintAllInfo;
}
The only difference in the two examples is the class keyword itself. The main
reason for using the class statement is for the additional ability to define
derived objects.
For more information, see “class statement” on page 52.
74
CHAPTER 2 The DynaScript Language
75
Objects
76
CHAPTER 2 The DynaScript Language
Paths
You can use both relative and absolute paths when working with DynaScript
objects. You can also use a tilde(~) with an absolute path instead of the Web
site name or Personal Web Server mapping for the following:
• site.GetDocument()
• site.CreateDocument()
• site.DeleteDocument()
• site.CopyDocument()
• site.RenameDocument()
• site.Include()
• the INCLUDE tag
• the import() statement
For example, if the name of the root document in your Web site is Product and
your mapping to that Web site is named product_site and you wanted to open
the document price.stm, you could use:
site.GetDocument("/Product/price.stm");
site.GetDocument("/product_site/price.stm");
The first example would work only from within Sybase Central while the
second example would work only through a Web server. Using the tilde allows
this statement in either situation:
site.GetDocument("~/price.stm");
The above-listed methods, tags, and statements also handle ..\ in a directory
path, which specifies that the path is relative to the current directory but is back
one level. Each occurrence of ..\ in a directory path specifies that the target
directory is back another level. If the number of occurrences of ..\ in a directory
path causes the directory to go back further than /Site, an error occurs.
Wildcards
There are two wildcard characters that you can use with
site.DeleteDocument(docName) and
document.GetDirectory([fileMask, sortOrder]): * and ?.
77
Objects
78
CH A PTE R 3 DynaScript Predefined Objects
About this chapter This chapter lists the predefined objects supported by PowerDynamo.
These predefined objects include ECMAScript objects, DOM objects for
XML, and DynaScript-specific objects that offer useful properties and
methods for developing Web sites.
Contents
Topic Page
Array object 81
attachment object 86
Boolean object 93
connection object 95
Date object 113
document object 135
DOMAttribute object 153
DOMCharacterData object 158
DOMComment object 163
DOMDocument object 164
DOMDocumentFragment object 172
DOMDocumentType object 173
DOMElement object 176
DOMEntity object 183
DOMEntityReference object 186
DOMImplementation object 187
DOMNamedNodeMap object 189
DOMNode object 194
DOMNodeList object 205
DOMNotation object 208
DOMProcessingInstruction object 211
The DOMText object 214
file object 217
FTP object 227
The Function object 241
java object 244
79
Topic Page
mailList object 255
mailPiece object (incoming) 260
mailPiece object (outgoing) 273
Math object 288
Number object 300
Object object 304
recipient object 306
query object 309
session object 329
site object 332
String object 361
system object 366
80
CHAPTER 3 DynaScript Predefined Objects
Array object
Object Enables the creation and manipulation of arrays.
Standard: ECMAScript
Syntax To use an Array property:
Array.propertyName
To use an Array method:
Array.MethodName( parameter )
The Array object has both a built-in object as well as constructors that allow
users to create instances of an Array object. When referring to Array in the
syntax of this chapter, we are referring to an instance of an array, not the built-
in Array object.
Description Calling an array as a function or as a constructor has equivalent results – both
create and initialize a new Array object.
To create an Array with a constructor:
myArray = new Array( [item0 [, item1 [, item2...]]] );
myArray = new Array( length )
It is generally more efficient to create an array with the number of elements you
expect to use (or approximately), rather than growing the Array dynamically.
Example • This example creates an array, fills it, then displays the contents:
<!--SCRIPT
myArray = new Array(4)
myArray[0]= "number one";
myArray[1]= "number two";
myArray[2]= "number three";
myArray[3]= "number four";
document.WriteLn(myArray);
-->
81
Array properties
Array properties
The Array object has this property:
length property
Syntax Array.length
Description Returns a value one higher than the highest element in the array.
Return Integer.
Example • This example returns 7:
<!--SCRIPT
myArray = new Array();
myArray[0] = "carrots";
myArray[1] = "corn";
myArray[6] = "green beans";
document.WriteLn( myArray.length );
-->
82
CHAPTER 3 DynaScript Predefined Objects
Array methods
The Array object has these methods:
join method
Syntax Array.join( separator )
Description Converts the elements of the array into strings which are then concatenated. If
no separator is given, commas will separate the strings.
Return String object.
Example This example lists the elements of the Array separated by the
“&” character:
<!--SCRIPT
myArray = new Array();
myArray[0] = "carrots";
myArray[1] = "corn";
myArray[2] = "green beans";
myArray[3] = "celery";
document.WriteLn( myArray.join( " & " ) );
-->
The output from this example is:
carrots & corn & green beans & celery
reverse method
Syntax Array.reverse( )
Description Reverses the order of the elements in the array.
Return Array object.
Example This example reverses and displays the content of the myArray array:
<!--SCRIPT
myArray = new Array();
myArray[0] = "carrots";
myArray[1] = "corn";
myArray[2] = "green beans";
myArray[3] = "celery";
document.WriteLn( myArray.reverse());
-->
83
Array methods
sort method
Syntax Array.sort( [compareFunction] )
Description Sorts the elements of an array. A compareFunction can optionally be used to
sort the array or the default may be used. The compare function takes two
arguments a, b. If
•a < b the return will be negative
•a = b the return will be 0
•a > b the return will be positive
Return Array object.
Example This example sorts the array alphabetically and displays the results:
<!--SCRIPT
myArray = new Array();
myArray[0] = "carrots";
myArray[1] = "corn";
myArray[2] = "green beans";
myArray[3] = "celery";
document.WriteLn( myArray.sort() );
-->
toString method
Syntax Array.toString( )
Description Converts the elements of the array to concatenated strings, separated by
commas.
Return String.
Example This example converts the array elements to strings and displays them:
<!--SCRIPT
myArray = new Array();
myArray[0] = "carrots";
myArray[1] = "corn";
myArray[2] = "green beans";
myArray[3] = "celery";
84
CHAPTER 3 DynaScript Predefined Objects
document.WriteLn( myArray.toString() );
-->
85
attachment object
attachment object
Object Represents file, data, or document attachments to incoming mail pieces.
Syntax attachment.propertyName
Description Use the attachment object to manipulate incoming mail piece attachments. You
can view and save attachments in different formats.
Example This script saves a mail piece file attachments to a hard drive:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistitem = mlist[12];
mlistitem.Retrieve();
document.WriteLn( "subject: " + mlistitem.subject );
document.WriteLn( "size: " + mlistitem.size );
document.WriteLn( "body: " + mlistitem.body );
document.WriteLn( "sender: " + mlistitem.sender );
for( i in mlistitem.attachments ) {
attach = mlistitem.attachments[i];
filesave = attach.SaveAsFile(
"g:\\temp\\Dynamo\\" + attach.name );
}
if (filesave) {
document.WriteLn( "The file has been saved." );
}
mlist.Disconnect();
-->
See also “mailList object” on page 255
“mailPiece object (incoming)” on page 260
“mailPiece object (outgoing)” on page 273
“recipient object” on page 306
86
CHAPTER 3 DynaScript Predefined Objects
attachment properties
The attachment object has these properties:
mimeType property
Syntax attachment.mimeType
Attributes This property is read-only.
Description The MIME type of the attachment, for example “image/gif”.
Return String.
Example This example retrieves a mail piece with a subject heading of “The attachment
object” and displays the attachment name and MIME type.
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
for (i in mlist) {
inPiece=mlist[i];
if (inPiece.subject == "The attachment object") {
inPiece.Retrieve();
document.WriteLn( "body: " + inPiece.body );
document.WriteLn( "sender: " + inPiece.sender
);
document.WriteLn( "attachment name: " +
inPiece.attachments[0].name);
document.WriteLn( "attachment Mime type: " +
inPiece.attachments[0].mimeType);
}
}
mlist.Disconnect();
-->
name property
Syntax attachment.name
Attributes This property is read-only.
Description The name or description of the attachment, if present. This is extracted from
MIME headers.
Return String.
87
attachment properties
Example This example uses the name property to save the file with the same name as the
attached file.
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistitem = mlist[12];
mlistitem.Retrieve();
document.WriteLn( "subject: " + mlistitem.subject );
document.WriteLn( "size: " + mlistitem.size );
document.WriteLn( "body: " + mlistitem.body );
document.WriteLn( "sender: " + mlistitem.sender );
for( i in mlistitem.attachments ) {
attach = mlistitem.attachments[i];
filesave = attach.SaveAsFile(
"g:\\temp\\Dynamo\\" + attach.name );
}
if (filesave) {
document.WriteLn("The file has been saved.");
}
mlist.Disconnect();
-->
88
CHAPTER 3 DynaScript Predefined Objects
attachment methods
The attachment object has these methods:
GetContents method
Syntax attachment.GetContents( )
Description Returns the content of the attachment.
Return String or binary.
Example This example retrieves a mail piece with an attachment and displays the
attachment:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com ",
"dynamo7@dbsrv.sybase.com");
mlistitem = mlist[6];
mlistitem.Retrieve();
attach = mlistitem.attachments[0];
contents = attach.GetContents();
if( attach.GetErrorCode() != 0 ) {
document.WriteLn( "Error: " +
attach.GetErrorInfo() );
} else {
document.contentType = attach.mimeType;
document.writeln( contents );
}
mlist.Disconnect();
-->
See also “autoCommit property” on page 97.
“connected property” on page 97.
GetErrorCode method
Syntax attachment.GetErrorCode( )
Description Returns a code representing the last error that occurred.
89
attachment methods
Return Integer.
Example This example retrieves a mail piece with an attachment and displays the
attachment:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com ");
mlistitem = mlist[6];
mlistitem.Retrieve();
attach = mlistitem.attachments[0];
contents = attach.GetContents();
if( attach.GetErrorCode() != 0 ) {
document.WriteLn( "Error: " +
attach.GetErrorInfo() );
} else {
document.contentType = attach.mimeType;
document.writeln( contents );
}
mlist.Disconnect();
-->
GetErrorInfo method
Syntax attachment.GetErrorInfo( )
Description Returns a string containing a meaningful error message.
Return String.
Example This example retrieves a mail piece with an attachment and displays the
attachment:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com ");
mlistitem = mlist[6];
mlistitem.Retrieve();
attach = mlistitem.attachments[0];
contents = attach.GetContents();
if( attach.GetErrorCode() != 0 ) {
document.WriteLn( "Error: " +
attach.GetErrorInfo() );
} else {
90
CHAPTER 3 DynaScript Predefined Objects
document.contentType = attach.mimeType;
document.writeln( contents );
}
mlist.Disconnect();
-->
SaveAsDocument method
Syntax attachment.SaveAsDocument ( document_name [,
fail_if_document_exists] )
Description Saves the content of the attachment as a PowerDynamo Web site document. If
fail_if_document_exists is set to true (the default), SaveAsDocument
fails if the document already exists. If set to false the document is overwritten.
Return Boolean.
Example This example saves an attachment as a Dynamo document:
<!--SCRIPT
mlist = new MailList ( "mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com" );
mlistitem = mlist[12];
mlistitem.Retrieve();
document.WriteLn( "subject: " + mlistitem.subject );
document.WriteLn( "size: " + mlistitem.size );
document.WriteLn( "body: " + mlistitem.body );
document.WriteLn( "sender: " + mlistitem.sender );
for( i in mlistitem.attachments ) {
attach = mlistitem.attachments[i];
filesave = attach.SaveAsDocument(
"g:\\temp\\Dynamo\\file.txt" );
}
if (filesave) {
document.WriteLn( "File has been saved" );
}
document.writeln( mlistitem.attachments );
mlist.Disconnect();
-->
91
attachment methods
SaveAsFile method
Syntax attachment.SaveAsFile ( file_path [, fail if file exists] )
Description Saves the content of the attachment to the file system. If
fail_if_file_exists is set to true (the default), then SaveAsDocument
fails if the document already exists. If set to false, the file is overwritten.
Return Boolean.
Example This example retrieves a mail piece and saves the attachments as files:
<!--SCRIPT
mlist = new MailList ( "dbsrv.sybase.com", "dynamo7",
"dynamo", "dynamo7@dbsrv.sybase.com" );
num = mlist.count
document.WriteLn("There are " + num + " messages in
the mail box");
mlistitem = mlist[12];
mlistitem.Retrieve();
document.WriteLn( "subject: " + mlistitem.subject );
document.WriteLn( "size: " + mlistitem.size );
document.WriteLn( "body: " + mlistitem.body );
document.WriteLn( "sender: " + mlistitem.sender );
for( i in mlistitem.attachments ) {
attach = mlistitem.attachments[i];
filesave = attach.SaveAsFile( "g:\\temp\\Dynamo\\"
+ att.name );
}
if (filesave) {
document.WriteLn( "It should have worked" );
}
document.writeln( mlistitem.attachments );
mlist.Disconnect();
-->
92
CHAPTER 3 DynaScript Predefined Objects
Boolean object
Object Allows you to create an object with a value of true or false. The Boolean object
has no properties.
Standard: ECMAScript
Syntax Boolean.MethodName( parameter )
Description You can set the Boolean object’s value when you create the object, or at a later
date. To create a Boolean object, use this constructor:
BoolObj = new Boolean ( [value] );
If you provide a value, the Boolean object will contain that initial value. If you
do not provide a value, the object will have the value of false.
Example This example creates a Boolean object and sets the value as false:
<!--SCRIPT
myBool = new Boolean( false );
document.WriteLn( myBool );
-->
93
Boolean methods
Boolean methods
The Boolean object has these methods:
toString method
Syntax Boolean.toString( )
Description Returns the value of the Boolean as a string.
Return String.
Example This example returns the value of the Boolean as a string:
<!--SCRIPT
myBool = new Boolean(true);
document.WriteLn(myBool.toString() );
-->
valueOf method
Syntax Boolean.valueOf( )
Description Returns the value of the Boolean object.
Return Boolean.
Example This example returns the value of the Boolean object:
<!--SCRIPT
myBool = new Boolean(true);
document.WriteLn(myBool.valueOf() );
-->
94
CHAPTER 3 DynaScript Predefined Objects
connection object
Object Describes a connection to a database.
Syntax To use a connection’s property:
connection.propertyName
To use a connection’s method:
connection.MethodName( parameter )
Description Dynamo requires two types of connections:
• Dynamo connections A connection to a data source capable of hosting a
Dynamo Web site (for example, Adaptive Server Anywhere).
• User connections definitions A connection to a data source that provides
the actual database content to the Web site.
When you create a Dynamo Web site, your Dynamo connection becomes the
default for your user connection as well. This connection information is
encapsulated in the <default> connection object.
You can use Sybase Central to change the default connection associated with a
script. For a detailed explanation of connections, see “Working with
connections” in the PowerDynamo User’s Guide.
If your database content is stored in one or more other data sources, you can
then create more connection objects to manage those sources.
There are two ways to create connection objects. To create a permanent User
connection that is added to the Connections folder, use this format:
For an ODBC connection:
site.CreateConnection( connName, description,
dataSource [,userName, password, ODBC,
connectParameters] )
For an Open Client connection:
site.CreateConnection( connName, description,
server, userName, password, Open Client [,database] )
The preferred method of creating a permanent user connection, however, is to
use Sybase Central to create it from within a script. For additional information,
see “Creating, deleting, modifying, and testing User connections” in the
PowerDynamo User’s Guide.
For a temporary connection which lasts only as long as your script is executing,
use the following:
95
connection object
chained mode
Open Client connections are automatically set to CHAINED = ON which is
equal to autoCommit=false. Use autoCommit property to set chained mode to
off (autoCommit=true).
The site object allows you to manipulate your Web site connections. For
information on CreateConnection, DeleteConnection or GetConnection see
“site object” on page 332
Example This script creates a permanent ODBC connection called myConn. Once
created, this connection is visible from the Connections folder in Sybase
Central:
<!--SCRIPT
/* creates a permanent ODBC connection */
site.CreateConnection ( "myConn","My new ODBC
96
CHAPTER 3 DynaScript Predefined Objects
connection","Godzilla","dba","sql","ODBC" );
-->
See also “Connect method” on page 228
“Disconnect method” on page 230
“GetSupportedMoves method” on page 110
“Rollback method” on page 111
97
connection properties
connection properties
The connection object has these properties:
autoCommit property
Syntax connection.autoCommit
Description If true, each SQL statement executed using the connection is automatically
committed immediately after it is executed.
chained mode
Open Client connections are automatically set to CHAINED = ON which is
equal to autoCommit=false. Use autoCommit property to set chained mode to
off (autoCommit=true).
Example This example adds $1000 to account 999999999. The insert is executed and
committed immediately:
<!--SCRIPT
connection.autoCommit = true;
query = connection.CreateQuery( "insert into savings
values ( ’999999999’, ’1000’ )" );
-->
connected property
Syntax connection.connected
Attributes This property is read-only.
Description Uses a Boolean value to indicate whether a connection has been made to the
database.
Example This example displays the return. True indicates a successful connection, false
indicates no connection has been made.
<!--SCRIPT
document.writeln( connection.connected );
connection.Connect();
document.writeln( connection.connected );
connection.Disconnect();
document.writeln( connection.connected );
-->
98
CHAPTER 3 DynaScript Predefined Objects
connectionType property
Syntax connection.connectionType
Attributes This property is read-only.
Description The type of connection (string). One of:
• ODBC
• Open Client
Example This example displays the connection type for a script's default connection
object:
<!--SCRIPT
// This script displays the type of connection
// being used.
document.Write( "This is an " );
document.Write( connection.connectionType );
document.WriteLn( " connection." );
-->
connectParameters property
Syntax connection.connectParameters
Description Connection parameters for an ODBC data source (string).
Example This example lists the connection parameters for the ODBC data source:
<!--SCRIPT
document.WriteLn( connection.connectParameters );
-->
This example could have the following output:
99
connection properties
autostop = no
database property
Syntax connection.database
Description The name of the database to which an Open Client connection (string) is made.
Example This example changes the database to which "myConnection" will connect.
<!--SCRIPT
myConn = site.GetConnection ( "myConnection" );
myConn.database = "newDatabaseName";
-->
databaseType property
Syntax connection.databaseType
Attributes This property is read-only.
Description The type of database to which you are connecting; for example, Adaptive
Server Enterprise.
Example This example displays the type of database that is currently connected to:
<!--SCRIPT
document.WriteLn( connection.databaseType );
-->
dataSource property
Syntax connection.dataSource
Description Name of an ODBC data source (string).
Example This example changes the data sourcethat "MyConnection" uses to connect to
"PowerDynamo Demo":
<!--SCRIPT
myConn = site.GetConnection ( "MyConnection" );
myConn.datasource = "PowerDynamo Demo";
-->
100
CHAPTER 3 DynaScript Predefined Objects
dataSourceList property
Syntax connection.dataSourceList
Attributes This property is read-only.
Description Names of all available ODBC data sources (array of strings).
Example This example lists all the available ODBC data sources:
<!--SCRIPT
list = connection.dataSourceList;
i = 0;
while( exists( list[i] ) ) {
document.writeln( list[i] );
i++;
}
-->
This example might have the following output:
SQL Anywhere Sample
PowerDynamo Demo
description property
Syntax connection.description
Description Description associated with the connection (string).
Example This example displays the description associated with the connection:
<!--SCRIPT
document.WriteLn( connection.description );
-->
If the connection includes a description, this example might have output
similar to:
Connection to the sample site.
isolationLevel property
Syntax connection.isolationLevel
Description The isolation level for the database that you are connected to. You must be
connected to set the isolation level. You can set this value with an integer or a
string but it is always retrieved as a string. The possible values are:
101
connection properties
name property
Syntax connection.name
Description Name of the connection object (string). The name of the default connection is
<default>.
Example This example displays the name of the connection object. The Connections
folder in Sybase Central lists all connection object names.
<!--SCRIPT
/* display the name of a connection object */
document.WriteLn( connection.name );
-->
This example has an output of:
<default>
102
CHAPTER 3 DynaScript Predefined Objects
password property
Syntax connection.password
Description User password for the data source (string).
Example This example changes the password for “MyConnection” to “secret”:
<!--SCRIPT
myConn = site.GetConnection ( "MyConnection" );
myconn.password = "secret";
-->
server property
Syntax connection.server
Description Server name for the Open Client connection (string). This property can be used
only when you are using an Open Client connection.
Example This example displays the server name to which the connection object is
connected:
<!--SCRIPT
/* display the server name */
document.WriteLn( connection.server );
-->
This example has an output of:
myserver
simulateCursors property
Syntax connection.simulateCursors
Description Allows support for movement through a query result set for individual
connections. This property is useful when working with Adaptive Server
Enterprise connections.
103
connection properties
104
CHAPTER 3 DynaScript Predefined Objects
userId property
Syntax connection.userId
Description User name for the ODBC data source (string).
Example This example gets the connection “Temp” and changes the password and user
ID.
<!--SCRIPT
// change the password and userId of the "Temp"
// connection object
myConn=site.GetConnection ( "Temp" );
myConn.password = "Top";
myConn.userId = "Secret";
-->
105
connection methods
connection methods
The connection object has these methods:
Commit method
Syntax connection.Commit ( )
Description Commits the transaction.
Return Boolean.
Example This example moves 100 dollars from a checking account to a savings account.
If the money is moved successfully, a commit is performed:
<!--SCRIPT
success = false;
query = connection.CreateQuery( "select amount from
savings where id = ’99999999’" );
if( query != null ) {
balance = query.GetValue(1) - 100;
query.Close();
query = connection.CreateQuery( "update savings
set amount = ’" + balance + "’ where id = ’99999999’" );
if( query != null ) {
query.Close();
query = connection.CreateQuery( "select
amount from chequing where id = ’99999999’" );
if( query != null ) {
balance = query.GetValue(1) + 100;
query.Close();
query = connection.CreateQuery( "update
chequing set amount = ’" + balance + "’ where id =
’99999999’" );
if( query != null ) {
query.Close();
success = true;
}
}
}
}
if( success ) {
connection.Commit();
} else {
connection.Rollback();
}
106
CHAPTER 3 DynaScript Predefined Objects
-->
Connect method
Syntax connection.Connect ( )
Description Connects to a connection object.
Return Boolean. Indicates whether the connection was successful or not.
Example This example connects to the myConn connection:
<!--SCRIPT
myConn = site.CreateConnection( "myConn","My new ODBC
connection", "Dynamo demo","dba","sql","ODBC" );
myConn.Connect();
-->
See also The “Disconnect method” on page 230
CreateComponent method
Syntax connection.CreateComponent (packageName, componentName )
Description This method is for calling Jaguar components.
connection.CreateComponent returns a component object representing
the object referenced within the package.
Return The component object or null.
Example This example calls a Jaguar component and uses its setMessage method:
<!--SCRIPT
myJagComponent = myJaguarconnection.CreateComponent(
"Demo_Components", "SharedMsg" );
myQueryObject = myJagcomponent.setMessage( message );
-->
CreateQuery method
Syntax connection.CreateQuery ( [ SQLStatement, [doExecute ]] )
Description Executes a query containing a sqlStatement and returns a query object
(equivalent to performing myQuery.SetSQL and myQuery.Execute).
107
connection methods
108
CHAPTER 3 DynaScript Predefined Objects
Clark, Alison
Cobb, Matthew
Coe, Kristen
Evans, Scott
...
See also “query object” on page 309.
Disconnect method
Description Disconnects a connection object from a database.
Syntax connection.Disconnect ( )
Example This example disconnects from a connection called myConn:
<!--SCRIPT
myConn = site.CreateConnection( "myConn","My new ODBC
connection", "Dynamo demo","dba","sql","ODBC" );
myConn.Disconnect();
-->
GetErrorCode method
Syntax connection.GetErrorCode( )
Description Returns the current error code.
Return Integer. Returns zero if a SQL instruction is carried out correctly, and
information to which the script can respond if it fails.
Example This example displays a 0 if the query executes without error:
<HTML>
<TITLE>sample.stm</TITLE>
<BODY>
<H1></H1>
<!--SQL
SELECT customer.fname, customer.lname,
customer.phone, customer.id
FROM DBA.customer customer
-->
<!--SCRIPT
queryError = connection.GetErrorCode();
109
connection methods
document.WriteLn( queryError );
-->
</BODY>
</HTML>
See also “query object” on page 309.
The “query properties” on page 311.
The “GetErrorInfo method” on page 317.
The “GetState method” on page 318.
GetErrorInfo method
Syntax connection.GetErrorInfo( )
Description A description of the error.
Return String.
Example This example displays information explaining why the query did not work
correctly:
<HTML>
<TITLE>sample.stm</TITLE>
<BODY>
<H1></H1>
<!--SQL
SELECT customer.fname, customer.lname,
customer.phone, customer.id
FROM DBA.customer customeer
-->
<!--SCRIPT
queryState = connection.GetState();
document.WriteLn( queryState );
queryInfo = connection.GetErrorInfo();
document.WriteLn( queryInfo );
-->
</BODY>
</HTML>
See also “query object” on page 309.
The “query properties” on page 311.
“GetErrorCode method” on page 317.
110
CHAPTER 3 DynaScript Predefined Objects
GetState method
Syntax connection.GetState( )
Description Returns the current SQL state of the query.
The values returned by GetState depend on your database driver. For more
information, see your database's documentation.
Example This example displays the SQL state for the connection:
<HTML>
<TITLE>sample.stm</TITLE>
<BODY>
<H1></H1>
<!--SQL
SELECT customer.fname, customer.lname,
customer.phone, customer.id
FROM DBA.customer customeer
-->
<!--SCRIPT
queryState = connection.GetState();
document.WriteLn( queryState );
queryInfo = connection.GetErrorInfo();
document.WriteLn( queryInfo );
-->
</BODY>
</HTML>
GetSupportedMoves method
Syntax connection.GetSupportedMoves ( )
111
connection methods
Description Provides a list of Move methods that can be called for queries using that
particular connection.
Example This example displays the available Move methods for the connection
connection:
<!--SCRIPT
moves = connection.GetSupportedMoves();
i = 0;
while( exists( moves[i] ) ) {
document.writeln( moves[i] );
i++;
}
-->
If this was a connection to Adaptive Server Anywhere, the output would be:
MoveFirst
MoveNext
MovePrevious
MoveRelative
Move
MoveLast
Rollback method
Syntax connection.Rollback ( )
Description Performs a rollback on the transaction.
Return Boolean.
Example This example moves 100 dollars from a checking account to a savings account.
If the money is not moved successfully, a rollback is done:
<!--SCRIPT
success = false;
query = connection.CreateQuery( "select amount from
savings where id = ’99999999’" );
if( query != null ) {
balance = query.GetValue(1) - 100;
query.Close();
query = connection.CreateQuery( "update savings set
amount = ’" + balance + "’ where id = ’99999999’" );
if( query != null ) {
query.Close();
query = connection.CreateQuery( "select amount
from chequing where id = ’99999999’ );
112
CHAPTER 3 DynaScript Predefined Objects
113
Date object
Date object
Object Enables the storage and retrieval of dates and times. The Date object has no
properties.
Standard: ECMAScript
Syntax To use a Date’s method:
Date.MethodName( parameter )
Description The Date object may be constructed in any of these ways:
MyDateObj = new Date( )
MyDateObj = new Date( dateVal )
MyDateObj = new Date( [year, month [, date [, hours [, minutes [,
seconds [, ms]]]]]] )
The following syntax creates an integer holding the number of milliseconds
from midnight, January 1, 1970.
myInt = DateUTC( [year, [month [, date [, hours [, minutes [, seconds [,
ms]]]]]]] )
The parameters are:
•dateVal A string (Jan 30, 1938) or the number of milliseconds in
Universal Coordinated Time (previously known as Greenwhich Mean
time) between the specified date and midnight January 1, 1970. To
maintain accuracy a range between -2147483649 to 2147483647 may be
used. Dates that are outside of this range should use the other Date
constructor or a floating point.
•year The full year of the specified date. For example 1996. A value of 0
to 99 would be converted to a value between 1900 to 1999.
•month The month of the specified date. 0 is equal to January.
•date The date of the specified date.
•hours The hour of the specified date. 0 is equal to midnight. If minutes is
specified, the hours attribute must also be set.
•minutes The number of minutes of the specified date. If seconds is
specified, the minutes attribute must also be set.
•seconds The number of seconds of the specified date. If milliseconds is
specified, the seconds attribute must also be set.
•ms The number of milliseconds of the specified date.
114
CHAPTER 3 DynaScript Predefined Objects
The Date object has both a built-in object as well as constructors that allow
users to create instances of a Date object. When referring to Date in the syntax
sections of this chapter, we are referring to an instance of the Date object, not
the built-in Date object.
If a value for the date object goes beyond its boundaries, the other values will
be modified accordingly. For example if 14 is the given value for the month
parameter, the month value will be equal to March.
Example • This example uses the Date constructor to create a date object:
<!--SCRIPT
myDateObj = new Date("98", "01", "11", "8","30")
-->
See also “valueOf method” on page 303
115
Date methods
Date methods
The Date object has these methods:
getDate method
Syntax Date.getDate( )
Description Returns the day of the month in local time.
Return Integer.
Example This example displays the numeric day of the month:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30" );
document.WriteLn( myDate.getDate() );
-->
getDay method
Syntax Date.getDay( )
Description Returns the day of the week in local time.
Return An integer between 0 and 6.
•0 Sunday
•1 Monday
•2 Tuesday
•3 Wednesday
•4 Thursday
•5 Friday
•6 Saturday
Example This example displays the day of the week, which in this case is 1 (Monday):
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30" );
document.WriteLn( "week day: " + myDate.getDay() );
-->
116
CHAPTER 3 DynaScript Predefined Objects
getFullYear method
Syntax Date.getFullYear( )
Description Returns the year in local time.
Return An absolute number representing the full year.
Example This example displays the full year of the Date object:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30" );
document.WriteLn( "year: " + myDate.getFullYear() );
-->
getHours method
Syntax Date.getHours( )
Description Returns the hours value in local time.
Return Integer between 0 and 23.
Example This example displays the numeric value of the Date objects hour:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30" );
document.WriteLn( "hour: " + myDate.getHours() );
-->
getMilliseconds method
Syntax Date.getMilliseconds( )
Description Returns the milliseconds value in local time.
Return Integer from 0 to 999.
Example This example displays the number of milliseconds in the Date object:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30" );
document.WriteLn( "Milliseconds: " +
myDate.getMilliseconds() );
-->
117
Date methods
getMinutes method
Syntax Date.getMinutes( )
Description Returns the minutes value in local time.
Return Integer between 0 and 59.
Example This example displays the number of minutes in the Date object:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30" );
document.WriteLn( "Minutes: " + myDate.getMinutes()
);
-->
getMonth method
Syntax Date.getMonth( )
Description Returns the month value in local time.
Return Integer between 0 and 11. 0 is equal to January.
Example This example displays the month value of the Date object:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30" );
document.WriteLn( "Month: " + myDate.getMonth() );
-->
getSeconds method
Syntax Date.getSeconds( )
Description Returns the seconds value.
Return Integer between 0 and 59.
Example This example displays the seconds value of the Date object:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30" );
document.WriteLn( "Seconds: " + myDate.getSeconds()
);
-->
118
CHAPTER 3 DynaScript Predefined Objects
getTime method
Syntax Date.getTime( )
Description Returns the time value in local time. This value represents the number of
milliseconds between the specified time and midnight, January 1, 1970.
Negative numbers indicate dates prior to midnight, January 1, 1970.
Return Integer.
Example This example displays the number of milliseconds that have elapsed since
January 1, 1970 and the Date object:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30" );
document.WriteLn( "Time: " + myDate.getTime() );
-->
getTimezoneOffset method
Syntax Date.getTimezoneOffset( )
Description Returns the difference in minutes, between the local time and the Universal
Coordinated Time.
Return Integer.
Example This example displays the number of minutes between the local time and the
Universal Coordinated Time:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30" );
document.WriteLn( "Time zone offset: " +
myDate.getTimezoneOffset() );
-->
getUTCDate method
Syntax Date.getUTCDate( )
Description Returns the numeric date of the Date object, in Universal Coordinated Time.
Return Integer between 1 and 31 that represents the date value in the Date object.
Example This example displays the numeric date of the date object in Universal
Coordinated Time:
<!--SCRIPT
119
Date methods
getUTCDay method
Syntax Date.getUTCDay( )
Description Returns the day of the week from the Date object, in Universal Coordinated
Time.
•0 Sunday
•1 Monday
•2 Tuesday
•3 Wednesday
•4 Thursday
•5 Friday
•6 Saturday
Return Integer between 0 and 6 representing the day of the week.
Example This example displays the day of the week in UTC time:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30" );
document.WriteLn( "UTC date: " + myDate.getUTCDay()
);
-->
getUTCFullYear method
Syntax Date.getUTCFullYear( )
Description Returns the full year from the Date object, in Universal Coordinated Time.
Return Integer.
Example This example displays the full year in UTC time:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30" );
document.WriteLn( "UTC full year: " +
120
CHAPTER 3 DynaScript Predefined Objects
myDate.getUTCFullYear() );
-->
getUTCHours method
Syntax Date.getUTCHours( )
Description Returns the hours from the Date object, in Universal Coordinated Time.
Return Integer 0 to 23.
Example This example returns the hours in UTC time:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30" );
document.WriteLn( "UTC hours: " +
myDate.getUTCHours() );
-->
getUTCMilliseconds method
Syntax Date.getUTCMilliseconds( )
Description Returns the milliseconds value in a Date object using Universal Coordinated
Time.
Return Integer.
Example This example displays the number of milliseconds being held in the Date object
in UTC time:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
document.WriteLn( "UTC milliseconds: " +
myDate.getUTCMilliseconds() );
-->
getUTCMinutes method
Syntax Date.getUTCMinutes( )
Description Returns the minutes value in a Date object, using Universal Coordinated Time.
Return Integer between 0 and 59.
121
Date methods
Example This example displays the number of minutes being held in the Date object in
UTC time:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
document.WriteLn( "UTC minutes: " +
myDate.getUTCMinutes() );
-->
getUTCMonth method
Syntax Date.getUTCMonth( )
Description Returns the month value in a Date object, using Universal Coordinated Time.
•0 January
•1 February
•2 March
•3 April
•4 May
•5 June
•6 July
•7 August
•8 September
•9 October
•10 November
•11 December
Return Integer between 0 and 11.
Example This example displays the UTC month of the Date object:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
document.WriteLn( "UTC month: " +
myDate.getUTCMonth() );
-->
122
CHAPTER 3 DynaScript Predefined Objects
getUTCSeconds method
Syntax Date.getUTCSeconds( )
Description Returns the seconds value in a Date object, using Universal Coordinated Time.
Return Integer between 0 and 59.
Example This example displays the number of seconds (in UTC time) in the Date object:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
document.WriteLn( "UTC seconds: " +
myDate.getUTCSeconds() );
-->
getYear method
Syntax Date.getYear( )
Description Returns the year value in a Date object in local time. Use the getFullYear
method instead, to avoid Y2K problems.
Return Integer.
Example This example displays the year of the Date object:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
document.WriteLn( "Year: " + myDate.getYear() );
-->
parse method
Syntax Date.parse( string )
Description Parses a string containing a date and returns the number of milliseconds
between the date and midnight of January 1, 1970. The string may be in the
following formats:
•Month/day/year For example, 03/18/93,
•Month-day-year For example, 03-18-93
•Month day year For example, March 23 93
123
Date methods
setDate method
Syntax Date.setDate( numDate )
Description Sets the numeric day of the month of the Date object. numDate is a numeric
value equal to the numeric date. If a value is greater than its range, the other
values will be modified accordingly. For example, if the current date was
January 3 and setDate was set to 33, the month would change to February and
the date would be set to 2.
Return Integer. The number of milliseconds since midnight, January 1, 1970.
Example This example changes the numeric date of the Date object to the 23rd:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
document.WriteLn( "Date: " + myDate.getDate() );
myDate.setDate( "23" );
document.WriteLn( "Date: " + myDate.getDate() );
-->
setFullYear method
Syntax Date.setFullYear( numYear [, numMonth, [numDate]] )
Description Sets the year value in the Date object. The range of years supported is
approximately 285616 years on either side of 1970. The parameters are:
124
CHAPTER 3 DynaScript Predefined Objects
setHours method
Syntax Date.setHours( numHours [, numMin, [numSec, [numMilli]]] )
Description Sets the hours value in the Date object using local time. If a value is greater
than its range, the value will be modified accordingly. For example, the
numHours value of 30 would actually be equal to 6:00:00 (a day plus 6 hours).
The parameters are:
•numHours The hour value you would like set.
•numMin The minute value you would like set. If you use numSec or
numMilli, numMin is required.
•numSec The number of seconds you would like set. If you use numMilli,
you must use numSec.
•numMilli The millisecond value you would like set.
Return Integer. The number of milliseconds since midnight, January 1, 1970.
Example This example changes the time of the Date object:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
document.WriteLn( "Hours: " + myDate.getHours() );
myDate.setHours( "12", "15", "01" );
document.WriteLn( "Hours: " + myDate.getHours() );
-->
125
Date methods
setMilliseconds method
Syntax Date.setMilliseconds( numMilli )
Description Sets the milliseconds value in the Date object. numMilli is the numeric value
equal to the millisecond value you wish to set. If the value is greater than 999,
the number of seconds is increased as required. For example, 1020
milliseconds would be equal to one second and 21 milliseconds.
Return Integer. The number of milliseconds since midnight, January 1, 1970.
Example This example changes the number of milliseconds in the Date object:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
document.WriteLn( "Hours: " +
myDate.getMilliseconds() );
myDate.setMilliseconds( "89" );
document.WriteLn( "Hours: " +
myDate.getMilliseconds() );
-->
setMinutes method
Syntax Date.setMinutes( numMin [, numSec, numMilli] )
Description Sets the minutes value in the Date object. If a value is greater than its range, the
value will be modified accordingly. For example, the value of 80 minutes
would actually be equal to 1:20:00. The parameters are:
•numMin The minute value to set. This parameter is required if you use
numSec or numMilli.
•numSec The number of seconds you would like set. This parameter is
required if you use numMilli.
•numMilli The millisecond value you would like set.
Return Integer. The number of milliseconds since midnight, January 1, 1970.
Example This example changes the value of the minutes in the Date object. Because the
number of minutes is larger than 59, the and the hour value will be incremented
by one (to 9), and the minute value is changed accordingly.
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
document.WriteLn( "Old Minutes: " +
126
CHAPTER 3 DynaScript Predefined Objects
myDate.getMinutes() );
myDate.setMinutes( "89" );
document.WriteLn( "New hours: " + myDate.getHours()
);
document.WriteLn( "New minutes: " +
myDate.getMinutes() );
-->
The output from this example is:
Old Minutes: 30
New hours: 9
New minutes: 29
setMonth method
Syntax Date.setMonth( numMonth [, dateVal] )
Description Sets the month value for the Date object. January is equal to 0. If the value of
a parameter exceeds its range, other parameters will be changed accordingly.
The parameters are:
•numMonth The numeric value of the month.
•dateVal The numeric value of the date.
Return Integer. The number of milliseconds since midnight, January 1, 1970.
Example This example changes the month value of the Date object to March:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
document.WriteLn( "Old month: " + myDate.getMonth()
);
myDate.setMonth( "02" );
document.WriteLn( "New month: " + myDate.getMonth()
);
-->
setSeconds method
Syntax Date.setSeconds( numSec [, numMilli] )
127
Date methods
Description Sets the seconds value in the Date object using local time. If the value of a
parameter exceeds its range, other parameters are changed accordingly. The
parameters are:
•numSec The second value to set. If you use numMilli, you must use
numSec.
•numMilli The millisecond value you would like set.
Return Integer. The number of milliseconds since midnight, January 1, 1970.
Example This example changes the value of the seconds in the Date object:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
myDate.setSeconds( "58" );
document.WriteLn( "Seconds: " + myDate.getSeconds()
);
-->
setTime method
Syntax Date.setTime( numMilli )
Description Sets the date and time value in the Date object. numMilli is an integer that
represents the number of milliseconds that have elapsed since midnight,
January 1, 1970 GMT. A negative number indicates a date earlier than January
1, 1970. PowerDynamo supports a range between -2147483649 and
2147483647. To set dates that are beyond this range, use a floating point.
Using setTime to set the date and time of a Date object is time zone
independent.
Return Integer. The number of milliseconds since midnight, January 1, 1970.
Example This example sets the date and time of a date object with the setTime method:
<!--SCRIPT
myDate = new Date( );
myDate.setTime( "5324654" );
document.WriteLn( "Year: " + myDate.getUTCFullYear()
);
document.WriteLn( "Month: " + myDate.getUTCMonth()
);
document.WriteLn( "Date: " + myDate.getUTCDate() );
document.WriteLn( "Hours: " + myDate.getUTCHours()
);
128
CHAPTER 3 DynaScript Predefined Objects
setUTCDate method
Syntax Date.setUTCDate( numDate )
Description Sets the numeric date in the Date object using Universal Coordinated Time.
numDate represents the date that is to be set.
If the value of a parameter exceeds its range, other parameters will be changed
accordingly. For example, if the current date was January 12 and
SetUTCDate(33) was given, the new month and date would be February 2.
Return Integer. The number of milliseconds since midnight, January 1, 1970.
Example This example changes the date of the Date object. Because the new date value
exceeds the number of days in the month of February, the month value is
incremented by one, and the date is changed accordingly:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
document.WriteLn( "Old date: " + myDate.getUTCDate()
);
document.WriteLn( "Old month: " +
myDate.getUTCMonth() );
myDate.setUTCDate( "45" );
document.WriteLn( "New date: " + myDate.getUTCDate()
);
document.WriteLn( "New month: " +
myDate.getUTCMonth() );
-->
This example displays this output:
Old date: 11
Old month: 1
New date: 17
129
Date methods
New month: 2
setUTCFullYear method
Syntax Date.setUTCFullYear( numYear [, numMonth, [numDate]] )
Description Sets the value of the year in the Date object using Universal Coordinated Time.
The range of years supported is approximately 285616 years on either side of
1970. The parameters are
•numYear The numeric value of the year to set.
•numMonth The numeric value of the month to set. If the numDate
parameter is specified, this parameter must also be set.
•numDate The numeric value of the date to set.
If the value of a parameter exceeds its range, other parameters are changed
accordingly. For example if the current date value was January 1, 1983 and the
numDate parameter given is 32, the date changes to February 1, 1983.
Return Integer. The number of milliseconds since midnight, January 1, 1970.
Example This example changes the year of the Date object and displays the new value:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
myDate.setUTCFullYear( "78" );
document.WriteLn( "New date: " +
myDate.getUTCFullYear() );
-->
setUTCHours method
Syntax Date.setUTCHours( numHours [, numMin, [numSec, [numMilli]]] )
Description Sets the hours value in the Date object using Universal Coordinated Time. If a
value is greater than its range, the value will be modified accordingly. For
example, the numHours value of 30 would actually be equal to 6:00:00 (a day
plus six hours). The parameters are:
•numHours The hour value you would like set.
•numMin The minute value you would like set. If you use numSec or
numMilli, you must set numMin.
130
CHAPTER 3 DynaScript Predefined Objects
•numSec The second value you would like set. If you use numMilli, you
must set numSec.
•numMilli The millisecond value you would like set.
Return Integer. The number of milliseconds since midnight, January 1, 1970.
Example This example changes the hours value of the Date object and displays the new
value:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
myDate.setUTCHours( "9" );
document.WriteLn( "New hour: " +
myDate.getUTCHours() );
-->
setUTCMilliseconds method
Syntax Date.setUTCMilliseconds( numMilli )
Description Sets the milliseconds value for the Date object. If the number of milliseconds
is greater than 999 or a negative number, the stored number of seconds reflects
this accordingly. For example, 1020 milliseconds is equal to one second and 21
milliseconds.
Return Integer. The number of milliseconds since midnight, January 1, 1970.
Example This example changes the milliseconds value of the Date object and displays
the new value:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
myDate.setUTCMilliseconds( "12" );
document.WriteLn( "New milliseconds: " +
myDate.getUTCMilliseconds() );
-->
setUTCMinutes method
Syntax Date.setUTCMinutes( numMin [numSec, numMilli] )
131
Date methods
Description Sets the minutes value in the Date object using Universal Coordinated Time. If
a value is greater than its range, the value is modified accordingly. For
example, the value of 80 minutes would actually be equal to 1:20:00. The
parameters are:
•numMin The minute value to set. This parameter is required if you use
numSec or numMilli.
•numSec The second value to set. This parameter is required if you use
numMilli.
•numMilli The millisecond value you would like set.
Return Integer. The number of milliseconds since midnight, January 1, 1970.
Example This example changes the minute value of the Date object and displays the new
value:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
myDate.setUTCMinutes( "45" );
document.WriteLn( "New minutes: " +
myDate.getUTCMinutes() );
-->
setUTCMonth method
Syntax Date.setUTCMonth( numMonth [, dateVal] )
Description Sets the month value for the Date object. January is equal to 0. If the value of
a parameter exceeds its range, other parameters are changed accordingly. The
parameters are:
•numMonth The numeric value of the month.
•dateVal The numeric value of the date.
Return Integer. The number of milliseconds since midnight, January 1, 1970.
Example This example changes the month value of the Date object and displays the new
value:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
myDate.setUTCMonth( "6" );
document.WriteLn( "New month: " +
myDate.getUTCMonth() );
132
CHAPTER 3 DynaScript Predefined Objects
-->
setUTCSeconds method
Syntax Date.setUTCSeconds( numSec [, numMilli] )
Description Sets the seconds value in the Date object using Universal Coordinated Time. If
the value of a parameter exceeds its range, other parameters are changed
accordingly. The parameters are:
•numSec The second value to set. This parameter is required if you use
numMilli.
•numMilli The millisecond value to set.
Return Integer. The number of milliseconds since midnight, January 1, 1970.
Example This example changes the second value of the Date object and displays the new
value:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
myDate.setUTCSeconds( "00" );
document.WriteLn( "New seconds: " +
myDate.getUTCSeconds() );
-->
setYear method
Syntax Date.setYear( numYear )
Description Sets the year value in the Date object. This method is currently maintained only
for backward compatibility. Use the setFullYear method instead.
Return Integer. The number of milliseconds since midnight, January 1, 1970.
toGMTString method
Syntax Date.toGMTString( )
Description Returns a date as a string in Greenwich Mean Time. This method is currently
supported only for backward compatibility. Use the toUTCString instead.
Return String.
133
Date methods
toLocaleString method
Syntax Date.toLocaleString( )
Description Returns a date as a string using the current locale.
Return String. The format of this string changes depending on the locale. For example,
the date January 10, 1998 is represented by:
• "01/10/98 00:00:00" in Canada or the United States or,
• "10/01/98 00:00:00" in Europe
Example This example displays the value of the Date object in local time:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
document.WriteLn( myDate.toLocaleString() );
-->
The output from this example is:
Wed, 11 Feb 1998 08:30:11
toString method
Syntax Date.toString( )
Description Returns the date as a string in a convenient, readable format in local time.
Return String.
Example This example displays the value of the Date object in local time:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
document.WriteLn( myDate.toString() );
-->
The output from this example is:
Wed, 11 Feb 1998 08:30:11
toUTCString method
Syntax Date.toUTCString( )
134
CHAPTER 3 DynaScript Predefined Objects
valueOf method
Syntax Date.valueOf( )
Description Returns the time value in local time. This value represents the number of
milliseconds between the specified time and midnight, January 1, 1970.
Negative numbers indicate dates prior to midnight, January 1, 1970.
Return Integer.
Example This example displays the number of milliseconds that have elapsed since
January 1, 1970 and the value of the Date object:
<!--SCRIPT
myDate = new Date( "98", "01", "11", "8","30", "11",
"35" );
document.WriteLn( myDate.valueOf() );
-->
135
document object
document object
Object Represents a document in your Web site. Each document can be a file or folder.
Syntax To use a document’s property:
document.propertyName
To use a document’s method:
document.MethodName( parameter )
Description The methods that you use to manipulate documents are shared between the
document object and the site object.
The site object allows you to manipulate your Web site’s documents. For
example, use the following format to create a document:
site.CreateDocument(docName, documentType,
description, content[,connectionName | connectionId])
For information on site.CreateDocument, site.DeleteDocument, or
site.GetDocument, see “site object” on page 332.
Caution
Don’t confuse the Dynamo document object and the JavaScript document
object. The Dynamo document object supports a different set of properties and
methods that are customized for working with databases.
Example This example creates a new document called MyDoc in the Site folder:
<!--SCRIPT
site.CreateDocument( "/site/MyDoc.stm","text", "my
new document", "hello" );
-->
See also “description property” on page 100.
“size property” on page 265.
“value property” on page 155.
136
CHAPTER 3 DynaScript Predefined Objects
document properties
The document object has these properties:
cachedOutputTimeOut property
Syntax document.cachedOutputTimeOut
Description Duration of time (integer) for which the generated output of a script or template
is cached. The default is zero. This property is not persistent–It is reset to zero
if you restart the Web server.
Example This example sets the cache time of the current document output to be 3
minutes.
<!--SCRIPT
/* setting the cache time */
document.WriteLn( "This is my output that will be
cached for 3 minutes." );
document.cachedOutputTimeOut = 3;
-->
connectionId property
Syntax document.connectionId
Description ID of associated connection object (integer). Connection IDs may change it
you restart the Web server. For this reason, Sybase recommends that you use
the connectionName property instead.
Example This example displays the connection Id of a script's associated connection
object:
<!--SCRIPT
/* displays the connection Id */
document.WriteLn( document.connectionId );
-->
The output from this example might look like this:
0
See also “connection object” on page 95.
137
document properties
connectionName property
Syntax document.connectionName
Description Name of the associated connection object (string).
Example This example displays the connection name of a script’s associated connection
object.
<!--SCRIPT
/* display the connection name */
document.WriteLn( document.connectionName );
-->
See also “connection object” on page 95.
contentType property
Syntax document.contentType
Description Type of document being displayed (string). The content types are standard
MIME content types. This property is not persistent and will be reset if the Web
server is restarted.
Example This example selects a graphic called bart.gif from a table in the database and
then displays it to a browser. The second part of the example tells the browser
to expect an image rather than HTML.
<!--SQL
select data from imagetable where imagename =
’bart.gif’
-->
<!--SCRIPT
/* set the content type to image */
document.contentType = "image/gif";
document.write( SQL.GetValue("data") );
-->
description property
Syntax document.description
Description Description associated with the document (string).
138
CHAPTER 3 DynaScript Predefined Objects
Example This example displays the description that was entered when the document
/Site/descript.ssc was created.
<!--SCRIPT
descDoc = site.GetDocument ( "/Site/descript.ssc" );
document.WriteLn( descDoc.description );
-->
id property
Syntax document.id
Attributes This property is read-only.
Description Internal document object ID (integer). IDs may change if you restart the Web
server. For this reason, Sybase recommends the use of the documentName
property to identify documents instead of the id property.
Example This example displays the document ID.
<HTML>
<TITLE>docid.stm</TITLE>
<BODY>
<H1>Display the document’s Id number.</H1>
<p>The document id for docid.stm is: </p>
<!--SCRIPT
document.WriteLn( document.id );
-->
</BODY>
</HTML>
The output would be similar to:
Display the document’s Id number.
265
lastModified property
Syntax document.lastModified
Attributes This property is read-only.
139
document properties
Description Returns the time (string) of the last change to the document (for example,
1996-10-24 14:24:29).
Example This example displays the date the document was last altered:
<!--SCRIPT
document.WriteLn( document.lastModified );
-->
The output from this example is:
1997-06-06 10:40:30
location property
Syntax document.location
Description Full URL for the document.
Linked Folders
You cannot move a linked folder inside a linked folder.
name property
Syntax document.name
Description Name (including extension, if any).
Example This example displays the name of the document.
<!--SCRIPT
/* name of the document. */
document.WriteLn( document.name );
-->
The output from this example is:
140
CHAPTER 3 DynaScript Predefined Objects
name.ssc
parent property
Syntax document.parent
Description The containing folder object of this document (document).
Linked Folders
You cannot move a linked folder inside a linked folder.
redirect property
Syntax document.redirect
Description The name of the URL to which the current request is to be directed (string).
This property is not persistent and will be reset if you restart the Web server.
Example This example directs a request to http://www.sybase.com:
<!--SCRIPT
document.redirect = "http://www.sybase.com";
-->
size property
Syntax document.size
Attributes This property is read-only.
Description Length in bytes (integer) of the document.
Example This example displays the size of the document:
141
document properties
<!--SCRIPT
/* Size of the document. */
document.WriteLn( document.size );
-->
source property
Syntax document.source
Description Uninterpreted document content (source).
Example This example changes the contents of /site/sample.stm to “hello world”:
<!--SCRIPT
sampleDoc = site.GetDocument( "/site/sample.stm" );
sampleDoc.source = "hello world";
-->
status property
Syntax document.status
Description A string that indicates a status code and a brief explanation of that code. The
status code values are defined in the HTTP specification.
Example This example prompts the user for a user ID and a password, then displays the
status code.
<!--SCRIPT
authType = document.GetServerVariable( "AUTH_TYPE" );
if( authType != null ) {
authType = authType.toUpperCase();
}
if( authType == "BASIC" ) {
// Web server has successfully authenticated
// the user
document.writeln( "<HTML>Welcome</HTML>" )
} else {
// document.status is part of the HTTP
// header sent to the browser.
// For "401" a browser will prompt the
// user for a userid and password and attempt
// to login to the Web server
document.status = "401 Unauthorized";
// since the HTTP headers are only seen by the
142
CHAPTER 3 DynaScript Predefined Objects
type property
Syntax document.type
Attributes This property is read-only.
Description The type of Dynamo document (string). One of:
• directory Dynamo folder
• directoryLink Dynamo linked folder
• image binary file
• script DynaScript file
• text Dynamo HTML template
Example This example displays the document type:
<!--SCRIPT
/* type of document */
document.WriteLn( document.type );
-->
value property
Syntax document.value.variable
Attributes This property is read-only.
Description Values of passed-in arguments (URL arguments, typically from an HTML
form), where variable is the argument name (array).
Example This example converts a user provided temperature from Celsius to Fahrenheit
or from Fahrenheit to Celsius.
143
document properties
The first part of the example prompts the user to select the type of conversion
and to enter a value. The values are held in the parameters theType and
temperature:
<HTML>
<H1>Converting Temperatures </H1>
<BODY>
</BODY>
</HTML>
The next part of the example receives the values entered by the user and uses
the values to calculate the requested temperature:
<HTML>
<TITLE>convert.stm</TITLE>
<BODY>
<H1>Temperature</H1>
<P>Your answer is: </P>
<!--SCRIPT
// receiving user provided data
var conversionType = document.value.theType;
144
CHAPTER 3 DynaScript Predefined Objects
</BODY>
</HTML>
The first part of the next example prompts the user to select items from a list in
which all the items have the same name element of "choice". If only one item
is selected, the value is held in document.value.variable. If two or more items
are selected from the list the values are held in document.value[0],
document.value[1], document.value[2], and so on.
The second part of the next example displays the arguments selected from the
first template.
<HTML>
<TITLE>multpar.stm</TITLE>
<BODY>
<HTML>
<H1>What Do I Have To Do Today? </H1>
<BODY>
<P> To do list:
<FORM METHOD=POST ACTION="display.stm" MULTIPLE
SIZE="5">
<OL>
<INPUT TYPE="checkbox" NAME="choice"
value="Laundry">Laundry<BR>
<INPUT TYPE="checkbox" NAME="choice" value="Walk the
dog">Walk the dog<BR>
<INPUT TYPE="checkbox" NAME="choice" value="Wash the
car">Wash the car<BR>
<INPUT TYPE="checkbox" NAME="choice"
value="Groceries">Get groceries<BR>
<INPUT TYPE="checkbox" NAME="choice" value="Dust">Dust
145
document properties
the house<BR>
</OL>
<P><INPUT TYPE="submit" VALUE="Submit List"></p>
<P><INPUT TYPE="RESET" VALUE="Clear Form"></P>
</FORM>
</BODY>
</HTML>
<HTML>
<TITLE>display.stm</TITLE>
<BODY>
<H1>My tasks are:</H1>
<!--SCRIPT
if( typeof( document.value.choice ) == "object" ) {
i = 0;
while( exists( document.value.choice[i] ) ) {
document.writeln( "value[" + i + "] = " +
document.value.choice[i] );
i++;
}
} else {
document.writeln( "value = " + document.value.choice
);
}
-->
</BODY>
</HTML>
The last example looks up and displays the ID for a customer whose first and
last name have been sent by a browser (typically in response to an HTML
form).
<!--SCRIPT
myQuery=connection.CreateQuery( "select id from
customer where lname = ’" + document.value.lastName +
"’ and fname = ’" + document.value.firstName + "’" );
myQuery.MoveNext();
document.WriteLn( yQuery.GetValue(1));
myQuery.Close();
-->
146
CHAPTER 3 DynaScript Predefined Objects
document methods
The document object has these methods:
ExportTo method
Syntax document.ExportTo(pathName [, newName])
Description For files, saves the file as an external (disk) file in the pathName disk directory.
For folders, saves the contained document tree (all nested files and folders) as
an external directory tree (disk files and folders) in the pathName disk
directory. newname allows you to optionally rename the file in its new location.
Return Boolean. This method returns true or false, indicating whether the method
succeeded or not.
Example This example exports /site/products.stm to the c:\ drive:
<!--SCRIPT
productDoc = site.GetDocument ( "/site/products.stm"
);
productDoc.ExportTo( "c:" )
-->
GetDirectory method
Syntax document.GetDirectory( [fileMask, sortOrder] )
Description For folder documents, returns an array of contained documents (for example, a
directory listing) matched by the string fileMask. fileMask can contain the
wildcard characters “*” and “?”. The sort order may be name or type. Name is
the sortOrder default.
For information on the wildcards, see “Wildcards” on page 77.
Return Array of document objects. Returns a list of contained documents.
Example This example displays all the documents in the /site folder that begin with the
letter a and then sorts them alphabetically:
<!--SCRIPT
siteDoc = site.GetDocument( "/site" );
dirList = siteDoc.GetDirectory( "a*", "name" );
for ( i in dirList ) {
document.WriteLn( dirList[i].name );
}
147
document methods
-->
GetGenerated method
Syntax document.GetGenerated( )
Description Returns the interpreted output from a document as a string. You cannot run this
method from within the same document from which you are calling
GetGenerated.
Return String. Returns the interpreted output.
Example This example runs the script /site/products.ssc and places the output in the
variable “part1”. /site/products.ssc takes two parameters; name and password.
myDoc = site.GetDocument( "/site/products.ssc" );
myDoc.value.name = "open";
myDoc.value.password = "sesame";
part1 = myDoc.GetGenerated();
Inside products.ssc you would use "document.value.name", and
"document.value.password" to access the parameter values.
See also The “Include method” on page 358.
GetServerVariable method
Syntax document.GetServerVariable( )
Description Returns a value from a server. The server variable name is dependent on which
server interface is being used. This method is not supported by CGI servers.
NSAPI
NSAPI (Dynamo
CGI (native cover for Personal
Equivalent ISAPI ) NSAPI) Web Server
AUTH_TYPE AUTH_TYPE auth- AUTH_TYP
type E
CONTENT_L CONTENT_LEN content CONTENT_ CONTENT_L
ENGTH GTH -length LENGTH ENGTH
CONTENT_T CONTENT_TYP content CONTENT_ CONTENT_T
YPE E -type TYPE YPE
GATEWAY_I GATEWAY_INT GATEWAY_I
NTERFACE ERFACE NTERFACE
148
CHAPTER 3 DynaScript Predefined Objects
NSAPI
NSAPI (Dynamo
CGI (native cover for Personal
Equivalent ISAPI ) NSAPI) Web Server
HTTP_USER HTTP_USER_A user- HTTP_USE HTTP_USER
_AGENT GENT agent R_AGENT _AGENT
PATH_INFO PATH_INFO path PATH_INFO PATH_INFO
PATH_TRAN PATH_TRANSL
SLATED ATED
QUERY_STR QUERY_STRIN query QUERY_ST QUERY_STR
ING G RING ING
REMOTE_A REMOTE_ADD ip REMOTE_A REMOTE_A
DDR R DDR DDR
REMOTE_H REMOTE_HOS
OST T
REMOTE_U REMOTE_USE auth- REMOTE_U
SER R user SER
REQUEST_ REQUEST_MET method REQUEST_ REQUEST_
METHOD HOD METHOD METHOD
SCRIPT_NA SCRIPT_NAME SCRIPT_NA SCRIPT_NA
ME ME ME
SERVER_NA SERVER_NAM
ME E
SERVER_PO SERVER_PORT SERVER_PO
RT RT
SERVER_PR SERVER_PROT protoco SERVER_PR SERVER_PR
OTOCOL OCOL l OTOCOL OTOCOL
SERVER_SO SERVER_SOFT SERVER_S SERVER_SO
FTWARE WARE OFTWARE FTWARE
HTTP_COOKIE cookie COOKIE COOKIE
URL URL_PREFI
X
UNMAPPED_R
EMOTE_USER
SERVER_PORT
_SECURE
HTTP_ACCEPT
ALL_HTTP
149
document methods
<!--SCRIPT
REMOTE_ADDR = document.GetServerVariable(
"REMOTE_ADDR" );
document.writeln( "<BR>REMOTE_HOST = "+ REMOTE_ADDR
);
-->
The output for this example is:
REMOTE_ADDR = 122.47.156.352
ImportFrom method
Syntax document.ImportFrom(fileName[, replaceOption, newName ])
Description Imports the external file (or folder and its contents) named fileName into the
Web site.
If name conflicts occur, the optional replaceOption determines how to resolve
them:
• newer Replaces existing file if incoming one is newer. This is the
default if you do not specify replaceOption.
• all Replaces existing file regardless of modification dates.
You can rename an imported file or folder with the optional newName
parameter.
Return Boolean. This method returns true or false, indicating whether the method
succeeded or not.
Example This example imports the file d:\test\products.stm into the Site folder:
<!--SCRIPT
/* Import a document to a folder */
myfolder = site.GetDocument ( "/Site" );
myfolder.ImportFrom ( ’d:\\test\\products.stm’,’all’
);
-->
IncludeGenerated method
Syntax document.IncludeGenerated( )
150
CHAPTER 3 DynaScript Predefined Objects
Description Includes the generated output of the document that is called in the output of the
currently executing script. A document cannot call
document.IncludeGenerated on itself.
Return Boolean. This method returns true or false, indicating whether the method
succeeded or not.
Example This example gets the include.stm document and then generates and displays
the output of that document within the current document:
<!--SCRIPT
mydoc=site.GetDocument( "~/include.stm" );
mydoc.IncludeGenerated();
-->
Here are the contents of include.stm:
<HTML>
<TITLE>include.stm</TITLE>
<BODY>
<H1></H1>
<!--SQL
SELECT customer.fname, customer.lname
FROM DBA.customer customer
-->
<TABLE BORDER>
<TR>
<TH>fname</TH>
<TH>lname</TH>
</TR>
<!--formatting--><TR>
<TD><!--data--></TD>
<TD><!--data--></TD>
</TR><!--/formatting-->
</TABLE>
</BODY>
</HTML>
The output from this example is:
<HTML>
<TITLE>include.stm</TITLE>
<BODY>
<H1></H1>
<TABLE BORDER>
<TR>
<TH>fname</TH>
151
document methods
<TH>lname</TH>
</TR>
<TR>
<TD>Michaels</TD>
<TD>Devlin</TD>
</TR><TR>
<TD>Beth</TD>
<TD>Reiser</TD>
</TR><TR>
<TD>Erin</TD>
<TD>Niedringhaus</TD>
</TR><TR>
<TD>Meghan</TD>
<TD>Mason</TD>
</TR><TR>
<TD>Laura</TD>
<TD>McCarthy</TD>
...
Write method
Syntax document.Write(outputString)
Description Appends outputString to the output generated by this document.
Example This example generates output without a line break:
<!--SCRIPT
document.WriteLn( "This is the write method. " );
document.writeLn( "You can use a lower case w." );
-->
The output of this example is:
This is the write method. You can use a lower case w.
WriteLn method
Syntax document.WriteLn(outputString)
Description Same as Write, but also adds a line break.
Line breaks produced with WriteLn only work when viewing an HTML
document as plain ASCII source (for example, in a text editor).
152
CHAPTER 3 DynaScript Predefined Objects
When this HTML is processed by a Web client, the resulting layout ignores
these line breaks, so WriteLn ultimately produces the same output as Write.
To force line breaks in the final output, you must use the HTML <P> or <BR>
tag. For example:
document.WriteLn( "<P>This starts on a new line" );
In general, WriteLn makes your HTML source easier to read, but does not
reflect how it is formatted by a Web client.
To remain compatible with JavaScript, Dynamo allows you to use write for
Write, and writeln for WriteLn.
Example This example:
<!--SCRIPT
document.WriteLn( "This is the writeln method. " );
document.writeln( "You can use lower case (writeln)
or upper case (WriteLn)," );
document.WriteLn( "but not Writeln." );
-->
outputs:
This is the writeln method.
You can use lower case (writeln) or upper case
(WriteLn),
but not Writeln.
See also The “Write method” on page 225.
153
DOMAttribute object
DOMAttribute object
Object Represents an attribute in an XML element. The XML element itself is
represented by a DOMElement object.
Syntax To use a DOMAttribute’s property:
DOMAttribute.propertyName
To use a DOMAttribute’s method:
DOMAttribute.MethodName( parameter )
Description DOMAttribute objects inherit the properties and methods of the DOMNode
object. The attributes for a particular DOMElement are accessible via the
attributes property of the DOMElement object.
The parentNode, previousSibling, and nextSibling properties of a
DOMAttribute object are null.
The children of the DOMAttribute object represent the attribute’s value.
Attributes whose values are inferred from the DTD are not yet supported and
do appear within the document tree.
DOMAttribute objects have all of the properties and methods of the DOMNode
object as well as the properties defined here.
To obtain a DOMAttribute object in an existing document, you can use the
getAttributeNode method of a DOMElement object, or the attributes
property of a DOMNode object.
To add a DOMAttribute object to a DOM document, you can use the
setAttributeNode method of a DOMElement object.
See also “getAttributeNode method” on page 178.
“attributes property” on page 195.
“setAttribute method” on page 181.
154
CHAPTER 3 DynaScript Predefined Objects
DOMAttribute properties
The DOMAttribute object has these properties as well as all the properties of
the DOMNode object, which are inherited:
name property
Syntax DOMAttribute.name
Description Returns the name of the attribute.
For the following start tag of an element:
<Region Type="State">
there is one attribute, which has the name Type.
Example The following DynaScript fragment writes out the name of each attribute of a
DOMElement object named elem:
attlist = elem.attributes
for( iAtt=0; iAtt < attlist.length; iAtt++ ) {
document.writeln( attlist.item(iAtt).name );
}
See also “getAttributeNode method” on page 178.
specified property
Syntax DOMAttribute.specified
Attributes This property is read-only.
Description If the attribute was explicitly given a value in the original document, the
specified property will be set to true. If no value was given the specified
property is set to false.
This property is set to true if the value of the attribute is changed.
Attributes whose values are not explicitly specified, but are instead inferred
from the DTD are not yet supported and do not appear within the document
tree. Therefore, for attributes within the document tree, this property is always
true.
Example This example writes out the name of each specified attribute of a DOMElement
object named elem:
155
DOMAttribute properties
attlist = elem.attributes
for( iAtt=0; iAtt < attlist.length; iAtt++ ) {
if( attlist.item(iAtt).specified == true ){
document.writeln( attlist.item(iAtt).name );
}
}
value property
Syntax DOMAttribute.value
Attributes This property is read/write.
Description When retrieved, this property returns the attribute value as a string. Entity
references will be replaced by their values.
When set, a DOMText object representing the string is created, and will become
the only child of the DOMAttribute object.
For the following start tag of an element:
<Region Type="State">
there is one attribute, which has the value State.
Example This DynaScript fragment writes out the value of each specified attribute of a
DOMElement object named elem:
attlist = elem.attributes
for( iAtt=0; iAtt < attlist.length; iAtt++ ) {
document.writeln( attlist.item(iAtt).value );
}
}
156
CHAPTER 3 DynaScript Predefined Objects
DOMAttribute methods
The DOMAttribute object has no methods of its own but inherits all the
methods of the DOMNode object.
157
DOMCDATASection object
DOMCDATASection object
Object Holds text data that includes characters that would otherwise need escaping or
replacing by entity references in an XML document.
Syntax To use a DOMCDATASection’s property:
DOMCDATASection.propertyName
To use a DOMCDATASection’s method:
DOMCDATASection.MethodName( parameter )
Description The DOMCDATASection object has no properties or methods of its own, but
inherits all the methods and properties of the DOMText object.
158
CHAPTER 3 DynaScript Predefined Objects
DOMCharacterData object
Object Represents character data in an XML document.
Syntax To use a DOMCharacterData’s property:
DOMCharacterData.propertyName
To use a DOMCharacterData’s method:
DOMCharacterData.MethodName( parameter )
Description The DOMCharacterDATA object inherits all the methods and properties of the
DOMNode object as well as providing its own set of methods and properties to
access and manipulate character data in the DOM.
159
DOMCharacterData properties
DOMCharacterData properties
The DOMCharacterData object has the properties listed in this section, in
addition to all of the properties of the DOMNode object, which are inherited:
data property
Syntax DOMCharacterData.data
Description The text represented by this object.
Example This DynaScript fragment writes out the character data associated with all text
node children of an element.
child = elem.firstChild;
do {
if( child.nodeType == 3 ){// text node
document.writeln( child.data );
child = child.nextSibling;
}
} while ( child != null )
length property
Syntax DOMCharacterData.length
Description The number of characters in the text representing by this object. The length is
an integer value greater than or equal to zero.
Example This DynaScript fragment writes out the length of each text node child of a
DOMElement object named elem.
child = elem.firstChild;
do {
if( child.nodeType == 3 ){// text node
document.writeln( child.data );
child = child.nextSibling;
}
} while ( child != null )
160
CHAPTER 3 DynaScript Predefined Objects
DOMCharacterData methods
The DOMCharacterData object inherits the methods from the DOMNode
object, but it also has its own methods, which are discussed in this section.
appendData method
Syntax DOMCharacterData.appendData( DOMString )
Description Appends the string to the end of the character data represented by this object.
DOMString is the string that is to be appended.
Example Here is a very simple document:
<?xml version=’1.0’ encoding=’ISO-8859-1’ ?>
<Customer>
<FName>Jessie</FName>
<LName>Gagliardo</LName>
<Address><Street>2800 Park Avenue</Street>
<City>Hull</City>
<Region Type="Province">PQ</Region>
</Address></Customer>
This DynaScript fragment, which includes a Region element, checks whether
the region is a province or a state, and appends a string indicating the country
to the text element.
child = elemRegion.firstChild;
if( elemRegion.getAttribute( "Type" ) == "Province" ){
child.appendData( ", Canada" );
} else {
child.appendData( ", USA" );
}
document.writeln( child.data );
deleteData method
Syntax DOMCharacterData.deleteData( offset, count )
Description Removes a range of characters from the text represented by this object. The
parameters are:
•offset The offset from which to begin removing characters. Offset values
begin at zero.
161
DOMCharacterData methods
•count The number of characters to delete. If the sum of offset and count
exceeds the length of the text, all characters from the offset to the end of
the data are deleted.
Example This DynaScript statement deletes the first two characters from a text node.
if( elem.nodeType == 3 ) { // text node
elem.deleteData( 0, 2 )
}
insertData method
Syntax DOMCharacterData.insertData( offset, DOMString )
Description Inserts a string at the specified character offset. The parameters are:
•offset The character offset at which to insert. Offset values begin at zero.
•DOMString The string to insert.
Example This DynaScript fragment inserts a string at the beginning of a text node.
if( elem.nodeType == 3 ) { // text node
elem.insertData( 0, "Region: " )
}
replaceData method
Syntax DOMCharacterData.replaceData( offset, count, DOMString )
Description Replaces the character starting at the specified character offset with the
specified string. The parameters are:
•offset The offset from which to start replacing. Offset values begin at
zero.
•count The number of characters to replace. If the sum of offset and count
exceeds length, all characters to the end of the data are replaced.
•DOMString The string with which the range is to be replaced.
Example This DynaScript fragment replaces the third and fourth characters in a text
node with the string “XXX”.
if( elem.nodeType == 3 ) { // text node
elem.replaceData( 3, 2, "XXX" )
}
162
CHAPTER 3 DynaScript Predefined Objects
substringData method
Syntax DOMCharacterData.substringData( offset, count )
Description Extracts a portion of the text represented by this object. The parameters are:
•offset The offset from which to start extracting. Offset values begin at
zero.
•count The number of characters to extract.
Return A string containing the extracted portion of the text.
Example This DynaScript fragment writes out the characters from the fourth to the
hundredth of all text nodes that are children of a Street element.
function SubstringDataCharacterData( domDoc ) {
var elemlist = domDoc.getElementsByTagName( "Street" )
for( iElem=0; iElem < elemlist.length; iElem++ ) {
var elem = elemlist.item( iElem );
var child = elem.firstChild;
do {
if( child.nodeType == 3 ){ // text node
var svar = child.substringData( 3, 99 );
document.writeln( "svar = " + svar );
}
child = child.nextSibling;
} while ( child != null )
}
}
163
DOMComment object
DOMComment object
Object The DOMComment object represents the text within a comment in an XML
document.
Syntax To use a DOMComment’s property:
DOMComment.propertyName
To use a DOMComment’s method:
DOMComment.MethodName( parameter )
Description The DOMComment object has no properties or methods of its own, but it does
inherit the properties and methods of the DOMCharacterData object.
See also “DOMCharacterData object” on page 158.
164
CHAPTER 3 DynaScript Predefined Objects
DOMDocument object
Object Represents an XML document.
Syntax To use a DOMDocument’s property:
DOMDocument.propertyName
To use a DOMDocument’s method:
DOMDocument.MethodName( parameter )
Description The DOMDocument object represents the root of the DOM document node tree,
and provides the primary access to the document’s data.
You can create a DOMDocument object either by calling the toDOMDocument
method, or by invoking the DOMDocument constructor.
• Calling toDOMDocument parses an existing XML document and returns a
DOMDocument object representing the document contents.
• Invoking the DOMDocument constructor creates an empty DOMDocument
object. The node object creation methods on the DOMDocument can then
be called to create new node objects. The created DOMNode objects have
an ownerDocument property which associates them with the
DOMDocument within whose context they were created.
DOMDocument objects inherit all of the properties and methods of the DOMNode
object as well as the properties and methods defined here.
Dynamo's current implementation of DOM follows the DOM Level 1
specification.
Example This statement creates a new, empty DOMDocument object.
doc = new DOMDocument()
165
DOMDocument properties
DOMDocument properties
The DOMDocument object inherits all the properties of the DOMNode object, as
well as the properties discussed in this section.
doctype property
Syntax DOMDocument.doctype
Description The DOMDocumentType object representing the document type declaration
(DTD) associated with this document. XML documents without a DTD return
null. DOM Level 1 does not support editing the DTD.
Example To return the DTD associated with the parsed XML document domDoc.
dtd = domDoc.doctype
See also “DOMDocumentType object” on page 173.
documentElement property
Syntax DOMDocument.documentElement
Description Each XML document has a single element that contains all other elements in
the document. This is called the root element or the document element. The
documentElement method returns the DOMElement object representing the
root element of the XML document.
Example To parse a document held in xmlString, create a variable holding the root
element of the document, and write out the name of that element, enter:
domDoc = toDOMDocument( xmlString );
docElement = domDoc.documentElement;
document.writeln( docElement.tagName );
implementation property
Syntax DOMDocument.implementation
Description The DOMImplementation object that handles this document. The
implementation features can then be retrieved using the hasFeature method
of the DOMImplementation object.
Example This example writes out details of the current implementation.
166
CHAPTER 3 DynaScript Predefined Objects
imp = domDoc.implementation;
document.writeln( "HTML? " + imp.hasFeature( "HTML",
"1.0" ) ) ;
document.writeln( "XML? " + imp.hasFeature( "XML",
"1.0" ) ) ;
The output from this example is:
HTML? false
XML? true
See also “DOMImplementation object” on page 187.
167
DOMDocument methods
DOMDocument methods
The DOMDocument object inherits the methods from the DOMNode object, as
well as the methods discussed in this section.
createAttribute method
Syntax DOMDocument.createAttribute( name )
Description Creates a DOMAttribute object representing an attribute of the given name.
The created attribute does not have any place in the document. It can be set on
an element by using the setAttributeNode method of a DOMElement
object, and the value of the attribute can be set using the setAttribute
method of a DOMElement object.
name is the name of the attribute for which a DOMAttribute object is being
created.
Return A DOMAttribute object.
Example This example creates an attribute named Region.
domDoc.createAttribute( "Region" );
See also “DOMAttribute object” on page 153.
“setAttribute method” on page 181.
createCDATASection method
Syntax DOMDocument.createCDATASection( data )
Description Creates a CDATA node whose value is the specified string. data is the content
of the CDATA section.
The created CDATA section does not have any place in the document. It can be
added as the child of a node by using the appendChild method of a DOMNode
object.
Return A DOMCDATASection object.
Example This example creates a CDATA section with text “Jane & John Doe”, and adds
it to the document as the last element before the end of the document element.
xmlString = "Jane & John Doe"
domCDATA = domDoc.createCDATASection( xmlString );
168
CHAPTER 3 DynaScript Predefined Objects
element.appendChild( domCDATA );
See also “DOMCDATASection object” on page 157.
“appendChild method” on page 202.
createComment method
Syntax DOMDocument.createComment( comment )
Description Creates a DOMComment object representing a comment containing the specified
string. comment should contain the text of the comment only, and should
exclude the comment start (<!--) and end (-->) characters.
The DOMComment object can be added as the child of a node in the document
using the DOMNode.appendChild method, or one of the other DOMNode
methods.
Return A DOMComment object.
Example This example creates a comment on the document domDoc and adds it to the
document as the final element before the end of the document element
(docElem).
domComment = domDoc.createComment(
"Browsers ignore this string" );
docElem.appendChild( domComment );
See also “DOMComment object” on page 163.
“DOMNode methods” on page 202.
createDocumentFragment method
Syntax DOMDocument.createDocumentFragment( )
Description Creates an empty DOMDocumentFragment object. These fragments can be
used in copy and paste operations.
Return A document fragment
Example To create a document fragment, enter:
domDoc.createDocumentFragment;
See also “DOMDocumentFragment object” on page 172.
“DOMNode methods” on page 202.
169
DOMDocument methods
createElement method
Syntax DOMDocument.createElement( tagName )
Description Creates a DOMElement object representing the specified element. tagName is
the name of the element type that is to be instantiated. Tag names in XML are
case-sensitive.
The element can be added as the child of a node using
DOMNode.appendChild method, or one of the other DOMNode methods.
Return A DOMElement object
Example This example creates an element named Customer.
domDoc.createElement( "Customer" );
See also “DOMElement object” on page 176.
“DOMNode methods” on page 202.
createEntityReference method
Syntax DOMDocument.createEntityReference( name )
Description Creates a DOMEntityReference object with the specified name.
Return A DOMEntityReference object.
Example This example creates a reference to the entity for the less than sign (left angle
bracket).
domDoc.createEntityReference( "lt" );
See also “DOMEntityReference object” on page 186.
“DOMNode methods” on page 202.
createProcessingInstruction method
Syntax DOMDocument.createProcessingInstruction( target, data )
Description Creates a DOMProcessingInstruction object given the specified target and
data strings. The parameters are:
•target The target part of the processing instruction.
•data The data for the object.
170
CHAPTER 3 DynaScript Predefined Objects
createTextNode method
Syntax DOMDocument.createTextNode( data )
Description Creates a DOMText object representing the specified data string.
Return A DOMText object.
Example This example creates a text node with content “Bartlebooth”.
domDoc.createTextNode( "Bartlebooth" )
See also “DOMNode methods” on page 202
getElementsByTagName method
Syntax DOMDocument.getElementsByTagName( tagname )
Description Returns a DOMNodeList object of all the DOMElement objects with a given tag
name in the order in which they would be encountered in the document. Tag
names in XML are case-sensitive. The special tag name “*” can be used to
retrieve a list of all DOMElement objects regardless of the tag name.
To search for DOMElement objects that are children of a particular element, use
the getElementsByTagName method on the DOMElement object.
Return A DOMNodeList object containing all the matched objects.
Example This example gets all elements named Region from the document domDoc,
and loops over those elements.
elemList = domDoc.getElementsByTagName( "Region" );
for( iElem=0; iElem < elemList.length; iElem++ ){
171
DOMDocument methods
prettyPrint method
Syntax DOMDocument.prettyPrint()
Description This method is not part of the DOM specification, and is provided for
debugging purposes.
Return A string containing a representation of the document structure.
Example To print out the entire structure of a document named domDoc, enter:
document.writeln( domDoc.prettyPrint() );
172
CHAPTER 3 DynaScript Predefined Objects
DOMDocumentFragment object
Object Represents a collection of node objects, and is typically used to represent a
portion of an XML document.
Syntax To use a DOMDocumentFragment’s property:
DOMDocumentFragment.propertyName
To use a DOMDocumentFragment’s method:
DOMDocumentFragment.MethodName( parameter )
Description The DOMDocumentFragment holds fragments of a DOMDocument object and
can be useful when you are rearranging documents.
When a DOMDocumentFragment object is inserted into the DOM document
tree, the children of the DOMDocumentFragment and not the
DOMDocumentFragment itself are inserted.
The DOMDocumentFragment object has no methods or properties of its own
but it does inherit all of the properties and methods of the DOMNode object.
See also “DOMNode object” on page 194
173
DOMDocumentType object
DOMDocumentType object
Object Represents the document type definition (DTD) portion of an XML document.
Syntax To use a DOMDocumentType’s property:
DOMDocumentType.propertyName
To use a DOMDocumentType’s method:
DOMDocumentType.MethodName( parameter )
Description The DOMDocumentType object is accessible through the docType property of
a DOMDocument object. The DOMDocumentType object provides access to the
list of entities and notations declared in the DTD. DOM Level 1 does not
support access to any other portion of the DTD.
The DOMDocumentType object has no methods of its own, but it does inherit
all of the properties and methods from the DOMNode object as well as the
properties defined here.
Example This example assigns a DOMDocumentType object to the variable dtd.
var xmlDoc = document.value.xml ;
var domDoc = toDOMDocument( xmlDoc );
var dtd = domDoc.doctype;
174
CHAPTER 3 DynaScript Predefined Objects
DOMDocumentType properties
The DOMDocumentType object inherits all properties from the DOMNode
object, but it also has its own properties, which are discussed in this section.
entities property
Syntax DOMDocumentType.entities
Description A DOMNamedNodeMap object containing the general entities both external and
internal. Each node in the node map is a DOMEntity object.
Example This XML document has a very simple DTD, consisting only of entity
declarations (only the first part of the document is shown).
<?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>Jessie...
If this XML document is held in a string named xmlDoc, this script writes out
the entity names.
var domDoc = toDOMDocument( xmlDoc );
var dtd = domDoc.doctype;
var entlist = dtd.entities
for( iEnt = 0; iEnt < entlist.length; iEnt++ ){
ent = entlist.item(iEnt);
document.writeln( "Name = " + ent.nodeName );
}
The output from this example is:
Name = PQ
Name = Logo
See also “DOMEntity object” on page 183.
“DOMNamedNodeMap object” on page 189.
name property
Syntax DOMDocumentType.name
175
DOMDocumentType properties
Description A string containing the name of the DTD that immediately follows the
DOCTYPE keyword.
In XML, the name of the DTD must match that of the document element.
Example This XML document has a very simple DTD, consisting only of entity
declarations (only the first part of the document is shown).
<?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>Jessie...
If this XML document is held in a string named xmlDoc, this script writes out
the DTD name.
var domDoc = toDOMDocument( xmlDoc.source);
var dtd = domDoc.doctype;
document.writeln( "Doctype name = " + dtd.name );
See also “documentElement property” on page 165.
notations property
Syntax DOMDocumentType.notations
Description A DOMNamedNodeMap containing the notations declared in the DTD. Each
node in the node map is a DOMNotation object.
Example This XML document has a very simple DTD, consisting only of entity
declarations (only the first part of the document is shown).
<?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>Jessie...
If this XML document is held in a string named xmlDoc, this script writes out
the notation name of the Logo entity.
See also “DOMNotation object” on page 208.
“DOMNamedNodeMap object” on page 189.
176
CHAPTER 3 DynaScript Predefined Objects
DOMElement object
Object Represents an element in an XML document.
Syntax To use a DOMElement’s property:
DOMElement.propertyName
To use a DOMElement’s method:
DOMElement.MethodName( parameter )
Description The getAttributes method of the DOMNode object can be used to get the set
of all attributes for an element. The getAttribute and getAttributeNode
methods on the DOMElement object can be used to retrieve individual
attributes.
DOMElement objects have all of the properties and methods of the DOMNode
object as well as the properties and methods defined here.
Example This example contains three elements – invoice, customer, and total:
<invoice >
<customer>Jina Janson</customer>
<total>$23.95</total>
</invoice>
177
DOMElement property
DOMElement property
The DOMElement object inherits all of the properties of the DOMNode object,
as well as the tagName property, discussed here.
tagName property
Syntax DOMElement.tagName
Description A string containing the name of the element. Element names are case-sensitive
in XML.
Example This example writes out the name of the document element of an XML DOM
document stored in domDoc.
docElem = domDoc.documentElement;
document.writeln( docElem.tagName );
178
CHAPTER 3 DynaScript Predefined Objects
DOMElement methods
The DOMElement object inherits all of the methods of the DOMNode object, but
it also has its own methods, which are discussed in this section.
getAttribute method
Syntax DOMElement.getAttribute( name )
Description Retrieves an attribute value by name.
Return The attribute value as a string or an empty string if the attribute does not have
value.
Example This example writes out the value of the Type attribute for each Region
element in a DOM document stored in the variable domDoc.
elemlist = domDoc.getElementsByTagName( "Region" );
for ( iEl = 0 ; iEl < elemlist.length ; iEl++ ){
elem = elemlist.item(iEl);
document.writeln( elem.getAttribute( "Type" ) );
}
getAttributeNode method
Syntax DOMElement.getAttributeNode( name )
Description Retrieves an attribute node by name.
Return A DOMAttribute object or null if there is no such attribute.
Example This example assigns a DOMAttribute object to a variable named attnode.
This object represents the Type attribute for a Region element in the DOM
document domDoc.
elemlist = domDoc.getElementsByTagName( "Region" );
for ( iEl = 0 ; iEl < elemlist.length ; iEl++ ){
elem = elemlist.item(iEl);
attnode = elem.getAttributeNode( "Type" );
document.writeln( attnode.nodeValue );
}
See also “DOMAttribute object” on page 153.
179
DOMElement methods
getElementsByTagName method
Syntax DOMElement.getElementsByTagName( name )
Description Returns a DOMNodeList object of all descendant elements with a given tag
name, in the order in which they would be encountered in the document. Tag
names in XML are case-sensitive. The special tag name “*” can be used to
retrieve a list of DOMElement objects regardless of the tag name.
To search for DOMElement objects in the entire document, use the
getElementsByTagName method on the DOMDocument object.
Return A list of matching Element nodes.
Example Here is a simple XML document with a nested structure:
<?xml version="1.0"?>
<List>
<ListItem>Item 1
<List><ListItem>Item 1.1</ListItem>
</List>
</ListItem>
<ListItem>Item 2</ListItem>
</List>
This script fragment writes out the text content of each ListItem element, in the
order in which they are encountered.
var docElem = domDoc.documentElement;
elemlist = docElem.getElementsByTagName( "ListItem" );
document.writeln( elemlist.length) ;
for( iEl=0; iEl < elemlist.length ; iEl++ ){
document.writeln(
elemlist.item(iEl).firstChild.nodeValue );
}
The output from this example is:
Item 1
Item 1.1
Item 2
See also “DOMNodeList object” on page 205.
normalize method
Syntax DOMElement.normalize( )
180
CHAPTER 3 DynaScript Predefined Objects
Description Normalizing an element places it and all its descendants into a standard format.
For all DOMText node objects that are descendants of this element, adjacent
(sibling) DOMText objects are combined into a single DOMText object.
Adjacent DOMCDATASection nodes are not combined even though they inherit
from DOMText.
Example This statement normalizes the element named elem.
elem.normalize();
removeAttribute method
Syntax DOMElement.removeAttribute( att_name )
Description Removes the specified attribute. att_name is the name of the attribute to be
removed.
The method returns nothing, as required by the DOM specification. This means
there is no natural way to check for the success of the method. You can,
however while debugging and testing, execute a prettyPrint() on the
element after the call.
Return This method returns nothing.
Example This function removes all Type attributes from Region elements in a
DOMDocument object stored in domDoc.
function RemoveTypeAttribute( domDoc ) {
elemlist = domDoc.getElementsByTagName( "Region" );
for( iElem=0; iElem < elemlist.length; iElem++ ) {
elem = elemlist.item( iElem );
elem.removeAttribute( "Type" );
}
}
See also “DOMAttribute object” on page 153.
removeAttributeNode method
Syntax DOMElement.removeAttributeNode( att_node )
Description Removes the specified attribute node.
Return The DOMAttribute object that was removed.
181
DOMElement methods
Example This example removes all Type attributes from Region elements in a
DOMDocument object stored in domDoc. It confirms the removal by writing
out the name of the removed attribute.
function RemoveTypeAttribute( domDoc ) {
elemlist = domDoc.getElementsByTagName( "Region" );
for( iElem=0; iElem < elemlist.length; iElem++ ) {
elem = elemlist.item( iElem );
attnode = elem.getAttributeNode( "Type" )
old_att = elem.removeAttributeNode( attnode );
document.writeln( "Attribute " + old_att.name +
"removed" );
}
}
See also “DOMAttribute object” on page 153.
setAttribute method
Syntax DOMElement.setAttribute( name, value )
Description Adds a new attribute to the element. If an attribute with that name is already
present in the element, its value is changed to be that of the value parameter.
The parameters are:
•name The name of the attribute to create or alter.
•value Value to set in string form. The string is not parsed, so any markup
is treated as literal text and may need to be escaped.
To assign an attribute value that contains entity references, first create a
DOMAttribute object, plus any DOMText and DOMEntityReference
objects. Then insert the text and entity reference objects as children of the
DOMAttribute, and use setAttributeNode to assign the attribute to the
element.
Example This function changes the value of the Type attribute for all Region elements
from its current setting to County.
function SetAttribute( domDoc ){
elemlist = domDoc.getElementsByTagName( "Region" );
for( iElem=0; iElem < elemlist.length; iElem++ ) {
elem = elemlist.item( iElem );
elem.setAttribute( "Type", "County" )
document.writeln( elem.prettyPrint() );
}
}
182
CHAPTER 3 DynaScript Predefined Objects
setAttributeNode method
Syntax DOMElement.setAttributeNode( newAttr )
Description Adds a new attribute. If an attribute with that name is already present in the
element, it is replaced by the new one. newAttr is the DOMAttribute object
representing the attribute to be set.
Return If the newAttr attribute replaces an existing attribute with the same name, the
previously existing DOMAttribute object is returned, otherwise null is
returned.
Example This function resets the value of the Type attribute for reach Region element to
County. It then uses prettyPrint to display the structure of the document for
debugging purposes.
function SetAttributeNode( domDoc ){
elemlist = domDoc.getElementsByTagName( "Region" );
for( iElem=0; iElem < elemlist.length; iElem++ ) {
elem = elemlist.item( iElem );
attnode = elem.getAttributeNode( "Type" );
attnode.value = "County";
old_att = elem.setAttributeNode( attnode );
}
document.writeln( domDoc.prettyPrint() );
}
See also “DOMAttribute object” on page 153.
183
DOMEntity object
DOMEntity object
Object Represents an entity declared in the document type declaration (DTD).
Syntax To use a DOMEntity’s property:
DOMEntity.propertyName
To use a DOMEntity’s method:
DOMEntity.MethodName( parameter )
Description The DOMEntity object has no methods of its own, but it does inherit all the
properties and methods of the DOMNode object, and has its own properties,
which are discussed in this section.
184
CHAPTER 3 DynaScript Predefined Objects
DOMEntity properties
The DOMEntity object inherits all the properties of the DOMNode object, as
well as the properties discussed in this section.
notationName property
Syntax DOMEntity.notationName
Description For unparsed entities, the name of the notation for the entity. For parsed entities
this is null.
Example This XML document has a very simple DTD, consisting only of entity
declarations (only the first part of the document is shown).
<?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>Jessie...
If the parsed XML document is held in a variable named domDoc, this script
writes out the notation names of each entity declared in the DTD.
var dtd = domDoc.doctype;
var entlist = dtd.entities
for( iEnt = 0; iEnt < entlist.length; iEnt++ ){
ent = entlist.item(iEnt);
document.writeln( "notationName = " +
ent.notationName );
}
The output of this example is:
notationName = null
notationName = GIF
publicId property
Syntax DOMEntity.publicId
Description The public identifier associated with the entity, if specified. If the public
identifier is not specified, it is null.
Example This declaration has a public identifier.
185
DOMEntity properties
systemId property
Syntax DOMEntity.systemId
Description The system identifier associated with the entity, if specified. Or null, if not
specified.
Example This XML document has a very simple DTD, consisting only of entity
declarations. Only the first part of the document is shown.
<?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>Jessie...
If the parsed XML document is held in a variable named domDoc, this script
writes out the notation names of each entity declared in the DTD.
var dtd = domDoc.doctype;
var entlist = dtd.entities
for( iEnt = 0; iEnt < entlist.length; iEnt++ ){
ent = entlist.item(iEnt);
document.writeln( "systemId = " +
ent.systemId );
}
This example is:
systemId = null
systemId = nautilus.gif
186
CHAPTER 3 DynaScript Predefined Objects
DOMEntityReference object
Object Represents an entity reference in an XML document.
Syntax To use a DOMEntityReference’s property:
DOMEntityReference.propertyName
To use a DOMEntityReference’s method:
DOMEntityReference.MethodName( parameter )
Description The DOMEntityReference object has no properties or methods of its own,
but it does inherit all of the properties and methods of the DOMNode object. The
children of the DOMEntityReference object represent the replacement value
of the entity reference.
See also “DOMNode object” on page 194.
“DOMEntity object” on page 183.
187
DOMImplementation object
DOMImplementation object
Object Provides a means of querying the capabilities of this application’s
implementation of DOM.
Syntax To use a DOMImplementation’s method:
DOMImplementation.MethodName( parameter )
Description The DOMImplementation object has one method used to query the features
supported by this specific implementation of DOM. This method is
independent of any particular instance of a DOMDocument.
Dynamo’s current implementation of DOM supports parsing of XML 1.0
documents according to DOM Level 1.
188
CHAPTER 3 DynaScript Predefined Objects
DOMImplementation methods
The DOMImplementation object has these methods:
hasFeature method
Syntax DOMImplementation.hasFeature( feature, version )
Description Tests if the DOM implementation includes a specific feature. The parameters
are:
•feature The package name of the feature to test. This can be “HTML” or
“XML”.
•version The version number of the package to test. Currently the only
valid value for this parameter is “1.0”, because Dynamo supports XML
1.0.
Return Boolean. True if the feature is implemented in the specified version, false
otherwise.
Example To write out the features supported by the Dynamo XML parser, enter:
domDoc = new DOMDocument();
implementation = domDoc.implementation;
document.writeln( "HTML? " + implementation.hasFeature(
"HTML", "1.0" ) ) ;
document.writeln( "XML? " + implementation.hasFeature(
"XML", "1.0" ) );
The output is:
HTML? false
XML? true
189
DOMNamedNodeMap object
DOMNamedNodeMap object
Object Represents a collection of DOMNode objects that can be accessed by name.
Syntax To use a DOMNamedNodeMap’s property:
DOMNamedNodeMap.propertyName
To use a DOMNamedNodeMap’s method:
DOMNamedNodeMap.MethodName( parameter )
Description DOMNamedNodeMap objects represent an unordered collection of DOMNode
objects. Objects within the node map can be accessed by an ordinal index, but
this is simply provided as a means of enumerating the objects within the node
map. It does not imply that the objects within the node map are ordered.
190
CHAPTER 3 DynaScript Predefined Objects
DOMNamedNodeMap property
The DOMNamedNodeMap object has these properties:
length property
Syntax DOMNamedNodeMap.length
Description The number of objects in the map.
Example This example loops over the items of a DOMNamedNodeMap object.
for ( i = 0; i < nodemap.length; i++ ){
// operations here
}
See also “DOMNamedNodeMap object” on page 189
191
DOMNamedNodeMap methods
DOMNamedNodeMap methods
The DOMNamedNodeMap object has these methods:
getNamedItem method
Syntax DOMNamedNodeMap.getNamedItem( name )
Description Retrieves a DOMNode specified by name.
Return A DOMNode object or null if the specified name did not identify any node in the
map.
Example This example creates a DOMNamedNodeMap named attlist from the
attributes property of an element, and then writes out the value of the
attribute with name attName.
attlist = elem.attributes
att = attlist.getNamedItem( attName );
document.writeln( att.value );
See also “DOMNode object” on page 194.
item method
Syntax DOMNamedNodeMap.item( index )
Description Returns the index item in the map. If index is greater than or equal to the
number of nodes in the map, null is returned. Valid values for index are 0
through length – 1.
Return A DOMNode object or null if the index is invalid.
Example This script fragment loops over the items of a DOMNamedNodeMap object and
assigns each node to a variable named thisNode.
for ( i = 0; i < nodemap.length; i++ ){
thisNode = nodemap.item( i );
}
removeNamedItem method
Syntax DOMNamedNodeMap.removeNamedItem( name )
Description Removes a DOMNode object specified by name.
192
CHAPTER 3 DynaScript Predefined Objects
Return The DOMNode object that was removed or null if the specified name did not
identify any node in the map.
Example This example removes the attribute named attType from each Region element,
and prints out messages for debugging purposes.
function RemoveNamedItem( domDoc, attType ){
elemlist = domDoc.getElementsByTagName( "Region" )
for( iElem=0; iElem < elemlist.length; iElem++ ) {
elem = elemlist.item( iElem );
attlist = elem.attributes
node = attlist.removeNamedItem( attType );
if( node == null ) {
document.writeln( "No attribute removed" );
} else {
document.writeln( "Removed attribute with value"
+ node.nodeValue );
}
}
document.writeln( domDoc.prettyPrint() );
}
See also “DOMNode object” on page 194
setNamedItem method
Syntax DOMNamedNodeMap.setNamedItem( node-name )
Description Adds a node using its nodeName property. The node-name parameter is a
DOMNode object to be stored in the named node map. The node will later be
accessible using the value of the node's nodeName property passed to the
getNamedItem method.
Return If the new node replaces an existing node with the same name, the previously
existing node is returned as a DOMNode object, otherwise null is returned.
Example This example replaces an attribute node with one of the same name, but a
changed value.
function SetNamedItem( domDoc, attType ){
elemlist = domDoc.getElementsByTagName( "Region" )
for( iElem=0; iElem < elemlist.length; iElem++ ) {
elem = elemlist.item( iElem );
attlist = elem.attributes
att = attlist.getNamedItem( attType );
att.value = "County";
oldNode = attlist.setNamedItem( att.name );
193
DOMNamedNodeMap methods
194
CHAPTER 3 DynaScript Predefined Objects
DOMNode object
Object Represents a single node in the DOM document tree.
Syntax To use a DOMNode’s property:
DOMNode.propertyName
To use a DOMNode’s method:
DOMNode.MethodName( parameter )
Description The DOMNode object is the primary object type for the entire Document Object
Model (DOM) suite of objects. It is the object from which most of the other
DOM objects inherit.
Each object that inherits from the DOMNode exposes a nodeType property to
identify the object. See the nodeType property below for valid values for the
nodeType.
All objects inheriting from the DOMNode object expose methods for dealing
with children, but not all node types necessarily have children. For example,
text nodes cannot have children. See the childNodes property below for a list
of which types of nodes can have children.
While each object that inherits from DOMNode exposes an attributes property,
only DOMElement objects can have attributes.
195
DOMNode properties
DOMNode properties
The DOMNode object has these properties:
attributes property
Syntax DOMNode.attributes
Description A DOMNamedNodeMap containing the attributes of this node. This property is
applicable only to nodes that are elements.
Example This fragment tests to see if a node is an element, and assigns the attributes of
the element to a DOMNamedNodeMap named attlist.
if( node.nodeType == 1 ){ // Element
attlist = node.attributes
} else {
document.writeln( "Not an element" );
}
See also “DOMNamedNodeMap object” on page 189.
childNodes property
Syntax DOMNode.childNodes
Description A DOMNodeList object that contains all the children of this node. If there are
no children, then this is a node list containing zero nodes.
Performance tip
To loop over a childNodes list, it is more efficient to use the nextSibling
property than to explicitly use the childNodes list of the parent object.
Not all nodes can have children. This table lists the types of children that are
valid for each type of node.
Node Type Node Types Valid for Children
document element (maximum of one), processing instruction,
comment, document type
document fragment element, processing instruction, comment, text,
CDATA section, entity reference
document type no children
196
CHAPTER 3 DynaScript Predefined Objects
firstChild property
Syntax DOMNode.firstChild
Description The DOMNode object representing the first child of this node, or null if there are
no children.
Example This fragment sets the variable node to the first child of the document element.
var docElem = domDoc.documentElement;
var node = docElem.firstChild;
lastChild property
Syntax DOMNode.lastChild
197
DOMNode properties
Description The DOMNode object representing the last child of this node, or null if there are
no children.
Example This fragment sets the variable node to the last child of the document element.
var docElem = domDoc.documentElement;
var node = docElem.lastChild;
nextSibling property
Syntax DOMNode.nextSibling
Description The DOMNode object representing the node immediately following this node,
or null if this is the last node.
Example This fragment loops over the siblings of an element named node.
do {
document.writeln( node.nodeName );
node = node.nextSibling;
} while ( node != null )
nodeName property
Syntax DOMNode.nodeName
Description The name of this node. The name of the node depends on the node type. This
table lists the contents of the nodeName property for each node type.
Node Type Contents of nodeName property
document “document”
document fragment “document-fragment”
document type document type name
entity reference name of entity referenced
element tag name
attribute name of attribute
processing instruction target
comment “comment”
text “text”
CDATA section “cdata-section”
entity entity name
notation notation name
198
CHAPTER 3 DynaScript Predefined Objects
XML is case sensitive. If you check the name of a node in a comparison, you
must ensure the check is case sensitive.
Example This fragment writes out the name of each of a set of nodes, held in a variable
named node.
do {
document.writeln( node.nodeName );
node = node.nextSibling;
} while ( node != null )
See also “getElementsByTagName method” on page 179.
nodeType property
Syntax DOMNode.nodeType
Description An integer representing the type of node object. This table lists the nodeType
number for each type of node.
Node Type Contents of nodeType property
element 1
attribute 2
text 3
CDATA section 4
entity reference 5
entity 6
processing instruction 7
comment 8
document 9
document type 10
document fragment 11
notation 12
Example This fragment performs different operations based on the type of node. The
node is held in a variable named domNode.
switch domNode.nodeType {
case 1:
//element operations
break;
case 2:
//attribute operations
break;
199
DOMNode properties
case 3:
//text operations
break;
case 4:
//CDATA section operations
break;
case 5:
//entity reference operations
break;
case 6:
//entity operations
break;
case 7:
// processing instruction operations
break;
case 8:
//comment operations
break;
case 9:
//document operations
break;
case 10:
// document type operations
break;
case 11:
// document fragment operations
break;
case 12:
//notation operations
break;
default:
document.writeln( "Invalid node type: " +
domChild.nodeType );
}
nodeValue property
Syntax DOMNode.nodeValue
Description The value of this node. The value depends on the type of node. This table lists
the contents of the nodeValue property for each node type.
Node Type Contents of nodeValue property
document null
200
CHAPTER 3 DynaScript Predefined Objects
Example This fragment writes out the nodeValue for an attribute named Type:
if( domAtt.nodeName == "Type" ){
document.writeln( domAtt.nodeValue );
}
ownerDocument property
Syntax DOMNode.ownerDocument
Description The DOMDocument object associated with this node. For DOMDocument
objects, this property is null.
Example This fragment writes out the name of the document element for the
DOMDocument object that owns domNode.
var domDoc = domNode.ownerDocument;
document.writeln( domDoc.documentElement.nodeName );
See also “DOMDocument object” on page 164.
parentNode property
Syntax DOMNode.parentNode
Description The DOMNode object representing the parent of this node, or null if there is no
parent. This node objects do not have a parent: DOMDocument,
DOMDocumentFragment, DOMAttribute, DOMEntity,
DOMDocumentType, and DOMNotation.
201
DOMNode properties
Example This example writes out the parent of the node held in the variable domNode,
if it exists.
if( domNode.parentNode != null ){
document.writeln( domNode.parentNode.nodeName;
}
previousSibling property
Syntax DOMNode.previousSibling
Description The DOMNode object representing the node immediately preceding this node,
or null if no nodes precede this node.
Example This function loops backwards through the children of a node.
function BackwardsChildNodes( domNode ){
var domChild = domNode.lastChild;
do {
document.writeln( domChild.nodeName );
domChild = domChild.previousSibling;
} while ( domChild != null )
}
202
CHAPTER 3 DynaScript Predefined Objects
DOMNode methods
The DOMNode object has these methods:
appendChild method
Syntax DOMNode.appendChild( newChild )
Description Adds the DOMNode newChild to the end of the list of children of this node. If
newChild already exists in the tree, it is first removed.
Return The DOMNode which was added or null if the node could not be appended (for
example, if newChild is not a valid type of child for this node).
Example This fragment adds a child element to a node held in the customer variable.
new_elem = domDoc.createElement( "Name" );
new_text = domDoc.createTextNode("Ann T. Dote" );
el = customer.appendChild( new_elem );
el.appendChild( new_text );
cloneNode method
Syntax DOMNode.cloneNode( deep )
Description Returns a duplicate of this DOMNode. The duplicate node has no parent. deep is
a Boolean indicating whether to clone the subtree under this node.
For DOMElement objects, all attributes and their values are copied.
Return The duplicate DOMNode.
Example This fragment makes a duplicate of the first child of a document element (and
its subtree) and adds it to the end of the list of its children. The call to
prettyPrint is for debugging purposes.
var docElem = domDoc.documentElement;
var thisNode = docElem.firstChild;
var newNode = thisNode.cloneNode( true );
docElem.appendChild( newNode );
document.writeln( domDoc.prettyPrint() );
203
DOMNode methods
hasChildNodes method
Syntax DOMNode.hasChildNodes( )
Description Indicates whether a node has any children
Return Boolean.
Example This statement tests to see whether thisNode has any children.
if( thisNode.hasChildNodes() ){
// operations here
}
insertBefore method
Syntax DOMNode.insertBefore( newChild, refChild )
Description Inserts the DOMNode newChild before the existing child DOMNode refChild. If
refChild is null, newChild is inserted at the end of the list of children.
If newChild is a DOMDocumentFragment, all of its children are inserted, in
order, before refChild. If newChild already exists in the tree, it is first removed.
Return The inserted DOMNode, or null if the node could not be inserted (for example,
if refChild is not a child of this node).
Example This fragment makes a duplicate of the first child of a document element (and
its subtree) and adds it as the penultimate child. The call to prettyPrint is
for debugging purposes.
var docElem = domDoc.documentElement;
var thisNode = docElem.firstChild;
var newNode = thisNode.cloneNode( true );
docElem.insertBefore( newNode, docElem.lastChild );
document.writeln( domDoc.prettyPrint() );
removeChild method
Syntax DOMNode.removeChild( oldChild )
Description Removes from the list of children, the child node indicated by oldChild.
Return The removed DOMNode or null if the child could not be removed (for example,
if oldChild is not a child of this node.
204
CHAPTER 3 DynaScript Predefined Objects
Example This fragment removes the last child of the document element from a
document.
var docElem = domDoc.documentElement;
var thisNode = docElem.lastChild;
var oldNode = docElem.removeChild( thisNode );
replaceChild method
Syntax DOMNode.replaceChild( newChild, oldChild )
Description Replaces the child DOMNode oldChild with the DOMNode newChild in the list
of children. If newChild already exists in the tree, it is first removed.
Return The replaced DOMNode (oldChild) or null if the node could not be replaced (for
example, if oldChild is not a child of this node).
Example This fragment replaces the last child of the document element with the first
child. The first child is removed from its place in the beginning of the list.
var thisNode = docElem.firstChild;
var oldNode = docElem.replaceChild( thisNode,
docElem.lastChild );
205
DOMNodeList object
DOMNodeList object
Object Represents an ordered collection of nodes.
Syntax To use a DOMNodeList’s property:
DOMNodeList.propertyName
To use a DOMNodeList’s method:
DOMNodeList.MethodName( parameter )
Description The DOMNodeList object represents an ordered collection of DOMNode
objects, or any object that inherits from DOMNode. The objects on the node list
are accessible via an integral index. Index values start at zero.
206
CHAPTER 3 DynaScript Predefined Objects
DOMNodeList property
The DOMNodeList object has this property:
length property
Syntax DOMNodeList.length
Description The number of objects in the list.
Example This fragment loops through the items of a DOMNodeList of elements.
for( iElem=0;
iElem < domParent.childNodes.length;
iElem++ ) {
thisChild = domParent.childNodes.item( iElem );
// other operations here
}
207
DOMNodeList methods
DOMNodeList methods
The DOMNodeList object has these methods:
item method
Syntax DOMNodeList.item( index )
Description Returns the indexth item in the collection. Valid values for index are 0 through
length – 1.
Return The node at the indexth position or null if the index is invalid.
Example This fragment loops through the items of a DOMNodeList of elements.
for( iElem=0;
iElem < domParent.childNodes.length;
iElem++ ) {
thisChild = domParent.childNodes.item( iElem );
// other operations here
}
208
CHAPTER 3 DynaScript Predefined Objects
DOMNotation object
Object Represents a notation declared in the DTD.
Syntax To use a DOMNotation’s property:
DOMNotation.propertyName
To use a DOMNotation’s method:
DOMNotation.MethodName( parameter )
Description DOMNotation objects inherit the properties and methods of the DOMNode
object. The nodeName property inherited from DOMNode holds the declared
name of the notation.
A notation node does not have any parent.
209
DOMNotation properties
DOMNotation properties
The DOMNotation object inherits all the properties of the DOMNode object,
and has the properties discussed in this section.
publicId property
Syntax DOMNotation.publicId
Description The public identifier of this notation, or null if no public identifier was
specified.
systemId property
Syntax DOMNotation.systemId
Description The system identifier of this notation, or null if no system identifier was
specified.
210
CHAPTER 3 DynaScript Predefined Objects
DOMNotation methods
The DOMNotation object has no methods of its own but inherits all of the
methods of the DOMNode object.
211
DOMProcessingInstruction object
DOMProcessingInstruction object
Object Represents a processing instruction in the XML document.
Syntax To use a DOMProcessingInstruction’s property:
DOMProcessingInstruction.propertyName
To use a DOMProcessingInstruction’s method:
DOMProcessingInstruction.MethodName( parameter )
Description DOMProcessingInstruction objects have all the properties and methods of
the DOMNode object as well as the properties defined here.
212
CHAPTER 3 DynaScript Predefined Objects
DOMProcessingInstruction properties
The DOMProcessingInstruction object inherits all of the properties of the
DOMNode object, and has its own properties discussed in this section.
data property
Syntax DOMProcessingInstruction.data
Description The content of this processing instruction. This property contains the text
beginning at the first non-white space character after the target to the character
immediately preceding the ?>.
Example This processing instruction has a data property of version=1.0.
<?xml version=’1.0’ ?>
This instruction writes out the data of the processing instruction that is the first
child of the parsed XML document domDoc.
domPI = domDoc.firstChild;
document.writeln( domPI.data );
target property
Syntax DOMProcessingInstruction.target
Description The target of this processing instruction. This is the first token following the
markup that begins the processing instruction.
Examples This processing instruction has a target of xml.
<?xml version=’1.0’ encoding=’ISO-8859-1’ ?>
This instruction writes out the target of the processing instruction that is the
first child of the parsed XML document domDoc.
domPI = domDoc.firstChild;
document.writeln( domPI.target );
213
DOMProcessingInstruction methods
DOMProcessingInstruction methods
The DOMProcessingInstruction object has no methods of its own but
inherits all the methods of the DOMNode object.
214
CHAPTER 3 DynaScript Predefined Objects
215
DOMText properties
DOMText properties
The DOMText object has no properties of its own but does inherit all the
properties of the DOMCharacterData object.
216
CHAPTER 3 DynaScript Predefined Objects
DOMText methods
The DOMText object inherits all the methods of the DOMCharacterData
object, but it also has one of its own methods, which is discussed here.
splitText method
Syntax DOMText.splitText( offset )
Description Breaks this text node into two text nodes at the specified offset, keeping both
in the tree as siblings. offset is the point where the text is to be split, starting
from 0.
After the split, this DOMText object contains the content up to the offset point.
The new DOMText node, added as the next sibling of this node, contains the
content at or after the offset point.
Return The new added DOMText node.
Example This script takes an element that has a single text node as child (holding a street
address), and adds text to the end of that node by splitting the text and then
normalizing:
streetText = streetElement.firstChild;
streetText.splitText(stText.length );
streetElement.lastChild.data = " -- now moved";
streetElement.normalize();
See also “normalize method” on page 179.
217
file object
file object
Object Provides manipulation of files through the file system. These are files external
to the Web site.
For information on manipulating documents internal to the Web site, see “site
object” on page 332.
Syntax To use a file property:
file.propertyName
To use a file method:
file.MethodName( parameter )
Description To manipulate a file, a file object is created to represent the file. To create a file
object, use the file constructor. The syntax to create a new file object is:
fileObj = new File( fileName, accessMode);
The specified file is opened using the access mode provided, and a file object
representing the open file is returned.
Example This example reads information from FILE_A.DAT and adds it to the end of
FILE_B.DAT, converting all tabs to spaces:
<!--SCRIPT
ifile = new File( "FILE_A.DAT", "r" );
ofile = new File( "FILE_B.DAT", "a" );
for( ch = ifile.ReadChar(); !ifile.eof; ch =
ifile.ReadChar() ) {
if( ch == "\t" ) {
ofile.Write( " " );
} else {
ofile.Write( ch );
}
}
ifile.Close();
ofile.Close();
-->
See also “name property” on page 87.
“mode property” on page 307.
218
CHAPTER 3 DynaScript Predefined Objects
file properties
The file object has these properties:
eof property
Syntax file.eof
Attributes This property is read-only.
Description Set to true when an input operation attempts to read past the end of the file.
Example This example reads each character in the file input.txt:
<!--SCRIPT
inputFile = new File( "d:\\test\\input.txt", "r" );
ch = inputFile.ReadChar ();
while ( ! inputFile.eof ) {
ch = inputFile.ReadChar();
}
-->
errorNumber property
Syntax file.errorNumber
Attributes This property is read-only.
Description A number representing the error code of the last file method called. If an error
occurred the errorNumber will be non-zero. The values for errorNumber
and errorString are system dependent and may differ between NT and
versions of UNIX.
Example This example displays the error number that results from opening a file in one
mode and then opening it again in a different mode without closing the first
instance:
<!--SCRIPT
inputFile = new File( "d:\\test\\input.txt", "r" );
ch = inputFile.ReadChar ();
while ( ! inputFile.eof ) {
ch = inputFile.ReadChar();
document.WriteLn( ch );
}
inputFile = new File( "d:\\test\\input.txt", "w" );
document.WriteLn( "The error number is: " +
219
file properties
inputFile.errorNumber );
-->
This example checks for an error code of 0 and returns a message if a new file
is created successfully:
<!--SCRIPT
errorString property
Syntax file.errorString
Attributes This property is read-only.
Description A string containing an error message for the error code of the last file method
called.
Example This example displays an error message if there is a problem with the first file
method called:
<!--SCRIPT
inputFile = new File( "d:\\test\\input5.txt","r" );
document.WriteLn( inputFile.errorString );
line = inputFile.ReadLine();
document.WriteLn( inputFile.GetFilePtr() );
inputFile.Close();
-->
220
CHAPTER 3 DynaScript Predefined Objects
If the file input5.txt cannot be found in the specified directory, the output looks
like:
No such file or directory
null
name property
Syntax file.name
Description Name of the file to be manipulated (string).
Example This example displays the name of the file represented by the file object
myFile:
<!--SCRIPT
myFile = new File( "d:\\test\\input.txt", "r" );
document.WriteLn( myFile.name );
-->
The output from this example is:
input.txt
mode property
Description The access mode with which the file was opened:
Access mode Description
r Open for read-only.
w Open for write, the file length to zero.
a Open for write at end of file.
rb Open binary file for reading.
rt Open text file for reading.
wb Create binary file for writing.
wt Create text file for writing.
ab Open binary file for write at end of file.
at Open text file for write at end of file.
r+ Open file for update (reading/writing).
w+ Create file for update (reading/writing).
a+ Open file for update at end of file.
rb+ Open binary file for update (reading/writing).
221
file properties
Syntax file.mode
Example This example opens the file output.txt and appends the phrase “hello world” to
the end of the file:
<!--SCRIPT
outputFile = new File ( "d:\\test\\output.txt", "a" );
outputFile.Write( "hello world" );
outputFile.Close();
-->
222
CHAPTER 3 DynaScript Predefined Objects
file methods
The file object has these methods:
Close method
Syntax file.Close( )
Description Closes the file associated with the file object.
Return Boolean. Returns true or false indicating whether the file was successfully
closed.
Example This example opens and then closes the file input.txt:
<!--SCRIPT
inputFile = new File ( "d:\\test\\input.txt", "r" );
inputFile.Close()
-->
Delete method
Syntax file.Delete( )
Description Deletes the file associated with the file object. The file must be closed to be
deleted.
Return Boolean. Returns true or false indicating whether the file was successfully
deleted.
Example This example deletes the file input.txt:
<!--SCRIPT
inputFile = new File ( "d:\\test\\input.txt", "r" );
inputFile.Close();
inputFile.Delete()
-->
GetFilePtr method
Syntax file.GetFilePtr( )
Description Returns the current file position. This position defines the position of the next
character read or written.
223
file methods
Open method
Syntax file.Open( )
Description Opens the file specified by the name property in the read/write mode specified
by the mode property.
Return Boolean.
Example This example opens the file data.txt for reading, then reopens the file for
writing:
<!--SCRIPT
dataFile = new File ( "d:\\test\\data.txt", "r" );
dataFile.Close( );
dataFile.mode = "w";
dataFile.Open( );
-->
Read method
Syntax file.Read( numBytes )
Description Reads the contents of a file. numBytes specifies the number of bytes to read. If
no value is given, the entire contents of the file are read. This method is the
recommended way of reading a binary file as ReadChar returns string data and
ReadLine assumes line end characters are present.
Return If the file is opened in text mode, the data returned is a string. If the file was
opened in binary mode, the data returned is of type binary.
Example This example reads the data from the input.txt file and displays it:
<!--SCRIPT
inputFile = new File( "d:\\temp\\input.txt","r" );
224
CHAPTER 3 DynaScript Predefined Objects
data=inputFile.Read();
document.WriteLn( data );
-->
ReadChar method
Syntax file.ReadChar( )
Description The character at the current file position is returned, and the file position is
advanced by one.
Return String. Returns the character read.
Example This example displays the first character of the file input.txt:
<!--SCRIPT
inputFile = new File( "d:\\test\\input.txt","r" );
document.WriteLn( inputFile.ReadChar() );
inputFile.Close();
-->
ReadLine method
Syntax file.ReadLine( )
Description Reads and returns a string starting from the current file position to the next
newline character or until end of file is reached. The newline character is not
discarded.
Return String. Returns the line read.
Example This example displays the first line of the file input.txt:
<!--SCRIPT
inputFile = new File( "d:\\test\\input.txt","r" );
document.WriteLn( inputFile.ReadLine() );
inputFile.Close();
-->
Seek method
Syntax file.Seek(offset)
225
file methods
Description Changes the current file position to the position indicated by offset. This
position defines the position of the next character read or written. The position
of the first character in the file is 0.
Return Boolean. Indicates whether the current file position was successfully set.
Example This example displays the fifth character from the file input.txt:
<!--SCRIPT
inputFile = new File( "d:\\test\\input.txt","r");
inputFile.Seek (4);
document.WriteLn( inputFile.ReadChar() );
inputFile.Close();
-->
Write method
Syntax file.Write(s)
Description The string value of s is written at the current file position. At the end of this
operation, the current file position is set just after the written value.
Return Boolean.
Example This example writes “hello world” to the file d:\test\output.txt, and erases all
other text in the file:
<!--SCRIPT
outputFile = new File ( "d:\\test\\output.txt","w" );
outputFile.Write( "hello world" );
outputFile.Close( );
-->
WriteLine method
Syntax file.WriteLine(s)
Description Identical to the Write method except that a new line is written following the
written value.
Return Boolean.
Example This example writes “hello world” to the file output.txt, and erases all other text
in the file:
<!--SCRIPT
outputFile = new File ( "d:\\test\\output.txt","w" );
226
CHAPTER 3 DynaScript Predefined Objects
227
FTP object
FTP object
Object Allows for FTP access through PowerDynamo.
Syntax To use an FTP method:
FTP.MethodName( parameter )
Description The FTP object has no properties. To use the FTP object, create a connection
to an FTP server using the FTP constructor:
FTPObj = new FTP( ftpServer, ftpUserId, ftpPassword);
Once the connection has been made, you can use the methods of the FTP object
to manipulate files and data between the local and a remote machine.
Example This example creates a connection to an FTP server and puts a file on the
remote machine:
<!--SCRIPT
ftpSybase = new FTP( "ftp.server.com", "Eric", "Smith"
);
ftpSybase.PutFile( "myfile.txt", "c:\\myfile.txt",
"ASCII" );
ftpSybase.Disconnect();
-->
228
CHAPTER 3 DynaScript Predefined Objects
FTP methods
The FTP object has these methods:
ChangeCurrentDirectory method
Syntax FTP.ChangeCurrentDirectory( directoryName )
Description Changes the current directory name on the FTP server.
Return Boolean.
Example This example creates a directory called Dynamo on the FTP server, changes to
that directory, and places a file called test.doc in it:
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
ftpSession.CreateDirectory("Dynamo");
ftpSession.ChangeCurrentDirectory("Dynamo");
if( !ftpSession.PutFile("test.doc",
"g:\\dynamo\\ftp\\test.doc")) {
document.writeln( ftpSession.GetErrorCode() );
document.writeln( ftpSession.GetErrorInfo() );
}
-->
Connect method
Syntax FTP.Connect( )
Description Connects to the FTP server.
Example This example connects to an FTP server and displays the current directory. It
then disconnects and requests again to display the current directory, but no
directory should be displayed. It then connects again, and once again displays
the current directory:
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
curdir = ftpSession.RetrieveCurrentDirectory();
document.WriteLn( "After connect " + curdir );
ftpSession.Disconnect();
curdir = ftpSession.RetrieveCurrentDirectory();
229
FTP methods
CreateDirectory method
Syntax FTP.CreateDirectory( directoryName )
Description Creates a directory on the FTP server.
Return Boolean.
Example This example creates a directory called Dynamo on the FTP server, changes to
that directory, and places a file called test.doc in it:
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
ftpSession.CreateDirectory("Dynamo");
ftpSession.ChangeCurrentDirectory("Dynamo");
if( !ftpSession.PutFile("test.doc",
"g:\\dynamo\\ftp\\test.doc")) {
document.writeln( ftpSession.GetErrorCode() );
document.writeln( ftpSession.GetErrorInfo() );
}
-->
DeleteFile method
Syntax FTP.DeleteFile( fileName )
Description Deletes a file from the FTP server.
Return Boolean.
Example This example deletes the test.doc file:
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
if( !ftpSession.DeleteFile( "test.doc" )) {
document.writeln( ftpSession.GetErrorCode() );
document.writeln( ftpSession.GetErrorInfo() );
230
CHAPTER 3 DynaScript Predefined Objects
}
ftpSession.Disconnect();
-->
Disconnect method
Syntax FTP.Disconnect( )
Description Disconnects from the FTP server.
Example This example connects to an FTP server, deletes a file, then disconnects:
<!--SCRIPT
ftpSession = new FTP ( "ftpserv", "anonymous",
"sam@sybase.com");
ftpSession.ChangeCurrentDirectory( "Dynamo" );
if( !ftpSession.DeleteFile( "test.doc" )) {
document.writeln( ftpSession.GetErrorCode() );
document.writeln( ftpSession.GetErrorInfo() );
}
ftpSession.Disconnect();
-->
GetErrorCode method
Syntax FTP.GetErrorCode( )
Description Returns a code representing the most recent error. This may be either a three-
digit FTP code or a three-digit code in the 900s that has been generated by
Dynamo.
Return Integer.
Example This example puts a file on the FTP server and checks for errors:
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
if( !ftpSession.PutFile("test.doc",
"g:\\dynamo\\ftp\\test.doc")) {
document.writeln( ftpSession.GetErrorCode() );
document.writeln( ftpSession.GetErrorInfo() );
}
-->
231
FTP methods
GetErrorInfo method
Syntax FTP.GetErrorInfo( )
Description Returns a string containing an error message, either from the FTP server or
from PowerDynamo.
Return String.
Example This example places a file on the FTP server and checks for errors:
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
if( !ftpSession.PutFile("test.doc",
"g:\\dynamo\\ftp\\test.doc")) {
document.writeln( ftpSession.GetErrorCode() );
document.writeln( ftpSession.GetErrorInfo() );
}
-->
PutData method
Syntax FTP.PutData( remoteFileName, localData [,transferType,
failIfRemoteFileExists] )
Description Stores Dynamo data to the FTP server from a local machine. The parameters
are:
• remoteFileName The name of the file on the remote machine.
• localData The name of the data variable in your script.
• transferType Can be one of ASCII, binary, EBCDIC, image or local.
The default is binary.
• failIfRemoteFileExists A Boolean specifying the action to be
taken if the file already exists. The default is true.
Return Boolean.
Example This script is called from another script where users already entered their first
and last name and those values are held in document.value.fname and
document.value.lname. This script sends the data in
document.value.lname to a file called putdata.ssc on the FTP server:
<!--SCRIPT
document.writeln("The first name is " +
document.value.fname);
232
CHAPTER 3 DynaScript Predefined Objects
-->
PutDataWithAppend method
Syntax FTP.PutDataWithAppend( remoteFileName, localData [, transferType] )
Description Similar to the PutData method except that if the remote file already exists, the
local data is appended to the end of the file. If the remote file does not exist, a
new file is created.
• remoteFileName The name of the file on the remote machine.
• localData The name of the data on the local machine.
• transferType Can be one of ASCII, binary, EBCDIC, image, or local.
The default is binary.
Return Boolean.
Example This script is called from another script where users entered their first and last
name and those values are held in document.value.fname and
document.value.lname. This script appends the data in
document.value.lname to a file called putdata.ssc on the FTP server:
<!--SCRIPT
document.writeln("The first name is " +
document.value.fname);
document.writeln("The last name is " +
document.value.lname);
233
FTP methods
document.writeln( ftpSession.GetErrorInfo() );
}
ftpSession.Disconnect();
-->
PutDocument method
Syntax FTP.PutDocument( remoteFileName, documentName [, transferType ] )
Description Copies a Dynamo Web site document to an FTP server. The parameters are:
• remoteFileName The name of the file on the remote machine.
• documentName The name of the PowerDynamo document on the local
machine.
• transferType Can be one of ASCII, binary, EBCDIC, image or local.
The default is binary.
Return Boolean.
Example This example puts the Dynamo script test.ssc on the FTP server:
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
PutDocumentWithAppend method
Syntax FTP.PutDocumentWithAppend( remoteFileName, documentName [,
tranferType, failIfRemoteFileExists] )
Description Similar to the PutData method except that if the remote file already exists on
the remote machine the Dynamo document is appended to the end. If the
remote file does not exist, a new file is created. The parameters are:
234
CHAPTER 3 DynaScript Predefined Objects
if( !ftpSession.PutDocumentWithAppend("test.ssc",
"test.ssc")) {
document.writeln( ftpSession.GetErrorCode() );
document.writeln( ftpSession.GetErrorInfo() );
}
ftpSession.Disconnect();
-->
PutFile method
Syntax FTP.PutFile( remoteFileName, localFileName [, transferType,
failIfRemoteFileExists] )
Description Puts a file to the FTP server from the Dynamo machine. The parameters are:
• remoteFileName The name of the file on the remote machine.
• localFileName The name of the file on the local machine.
• transferType Can be one of ASCII, binary, EBCDIC, image, or local.
The default is binary.
• failIfRemoteFileExists A Boolean specifying the action to be
taken if the file already exists. The default is true.
Return Boolean.
Example This example puts a file on the FTP server:
235
FTP methods
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
if( !ftpSession.PutFile("test.doc",
"g:\\dynamo\\ftp\\test.doc")) {
document.writeln( ftpSession.GetErrorCode() );
document.writeln( ftpSession.GetErrorInfo() );
}
-->
PutFileWithAppend method
Syntax FTP.PutFileWithAppend( remoteFileName, localFileName [,
transferType ] )
Description Similar to the PutFile method, except that if a file already exists on the
remote machine, the file is appended to the end. If the file does not already
exist, a new one is created. The parameters are:
• remoteFileName The name of the file on the remote machine.
• localFileName The name of the file on the local machine.
• transferType Can be one of ASCII, binary, EBCDIC, image, or local.
The default is binary.
Return Boolean.
Example This example appends the text in the file test.txt to an existing file called test.txt
on the FTP server:
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
if( !ftpSession.PutFileWithAppend("test.txt",
"g:\\dynamo\\ftp\\test.txt")) {
document.writeln( ftpSession.GetErrorCode() );
document.writeln( ftpSession.GetErrorInfo() );
}
-->
RemoveDirectory method
Syntax FTP.RemoveDirectory( directoryName )
236
CHAPTER 3 DynaScript Predefined Objects
Description Removes a directory from the FTP server. directoryName is the directory to
remove.
Return Boolean.
Example This example deletes a directory called Dynamo from the FTP server:
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
if( !ftpSession.RemoveDirectory( "Dynamo")) {
document.writeln( ftpSession.GetErrorCode() );
document.writeln( ftpSession.GetErrorInfo() );
}
ftpSession.Disconnect();
-->
RetrieveCurrentDirectory method
Syntax FTP.RetrieveCurrentDirectory( )
Description Retrieves the current directory name from the FTP server.
Return String.
Example This example displays the current FTP directory:
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
ftpSession.ChangeCurrentDirectory("Dynamo");
curdir = ftpSession.RetrieveCurrentDirectory();
document.WriteLn( curdir );
ftpSession.Disconnect();
-->
RenameFile method
Syntax FTP.RenameFile( oldFileName, newFileName )
Description Renames a file on the FTP server. The parameters are:
• oldFileName The name of the existing file on the FTP server.
• newFileName The new name for the file.
Return Boolean.
237
FTP methods
Example This example renames a file on the FTP server from test.txt to newtest.txt:
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
if( !ftpSession.RenameFile("test.txt",
"newtest.txt")) {
document.writeln( ftpSession.GetErrorCode() );
document.writeln( ftpSession.GetErrorInfo() );
}
ftpSession.Disconnect();
-->
RetrieveData method
Syntax FTP.RetrieveData( remoteFileName [, transferType] )
Description Retrieves data from the FTP server and turns it into a DynaScript variable. The
parameters are:
• remotefileName The name of the file on the remote machine.
• transferType Can be one of ASCII, binary, EBCDIC, image, or
local. The default is binary.
Return String or binary.
Example This example retrieves data from a file on an FTP server and displays the value:
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
lname = ftpSession.RetrieveData("putdata.ssc");
document.WriteLn("last name: " + lname);
ftpSession.Disconnect();
-->
RetrieveDirectoryListing method
Syntax FTP.RetrieveDirectoryListing( [ directoryName ] )
Description Returns a directory listing from the FTP server. If you do not provide a
directory name, a directory listing from the current directory is provided.
Return List of strings.
238
CHAPTER 3 DynaScript Predefined Objects
Example This example displays a directory listing for the FTP server:
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
dir = ftpSession.RetrieveDirectoryListing();
document.WriteLn("The FTP directory listing is: " +
dir);
ftpSession.Disconnect();
-->
RetrieveDocument method
Syntax FTP.RetrieveDocument( remoteFileName, documentName [,
connectionName, transferType, failIfLocalFileExists] )
Description Retrieves a document from the FTP server and stores it in a PowerDynamo
Web site. The parameters are:
• remoteFileName The name of the file on the remote machine.
• documentName The name of the file on the local machine.
• connectionName The name of the connection to be associated with the
document. The default is <inherited>.
• transferType Can be one of ASCII, binary, EBCDIC, image, or local.
The default is binary.
• failIfLocalFileExists A Boolean specifying the action to be
taken if the file already exists. The default is true.
Return Boolean.
Example This example retrieves a document from the FTP server called test.ssc and
stores it in a PowerDynamo Web site:
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
if( !ftpSession.RetrieveDocument("test.ssc",
"test_returned.ssc")) {
document.writeln( ftpSession.GetErrorCode() );
document.writeln( ftpSession.GetErrorInfo() );
}
ftpSession.Disconnect();
-->
239
FTP methods
RetrieveFile method
Syntax FTP.RetrieveFile( remoteFileName, localFileName [, transferType,
failIfLocalFileExists] )
Description Retrieves a file from the FTP server and saves it to the local machine. The
parameters are:
• remoteFileName The name of the file on the remote machine.
• localFileName The name of the file on the local machine.
• transferType Can be one of ASCII, binary, EBCDIC, image, or local.
The default is binary.
• failIfLocalFileExists A Boolean specifying the action to be
taken if the file already exists. The default is true.
Return Boolean.
Example This example retrieves a file from the FTP server and places it on the local
machine:
<!--SCRIPT
ftpSession = new FTP ("ftpserv", "anonymous",
"sam@sybase.com");
RetrieveFileWithAppend method
Syntax FTP.RetrieveFileWithAppend( remoteFileName, localFileName [,
transferType ] )
Description Similar to the RetrieveFile method, except if the file already exists locally,
the remote file is appended to the end. If the file does not exist a new one is
created. The parameters are:
• remoteFileName The name of the file on the remote machine.
• localFileName The name of the file on the local machine.
240
CHAPTER 3 DynaScript Predefined Objects
241
The Function object
document.writeln( square(5) );
document.writeln( square1(5) );
-->
242
CHAPTER 3 DynaScript Predefined Objects
Function properties
The Function object has this property:
length property
Syntax Function.length
Attributes This property is read-only.
Description Returns the number of parameters required by the Function.
Return Integer.
Example This example returns the number of parameters required by the function:
<!--SCRIPT
myFunc = new Function( "x","y", "return x * y;" );
document.WriteLn( "The function myFunc takes " +
myFunc.length + " parameters." );
document.WriteLn( myFunc(5, 6) );
-->
243
Function methods
Function methods
The Function object has this method:
toString method
Syntax Function.toString( )
Description Returns the body of the function as a string.
Return String.
Example • This example displays the body of the function:
<!--SCRIPT
myFunc = new Function( "x","y", "return x * y;" );
document.writeln( myFunc(5, 6) );
document.WriteLn( myFunc.toString() );
-->
244
CHAPTER 3 DynaScript Predefined Objects
java object
Object Allows for manipulation of Java classes within PowerDynamo scripts.
The java object represents an object used for working with a Java class within
your Web site.
Syntax To use a java method:
java.MethodName( parameter )
Description To use Java class objects within your Web site, your Web site must be
configured to enable Java. Sybase Central allows for easy Java class setup for
PowerDynamo Web sites. You should be aware of the following configuration
options in the Configuration folder of Sybase Central if you want to create and
use instances of Java class objects within your Dynamo scripts:
• Java VM PowerDynamo supports the Sun Java VM and the Microsoft
VM. You must select one of these VMs for PowerDynamo to support Java.
• Java class cache size To improve performance, information about
the methods and properties of Java classes is cached. This option enables
you to set the cache size.
• Class path for the mapping You must specify a path for class files
that are stored in a Dynamo Web site.
245
java object
public Fibonacchi()
{
prev1 = 1;
prev = 0;
next = 0;
}
246
CHAPTER 3 DynaScript Predefined Objects
java methods
The java object has these methods:
CreateComponent method
Syntax java.CreateComponent( componentName [, managerUrl, id, password,
narrowingComponent] )
Description Creates an instance of a Jaguar component, using CORBA naming services,
through Java. The parameters are:
•componentName The name of the component.
•managerUrl An URL to Jaguar Manager. For example,
“iiop://testMachine:9000”. This parameter is required to call a component
on another machine.
•id A Jaguar Manager user ID.
•password A Jaguar Manager password.
•narrowingComponent The name of the component you would like to
narrow.
The Jaguar server returns a component instance which must be narrowed
(cast) to an instance of an interface that the component supports. The
default interface is set to the name of the Jaguar component that is being
called. Use this only if you want to change the interface to something other
than the default. For example, by default, the component
SVU/SVUEnrollment is narrowed to the interface
“SVU/SVUEnrollment”. For more information on narrowing, see the
Jaguar Programmer’s Guide.
When you are generating stubs for your Jaguar components you can
specify a Java package other than the default, in which to store the stubs.
If this is the case, when the component is later being created by
DynaScript, the location of the stubs must be specified. To specify a stub
location that is something other than the default, the
narrowing_component parameter of the CreateComponent method
should be used. For example, if you have stored your Java stubs for the
SVU Jaguar package in com/sybase/jaguar/sample/svu/SVUMetaData
then you would use the following syntax to create an instance of a
SVUMetaData component that resides in the SVU Jaguar package:
java.CreateComponent( "SVU/SVUMetaData",
247
java methods
Return A Jaguar component object or null if the component could not be created. This
is a DynaScript Java object.
Example This example creates an instance of a component called comp. Once the object
is created, its method getMajors is called and the Record Set is displayed:
<HTML>
<H1>A CreateComponent example</H1>
<!--SCRIPT
document.writeln( "<H3>Testing SVUEnrollment
getMajors</H3>" );
comp = java.CreateComponent( "SVU/SVUEnrollment" );
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++;
}
-->
</HTML>
For information on result sets and the getResultSet method, see the Jaguar CTS
Programmer’s Guide.
248
CHAPTER 3 DynaScript Predefined Objects
site.GetErrorInfo( )
The site.GetErrorInfo( ) method may be used for retrieving error information.
CreateObject method
Syntax java.CreateObject( className [, list of constructor parameters ] )
Description Instantiates a Java class object. The parameters are:
•className The name of the Java class.
•list of constructor parameters These parameters are passed to the Java
class constructor.
Return A DynaScript object representing the Java class. Returns Null if the Java class
cannot be created.
Example This example creates an instance of Java class that performs the fibonacchi
mathematical procedure. It involves the GenerateNext method and returns
results.
<!--SCRIPT
fib = java.CreateObject( "Fibonacchi" );
// retrieve a property on the class
document.writeln( "The value of next is " + fib.next +
" The value of prev is " + fib.prev );
// set a property on the class
fib.next = 5;
for( i = 0; i < 20; i++ ) {
// invoke a method on the class
fib.generateNext();
document.writeln( "The value of next is " + fib.next
+ " The value of prev is " + fib.prev );
}
-->
249
java methods
CallStaticMethod method
Syntax java.CallStaticMethod( className, staticMethod [, list of method
parameters] )
Description Calls a static Java method. You need not create a Java object
(java.CreateObject) to call static methods of that object. The parameters are:
•className The name of the Java class containing the static method.
•staticMethod The name of the static method to be called.
•list of method parameters Any parameters to be passed on to the static
method.
Return The return type is dependent on the type of return value of the static method.
Example This example executes the static method doubleme of the class Fibonacchi.
Calling a static method does not require that an object representing a Java class
instance be created.
<!--SCRIPT
result = java.CallStaticMethod("Fibonacchi",
"doubleme", 2.5);
document.writeln( result );
-->
See also “PowerDynamo and Java” in PowerDynamo User’s Guide
GetHomeInterface method
Syntax java.GetHomeInterface(component_name [, provider_url, user_id,
password] )
Description Allows access to the EJBHome interface for a Jaguar component. The
parameters are:
•component_name The name of the component to instantiate.
Component names are composed as follows:
[<server-context>]<package>/<comp>
250
CHAPTER 3 DynaScript Predefined Objects
• 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.
•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.
251
java methods
GetUserTransaction method
Syntax java.GetUserTransaction( [ <provider_url>, <user_id>, <password>] )
Description Allows access to the EJB UserTransaction object. The parameters are:
•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.
252
CHAPTER 3 DynaScript Predefined Objects
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.
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.
253
java methods
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 */
}
...
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")
254
CHAPTER 3 DynaScript Predefined Objects
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 “PowerDynamo and Java” in the PowerDynamo User’s Guide.
255
mailList object
mailList object
Object Represents a list of mail pieces on a POP3 server.
Syntax To use a mailList property:
mailList.propertyName
256
CHAPTER 3 DynaScript Predefined Objects
257
mailList properties
mailList properties
The mailList object has this property:
count property
Syntax mailList.count
Attributes This property is read-only.
Description The number of messages in the mail list.
Return Integer.
Example This example displays the number of messages in the mail list.
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"secret", "elmo@mail.sybase.com");
document.WriteLn(mlist);
document.WriteLn("There are " + mlist.count + " messages
in the mail list");
-->
See also “mailPiece object (incoming)” on page 260.
“mailPiece object (outgoing)” on page 273.
258
CHAPTER 3 DynaScript Predefined Objects
mailList methods
The mailList object has these methods:
Disconnect method
Syntax mailList.Disconnect( [deleteMarkedPieces] )
Description Disconnects from the mail server. The optional parameter deleteMarkedPieces
indicates whether or not mail pieces marked for deletion should be deleted
from the mail server at the time of disconnect. The default is true.
Return Boolean indicating if the disconnect was successful.
Example This example connects and then disconnects from the mail server:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"secret", "elmo@mail.sybase.com ");
if( !mlist.Disconnect() ) {
document.writeln( mlist.GetErrorCode() );
document.writeln( mlist.GetErrorInfo() );
}
-->
See also “mailPiece object (incoming)” on page 260.
“mailPiece object (outgoing)” on page 273.
GetErrorCode method
Syntax mailList.GetErrorCode( )
Description Returns a code representing the most recent generated error. The error will
either be a three-digit POP3 reply code or a three-digit code in the 900 range
generated by Dynamo.
Return Integer.
Example This example returns an error if any problems are encountered while
disconnecting from the mail server:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"secret", "elmo@mail.sybase.com ");
if( !mlist.Disconnect() ) {
259
mailList methods
document.writeln( mlist.GetErrorCode() );
document.writeln( mlist.GetErrorInfo() );
}
document.WriteLn(mlist);
-->
See also “mailList object” on page 255
“mailPiece object (incoming)” on page 260
“mailPiece object (outgoing)” on page 273
GetErrorInfo method
Syntax mailList.GetErrorInfo( )
Description Returns a string containing an error message. The error can either be a
complete reply from the POP3 server or from PowerDynamo.
Return String.
Example This example returns an error if any problems are encountered while
disconnecting from the mail server
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"secret", "elmo@mail.sybase.com " );
if( !mlist.Disconnect() ) {
document.writeln( mlist.GetErrorCode() );
document.writeln( mlist.GetErrorInfo() );
}
-->
See also “mailPiece object (incoming)” on page 260.
“mailPiece object (outgoing)” on page 273.
260
CHAPTER 3 DynaScript Predefined Objects
261
mail piece properties (incoming)
attachments property
Syntax mailPiece.attachments
Attributes This property is read-only.
Description A list of attachments contained with the incoming mail piece.
Return List of attachment objects.
Example This example displays the names of all attachments in incoming mail piece
number 7:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistItem = mlist[7]
lmilstItem.Retrieve()
for ( i in mlistItem.attachment );{P
document.WriteLn( mlistitem.attachments[i].name;
}
mlist.Disconnect();
-->
See also “mailList object” on page 255.
body property
Syntax mailPiece.body
Attributes This property is read-only.
Description The body or content text of the incoming mail piece. This property is available
only after doing a Retrieve.
Return String.
Example This example displays the body of an incoming mail piece:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistitem = mlist[1];
262
CHAPTER 3 DynaScript Predefined Objects
mlistitem.Retrieve();
document.WriteLn( mlistitem.body );
mlist.Disconnect();
-->
See also “mailList object” on page 255.
“mailPiece object (outgoing)” on page 273.
from property
Syntax mailPiece.from
Attributes This property is read-only.
Description The person from whom the mail piece originated.
Return String.
Example This example display the address from which the mail piece originated:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistitem = mlist[4];
document.WriteLn( mlistitem.from );
mlist.Disconnect();
-->
See also “mailList object” on page 255.
headers property
Syntax mailPiece.headers
Attributes This property is read-only.
Description The ARPA message headers. These are the unprocessed header fields from the
mail piece.
Return String.
Example This example displays the headers:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistitem = mlist[4];
263
mail piece properties (incoming)
document.WriteLn( mlistitem.headers );
mlist.Disconnect();
-->
See also “mailList object” on page 255.
“mailPiece object (outgoing)” on page 273.
recipients property
Syntax mailPiece.recipients
Attributes This property is read-only.
Description The recipients of the incoming mail piece.
Return List of recipient objects.
Example This example displays a list of the recipients for the incoming mail piece:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com ");
mlistitem=mlist[2];
mlistitem.Retrieve();
for (i in mlistitem.recipients ){
document.WriteLn(mlistitem.recipients[i]);
}
mlist.Disconnect();
-->
See also “mailList object” on page 255.
“mailPiece object (outgoing)” on page 273.
replyTo property
Syntax mailPiece.replyTo
Attributes This property is read-only.
Description Who the recipient of the mail piece should reply to. This is a list of recipient
objects. If this field exists, the reply method responds to the recipients listed
here instead of to addresses specified in the from field.
Return List of recipient objects.
264
CHAPTER 3 DynaScript Predefined Objects
Example This example displays the address of the individual to whom the mail piece is
sent if the Reply method is used. If the replyTo property is null, the mail
piece will be sent to the address held in the from property
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com ");
mlistitem=mlist[2];
mlistitem.Retrieve();
for (i in mlistitem.replyTo ){
document.WriteLn(mlistitem.replyTo[i]);
}
mlist.Disconnect();
-->
sender property
Syntax mailPiece.sender
Attributes This property is read-only.
Description The address from where the mail piece was sent. This is not necessarily the
same address as the from field (in the case where a mail piece has been
redirected).
Return String.
Example This example indicates if the mail piece was sent directly by the author or by a
“sender”:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com ");
mlistitem = mlist[2];
mlistitem.Retrieve();
if (mlistitem.sender(true)){
document.WriteLn("This mail piece was sent from "
+ mlistitem.sender + "for " + mlistitem.from);
}else{
document.WriteLn("There was no sender property on
this mail piece");
}
265
mail piece properties (incoming)
mlist.Disconnect();
-->
See also “mailList object” on page 255.
“mailPiece object (outgoing)” on page 273.
size property
Syntax mailPiece.size
Attributes This property is read-only.
Description The size (bytes) of the incoming mail piece.
Return Integer.
Example This example displays the size of the mail piece:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistitem = mlist[9];
mlistitem.Retrieve();
document.WriteLn( "size: " + mlistitem.size );
mlist.Disconnect();
-->
See also “mailList object” on page 255
“mailPiece object (outgoing)” on page 273
subject property
Syntax mailPiece.subject
Attributes This property is read-only.
Description The subject of the incoming mail piece.
Return String.
Example This example displays the subject of the mail piece:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistitem = mlist[1];
266
CHAPTER 3 DynaScript Predefined Objects
document.WriteLn( mlistitem.subject );
mlist.Disconnect();
-->
See also “mailList object” on page 255
“mailPiece object (outgoing)” on page 273
267
mail piece methods (incoming)
Delete method
Syntax mailPiece.Delete( )
Description Marks a mail piece for deletion. The mail piece is not actually deleted until the
POP3 server is disconnected.
Return Boolean.
Example This example marks a mail piece for deletion:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
for (i in mlist) {
inPiece = mlist[i];
inPiece.Retrieve();
document.WriteLn(inPiece.body);
inPiece.Delete();
}
-->
mlist.Disconnect();
See also “mailList object” on page 255.
“mailPiece object (outgoing)” on page 273.
Forward method
Syntax mailPiece.Forward( userName [, includeAttachments] )
Description Prepares an outgoing mail piece object to be forwarded with all the appropriate
properties and recipients specified from the incoming mail piece. The
forwarded mail piece may be edited and then sent with the outgoing mail piece
send method. The parameters are:
•userName The address of the user to forward the mail piece to.
•includeAttachments Specifies whether all attachments of the incoming
mail piece should be included in the preparation of the outgoing mail
piece. The default is true.
268
CHAPTER 3 DynaScript Predefined Objects
GetErrorCode method
Syntax mailPiece.GetErrorCode( )
Description Returns a code representing the most recently generated error. The error
generated will either be a three-digit POP3 reply code or a three-digit code in
the 900 range generated by Dynamo.
Return Integer.
Example This example checks that the send method was completed successfully:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistitem = mlist[0];
mlistitem.Retrieve();
forward = mlistitem.Forward("jim@sybase.com");
if( !forward.Send() ) {
document.writeln( forward.GetErrorCode() );
document.writeln( forward.GetErrorInfo() );
}
269
mail piece methods (incoming)
-->
See also “mailList object” on page 255.
“mailPiece object (outgoing)” on page 273.
GetErrorInfo method
Syntax mailPiece.GetErrorInfo( )
Description Returns a string containing an error message. The error generated is either a
reply from the POP3 server or from PowerDynamo.
Return String.
Example This example verifies that the send method completed successfully:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistitem = mlist[0];
mlistitem.Retrieve();
forward = mlistitem.Forward("jim@sybase.com");
if( !forward.Send() ) {
document.writeln( forward.GetErrorCode() );
document.writeln( forward.GetErrorInfo() );
}
-->
See also “mailList object” on page 255.
“mailPiece object (outgoing)” on page 273.
Redirect method
Syntax mailPiece.Redirect( userName )
Description Prepares an outgoing mail piece object to be redirected with all the appropriate
properties and recipients specified from the incoming mail piece. userName is
the internet e-mail address of the person to redirect the mail piece to. The
redirected mail piece may be edited and then sent with the outgoing mail piece
object Send method.
270
CHAPTER 3 DynaScript Predefined Objects
Reply method
Syntax mailPiece.Reply( [replyMode, includeOriginal, includeAttachments] )
Description Creates an outgoing mail piece from an incoming mail piece with some
properties and the recipients preset.
• replyMode can be one of:
•" sender" Indicates that the mail piece is to be sent to the address
specified in the replyTo property. If the replyTo property of the
original mail piece does not exist, the mail piece will be sent to the
address specified in the from property of the original mail piece.
•" all" Indicates that the mail piece is to be sent to all recipients
including the sender.
• includeOriginal Can be true or false. If true, the original mail piece
body is included in the body of the outgoing mail piece. The default is
false.
271
mail piece methods (incoming)
Retrieve method
Syntax mailPiece.Retrieve( [deleteFromServer] )
Description Retrieves the full mail piece from the POP3 server. You must be connected to
the POP3 mail server to use this method. The deleteFromServer parameter
specifies whether to mark the retrieved mail piece for deletion after retrieval.
The deleteFromServer parameter may be set to true or false. The default is
false. If set to true, the marked mail piece is deleted from the server once you
disconnect from the POP3 server.
Return Boolean.
Example This example retrieves a mail piece:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com ");
272
CHAPTER 3 DynaScript Predefined Objects
num = mlist.count
document.WriteLn("There are " + num + " messages in the
mail box");
mlistitem = mlist[1];
mlistitem.Retrieve();
document.WriteLn( mlistitem.body + "\n\n" );
mlist.Disconnect();
-->
See also “mailList object” on page 255
“mailPiece object (outgoing)” on page 273
273
mailPiece object (outgoing)
mp.AddRecipient( "theGrouch@sybase.com");
mp.AttachDocument( "attachment.gif" );
if( !mp.Send() ) {
document.writeln( mp.GetErrorCode() );
document.writeln( mp.GetErrorInfo() );
}
See also “attachment object” on page 86
“mailPiece object (incoming)” on page 260
“mailList object” on page 255
“recipient object” on page 306
274
CHAPTER 3 DynaScript Predefined Objects
body property
Syntax mailPiece.body
Attributes This property is read/write.
Description The body text of the mail piece.
Binary data
Binary data must be sent as an attachment.
Example This example creates an outgoing mail piece. It is assumed that you have set
the smtpHost from within Sybase Central:
<!--SQL
mp = new MailPiece();
mp.subject = "Example of the body property";
mp.from = "elmo@sybase.com";
mp.body = "This is the body of the outgoing mail
piece.";
mp.AddRecipient( "theGrouch@sybase.com" );
if( !mp.Send() ) {
document.writeln( mp.GetErrorCode() );
document.writeln( mp.GetErrorInfo() );
}
-->
from property
Syntax mailPiece.from
Attributes This property is read/write.
275
mailPiece properties (outgoing)
Description The address from where the mail piece is being sent. This address must be a
valid Internet mail user name in canonical form.
Example This example sends a piece of e-mail to a specific address depending on the
input given by the user. The user must also enter their own e-mail address so
the recipient knows who to respond to.
Following is the form that requests information from the user:
<HTML>
<BODY>
<H1>Problem tracking</H1>
<p>This Web page is used to filter software problems to
the appropriate help personel.
276
CHAPTER 3 DynaScript Predefined Objects
277
mailPiece properties (outgoing)
break;
case "Product Other":
mp.AddRecipient("other@sybase.com");
break;
}
if( !mp.Send() ) {
document.writeln( mp.GetErrorCode() );
document.writeln( mp.GetErrorInfo() );
}
-->
<P>Select the back buttom if you wish to send another
e-mail</P>
</BODY>
</HTML>
See also “attachment object” on page 86.
“mailPiece object (incoming)” on page 260.
“mailList object” on page 255.
“recipient object” on page 306.
sender property
Syntax mailPiece.sender
Attributes This property is read/write.
Description You can use this property if a mail piece is sent from a destination other than
that of the person who the message is from. For example, if an assistant wanted
to send a message as requested by their supervisor, mailPiece.sender
would be the address of the assistant while mailPiece.from would be the
address of the supervisor.
Example This example sets the sender property on the mp mailpiece object:
<!--SCRIPT
mp = new MailPiece();
mp.from = "elmo@sybase.com";
mp.sender = "elmojr@sybase.com";
mp.AddRecipient( "oscar@sybase.com" );
278
CHAPTER 3 DynaScript Predefined Objects
smtpHost property
Syntax mailPiece.smtpHost
Attributes This property is read/write.
Description Specifies the name of the host to be used as a gateway for sending the mail
piece. If this value is empty, the value of smtpHost in the PowerDynamo
Configuration folder is used as the gateway. If the smtpHost has not been
specified in Sybase Central or the document, the mail piece will not be sent.
For information on setting the smtpHost in Sybase Central see “Changing
Dynamo configuration settings” in the PowerDynamo User’s Guide.
Example This example sets the smtpHost as mailsrv.sybase.com:
<!--SCRIPT
mp = new MailPiece();
mp.from = "elmo@sybase.com";
mp.sender = "elmojr@sybase.com";
mp.AddRecipient( "oscar@sybase.com" );
mp.smtpHost="mailsrv.sybase.com";
mp.subject = "Request for comment";
mp.body = "Your input is needed immediately";
mp.Send();
-->
See also “attachment object” on page 86.
“mailPiece object (incoming)” on page 260.
“mailList object” on page 255.
“recipient object” on page 306.
279
mailPiece properties (outgoing)
body property
Syntax mailPiece.body
Attributes This property is read/write.
Description The body text of the mail piece.
Binary data
Binary data must be sent as an attachment.
280
CHAPTER 3 DynaScript Predefined Objects
AddRecipient method
Syntax mailPiece.AddRecipient( userName [, userMode] )
Description Specifies the address or addresses where a mail piece is to be sent. The
parameters are:
•userName The e-mail address of the recipient.
•userMode Identifies the type of delivery.
Mode can be one of:
• to recipient is the main target of the mail piece.
• cc recipient is being carbon-copied.
• bcc recipient is being blind carbon-copied.
Return Boolean.
Example The following example sends a piece of mail to a specific address depending
on the input given by the user. The user must also enter their own e-mail
address so the recipient will know who to respond to.
This script creates a form that requests information from the user:
<HTML>
<BODY>
<H1>Problem tracking</H1>
<p>This Web page is used to filter software problems to
the appropriate help personel.
281
mailPiece methods (outgoing)
</OL>
<P>Enter your mail address:
<INPUT Type="TEXT" Name="from" SIZE=40></P>
<P>Describe your problem:
<INPUT Type="TEXT" Name="body" SIZE="50" ></P>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>
From a browser, the form looks something like this:
282
CHAPTER 3 DynaScript Predefined Objects
body = document.value.body
mp = new MailPiece();
switch( product ) {
case "Product A":
mp.AddRecipient("prodA@sybase.com");
break;
case "Product B":
mp.AddRecipient("prodB@sybase.com");
break;
case "Product C":
mp.AddRecipient("prodC@sybase.com");
break;
case "Product Other":
mp.AddRecipient("other@sybase.com");
break;
}
if( !mp.Send() ) {
document.writeln( mp.GetErrorCode() );
document.writeln( mp.GetErrorInfo() );
}
-->
<P>Select the back button if you wish to send another
e-mail</P>
</BODY>
</HTML>
See also “attachment object” on page 86.
“mailPiece object (incoming)” on page 260.
“mailList object” on page 255.
“recipient object” on page 306.
AddReplyTo method
Syntax mailPiece.AddReplyTo( userName )
Description Adds an address to the list of addresses from which responses to this mail piece
are directed.
Return Boolean.
283
mailPiece methods (outgoing)
Example This mail piece, when replied to, will be sent to elmo and elmojr:
<!--SCRIPT
mp = new MailPiece();
mp.from = "elmo@sybase.com";
mp.AddReplyTo = "elmojr@sybase.com";
mp.AddRecipient( "sam@sybase.com" );
mp.subject = "Request for comment";
mp.body = "Your input is needed immediately";
mp.Send();
-->
See also “attachment object” on page 86.
“mailPiece object (incoming)” on page 260.
“mailList object” on page 255.
“recipient object” on page 306.
AttachData method
Syntax mailPiece.AttachData( data [,MIMEtype, description] )
Description Attaches a piece of data (typically held in a DynaScript variable) to the mail
piece.
Return Boolean.
Example This example attaches a piece of data to the mail piece after retrieving it from
the database:
<!--SCRIPT
myQuery = connection.CreateQuery( "select data from
ImageTable where name = ’muppets’" );
myQuery.MoveNext();
imageData = myQuery.GetValue(1);
mp = new MailPiece();
mp.from = "elmo@sybase.com";
mp.AddRecipient( "sam@sybase.com" );
mp.subject = "Request for comment";
mp.body = "Your input is needed immediately. Please
review the attached graphic";
mp.AttachData( imageData, "image/jpg",
"gorgeous.jpg" );
mp.Send();
-->
284
CHAPTER 3 DynaScript Predefined Objects
AttachDocument method
Syntax mailPiece.AttachDocument( documentName )
Description Attaches a document in a PowerDynamo Web site to the mail piece.
Return Boolean.
Example This example attaches a document called muppets.gif to the mail piece object:
<!--SCRIPT
mp = new MailPiece();
mp.from = "elmo@sybase.com";
mp.AddRecipient( "sam@sybase.com" );
mp.subject = "Request for comment";
mp.body = "Your input is needed immediately. Please
review the attached document";
mp.AttachDocument("~/mail/muppets.gif");
mp.Send();
-->
See also “attachment object” on page 86.
“mailPiece object (incoming)” on page 260.
“mailList object” on page 255.
“recipient object” on page 306.
“AttachData method” on page 283.
“AttachFile method” on page 284.
AttachFile method
Syntax mailPiece.AttachFile( filePath )
Description Attaches a file from the file system to the mail piece.
285
mailPiece methods (outgoing)
Return Boolean.
Example This example attaches a system file called autoexec.bat to the mail piece
object:
<!--SCRIPT
mp = new MailPiece();
mp.from = "elmo@sybase.com";
mp.AddRecipient( "sam@sybase.com" );
mp.subject = "File update";
mp.body = "Your file should look something like the
attached.";
mp.AttachFile("c:\\autoexec.bat");
mp.Send();
-->
See also “attachment object” on page 86.
“mailPiece object (incoming)” on page 260.
“mailList object” on page 255.
“recipient object” on page 306.
“AttachData method” on page 283.
“AttachDocument method” on page 284.
GetErrorCode method
Syntax mailPiece.GetErrorCode( )
Description Returns a code representing the most recent error that occurred. The error is
either a three-digit SMTP reply code or a three-digit code in the 900 range
generated by PowerDynamo.
Return Integer.
Example This example sends a piece of mail and then checks for errors:
<!--SCRIPT
mp = new MailPiece();
mp.from = "elmo@sybase.com";
mp.AddRecipient( "sam@sybase.com" );
mp.subject = "Request for comment";
mp.body = "Your input is needed immediately. Please
review the attached Dynamo document";
mp.AttachDocument("~/mail/muppets.gif");
mp.Send();
286
CHAPTER 3 DynaScript Predefined Objects
if( !mp.Send() ) {
document.writeln( mp.GetErrorCode() );
document.writeln( mp.GetErrorInfo() );
}
-->
See also “mailPiece object (incoming)” on page 260.
“mailList object” on page 255.
“GetErrorInfo method” on page 286.
GetErrorInfo method
Syntax mailPiece.GetErrorInfo( )
Description Returns a string containing an error message. The message is either a reply
either from the SMTP server or from PowerDynamo.
Return String.
Example This example sends a mail piece and then checks for errors:
<!--SCRIPT
mp = new MailPiece();
mp.from = "elmo@sybase.com";
mp.AddRecipient( "sam@sybase.com" );
mp.subject = "Request for comment";
mp.body = "Your input is needed immediately. Please
review the attached Dynamo document";
mp.AttachDocument("~/mail/muppets.gif");
mp.Send();
if( !mp.Send() ) {
document.writeln( mp.GetErrorCode() );
document.writeln( mp.GetErrorInfo() );
}
-->
See also “mailPiece object (incoming)” on page 260.
“mailList object” on page 255.
“GetErrorCode method” on page 285.
Send method
Syntax mailPiece.Send( userName )
287
mailPiece methods (outgoing)
Description Sends a mail piece through SMTP. Use GetErrorInfo and GetErroCode to
check for failures.
Return Boolean.
Example This example creates and sends a mail piece:
<!--SCRIPT
mp = new MailPiece();
mp.from = "elmo@sybase.com";
mp.AddRecipient( "sam@sybase.com" );
mp.subject = "Request for comment";
mp.body = "Your input is needed immediately";
mp.Send();
-->
See also “mailPiece object (incoming)” on page 260.
“mailList object” on page 255.
“GetErrorCode method” on page 285.
“GetErrorInfo method” on page 286.
288
CHAPTER 3 DynaScript Predefined Objects
Math object
Object The Math object provides basic Math functionality to users.
Standard: ECMAScript
Syntax To use a Math property:
Math.propertyName
289
Math properties
Math properties
The Math object has these properties:
E property
Syntax Math.E
Attributes This property is read-only.
Description Returns the number value for e, the base of the natural logarithms, which is
approximately 2.71828182845905.
Return Floating point.
Example To display the value of e:
<!--SCRIPT
a = Math.E;
document.WriteLn( a );
-->
LN2 property
Syntax Math.LN2
Attributes This property is read-only.
Description Returns the number value for the natural logarithm of 2, which is
approximately 0.693147180559945.
Return Floating point.
Example To display the value of LN2:
<!--SCRIPT
a = Math.LN2;
document.WriteLn( a );
-->
LN10 property
Syntax Math.LN10
Attributes This property is read-only.
290
CHAPTER 3 DynaScript Predefined Objects
Description Returns the value for the natural logarithm of 10, which is approximately
2.30258509299405.
Return Floating point.
Example To display the value of LN10:
<!--SCRIPT
a = Math.LN10;
document.WriteLn( a );
-->
LOG2E property
Syntax Math.LOG2E
Attributes This property is read-only.
Description Returns the number value for the base-2 logarithm of e, Euler’s constant. This
value is approximately 1.44269504088896.
Return Floating point.
Example To display the value of LOG2E:
<!--SCRIPT
a = Math.LOG2E;
document.WriteLn( a );
-->
LOG10E property
Syntax Math.LOG10E
Attributes This property is read-only.
Description Returns the number value for the base-10 logarithm of e, Euler’s constant. This
value is approximately 0.434294481903252.
Return Floating point.
Example To display the value of LOG10E:
<!--SCRIPT
a = Math.LOG10E;
document.WriteLn( a );
-->
291
Math properties
PI property
Syntax Math.PI
Attributes This property is read-only.
Description Returns the ratio of the circumference of a circle to its diameter, which is
approximately 3.14159265358979.
Return Floating point.
Example To display the value of PI:
<!--SCRIPT
a = Math.PI;
document.WriteLn( a );
-->
SQRT1_2 property
Syntax Math.SQRT1_2
Attributes This property is read-only.
Description Returns the number value for the square root of 1/2, which is approximately
0.707106781186548.
Return Floating point.
Example To display the value of the square root of 1/2:
<!--SCRIPT
a = Math.SQRT1_2;
document.WriteLn( a );
-->
SQRT2 property
Syntax Math.SQRT2
Attributes This property is read-only.
Description Returns the number value for the square root of 2, which is approximately
1.4142135623731.
Return Floating point.
Example To display the value of the square root of 2:
292
CHAPTER 3 DynaScript Predefined Objects
<!--SCRIPT
a = Math.SQRT2;
document.WriteLn( a );
-->
293
Math methods
Math methods
The Math object has these methods:
abs method
Syntax Math.abs( num )
Description Returns the absolute value of a number.
Return The absolute value of the number argument.
Example This example returns the absolute value of -8:
<!--SCRIPT
document.WriteLn( Math.abs( -8 ) );
-->
acos method
Syntax Math.acos( num )
Description Returns the arc cosine of a number.
Return Floating point.
Example This example returns the arc cosine of .43:
<!--SCRIPT
document.WriteLn( Math.acos( .43 ) );
-->
asin method
Syntax Math.asin( )
Description Returns the arc sine of a number.
Return Floating point.
Example This example returns the arc sine of 1:
<!--SCRIPT
document.WriteLn( Math.asin( 1 ) );
-->
294
CHAPTER 3 DynaScript Predefined Objects
atan method
Syntax Math.atan( num )
Description Returns the arc tangent of a number.
Return Floating point.
Example This example displays the arc tangent of .43:
<!--SCRIPT
document.WriteLn( Math.atan( .43 ) );
-->
atan2 method
Syntax Math.atan2( y, x )
Description Returns the angle in radians from the x axis to the y, x point. The parameters
are:
•y The y coordinate.
•x The x coordinate.
Return Floating point.
Example This example returns the angle from the x axis to the y, x point:
<!--SCRIPT
document.WriteLn( Math.atan2( 3, -12 ) );
-->
ceil method
Syntax Math.ceil( num )
Description Returns the smallest number value that is not less than the argument and is
equal to a mathematical integer.
Return Integer.
Example This example displays the smallest integer possible that is not less than 6.333:
<!--SCRIPT
document.WriteLn( Math.ceil( 6.333 ) );
-->
295
Math methods
cos method
Syntax Math.cos( num )
Description Returns the cosine of a number.
Return Floating point.
Example This example returns the cosine of 45:
<!--SCRIPT
document.WriteLn( Math.cos( 45 ) );
-->
exp method
Syntax Math.exp( num )
Description Returns E raised to the power of the argument (num).
Return Floating point.
Example This example calculates and displays the value of E to the power of 8:
<!--SCRIPT
document.WriteLn( Math.exp( 8 ) );
-->
floor method
Syntax Math.floor( num )
Description Returns the greatest number value that is not greater than the argument and is
equal to a mathematical integer.
Return Integer.
Example This example calculates and displays the greatest number value that is not
greater than the argument and is equal to a mathematical integer:
<!--SCRIPT
document.WriteLn( Math.floor( 634.8 ));
-->
296
CHAPTER 3 DynaScript Predefined Objects
log method
Syntax Math.log( num )
Description Returns the natural logarithm of a number.
Return Floating point.
Example This example displays the logarithm of the number 6:
<!--SCRIPT
document.WriteLn( Math.log( 6 ) );
-->
max method
Syntax Math.max( numExp, numValue )
Description Returns the larger of two arguments. The parameters are:
•numExp A numeric expression that will be compared with numValue.
•numValue A numeric value that will be compared with numExp.
Return Floating point.
Example This example returns the larger value of x and y:
<!--SCRIPT
x = 7.543643;
y = 7.954854345;
minValue = Math.max( x, y );
document.WriteLn( minValue );
-->
min method
Syntax Math.min( numExp, numValue )
Description Returns the smaller of the two arguments. The parameters are:
•numExp A numeric expression that will be compared with numValue.
•numValue A numeric value that will be compared with numExp.
Return Floating point.
Example This example returns the smaller value:
<!--SCRIPT
297
Math methods
x = 7.543643;
y = 7.954854345;
minValue = Math.min( x, y );
document.WriteLn( minValue );
-->
pow method
Syntax Math.pow( num, exponent )
Description Returns the result of raising x to the power y. The parameters are:
•num The base value (x).
•exponent The exponent value (y).
Return Floating point.
Example This example returns the results of calculating 3 to the power of 8:
<!--SCRIPT
x = Math.pow( 3, 8 );
document.WriteLn( x );
-->
random method
Syntax Math.random( )
Description Returns a randomly generated positive number equal to or greater than 0 but
less than 1.
Return Floating point.
Example To return a number s equal to or greater than 0 but less than 1:
<!--SCRIPT
x = Math.random();
document.WriteLn( x );
-->
round method
Syntax Math.round( num )
298
CHAPTER 3 DynaScript Predefined Objects
sin method
Syntax Math.sin( num )
Description Returns the sine of a number.
Return Floating point.
Example This example displays the sine of 54:
<!--SCRIPT
document.WriteLn( Math.sin( 54 ) );
-->
sqrt method
Syntax Math.sqrt( num )
Description Returns the square root of a number.
Return Floating point.
Example This example displays the square root of 64:
<!--SCRIPT
document.WriteLn( Math.sqrt(64) );
-->
tan method
Syntax Math.tan( num )
Description Returns the tangent of a number.
Return Floating point
Example This example displays the tangent of 43:
299
Math methods
<!--SCRIPT
document.WriteLn( Math.tan( 43 ) );
-->
300
CHAPTER 3 DynaScript Predefined Objects
Number object
Object Enables you to use methods and obtain properties on a number.
Standard: ECMAScript
Syntax To use a Number property:
Number.propertyName
To use a Number method:
Number.MethodName( parameter )
Description The Number object represents a number for which you want to use methods
and properties made available with the Number object. These methods and
properties are not available to numbers that are held by variables ( num = 14 ).
You can call a Number object as a function:
Number( value );
or as a constructor:
myNumber = new Number( value );
When called as a function, a type conversion is performed and a number is
returned. A new Number object is not created. When a Number object is
created through a constructor, a Number object is returned.
The Number object has both a built-in object as well as constructors that allow
users to create instances of a Number object. When referring to Number in the
syntax sections of this chapter, we are referring to an instance of a Number
object, not the built-in Number object.
Example This example creates a Number object with the value of 32:
<!--SCRIPT
num = new Number( 32 );
document.WriteLn( num );
-->
301
Number properties
Number properties
The Number object has these properties:
MAX_VALUE property
Syntax Number.MAX_VALUE
Attributes This property is read-only.
Description Returns the largest positive finite value of the number type, which is
approximately 1.7976931348623157e308.
Return Integer.
Example This example displays the largest possible number that can be used in
PowerDynamo:
<!--SCRIPT
document.WriteLn( Number.MAX_VALUE );
-->
MIN_VALUE property
Syntax Number.MIN_VALUE
Attributes This property is read-only.
Description Returns the smallest positive nonzero value of the number type, which is
approximately 5e-324.
Return Integer.
Example This example displays the smallest positive non-zero number that can be used
in PowerDynamo:
<!--SCRIPT
document.WriteLn( Number.MIN_VALUE );
-->
NaN property
Syntax Number.NaN
Attributes This property is read-only.
302
CHAPTER 3 DynaScript Predefined Objects
Description A value that indicates that an arithmetic expression returned a value that was
not a number.
Return String (NaN)
Example This example will have an output of NaN.
<!--SCRIPT
document.WriteLn( Number.NaN );
-->
NEGATIVE_INFINITY property
Syntax Number.NEGATIVE_INFINITY
Attributes This property is read-only.
Description Returns a string indicating that a number is outside the range that ECMAScript
is capable of representing.
Return String (-Infinity).
Example This example will have an output of -Infinity:
<!--SCRIPT
document.WriteLn( Number.NEGATIVE_INFINITY );
-->
POSITIVE_INFINITY property
Syntax Number.POSITIVE_INFINITY
Attributes This property is read-only.
Description Returns a string indicating that a number is outside the range that ECMAScript
is capable of representing.
Return String (Infinity)
Example This example will have an output of Infinity:
<!--SCRIPT
document.WriteLn( Number.POSITIVE_INFINITY );
-->
303
Number methods
Number methods
The Number object has these methods:
toString method
Syntax Number.toString( [radix] )
Description Returns a string representation of the Number object. A radix may be used if
you wish to work with something other than base 10.
Return String.
Example This example creates a number object and converts the value to a string:
<!--SCRIPT
num = new Number( 16 );
stringNum = num.toString();
document.WriteLn( stringNum );
-->
valueOf method
Syntax Number.valueOf( )
Description Extracts the number value of the number object as an integer.
Return Integer.
Example This example creates a number object, and then converts it back to an integer,
which is held in the variable intNum.
<!--SCRIPT
num = new Number( 16 );
intNum = num.valueOf();
document.WriteLn( intNum );
-->
304
CHAPTER 3 DynaScript Predefined Objects
Object object
Object Allows you to create an instance of an object that is set depending on the type
of value that is passed in as a parameter.
Standard: ECMAScript
Syntax To use an Object property:
Object.propertyName
To use an Object method:
Object.MethodName( parameter )
Description The actual object that is created when using this constructor varies depending
on the parameter that is supplied. For example, if you supply a Boolean value
such as true (new Object(true); ) a Boolean object is created. The only
time that an actual Object object is created is when no value or null is supplied
as the constructor parameter.
To create a new Object object, use:
myObj = new Object ( [parameter] );
Example This example creates several different objects:
<!--SCRIPT
//creates a Boolen object
myObj1 = new Object(true);
document.WriteLn(typeof(myObj1));
//creates a Script object
myObj2 = new Object("my object");
document.WriteLn(typeof(myObj2));
//creates a Date object
myObj3 = new Object( new Date( 1997, 01, 01 ) );
document.WriteLn(myObj3);
document.WriteLn(typeof(myObj3));
//creates a Number object
myObj4 = new Object(123);
document.WriteLn(typeof(myObj4));
//creates a Objec object
myObj4 = new Object();
document.WriteLn(typeof(myObj4));
-->
305
Object methods
Object methods
The Object object has these methods:
toString method
Syntax Object.toString( )
Description Returns the value of the object as a string.
Return String.
Example To display the value of the myObj object:
<!--SCRIPT
myObj = new Object( "my object" );
document.WriteLn( myObj.toString() );
-->
valueOf method
Syntax Object.valueOf( )
Description Extracts the value of the object.
Return Integer.
Example To return the value of the myObj object:
<!--SCRIPT
myObj = new Object(null);
document.WriteLn( typeof( myObj ) );
document.WriteLn( "value = " + myObj.valueOf() );
-->
306
CHAPTER 3 DynaScript Predefined Objects
recipient object
Object Represents the recipients of a mail piece.
Syntax To use a recipient property:
recipient.propertyName
Description Use the recipient object to view the names and delivery mode of the recipients
mail piece.
Example This example checks the name and mode of the recipients of the mail piece:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistitem = mlist[12];
mlistitem.Retrieve();
for( i in mlistitem.recipients ) {
recip = mlistitem.recipients[i];
document.WriteLn("The name is: " + recip.name);
document.WriteLn("The mode is: " + recip.mode);
}
-->
See also “recipients property” on page 263.
“attachment object” on page 86.
“mailList object” on page 255.
“mailPiece object (incoming)” on page 260.
“mailPiece object (outgoing)” on page 273.
307
recipient properties
recipient properties
The recipient object has these properties:
mode property
Syntax recipient.mode
Attributes This property is read-only.
Description Identifies the type of delivery.
Mode can be one of:
• to recipient is the main target of the mail piece.
• cc recipient is being carbon-copied.
• bcc recipient is being blind carbon-copied.
Return String.
Example This example checks the name and mode of the recipients of the mail piece:
<!--SCRIPT
mlist = new MailList ("mail.sybase.com", "elmo",
"dynamo", "elmo@mail.sybase.com");
mlistitem = mlist[12];
mlistitem.Retrieve();
for( i in mlistitem.recipients ) {
recip = mlistitem.recipients[i];
document.WriteLn("The name is: " + recip.name);
document.WriteLn("The mode is: " + recip.mode);
}
-->
See also “mailList object” on page 255.
“mailPiece object (incoming)” on page 260.
“mailPiece object (outgoing)” on page 273.
name property
Syntax recipient.name
308
CHAPTER 3 DynaScript Predefined Objects
for( i in mlistitem.recipients ) {
recip = mlistitem.recipients[i];
document.WriteLn("The name is: " + recip.name);
document.WriteLn("The mode is: " + recip.mode);
}
-->
See also “mailList object” on page 255.
“mailPiece object (incoming)” on page 260.
“mailPiece object (outgoing)” on page 273.
309
query object
query object
Object Provides a scriptable way to work with a SQL query embedded in a Dynamo
template.
Syntax To use a query’s property:
query.propertyName
To use a query’s method:
query.MethodName( parameter )
Description Each embedded query has a name (by default, SQL). In scripts following the
embedded query, you can obtain and change information about the query by
working with the query object of the same name.
You can also create a query object from within a script. To do this, use
connection.CreateQuery.
Example The following query prints out the number of rows in a result set:
<!--SQL
SELECT id from "dba".product
-->
<!--SCRIPT
document.WriteLn( "We stock " + SQL.GetRowCount() +
" different products." );
-->
In this example, the query has the default name of SQL. If the SQL tag
explicitly specified a name, as in:
<!--SQL NAME = productQuery
then you would reference the query accordingly:
productQuery.GetRowCount()
In the script that follows the query, SQL.GetRowCount() is the
GetRowCount method of the SQL query object. It takes no arguments, and
returns the number of rows in the query result set.
The following complete template shows how a script can use the query object
to access the results of an embedded query. The template executes a query on
the product table and formats the result in a table. Although you format using
a FORMATTING tag, using scripts provides more flexibility:
<HTML>
<TITLE>SQL and script example</TITLE>
<BODY>
<!--SQL
310
CHAPTER 3 DynaScript Predefined Objects
-->
<!--SCRIPT
thisColumnCount = SQL.GetColumnCount();
311
query properties
query properties
The query object has this property:
connection property
Syntax query.connection
Attributes This property is read-only.
Description The connection object used to execute the query.
Example This example displays the name of the connection used to execute the query:
<!--SQL
select name from product
-->
<!--SCRIPT
document.WriteLn( SQL.connection.name );
-->
cursorType property
Syntax query.cursorType
Description Use this property when you are executing stored procedures in a Microsoft
SQL Server database that return multiple result sets. The cursorType must be
set to ForwardOnly to avoid problems during execution.
Example This example executes a stored procedure that returns multiple results sets
from a Microsoft SQL Server database:
<!--SCRIPT MSSQL_MultiStatement.ssc
/*
CREATE PROCEDURE test3 AS
select * into #footable from employee
select * from #footable
*/
conn = site.GetConnection( "MSSQLServer" );
// create an empty query
q = conn.CreateQuery();
312
CHAPTER 3 DynaScript Predefined Objects
q.cursorType = "ForwardOnly";
q.SetSQL( "exec test3" );
q.Execute();
if( q.GetErrorCode() != 0 ) {
document.writeln(q.GetErrorInfo());
}
while( q.MoveNext() ){
document.writeln( q.GetValue(1)+’ ’+q.GetValue(2)+’
’+q.GetValue(3)+’ ’+q.GetValue(4) );
}
-->
See also “CreateQuery method” on page 106.
stripTrailingBlanks property
Syntax query.stripTrailingBlanks
Description Use this property to strip trailing blanks from query data. This property is quite
useful when executing queries against databases that have trailing blank
characters such as Adaptive Server Enterprise. The stripTrailingBlanks
property may be set to true or false. False is the default.
Example This example executes a query against an Adaptive Server Enterprise database
and strips that trailing blanks from the output:
<!--SCRIPT
SQL=connection.CreateQuery("select distinct name from
product order by name" );
SQL.stripTrailingBlanks = true;
while SQL.MoveNext() {
document.WriteLn("[" +SQL.GetValue(1) + "]");
}
-->
The output from this example is:
[Baseball Cap]
[Shorts]
[Sweatshirt]
[Tee Shirt]
[Visor]
Without stripping the trailing blanks, the output might look like this:
[Baseball Cap ]
[Shorts ]
313
query properties
[Sweatshirt ]
[Tee Shirt ]
[Visor ]
You can also use the stripTrailingBlanks property in conjunction with
the ResultsToXMLString:
<!--SCRIPT
SQL=connection.CreateQuery("select distinct name from
product order by name" );
SQL.stripTrailingBlanks = true;
document.WriteLn( SQL.ResultsToXMLString() );
-->
See also “CreateQuery method” on page 106.
314
CHAPTER 3 DynaScript Predefined Objects
query methods
The query object has these methods:
Close method
Syntax query.Close( )
Description Closes the active query. To reestablish the query you must execute it again.
Closing a query
A query is automatically closed when the query object (myQuery in the
following example) goes out of scope. Typically, this is at the end of the script.
Return Boolean. This method returns true or false, indicating whether the method
succeeded or not.
Example This example executes a query, then closes it.
<!--SCRIPT
myQuery = connection.CreateQuery ( "update product set
color = ’Red’ where color = ’White’" );
myQuery.Close();
-->
Execute method
Syntax query.Execute( )
Description Executes the current query object’s SQL statement.
Return Boolean. This method returns true or false, indicating whether the method
succeeded or not.
Example This example prepares a query using a SQL tag with the attribute NO_EXECUTE,
and later executes the query from within a SCRIPT tag:
<!--SQL NO_EXECUTE NAME=myQuery
select id from "dba".product
-->
<!--SCRIPT
myQuery.Execute();
-->
315
query methods
GetColumnCount method
Syntax query.GetColumnCount( )
Description Returns the number of columns in the query result set.
Example This example writes out the labels for each column within the result set of the
query:
<!--SCRIPT
myQuery = connection.CreateQuery( ’select lname, fname
from customer’ );
count = myQuery.GetColumnCount();
for( i = 1; i <= count; i++ ) {
document.WriteLn( myQuery.GetColumnLabel( i ) );
}
-->
GetColumnIndex method
Syntax query.GetColumnIndex(colName )
Description Returns the index of the column named colName [case-insensitive string] in
the query, where the first column’s index is 1.
Return Integer. If no match is found, returns false.
Example This example displays the index of the fname column:
<!--SCRIPT
myQuery=connection.CreateQuery
( ’select lname, fname from customer’ );
document.WriteLn( myQuery.GetColumnIndex("fname") );
-->
The output from this example is:
2
GetColumnLabel method
Syntax query.GetColumnLabel(colNum)
Description Returns the column name or column alias (as specified in the SQL query) for
the colNum column. Columns are numbered starting with 1.
Return String. Returns the column name or alias.
316
CHAPTER 3 DynaScript Predefined Objects
Example This example writes out the labels for each column within the result set of the
query:
<!--SCRIPT
myQuery = connection.CreateQuery( ’select lname, fname
from customer’ );
count = myQuery.GetColumnCount();
for( i = 1; i <= count; i++ ) {
document.WriteLn( myQuery.GetColumnLabel( i ) );
}
-->
GetEmpty method
Syntax query.GetEmpty( )
Description Indicates if the result set is empty.
Note
If no Move method has yet been called on the query object, calling GetEmpty
moves the cursor to the first row of the result set.
Return Boolean. This method returns true if the result set is empty.
Example This example performs two queries and then displays one of two outputs,
depending on the result of the query:
<!--SQL NAME = White
select id from product where color = ’white’
-->
<!--SQL NAME = Red
select id from product where color = ’red’
-->
<!--SCRIPT
document.WriteLn( "There are " + (White.GetEmpty()?
"no" : "some" ) + " white products." );
document.WriteLn( "There are " + (Red.GetEmpty()? "no"
: "some" ) + " red products." );
-->
The output from this example is:
There are some white products.
There are no red products.
317
query methods
GetErrorCode method
Syntax query.GetErrorCode( )
Description Returns the current error code.
Return Integer. Returns zero if a SQL instruction is carried out correctly, and
information to which the script can respond if it fails.
Example This example displays a message that indicates whether the query was
successfully executed or not:
<!--SQL
select id from product
-->
<!--SCRIPT
document.WriteLn( "The query" );
if ( SQL.GetErrorCode()==0 ) {
document.WriteLn( "succeeded." );
} else {
document.WriteLn( "failed." );
}
-->
GetErrorInfo method
Syntax query.GetErrorInfo( )
Description A description of the error.
Return String.
Example This example displays a message indicating why the query failed:
<!--SCRIPT
myQuery=connection.CreateQuery( ’select badname from
product’ );
document.WriteLn( myQuery.GetErrorInfo() );
-->
The output from this example is:
[Sybase][ODBC Driver]: column ’badname’ not found
GetRowCount method
Syntax query.GetRowCount( )
318
CHAPTER 3 DynaScript Predefined Objects
Description The number of rows in the result set of the current query.
Example This example displays the number of products in the query result set:
<!--SQL
select id from product
-->
<!--SCRIPT
document.WriteLn( "We stock " + SQL.GetRowCount() + "
products." );
-->
GetState method
Syntax query.GetState( )
Description Returns the current SQL state of the query.
The values returned by GetState depend on your database driver. For more
information, see your database’s documentation.
Example This example displays the SQL state for the query:
<!--SQL NO_SQL_ERROR
select badname from product
-->
<!--SCRIPT
document.WriteLn( SQL.GetState() );
-->
The output is:
S0022
GetValue method
Syntax query.GetValue(colNum|colName)
Description Returns the value in the colNum [integer] or colName[string] column of the
current row of the result set.
Example This example displays a list of first and last names.
319
query methods
<!--SQL
select lname, fname from customer
-->
<!--SCRIPT
while ( SQL.MoveNext() ){
document.WriteLn( SQL.GetValue(1) + "," +
SQL.GetValue(2) );
}
-->
The output from this example looks something like this:
Devlin,Michaels
Reiser,Beth
Niedringhaus,Erin
Mason,Meghan
McCarthy,Laura
Phillips,Paul
Colburn,Kelly
Goforth,Matthew
Gagliardo,Jessie
Agliori,Michael
Ricci,Dylan
...
Move method
Syntax query.Move(rowNum )
Description Changes the current row to the rowNum [integer] row of a query result set.
320
CHAPTER 3 DynaScript Predefined Objects
Return Boolean. This method returns true or false, indicating whether the method
succeeded or not.
Example This example displays the data in the fifth row of the result set:
<!--SQL
select lname, fname from customer
-->
<!--SCRIPT
SQL.Move(5)
document.WriteLn( SQL.GetValue(1) + "," +
SQL.GetValue(2) );
-->
MoveFirst method
Syntax query.MoveFirst( )
Description Changes the current row to the first row of a query result set.
321
query methods
Return Boolean. This method returns true or false, indicating whether the method
succeeded or not.
Example This example moves through each of the rows of a query result set and
repositions at the first row.
<!--SQL
select lname, fname from customer
-->
<!--SCRIPT
while ( SQL.MoveNext() ) {
document.WriteLn( SQL.GetValue(1) + "," +
SQL.GetValue(2) );
}
SQL.MoveFirst();
-->
See also “simulateCursors property” on page 102.
MoveLast method
Syntax query.MoveLast( )
Description Changes the current row to the last row of a query result set.
322
CHAPTER 3 DynaScript Predefined Objects
Return Boolean. This method returns true or false, indicating whether the method
succeeded or not.
Example This example displays the results of a query from the end of the result set to the
beginning:
<!--SQL
select lname, fname from customer
-->
<!--SCRIPT
SQL.MoveLast();
do {
document.WriteLn( SQL.GetValue(1) + "," +
SQL.GetValue(2) );
} while ( SQL.MovePrevious() );
-->
See also The “simulateCursors property” on page 102.
MoveNext method
Syntax query.MoveNext( )
Description Changes the current row to the next row of a query result set.
323
query methods
Return Boolean. This method returns true or false, indicating whether the method
succeeded or not.
Example This example displays the data in each row of a query result set.
<!--SQL
select lname, fname from customer
-->
<!--SCRIPT
while ( SQL.MoveNext() ){
document.WriteLn( SQL.GetValue(1) + "," +
SQL.GetValue(2) );
}
-->
MovePrevious method
Syntax query.MovePrevious( )
Description Changes the current row to the previous row of a query result set. This is a
method of the query object.
Return Boolean. This method returns true or false, indicating whether the method
succeeded or not.
324
CHAPTER 3 DynaScript Predefined Objects
Example This example displays the results of a query from the end of the result set to the
beginning:
<!--SQL
select lname, fname from customer
-->
<!--SCRIPT
SQL.MoveLast();
do {
document.WriteLn( SQL.GetValue(1) + "," +
SQL.GetValue(2) );
} while ( SQL.MovePrevious() );
-->
See also “simulateCursors property” on page 102.
MoveRelative method
Syntax query.MoveRelative(relativeRowNum)
Description Moves to a row that is relativeRowNum [integer] rows before or after the
current row of a query result set.
Return Boolean. This method returns true or false, indicating whether the method
succeeded or not.
325
query methods
Example This example displays the data in the row that is sixth from the end of the
rowset and then the second last row of the rowset:
<!--SQL
select lname, fname from customer
-->
<!--SCRIPT
SQL.MoveLast();
SQL.MoveRelative(-5)
document.WriteLn( SQL.GetValue(1) + "," +
SQL.GetValue(2) );
SQL.MoveRelative(4);
document.WriteLn( SQL.GetValue(1) + "," +
SQL.GetValue(2) );
-->
Opened method
Syntax query.Opened( )
Description Indicates whether a query object is open. The query object is opened either by
calling the Execute method on the query, using the site.CreateQuery method,
or by executing the query through a SQL tag.
Return Boolean. This method returns true if a query object is open.
Example This example displays whether the query was successfully opened:
<!--SQL
select lname, fname from customer
-->
<!--SCRIPT
document.WriteLn( "The query is " + ( SQL.Opened()?
"open." : "closed." ) );
-->
Refresh method
Syntax query.Refresh( )
Description Reexecutes the current query and obtains a new result set. This may or may not
reset the current cursor. If the cursor cannot be moved to the current row
(because, for example, the row has been deleted), the cursor is moved to the
first row of the result set.
326
CHAPTER 3 DynaScript Predefined Objects
To guarantee that the cursor is at the beginning of the result set after calling
Refresh, you must call MoveFirst (or Move(0)).
Return Boolean. This method returns true or false, indicating whether the method
succeeded or not.
Example This example executes the same query choice twice; once via the SQL tag, and
once via the refresh method:
<!--SQL
select lname from customer
-->
<!--SCRIPT
SQL.Refresh();
-->
ResultsToXMLString method
Syntax query. ResultsToXMLString ( [resultSetTag, rowTag, columnTag,
useCDATA ] )
Description Returns the result of a query formatted as an XML string.
The parameters for this method are:
• resultSetTag The tag surrounding the full result set. If no tag is
specified, SYBRESULTSET is used.
• rowTag The tag for defining a row. If no tag is specified, SYBROW is
used.
• columnTag The tag for defining a column. If no tag is specified, the
column's label is used.
• useCDATA Instructs Dynamo to encode characters using CDATA to
escape special XML characters. If use_CDATA is not specified, characters
are encoded using the ampersand method.
Return String. The result set is returned as an XML formatted string.
Example This example performs a query and returns the results as an XML string:
<!--SCRIPT
queryobj = connection.CreateQuery( "select
product.description, product.color from product order
by product.description" );
xmlString = queryobj.ResultsToXMLString(
"MYRESULTSET", "MYROW", "MYCOLUMN" );
327
query methods
document.writeln( xmlString );
-->
The output from this example looks similar to this (line breaks have been added
for display reasons, but do not normally occur):
<MYRESULTSET>
<MYROW><MYCOLUMN>Cloth
Visor</MYCOLUMN><MYCOLUMN>White</MYCOLUMN></MYROW>
<MYROW><MYCOLUMN>Cotton
Cap</MYCOLUMN><MYCOLUMN>Black</MYCOLUMN></MYROW>
<MYROW><MYCOLUMN>Cotton
Shorts</MYCOLUMN><MYCOLUMN>Black</MYCOLUMN></MYROW>
<MYROW><MYCOLUMN>Crew
Neck</MYCOLUMN><MYCOLUMN>Black</MYCOLUMN></MYROW>
<MYROW><MYCOLUMN>Hooded
Sweatshirt</MYCOLUMN><MYCOLUMN>Green</MYCOLUMN></MYROW
>
<MYROW><MYCOLUMN>Plastic
Visor</MYCOLUMN><MYCOLUMN>Black</MYCOLUMN></MYROW>
<MYROW><MYCOLUMN>Tank
Top</MYCOLUMN><MYCOLUMN>White</MYCOLUMN></MYROW>
<MYROW><MYCOLUMN>V-
neck</MYCOLUMN><MYCOLUMN>Orange</MYCOLUMN></MYROW>
<MYROW><MYCOLUMN>Wool
cap</MYCOLUMN><MYCOLUMN>White</MYCOLUMN></MYROW>
<MYROW><MYCOLUMN>Zipped
Sweatshirt</MYCOLUMN><MYCOLUMN>Blue</MYCOLUMN></MYROW>
</MYRESULTSET>
SetSQL method
Syntax query.SetSql(sqlStatement )
Description Sets the SQL statement in the current query object to sqlStatement [string].
Return Boolean. This method returns true or false, indicating whether the method
succeeded or not.
Example This example issues two queries by reusing the same query object:
<!--SCRIPT
myQuery = connection.CreateQuery ( ’select lname,
fname from customer’ );
while( myQuery.MoveNext() ) {
document.WriteLn( "customer: " + myQuery.GetValue(1)
328
CHAPTER 3 DynaScript Predefined Objects
+ "," + myQuery.GetValue(2) );
}
myQuery.SetSQL ( ’select id from product’ );
myQuery.Execute();
while ( myQuery.MoveNext() ) {
document.WriteLn( "id:"+myQuery.GetValue(1) );
}
-->
329
session object
session object
Object The session object is a special object that the Web site uses to store
information about a session for a given Web client.
Syntax To use a session property:
session.propertyName
Description The session object provides a way of maintaining information while a user of
your site navigates through a set of pages.
Web connections and Web connections are typically sessionless – from your Web client, you can
sessions jump from one Web site to another (and back) at any time. The Web site never
knows exactly when you've ended your “session” with it.
It is desirable, though, to maintain some concept of a session between the Web
client and the Web site. If you, as the Web site, set up a welcome page that asks
the user to log in with a name and password, each of the pages that you then
make available to them must “know” somehow that the user has already logged
in. If, however, they haven't logged in (or haven't logged in recently), the site
needs a way of detecting this to force them to log in again.
Duration of a session The Dynamo session object provides a way of storing session information so
that it persists for the duration of this particular client-to-site connection.
Because there is no explicit end to a session, though, the duration of the
connection must be decided arbitrarily. Session objects are created once they
are accessed.
By default, Dynamo considers a session to last five minutes from the time of
the user's last action at a given Web site (you can change this default duration
globally or for specific session objects). For the duration of a session, the site
maintains information about the user's connection – a login name, their last
action, or whatever other information the site requests from the client.
The site stores session information in a session object – one object for each
client. A session object is accessible to all Web pages in the site, so they can
check its status as they require. After the specified duration elapses (or times
out), the session object associated with the client goes away. Web pages
accessing the object are still able to query the session object to determine that
the session has ended (no longer exists). Null would be returned in this case.
Using the session The session object has only one predefined property (timeOut). You define
object the additional properties that you want to keep track of during a client's session.
The session information itself typically comes from client input such as an
HTML form. A login page, for example, might prompt a user for a name and
password.
330
CHAPTER 3 DynaScript Predefined Objects
331
session property
session property
The session object has this property:
timeOut property
Syntax session.timeOut
Description The duration of the session (in minutes). This property exists only if the
timeOut value has been changed from the default of five minutes. To check if
this property exists, use:
if ( exists (session.timeOut)) {
. . .
For more information on Dynamo's default cookie timeout see “Changing
Dynamo configuration settings” in PowerDynamo User’s Guide.
Each session instance can set its own timeOut value.
Example This script sets a time out of 10 minutes for the session object after a user’s
login has been validated:
<!--SCRIPT
if ( exists (session)
&& session.loginCorrect ){
session.timeOut = 10;
}
-->
332
CHAPTER 3 DynaScript Predefined Objects
site object
Object Describes a Web site. Using the site object, you can manage documents and
database connections in your site, and customize the management interface to
suit your needs.
Syntax To use a site property:
site.propertyName
To use a site method:
site.MethodName( parameter )
Script-based Management of Dynamo Web sites is driven by scripts. The site object
management provides methods that allow you to perform common management tasks:
• Creation and management of templates and scripts in your Web site.
• Creation and management of the connections to the databases providing
the live content for your Web site.
• Creation and modification of wizards and property sheets to suit your
work style and content needs.
• Addition of menu items and icons to the Sybase Central interface, to use
the wizards that you create.
Managing documents In a Dynamo Web site, you can manage documents and database connections
and connections either by using Sybase Central or by writing your own scripts. In either case,
the site object is responsible for the basic management tasks:
• Documents are manipulated using CreateDocument,
DeleteDocument, and GetDocument.
• Database connections are manipulated using CreateConnection,
DeleteConnection, and several GetConnection variants.
Customizing the Because the Dynamo management tools are script-based, you can alter these
management interface scripts or create new ones to tailor the interface to your needs:
• You can create your own wizard dialogs using CreateWizard.
333
site object
You can examine how Dynamo constructs its own wizards by inspecting
the NewTempl.ssc, NewConn.ssc, and NewFold.ssc scripts in the
Site/system folder.
• You can create your own controls (icons, menu items, and so on) by using
the OnEvent method.
You can examine how Dynamo adds its own controls at startup by
inspecting the Autoexec.ssc script in the Site/system folder.
Example This example creates a new connection called myConnection, and then
creates a new document in the Web site to use the new connection. The contents
of the new document is the word “hello”:
<!--SCRIPT
newConn = site.CreateConnection ( "MyConnection", "my
new connection", "PowerDynamo Demo" );
newDoc = site.CreateDocument ( "/Site/myDoc.stm",
"text", "my new document", "hello", "MyConnection" );
-->
See also For more information on the document object, see “document object” on page
135.
For more information on the connection object, see “connection object” on
page 95.
334
CHAPTER 3 DynaScript Predefined Objects
site properties
The site object has this property:
type property
Syntax site.type
Attributes This property is read-only.
Description Indicates if the site type is of database or dynamic file.
Example This example displays the type of site that is being used by the sample Dynamo
application:
<!--SCRIPT
document.WriteLn( site.type );
-->
The output from this example is:
database
335
site methods
site methods
The site object has these methods:
AskQuestion method
Syntax site.AskQuestion (title, message)
Description Displays a message with Yes and No buttons. This method is supported only
when executing documents through Sybase Central.
Return Boolean. Returns true if the user picked Yes, and false otherwise.
Example To ask the user if he would like to continue:
<!--SCRIPT
if ( site.AskQuestion ( "Error", "Do you wish to
continue?" )) {
document.WriteLn( "continuing" );
}
document.WriteLn( "good bye" );
-->
CopyDocument method
Syntax site.CopyDocument (source document, destination document)
Description Copies a document from one location to another. The destination document
may be given a name other than the source document name when being copied.
The specified path may be a relative or an absolute path or the tilde (~)
character may be used. This is a method of the site object.
For information on using the tilde character see “Paths” on page 77.
Return Boolean.
Example This example takes a copy of form.stm and places it into a folder called Forms
with the new name form_new.stm:
<!--SCRIPT
site.CopyDocument("~/form.stm","/Forms/form_new.stm");
-->
336
CHAPTER 3 DynaScript Predefined Objects
CreateConnection method
Syntax For ODBC connections:
site.CreateConnection(connName, description, dataSource [,
userName, password, type, connectParameters])
For Open Client connections:
site.CreateConnection(connName, description, server, userName,
password, type [, database])
Description Creates a new persistent connection and returns a new connection object,
where:
• connName [string] is the name of the connection.
• description [string] is a comment for the connection object.
• dataSource [string] is the name of the ODBC data source (not applicable
to Open Client connections),
or
server [string] is the server name of the Open Client connection (not
applicable to ODBC connections).
• userName [string] is the name of the database user (optional for ODBC
connections).
• password [string] is the password of the database user (optional for ODBC
connections).
• type [string] is the type of connection, can be ODBC or Open Client. The
default is ODBC.
• connectParameters [string] are the parameters for connecting to the
database (optional for ODBC connections, not applicable to Open Client
connections).
• database [string] is the name of the database to which to connect (optional
for Open Client connection; not applicable to ODBC connections).
337
site methods
If the data source or server is blank, the connection inherits the necessary
information from the main connection (the connection used by Dynamo to
access the Web site documents). The connection object returned by
CreateConnection in this case is “incomplete” and cannot be used to create
a query. To obtain a connection object with the blank fields filled in, use
site.GetConnection.
Temporary connection
To create a temporary connection, use the connection constructor. See
“connection object” on page 95 for more information.
Return Connection object representing the newly created connection, or null if the
connection cannot be created.
Typical reasons for null to be returned are:
• A connection of the given name already exists.
• A successful connection could not be made to the database using the
parameters supplied.
Example This script creates a new ODBC connection to the sample database, and uses
the new connection to execute a query.
<!--SCRIPT createConnection.ssc
/* Creating a connection to another site */
<HTML>
<TITLE>Query of the sample database </TITLE>
<BODY>
<H1>Information regarding the management team</H1>
<!--SQL CONNECTION_OBJECT = myConn
SELECT employee."manager_id", employee."emp_lname",
employee."emp_fname", employee."salary"
FROM "DBA"."employee" employee
338
CHAPTER 3 DynaScript Predefined Objects
-->
<TABLE BORDER>
<TR>
<TH>manager_id</TH>
<TH>emp_lname</TH>
<TH>emp_fname</TH>
<TH>salary</TH>
</TR>
<!--formatting--><TR>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>
<TD><!--data--></TD>
</TR><!--/formatting-->
</TABLE>
</BODY>
</HTML>
CreateDocument method
Syntax site.CreateDocument(docName, documentType, description, content [,
connectionName | connectionId])
Description Creates a new document in the Web site and returns a document object. The
parameters are:
• docName [string] is the name of the document. docName can be a relative
or an absolute path or the tilde (~) character may be used (see “Paths” on
page 77).
Example: "/Site/test/customer.stm"
• documentType [string] is the type of document (see document.type).
• description [string] is a comment for the document object.
If the documentType is directoryLink, description is the directory path
of the disk-based folder.
• content [string] is the document content (source).
• connectionName | connectionId [string | integer] is the name or ID of a
connection object, representing the database to which the document will
connect (optional).
339
site methods
Note:
Connection IDs are not persistent. If you restart Dynamo, connection IDs may
not be the same. For this reason, we recommend the use of connection names
whenever possible.
Return Document object representing the newly created document, or null if the
document cannot be created.
A typical reason for null to be returned is that a document by that name already
exists.
Example This script creates a new template called MyDoc.stm inside the Site folder. The
new document will consist of the word “hello”.
<!--SCRIPT newdoc.ssc
site.CreateDocument( "/site/MyDoc.stm","text", "my
new document", "hello" );
-->
See also “document object” on page 135.
CreatePropertySheet method
Syntax site.CreatePropertySheet(propertySheetObject)
Description Starts the property sheet defined by propertySheetObject, where
propertySheetObject is an indexed object, and each array element in it
represents a separate property sheet page with the following properties:
• type Type of input required for the page. One of:
• text Single-line text box.
• password Single-line text box with typed characters shown as
asterisks (for security).
• textArea Multi-line text box.
340
CHAPTER 3 DynaScript Predefined Objects
341
site methods
342
CHAPTER 3 DynaScript Predefined Objects
this.type = "Advanced";
this.title = title;
this.explanation = explanation;
// Items: An array of items to be placed on the wizard
// page. Each member of the array should be of type
// wizardItem or wizardPictureItem. Null may be passed
// in if you would like a wizard page with no input
// fields in it.
this.items = items;
}
-->
Return Boolean. Returns true or false, indicating whether the user proceeded through
the wizard or not.
Example This example shows how a script can use the site object to create a property
sheet.
<!--SCRIPT NewLink.ssc
/* Add a folder linked to a directory*/
var webRoot = site.GetRootDocument();
import ( webRoot.location +
’/system/utils/strtable.ssc’ );
import ( webRoot.location +
’/system/utils/wizard.ssc’ );
var pSheet;
343
site methods
+ ’/’ + pSheet.name.value;
var newFolder = site.CreateDocument( fullname,
’directorylink’, pSheet.directory.value );
if( newFolder == null ) {
document.writeln( formatString(
IntlStr.unableToCreate, fullname ) );
}
} else {
document.writeln( IntlStr.noFolderName );
}
}
-->
CreateWizard method
Syntax site.CreateWizard(wizardObject)
Description Starts the wizard defined by wizardObject, where wizardObject is an indexed
object, and each array element in it represents a separate wizard page with the
following properties:
• type Type of input required for the page. One of:
• text Single-line text box.
• password Single-line text box with typed characters shown as
asterisks (for security).
• textArea Multi-line text box.
• choice Combo box of values (uses choices).
• sql SQL-query textArea with button to open query editor.
• fileBrowse Single-line text box with Browse button to open
standard file-selection dialog.
• directoryBrowse Single-line text box with Browse button to
open standard folder-selection dialog.
• explanation [string] Explanatory text for the page (ignored if the type is
sql).
• question [string] Text that prompts for the value (ignored if the type is
sql).
344
CHAPTER 3 DynaScript Predefined Objects
• choices [array] The enumerated values for the combo box (if type is
choice).
• selected [integer] The number of the element of the choices array that
is selected by default when the wizard page is displayed (if type is
choice).
• next [integer, string, or function] The page to go to when the user presses
the “Next” button. Usually used to validate input or select a different
branch of the wizard. An integer represents an index to a wizard page, a
string represents the name of a wizard page, and a function can return
either an integer or a string that indicates which page to go to.
• help [string] The help that you would like displayed for the page. The
help is displayed by right-clicking in the page.
• value The value entered by the user when the wizard is created.
This method is supported only when executing documents from within Sybase
Central.
You can find the following wizard.ssc class file in the /system/utils directory of
your site folder:
<!--SCRIPT wizard.ssc
345
site methods
this.top = top;
this.width = width;
this.height = height;
}
346
CHAPTER 3 DynaScript Predefined Objects
Return Boolean. Returns true or false, indicating whether the user proceeded through
the wizard or not.
Examples This example shows how a script can use the site object to create a wizard.
Each page contains a single item:
<!--SCRIPT
/*Simple wizard example */
var wiz;
var products;
products[0] = "widget";
products[1] = "hammer";
products[2] = "putty";
347
site methods
products[3] = "stripper";
site.CreateWizard( wiz );
var wiz;
var items;
var provinces;
provinces[0] = "Alberta";
provinces[1] = "British Columbia";
provinces[2] = "Manitoba";
provinces[3] = "New Brunswick";
provinces[4] = "Newfoundland";
provinces[5] = "Northwest Territories";
provinces[6] = "Nova Scotia";
provinces[7] = "Ontario";
provinces[8] = "Prince Edward Island";
provinces[9] = "Quebec";
provinces[10] = "Saskatchewan";
provinces[11] = "Yukon";
348
CHAPTER 3 DynaScript Predefined Objects
349
site methods
this.question = question;
this.choices = choices;
this.selected = selected;
this.next = next;
this.help = help;
}
var wiz;
function whichpage() {
var pagestr = "page";
pagestr += ( wiz.start.selected + 1 );
return pagestr;
}
var choices;
choices[0] = ’New Customer’;
choices[1] = ’Returning Customer’;
350
CHAPTER 3 DynaScript Predefined Objects
var products;
products[0] = "hat";
products[1] = "shirt";
products[2] = "pogo stick";
products[3] = "ball of yarn";
351
site methods
-->
DeleteConnection method
Syntax site.DeleteConnection(connName)
Description Deletes the persistent connection defined by connName.
Return Boolean. This method returns true or false, indicating whether the method
succeeded or not.
Typical reasons for false to be returned include:
• A connection by that name does not exist.
• The connection is in use.
Example This example deletes the connection named MyConnection:
<!--SCRIPT
if ( site.DeleteConnection("MyConnection") ) {
document.WriteLn( "deleted" );
}else{
document.WriteLn( "unable to delete connection" );
}
-->
See also “connection object” on page 95.
DeleteDocument method
Syntax site.DeleteDocument(docName)
Description Deletes the document object defined by docName. docName may contain the
wildcard characters * and ? and can be an absolute or relative path. The tilde
(~) may also be used.
For information on the * and ? wildcards see “Wildcards” on page 77.
352
CHAPTER 3 DynaScript Predefined Objects
Return Boolean. This method returns true or false, indicating whether the method
succeeded or not.
Typical reasons for false to be returned include:
• A document by that name does not exist.
• The document is in use.
Example This example deletes a document called MyDoc.stm from within the Site
folder.
<!--SCRIPT
if ( site.DeleteDocument( "/Site/MyDoc.stm" )){
document.WriteLn( "deleted" );
} else {
document.WriteLn( "unable to delete document" );
}
-->
See also “document object” on page 135.
GetConnection method
Syntax site.GetConnection(connName | connId)
Description Returns the connection object representing the persistent connection called
connName[string], or having id connId[integer].
Note:
Connection IDs are not persistent. If you restart Dynamo, connection IDs may
not be the same. For this reason, Sybase recommends the use of connection
names whenever possible.
353
site methods
GetConnectionIdList method
Syntax site.GetConnectionIdList( [true|false] )
Description Returns an array of IDs of connection objects. If true is specified, the list of
connection IDs will include IDs representing the special connections <no
connection> and <inherited>. If false is specified, the list of connection IDs
does not include IDs representing the special connections. The default is true.
Return Array of integers.
Example To display a list of connection IDs.
<!--SCRIPT
document.WriteLn( site.GetConnectionIdList() );
-->
See also “connection object” on page 95.
GetConnectionNameList method
Syntax site.GetConnectionNameList( [true|false] )
Description Returns an array of names of connection objects. If true is specified, the list of
connection names includes the two special connections <no connection> and
<inherited>. If false is specified, the list does not include the special
connections. The default is true.
Return Array of strings.
Example This script displays the list of connection names.
<!--SCRIPT
document.WriteLn( site.GetConnectionNameList() );
354
CHAPTER 3 DynaScript Predefined Objects
-->
See also “connection object” on page 95.
GetDocument method
Syntax site.GetDocument(docName | docId)
Description Returns the document object defined by docName [string] or docId [integer].
docName may be a relative or an absolute path or you can use the tilde (~)
character. For more information on using the tilde please see “Paths” on page
77.
Note:
IDs are not guaranteed to be the same after restarting the Web server. For this
reason, Sybase recommends that you use the document name to identify
documents.
Return Document object representing the specified document, or null if the document
could not be retrieved. A typical reason for null to be returned is that the
specified document does not exist.
Example This script retrieves the document MyDoc.stm from within the Site folder,
passes a login name and password to MyDoc.stm, executes MyDoc.stm, and
displays the output:
<!--SCRIPT
myDoc = site.GetDocument( ’/Site/MyDoc.stm’ );
myDoc.value.loginName = "homer";
myDoc.value.password = "doh";
document.WriteLn( myDoc.GetGenerated() );
-->
See also “document object” on page 135.
GetErrorCode method
Syntax site.GetErrorCode( )
Description Returns the current error code.
Return Integer. Returns an error code associated with the last operation performed.
Example This example displays information as to why the connection was not created
successfully:
355
site methods
<HTML>
<TITLE>sample.stm</TITLE>
<BODY>
<!--SCRIPT
myConn = new Connection( ’connection1’, ’’, ’ASA 6.0
Sample’, ’basUser’, ’badPassword’ );
if( myConn == null ) {
document.writeln( "Error Code: " +
site.GetErrorCode() );
document.writeln( "Error Message: " +
site.GetErrorInfo() );
document.writeln( "Error State: " +
site.GetState() );
}
-->
</BODY>
</HTML>
See also “query object” on page 309.
“connection properties” on page 97.
“GetErrorInfo method” on page 317.
“GetState method” on page 318.
“GetErrorInfo method” on page 109.
“GetState method” on page 110.
GetErrorInfo method
Syntax site.GetErrorInfo( )
Description A description of the error associated with the last operation performed.
Return String.
Example This example displays information as to why the connection was not created
successfully:
<HTML>
<TITLE>sample.stm</TITLE>
<BODY>
<!--SCRIPT
myConn = new Connection( ’connection1’, ’’, ’ASA 6.0
Sample’, ’basUser’, ’badPassword’ );
if( myConn == null ) {
356
CHAPTER 3 DynaScript Predefined Objects
GetEventList method
Syntax site.GetEventList([controlType])
Description Returns an array of all controlType event handlers currently installed (by
OnEvent). If controlType is not specified, all installed event handlers are
returned.
controlType is described in the OnEvent method.
Each event handler object contains read-only properties that correspond to the
parameters of the OnEvent method. The only difference is the handlerScript
property, which always has an absolute path, regardless of how it was initially
specified with OnEvent.
Return Array of event handler objects.
Example This example uses GetEventList to display all previously created event
handlers with the control type of Icon.
<!--SCRIPT
// Show "Icon" event handlers for directories
eventList = site.GetEventList( ’Icon’ );
i = 0;
while( exists( eventList[i]) ) {
event = eventList[i];
document.writeln( event.controlLabel );
i++;
}
357
site methods
-->
GetRootDocument method
Syntax site.GetRootDocument( )
Description Returns the document object representing the root document of the Web site (in
most cases, the Site folder).
Return Document object.
Example This script executes a template called MyDoc.stm which resides in the root
directory of the Web site:
<!--SCRIPT
root = site.GetRootDocument();
myDoc = site.GetDocument( root.location + ’/MyDoc.stm’
);
document.WriteLn( myDoc.GetGenerated() );
-->
GetState method
Syntax site.GetState( )
Description Returns information about the SQL state of the last query operation performed.
GetState is meaningful only if the most recent error was database-related.
Example This example displays the state of the most recent Dynamo database error:
<HTML>
<TITLE>sample.stm</TITLE>
<BODY>
<!--SQL
SELECT customer.fname, customer.lname,
customer.phone, customer.id
FROM DBA.customer customeer
-->
<!--SCRIPT
queryState = site.GetState();
document.WriteLn( queryState );
queryInfo = site.GetErrorInfo();
document.WriteLn( queryInfo );
queryCode = site.GetErrorCode();
358
CHAPTER 3 DynaScript Predefined Objects
document.WriteLn( queryCode );
-->
</BODY>
</HTML>
Include method
Syntax site.Include(scriptName)
Description Executes the specified script and returns a string containing the generated
output of scriptName (absolute or relative path).
Return String.
Example This executes the script sample.ssc and returns the generated output.
<!--SCRIPT
output = site.Include( ’Site/sample.stm’ );
document.WriteLn( output );
-->
See also “site object” on page 332.
“site properties” on page 334.
“GetGenerated method” on page 147.
OnEvent method
Syntax site.OnEvent(itemName, controlType, controlLabel, description,
handlerScript)
Description Adds an event handler to the management interface (typically for creating an
icon or menu item in Sybase Central), where:
• itemName is the type of item to which the control applies. One of:
• connection Any connection.
• connectionFolder The connection folder.
• directory Any document folder.
• image Binary data (not script or template).
• script Any script.
• site The Web site database (not the Web site folder).
359
site methods
360
CHAPTER 3 DynaScript Predefined Objects
This example, if added to the autoexec.ssc file, would cause the execution of
error.ssc whenever a request was made for a document that generates an error:
site.OnEvent(’’,’Parser’,’’,’’,’error.ssc’);
This example, if added to the autoexec.ssc file, would cause the execution of
notfound.ssc whenever a request was made for a document that could not be
found:
site.OnEvent(’’,’status404’,’’,’’,’notfound.ssc’);
RenameDocument method
Syntax site.RenameDocument(source document, destination document)
Description Takes source document, renames and saves it in destination document (i.e.
source document is moved). The specified path may be a relative or an absolute
path or the tilde (~) character may be used. This is a method of the site object.
For information on using the tilde character, see “Paths” on page 77.
Return Boolean.
Example This example moves forms.stm from the root of the Web site, renames it to
test.stm and places it in the Sample location:
<!--SCRIPT
site.RenameDocument("~/form.stm","~/Sample/test.stm");
-->
ShowMessage method
Syntax site.ShowMessage (title, message)
Description Displays a message with an OK box. This method is supported only from
within Sybase Central.
Example This example displays the message “Task complete”.
<!--SCRIPT
site.ShowMessage("Request status", "Task complete");
-->
361
String object
String object
Object Enables manipulation and formatting of strings as objects and objects as
strings.
Standard: ECMAScript
Syntax To use a String method:
String.MethodName( parameter )
Description You can call String object as a function:
String( value );
or as a constructor:
myString = new String( value );
When called as a function, a type conversion is performed and a string is
returned. A new String object is not created. When a String object is created
through a constructor a String object is returned.
Example This example creates a new String object:
<!--SCRIPT
myString = new String( "hello" );
document.WriteLn( myString );
-->
362
CHAPTER 3 DynaScript Predefined Objects
String methods
The String object has these methods:
charAt method
Syntax String.charAt( position )
Description Returns the character in the string located at position. The position is 0 indexed.
Return Character.
Example This example displays the character e:
<!--SCRIPT
myString = new String("hello");
document.WriteLn(myString.charAt(1));
-->
indexOf method
Syntax String.indexOf( substring [, position] )
Description Searches for substring within a string. You can optionally specify the position
that the search is to begin. If not specified, the search begins at 0.
Return An integer indicating the start location of the substring. If the substring is not
found, -1 is returned.
Example This example has a return of 3:
<!--SCRIPT
myString = new String("hello world");
x = myString.indexOf("lo");
document.WriteLn(x);
-->
lastIndexOf method
Syntax String.lastIndexOf( substring [, position] )
Description Searches for the last occurrence of a substring within a script. The position that
the search is to begin may be optionally specified. If not specified, the search
will begin at 0.
363
String methods
Return An integer indicating the start location of the last substring found. If the
substring is not found, -1 is returned.
Example This example has a return of 14:
<!--SCRIPT
myString = new String( "hello world hello" );
x = myString.lastIndexOf( "ll" );
document.WriteLn( x );
-->
split method
Syntax String.split( separatorString )
Description Separates a string at the separatorString and returns the resulting substrings as
an Array object. The separatorString characters are not part of the returned
substrings.
If an empty separator string is provided (“ ”) as the separator string, the string
is split into an array of chars.
Return An Array object.
Example This example splits a string each time the separator string 'split' is encountered:
<!--SCRIPT
myString = new String( "This string will split each
time the string ’split’ is encountered" );
splitString = myString.split( "split" );
document.WriteLn( splitString );
-->
The output from this example looks similar to:
{ This string will , each time the string ’, ’ is
encountered }
substring method
Syntax String.substring( start )
Description Returns a substring value that is extracted from the string object starting at the
start value (numeric position) and continuing to the end of the string object.
Return String.
364
CHAPTER 3 DynaScript Predefined Objects
substring method
Syntax String.substring( start, end )
Description Returns a substring value that is extracted from the string object starting at the
start value and ending (but not including) the end value.
Return String.
Example This example returns “world”:
<!--SCRIPT
myString = new String( "Hello world, hello" );
sampleString = myString.substring( 5, 11 );
document.WriteLn( sampleString );
-->
toLowerCase method
Syntax String.toLowerCase( )
Description Converts a string object to an entirely lower-case string.
Return String.
Example This example returns of “hello, world hello”:
<!--SCRIPT
myString = new String( "Hello world, hello" );
sampleString = myString.toLowerCase();
document.WriteLn( sampleString );-->
-->
toString method
Syntax String.toString( )
365
String methods
toUpperCase method
Syntax String.toUpperCase( )
Description Converts a string object to upper case.
Return String.
Example This example will returns of “HELLO WORLD, HELLO”:
<!--SCRIPT
myString = new String( "Hello world, hello" );
sampleString = myString.toUpperCase();
document.WriteLn( sampleString );
-->
valueOf method
Syntax String.valueOf( )
Description Returns the string value.
Return String.
Example • This example returns “Hello world, hello”:
<!--SCRIPT
myString = new String( "Hello world, hello" );
document.WriteLn( myString.valueOf() );
-->
366
CHAPTER 3 DynaScript Predefined Objects
system object
Object Provides functionality for interacting with the server’s operating system
environment.
Syntax To use a system property:
system.propertyName
To use a system method:
system.MethodName( parameter )
Description The system object is provided for you.
Example This example modifies the system path.
<--SCRIPT
// Adds e:\src to the Environment System Path
path = system.GetEnv( "PATH" );
path = path + "e:\src;";
system.SetEnv( "PATH", path, true );
-->
See also “errorNumber property” on page 218.
“errorString property” on page 219.
367
system properties
system properties
The system object has these properties:
errorNumber property
Syntax system.errorNumber
Attributes This property is read-only.
Description A number [integer] representing the error code of the last system method call.
Example This example displays an error code:
<!--SCRIPT
document.WriteLn( system.errorNumber );
-->
See also “errorString property” on page 219.
errorString property
Syntax system.errorString
Attributes This property is read-only.
Description A string containing an error message for the error code of the last system
method call. This is a read only property.
Example This example displays an error message:
<!--SCRIPT
document.WriteLn( system.errorString );
-->
See also “errorNumber property” on page 218.
368
CHAPTER 3 DynaScript Predefined Objects
system methods
The system object has these methods:
Exec method
Syntax system.Exec(cmd)
Description Executes a command outside the Dynamo Script Interpreter.
Return Boolean. Returns true or false indicating whether or not the call succeeded:
Example This example launches the Windows Notepad utility.
<--SCRIPT
// Launches notepad
system.Exec( "notepad.exe" );
-->
GetCWD method
Syntax system.GetCWD( )
Description Returns the current working directory.
Return String.
Example To return the current directory:
<!--SCRIPT
// Prints the current working directory
document.WriteLn( system.GetCWD() );
-->
GetEnv method
Syntax system.GetEnv(env)
Description Searches the environment for an environment entry matching env, and returns
its value.
Return String or null if no matching entry found.
Example This example retrieves the environment’s PATH entry:
<!--SCRIPT
369
system methods
SetEnv method
Syntax system.SetEnv(env,value,overwrite)
Description Searches the environment for an entry matching env. If there is no such entry,
an entry is created and set to value; otherwise, if overwrite is true the entry
is set to value.
Example This example modifies the system path.
<!--SCRIPT
// Adds e:\src to the Environment System Path
path = system.GetEnv( "PATH" );
path = path + "e:\src;";
system.SetEnv( "PATH", path, true );
-->
370
Index
A B
abs method (Math object) 293 backslash
absolute paths 77 special character 65
acos method (Math object) 293 base classes
ActiveX objects 62 about 73
AddRecipient method (outgoing mail piece object) body property (incoming mail piece object) 261
280 body property (outgoing mail piece object) 274, 279
AddReplyTo method (outgoing mail piece object) Boolean literals 37
282 Boolean object
apostrophe about 93
special character 65 methods 94
appendChild method (DOMNode object) 202 BORDER attribute (FORMATTING tag) 14
appendData method (DOMCharacterData object) break statements
160 about 50
arguments object 61 built-in functions 62
Array object
about 81
methods 83
properties 82 C
arrays
CACHED_OUTPUT_TIMEOUT attribute
about 71
(DOCUMENT tag) 10
asin method (Math object) 293
cachedOutputTimeOut property (document object)
AskQuestion method (site object) 335
136
atan method (Math object) 294
callee property (arguments object) 61
371
Index
CallStaticMethod method (java object) 249, 251 connectionType property (connection object) 98
CDATA connectParameters property (connection object) 98
FORMATTING tag 14 CONTENT_TYPE attribute (DOCUMENT tag) 10
ceil method (Math object) 294 contentType property (document object) 137
chained mode 96 continue statement
ChangeCurrentDirectory method (FTP object) 228 about 51
charAt method (String object) 362 control characters in strings 37
childNodes property (DOMNode object) 195 controls
class statements creating 358
about 52, 73, 74 conventions
classes about xviii
about 70, 73 syntax xviii
instances 76 cookies for sessions 329
cloneNode method (DOMNode object) 202 CopyDocument method (site object) 335
Close method (file object) 222 cos method (Math object) 295
Close method (query object) 314, 315 count property (mailList object) 257
COLUMN_TAG attribute (FORMATTING tag) 14 createAttribute method (DOMDocument object) 167
COMMAND attribute (EXECUTE tag) 13 createCDATASection method (DOMDocument object)
comment statements 167
about 58 createComment method (DOMDocument object) 168
comments CreateComponent method 246
HTML 35 CreateComponent method (connection object) 106
Commit method (connection object) 105 CreateComponent method (java object) 246
COMPONENT (Dynamo tag) 5 CreateConnection method (site object) 336
COMPONENT_NAME attribute (COMPONENT tag) 5 CreateDirectory method (FTP object) 229
conditional SQL tags 29 CreateDocument method (site object) 338
Connect method (connection object) 106 createDocumentFragment method (DOMDocument
Connect method (FTP object) 228 object) 168
connected property (connection object) 97 createElement method (DOMDocument object) 169
connection object createEntityReference method (DOMDocument object)
about 95 169
methods 105 CreateObject function (built-in) 62
properties 97 CreateObject method (java object) 248
connection property (query object) 311 createProcessingInstruction method (DOMDocument
CONNECTION_NAME attribute (SQL tag) 24 object) 169
CONNECTION_NAME attribute (SQL_INSERT tag) 26 CreatePropertySheet method (site object) 339
CONNECTION_OBJECT attribute (COMPONENT tag) CreateQuery method (connection object) 106
5 createTextNode method (DOMDocument object) 170
CONNECTION_OBJECT attribute (SQL tag) 24 CreateWizard method (site object) 343
CONNECTION_OBJECT attribute (SQL_INSERT tag) cursorType property (query object) 311
26
connectionId property (document object) 136
connectionName property (document object) 137
connections D
site object 332 DATA
temporary 95 in HTML 9
372
Index
374
Index
getMonth method (Date object) 117 ImportFrom method (document object) 149
getNamedItem method (DOMNamedNodeMap object) INCLUDE 20
191 in HTML 20
GetRootDocument method (site object) 357 INCLUDE (Dynamo tag) 20
GetRowCount method (query object) 317 Include method (site object) 358
getSeconds method (Date object) 117 IncludeGenerated method (document object) 149
GetServerVariable method (document object) 147 INDEX attribute (LABEL tag) 19, 21
GetState method (connection object) 110 indexed and named members 76
GetState method (query object) 318 indexOf method (String object) 362
GetState method (site object) 357 inheritance
GetSupportedMoves method (connection object) 110 about 70, 72, 74
getTime method (Date object) 118 insertBefore method (DOMNode object) 203
getTimezoneOffset method (Date object) 118 insertData method (DOMCharacterData object) 161
getUTCDate method (Date object) 118 inserting data 26
getUTCDay method (Date object) 119 instances
getUTCFullYear method (Date object) 119 creating 70, 76
getUTCHours method (Date object) 120 integer literals 36
getUTCMilliseconds method (Date object) 120 interface
getUTCMinutes method (Date object) 120 customizing 332
getUTCMonth method (Date object) 121 isFinite function (built-in) 62
getUTCSeconds method (Date object) 122 isNan function (built-in) 62
GetValue method (query object) 318 isolationLevel property (connection object) 100
getYear method (Date object) 122 item method (DOMNamedNodeMap object) 191
item method (DOMNodeList object) 207
H
hasChildNodes method (DOMNode object) 203 J
hasFeature method (DOMImplementation object) 188 Jaguar
headers property (incoming mail piece object) 262 calling components 106
HTML COMPONENT tag 5
comments 35 JaguarL creating a component 246
HTML headers for functions 60 java object
about 244
methods 246
JavaScript
I tags 35
id property (document object) 138 JavaScript Authoring Guide
identifiers URL 33
about 38 join method (Array object) 83
IF (Dynamo tag) 19
if-else statements
about 46
implementation property (DOMDocument object) 165 L
import statements LABEL (Dynamo tag) 21
about 56, 60 lastChild property (DOMNode object) 196
376
Index
M N
mail NAME attribute (DATA tag) 9
sending 22, 286 NAME attribute (FORMATTING tag) 14
mail piece object (incoming) NAME attribute (LABEL tag) 19, 21
about 260 name property (attachment object) 87
methods 267 name property (connection object) 101
properties 261 name property (document object) 139
mail piece object (outgoing) name property (DOMAttribute object) 154
about 273 name property (DOMDocumentType object) 174
methods 280 name property (file object 220
properties 274 name property (recipient object) 307
mailList named and indexed members 76
methods 258 NaN property (Number object) 301
mailList object NEGATIVE_INFINITY property (Number object)
about 255 302
properties 257 nesting
MAILPIECE (Dynamo tag) 22 FORMATTING tag 18
Math new features
methods 293 documentation xvii
Math object new operator
about 288 about 54, 76
Index
378
Index
P java 244
mail piece (incoming) 260
parent property (document object) 140
mail piece (outgoing) 273
parentNode property (DOMNode object) 200
mailList 255
parse method (Date object) 122
Math 288
parseFloat function (built-in) 62
Number 300
parseInt function (built-in) 62
Object 304
passing parameters 147
query 309
passing values 142
recipient 306
passing variables 60
session 329
password property (connection object) 102
site 332
path 77
String 361
PI property (Math object) 291
system 366
PKG attribute (COMPONENT tag) 5
prettyPrint method (DOMDocument object) 171
polymorphism
previousSibling property (DOMNode object) 201
about 70, 72
properties
POSITIVE_INFINITY property (Number object)
about 70
302
property sheets
pow method (Math object) 297
creating 339
predefined objects
publicId property (DOMEntity object) 184
about 79
publicId property (DOMNotation object) 209
Array 81
PutData method (FTP object) 231
attachment 86
PutDataWithAppend method (FTP object) 232
Boolean 93
PutDocument method (FTP object) 233
connection 95
PutDocumentWithAppend method (FTP object) 233
Date 113
PutFile method (FTP object) 234
document 135
PutFileWithAppend method (FTP object) 235
DOMAttribute 153
DOMCDATASection 157
DOMCharacterData 158
DOMComment 163 Q
DOMDocument 164
QUERY attribute (DATA tag) 9
DOMDocumentFragment 172
query object
DOMDocumentType 173
about 309
DOMElement 176
methods 314
DOMEntity 183
properties 311
DOMEntityReference 186
DOMImplementation 187
DOMNamedNodeMap 189
DOMNode 194 R
DOMNodeList 205
DOMNotation 208 random method (Math object) 297
DOMProcessingInstruction 211 Read method (file object) 223
DOMText 214 ReadChar method (file object) 224
file 217 ReadLine method (file object) 224
FTP 227 recipient object
Function 241 about 306
Index
380
Index
T JavaScript guide 33
USE_CDATA attribute (FORMATTING tag) 14
tagName property (DOMElement object) 177
userId property (connection object) 104
tags
Dynamo tags 2
Jaguar 5
JavaScript vs Dynamo 35 V
scripts 35
value property (document object) 142
tan method (Math object) 298
value property (DOMAttribute object) 155
target property (DOMProcessingInstruction object) 212
valueOf method (Boolean object) 94
temporary
valueOf method (Date object) 134
connections 95
valueOf method (Number object) 303
DOMDocumentTypes 173
valueOf method (Object object) 305
DOMEntitys 183
valueOf method (String object) 365
DOMImplementations 187
values
DOMTexts 214
passing 142
this keyword
var statements
about 53
about 54
tilde 77
variables
timeOut property (session object) 331
about 38
TO attribute (MAILPIECE tag) 22
assigning values 39
toDOMDocument function (built-in) 65
checking, 64
toGMTString method (Date object) 132
data types 38
toLocaleString method (Date object) 133
declaration 38
toLowerCase method (String object) 364
passing by value and reference 60
toString method (Array object) 84
scope 39
toString method (Boolean object) 94
toString method (Date object) 133
toString method (Function object) 243
toString method (Number object) 303 W
toString method (Object object) 305
toString method (String object) 364 Web authoring tools
toUpperCase method (String object) 365 using with PowerDynamo 35
toUTCString method (Date object) 133 while statements
toXMLString function (built-in) 66 about 47
trailing blanks wildcards 77
stripping them 14 with statements
type property (document object) 142 about 52
type property(site object) 334 wizards
typeof function (built-in) 67 creating 343
typing of variables 38 Write method (document object) 151
Write(s) method (file object) 225
WriteLine(s) method (file object) 225
WriteLn method (document object) 151
U
unescape function (built-in) 62
URL
382
Index
X
XML
FORMATTING 14
ResultsToXML method 326
xmlEscape function (built-in) 68
Index
384