powerdynamo - unione parmense degli industriali · contents paths ..... 73 wildcards..... 73

360
PowerDynamo Reference PowerDynamo Version 3.5

Upload: others

Post on 02-Mar-2021

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

PowerDynamo Reference

PowerDynamoVersion 3.5

Page 2: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

n new

29-9

the

erver, catio

s, n prise ork n ase,

upport, it,

erAMC, ipt, erWare

or, S SQL , SQL L

inancial orkbench, ream,

e roup

s.

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 i 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) 2845.

Customers in other countries with a U.S. license agreement may contact Customer Fulfillment via the above fax number. All or 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 SAdaptive Server Anywhere, Adaptive Server Enterprise, Adaptive Server Enterprise Monitor, Adaptive Server Enterprise Replin, 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, DataExpresDataServer, DataWindow, DB-Library, dbQueue, Developers Workbench, Direct Connect Anywhere, DirectConnect, DistributioDirector, E-Anywhere, E-Whatever, Embedded SQL, EMS, Enterprise Application Server, Enterprise Application Studio, EnterClient/Server, Enterprise Connect, Enterprise Data Studio, Enterprise Manager, Enterprise SQL Server Manager, Enterprise WArchitecture, Enterprise Work Designer, Enterprise Work Modeler, EWA, Gateway Manager, ImpactNow, InfoMaker, InformatioAnywhere, Information Everywhere, InformationConnect, InternetBuilder, iScript, Jaguar CTS, jConnect for JDBC, KnowledgeBMainframeConnect, Maintenance Express, MAP, MDI Access Server, MDI Database Gateway, media.splash, MetaWorks, MySNet-Gateway, Net-Library, NetImpact, ObjectConnect, ObjectCycle, OmniConnect, OmniSQL Access Module, OmniSQL ToolkOpen 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, PowPowerBuilder, PowerBuilder Foundation Class Library, PowerDesigner, PowerDimensions, PowerDynamo, PowerJ, PowerScrPowerSite, PowerSocket, Powersoft, PowerStage, PowerStudio, PowerTips, Powersoft Portfolio, Powersoft Professional, PowDesktop, 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 Design-Designor, SDF, Secure SQL Server, Secure SQL Toolset, Security Guardian, SKILS, smart.partners, smart.parts, smart.script,Advantage, SQL Anywhere, SQL Anywhere Studio, SQL Code Checker, SQL Debug, SQL Edit, SQL Edit/TPU, SQL EverywhereModeler, SQL Remote, SQL Server, SQL Server Manager, SQL SMART, SQL Toolset, SQL Server/CFT, SQL Server/DBM, SQServer SNMP SubAgent, SQL Station, SQLJ, STEP, SupportNow, Sybase Central, Sybase Client/Server Interfaces, Sybase FServer, Sybase Gateways, Sybase MPP, Sybase SQL Desktop, Sybase SQL Lifecycle, Sybase SQL Workgroup, Sybase User WSybaseWare, Syber Financial, SyberAssist, SyBooks, System 10, System 11, System XI (logo), SystemTools, Tabular Data StTransact-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, WarehousWORKS, Watcom, Watcom SQL, Watcom SQL Server, Web Deployment Kit, Web.PB, Web.SQL, WebSights, WebViewer, WorkGSQL 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 companie

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

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

Page 3: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Contents

About This Book ........................................................................................................................ xvii

CHAPTER 1 Dynamo Tags................................................................................... 1Overview .......................................................................................... 1Dynamo tags versus DynaScript ...................................................... 3The Dynamo tags ............................................................................. 4

COMPONENT ........................................................................... 4DATA......................................................................................... 8DOCUMENT.............................................................................. 9ELSE ....................................................................................... 11ELSEIF .................................................................................... 11ENDIF...................................................................................... 12EVALUATE.............................................................................. 12EXECUTE ............................................................................... 13FORMATTING......................................................................... 13IF ............................................................................................. 19INCLUDE................................................................................. 19LABEL ..................................................................................... 20MAILPIECE ............................................................................. 21SCRIPT ................................................................................... 22SQL ......................................................................................... 23SQL_INSERT .......................................................................... 25SQL condition.......................................................................... 28SQL_ERROR_CODE.............................................................. 29SQL_ERROR_INFO................................................................ 30SQL_STATE............................................................................ 31

CHAPTER 2 The DynaScript Language............................................................ 33Overview ........................................................................................ 33SCRIPT tag .................................................................................... 34Literals............................................................................................ 34

Integers ................................................................................... 35Floating-point numbers............................................................ 35

iii

Page 4: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Contents

Booleans ................................................................................. 35Strings ..................................................................................... 35

Variables ........................................................................................ 36Expressions.................................................................................... 38Operators ....................................................................................... 39

Arithmetic operators ................................................................ 40Conditional operator ................................................................ 40String operators....................................................................... 41Comparison operators............................................................. 41Boolean operators ................................................................... 42Bitwise operators..................................................................... 42Delete operator........................................................................ 42Void operator........................................................................... 43Typeof operator ....................................................................... 43

Statements ..................................................................................... 43if-else statement ...................................................................... 44for statement ........................................................................... 44while statement ....................................................................... 45do-while statement .................................................................. 45switch statement...................................................................... 46break statement....................................................................... 48continue statement .................................................................. 48for-in statement ....................................................................... 48with statement ......................................................................... 49class statement ....................................................................... 50this keyword ............................................................................ 51new operator ........................................................................... 51var statement........................................................................... 52function statement ................................................................... 52return statement ...................................................................... 53import statement...................................................................... 54comment statements ............................................................... 55exit statement .......................................................................... 56

Functions........................................................................................ 56Functions and the arguments object ....................................... 57Built-in functions ...................................................................... 58Dynamo-specific built-in functions........................................... 59

Objects ........................................................................................... 66Properties and methods .......................................................... 66Object-oriented concepts ........................................................ 68Defining base classes ............................................................. 69Extending existing classes by inheritance............................... 70Creating instances of classes.................................................. 72Working with named and indexed members ........................... 72

iv

Page 5: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Contents

Paths ....................................................................................... 73Wildcards................................................................................. 73

CHAPTER 3 DynaScript Predefined Objects ................................................... 75Array object .................................................................................... 76Array properties.............................................................................. 77

length property ........................................................................ 77Array methods................................................................................ 77

join method.............................................................................. 77reverse method ....................................................................... 78sort method ............................................................................. 78toString method ....................................................................... 79

attachment object........................................................................... 80attachment properties .................................................................... 80

mimeType property ................................................................. 81name property ......................................................................... 81

attachment methods....................................................................... 82GetContents method ............................................................... 82GetErrorCode method ............................................................. 83GetErrorInfo method................................................................ 84SaveAsDocument method....................................................... 84SaveAsFile method ................................................................. 85

Boolean object ............................................................................... 86Boolean methods ........................................................................... 86

toString method ....................................................................... 86valueOf method ....................................................................... 87

connection object ........................................................................... 87connection properties..................................................................... 90

autoCommit property ............................................................... 90connected property.................................................................. 90connectionType property......................................................... 91connectParameters property ................................................... 91database property ................................................................... 92databaseType property ........................................................... 92dataSource property................................................................ 92dataSourceList property .......................................................... 93description property................................................................. 93isolationLevel property ............................................................ 93name property ......................................................................... 94password property................................................................... 95server property ........................................................................ 95simulateCursors property ........................................................ 95userId property ........................................................................ 97

connection methods ....................................................................... 97

Page 6: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Contents

Commit method ....................................................................... 97Connect method ...................................................................... 98CreateComponent method ...................................................... 98CreateQuery method............................................................... 99Disconnect method................................................................ 100GetErrorCode method ........................................................... 100GetErrorInfo method.............................................................. 101GetState method ................................................................... 102GetSupportedMoves method ................................................ 103Rollback method.................................................................... 103

Date object ................................................................................... 104Date methods............................................................................... 106

getDate method..................................................................... 106getDay method ...................................................................... 106getFullYear method ............................................................... 107getHours method................................................................... 107getMilliseconds method......................................................... 107getMinutes method................................................................ 108getMonth method .................................................................. 108getSeconds method .............................................................. 108getTime method .................................................................... 109getTimezoneOffset method ................................................... 109getUTCDate method ............................................................. 110getUTCDay method............................................................... 110getUTCFullYear method........................................................ 111getUTCHours method ........................................................... 111getUTCMilliseconds method ................................................. 111getUTCMinutes method ........................................................ 112getUTCMonth method ........................................................... 112getUTCSeconds method ....................................................... 113getYear method..................................................................... 113parse method ........................................................................ 114setDate method ..................................................................... 114setFullYear method ............................................................... 115setHours method ................................................................... 115setMilliseconds method ......................................................... 116setMinutes method ................................................................ 116setMonth method................................................................... 117setSeconds method............................................................... 118setTime method..................................................................... 118setUTCDate method.............................................................. 119setUTCFullYear method........................................................ 120setUTCHours method............................................................ 121setUTCMilliseconds method.................................................. 121

vi

Page 7: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Contents

setUTCMinutes method......................................................... 122setUTCMonth method ........................................................... 122setUTCSeconds method ....................................................... 123setYear method ..................................................................... 123toGMTString method ............................................................. 124toLocaleString method .......................................................... 124toString method ..................................................................... 124toUTCString method.............................................................. 125valueOf method ..................................................................... 125

document object........................................................................... 126document properties .................................................................... 127

cachedOutputTimeOut property ............................................ 127connectionId property............................................................ 127connectionName property ..................................................... 128contentType property ............................................................ 128description property............................................................... 128id property ............................................................................. 129lastModified property ............................................................. 129location property.................................................................... 130name property ....................................................................... 130parent property ...................................................................... 131redirect property .................................................................... 131size property.......................................................................... 131source property ..................................................................... 132status property....................................................................... 132type property ......................................................................... 133value property........................................................................ 133

document methods....................................................................... 136ExportTo method................................................................... 137GetDirectory method ............................................................. 137GetGenerated method........................................................... 138GetServerVariable method.................................................... 138ImportFrom method............................................................... 140IncludeGenerated method..................................................... 140Write method ......................................................................... 142WriteLn method ..................................................................... 142

DOMAttribute object ..................................................................... 143DOMAttribute properties .............................................................. 144

name property ....................................................................... 144specified property .................................................................. 145value property........................................................................ 145

DOMAttribute methods................................................................. 146DOMCDATASection object .......................................................... 146DOMCharacterData object ........................................................... 146

Page 8: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Contents

DOMCharacterData properties .................................................... 147data property ......................................................................... 147length property ...................................................................... 147

DOMCharacterData methods....................................................... 148appendData method.............................................................. 148deleteData method ................................................................ 148insertData method ................................................................. 149replaceData method .............................................................. 149substringData method ........................................................... 150

DOMComment object................................................................... 150DOMDocument object .................................................................. 151DOMDocument properties ........................................................... 151

doctype property.................................................................... 151documentElement property ................................................... 152implementation property........................................................ 152

DOMDocument methods.............................................................. 153createAttribute method .......................................................... 153createCDATASection method ............................................... 153createComment method........................................................ 154createDocumentFragment method........................................ 154createElement method .......................................................... 155createEntityReference method.............................................. 155createProcessingInstruction method ..................................... 155createTextNode method........................................................ 156getElementsByTagName method ......................................... 156prettyPrint method ................................................................. 157

DOMDocumentFragment object .................................................. 157DOMDocumentType object .......................................................... 158DOMDocumentType properties ................................................... 158

entities property..................................................................... 158name property ....................................................................... 159notations property.................................................................. 160

DOMElement object ..................................................................... 160DOMElement property ................................................................. 161

tagName property.................................................................. 161DOMElement methods................................................................. 161

getAttribute method ............................................................... 161getAttributeNode method ...................................................... 162getElementsByTagName method ......................................... 162normalize method.................................................................. 163removeAttribute method ........................................................ 164removeAttributeNode method ............................................... 164setAttribute method ............................................................... 165setAttributeNode method....................................................... 165

viii

Page 9: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Contents

DOMEntity object ......................................................................... 166DOMEntity properties................................................................... 166

notationName property.......................................................... 167publicId property.................................................................... 167systemId property.................................................................. 168

DOMEntityReference object......................................................... 168DOMImplementation object.......................................................... 169DOMImplementation methods ..................................................... 169

hasFeature method ............................................................... 169DOMNamedNodeMap object ....................................................... 170DOMNamedNodeMap property ................................................... 170

length property ...................................................................... 171DOMNamedNodeMap methods................................................... 171

getNamedItem method.......................................................... 171item method........................................................................... 171removeNamedItem method................................................... 172setNamedItem method .......................................................... 172

DOMNode object.......................................................................... 173DOMNode properties ................................................................... 174

attributes property ................................................................. 174childNodes property .............................................................. 174firstChild property .................................................................. 175lastChild property .................................................................. 176nextSibling property............................................................... 176nodeName property............................................................... 176nodeType property ................................................................ 177nodeValue property ............................................................... 179ownerDocument property ...................................................... 179parentNode property ............................................................. 180previousSibling property ........................................................ 180

DOMNode methods ..................................................................... 181appendChild method ............................................................. 181cloneNode method ................................................................ 181hasChildNodes method ......................................................... 182insertBefore method .............................................................. 182removeChild method ............................................................. 182replaceChild method ............................................................. 183

DOMNodeList object .................................................................... 183DOMNodeList property ................................................................ 183

length property ...................................................................... 184DOMNodeList methods................................................................ 184

item method........................................................................... 184DOMNotation object ..................................................................... 184DOMNotation properties .............................................................. 185

Page 10: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Contents

publicId property.................................................................... 185systemId property.................................................................. 185

DOMNotation methods................................................................. 185DOMProcessingInstruction object ................................................ 185DOMProcessingInstruction properties ......................................... 186

data property ......................................................................... 186target property ....................................................................... 186

DOMProcessingInstruction methods............................................ 187The DOMText object .................................................................... 187DOMText properties..................................................................... 188DOMText methods ....................................................................... 188

splitText method .................................................................... 188file object ...................................................................................... 188file properties................................................................................ 189

eof property ........................................................................... 190errorNumber property............................................................ 190errorString property ............................................................... 191name property ....................................................................... 192mode property ....................................................................... 192

file methods.................................................................................. 193Close method ........................................................................ 193Delete method ....................................................................... 193GetFilePtr method ................................................................. 194Open method......................................................................... 194Read method......................................................................... 195ReadChar method ................................................................. 195ReadLine method .................................................................. 196Seek method ......................................................................... 196Write method ......................................................................... 196WriteLine method .................................................................. 197

FTP object.................................................................................... 197FTP methods................................................................................ 198

ChangeCurrentDirectory method .......................................... 198Connect method .................................................................... 198CreateDirectory method ........................................................ 199DeleteFile method ................................................................. 199Disconnect method................................................................ 200GetErrorCode method ........................................................... 200GetErrorInfo method.............................................................. 201PutData method .................................................................... 201PutDataWithAppend method................................................. 202PutDocument method............................................................ 203PutDocumentWithAppend method ........................................ 204PutFile method ...................................................................... 205

x

Page 11: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Contents

PutFileWithAppend method................................................... 205RemoveDirectory method...................................................... 206RetrieveCurrentDirectory method.......................................... 206RenameFile method .............................................................. 207RetrieveData method ............................................................ 207RetrieveDirectoryListing method ........................................... 208RetrieveDocument method.................................................... 208RetrieveFile method .............................................................. 209RetrieveFileWithAppend method........................................... 210

The Function object...................................................................... 210Function properties ...................................................................... 211

length property ...................................................................... 211Function methods......................................................................... 212

toString method ..................................................................... 212java object .................................................................................... 212java methods................................................................................ 214

CreateComponent method .................................................... 215CreateObject method ............................................................ 217CallStaticMethod method ...................................................... 217GetHomeInterface method .................................................... 218GetUserTransaction method ................................................. 220

mailList object .............................................................................. 223mailList properties ........................................................................ 224

count property ....................................................................... 224mailList methods .......................................................................... 225

Disconnect method................................................................ 225GetErrorCode method ........................................................... 226GetErrorInfo method.............................................................. 226

mailPiece object (incoming) ......................................................... 227mail piece properties (incoming) .................................................. 228

attachments property............................................................. 228body property ........................................................................ 228from property ......................................................................... 229headers property ................................................................... 229recipients property................................................................. 230replyTo property .................................................................... 230sender property ..................................................................... 231size property.......................................................................... 232subject property..................................................................... 232

mail piece methods (incoming) .................................................... 233Delete method ....................................................................... 233Forward method .................................................................... 233GetErrorCode method ........................................................... 234GetErrorInfo method.............................................................. 235

Page 12: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Contents

Redirect method .................................................................... 235Reply method ........................................................................ 236Retrieve method .................................................................... 237

mailPiece object (outgoing).......................................................... 238mailPiece properties (outgoing) ................................................... 239

body property ........................................................................ 239from property ......................................................................... 240sender property ..................................................................... 242smtpHost property ................................................................. 243body property ........................................................................ 244

mailPiece methods (outgoing)...................................................... 244AddRecipient method ............................................................ 244AddReplyTo method.............................................................. 247AttachData method................................................................ 248AttachDocument method....................................................... 248AttachFile method ................................................................. 249GetErrorCode method ........................................................... 250GetErrorInfo method.............................................................. 250Send method ......................................................................... 251

Math object................................................................................... 252Math properties ............................................................................ 252

E property.............................................................................. 252LN2 property.......................................................................... 253LN10 property........................................................................ 253LOG2E property .................................................................... 254LOG10E property .................................................................. 254PI property............................................................................. 254SQRT1_2 property ................................................................ 255SQRT2 property .................................................................... 255

Math methods .............................................................................. 255abs method............................................................................ 256acos method.......................................................................... 256asin method........................................................................... 256atan method .......................................................................... 256atan2 method ........................................................................ 257ceil method ............................................................................ 257cos method............................................................................ 257exp method............................................................................ 258floor method .......................................................................... 258log method............................................................................. 258max method........................................................................... 259min method............................................................................ 259pow method........................................................................... 260random method ..................................................................... 260

xii

Page 13: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Contents

round method ........................................................................ 260sin method............................................................................. 261sqrt method ........................................................................... 261tan method ............................................................................ 261

Number object.............................................................................. 261Number properties ....................................................................... 262

MAX_VALUE property........................................................... 262MIN_VALUE property ............................................................ 263NaN property ......................................................................... 263NEGATIVE_INFINITY property ............................................. 264POSITIVE_INFINITY property............................................... 264

Number methods.......................................................................... 264toString method ..................................................................... 264valueOf method ..................................................................... 265

Object object ................................................................................ 265Object methods ............................................................................ 266

toString method ..................................................................... 266valueOf method ..................................................................... 267

recipient object ............................................................................. 267recipient properties....................................................................... 268

mode property ....................................................................... 268name property ....................................................................... 269

query object.................................................................................. 269query properties ........................................................................... 271

connection property............................................................... 271cursorType property .............................................................. 272stripTrailingBlanks property ................................................... 273

query methods ............................................................................. 274Close method ........................................................................ 274Execute method .................................................................... 274GetColumnCount method...................................................... 275GetColumnIndex method ...................................................... 275GetColumnLabel method ...................................................... 275GetEmpty method ................................................................. 276GetErrorCode method ........................................................... 277GetErrorInfo method.............................................................. 277GetRowCount method........................................................... 277GetState method ................................................................... 278GetValue method .................................................................. 278Move method......................................................................... 279MoveFirst method.................................................................. 280MoveLast method.................................................................. 281MoveNext method ................................................................. 282MovePrevious method........................................................... 283

Page 14: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Contents

MoveRelative method............................................................ 284Opened method..................................................................... 285Refresh method..................................................................... 285ResultsToXMLString method ................................................ 286SetSQL method..................................................................... 287

session object .............................................................................. 288session property........................................................................... 290

timeOut property.................................................................... 290site object ..................................................................................... 291site properties............................................................................... 292

type property ......................................................................... 292site methods................................................................................. 293

AskQuestion method ............................................................. 293CopyDocument method......................................................... 293CreateConnection method .................................................... 294CreateDocument method ...................................................... 296CreatePropertySheet method................................................ 297CreateWizard method ........................................................... 301DeleteConnection method..................................................... 309DeleteDocument method....................................................... 309GetConnection method ......................................................... 310GetConnectionIdList method................................................. 311GetConnectionNameList method .......................................... 311GetDocument method ........................................................... 312GetErrorCode method ........................................................... 312GetErrorInfo method.............................................................. 313GetEventList method............................................................. 314GetRootDocument method.................................................... 315GetState method ................................................................... 315Include method...................................................................... 316OnEvent method ................................................................... 316RenameDocument method ................................................... 318ShowMessage method.......................................................... 318

String object ................................................................................. 319String methods ............................................................................. 319

charAt method ....................................................................... 319indexOf method ..................................................................... 320lastIndexOf method ............................................................... 320split method ........................................................................... 320substring method................................................................... 321substring method................................................................... 321toLowerCase method ............................................................ 322toString method ..................................................................... 322toUpperCase method ............................................................ 322

xiv

Page 15: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Chapter

valueOf method ..................................................................... 323system object................................................................................ 323system properties ......................................................................... 324

errorNumber property ............................................................ 324errorString property................................................................ 324

system methods ........................................................................... 324Exec method.......................................................................... 325GetCWD method ................................................................... 325GetEnv method...................................................................... 325SetEnv method ...................................................................... 326

xv

Page 16: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

xvi

Page 17: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

b

tion:

te

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.

Printed and online documentationPowerDynamo documentation is available in both printed and online formats.

There are two online formats, which contain the same content:

• Windows Help, and

• An HTML version, which you can import into a PowerDynamo Wesite, is also available.

Online documentation more complete and timelyOnline documentation is more up to date than the printed documentain case of differences between the two, you should follow the online documentation. The online documentation may also be more complethan the printed documentation.

Syntax conventionsThe following conventions are used in this manual:

xvii

Page 18: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

About this book

Conventions used in this bookPowerDynamo Web sites work with either Adaptive Server Enterprise or Adaptive Server Anywhere databases. In this book, sections that apply to only one of these databases are marked by [Adaptive Server Anywhere] or [Adaptive Server Enterprise] at the beginning of the appropriate section.

Type Symbol Syntax ConventionKeywords and tags

SCRIPT SQL keywords and HTML tags are shown in uppercase.

Placeholders name Items that the user must replace with appropriate identifiers or expressions are shown in italics.

Options | Options are separated by vertical bars. Any one of the items is allowed.

Continuation ... Lines beginning with ... are a continuation of the statements from the previous line.

Lists ",..." Lists are shown with a list element followed by ",...". This means that one or more list elements are allowed and if more than one is specified, they must be separated by commas.

Optional portions

[ ] Optional portions of a statement are enclosed in square brackets. For example, FORMATTING [ MAXROWS = num ] indicates that the MAXROWS = num is optional. Alternative optional parts of a statement are sometimes listed within the brackets separated by vertical bars. For example, [ ASC | DESC ] indicates that ASC or DESC are optional. Do not type bracket.

Alternatives { } When one of the options must be chosen, the alternatives are enclosed in curly braces. For example [ QUOTES { ON | OFF } ] indicates that if the QUOTES option is chosen, one of ON or OFF must be provided. Do not type the braces.

xviii

Page 19: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

About this book

xix

Page 20: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

About this book

xx

Page 21: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

e

C H A P T E 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 thPowerDynamo User’s Guide.

Contents

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.

Topic Page

Overview 1

Dynamo tags versus DynaScript 3

The Dynamo tags 4

Dynamo Tag Syntax

COMPONENT <!--COMPONENT-->

DATA <!--DATA-->

DOCUMENT <!--DOCUMENT-->

ELSE <!--ELSE-->

ELSEIF <!--ELSEIF-->

ENDIF <!--ENDIF-->

EVALUATE <!--EVALUATE-->

1

Page 22: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Overview

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.

EXECUTE <!--EXECUTE-->

FORMATTING <!--FORMATTING--><!--/FORMATTING-->

IF <!--IF-->

INCLUDE <!--INCLUDE-->

LABEL <!--LABEL-->

MAILPEICE <!--MAILPIECE-->...body of mail piece<!--/MAILPIECE-->

SCRIPT <!--SCRIPT...DynaScript code-->

SQL <!--SQL...SQL query-->

SQL_ERROR_CODE <!--SQL_ERROR_CODE-->

SQL_ERROR_INFO <!--SQL_ERROR_INFO-->

SQL_INSERT <!--SQL_INSERT-->

SQL_ON_ERROR <!--SQL_ON_ERROR--><!--/SQL_ON_ERROR-->

SQL_ON_NO_ERROR <!--SQL_ON_NO_ERROR--><!--/SQL_ON_NO_ERROR-->

SQL_ON_ROWS <!--SQL_ON_ROWS--><!--/SQL_ON_ROWS-->

SQL_ON_NO_ROWS <!--SQL_ON_NO_ROWS--><!--/SQL_ON_NO_ROWS-->

SQL_STATE <!--SQL_STATE-->

Dynamo Tag Syntax

2

Page 23: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 1 Dynamo Tags

Server sideDynamo tags are processed by the server as opposed to HTML tags which are processed by the browser.

Dynamo tags versus DynaScriptThe Dynamo tags described in this chapter provide the functionality that is normally associated with a programming language such as JavaScript or DynaScript. If you are more comfortable with HTML and do not require the flexibility of DynaScript, you can use the Dynamo tags to manipulate your Web site documents. The following table displays the Dynamo tags with their DynaScript equivalent.

Dynamo tag DynaScript equivalent

COMPONENT connection/CreateComponent

DATA query/GetValue()

DOCUMENT Select properties of the document object

ELSE else

ELSEIF if-else

ENDIF }

EVALUATE N/A

EXECUTE system.Exec()

FORMATTING N/A

IF if

INCLUDE output=site.Include(scriptName);document.WriteLn(output);

LABEL query/GetColumnLabel()

MAILPIECE mp = new MailPiece();

SCRIPT N/A

SQL connection/CreateQuery()

SQL_ERROR_CODE query/GetErrorCode()

SQL_ERROR_INFO query/GetErrorInfo()

SQL_INSERT N/A

SQL_ON_ERROR if (SQL.GetErrorCode()!=0) {...

SQL_ON_NO_ERROR if (SQL.GetErrorCode()==0) {...

3

Page 24: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The Dynamo tags

on

nts.

For complete information on DynaScript, see “The DynaScript Language”page 33.

The Dynamo tagsThis section lists the function, syntax, attributes, and examples for each Dynamo tag.

COMPONENT Function Use the COMPONENT tag to embed Jaguar components in HTML docume

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)

-->

SQL_ON_ROWS if (!SQL.GetEmpty()) {...

SQL_ON_NO_ROWS if (SQL.GetEmpty()) {...

SQL_STATE document.Write(SQL.GetState());

Dynamo tag DynaScript equivalent

4

Page 25: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 1 Dynamo Tags

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

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.

HOST The host and port name to use for the componentHOST=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.

5

Page 26: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The Dynamo tags

$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-->

</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

6

Page 27: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 1 Dynamo Tags

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 ) {if( type == -1 ) { //LONGVARCHAR return query.getString( index );} else if( type == -2 ) { //BINARY return query.getBytes( index );} else if( type == -3 ) { //VARBINARY return query.getBytes( index );} else if( type == -4 ) { //LONGVARBINARY return query.getBytes( index );} else if( type == -5 ) { //BIGINT return query.getLong( index );} else if( type == -6 ) { //TINYINT return query.getShort( index );} else if( type == -7 ) { //BIT return query.getBytes();}

} else {return query.getBytes( index );

} } document.writeln( "<H3>Testing SVUEnrollment getmajors</H3>" ); //The result of the tag is stored in the variable //COMPONENT prequery = COMPONENT; //The RecordSet returned needs to fixed using a //static method call query = java.CallStaticMethod( "com.sybase.CORBA.jdbc11.SQL","getResultSet",prequery ); received = query.next(); i = 0; while( received ) { metadata = query.getMetaData(); for( j = 1; j <= 3; j++ ) { value = GetValue( query, metadata, j );

7

Page 28: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The Dynamo tags

document.writeln( value ); }received = query.next();i++; }-->

See also “CreateComponent method” on page 215

“Calling Jaguar Component Methods from PowerDynamo” in the PowerDynamo User’s Guide.

DATA Function The DATA tag allows an undetermined number of rows to be returned from a

query.

Syntax <!--DATA [ QUERY=queryname ] [ NAME=colname ] -->

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-->

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-->

8

Page 29: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 1 Dynamo Tags

t, rected ould

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><TD><!--DATA--></TD><TD><!--DATA--></TD></TR><!--/FORMATTING--></TABLE></BODY></HTML>

See also “FORMATTING” on page 13.

“LABEL” on page 20.

DOCUMENT Function The DOCUMENT tag allows you to set certain properties of the documen

such as the content type, status, whether or not the request should be redito an alternate URL, and the duration of time, if any, the request output shbe cached.

Syntax <!--DOCUMENT [ CONTENT_TYPE = type ]

... [ REDIRECT = URL ]

... [ STATUS = statusCode ]

... [ CACHED_OUTPUT_TIMEOUT = minutes ] -->

9

Page 30: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The 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.phoneFROM 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>

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_TIMEOUT

Duration of time (in minutes) for which the generated output of a script or template will be cached. This attribute is optional. The default is 0.

10

Page 31: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 1 Dynamo Tags

in d

the

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 participatethis promotion” displays. If the condition is false, the ELSE tag is used andisplays “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>

ELSEIF Function The ELSEIF tag can be used after an IF tag to check another condition if

first condition associated with the IF tag was false.

Syntax <!--ELSEIF EXPR = expression -->

Example An example of the ELSEIF tag is as follows:

<HTML><!--SCRIPT var num=22;--><!--IF EXPR="num > 5" --> <!--IF EXPR="num > 10" --> num is greater than 10 <!--ELSEIF EXPR="num < 10"-->

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.

11

Page 32: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The Dynamo tags

num is greater than 5 and less than 10 <!--ELSE--> num is 10 <!--ENDIF--><!--ENDIF--></HTML>

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;--><!--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 -->

Example An example of the EVALUATE tag is as follows:

<!--EVALUATE EXPR="j + 1" -->

Attribute Description

EXPR The expression to be evaluated. This attribute is required.

12

Page 33: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 1 Dynamo Tags

dollars.

If j is equal to 5, the above example would have an output of:

6 dollars

EXECUTE Function The EXECUTE tag allows you to execute a system command.

Syntax <!--EXECUTE COMMAND = commandname -->

Examples This example launches notepad.exe:

<!--EXECUTE command = "notepad.exe"-->

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][COLUMN_TAG=columntagname][USE_CDATA ] [ MAXROWS = num ] [ NAME = stmtname ] [STARTROW = rownum ] [STRIP_TRAILING_BLANKS]] -->

<!--/FORMATTING -->

Attribute Description

COMMAND The name of the command to be executed. This attribute is required.

<!--EXECUTE COMMAND="mycommand"-->

13

Page 34: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The Dynamo tags

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.

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><!--SQLSELECT customer.fname, customer.lnameFROM 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.

14

Page 35: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 1 Dynamo Tags

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-->

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

Attribute Description

15

Page 36: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The Dynamo tags

s e ad,

on

tags.

e

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.

Formatting using scriptsYou can also use embedded scripts to format output. The flexibility of scripts allows more varied formatting than the formatting tags.

For more information, see “The DynaScript Language” on page 33.

The HTML tags for formatting instructions are slightly different from the tagused for SQL statements. To allow an HTML editor to modify and refine thactual formatting, the formatting description is not inside a comment. Instecomment tags are used for placeholders for the data, which are replacedprocessing by the actual data.

All data placeholders must be between formatting start and end comment The start tag is:

<!--FORMATTING-->

The end tag is:

<!--/FORMATTING-->

There is no restriction on the HTML code that can be included between thtags. 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>

STRIP_TRAILING_BLANKS

Strips trailing blanks from query data. By default, 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.

Attribute Description

16

Page 37: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 1 Dynamo Tags

<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.

<!--SQLselect code from productlist--><!--FORMATTING MAXROWS=3-->Product code: <!--DATA--><!--/FORMATTING -->

has the output of:

Product code: 111Product code: 222Product code: 333

You can nest the FORMATTING tag inside other FORMATTING tags. For example, this fragment:

<!--FORMATTING NAME=Query1--> <!--FORMATTING NAME=Query2--> <!--DATA QUERY=Query1--><!--DATA--> <!--/FORMATTING--><!--/FORMATTING-->

Would have an output similar to:

Fred26Fred32Fred27Fred34Jane26Jane32Jane27Jane34

If you do not specify a QUERY attribute on the DATA tag, the query specified on the innermost <!--FORMATTING--> block is assumed.

Using nested FORMATTING statements on databases that do not support backward cursor movement causes a performance degradation. Sybase strongly recommends that you not nest FORMATTING sections unless absolutely necessary.

17

Page 38: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The Dynamo tags

You may also reference a query that is outside of the formatting block. For example:

<!--formatting NAME=Query1--> <!--data QUERY=Query3 NAME=title--><!--DATA--><!--/formatting-->

This example uses the FORMAT_AS=XML tag to create the output in XML.

<!--SQL select product.description, product.color from product order by product.description --> <!--FORMATTING FORMAT_AS="XML" 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>CottonShorts</MYDESCRIPTION><MYCOLOR>Black</MYCOLOR></MYROW> <MYROW><MYDESCRIPTION>Crew Neck</MYDESCRIPTION><MYCOLOR>Black</MYCOLOR></MYROW> <MYROW><MYDESCRIPTION>HoodedSweatshirt</MYDESCRIPTION><MYCOLOR>Green</MYCOLOR></MYROW> <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>ZippedSweatshirt</MYDESCRIPTION><MYCOLOR>Blue</MYCOLOR></MYROW> </MYRESULTSET>

See also “DATA” on page 8.

18

Page 39: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 1 Dynamo Tags

d

is ate sed

nt.

“LABEL” on page 20.

IF Function The ID tag allows for manipulation of script flow. If the condition associate

with the tag is true the text associated with the IF tag will be executed.

Syntax <!--IF EXPR=expression -->

<!--ENDIF -->

Example This example uses the IF tag to check if a condition (YearOfBirth < 1979)true or false. If the condition is true the text “You are old enough to participin this promotion” displays. If the condition is false, the else statement is uand 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 docume

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 73.

Syntax <!--INCLUDE NAME = filename -->

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.

19

Page 40: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The Dynamo tags

Example • This template:

<HTML><TITLE>sample.stm</TITLE><BODY><H1>Book Stores</H1><P>The following book stores are owned by the Read Smart Corporation</P><!--INCLUDE name="stores.stm"--><P>For detailed information on individual book stores, dial the store directly. If youhave a question about the corporation, dial Read Smart’s 1-800 number. </P></BODY></HTML>

displays this output, when executed:

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 ] -->

Argument Description

NAME Name of the document that is to have its output included in the output of the current document.

20

Page 41: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 1 Dynamo Tags

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:

<!--SQL select name, color, size from product-->

<!--FORMATTING--><!--LABEL-->: <!--DATA--><!--LABEL-->: <!--DATA--><!--LABEL-->: <!--DATA--><!--/FORMATTING-->

produce the following output:

name: Tee Shirtcolor: Whitesize: Small

name: Tee Shirtcolor: Orangesize: Medium

name: Tee Shirtcolor: Blacksize: One size fits all

See also “FORMATTING” on page 13

“DATA” on page 8

MAILPIECE Function Use the MAILPIECE tag to send mail through a SMTP host.

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.

21

Page 42: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The Dynamo tags

Syntax <!--MAILPIECE TO = recipientAddress [ FROM = fromAddress ] [ SUBJECT = subject ] [ SMTPHOST = SMTPAddress ] -->

Body of the mail piece

<!--/MAILPIECE -->

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="[email protected]" FROM="[email protected]" 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

-->

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.

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.

22

Page 43: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 1 Dynamo Tags

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><!--SCRIPTdocument.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.

23

Page 44: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The Dynamo tags

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.

CONNECTION_OBJECT Name of the DynaScript connection object that the SQL query is to use. This attribute is optional:

<!--SQL CONNECTION_OBJECT=connObjselect * 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=sqlselect * from product

-->

Attribute Description

24

Page 45: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 1 Dynamo Tags

Only one connectionYou can use only one of: CONNECTION_NAME, CONNECTION_OBJECT, DSN, or SERVER.

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><!--SQLSELECT Book.Title, Book.BookID, Book.PriceFROM DBA.Book Book --></BODY></HTML>

SQL_INSERT Function Performs an insert operation using the document’s parameters.

SERVER, DBN*, UID, PWD

The server name on which the SQL query should be 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=sqlselect * 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.

Attribute Description

25

Page 46: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The Dynamo tags

.

y

:

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.

CONNECTION_NAME Name of the connection that the SQL query is to useThis 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 youwould like a SQL insert to use. For example:

<!--SQL_INSERT CONNECTION_NAME="MyConnection" TABLE="product" -->

You can find a list of PowerDynamo connection in theConnections 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 querto use. Using a data source name to connect to a database bypasses both connections and connectionobjects. 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"-->

26

Page 47: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 1 Dynamo Tags

ave If the the

Only one connectionYou can use only one of: CONNECTION_NAME, CONNECTION_OBJECT, DSN, or SERVER.

Description Use SQL_INSERT to enter data into a table. For example, lets’s say you hcreated a form that asks a user to enter the information to add to the table.names on the form match the names of the table columns, you can insertinformation 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>

SERVER, DBN*, UID, PWD

The server name on which the SQL query should be 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.

NO_EXECUTE Allows you to prepare a SQL query without executing it.

<!--SQL_INSERT NAME=myQuery NO_EXECUTETABLE="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.

Attribute Description

27

Page 48: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The Dynamo tags

<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><LI><INPUT TYPE="text" NAME="unit_price" > Price<BR></OL><P><INPUT TYPE="submit"></p><P><INPUT TYPE="RESET" VALUE="Clear Form"></P></FORM></BODY></HTML>

calls:

<HTML><TITLE>insert.ssc</TITLE><BODY><H1>DynaScript Sample</H1><!--SQL_INSERT TABLE="product" --></BODY></HTML>

The above example would be equivalent to:

<!--SQLinsert into product ( id, name, description, size, color, quantity, unit_price )values ( 999, ’dog’, ’furry’, ’dog_sized’, ’brown’, 1, 123 )-->

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 -->

28

Page 49: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 1 Dynamo Tags

Parameters type:

NO_ERROR | ERROR | NO_ROWS | ROWS

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.

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.

<!--SQLselect 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.

Attribute Description

NAME Name of a query. This attribute is optional. If you do not provide a query name, “SQL” is assumed.

Start tag End tag Condition

<!--SQL_ON_NO_ERROR--> <!--/SQL_ON_NO_ERROR-->

Query did not produce an error.

<!--SQL_ON_ERROR--> <!--/SQL_ON_ERROR--> Query produced an error.

<!--SQL_ON_NO_ROWS--> <!--/SQL_ON_NO_ROWS--> Result set did not produce any rows.

<!--SQL_ON_ROWS--> <!--/SQL_ON_ROWS--> Result set produced at least one row.

29

Page 50: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The Dynamo tags

Syntax <!--SQL_ERROR_CODE [ NAME = queryname ] -->

Example This example returns 0 as well as the output generated from the SQL query as long as no errors are encountered during execution.

<!--SQLSELECT Stock."Quantity", Stock."BookID"FROM "DBA"."Stock" Stock --> <!--SQL_ERROR_CODE--><TABLE BORDER><TR><TH>Quantity</TH><TH>BookID</TH></TR><!--formatting--><TR><TD><!--DATA--></TD><TD><!--DATA--></TD></TR><!--/formatting--></TABLE></BODY></HTML>

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 ] -->

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()) {

Attribute Description

NAME Name of a query. This attribute is optional. If you do not provide a query name, “SQL” is assumed.

Attribute Description

NAME Name of a query. This attribute is optional. If you do not provide a query name, “SQL” is assumed.

30

Page 51: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 1 Dynamo Tags

document.WriteLn(myQuery.GetValue(1) + "," + myQuery.GetValue(2)); } myQuery.MoveFirst();-->

SQL_STATE Function The SQL_STATE tag returns the current SQL state of a query.

Syntax <!--SQL_STATE [ NAME = queryname ] -->

Example This example displays the state of the SQL query:

<!--SQL select lname, fname from customer--><!--SQL_STATE--><!--SCRIPT while (SQL.MoveNext()){ document.WriteLn(SQL.GetValue(1) + "," + SQL.GetValue(2)); }-->

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"-->

31

Page 52: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The Dynamo tags

32

Page 53: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

C H A P T E 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

OverviewDynaScripts are built from the following language elements:

• SCRIPT tag

• literals

• variables

• expressions

• operators

• statements

• functions

Topic Page

Overview 33

SCRIPT tag 34

Literals 34

Variables 36

Expressions 38

Operators 39

Statements 43

Functions 56

Objects 66

33

Page 54: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

SCRIPT tag

that rver

• objects

Each of these elements is described in the following sections.

SCRIPT tagDynaScripts are embedded in documents as HTML comments. An HTMLcomment 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 contentsfall between the start and end tags. This allows the Dynamo application seto process the script.

JavaScript tags vs. Dynamo tags

JavaScript SCRIPT tags are very similar to DynaScript SCRIPT tags. JavaScript uses SCRIPT tags with this syntax:

<SCRIPT LANGUAGE="JavaScript">

DynaScript uses SCRIPT tags with this syntax:

<!--SCRIPT -->

LiteralsLiterals 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)

34

Page 55: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

a-

tes. iven

IntegersIntegers 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 orf), with a leading 0x (or 0X).

Example: 0x3F

Floating-point numbersA 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

BooleansThe Boolean (logical) type can be true or false.

StringsA string is zero or more characters enclosed in single (') or double (") quoYou must use the same kind of quote (single or double) to start and end a gstring.

35

Page 56: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Variables

(an

cape

;

start

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 backslashescape 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 escharacter, one as the literal backslash).

VariablesYou do not have to declare DynaScript variables or assign them to a fixeddatatype. A variable must have a value before you use it in an expressionotherwise a runtime warning is generated.

Variable names Each variable is identified by a case-sensitive name. Variable names mustwith 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:

36

Page 57: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

e

ed.

x_magiccurrent_productProduct99

These are invalid variable names:

x 13magiccurrent!productProduct-99R&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 43.

Datatypes Scripts use the following datatypes:

Table 2-1: Datatypes

For more information on the operators that work with these datatypes, se“Operators” on page 39.

Assigning values to variables

Assign a value to a variable using the = operator, just as in many other programming languages. In DynaScripts, however, assigning a value to avariable 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 creat

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

37

Page 58: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Expressions

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.

ExpressionsExpressions 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 datatypes

Every expression has a value and a datatype. The datatype is one of numeric, string, Boolean, function, object, or null.

38

Page 59: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

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".

To make meaningful evaluation of expressions possible, DynaScript has rules for automatic conversion of datatypes. In the above example, 10 is converted to a string and concatenated with the other string to give the final value.

Operators and datatypes

An operator can act on expressions of certain datatypes. For example, the multiplication operator (*) can act on numeric expressions, but cannot act on string expressions:

// valid use of multiplication( 2 * 3.14159 * radius )// invalid use of multiplication"What" * "happens now?"

Some operators can act on more than one datatype. The most common of these is the addition operator (+). The addition operator can add two numbers together, or concatenate two strings.

Ternary, binary and unary operators

Operators are either ternary, binary, or unary. Binary operators act on two operands, such as the arithmetic operators:

x + y45 / 56

Unary operators act on only one expression. For example, the postfix ++ operator adds one to the value of a variable:

x++ ;

The less common ternary operators act on three expressions.

OperatorsThis section describes the operators available in scripts.

Ternary, binary and unary operators

Operators act on one or more expressions called operands. Operators can be 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:

39

Page 60: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Operators

a

after

d the

x + y ;

The increment operator (which adds one to a number) is a unary operator, so the following is a valid expression:

x++ ;

Arithmetic operatorsThe following arithmetic operators are provided:

Notes • Comparison operators can also operate on numbers, but the result isBoolean value.

• The increment and decrement operators can be used either before orthe operand: both of the following are valid statements:

x++++x

When the operator precedes the operand, the operand is decrementebefore the expression is evaluated; if the operator follows the operand,operand is decremented after the expression is evaluated. The followingstatements illustrate the difference:

x = 56 ;y = x-- ; // Sets y to 56 and decrements x to 55y = --x ; // Decrements x to 55 and sets y to 55

Conditional operatorThe following conditional operator is provided:

Operator Description Binary or unary

+ addition binary

- subtraction binary

* multiplication binary

/ division binary

% modulo binary

++ increment unary

-- decrement unary

- negation unary

40

Page 61: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

The ? operator is ternary, meaning that it acts on three expressions.

The ? operator evaluates to one of two values, based on a condition. An example of the ? operator is as follows:

(grade == "pass") ? "Excellent" : "Try again";

String operatorsThe following string operators are provided:

Comparison operators can also operate on strings, but the result is a Boolean value.

Comparison operatorsThe following comparison operators are provided:

These operators can act on numbers or strings, and return a Boolean (logical) value of true or false.

Operator Description

? Conditional

Operator Description

+ Concatenation

+= Concatenation with assignment

Operator Description

= = Equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

<> Not equal to

!= Not equal to

41

Page 62: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Operators

Boolean operatorsBoolean operators operate on Boolean (logical) expressions. The following Boolean operators are provided:

Bitwise operatorsBitwise 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:

Delete operatorThe delete operator may be used to delete a property from an object or to delete an element from an array. For example

delete x

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.

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-propagating Right shift

Shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left.

>>> Zero-fill right shift

Shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left.

42

Page 63: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

Returns true if deletion is successful, false otherwise.

Void operatorThe 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 operatorThe 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.

StatementsDynaScript 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

• break and continue

• object-manipulation statements

• for-in

• with

43

Page 64: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Statements

ns.

ents e.

ed

• class, this, and new

• miscellaneous statements

• var

• function, return

• import

• comments

• exit

Separating statements In DynamoScripts, you do not have to separate statements with semicolo

if-else statementThe if-else statement tests a condition, then executes one set of statemif the condition is true, and (optionally) another set of statements if it's fals

Syntax if ( condition ) {

statements }

[ else {

statements } ]

• condition Any Boolean expression.

• statements Any script statements. Multiple statements must be enclosin braces.

Example if ( status == true ) {document.WriteLn( "Your order succeeded.") ;document.WriteLn( "Now in stock: " + quantity) ;

} else {document.WriteLn( "Your order failed.") ;document.WriteLn( "We only have " + quantity

+ " in stock.") ;}

for statementThe for statement iterates over values in a loop while a condition is true.

Syntax for ( [ initial-expression ]; [ condition ]; [ increment expression ] ) {

statements } ;

44

Page 65: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

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 statementThe 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 } ;

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 statementThe 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 ) ;

45

Page 66: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Statements

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 ) ;

switch statementThe 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 function countVowels( phrase ) { var cntA=0, cntE=0, cntI=0, cntO=0, cntU=0, cntOther=0; var index; var character; var length = phrase.length; for( index = 0; index < length; index++ ) { character = phrase.charAt( index ); switch( character ) { case ’A’: case ’a’: cntA++; break; case ’E’: case ’e’: cntE++;

46

Page 67: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

break; case ’I’: case ’i’: cntI++; break; case ’O’: case ’o’: cntO++; break; case ’U’: case ’u’: cntU++; break; default: if( character >= ’a’ && character <= ’z’ || character >= ’A’ && character <= ’Z’ ) { cntOther++; } } } document.WriteLn("There are " + cntA + " occurrences of the letter A" ); document.WriteLn("There are " + cntE + " occurrences of the letter E" ); document.WriteLn("There are " + cntI + " occurrences of the letter I" ); document.WriteLn("There are " + cntO + " occurrences of the letter O" ); document.WriteLn("There are " + cntU + " occurrences of the letter U" ); document.WriteLn("There are " + cntOther + " consonants" ); } /* mainline */ countVowels( "Happy Birthday!" );

-->

47

Page 68: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Statements

break statementThe 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 ) ;

continue statementThe 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 statementThe 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 }

48

Page 69: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

ed

ing

a the

to be

ed

• variable A variable to be used as the loop iterator.

• object Any object.

• statements Any script statements. Multiple statements must be enclosin braces.

Example You can list the properties, property values, and methods of any object usthe following simple script, where objectName is the name of the particular object:

<!--SCRIPTfor ( i in objectName ) {document.WriteLn( i + " = " + objectName[i] ) ;}-->

with statementUse the with statement for working with several properties or methods of given object. It establishes a default object for a block of statements. Withinblock, any property or methods that do not specify an object are assumedfor the default object.

Syntax with ( object ) {

statements }

• object Any object.

• statements Any script statements. Multiple statements must be enclosin 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" ;}

49

Page 70: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Statements

eter

w

se

.

nts

new

rrides

it

class statementThe 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 assigningvalues to properties). If you're extending an existing class, the paramlist 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 neclass is derived from.

• parentParam [variable] Parameters for the parent class. Typically theare a subset of the param list. The parent constructor is executed using these parameters before the constructor of the new class is executed

• statements Constructor statements for the new class. These statemetypically:

• Assign the new parameters to the properties you've added to the class, using the this keyword to reference the new class. For example:

this.name = incomingName ;

• Define methods for the new class. If you define a method with thesame name as a method in the parent class, the new method ovethe parent method.

You can define methods inline (inside the class definition), or by assigning method names to existing functions (outside the class definition). Inline method declaration is preferable, however, sinceencapsulates the method within the class and allows methods in different classes to have the same name (making polymorphism possible).

Example class salariedEmployee(name, title, managerName, salary) extends employee(name, title, managerName) {

this.salary = salary;function PrintAllInfo() {

50

Page 71: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

rs.

ter.

document.WriteLn("Name: " + this.name);document.WriteLn("Title: " + this.title);document.WriteLn("Reports to: " +

this.managerName);document.WriteLn("Salary: " + this.salary);

}this.PrintAllInfo = PrintAllInfo;

}

this keywordThe 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 ;this.size = size ;this.color = color ;this.quantity = quantity ;this.price = price ;}

new operatorThe new operator creates an instance of a class using the given paramete

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 parame

Example var currentProduct = new product(600,"Sweatshirt", "Large", "Green", 39, 24.00 ) ;

51

Page 72: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Statements

ns sed

o the are

ored ird

var statementThe 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 ;

function statementThe function statement declares a function, which is a set of instructions thatyou 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 functioby value. Any change made to the argument inside the function is not pasback 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 tcalling environment. Since arrays are a special case of objects, they passed by reference.

• When the function is called, the actual parameters (arguments) are stin the arguments array property of the function. This array indexes allactual parameters starting at 0. For example, you could access the thparameter of a function called MyFunction as MyFunction.arguments[2].

You can access the total number of actual parameters as arguments.length.

52

Page 73: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

ller

Variable number of arguments

Functions can accept more or less parameters than are formally declared for 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 lowif ( this.quantity >= orderQuantity ) {

this.quantity -= orderQuantity ;return ( true ) ;

} else {return ( false ) ;

}}

return statementThe return statement is used inside a function to return a value to the caof 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 lowif ( this.quantity >= orderQuantity ) {

this.quantity -= orderQuantity ;return ( true ) ;

} else {return ( false ) ;

}}

...then call the function in an expression:

53

Page 74: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Statements

r

ss

t:

if ( OrderItem(desiredQuantity) == true ) {document.WriteLn("Ordered successfully");} else {document.WriteLn("Order failed - stock is low");}

import statementThe 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.

Syntax import documentName | (stringExpression) [newContext | useContext] ;

• documentName [string] The script file to include. This can be quoted ounquoted.

• stringExpression [expression] The script file to include. This allows youto build file names programmatically.

• newContext [keyword] Specifies that the current context (variables orobjects) is not to be shared with the imported file.

• useContext [keyword] Specifies that the imported file is to have acceto the current context.

Example If you stored a set of common functions in a script called common.ssc, you could use these functions in another document by including the statemen

import "common.ssc" ;

To import a script called myScript.ssc, residing in a test folder at the root of your Web site, you could use the statements:

rootDoc = site.GetRootDocument();import (rootDoc.location + "/test/myScript.ssc");

54

Page 75: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

:

The following example demonstrates the sharing of variables between a main file and the file that it imports:

<!--SCRIPT main.ssc document.writeln( "Start main.ssc" ); var foo = "This is from main.ssc"; import "importee.ssc" useContext; document.writeln( narf ); document.writeln( "End main.ssc" );-->

<!--SCRIPT importee.ssc document.writeln( "Start importee.ssc" ); var narf = "This is from importee.ssc"; document.writeln( foo ); document.writeln( "End importee.ssc" );-->

Executing main.ssc produces:

Start main.sscStart importee.sscThis is from main.sscEnd importee.sscThis is from importee.sscEnd main.ssc

comment statementsComment 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 commentthat extendsover 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 ;

55

Page 76: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Functions

exit statementThe 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><!--SCRIPTif( document.value.password != "halibut" ) {

document.writeln( "<H2>Invalid password!</H2></BODY></HTML>" );

exit;}--><H1>Secret Information</H1><!--SQLselect color from product--><!--formatting--><!--/formatting--></BODY></HTML>

FunctionsYou 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 ) );-->

56

Page 77: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

s sed

o the are

e

sion:

, y any

ion.

Define functions before using themYou must define a function before it can be used, since the application server

processes an HTML document from top to bottom.

A function can accept string, number, or object parameters.

• Simple variables such as strings and numbers are passed to functionby value. Any change made to the argument inside the function is not pasback 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 tcalling environment. Since arrays are a special case of objects, they passed by reference.

Parentheses must be usedYou must use parentheses when calling a function, even if it doesn’t tak

away arguments.

A function can perform a set of statements without returning a value. For example:

PrintInvoices();

A function can also return a value to the caller by including a return statement. In this case, the function is typically called as part of an expres

nextCustomerName = GetCustomerName(customerNum);

You can define functions inside a particular document. For more flexibilityyou can define them in a separate script, which can then be referenced bdocuments that use the function (using the import statement).

For more information on the function, return, and import statements, see “Statements” on page 43.

Functions and the arguments objectThe arguments object may be used with a function to return an array thatcontains the arguments that were passed to the currently executing functFor Example:

<!--SCRIPT

57

Page 78: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Functions

his

function addVar( x, y, z ) { document.writeln( addVar.arguments[0] ); document.writeln( arguments ); return x + y + z; } 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) );-->

Built-in functionsDynamo supports the following ECMAScript built-in functions:

• escape(string) Returns a string containing the ISO Latin-1 representation of each character in string. This is typically used to encodespecial characters so they can be used in URLs.

• eval(string) If string represents an expression, this evaluates the expression. If the argument is one or more ECMAScript statements, tperforms the statements.

58

Page 79: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

r m

ct to ram

le

a es

rsion

• isFinite(number) Returns a Boolean indicating whether the supplied number is finite.

• isNaN(number) Returns a Boolean indicating whether the supplied number is the reserved value NaN (not a number).

• parseFloat(string) Parses string and tries to return a floating-point number.

• parseInt(string [, radix]) Parses string and tries to return an integer of the specified radix (base).

• unescape(string) Returns a string containing the ASCII characters fothe encoded string. This is typically used to decode special characters froURLs.

Dynamo-specific built-in functionsDynamo provides the following built-in functions:

• CreateObject(string) Creates an instance of an ActiveX Object. string represents the program ID of the object being called. Use CreateObjeaccess data that is available through a third-party application. The progID is available from your Registry under HKEY_CLASSES_ROOT. If a program ID is not listed in your Registry, the application is not availabfor use.

Only available from Windows or NTCreateObject is available only on Windows 95 or NT platforms, andcan be used only with nonvisual ActiveX objects.

The following example creates an instance of an ActiveX Object fromVisual Basic application. The object is used for converting temperaturfrom Celsius to Fahrenheit or from Fahrenheit to Celsius.

The template prompts the user to select the appropriate type of conveand to enter a value.

59

Page 80: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Functions

<HTML><H1>Converting Temperatures </H1><BODY>

<P>This page allows you to convert a temperature from <I>Celsius</I> to<I>Fahrenheit</I> or from <I>Fahrenheit</I> to <I>Celsius</I>.<BR><HR WIDTH="100%">

<P>Select the appropriate button and enter the temperature you would liketo convert.

<FORM METHOD=POST ACTION="convert.stm"><OL><LI><INPUT TYPE="radio" NAME="theType" value="CtoF" CHECKED>Celsius to Fahrenheit<BR><INPUT TYPE="radio" NAME="theType" value="FtoC">Fahrenheit to Celsius<BR><LI><INPUT TYPE="text" NAME="temperature" SIZE="4"> Temperature</OL><P><INPUT TYPE="submit"></p><P><INPUT TYPE="RESET" VALUE="Clear Form"></P></FORM>

</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 =

60

Page 81: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

out

e are :

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>

• exists(variables) Checks if a variable has been assigned a value withcreating an instance of that variable.

if( exists( session.logon ))...

• formatString(string) Substitutes a parameter into a format string. Thformat string should contain a “%1”, “%2”, etc. where the parameters to be substituted. Up to nine parameters are supported. For example

Document.writeln( formatString("%1 students have %2 the exam", 32, "passed"));

Produces the output:

32 students have passed the exam

To have a percent sign in the format string, use “%%”.

61

Page 82: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Functions

ophe e

ent. be

base

st s:

ter)

• sqlEscape(string [,Boolean]) Prepares a string for use as a SQL statement. This is typically used to encode special characters (apostrand backslash for Adaptive Server Anywhere; apostrophe for AdaptivServer Enterprise) so they can be used as string literals in a SQL statemsqlEscape takes two parameters. The first parameter is the string to processed, the second optional parameter is a Boolean that indicateswhether the backslash characters are to be escaped.

sqlEscape causes the special characters to be doubled up for the datato read them correctly when being passed. If the string \site\system\doc’s was being passed into a SQL statement againan Adaptive Server Anywhere database it could be prepared as follow

dir = sqlEscape( dir, true );

This would produce the string ’\\site\\system\\doc’’s’. Similarly, to prepare the dir string to be used against Adaptive Server Enterpriseyou would do something like:

dir = sqlEscape( dir, false );

This would produce the string ’\site\system\doc’’s’

• toDOMDocument(xmlString) Parses a document and returns an XMLDOM document. The DOM objects (see the Predefined Objects chapcan then be used to manipulate the document.

<!--SCRIPT xmlStr = ’<BOOK><TITLE>Guiness World Record Book</TITLE>&<CHAPTER pages="10">This is chapter 1</CHAPTER>&<CHAPTER pages="30">This is chapter 2</CHAPTER>&<CHAPTER pages="20">This is chapter 3</CHAPTER>&</BOOK>’ domDoc = toDOMDocument( xmlStr ); if( domDoc == null ) { document.writeln( site.GetErrorInfo() ); return; } document.writeln( domDoc.prettyPrint() ); -->

62

Page 83: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

s

s

ers

• toXMLString(object [, use_CDATA, index_tag]) Prepares a DynaScript object for XML representation. Nesting objects is permitted.

• object is the DynaScript object for which XML representation irequired.

• use_CDATA indicates that you want to use CDATA to escape special XML characters. If use_CDATA is false, characters will be encoded with the normal ampersand method. The default value ifalse.

• index_tag specifies a set of tags to use when unnamed membof an object are encountered.

This example uses toXMLString to display automobile service information:

<!--SCRIPTdocument.WriteLn("Car for Service")carObj = null;carObj.manufact = "Mazda";carObj.model = "MX6";carObj.year = "1998";carObj.color = "blue";carObj.owner.name = "Rick Smith";carObj.owner.address = "21 King St. Waterloo";carObj.work = "new brakes";information = toXMLString( carObj );document.WriteLn( information );-->

The output from the above example would look something like this:

Car for service<manufac>Mazda</manufac><model>MX6</model><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:

<!--SCRIPTdocument.WriteLn("Parts for order");part1.shop = "Jim & Son’s Autobody";part1.partname = "strut";part1.sku = "123";

63

Page 84: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Functions

nd

me

part2.shop = "Jim & Son’s Autobody";part2.partname = "clutch";part2.sku = "456";

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>

• typeof( ) The typeof() function takes a single object as an argument areturns a string that can be:

• “object”

• “string”

• “number”

• “Boolean”

• “binary”

• “function”

• “null”

The following example stores multiple document values of the same naas a DynaScript object. The typeof( ) function is used to determine what values have been received:

<!--SCRIPT SelectMultipleAction.ssc/* e.g. URL http://localhost/site/SelectMultipleAction.ssc?color=Red&color=Green&color=Blue */

64

Page 85: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

p;,

[

any

if( exists( document.value.color ) ) { if( typeof( document.value.color) == ’object’ ) { // multiple color values i = 0; while( exists( document.value.color[i] ) ) { document.writeln( document.value.color[i] ); i++; } } else { // single coloFur value document.writeln( document.value.color ); }} else { // no color selected document.writeln( ’no color was selected’ );}

-->

For more information about working with multiple selection lists, see “value property” on page 145.

• xmlEscape( string [,useCDATA] ) Prepares a string for use as XML.

If useCDATA is false, the characters &, <, and > are escaped as &am&lt; and &gt. For example:

document.writeln( xmlEscape( "<MyTag> Hello! </MyTag>" ) );

would produce:

&lt;MyTag&gt; Hello! &lt;/MyTag&gt;

If useCDATA is true, the string will be surrounded by the tags <![CDATAand ]]>. For example,

document.writeln( xmlEscape( "Tom & Jerry", true ) );

would produce:

"<![CDATA[Tom & Jerry]]>"

If there is not an <, >, or & in the string, xmlEscape does not encode characters.

65

Page 86: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Objects

at

).

of n

ask ript

f the

erties.

stor

ObjectsDynaScript is object-oriented, which means it supports objects and the fundamental object-oriented concepts of:

• encapsulation An object contains both properties and the methods thmanipulate 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 existing objects (by inheriting existing properties and methods and theadding 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 tof developing database-driven content. For more information, see “DynaScPredefined Objects” on page 75.

Properties and methodsAn object is a convenient way to collect a set of related information (properties) into one place, together with the actions (methods) that manipulate that information.

Case-sensitive namesThe names of object properties and methods are case-sensitive.

Properties A property is a variable in an object that describes some part or attribute oobject.

A property can be any datatype. Objects can contain other objects as prop

Property names must be unique within the scope of the class and its anceclasses (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";

66

Page 87: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

be thod

, its

or

mply ple:

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 mustunique within the scope of the class. If it has the same name as a mein one of its ancestor classes, it overrides (redefines) that method forinstances of its own class.

• If a method is defined as a global function (outside the class definition)name must be unique within the scope of the current script.

You can call an object method using standard dot notation:

objectName.MethodName()

Parentheses must be usedYou must use parentheses when calling a method, even if it takes no

arguments.

You can define objects as conventional arrays that use integer indexes. Fexample:

price[0] = 19.95price[1] = 42.99

You can also use text literals as indexes. In this case, the array notation sibecomes an alternative to the dot notation for object properties. For exam

sampleEmployee.name

can also be referenced as

sampleEmployee["name"]

67

Page 88: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Objects

s of

Restrictions on integer indexesNote that, for integer indexes, you cannot use the dot notation

interchangeably with the array notation because of property-naming rules. For example, you cannot reference price[2] as price.2, because 2 is not a valid identifier name (it does not start with a letter). Also, you cannot reference it as price["2"]. You must use the conventional array notation of price[2].

Object-oriented conceptsEncapsulation 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 extensionexisting classes.

The simplest form of inheritance is single inheritance, in which a new class can inherit properties and methods from a single parent class.

68

Page 89: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

lso

ad.

the

line od

name

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.

Defining base classesTo define a base class (one that does not inherit anything from existing classes), you can:

• Define a function that represents the class

• Use the class statement (a DynaScript extension)

The Dynamo class statement is a more flexible construct (since you can ause it for derived classes) but if you require compatibility with standard ECMAScript you may want to use the function-declaration technique inste

Using the function statement

To define a base class using the standard function-declaration technique,declare a function using the class name and the property names, assign property values, and define a method that references the function.

You can define methods inline (inside the class definition), or by assigningmethod names to existing global functions (outside the class definition). Inmethod declaration is preferable, however, since it encapsulates the methwithin the class and allows methods in different classes to have the same (making polymorphism possible).

The following example defines an employee class, with three properties (name, title, and managerName) and one method (PrintAllInfo) defined inline:

function PrintAllInfo() {document.WriteLn("Name: " + this.name);document.WriteLn("Title: " + this.title);document.WriteLn("Reports to: " +this.managerName);

function employee(name, title, managerName) {this.name = name;this.title = title;this.managerName = managerName;

}

69

Page 90: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Objects

d t

d a

this.PrintAllInfo = PrintAllInfo;}

For more information, see “function statement” on page 52.

Using the class statement

To define a base object using the class statement, declare the class name anthe property names, assign the property values, and define a method thareferences the function.

As in the function-declaration technique, you can define methods inline orassign 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 50.

Extending existing classes by inheritanceA derived class (also called a subclass) extends the definition of an existing class. It inherits the properties and methods of the parent class (also callesuperclass), and then adds (or redefines) its own additional properties andmethods.

To define a derived class, use the class statement as follows:

• Declare the class name and the property names (typically the new properties and the parent properties).

• Identify the parent class and pass it the parameters that it expects.

70

Page 91: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

ames

e

• Assign the property values of the new class.

• Define the methods of the new class as functions.

As for base classes, you can define methods inline or assign method nto existing global functions.

For more information, see “class statement” on page 50.

Example The following example defines an employee class, then derives a salariedEmployee subclass from it:

• The subclass inherits the name, title, and managerName properties and the PrintNameAndTitle method.

• The subclass adds one new property (salary) and one new method (PrintAllInfo) method that includes the new salary information in thoutput.

class employee(name, title, managerName) {this.name = name;this.title = title;this.managerName = managerName;function PrintNameAndTitle() {

document.WriteLn("Name, title: " + this.name+ ", " + this.title);

}this.PrintNameAndTitle = PrintNameAndTitle;}class salariedEmployee(name, title, managerName, salary)extends employee(name, title, managerName) {

this.salary = salary;function PrintAllInfo() {

document.WriteLn("Name: " + this.name);document.WriteLn("Title: " + this.title);document.WriteLn("Reports to: " +

this.managerName);document.WriteLn("Salary: " + this.salary);

}this.PrintAllInfo = PrintAllInfo;

}

71

Page 92: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Objects

and of

d

Creating instances of classesOnce you’ve defined an object class, you can start creating specific objects (instances) of that class. If, for example, you’ve defined a salariedEmployee class, you can then start creating records for salaried employees.

To create instances of a class, you assign a variable using the new operator with the name of the class and the property values for this new instance of the class. The usage is the same whether you used the standard function-declaration technique or the Dynamo class statement.

For more information, see “new operator” on page 51.

Example The following example creates salaryEmp as a new instance of the salariedEmployee class, and supplies it with appropriate values for the class properties (name, title, managerName, and salary).

var salaryEmp = new salariedEmployee("Ned Simpson", "Technical Writer", "Barney Burns", 80000);

Working with named and indexed membersNamed and indexed members are separate entities. For example, if X.a=1X.b=2, document.writeline X[0] would not equal 1 but would have a valueundefined. The following example further demonstrates this:

<!--SCRIPTX.a=1;X[1]=2;X.b=3;X[0]=4;for(i in X) {

document.writeln( X[i] );}-->

Would have this output:

1342

The for in statement iterates through named members first, then indexemembers.

72

Page 93: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 2 The DynaScript Language

and pen

ows

ack et tory

PathsYou 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 Productyour mapping to that Web site is named product_site and you wanted to othe 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 allthis 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 bone level. Each occurrence of ..\ in a directory path specifies that the targdirectory is back another level. If the number of occurrences of ..\ in a direcpath causes the directory to go back further than /Site, an error occurs.

WildcardsThere are two wildcard characters that you can use with site.DeleteDocument(docName) and document.GetDirectory([fileMask, sortOrder]): * and ?.

73

Page 94: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Objects

Use the * wildcard to represent any number of alphanumeric characters. For example, site.DeleteDocument("/Site/a*.stm") deletes all templates starting with the letter a from the root of the Web site.

Use the ? wildcard to represent a single alphanumeric character. For example, site.DeleteDocument("/Site/a?.stm") would delete template files that started with an a and had one more character in the file name such as aa.stm or ab.stm. The previous example would not delete the files acrobat.stm or a.stm.

74

Page 95: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

C H A P T E 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 76

attachment object 80

Boolean object 86

connection object 87

Date object 104

document object 126

DOMAttribute object 143

DOMCharacterData object 146

DOMComment object 150

DOMDocument object 151

DOMDocumentFragment object 157

DOMDocumentType object 158

DOMElement object 160

DOMEntity object 166

DOMEntityReference object 168

DOMImplementation object 169

DOMNamedNodeMap object 170

DOMNode object 173

DOMNodeList object 183

DOMNotation object 184

DOMProcessingInstruction object 185

The DOMText object 187

file object 188

FTP object 197

The Function object 210

java object 212

75

Page 96: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Array object

you lly.

Array objectObject 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 elementsexpect to use (or approximately), rather than growing the Array dynamica

Example • This example creates an array, fills it, then displays the contents:

mailList object 223

mailPiece object (incoming) 227

mailPiece object (outgoing) 238

Math object 252

Number object 261

Object object 265

recipient object 267

query object 269

session object 288

site object 291

String object 319

system object 323

Topic Page

76

Page 97: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

<!--SCRIPT myArray = new Array(4)myArray[0]= "number one";myArray[1]= "number two";myArray[2]= "number three";myArray[3]= "number four";document.WriteLn(myArray);-->

Array propertiesThe Array object has this property:

length propertySyntax Array.length

Description Returns a value one higher than the highest element in the array.

Return Integer.

Example • This example returns 7:

<!--SCRIPTmyArray = new Array();myArray[0] = "carrots";myArray[1] = "corn";myArray[6] = "green beans";document.WriteLn( myArray.length );-->

Array methodsThe Array object has these methods:

join methodSyntax Array.join( separator )

77

Page 98: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Array methods

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 methodSyntax 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());-->

sort methodSyntax Array.sort( [compareFunction] )

78

Page 99: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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 methodSyntax 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"; document.WriteLn( myArray.toString() );-->

79

Page 100: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

attachment object

attachment objectObject 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", "[email protected]"); 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 223

“mailPiece object (incoming)” on page 227

“mailPiece object (outgoing)” on page 238

“recipient object” on page 267

attachment propertiesThe attachment object has these properties:

80

Page 101: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

ent

om

as the

mimeType propertySyntax 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 attachmobject” and displays the attachment name and MIME type.

<!--SCRIPT mlist = new MailList ("mail.sybase.com", "elmo", "dynamo", "[email protected]"); 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 propertySyntax attachment.name

Attributes This property is read-only.

Description The name or description of the attachment, if present. This is extracted frMIME headers.

Return String.

Example This example uses the name property to save the file with the same name attached file.

<!--SCRIPT mlist = new MailList ("mail.sybase.com", "elmo", "dynamo", "[email protected]");

81

Page 102: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

attachment methods

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();-->

attachment methodsThe attachment object has these methods:

GetContents methodSyntax 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", "[email protected] ", "[email protected]"); mlistitem = mlist[6]; mlistitem.Retrieve(); attach = mlistitem.attachments[0]; contents = attach.GetContents(); if( attach.GetErrorCode() != 0 ) {

82

Page 103: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

document.WriteLn( "Error: " + attach.GetErrorInfo() ); } else { document.contentType = attach.mimeType; document.writeln( contents ); } mlist.Disconnect();

-->

See also “autoCommit property” on page 90.

“connected property” on page 90.

GetErrorCode methodSyntax attachment.GetErrorCode( )

Description Returns a code representing the last error that occurred.

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", "[email protected] "); 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();-->

83

Page 104: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

attachment methods

GetErrorInfo methodSyntax 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", "[email protected] "); 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();-->

SaveAsDocument methodSyntax 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", "[email protected]" ); mlistitem = mlist[12]; mlistitem.Retrieve();

84

Page 105: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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();-->

SaveAsFile methodSyntax 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", "[email protected]" ); 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 ); }

85

Page 106: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Boolean object

if (filesave) { document.WriteLn( "It should have worked" ); } document.writeln( mlistitem.attachments ); mlist.Disconnect();-->

Boolean objectObject 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 );-->

Boolean methodsThe Boolean object has these methods:

toString methodSyntax 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:

86

Page 107: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

a

s

the

with a

<!--SCRIPT myBool = new Boolean(true); document.WriteLn(myBool.toString() );-->

valueOf methodSyntax 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() );-->

connection objectObject 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 hostingDynamo Web site (for example, Adaptive Server Anywhere).

• User connections definitions A connection to a data source that providethe actual database content to the Web site.

When you create a Dynamo Web site, your Dynamo connection becomesdefault 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 script. For a detailed explanation of connections, see “Working with connections” in the PowerDynamo User’s Guide.

87

Page 108: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

connection object

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:

To create an ODBC connection:

X = new Connection ( name, description, datasource [,userName, password, ODBC, connectParameters] );

To create an Open Client connection:X = new Connection ( name, description, server, userName, password, Open Client [,database] );

If a connection is not successfully created, null is returned. Use site.GetState, site.GetErrorInfo, and site.GetErrorCode to retrieve information about the state of the connection.

88

Page 109: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

the

e

chained modeOpen 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).

Stored procedures and chained modeWhen stored procedures are created they inherit the mode of the connection through which they were created. Stored procedures that are created through an Open Client connection will have their mode set to chained by default. Once a stored procedure has been created it is possible to change its mode, so that it may be used by a connection regardless of mode, with the command: sp_procxmode stored_procedure_name, “anymode”Substitute your procedure name for the “stored_procedure_name”.

The connection objectIf there is no connection associated with a script (the connection shown indocument properties is “no connection”), then there will not be a connection object.

The site object allows you to manipulate your Web site connections. For information on CreateConnection, DeleteConnection or GetConnection se“site object” on page 291

Example This script creates a permanent ODBC connection called myConn. Oncecreated, this connection is visible from the Connections folder in Sybase Central:

<!--SCRIPT /* creates a permanent ODBC connection */ site.CreateConnection ( "myConn","My new ODBC connection","Godzilla","dba","sql","ODBC" ); -->

See also “Connect method” on page 198

“Disconnect method” on page 200

“GetSupportedMoves method” on page 103

“Rollback method” on page 103

89

Page 110: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

connection properties

connection propertiesThe connection object has these properties:

autoCommit propertySyntax connection.autoCommit

Description If true, each SQL statement executed using the connection is automatically committed immediately after it is executed.

chained modeOpen 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 propertySyntax 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 );-->

90

Page 111: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

n

This example has an output of:

falsetruefalse

See also The “Disconnect method” on page 200

The “Connect method” on page 198

connectionType propertySyntax 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 connectioobject:

<!--SCRIPT // This script displays the type of connection // being used. document.Write( "This is an " ); document.Write( connection.connectionType ); document.WriteLn( " connection." );-->

connectParameters propertySyntax 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:

91

Page 112: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

connection properties

autostop = no

database propertySyntax 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 propertySyntax 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 propertySyntax 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";-->

92

Page 113: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

dataSourceList propertySyntax 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 SamplePowerDynamo Demo

description propertySyntax 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 propertySyntax 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:

93

Page 114: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

connection properties

e, the

tion

n is

ns

• -1 “The isolation level is undetermined or cannot be determined.”

• 0 “ReadUncommitted”

• 1 “ReadCommitted”

• 2 “RepeatableRead”

• 3 “Serializable”

• 4 “Versioning”

If you set the isolation level to a value that the database does not recognizold isolation value will remain.

Example This example displays the current isolation level and then resets the isolalevel to 3:

<!--SCRIPT myConn=site.GetConnection("MyConnection") myConn.Connect(); document.WriteLn( "The isolation level = " + myConn.isolationLevel ) myConn.isolationLevel = 3; document.WriteLn( "The isolation level = " + myConn.isolationLevel )-->

name propertySyntax connection.name

Description Name of the connection object (string). The name of the default connectio<default>.

Example This example displays the name of the connection object. The Connectiofolder 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>

94

Page 115: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

used

password propertySyntax 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 propertySyntax connection.server

Description Server name for the Open Client connection (string). This property can be 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 propertySyntax 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.

95

Page 116: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

connection properties

[Adaptive Server Enterprise] The cursor support of Adaptive Server Enterprise is not as extensive as that of Adaptive Server Anywhere, and some of the Move functions are unavailable.

To use Move, MoveFirst, MoveLast, MovePrevious or MoveRelative with an Adaptive Server Enterprise connection you simulate the cursor abilities of Adaptive Server Anywhere using connection.simulateCursors.

To simulate cursors for all connections indefinitely, modify your Registry as follows:

From your system’s Registry Editor, open the following file: HKEY_LOCAL_MACHINE\SOFTWARE\SYBASE\SYBASE TOOLS

Add the new string value name Simulate Cursors with the string value of "yes."

Using simulated cursors may cause a decline in performance. When possible, use MoveNext instead.

Example This example allows MovePrevious to be used with an Adaptive Server Enterprise connection:

<!--SQL select lname from customer--><!--script connection.simulateCursors = true; SQL.MoveLast() while( SQL.MovePrevious() ) { document.writeln( SQL.GetValue(1) ); }-->

See also “query object” on page 269

The “query properties” on page 271

The “Move method” on page 279

The “MoveFirst method” on page 280

The “MoveLast method” on page 281

The “MoveNext method” on page 282

The “MovePrevious method” on page 283

The “MoveRelative method” on page 284

96

Page 117: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

user

ount.

userId propertySyntax connection.userId

Description User name for the ODBC data source (string).

Example This example gets the connection “Temp” and changes the password andID.

<!--SCRIPT // change the password and userId of the "Temp" // connection object myConn=site.GetConnection ( "Temp" ); myConn.password = "Top"; myConn.userId = "Secret";-->

connection methodsThe connection object has these methods:

Commit methodSyntax connection.Commit ( )

Description Commits the transaction.

Return Boolean.

Example This example moves 100 dollars from a checking account to a savings accIf 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’" );

97

Page 118: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

connection methods

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(); }-->

Connect methodSyntax 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 200

CreateComponent methodSyntax connection.CreateComponent (packageName, componentName )

Description This method is for calling Jaguar components. connection.CreateComponent returns a component object representingthe object referenced within the package.

98

Page 119: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

n

ute it.

”) for

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 methodSyntax connection.CreateQuery ( [ SQLStatement, [doExecute ]] )

Description Executes a query containing a sqlStatement and returns a query object (equivalent to performing myQuery.SetSQL and myQuery.Execute).

You can use CreateQuery method in these ways:

• connection.CreateQuery() creates an “empty” query object. You cathen call the SetSQL and Execute methods at a later time.

• connection.CreateQuery("select * from product") creates and executes a query.

• connection.CreateQuery("select * from product", false) creates a query object and sets the SQL statement, but does not execYou can then call the Execute method at a later time.

Return Returns a query object.

Example This example queries the sample database (using the connection “samplea list of all the employees and then displays the list in alphabetical order:

<!--SCRIPT // Create a query to display first and last name // of employees in alphabetical order myConn=site.GetConnection( "sample" ); if ( myConn != null ) { myQuery = myConn.CreateQuery( "select emp_lname, emp_fname from employee order by emp_lname, emp_fname" ); if ( myQuery.GetErrorCode != 0 ) while( myQuery.MoveNext() ) { lastName = myQuery.GetValue(1); firstName = myQuery.GetValue(2); document.WriteLn( lastName + ", " + firstName ); }

99

Page 120: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

connection methods

}-->

This example has the following output:

Ahmed, AlexBarker, JosephBarletta, IreneBertrand, JeannetteBigelow, JanetBlaikie, BarbaraBraun, JaneBreault, RobertBucceri, MatthewButterfield, JoyceChao, Shih LinCharlton, DougChin, PhilipClark, AlisonCobb, MatthewCoe, KristenEvans, Scott...

See also “query object” on page 269.

Disconnect methodDescription 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 methodSyntax connection.GetErrorCode( )

Description Returns the current error code.

100

Page 121: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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(); document.WriteLn( queryError );--></BODY></HTML>

See also “query object” on page 269.

The “query properties” on page 271.

The “GetErrorInfo method” on page 277.

The “GetState method” on page 278.

GetErrorInfo methodSyntax 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

101

Page 122: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

connection methods

e

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 269.

The “query properties” on page 271.

“GetErrorCode method” on page 277.

“GetState method” on page 278.

GetState methodSyntax connection.GetState( )

Description Returns the current SQL state of the query.

The values returned by GetState depend on your database driver. For morinformation, 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>

102

Page 123: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

e:

</HTML>

See also “query object” on page 269.

The “query properties” on page 271.

“GetErrorCode method” on page 277.

“GetErrorInfo method” on page 277.

GetSupportedMoves methodSyntax connection.GetSupportedMoves ( )

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 b

MoveFirstMoveNextMovePreviousMoveRelativeMoveMoveLast

Rollback methodSyntax connection.Rollback ( )

Description Performs a rollback on the transaction.

Return Boolean.

103

Page 124: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Date object

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’ ); 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(); }-->

Date objectObject 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 )

104

Page 125: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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.

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:

105

Page 126: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Date methods

<!--SCRIPT myDateObj = new Date("98", "01", "11", "8","30")-->

See also “valueOf method” on page 265

Date methodsThe Date object has these methods:

getDate methodSyntax 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 methodSyntax 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

106

Page 127: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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() );-->

getFullYear methodSyntax 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 methodSyntax 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 methodSyntax 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:

107

Page 128: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Date methods

<!--SCRIPT myDate = new Date( "98", "01", "11", "8","30" ); document.WriteLn( "Milliseconds: " + myDate.getMilliseconds() );-->

getMinutes methodSyntax 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 methodSyntax 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 methodSyntax Date.getSeconds( )

Description Returns the seconds value.

Return Integer between 0 and 59.

Example This example displays the seconds value of the Date object:

108

Page 129: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

<!--SCRIPT myDate = new Date( "98", "01", "11", "8","30" ); document.WriteLn( "Seconds: " + myDate.getSeconds() );-->

getTime methodSyntax 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 methodSyntax 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() );-->

109

Page 130: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Date methods

getUTCDate methodSyntax 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 myDate = new Date( "98", "01", "11", "8","30" ); myUTCDate = myDate.getUTCDate(); document.WriteLn( "UTC date: " + myUTCDate );-->

getUTCDay methodSyntax 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() );-->

110

Page 131: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

getUTCFullYear methodSyntax 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: " + myDate.getUTCFullYear() );-->

getUTCHours methodSyntax 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 methodSyntax 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: " +

111

Page 132: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Date methods

myDate.getUTCMilliseconds() );-->

getUTCMinutes methodSyntax Date.getUTCMinutes( )

Description Returns the minutes value in a Date object, using Universal Coordinated Time.

Return Integer between 0 and 59.

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 methodSyntax 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

112

Page 133: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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() );-->

getUTCSeconds methodSyntax 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 methodSyntax 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() );-->

113

Page 134: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Date methods

parse methodSyntax 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

• Hour:minute:second For example, March 23 93 11:23:03. You do not need to specify hours, minutes, and seconds. All, one, or none or these values may be specified.

Use the parse method with the built-in Date object as shown in this example. The parse method does not work with instances of the Date object.

Return Integer (milliseconds).

Example This example returns the number of milliseconds between the date string and January 1, 1970:

<!--SCRIPT dateString = "March 11, 1996" document.WriteLn( Date.parse(dateString) );-->

setDate methodSyntax 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() );

114

Page 135: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

myDate.setDate( "23" ); document.WriteLn( "Date: " + myDate.getDate() );-->

setFullYear methodSyntax 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:

• 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.

Return Integer. The number of milliseconds since midnight, January 1, 1970.

Example This example changes the year of the Date object to 1999:

<!--SCRIPT myDate = new Date( "98", "01", "11", "8","30", "11", "35" ); document.WriteLn( "Year: " + myDate.getFullYear() ); myDate.setFullYear( "99" ); document.WriteLn( "Year: " + myDate.getFullYear() );-->

setHours methodSyntax 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.

115

Page 136: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Date methods

• 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() );-->

setMilliseconds methodSyntax 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 methodSyntax 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:

116

Page 137: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

• 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: " + 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: 30New hours: 9New minutes: 29

setMonth methodSyntax 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

117

Page 138: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Date methods

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 methodSyntax Date.setSeconds( numSec [, numMilli] )

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 methodSyntax 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.

118

Page 139: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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() ); document.WriteLn( "Minutes: " + myDate.getUTCMinutes() );-->

The output from this example is:

Year: 1970Month: 0Date: 1Hours: 1Minutes: 28

setUTCDate methodSyntax 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",

119

Page 140: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Date methods

"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: 11Old month: 1New date: 17New month: 2

setUTCFullYear methodSyntax 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() );

120

Page 141: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

-->

setUTCHours methodSyntax 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.

• 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 methodSyntax 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:

121

Page 142: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Date methods

<!--SCRIPT myDate = new Date( "98", "01", "11", "8","30", "11", "35" ); myDate.setUTCMilliseconds( "12" ); document.WriteLn( "New milliseconds: " + myDate.getUTCMilliseconds() ); -->

setUTCMinutes methodSyntax Date.setUTCMinutes( numMin [numSec, numMilli] )

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 methodSyntax 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:

122

Page 143: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

• 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() );-->

setUTCSeconds methodSyntax 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 methodSyntax Date.setYear ( numYear )

123

Page 144: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Date methods

.

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 methodSyntax 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.

toLocaleString methodSyntax 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 methodSyntax Date.toString( )

Description Returns the date as a string in a convenient, readable format in local time

Return String.

124

Page 145: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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 methodSyntax Date.toUTCString( )

Description Returns a date as a string in Universal Coordinated Time.

Return String.

Example This example displays the value of the Date object in Universal Coordinated Time:

<!--SCRIPT myDate = new Date( "98", "01", "11", "8","30", "11", "35" ); document.WriteLn( myDate.toUTCString() );-->

The output from this example is:

Wed, 11 Feb 1998 13:30:11 UTC

valueOf methodSyntax 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",

125

Page 146: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

document object

t and

"35" ); document.WriteLn( myDate.valueOf() );-->

document objectObject 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 291.

CautionDon’t confuse the Dynamo document object and the JavaScript documenobject. The Dynamo document object supports a different set of propertiesmethods 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 93.

“size property” on page 232.

“value property” on page 145.

126

Page 147: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

it u use

on

document propertiesThe document object has these properties:

cachedOutputTimeOut propertySyntax 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 3minutes.

<!--SCRIPT /* setting the cache time */ document.WriteLn( "This is my output that will be cached for 3 minutes." ); document.cachedOutputTimeOut = 3;-->

connectionId propertySyntax document.connectionId

Description ID of associated connection object (integer). Connection IDs may changeyou restart the Web server. For this reason, Sybase recommends that yothe connectionName property instead.

Example This example displays the connection Id of a script's associated connectiobject:

<!--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 87.

127

Page 148: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

document properties

d eb

and wser

connectionName propertySyntax 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 87.

contentType propertySyntax document.contentType

Description Type of document being displayed (string). The content types are standarMIME content types. This property is not persistent and will be reset if the Wserver is restarted.

Example This example selects a graphic called bart.gif from a table in the databasethen displays it to a browser. The second part of the example tells the broto 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 propertySyntax document.description

Description Description associated with the document (string).

128

Page 149: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

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 propertySyntax 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.

The document id for docid.stm is:

265

lastModified propertySyntax document.lastModified

Attributes This property is read-only.

129

Page 150: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

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 propertySyntax document.location

Description Full URL for the document.

Linked FoldersYou cannot move a linked folder inside a linked folder.

Example This example displays the location of the document object.

<!--SCRIPT /* location of the document. */ document.WriteLn( document.location );-->

The output from this example is:

/Site/location.ssc

name propertySyntax 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:

130

Page 151: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

name.ssc

parent propertySyntax document.parent

Description The containing folder object of this document (document).

Linked FoldersYou cannot move a linked folder inside a linked folder.

Example This example moves the document /site/sample/products.stm into /site/myFolder:

<!--SCRIPT myFolderDoc = site.GetDocument( "/site/myFolder" ); productsDoc = site.GetDocument( "/site/sample/products.stm" ); productsDoc.parent = myFolderDoc-->

redirect propertySyntax 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 propertySyntax 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:

131

Page 152: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

document properties

The

s the

<!--SCRIPT /* Size of the document. */ document.WriteLn( document.size );-->

source propertySyntax 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 propertySyntax document.status

Description A string that indicates a status code and a brief explanation of that code. status code values are defined in the HTTP specification.

Example This example prompts the user for a user ID and a password, then displaystatus 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

132

Page 153: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

nheit

// browser, we still need to provide an // informational message which // will be displayed if the user selects // cancel in the login dialog document.writeln( "<html><body><h1>" ); document.writeln( document.status ); document.writeln( "</h1></body></html>" );}-->

type propertySyntax 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 propertySyntax 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 Fahreor from Fahrenheit to Celsius.

133

Page 154: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

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>

<P>This page allows you to convert a temperature from <I>Celsius</I> to<I>Fahrenheit</I> or from <I>Fahrenheit</I> to <I>Celsius</I>.<BR><HR WIDTH="100%">

<P>Select the appropriate button and enter the temperature you would liketo convert.

<FORM METHOD=POST ACTION="convert.stm"><OL><LI><INPUT TYPE="radio" NAME="theType" value="CtoF" CHECKED>Celsius to Fahrenheit<BR><INPUT TYPE="radio" NAME="theType" value="FtoC">Fahrenheit to Celsius<BR><LI><INPUT TYPE="text" NAME="temperature" SIZE="4"> Temperature</OL><P><INPUT TYPE="submit"></p><P><INPUT TYPE="RESET" VALUE="Clear Form"></P></FORM>

</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;

134

Page 155: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

var tempnumber = document.value.temperature;

var DemoObj = CreateObject( "SybaseDemoObject.TempConvert" ); if( conversionType == "CtoF" ){ var c = DemoObj.ConvertCtoF( tempnumber ); document.WriteLn( "The Celsius temperature of " + tempnumber + " is " + c + " on the Fahrenheit scale." ); } else { var f = DemoObj.ConvertFtoC( tempnumber ); document.WriteLn( "The Fehrenheit temperature of " + tempnumber + " is " + f + " on the Celsius scale." ); } -->

</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

135

Page 156: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

document methods

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();-->

document methodsThe document object has these methods:

136

Page 157: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

is

the

ExportTo methodSyntax 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 methodSyntax 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 the sortOrder default.

For information on the wildcards, see “Wildcards” on page 73.

Return Array of document objects. Returns a list of contained documents.

Example This example displays all the documents in the /site folder that begin withletter 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 ); }-->

137

Page 158: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

document methods

rd.

hich rs.

GetGenerated methodSyntax 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 passwo

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 316.

GetServerVariable method Syntax document.GetServerVariable( )

Description Returns a value from a server. The server variable name is dependent on wserver interface is being used. This method is not supported by CGI serve

CGI Equivalent ISAPI

NSAPI (native)

NSAPI (Dynamo cover for NSAPI)

Personal Web Server

AUTH_TYPE AUTH_TYPE auth-type

AUTH_TYPE

CONTENT_LENGTH

CONTENT_LENGTH

content-length

CONTENT_LENGTH

CONTENT_LENGTH

CONTENT_TYPE

CONTENT_TYPE

content-type

CONTENT_TYPE

CONTENT_TYPE

GATEWAY_INTERFACE

GATEWAY_INTERFACE

GATEWAY_INTERFACE

HTTP_USER_AGENT

HTTP_USER_AGENT

user-agent

HTTP_USER_AGENT

HTTP_USER_AGENT

PATH_INFO PATH_INFO path PATH_INFO PATH_INFO

138

Page 159: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

Return String. Returns a value from the server.

Example This example displays the address of the remote host:

<!--SCRIPT REMOTE_ADDR = document.GetServerVariable( "REMOTE_ADDR" );

PATH_TRANSLATED

PATH_TRANSLATED

QUERY_STRING

QUERY_STRING

query QUERY_STRING

QUERY_STRING

REMOTE_ADDR

REMOTE_ADDR

ip REMOTE_ADDR

REMOTE_ADDR

REMOTE_HOST

REMOTE_HOST

REMOTE_USER

REMOTE_USER

auth-user

REMOTE_USER

REQUEST_METHOD

REQUEST_METHOD

method REQUEST_METHOD

REQUEST_METHOD

SCRIPT_NAME

SCRIPT_NAME SCRIPT_NAME

SCRIPT_NAME

SERVER_NAME

SERVER_NAME

SERVER_PORT

SERVER_PORT SERVER_PORT

SERVER_PROTOCOL

SERVER_PROTOCOL

protocol

SERVER_PROTOCOL

SERVER_PROTOCOL

SERVER_SOFTWARE

SERVER_SOFTWARE

SERVER_SOFTWARE

SERVER_SOFTWARE

HTTP_COOKIE cookie COOKIE COOKIE

URL URL_PREFIX

UNMAPPED_REMOTE_USER

SERVER_PORT_SECURE

HTTP_ACCEPT

ALL_HTTP

CGI Equivalent ISAPI

NSAPI (native)

NSAPI (Dynamo cover for NSAPI)

Personal Web Server

139

Page 160: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

document methods

f the

document.writeln( "<BR>REMOTE_HOST = "+ REMOTE_ADDR );-->

The output for this example is:

REMOTE_ADDR = 122.47.156.352

ImportFrom methodSyntax 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 methodsucceeded 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 methodSyntax document.IncludeGenerated( )

Description Includes the generated output of the document that is called in the output ocurrently executing script. A document cannot call document.IncludeGenerated on itself.

140

Page 161: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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><!--SQLSELECT customer.fname, customer.lnameFROM 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><TH>lname</TH></TR><TR><TD>Michaels</TD>

141

Page 162: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

document methods

<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 methodSyntax 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 methodSyntax 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).

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:

142

Page 163: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

and

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 196.

DOMAttribute objectObject 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 do appear within the document tree.

143

Page 164: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMAttribute properties

of

f a

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 162.

“attributes property” on page 174.

“setAttribute method” on page 165.

DOMAttribute propertiesThe DOMAttribute object has these properties as well as all the propertiesthe DOMNode object, which are inherited:

name propertySyntax 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 oDOMElement object named elem:

attlist = elem.attributesfor( iAtt=0; iAtt < attlist.length; iAtt++ ) { document.writeln( attlist.item(iAtt).name );}

See also “getAttributeNode method” on page 162.

144

Page 165: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

specified propertySyntax 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:

attlist = elem.attributesfor( iAtt=0; iAtt < attlist.length; iAtt++ ) { if( attlist.item(iAtt).specified == true ){ document.writeln( attlist.item(iAtt).name ); }}

value propertySyntax 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.attributesfor( iAtt=0; iAtt < attlist.length; iAtt++ ) {

145

Page 166: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMAttribute methods

document.writeln( attlist.item(iAtt).value ); }}

DOMAttribute methodsThe DOMAttribute object has no methods of its own but inherits all the methods of the DOMNode object.

DOMCDATASection objectObject 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.

DOMCharacterData objectObject 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.

146

Page 167: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

DOMCharacterData propertiesThe DOMCharacterData object has the properties listed in this section, in addition to all of the properties of the DOMNode object, which are inherited:

data propertySyntax 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 propertySyntax 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 )

147

Page 168: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMCharacterData methods

DOMCharacterData methodsThe DOMCharacterData object inherits the methods from the DOMNode object, but it also has its own methods, which are discussed in this section.

appendData methodSyntax 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 methodSyntax 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.

148

Page 169: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

• 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 methodSyntax 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 methodSyntax 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" )}

149

Page 170: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMComment object

substringData methodSyntax 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 ) }}

DOMComment objectObject 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 146.

150

Page 171: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

a

DOMDocument objectObject 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 returnsDOMDocument 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()

DOMDocument propertiesThe DOMDocument object inherits all the properties of the DOMNode object, as well as the properties discussed in this section.

doctype propertySyntax DOMDocument.doctype

151

Page 172: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMDocument properties

ts in

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 158.

documentElement propertySyntax DOMDocument.documentElement

Description Each XML document has a single element that contains all other elementhe 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 rootelement of the document, and write out the name of that element, enter:

domDoc = toDOMDocument( xmlString );docElement = domDoc.documentElement;document.writeln( docElement.tagName );

implementation propertySyntax 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.

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? falseXML? true

152

Page 173: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

e.

et on

n be

See also “DOMImplementation object” on page 169.

DOMDocument methodsThe DOMDocument object inherits the methods from the DOMNode object, as well as the methods discussed in this section.

createAttribute methodSyntax DOMDocument.createAttribute( name )

Description Creates a DOMAttribute object representing an attribute of the given nam

The created attribute does not have any place in the document. It can be san 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 143.

“setAttribute method” on page 165.

createCDATASection methodSyntax 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 caadded as the child of a node by using the appendChild method of a DOMNode object.

Return A DOMCDATASection object.

153

Page 174: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMDocument methods

dds ment.

ed

ent

Example This example creates a CDATA section with text “Jane & John Doe”, and ait to the document as the last element before the end of the document ele

xmlString = "Jane & John Doe"domCDATA = domDoc.createCDATASection( xmlString );element.appendChild( domCDATA );

See also “DOMCDATASection object” on page 146.

“appendChild method” on page 181.

createComment methodSyntax DOMDocument.createComment( comment )

Description Creates a DOMComment object representing a comment containing the specifistring. 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 documusing 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 150.

“DOMNode methods” on page 181.

createDocumentFragment methodSyntax 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:

154

Page 175: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

are

ngle

domDoc.createDocumentFragment;

See also “DOMDocumentFragment object” on page 157.

“DOMNode methods” on page 181.

createElement methodSyntax 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 XMLcase-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 160.

“DOMNode methods” on page 181.

createEntityReference methodSyntax 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 abracket).

domDoc.createEntityReference( "lt" );

See also “DOMEntityReference object” on page 168.

“DOMNode methods” on page 181.

createProcessingInstruction methodSyntax DOMDocument.createProcessingInstruction( target, data )

155

Page 176: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMDocument methods

ag to

se

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.

Return A DOMProcessingInstruction object.

Example This example creates a processing instruction that is a simple form of the required heading for an XML document. It then appends this processing instruction to an empty DOMDocument object.

domDoc = new DOMDocument();docPI = domDoc.createProcessingInstruction( "xml", "version=’1.0’" );domDoc.appendChild( docPI );

See also “DOMProcessingInstruction object” on page 185.

“DOMNode methods” on page 181.

createTextNode methodSyntax 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 181

getElementsByTagName methodSyntax 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. Tnames in XML are case-sensitive. The special tag name “*” can be used retrieve a list of all DOMElement objects regardless of the tag name.

To search for DOMElement objects that are children of a particular element, uthe getElementsByTagName method on the DOMElement object.

156

Page 177: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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++ ){ elem = elemList.item( iElem ); -- operations here}

prettyPrint methodSyntax 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() );

DOMDocumentFragment objectObject 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.

157

Page 178: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMDocumentType object

nt.

rit

on.

nd

See also “DOMNode object” on page 173

DOMDocumentType objectObject Represents the document type definition (DTD) portion of an XML docume

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 thelist 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 inheall 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;

DOMDocumentType propertiesThe DOMDocumentType object inherits all properties from the DOMNode object, but it also has its own properties, which are discussed in this secti

entities propertySyntax DOMDocumentType.entities

Description A DOMNamedNodeMap object containing the general entities both external ainternal. 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).

158

Page 179: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

<?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.entitiesfor( iEnt = 0; iEnt < entlist.length; iEnt++ ){ ent = entlist.item(iEnt); document.writeln( "Name = " + ent.nodeName );}

The output from this example is:

Name = PQName = Logo

See also “DOMEntity object” on page 166.

“DOMNamedNodeMap object” on page 170.

name propertySyntax DOMDocumentType.name

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.

159

Page 180: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMElement object

t

var domDoc = toDOMDocument( xmlDoc.source);var dtd = domDoc.doctype;document.writeln( "Doctype name = " + dtd.name );

See also “documentElement property” on page 152.

notations propertySyntax 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 184.

“DOMNamedNodeMap object” on page 170.

DOMElement objectObject 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 seof all attributes for an element. The getAttribute and getAttributeNode methods on the DOMElement object can be used to retrieve individual attributes.

160

Page 181: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

sitive

M

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>

DOMElement propertyThe DOMElement object inherits all of the properties of the DOMNode object, as well as the tagName property, discussed here.

tagName propertySyntax DOMElement.tagName

Description A string containing the name of the element. Element names are case-senin XML.

Example This example writes out the name of the document element of an XML DOdocument stored in domDoc.

docElem = domDoc.documentElement;document.writeln( docElem.tagName );

DOMElement methodsThe 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 methodSyntax DOMElement.getAttribute( name )

Description Retrieves an attribute value by name.

161

Page 182: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMElement methods

Tag to

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 methodSyntax 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 143.

getElementsByTagName methodSyntax DOMElement.getElementsByTagName( name )

Description Returns a DOMNodeList object of all descendant elements with a given tagname, in the order in which they would be encountered in the document. names in XML are case-sensitive. The special tag name “*” can be used 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.

162

Page 183: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

rmat. nt

rit

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 1Item 1.1Item 2

See also “DOMNodeList object” on page 183.

normalize methodSyntax DOMElement.normalize( )

Description Normalizing an element places it and all its descendants into a standard foFor all DOMText node objects that are descendants of this element, adjace(sibling) DOMText objects are combined into a single DOMText object.

Adjacent DOMCDATASection nodes are not combined even though they inhefrom DOMText.

Example This statement normalizes the element named elem.

elem.normalize();

163

Page 184: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMElement methods

removeAttribute methodSyntax 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 143.

removeAttributeNode methodSyntax DOMElement.removeAttributeNode( att_node )

Description Removes the specified attribute node.

Return The DOMAttribute object that was removed.

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" ); }

164

Page 185: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

dy eter.

e

}

See also “DOMAttribute object” on page 143.

setAttribute methodSyntax DOMElement.setAttribute( name, value )

Description Adds a new attribute to the element. If an attribute with that name is alreapresent in the element, its value is changed to be that of the value paramThe 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() ); }}

See also “DOMAttribute object” on page 143

setAttributeNode methodSyntax DOMElement.setAttributeNode( newAttr )

Description Adds a new attribute. If an attribute with that name is already present in thelement, it is replaced by the new one. newAttr is the DOMAttribute object representing the attribute to be set.

165

Page 186: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMEntity object

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 143.

DOMEntity objectObject 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 theproperties and methods of the DOMNode object, and has its own properties, which are discussed in this section.

DOMEntity propertiesThe DOMEntity object inherits all the properties of the DOMNode object, as well as the properties discussed in this section.

166

Page 187: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

notationName propertySyntax 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.entitiesfor( iEnt = 0; iEnt < entlist.length; iEnt++ ){ ent = entlist.item(iEnt); document.writeln( "notationName = " + ent.notationName );}

The output of this example is:

notationName = nullnotationName = GIF

publicId propertySyntax 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.

<!ENTITY PubLogo PUBLIC "-//MyOrg//GIF Logo//EN" "logo.gif" NDATA GIF>

If this entity declaration is stored in a variable named ent, then the following instructions write out the public identifier of the entity.

document.writeln( "publicId " + ent.publicId );

167

Page 188: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMEntityReference object

The output from this example is:

publicId -//MyOrg//GIF Logo//EN

systemId propertySyntax 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.entitiesfor( iEnt = 0; iEnt < entlist.length; iEnt++ ){ ent = entlist.item(iEnt); document.writeln( "systemId = " + ent.systemId );}

This example is:

systemId = nullsystemId = nautilus.gif

DOMEntityReference objectObject Represents an entity reference in an XML document.

Syntax To use a DOMEntityReference’s property:

DOMEntityReference.propertyName

To use a DOMEntityReference’s method:

168

Page 189: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

es

ters

L”

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 173.

“DOMEntity object” on page 166.

DOMImplementation objectObject 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 featursupported 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.

DOMImplementation methodsThe DOMImplementation object has these methods:

hasFeature methodSyntax DOMImplementation.hasFeature( feature, version )

Description Tests if the DOM implementation includes a specific feature. The parameare:

• feature The package name of the feature to test. This can be “HTMor “XML”.

169

Page 190: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMNamedNodeMap object

me.

, but ode

• 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, falseotherwise.

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? falseXML? true

DOMNamedNodeMap objectObject Represents a collection of DOMNode objects that can be accessed by na

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 indexthis is simply provided as a means of enumerating the objects within the nmap. It does not imply that the objects within the node map are ordered.

DOMNamedNodeMap propertyThe DOMNamedNodeMap object has these properties:

170

Page 191: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

he

length propertySyntax 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 170

DOMNamedNodeMap methodsThe DOMNamedNodeMap object has these methods:

getNamedItem methodSyntax 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 tmap.

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.attributesatt = attlist.getNamedItem( attName );document.writeln( att.value );

See also “DOMNode object” on page 173.

item methodSyntax 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.

171

Page 192: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMNamedNodeMap methods

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 methodSyntax DOMNamedNodeMap.removeNamedItem( name )

Description Removes a DOMNode object specified by name.

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 173

setNamedItem methodSyntax DOMNamedNodeMap.setNamedItem( node-name )

172

Page 193: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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 ); if( oldNode == null ) { document.writeln( "New attribute added" ); } else { document.writeln( "Replaced attribute" ); } }}

DOMNode objectObject 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.

173

Page 194: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMNode properties

re

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.

DOMNode propertiesThe DOMNode object has these properties:

attributes propertySyntax 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 170.

childNodes propertySyntax DOMNode.childNodes

Description A DOMNodeList object that contains all the children of this node. If there ano children, then this is a node list containing zero nodes.

174

Page 195: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

Performance tipTo 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.

Example This example loops through the childNodes of a node.

function ChildNodes( domDoc ){ docElem = domDoc.documentElement; var node = docElem.firstChild; do { document.writeln( node.nodeName ); node = node.nextSibling; } while ( node != null )}

firstChild propertySyntax DOMNode.firstChild

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

entity reference element, processing instruction, comment, text, CDATA section, entity reference

element element, text, comment, processing instruction, CDATA section, entity reference

attribute text, entity reference

processing instruction no children

comment no children

text no children

CDATA section no children

entity element, processing instruction, comment, text, CDATA section, entity reference

notation no children

175

Page 196: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMNode properties

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 propertySyntax DOMNode.lastChild

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 propertySyntax 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 propertySyntax 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”

176

Page 197: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

ype

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 162.

nodeType propertySyntax DOMNode.nodeType

Description An integer representing the type of node object. This table lists the nodeTnumber for each type of node.

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

Node Type Contents of nodeName property

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

177

Page 198: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMNode properties

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; 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

document 9

document type 10

document fragment 11

notation 12

Node Type Contents of nodeType property

178

Page 199: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

break; default: document.writeln( "Invalid node type: " + domChild.nodeType ); }

nodeValue propertySyntax 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.

Example This fragment writes out the nodeValue for an attribute named Type:

if( domAtt.nodeName == "Type" ){ document.writeln( domAtt.nodeValue );}

ownerDocument propertySyntax DOMNode.ownerDocument

Description The DOMDocument object associated with this node. For DOMDocument objects, this property is null.

Node Type Contents of nodeValue property

document null

document fragment null

document type null

entity reference null

element null

attribute value of attribute

processing instruction entire content excluding the target

comment content of the comment

text content of the text node

CDATA section content of the CDATA section

entity null

notation null

179

Page 200: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMNode properties

e,

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 151.

parentNode propertySyntax 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.

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 propertySyntax DOMNode.previousSibling

Description The DOMNode object representing the node immediately preceding this nodor 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 )}

180

Page 201: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

DOMNode methodsThe DOMNode object has these methods:

appendChild methodSyntax 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 methodSyntax 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() );

181

Page 202: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMNode methods

hasChildNodes methodSyntax 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 methodSyntax 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 methodSyntax 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.

182

Page 203: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

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 methodSyntax 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 );

DOMNodeList objectObject 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.

DOMNodeList propertyThe DOMNodeList object has this property:

183

Page 204: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMNodeList methods

length propertySyntax 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}

DOMNodeList methodsThe DOMNodeList object has these methods:

item methodSyntax 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}

DOMNotation objectObject Represents a notation declared in the DTD.

Syntax To use a DOMNotation's property:

DOMNotation.propertyName

184

Page 205: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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.

DOMNotation propertiesThe DOMNotation object inherits all the properties of the DOMNode object, and has the properties discussed in this section.

publicId propertySyntax DOMNotation.publicId

Description The public identifier of this notation, or null if no public identifier was specified.

systemId propertySyntax DOMNotation.systemId

Description The system identifier of this notation, or null if no system identifier was specified.

DOMNotation methodsThe DOMNotation object has no methods of its own but inherits all of the methods of the DOMNode object.

DOMProcessingInstruction objectObject Represents a processing instruction in the XML document.

185

Page 206: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMProcessingInstruction properties

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.

DOMProcessingInstruction propertiesThe DOMProcessingInstruction object inherits all of the properties of the DOMNode object, and has its own properties discussed in this section.

data propertySyntax 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 propertySyntax 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’ ?>

186

Page 207: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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 );

DOMProcessingInstruction methodsThe DOMProcessingInstruction object has no methods of its own but inherits all the methods of the DOMNode object.

The DOMText objectObject Represents textual content.

Syntax To use a DOMText’s property:

DOMText.propertyName

To use a DOMText’s method:

DOMText.MethodName( parameter )

Description DOMText objects inherit all of the properties and methods of the DOMCharacterData object.

If there is no markup inside an element’s content, the text is contained in a single DOMText object that is the only child of the element. If there is markup, the content is parsed into a list of elements and text nodes that form the list of children of the element.

When a DOMDocument is created (via the toDOMDocument method), there is only one DOMText object for each block of text. Additional DOMText objects can then be added, resulting in adjacent text nodes without intervening markup. You can use the normalize method on a DOMElement to merge adjacent DOMText objects into a single DOMText object.

See also “DOMCharacterData object” on page 146.

187

Page 208: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

DOMText properties

rnal

DOMText propertiesThe DOMText object has no properties of its own but does inherit all the properties of the DOMCharacterData object.

DOMText methodsThe DOMText object inherits all the methods of the DOMCharacterData object, but it also has one of its own methods, which is discussed here.

splitText methodSyntax 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 163.

file objectObject Provides manipulation of files through the file system. These are files exte

to the Web site.

188

Page 209: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

site

file

bject

For information on manipulating documents internal to the Web site, see “object” on page 291.

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 aobject, 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 orepresenting 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 81.

“mode property” on page 268.

file propertiesThe file object has these properties:

189

Page 210: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

file properties

eof propertySyntax 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 propertySyntax 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: " + inputFile.errorNumber );-->

This example checks for an error code of 0 and returns a message if a new file is created successfully:

190

Page 211: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

<!--SCRIPT

//Common Values for errorNumber on NT://0 No error//1 No such file or directory//6 Permission denied

var fileName = "c:\\foo.txt";

myFile = new File( fileName, "rt" ); if( myFile.errorNumber != 0 ) { // if error was encountered: document.writeln( "Error number " + myFile.errorNumber + " was encountered: " + myFile.errorString ); } else { document.writeln( myFile.name + " accessed successfully in " + myFile.mode + " mode." ); }-->

errorString propertySyntax 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();-->

If the file input5.txt cannot be found in the specified directory, the output looks like:

No such file or directorynull

191

Page 212: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

file properties

name propertySyntax 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 propertyDescription 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).

wb+ Create binary file for update.

ab+ Open binary file for update at end of file.

rt+ Open text file for update (reading/writing).

wt+ Create text file for update (reading/writing).

at+ Open text file for update at end of file.

192

Page 213: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

Changing a file modeSimply changing the file mode does not change the mode of the currently opened file. A call to Close followed by a call to Open is required to change a file mode.

Syntax file.mode

Example This example opens the file output.txt and appends the phrase “hello world” tothe end of the file:

<!--SCRIPT outputFile = new File ( "d:\\test\\output.txt", "a" ); outputFile.Write( "hello world" ); outputFile.Close();-->

file methodsThe file object has these methods:

Close methodSyntax file.Close( )

Description Closes the file associated with the file object.

Return Boolean. Returns true or false indicating whether the file was successfullyclosed.

Example This example opens and then closes the file input.txt:

<!--SCRIPT inputFile = new File ( "d:\\test\\input.txt", "r" ); inputFile.Close()-->

Delete methodSyntax file.Delete( )

193

Page 214: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

file methods

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 methodSyntax file.GetFilePtr( )

Description Returns the current file position. This position defines the position of the next character read or written.

Return Integer. Position.

Example This example displays the current position within the file input.txt:

<!--SCRIPT inputFile = new File( "d:\\test\\input.txt","r" ); line = inputFile.ReadLine(); document.WriteLn( inputFile.GetFilePtr() ); inputFile.Close();-->

Open methodSyntax 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( );

194

Page 215: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

dataFile.mode = "w"; dataFile.Open( );-->

Read methodSyntax 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" ); data=inputFile.Read(); document.WriteLn( data ); -->

ReadChar methodSyntax 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();-->

195

Page 216: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

file methods

ReadLine methodSyntax 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 methodSyntax file.Seek(offset)

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 methodSyntax 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.

196

Page 217: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

ction

object

e

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 methodSyntax file.WriteLine(s)

Description Identical to the Write method except that a new line is written following thewritten value.

Return Boolean.

Example This example writes “hello world” to the file output.txt, and erases all other textin the file:

<!--SCRIPT outputFile = new File ( "d:\\test\\output.txt","w" ); outputFile.WriteLine( "hello world" ); outputFile.Close( );-->

FTP objectObject 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 conneto 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 FTPto 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 thremote machine:

<!--SCRIPT

197

Page 218: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

FTP methods

ftpSybase = new FTP( "ftp.server.com", "Eric", "Smith" );ftpSybase.PutFile( "myfile.txt", "c:\\myfile.txt", "ASCII" );ftpSybase.Disconnect(); -->

FTP methodsThe FTP object has these methods:

ChangeCurrentDirectory methodSyntax 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", "[email protected]"); 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 methodSyntax FTP.Connect( )

Description Connects to the FTP server.

198

Page 219: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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", "[email protected]"); curdir = ftpSession.RetrieveCurrentDirectory(); document.WriteLn( "After connect " + curdir ); ftpSession.Disconnect(); curdir = ftpSession.RetrieveCurrentDirectory(); document.WriteLn( "After disconnect " + curdir ); ftpSession.Connect(); curdir = ftpSession.RetrieveCurrentDirectory(); document.WriteLn( "After connect " +curdir );-->

CreateDirectory methodSyntax 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", "[email protected]"); 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 methodSyntax FTP.DeleteFile( fileName )

199

Page 220: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

FTP methods

Description Deletes a file from the FTP server.

Return Boolean.

Example This example deletes the test.doc file:

<!--SCRIPT ftpSession = new FTP ("ftpserv", "anonymous", "[email protected]");if( !ftpSession.DeleteFile( "test.doc" )) { document.writeln( ftpSession.GetErrorCode() ); document.writeln( ftpSession.GetErrorInfo() ); } ftpSession.Disconnect();-->

Disconnect methodSyntax 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", "[email protected]"); ftpSession.ChangeCurrentDirectory( "Dynamo" ); if( !ftpSession.DeleteFile( "test.doc" )) { document.writeln( ftpSession.GetErrorCode() ); document.writeln( ftpSession.GetErrorInfo() ); } ftpSession.Disconnect();-->

GetErrorCode methodSyntax 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.

200

Page 221: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

Example This example puts a file on the FTP server and checks for errors:

<!--SCRIPT ftpSession = new FTP ("ftpserv", "anonymous", "[email protected]"); if( !ftpSession.PutFile("test.doc", "g:\\dynamo\\ftp\\test.doc")) { document.writeln( ftpSession.GetErrorCode() ); document.writeln( ftpSession.GetErrorInfo() ); }-->

GetErrorInfo methodSyntax 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", "[email protected]"); if( !ftpSession.PutFile("test.doc", "g:\\dynamo\\ftp\\test.doc")) { document.writeln( ftpSession.GetErrorCode() ); document.writeln( ftpSession.GetErrorInfo() ); }-->

PutData methodSyntax 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.

201

Page 222: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

FTP methods

l.

first

he st, a

l.

• transferType Can be one of ASCII, binary, EBCDIC, image or locaThe 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 theirand 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); document.writeln("The last name is " + document.value.lname);

ftpSession = new FTP ("ftpserv", "anonymous", "[email protected]"); if( !ftpSession.PutData("putdata.ssc", document.value.lname)) { document.writeln( ftpSession.GetErrorCode() ); document.writeln( ftpSession.GetErrorInfo() ); } ftpSession.Disconnect();

-->

PutDataWithAppend methodSyntax FTP.PutDataWithAppend( remoteFileName, localData [, transferType] )

Description Similar to the PutData method except that if the remote file already exists, tlocal data is appended to the end of the file. If the remote file does not exinew 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 locaThe default is binary.

Return Boolean.

202

Page 223: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

al

l.

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);

ftpSession = new FTP ("ftpserv", "anonymous", "[email protected]"); if( !ftpSession.PutDataWithAppend("putdata.ssc", document.value.lname)) { document.writeln( ftpSession.GetErrorCode() ); document.writeln( ftpSession.GetErrorInfo() ); } ftpSession.Disconnect();

-->

PutDocument methodSyntax 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 locmachine.

• transferType Can be one of ASCII, binary, EBCDIC, image or locaThe default is binary.

Return Boolean.

Example This example puts the Dynamo script test.ssc on the FTP server:

<!--SCRIPT ftpSession = new FTP ("ftpserv", "anonymous", "[email protected]"); if( !ftpSession.PutDocument("test.ssc", "test.ssc")) {

203

Page 224: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

FTP methods

al

l.

document.writeln( ftpSession.GetErrorCode() ); document.writeln( ftpSession.GetErrorInfo() ); } ftpSession.Disconnect();-->

PutDocumentWithAppend methodSyntax 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:

• remoteFileName The name of the file on the remote machine.

• documentName The name of the PowerDynamo document on the locmachine.

• transferType Can be one of ASCII, binary, EBCDIC, image, or locaThe 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 appends the content of test.ssc to the content of the existing test.ssc file on the remote machine:

<!--SCRIPT ftpSession = new FTP ("ftpserv", "anonymous", "[email protected]"); if( !ftpSession.PutDocumentWithAppend("test.ssc", "test.ssc")) { document.writeln( ftpSession.GetErrorCode() ); document.writeln( ftpSession.GetErrorInfo() ); } ftpSession.Disconnect();-->

204

Page 225: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

l.

y

l.

PutFile methodSyntax 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 locaThe 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:

<!--SCRIPT ftpSession = new FTP ("ftpserv", "anonymous", "[email protected]"); if( !ftpSession.PutFile("test.doc", "g:\\dynamo\\ftp\\test.doc")) { document.writeln( ftpSession.GetErrorCode() ); document.writeln( ftpSession.GetErrorInfo() ); }-->

PutFileWithAppend methodSyntax 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 alreadexist, 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 locaThe default is binary.

Return Boolean.

205

Page 226: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

FTP methods

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", "[email protected]"); if( !ftpSession.PutFileWithAppend("test.txt", "g:\\dynamo\\ftp\\test.txt")) { document.writeln( ftpSession.GetErrorCode() ); document.writeln( ftpSession.GetErrorInfo() ); }-->

RemoveDirectory methodSyntax FTP.RemoveDirectory( directoryName )

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", "[email protected]"); if( !ftpSession.RemoveDirectory( "Dynamo")) { document.writeln( ftpSession.GetErrorCode() ); document.writeln( ftpSession.GetErrorInfo() ); } ftpSession.Disconnect();-->

RetrieveCurrentDirectory methodSyntax 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",

206

Page 227: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

The

"[email protected]"); ftpSession.ChangeCurrentDirectory("Dynamo"); curdir = ftpSession.RetrieveCurrentDirectory(); document.WriteLn( curdir ); ftpSession.Disconnect();-->

RenameFile methodSyntax 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.

Example This example renames a file on the FTP server from test.txt to newtest.txt:

<!--SCRIPT ftpSession = new FTP ("ftpserv", "anonymous", "[email protected]"); if( !ftpSession.RenameFile("test.txt", "newtest.txt")) { document.writeln( ftpSession.GetErrorCode() ); document.writeln( ftpSession.GetErrorInfo() ); } ftpSession.Disconnect();-->

RetrieveData methodSyntax FTP.RetrieveData( remoteFileName [, transferType] )

Description Retrieves data from the FTP server and turns it into a DynaScript variable.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.

207

Page 228: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

FTP methods

he

l.

Example This example retrieves data from a file on an FTP server and displays the value:

<!--SCRIPT ftpSession = new FTP ("ftpserv", "anonymous", "[email protected]"); lname = ftpSession.RetrieveData("putdata.ssc"); document.WriteLn("last name: " + lname); ftpSession.Disconnect();-->

RetrieveDirectoryListing methodSyntax 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.

Example This example displays a directory listing for the FTP server:

<!--SCRIPT ftpSession = new FTP ("ftpserv", "anonymous", "[email protected]"); dir = ftpSession.RetrieveDirectoryListing(); document.WriteLn("The FTP directory listing is: " + dir); ftpSession.Disconnect();-->

RetrieveDocument methodSyntax 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 tdocument. The default is <inherited>.

• transferType Can be one of ASCII, binary, EBCDIC, image, or locaThe default is binary.

208

Page 229: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

e

l.

al

• 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", "[email protected]"); if( !ftpSession.RetrieveDocument("test.ssc", "test_returned.ssc")) { document.writeln( ftpSession.GetErrorCode() ); document.writeln( ftpSession.GetErrorInfo() ); } ftpSession.Disconnect();-->

RetrieveFile methodSyntax FTP.RetrieveFile( remoteFileName, localFileName [, transferType,

failIfLocalFileExists] )

Description Retrieves a file from the FTP server and saves it to the local machine. Thparameters 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 locaThe 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 locmachine:

<!--SCRIPT ftpSession = new FTP ("ftpserv", "anonymous", "[email protected]"); if( !ftpSession.RetrieveFile( "test.txt", "g:\\Dynamo\\Ftp\\test.txt" )) {

209

Page 230: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

The Function object

l.

t to a

document.writeln( ftpSession.GetErrorCode() ); document.writeln( ftpSession.GetErrorInfo() ); } ftpSession.Disconnect();-->

RetrieveFileWithAppend methodSyntax 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.

• transferType Can be one of ASCII, binary, EBCDIC, image or locaThe default is binary.

Return Boolean.

Example This example retrieves a file from the FTP server and appends the contenfile called test.txt that already exists on the local machine:

<!--SCRIPT ftpSession = new FTP ("ftpserv", "anonymous", "[email protected]"); if( !ftpSession.RetrieveFileWithAppend( "test.txt", "g:\\Dynamo\\Ftp\\test.txt" )) { document.writeln( ftpSession.GetErrorCode() ); document.writeln( ftpSession.GetErrorInfo() ); } ftpSession.Disconnect();-->

The Function objectObject Enables the creation of functions.

Standard: ECMAScript

210

Page 231: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

Syntax To use a Function property:

Function.propertyName

To use a Function method:

Function.MethodName( parameter )

Description The function constructor can be used to create a function on the fly:

funcName = new Function( [[parameter1 [, parameter2...]], body] );

The function keyword can also be used to create a function, in which case the function is not created until it has been called from somewhere else in the script:

function funcName ( [parameter1 [, parameter2...]], ) {

body

}

Example This example creates two Function objects called square and square1 and executes them:

<!--SCRIPT // function created with a constructor square = new Function( "number", "return number * number;" ); // function created with the keyword function square1 ( number) { return number * number } document.writeln( square(5) ); document.writeln( square1(5) );-->

Function propertiesThe Function object has this property:

length propertySyntax Function.length

Attributes This property is read-only.

211

Page 232: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Function methods

ithin

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) );-->

Function methodsThe Function object has this method:

toString methodSyntax 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() );-->

java objectObject Allows for manipulation of Java classes within PowerDynamo scripts.

The java object represents an object used for working with a Java class wyour Web site.

Syntax To use a java method:

java.MethodName( parameter )

212

Page 233: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

ft ava.

t ables

l, the

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 MicrosoVM. You must select one of these VMs for PowerDynamo to support J

• Java class cache size To improve performance, information abouthe methods and properties of Java classes is cached. This option enyou to set the cache size.

• Class path for the mapping You must specify a path for class filesthat are stored in a Dynamo Web site.

Executing from within Sybase CentralTo execute scripts that use the Java object from within Sybase Centramapping and Dynamo site name must be the same.

For more information on PowerDynamo configuration settings in Sybase Central, see “Changing Dynamo configuration settings” in the PowerDynamo User’s Guide.

You must specify all parameters when you are working with the java object. Unlike other DynaScript objects, an error occurs if parameters are excluded when calling a Java class method or property.

Accessing Java methods and propertiesYou can access methods from any Java class. Properties, however, can be accessed only from JavaBeans.

Example Let’s assume we are working with this class:

class Fibonacchi{ public long prev1; public long prev; public long next; public long getPrev() { return prev; } public long getNext() { return next; }

public Fibonacchi() {

213

Page 234: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

java methods

prev1 = 1; prev = 0; next = 0; }

public void generateNext() { next = prev1 + prev; prev = prev1; prev1 = next; } static public double doubleme( double t ) { return t*2; }}

To call this class, your script might look something like this:

// call a static method on the classresult = java.CallStaticMethod( "Fibonacchi", "doubleme", 2.5 );document.writeln( result );// create a DynaScript object representing a Java classfib = java.CreateObject( "Fibonacchi" );// retrieve a property on the classdocument.writeln( "The value of next is " + fib.next + " The value of prev is " + fib.prev );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 );}

For more information on using Java in your PowerDynamo scripts see “PowerDynamo and Java” in PowerDynamo User’s Guide.

java methodsThe java object has these methods:

214

Page 235: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

ent

tubs.

tub

the

CreateComponent methodSyntax 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 componon 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 canspecify a Java package other than the default, in which to store the sIf this is the case, when the component is later being created by DynaScript, the location of the stubs must be specified. To specify a slocation 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 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", "iiop://localhost:9000", "Jagadmin", "", " com/sybase/jaguar/sample/svu/SVUMetaData" );

If however, you used the default value when generating stubs for the SVUpackage, your syntax would look like the following:

java.CreateComponent( "SVU/SVUMetaData" );

215

Page 236: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

java methods

Setting the Java VMThe Java VM configuration option must be set to the Sun VM for scripts with this method to execute. Change the VM option using the Configuration\Default General Settings\Java VM folder in Sybase Central.

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.

site.GetErrorInfo( )The site.GetErrorInfo( ) method may be used for retrieving error information.

See also “Calling Jaguar Component Methods from PowerDynamo” in the PowerDynamo User’s Guide.

216

Page 237: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

CreateObject methodSyntax 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.

Setting the Java VMThe Java VM configuration option must be set to the Sun VM for scripts with this method to execute. Change the VM option using the Configuration\Default General Settings\Java VM folder in Sybase Central.

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.

<!--SCRIPTfib = java.CreateObject( "Fibonacchi" );// retrieve a property on the classdocument.writeln( "The value of next is " + fib.next + " The value of prev is " + fib.prev );// set a property on the classfib.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 );}-->

See also “PowerDynamo and Java” in the PowerDynamo User’s Guide.

CallStaticMethod methodSyntax 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:

217

Page 238: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

java methods

ing

as

ger.

• 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.

<!--SCRIPTresult = java.CallStaticMethod("Fibonacchi", "doubleme", 2.5);document.writeln( result );

-->

See also “PowerDynamo and Java” in PowerDynamo User’s Guide

GetHomeInterface methodSyntax 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>

• server-context – The root naming context for the server where the component is installed. server-context is optional and necessary onlyif a root naming context has been set for the server. The root namcontext can also be given as the initial context in the provider_url.

• package – The Jaguar package to which the component belongs, displayed in Jaguar Manager.

• component – The component name, as displayed in Jaguar Mana

218

Page 239: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

d

rves

ou

en d

a

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 isassumed to be relative to this initial name context. For example, if theprovider_url parameter is set to iiop://localhost:9000/USA/Sybase, anyour 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 nameserver. 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 seas 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 yspecify USA/Sybase/, then the component_name parameter is assumed to be relative to this location in the name hierarchy. Whspecifying the initial context, the trailing slash is optional; it is addeautomatically if you do not specify an initial context that ends withslash.

• 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.

219

Page 240: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

java methods

rves

The password parameter is optional and default is no password.

Note The Dynamo methods GetHomeInterface and GetUserTransaction enable access to EJB interfaces of Jaguar components.

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

Example Use java.GetHomeInterface to create an instance of the EJBHome interface for the component Test/Cart. Then use the Home interface to create an actual instance of Test/Cart.

carthomeObj = java.GetHomeInterface("CartPackage/Cart")

cartObj = carthomeObj.create("John", "7506");

cartObj.addItem(66)

cartObj.addItem(22)

cartObj.purchase()

carthomeObj.remove(...)

See also “PowerDynamo and Java” in the PowerDynamo User’s Guide.

GetUserTransaction methodSyntax 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 seas the name server for your application.

• iiop-port Is the IIOP port number for the server.

220

Page 241: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

ou are en d

a

st”,

• initial-context Is the optional initial naming context, which can be used to set a default prefix for name resolution. For example, if yspecify USA/Sybase/, all names that you resolve with the contextassumed to be relative to this location in the name hierarchy. Whspecifying the initial context, the trailing slash is optional; it is addeautomatically if you do not specify an initial context that ends withslash.

• user_id The user name for the Jaguar session. If authorization is enabled for your Jaguar server this optional parameter, which defaults to “gueis used to authorize access to Jaguar components.

• password The password for the Jaguar session. If authorization is enabled for your Jaguar server, this optional parameter, which defaults to no password, is used to authorize access to Jaguar components.

Note The Dynamo methods GetHomeInterface and GetUserTransaction enable access to EJB interfaces of Jaguar components.

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

Comments The components that participate in the transaction managed with the UserTransaction object must be in the same server as the UserTransaction object, which cannot be assumed if a Jaguar cluster is used to ensure that this requirement is met:

1 Use the same name server to create the UserTransaction object that was used when creating the component instances. That is, supply the same provider_url to GetUserTransaction() and GetHomeInterface(), CreateComponent(). The initial-context values of the URLs can differ.

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.

221

Page 242: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

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")

222

Page 243: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

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.

mailList objectObject Represents a list of mail pieces on a POP3 server.

Syntax To use a mailList property:

mailList.propertyName

To use a mailList method:

mailList.MethodName( parameter )

Description The mailList object is used to retrieve a list of the mail pieces on a POP3 server. The list, once returned, contains enough information for the user to sort through and select particular mail pieces for full retrieval.

To create a preview list of incoming mail piece objects, use the mailList constructor. The syntax to create a new mailList object is:

mailListObj = new MailList( popServer, popUser, popPassword, fullUserName [, useAPOP] );

The parameters are:

223

Page 244: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

mailList properties

e

lmo. f the

• popServer The name of the POP3 server.

• popUser The user ID for the POP3 server.

• popPassword The password for the POP3 server.

• fullUserName The full mail address.

• useAPOP If true, specifies that the POP3 APOP command should be used to log on to the POP3 server. If false, the POP3 commands USER and PASS are used – this causes your password to be sent as clear text. Thdefault is true.

Example This example returns a list of the mail pieces that are waiting for the user eThe list indicates where the message was sent from and the subject line omessage:

<!--SCRIPT mlist = new MailList ("mail.sybase.com", "elmo", "secret", "[email protected]");for ( i in mlist) { inPiece=mlist[i] document.writeln(inPiece.from); document.writeln(inPiece.subject);}-->

See also “mailPiece object (incoming)” on page 227.

“mailPiece object (outgoing)” on page 238.

“attachment object” on page 80.

mailList propertiesThe mailList object has this property:

count propertySyntax mailList.count

Attributes This property is read-only.

Description The number of messages in the mail list.

Return Integer.

224

Page 245: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

d

Example This example displays the number of messages in the mail list.

<!--SCRIPTmlist = new MailList ("mail.sybase.com", "elmo", "secret", "[email protected]");document.WriteLn(mlist);document.WriteLn("There are " + mlist.count + " messages in the mail list");-->

See also “mailPiece object (incoming)” on page 227.

“mailPiece object (outgoing)” on page 238.

mailList methodsThe mailList object has these methods:

Disconnect methodSyntax mailList.Disconnect( [deleteMarkedPieces] )

Description Disconnects from the mail server. The optional parameter deleteMarkedPieces indicates whether or not mail pieces marked for deletion should be deletefrom 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", "[email protected] ");if( !mlist.Disconnect() ) { document.writeln( mlist.GetErrorCode() ); document.writeln( mlist.GetErrorInfo() );}-->

See also “mailPiece object (incoming)” on page 227.

“mailPiece object (outgoing)” on page 238.

225

Page 246: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

mailList methods

GetErrorCode methodSyntax 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", "[email protected] ");if( !mlist.Disconnect() ) { document.writeln( mlist.GetErrorCode() ); document.writeln( mlist.GetErrorInfo() );}

document.WriteLn(mlist);-->

See also “mailList object” on page 223

“mailPiece object (incoming)” on page 227

“mailPiece object (outgoing)” on page 238

GetErrorInfo methodSyntax 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", "[email protected] " );if( !mlist.Disconnect() ) { document.writeln( mlist.GetErrorCode() ); document.writeln( mlist.GetErrorInfo() );}

226

Page 247: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

eld ts

You ail

ody,

-->

See also “mailPiece object (incoming)” on page 227.

“mailPiece object (outgoing)” on page 238.

mailPiece object (incoming)Object This object is a mail piece received by a specific recipient which is being h

on a mail server. The mailList object is a list of incoming mail piece objecrepresenting mail accessible via a POP3 server.

Syntax To use an incoming mail piece property:

mailPiece.propertyName

To use an incoming mail list method:

mailPiece.MethodName( parameter )

Description Each incoming mail piece is represented by an incoming mail piece object.can manipulate the object to display the different parts of the incoming mpiece.

Example This example retrieves a mail piece (mlistitem) and displays its subject, band attachments:

<!--SCRIPT mlist = new MailList ("mail.sybase.com", "elmo", "secret", "[email protected] ");mlistitem = mlist[1];mlistitem.Retrieve();document.WriteLn( mlistitem.subject );document.WriteLn( mlistitem.body );document.WriteLn( mlistitem.attachments );mlist.Disconnect();-->

See also “attachment object” on page 80.

“mailList object” on page 223.

“mailPiece object (outgoing)” on page 238.

“recipient object” on page 267.

227

Page 248: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

mail piece properties (incoming)

ble

mail piece properties (incoming)The incoming mail piece object has these properties:

attachments propertySyntax 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", "[email protected]"); 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 223.

body propertySyntax mailPiece.body

Attributes This property is read-only.

Description The body or content text of the incoming mail piece. This property is availaonly 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", "[email protected]"); mlistitem = mlist[1];

228

Page 249: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

om the

mlistitem.Retrieve(); document.WriteLn( mlistitem.body ); mlist.Disconnect();-->

See also “mailList object” on page 223.

“mailPiece object (outgoing)” on page 238.

from propertySyntax 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", "[email protected]"); mlistitem = mlist[4]; document.WriteLn( mlistitem.from ); mlist.Disconnect();-->

See also “mailList object” on page 223.

headers propertySyntax mailPiece.headers

Attributes This property is read-only.

Description The ARPA message headers. These are the unprocessed header fields frmail piece.

Return String.

Example This example displays the headers:

<!--SCRIPT mlist = new MailList ("mail.sybase.com", "elmo", "dynamo", "[email protected]"); mlistitem = mlist[4];

229

Page 250: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

mail piece properties (incoming)

nt ed

document.WriteLn( mlistitem.headers ); mlist.Disconnect();-->

See also “mailList object” on page 223.

“mailPiece object (outgoing)” on page 238.

recipients propertySyntax 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", "[email protected] "); mlistitem=mlist[2]; mlistitem.Retrieve(); for (i in mlistitem.recipients ){ document.WriteLn(mlistitem.recipients[i]); } mlist.Disconnect();-->

See also “mailList object” on page 223.

“mailPiece object (outgoing)” on page 238.

replyTo propertySyntax mailPiece.replyTo

Attributes This property is read-only.

Description Who the recipient of the mail piece should reply to. This is a list of recipieobjects. If this field exists, the reply method responds to the recipients listhere instead of to addresses specified in the from field.

Return List of recipient objects.

230

Page 251: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

the

by a

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", "[email protected] "); mlistitem=mlist[2]; mlistitem.Retrieve(); for (i in mlistitem.replyTo ){ document.WriteLn(mlistitem.replyTo[i]); } mlist.Disconnect();-->

See also “mailList object” on page 223

“mailPiece object (outgoing)” on page 238

sender propertySyntax mailPiece.sender

Attributes This property is read-only.

Description The address from where the mail piece was sent. This is not necessarily same address as the from field (in the case where a mail piece has beenredirected).

Return String.

Example This example indicates if the mail piece was sent directly by the author or “sender”:

<!--SCRIPT mlist = new MailList ("mail.sybase.com", "elmo", "dynamo", "[email protected] "); 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"); }

231

Page 252: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

mail piece properties (incoming)

mlist.Disconnect();-->

See also “mailList object” on page 223.

“mailPiece object (outgoing)” on page 238.

size propertySyntax 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", "[email protected]"); mlistitem = mlist[9]; mlistitem.Retrieve(); document.WriteLn( "size: " + mlistitem.size ); mlist.Disconnect();-->

See also “mailList object” on page 223

“mailPiece object (outgoing)” on page 238

subject propertySyntax 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", "[email protected]"); mlistitem = mlist[1];

232

Page 253: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

the

document.WriteLn( mlistitem.subject ); mlist.Disconnect();-->

See also “mailList object” on page 223

“mailPiece object (outgoing)” on page 238

mail piece methods (incoming)The incoming mail piece object has these methods:

Delete methodSyntax mailPiece.Delete( )

Description Marks a mail piece for deletion. The mail piece is not actually deleted untilPOP3 server is disconnected.

Return Boolean.

Example This example marks a mail piece for deletion:

<!--SCRIPT mlist = new MailList ("mail.sybase.com", "elmo", "dynamo", "[email protected]"); for (i in mlist) { inPiece = mlist[i]; inPiece.Retrieve(); document.WriteLn(inPiece.body); inPiece.Delete(); }-->mlist.Disconnect();

See also “mailList object” on page 223.

“mailPiece object (outgoing)” on page 238.

Forward methodSyntax mailPiece.Forward( userName [, includeAttachments] )

233

Page 254: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

mail piece methods (incoming)

e in

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.

Setting the smtpHostYou must either set the smtpHost property or specify a default for it in Sybase Central before you can forward a message using this method.

Return Outgoing mail piece object.

Example This example forwards a piece of mail:

<!--SCRIPT mlist = new MailList ("mail.sybase.com", "elmo", "dynamo", "[email protected]"); mlistitem = mlist[0]; mlistitem.Retrieve(); forwardmp = mlistitem.Forward("[email protected]") document.writeln(forwardmp.body); forwardmp.body = ( "Please review this mail piece " + forwardmp.body ); forwardmp.Send();-->

See also “mailList object” on page 223.

“mailPiece object (outgoing)” on page 238.

GetErrorCode methodSyntax mailPiece.GetErrorCode( )

Description Returns a code representing the most recently generated error. The errorgenerated will either be a three-digit POP3 reply code or a three-digit codthe 900 range generated by Dynamo.

Return Integer.

Example This example checks that the send method was completed successfully:

234

Page 255: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

er a

<!--SCRIPT mlist = new MailList ("mail.sybase.com", "elmo", "dynamo", "[email protected]"); mlistitem = mlist[0]; mlistitem.Retrieve(); forward = mlistitem.Forward("[email protected]"); if( !forward.Send() ) { document.writeln( forward.GetErrorCode() ); document.writeln( forward.GetErrorInfo() ); }-->

See also “mailList object” on page 223.

“mailPiece object (outgoing)” on page 238.

GetErrorInfo methodSyntax mailPiece.GetErrorInfo( )

Description Returns a string containing an error message. The error generated is eithreply 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", "[email protected]"); mlistitem = mlist[0]; mlistitem.Retrieve(); forward = mlistitem.Forward("[email protected]"); if( !forward.Send() ) { document.writeln( forward.GetErrorCode() ); document.writeln( forward.GetErrorInfo() ); }-->

See also “mailList object” on page 223.

“mailPiece object (outgoing)” on page 238.

Redirect methodSyntax mailPiece.Redirect( userName )

235

Page 256: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

mail piece methods (incoming)

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.

Setting the smtpHostYou must either set the smtpHost property or specify a default for it in Sybase Central before you can forward a message using this method.

Return Outgoing mail piece object.

Example This example retrieves a mail piece and then redirects it to another user:

<!--SCRIPT mlist = new MailList ("mail.sybase.com", "elmo", "dynamo", "[email protected]"); mlistitem = mlist[0]; mlistitem.Retrieve(); mp = mlistitem.Redirect("[email protected]"); if( !mp.Send() ) { document.writeln( mp.GetErrorCode() ); document.writeln( mp.GetErrorInfo() ); }-->

See also “mailList object” on page 223.

“mailPiece object (outgoing)” on page 238.

Reply methodSyntax 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.

236

Page 257: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

e

o ult

ase

d to

al. you

• includeOriginal Can be true or false. If true, the original mail piecbody is included in the body of the outgoing mail piece. The default isfalse.

• includeAttachments Can be true or false. If true, all attachments tthe original mail piece are included in the outgoing mail piece. The defais false.

Setting the smtpHostYou must either set the smtpHost property or specify a default for it in SybCentral before you can forward a message using this method.

Return Outgoing mail piece object.

Example This example retrieves and replies to a mail piece.

<!--SCRIPT mlist = new MailList ("mail.sybase.com", "elmo", "dynamo", "[email protected]");mlistitem = mlist[8];mlistitem.Retrieve();replymp = mlistitem.Reply( "all", true );replymp.body = replymp.body +"This is the body of the reply mail piece. It should be appended to the original mail piece body"; replymp.Send();-->

See also “mailList object” on page 223.

“mailPiece object (outgoing)” on page 238.

Retrieve methodSyntax mailPiece.Retrieve( [deleteFromServer] )

Description Retrieves the full mail piece from the POP3 server. You must be connectethe POP3 mail server to use this method. The deleteFromServer parameter specifies whether to mark the retrieved mail piece for deletion after retrievThe deleteFromServer parameter may be set to true or false. The default isfalse. If set to true, the marked mail piece is deleted from the server oncedisconnect from the POP3 server.

Return Boolean.

Example This example retrieves a mail piece:

237

Page 258: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

mailPiece object (outgoing)

t

t or

<!--SCRIPT mlist = new MailList ("mail.sybase.com", "elmo", "dynamo", "[email protected] ");num = mlist.countdocument.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 223

“mailPiece object (outgoing)” on page 238

mailPiece object (outgoing)Object Represents a mail piece that is to be sent via SMTP.

Syntax To use a mailPiece property:

mailPiece.propertyName

To use a mailPiece method:

mailPiece.MethodName( parameter )

Description Use the mailPiece constructor to create an outgoing mail piece object tharepresents a piece of outgoing mail. The syntax is:

mailPiece = new MailPiece( );

You can also create outgoing mail pieces by calling the Forward, RedirecReply method on an incoming mail piece object.

Example This example creates and sends a simple mail piece with an attachment:

mp = new MailPiece();mp.subject = "This is my subject text";mp.from = "[email protected]";mp.body = "This is my mail piece body.";mp.smtpHost = "mail.sybase.com";

mp.AddRecipient( "[email protected]");mp.AttachDocument( "attachment.gif" );if( !mp.Send() ) { document.writeln( mp.GetErrorCode() ); document.writeln( mp.GetErrorInfo() );

238

Page 259: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

set

}

See also “attachment object” on page 80

“mailPiece object (incoming)” on page 227

“mailList object” on page 223

“recipient object” on page 267

mailPiece properties (outgoing)The mailPiece object has these properties:

body propertySyntax mailPiece.body

Attributes This property is read/write.

Description The body text of the mail piece.

Binary dataBinary data must be sent as an attachment.

Example This example creates an outgoing mail piece. It is assumed that you havethe smtpHost from within Sybase Central:

<!--SQL mp = new MailPiece(); mp.subject = "Example of the body property"; mp.from = "[email protected]"; mp.body = "This is the body of the outgoing mail piece."; mp.AddRecipient( "[email protected]" ); if( !mp.Send() ) { document.writeln( mp.GetErrorCode() ); document.writeln( mp.GetErrorInfo() ); }-->

See also “attachment object” on page 80.

“mailPiece object (incoming)” on page 227.

239

Page 260: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

mailPiece properties (outgoing)

be a

the s so

“mailList object” on page 223.

“recipient object” on page 267.

from propertySyntax mailPiece.from

Attributes This property is read/write.

Description The address from where the mail piece is being sent. This address must valid Internet mail user name in canonical form.

Example This example sends a piece of e-mail to a specific address depending oninput given by the user. The user must also enter their own e-mail addresthe 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.

<p>Select the product that you require help for:<FORM METHOD=POST ACTION=’mailsend.ssc’><OL><LI><INPUT TYPE=’radio’ Name="product" Value="Product A">Product A<LI><INPUT TYPE=’radio’ Name="product" Value="Product B">Product B<LI><INPUT TYPE=’radio’ Name="product" Value="Product C">Product C<LI><INPUT TYPE=’radio’ Name="product" Value="Product Other">Product Other</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>

240

Page 261: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

From a browser, the form would look something like this:

Following is the script (mailsend.ssc) that is called to process the information entered on the form:

<HTML><BODY><!--SCRIPT mailsend.ssc product = document.value.product from = document.value.from body = document.value.body mp = new MailPiece(); switch( product ) { case "Product A": mp.AddRecipient("[email protected]"); break; case "Product B": mp.AddRecipient("[email protected]"); break; case "Product C": mp.AddRecipient("[email protected]");

241

Page 262: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

mailPiece properties (outgoing)

han anted

break; case "Product Other": mp.AddRecipient("[email protected]"); break; }

mp.subject = "Mail Piece Example"; mp.from = from; mp.body = body;

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 80.

“mailPiece object (incoming)” on page 227.

“mailList object” on page 223.

“recipient object” on page 267.

sender propertySyntax mailPiece.sender

Attributes This property is read/write.

Description You can use this property if a mail piece is sent from a destination other tthat of the person who the message is from. For example, if an assistant wto 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 = "[email protected]"; mp.sender = "[email protected]"; mp.AddRecipient( "[email protected]" );

242

Page 263: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

ail

nt.

mp.subject = "Request for comment"; mp.body = "Your input is needed immediately"; mp.Send();-->

See also “attachment object” on page 80.

“mailPiece object (incoming)” on page 227.

“mailList object” on page 223.

“recipient object” on page 267.

smtpHost propertySyntax mailPiece.smtpHost

Attributes This property is read/write.

Description Specifies the name of the host to be used as a gateway for sending the mpiece. If this value is empty, the value of smtpHost in the PowerDynamo Configuration folder is used as the gateway. If the smtpHost has not beenspecified in Sybase Central or the document, the mail piece will not be se

For information on setting the smtpHost in Sybase Central see “ChangingDynamo configuration settings” in the PowerDynamo User’s Guide.

Example This example sets the smtpHost as mailsrv.sybase.com:

<!--SCRIPT mp = new MailPiece(); mp.from = "[email protected]"; mp.sender = "[email protected]"; mp.AddRecipient( "[email protected]" ); 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 80.

“mailPiece object (incoming)” on page 227.

“mailList object” on page 223.

“recipient object” on page 267.

243

Page 264: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

mailPiece methods (outgoing)

body propertySyntax mailPiece.body

Attributes This property is read/write.

Description The body text of the mail piece.

Binary dataBinary data must be sent as an attachment.

Example This example creates a simple outgoing mail piece:

<!--SCRIPTmp = new MailPiece();mp.from = "[email protected]";mp.AddRecipient( "[email protected]" );mp.subject = "Request for comment";mp.body = "Your input is needed immediately";mp.Send();-->

See also “attachment object” on page 80.

“mailPiece object (incoming)” on page 227.

“mailList object” on page 223.

“recipient object” on page 267.

mailPiece methods (outgoing)The mailPiece object has these methods:

AddRecipient methodSyntax mailPiece.AddRecipient( userName [, userMode] )

Description Specifies the address or addresses where a mail piece is to be sent. Theparameters are:

• userName The e-mail address of the recipient.

• userMode Identifies the type of delivery.

Mode can be one of:

244

Page 265: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

ing

• 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 dependon 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.

<p>Select the product that you require help for:<FORM METHOD=POST ACTION=’mailsend.ssc’><OL><LI><INPUT TYPE=’radio’ Name="product" Value="Product A">Product A<LI><INPUT TYPE=’radio’ Name="product" Value="Product B">Product B<LI><INPUT TYPE=’radio’ Name="product" Value="Product C">Product C<LI><INPUT TYPE=’radio’ Name="product" Value="Product Other">Product Other</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:

this is the script (mailsend.ssc) to process information entered on the form:

<HTML><BODY><!--SCRIPT mailsend.ssc product = document.value.product from = document.value.from

245

Page 266: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

mailPiece methods (outgoing)

body = document.value.body mp = new MailPiece(); switch( product ) { case "Product A": mp.AddRecipient("[email protected]"); break; case "Product B": mp.AddRecipient("[email protected]"); break; case "Product C": mp.AddRecipient("[email protected]"); break; case "Product Other": mp.AddRecipient("[email protected]"); break; }

246

Page 267: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

piece

mp.subject = "Mail Piece Example"; mp.from = from; mp.body = body;

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 80.

“mailPiece object (incoming)” on page 227.

“mailList object” on page 223.

“recipient object” on page 267.

AddReplyTo methodSyntax mailPiece.AddReplyTo( userName )

Description Adds an address to the list of addresses from which responses to this mailare directed.

Return Boolean.

Example This mail piece, when replied to, will be sent to elmo and elmojr:

<!--SCRIPTmp = new MailPiece();mp.from = "[email protected]";mp.AddReplyTo = "[email protected]";mp.AddRecipient( "[email protected]" );mp.subject = "Request for comment";mp.body = "Your input is needed immediately";mp.Send();-->

See also “attachment object” on page 80.

“mailPiece object (incoming)” on page 227.

“mailList object” on page 223.

247

Page 268: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

mailPiece methods (outgoing)

ail

rom

“recipient object” on page 267.

AttachData methodSyntax mailPiece.AttachData( data [,MIMEtype, description] )

Description Attaches a piece of data (typically held in a DynaScript variable) to the mpiece.

Return Boolean.

Example This example attaches a piece of data to the mail piece after retrieving it fthe database:

<!--SCRIPT myQuery = connection.CreateQuery( "select data from ImageTable where name = ’muppets’" ); myQuery.MoveNext(); imageData = myQuery.GetValue(1); mp = new MailPiece(); mp.from = "[email protected]"; mp.AddRecipient( "[email protected]" ); 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();-->

See also “mailPiece object (incoming)” on page 227.

“mailList object” on page 223.

“recipient object” on page 267.

“AttachDocument method” on page 248.

“AttachFile method” on page 249.

AttachDocument methodSyntax mailPiece.AttachDocument( documentName )

Description Attaches a document in a PowerDynamo Web site to the mail piece.

Return Boolean.

248

Page 269: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

Example This example attaches a document called muppets.gif to the mail piece object:

<!--SCRIPT mp = new MailPiece(); mp.from = "[email protected]"; mp.AddRecipient( "[email protected]" ); 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 80.

“mailPiece object (incoming)” on page 227.

“mailList object” on page 223.

“recipient object” on page 267.

“AttachData method” on page 248.

“AttachFile method” on page 249.

AttachFile methodSyntax mailPiece.AttachFile( filePath )

Description Attaches a file from the file system to the mail piece.

Return Boolean.

Example This example attaches a system file called autoexec.bat to the mail piece object:

<!--SCRIPTmp = new MailPiece();mp.from = "[email protected]";mp.AddRecipient( "[email protected]" );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 80.

249

Page 270: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

mailPiece methods (outgoing)

r is e

“mailPiece object (incoming)” on page 227.

“mailList object” on page 223.

“recipient object” on page 267.

“AttachData method” on page 248.

“AttachDocument method” on page 248.

GetErrorCode methodSyntax mailPiece.GetErrorCode( )

Description Returns a code representing the most recent error that occurred. The erroeither a three-digit SMTP reply code or a three-digit code in the 900 ranggenerated by PowerDynamo.

Return Integer.

Example This example sends a piece of mail and then checks for errors:

<!--SCRIPT mp = new MailPiece(); mp.from = "[email protected]"; mp.AddRecipient( "[email protected]" ); 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 227.

“mailList object” on page 223.

“GetErrorInfo method” on page 250.

GetErrorInfo methodSyntax mailPiece.GetErrorInfo( )

250

Page 271: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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 = "[email protected]"; mp.AddRecipient( "[email protected]" ); 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 227.

“mailList object” on page 223.

“GetErrorCode method” on page 250.

Send methodSyntax mailPiece.Send( userName )

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 = "[email protected]"; mp.AddRecipient( "[email protected]" ); mp.subject = "Request for comment"; mp.body = "Your input is needed immediately"; mp.Send();-->

See also “mailPiece object (incoming)” on page 227.

251

Page 272: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Math object

for , we t.

ts:

“mailList object” on page 223.

“GetErrorCode method” on page 250.

“GetErrorInfo method” on page 250.

Math objectObject The Math object provides basic Math functionality to users.

Standard: ECMAScript

Syntax To use a Math property:

Math.propertyName

To use a Math method:

Math.MethodName( parameter )

Description The Math object provides basic math functionality in your PowerDynamo script or template.

The Math object is provided as a built-in object. There are no constructorscreating instances of a Math object. When referring to Math in this chapterare referring to the built-in Math object, not an instance of the Math objec

Example This example uses the pow method of the Math object and displays the resul

<!--SCRIPT ans = Math.pow( 4, 3 ); document.WriteLn(ans)-->

Math propertiesThe Math object has these properties:

E propertySyntax Math.E

Attributes This property is read-only.

252

Page 273: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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 propertySyntax 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 propertySyntax Math.LN10

Attributes This property is read-only.

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 );-->

253

Page 274: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Math properties

LOG2E propertySyntax 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 propertySyntax 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 );-->

PI propertySyntax 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:

254

Page 275: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

<!--SCRIPT a = Math.PI; document.WriteLn( a );-->

SQRT1_2 propertySyntax 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 propertySyntax 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:

<!--SCRIPT a = Math.SQRT2; document.WriteLn( a );-->

Math methodsThe Math object has these methods:

255

Page 276: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Math methods

abs methodSyntax 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 methodSyntax 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 methodSyntax 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 ) );-->

atan methodSyntax Math.atan( num )

Description Returns the arc tangent of a number.

256

Page 277: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

Return Floating point.

Example This example displays the arc tangent of .43:

<!--SCRIPT document.WriteLn( Math.atan( .43 ) );-->

atan2 methodSyntax 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 methodSyntax 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 ) );-->

cos methodSyntax Math.cos( num )

257

Page 278: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Math methods

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 methodSyntax 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 methodSyntax 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 ));-->

log methodSyntax Math.log( num )

Description Returns the natural logarithm of a number.

258

Page 279: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

Return Floating point.

Example This example displays the logarithm of the number 6:

<!--SCRIPT document.WriteLn( Math.log( 6 ) );-->

max methodSyntax 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 methodSyntax 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 x = 7.543643; y = 7.954854345; minValue = Math.min( x, y ); document.WriteLn( minValue );-->

259

Page 280: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Math methods

pow methodSyntax 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 methodSyntax 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 methodSyntax Math.round( num )

Description Returns the supplied number, rounded to the nearest integer.

Return Integer.

Example This example rounds the number 54.354 to the nearest integer:

<!--SCRIPT document.WriteLn( Math.round( 54.354 ) );-->

260

Page 281: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

sin methodSyntax 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 methodSyntax 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 methodSyntax Math.tan( num )

Description Returns the tangent of a number.

Return Floating point

Example This example displays the tangent of 43:

<!--SCRIPT document.WriteLn( Math.tan( 43 ) );-->

Number objectObject Enables you to use methods and obtain properties on a number.

261

Page 282: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Number properties

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 );-->

Number propertiesThe Number object has these properties:

MAX_VALUE propertySyntax Number.MAX_VALUE

Attributes This property is read-only.

262

Page 283: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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 propertySyntax 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 propertySyntax Number.NaN

Attributes This property is read-only.

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 );-->

263

Page 284: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Number methods

NEGATIVE_INFINITY propertySyntax 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 propertySyntax 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 );-->

Number methodsThe Number object has these methods:

toString methodSyntax 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.

264

Page 285: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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 methodSyntax 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 );-->

Object objectObject 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.

265

Page 286: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Object methods

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));-->

Object methodsThe Object object has these methods:

toString methodSyntax 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() );-->

266

Page 287: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

valueOf methodSyntax 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() );-->

recipient objectObject 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:

<!--SCRIPTmlist = new MailList ("mail.sybase.com", "elmo", "dynamo", "[email protected]");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 230.

“attachment object” on page 80.

“mailList object” on page 223.

267

Page 288: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

recipient properties

ce:

“mailPiece object (incoming)” on page 227.

“mailPiece object (outgoing)” on page 238.

recipient propertiesThe recipient object has these properties:

mode propertySyntax 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 pie

<!--SCRIPTmlist = new MailList ("mail.sybase.com", "elmo", "dynamo", "[email protected]");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 223.

“mailPiece object (incoming)” on page 227.

“mailPiece object (outgoing)” on page 238.

268

Page 289: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

mo

by

name propertySyntax recipient.name

Attributes This property is read-only.

Description The name of the recipient for a mail piece.

Return String.

Example This example checks the name and mode of the recipients of the mail piece:

<!--SCRIPTmlist = new MailList ("mail.sybase.com", "elmo", "dynamo", "[email protected]");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 223.

“mailPiece object (incoming)” on page 227.

“mailPiece object (outgoing)” on page 238.

query objectObject Provides a scriptable way to work with a SQL query embedded in a Dyna

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 queryworking with the query object of the same name.

269

Page 290: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

query object

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><!--SQLselect id, name, size, color, quantity, unit_price from product

-->

<!--SCRIPTthisColumnCount = SQL.GetColumnCount();

// Mark the start of the tabledocument.Write( "<TABLE BORDER ><TR>" );

// Write out table titlesfor ( iCol=1 ; iCol<=thisColumnCount ; iCol++ ) {

document.Write( "<TH>" +

270

Page 291: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

SQL.GetColumnLabel( iCol ) + "</TH>");} document.WriteLn( "</TR>" );

// Write out table valueswhile( SQL.MoveNext() ) {

for ( iCol = 1; iCol <= thisColumnCount; iCol++ ) {document.Write( "<TD>" + SQL.GetValue( iCol ) +

"</TD>" );}document.WriteLn( "</TR>" );

//Mark the end of the tabledocument.WriteLn( "</TABLE>" );--></BODY></HTML>

This query has the default name SQL; Columns and rows are numbered starting at 1.

• The HTML table tags used in this example are:

• <TABLE> and </TABLE> mark the start and end of the table.

• <TR> and </TR> mark the start and end of a table row.

• <TH> and </TH> mark the start and end of a table heading cell.

• <TD> and </TD> mark the start and end of a table data cell.

• The while statement is used to loop over the rows of the table.

• The for statement is used to loop over the columns of each row.

query propertiesThe query object has this property:

connection propertySyntax query.connection

Attributes This property is read-only.

Description The connection object used to execute the query.

271

Page 292: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

query properties

ft

ts

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 );-->

See also “connection object” on page 87.

“CreateQuery method” on page 99.

cursorType propertySyntax query.cursorType

Description Use this property when you are executing stored procedures in a MicrosoSQL 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 sefrom a Microsoft SQL Server database:

<!--SCRIPT MSSQL_MultiStatement.ssc/* CREATE PROCEDURE test3 ASselect * into #footable from employeeselect * from #footable*/conn = site.GetConnection( "MSSQLServer" );// create an empty queryq = conn.CreateQuery();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 99.

272

Page 293: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

stripTrailingBlanks propertySyntax 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:

<!--SCRIPTSQL=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 ][Sweatshirt ][Tee Shirt ][Visor ]

You can also use the stripTrailingBlanks property in conjunction with the ResultsToXMLString:

<!--SCRIPTSQL=connection.CreateQuery("select distinct name from product order by name" );SQL.stripTrailingBlanks = true;document.WriteLn( SQL.ResultsToXMLString() );-->

See also “CreateQuery method” on page 99.

273

Page 294: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

query methods

query methodsThe query object has these methods:

Close methodSyntax query.Close( )

Description Closes the active query. To reestablish the query you must execute it again.

Closing a queryA 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 methodSyntax 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();-->

274

Page 295: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

GetColumnCount methodSyntax 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 methodSyntax 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 methodSyntax 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.

275

Page 296: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

query methods

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 methodSyntax query.GetEmpty( )

Description Indicates if the result set is empty.

NoteIf 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 = Whiteselect id from product where color = ’white’--><!--SQL NAME = Redselect 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.

276

Page 297: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

GetErrorCode methodSyntax 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 methodSyntax 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 methodSyntax query.GetRowCount( )

277

Page 298: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

query methods

Description The number of rows in the result set of the current query.

[Adaptive Server Enterprise]Row count is not always available for some database servers, including Adaptive Server Enterprise. If unavailable, a return of -1 will be given.

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 methodSyntax 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 methodSyntax 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.

278

Page 299: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

<!--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,MichaelsReiser,BethNiedringhaus,ErinMason,MeghanMcCarthy,LauraPhillips,PaulColburn,KellyGoforth,MatthewGagliardo,JessieAgliori,MichaelRicci,Dylan...

Move methodSyntax query.Move(rowNum )

Description Changes the current row to the rowNum [integer] row of a query result set.

279

Page 300: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

query methods

Cursor support for some database serversThe cursor support of some database servers, including Adaptive Server Enterprise, is not as extensive as that of Adaptive Server Anywhere, and some of the Move functions are unavailable.

To use Move, MoveFirst, MoveLast, MovePrevious, or MoveRelative with these database servers you can simulate the cursor abilities of Adaptive Server Anywhere. To do this for all connections, modify your registry. From your system’s Registry Editor, open the following file: HKEY_LOCAL_MACHINE\SOFTWARE\SYBASE\SYBASE TOOLS

Add the new string value name Simulate Cursors with the string value of "yes".

To do this for a specific connection, use the simulateCursors property of the connection object.

Using simulated cursors will cause a decline in performance. When possible, use MoveNext instead of modifying your Registry settings.

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 methodSyntax query.MoveFirst( )

Description Changes the current row to the first row of a query result set.

280

Page 301: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

Cursor support for some database serversThe cursor support of some database servers, including Adaptive Server Enterprise, is not as extensive as that of Adaptive Server Anywhere, and some of the Move functions are unavailable.

To use Move, MoveFirst, MoveLast, MovePrevious, or MoveRelative with these database servers you can simulate the cursor abilities of Adaptive Server Anywhere. To do this for all connections, modify your registry. From your system’s Registry Editor, open the following file: HKEY_LOCAL_MACHINE\SOFTWARE\SYBASE\SYBASE TOOLS

Add the new string value name Simulate Cursors with the string value of "yes".

To do this for a specific connection, use the simulateCursors property of the connection object.

Using simulated cursors will cause a decline in performance. When possible, use MoveNext instead of modifying your Registry settings.

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 95.

MoveLast methodSyntax query.MoveLast( )

Description Changes the current row to the last row of a query result set.

281

Page 302: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

query methods

Cursor support for some database serversThe cursor support of some database servers, including Adaptive Server Enterprise, is not as extensive as that of Adaptive Server Anywhere, and some of the Move functions are unavailable.

To use Move, MoveFirst, MoveLast, MovePrevious, or MoveRelative with these database servers you can simulate the cursor abilities of Adaptive Server Anywhere. To do this for all connections, modify your registry. From your system’s Registry Editor, open the following file: HKEY_LOCAL_MACHINE\SOFTWARE\SYBASE\SYBASE TOOLS

Add the new string value name Simulate Cursors with the string value of "yes".

To do this for a specific connection, use the simulateCursors property of the connection object.

Using simulated cursors will cause a decline in performance. When possible, use MoveNext instead of modifying your Registry settings.

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 95.

MoveNext method Syntax query.MoveNext( )

Description Changes the current row to the next row of a query result set.

282

Page 303: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

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 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 methodSyntax query.MovePrevious( )

Description Changes the current row to the previous row of a query result set. This is a method of the query object.

Cursor support for some database serversThe cursor support of some database servers, including Adaptive Server Enterprise, is not as extensive as that of Adaptive Server Anywhere, and some of the Move functions are unavailable.

To use Move, MoveFirst, MoveLast, MovePrevious, or MoveRelative with these database servers you can simulate the cursor abilities of Adaptive Server Anywhere. To do this for all connections, modify your registry. From your system’s Registry Editor, open the following file: HKEY_LOCAL_MACHINE\SOFTWARE\SYBASE\SYBASE TOOLS

Add the new string value name Simulate Cursors with the string value of "yes".

To do this for a specific connection, use the simulateCursors property of the connection object.

Using simulated cursors will cause a decline in performance. When possible, use MoveNext instead of modifying your Registry settings.

Return Boolean. This method returns true or false, indicating whether the method succeeded or not.

283

Page 304: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

query methods

ome

tive m

ble,

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 95.

MoveRelative methodSyntax query.MoveRelative(relativeRowNum)

Description Moves to a row that is relativeRowNum [integer] rows before or after the current row of a query result set.

Cursor support for some database serversThe cursor support of some database servers, including Adaptive Server Enterprise, is not as extensive as that of Adaptive Server Anywhere, and sof the Move functions are unavailable.

To use Move, MoveFirst, MoveLast, MovePrevious, or MoveRelative with these database servers you can simulate the cursor abilities of AdapServer Anywhere. To do this for all connections, modify your registry. Froyour system's Registry Editor, open the following file: HKEY_LOCAL_MACHINE\SOFTWARE\SYBASE\SYBASE TOOLS

Add the new string value name Simulate Cursors with the string value of "yes".

To do this for a specific connection, use the simulateCursors property of the connection object.

Using simulated cursors will cause a decline in performance. When possiuse MoveNext instead of modifying your Registry settings.

Return Boolean. This method returns true or false, indicating whether the methodsucceeded or not.

284

Page 305: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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 methodSyntax 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 methodSyntax 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.

285

Page 306: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

query methods

ters

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 methodSyntax 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, characare 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" );

286

Page 307: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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 methodSyntax 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)

287

Page 308: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

session object

ever

Web t asks then ged ite

o

they

of ation te st

+ "," + myQuery.GetValue(2) ); } myQuery.SetSQL ( ’select id from product’ ); myQuery.Execute(); while ( myQuery.MoveNext() ) { document.WriteLn( "id:"+myQuery.GetValue(1) ); }-->

session objectObject 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 sessions

Web connections are typically sessionless – from your Web client, you can jump from one Web site to another (and back) at any time. The Web site nknows exactly when you've ended your “session” with it.

It is desirable, though, to maintain some concept of a session between theclient and the Web site. If you, as the Web site, set up a welcome page thathe user to log in with a name and password, each of the pages that you make available to them must “know” somehow that the user has already login. If, however, they haven't logged in (or haven't logged in recently), the sneeds 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 sthat 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 are accessed.

By default, Dynamo considers a session to last five minutes from the timethe user's last action at a given Web site (you can change this default durglobally or for specific session objects). For the duration of a session, the simaintains information about the user's connection – a login name, their laaction, or whatever other information the site requests from the client.

288

Page 309: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

can

that

ase.

sion.

nd

r

et a is

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 check its status as they require. After the specified duration elapses (or times out), the session object associated with the client goes away. Web pagesaccessing the object are still able to query the session object to determinethe session has ended (no longer exists). Null would be returned in this c

Using the session object

The session object has only one predefined property (timeOut). You define the additional properties that you want to keep track of during a client's ses

The session information itself typically comes from client input such as anHTML form. A login page, for example, might prompt a user for a name apassword.

To check whether or not there is session information available, use:

if ( exists(session) ){...

The client sends the requested information as a URL with arguments. Foexample:

http://www.acme.com/check_login.htm?username=hsimpson&password=doh

The receiving document (in this case, check_login.htm) can then read the incoming values, look them up in a password list or database table, and sproperty in the session object accordingly. For example, if the user's login correct, the following statement sets a user-defined property called loginCorrect:

session.loginCorrect = true;

Until the session times out, other pages can then check the session.loginCorrect property each time they load. For example:

<!--SCRIPT if ( !exists(session) || !session.loginCorrect ) { document.WriteLn( "Permission denied." ); } else { // show authorized content here }-->

For a working example of the session object used in a login page, see the sample application in the /Site/app folder of the Dynamo demo database.

289

Page 310: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

session property

Using cookies for sessions

Internally, Dynamo implements the session object using cookies, which are small chunks of information passed between a particular Web client and Web site. A cookie provides a way for the site to remember information about that client’s session. For more information on cookies and how they store persistent information for a Web connection, see the Netscape Web site at http://www.netscape.com.

session propertyThe session object has this property:

timeOut propertySyntax 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; }-->

290

Page 311: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

ding

use

ctions se,

hese

site objectObject 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 )

Description Only one site object allowedYou cannot create additional site objects in your scripts.

Script-based management

Management of Dynamo Web sites is driven by scripts. The site object 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 provithe live content for your Web site.

• Creation and modification of wizards and property sheets to suit yourwork style and content needs.

• Addition of menu items and icons to the Sybase Central interface, to the wizards that you create.

Managing documents and connections

In a Dynamo Web site, you can manage documents and database conneeither by using Sybase Central or by writing your own scripts. In either cathe 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 management interface

Because the Dynamo management tools are script-based, you can alter tscripts or create new ones to tailor the interface to your needs:

• You can create your own wizard dialogs using CreateWizard.

291

Page 312: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

site properties

sing

ntents

amo

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 uthe 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 coof 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 page126.

For more information on the connection object, see “connection object” onpage 87.

site propertiesThe site object has this property:

type propertySyntax 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 Dynapplication:

<!--SCRIPT document.WriteLn( site.type );-->

292

Page 313: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

The output from this example is:

database

site methodsThe site object has these methods:

AskQuestion methodSyntax 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 methodSyntax 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 73.

Return Boolean.

Example This example takes a copy of form.stm and places it into a folder called Formswith the new name form_new.stm:

<!--SCRIPT

293

Page 314: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

site methods

le

BC

he

ent

nal

site.CopyDocument("~/form.stm","/Forms/form_new.stm");-->

CreateConnection methodSyntax 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 applicabto 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 ODBCconnections).

• password [string] is the password of the database user (optional for ODconnections).

• type [string] is the type of connection, can be ODBC or Open Client. Tdefault is ODBC.

• connectParameters [string] are the parameters for connecting to the database (optional for ODBC connections, not applicable to Open Cliconnections).

• database [string] is the name of the database to which to connect (optiofor Open Client connection; not applicable to ODBC connections).

294

Page 315: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

ate

e

uses

CreateConnection and DeleteConnectionYou cannot delete a connection that a script is actively referencing. Because of this, do not use CreateConnection and DeleteConnection in the same script unless the connection object has gone out of scope, or has been set to null by the time DeleteConnection is called.

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 crea query. To obtain a connection object with the blank fields filled in, use site.GetConnection.

Temporary connectionTo create a temporary connection, use the connection constructor. See “connection object” on page 87 for more information.

Return Connection object representing the newly created connection, or null if thconnection 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 theparameters supplied.

Example This script creates a new ODBC connection to the sample database, andthe new connection to execute a query.

<!--SCRIPT createConnection.ssc /* Creating a connection to another site */

myConn = site.CreateConnection ( "Dynamo Demo", "sample application", "sample", "dba", "sql" );-->

<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

295

Page 316: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

site methods

” on

will

-->

<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 methodSyntax 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 “Pathspage 73).

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 connect (optional).

296

Page 317: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

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.

CreateDocument and DeleteDocument:You cannot delete a document that a script is actively referencing. Because of this, do not use CreateDocument and DeleteDocument in the same script unless the document object has gone out of scope, or has been set to null by the time DeleteDocument is called.

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 126.

CreatePropertySheet methodSyntax 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.

297

Page 318: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

site methods

e

ated.

ase

• 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).

• 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).

• help [string] The help that you would like displayed for the page. Thhelp is displayed by right clicking on the page.

• value The value entered by the user when the property sheet is cre

This method is supported only when executing documents from within SybCentral.

You can find the following propsht.ssc class file in the /system/utils directory of your site folder:

<!--SCRIPT propsht.ssc created on 06/25/97 09:33:32

// The following class is used for creating simple// property sheet pages

class propertySheetPage( type, title, explanation, question, choices, selected, help ) { this.type = type; this.title = title; this.explanation = explanation; this.question = question; this.choices = choices; this.selected = selected; this.help = help;}

298

Page 319: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

// The following class is used to indicate the // position of an item on a property sheet page. // If null is passed in to any of the parameters, // a default value will be used.

class itemPosition( left, top, width, height ){ this.left = left; this.top = top; this.width = width; this.height = height;}

// The following class is used to make a single// item that you would like to place on a property // sheet page.

class propertySheetItem( type, question, choices, selected, position, help ){ this.type = type; this.question = question; this.choices = choices; this.selected = selected; this.position = position; this.help = help;}

// The following class is used to place a bitmap on // a property sheet page.

class propertySheetPictureItem( picture, position ){ this.type = "picture"; this.picture = picture; this.position = position;}

// The following class is used to make advanced // property pages that contain more than one input // field.

class propertySheetAdvanced( title, explanation, items ){

299

Page 320: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

site methods

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; pSheet.name = new wizardPage( ’Text’, IntlStr.wizNewLink.p1.title, IntlStr.wizNewLink.p1.explanation, IntlStr.wizNewLink.p1.question ); pSheet.directory = new wizardPage( ’DirectoryBrowse’, IntlStr.wizNewLink.p2.title, IntlStr.wizNewLink.p2.explanation, IntlStr.wizNewLink.p2.question ); /* Display the wizard */ if( site.CreatePropertySheet(pSheet) ) { /* Check if a folder name was provided */ if( pSheet.name.value.length > 0 ) { /* Create the folder in the specified */ /* directory */

300

Page 321: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

var fullname = document.location; + ’/’ + 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 methodSyntax 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).

301

Page 322: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

site methods

ses

, a n

e

ase

• 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 presthe “Next” button. Usually used to validate input or select a different branch of the wizard. An integer represents an index to a wizard pagestring represents the name of a wizard page, and a function can retureither an integer or a string that indicates which page to go to.

• help [string] The help that you would like displayed for the page. Thhelp 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 SybCentral.

You can find the following wizard.ssc class file in the /system/utils directory of your site folder:

<!--SCRIPT wizard.ssc

// The following class is used for creating simple// wizard pages

class wizardPage( type, title, explanation, question, choices, selected, next, help ) { this.type = type; this.title = title; this.explanation = explanation; this.question = question; this.choices = choices; this.selected = selected; this.next = next; this.help = help; } // The following class is used to indicate the // position of an item on a wizard page. If null// is passed in to any of the parameters, a default// value will be used.

class itemPosition( left, top, width, height ) { this.left = left;

302

Page 323: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

this.top = top; this.width = width; this.height = height; } // The following class is used to make a single// item that you would like to place on a wizard // page.

class wizardItem( type, question, choices, selected, position, help ) { this.type = type; this.question = question; this.choices = choices; this.selected = selected; this.position = position; this.help = help; } // The following class is used to place a bitmap on // a wizard page.

class wizardPictureItem( picture, position ) { this.type = "picture"; this.picture = picture; this.position = position; }

// The following class is used to make advanced wizard // pages that contain more than one input field. class wizardAdvanced( title, explanation, items, next ) { 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; this.next = next; }-->

303

Page 324: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

site methods

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 */ class wizardPage( type, title, explanation, question, choices, selected, next, help ) { this.type = type; this.title = title; this.explanation = explanation; this.question = question; this.choices = choices; this.selected = selected; this.next = next; this.help = help; } var wiz; // From "start" control passes to "page1". wiz.start = new wizardPage( ’text’, ’Customer Information’, ’New customer data should be entered here.’, ’What company do you represent?’, null, null, ’page1’ ); // From "page1" control passes to "productpage".

wiz.page1 = new wizardPage( ’text’, ’Customer Information’, "You must provide a name for direct billing.", ’Please enter a first and last name.’, null, null, ’productpage’ ); var products; products[0] = "widget"; products[1] = "hammer"; products[2] = "putty";

304

Page 325: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

products[3] = "stripper";

wiz.productpage = new wizardPage( ’choice’, ’Product’, ’We have various products available for our customers. To place an order, select a product from the following list.’, ’Choose a product.’, products ); site.CreateWizard( wiz ); document.writeln( "Customer " + wiz.page1.value + " ordered a " + wiz.productpage.value );-->

This example uses the wizardAdvanced class and the itemPosition class while creating a wizard that asks users for their mailing address. The wizardAdvanced class is used to create wizards that have multiple items per page:

<!--SCRIPT var webRoot = site.GetRootDocument(); import ( webRoot.location + ’/system/utils/wizard.ssc’ );

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";

// third and fourth arguments to wizardItem are // ignored by all types except "choice"// if a null argument is passed to itemPosition, it

305

Page 326: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

site methods

// uses the default items.firstName = new wizardItem( "text", "First Name", null, null, new itemPosition( null, 20, 65, null ) ); items.lastName = new wizardItem( "text", "Last Name", null, null, new itemPosition( 160, 20, 100, null ) ); items.street = new wizardItem( "text", "Street" ); items.city = new wizardItem( "text", "City", null, null, new itemPosition( null, 75, 80, null ) ); items.province = new wizardItem( "choice", "Province", provinces, 0, new itemPosition( 175, 75, 85, null ) ); items.postalCode = new wizardItem( "text", "Postal Code", null, null, new itemPosition( null, null, 80, null ) );

// wizardAdvanced displays all the wizardItems in // the items array on one page. wiz.page = new wizardAdvanced( "Address", "Please enter your mailing address.", items );

if( site.CreateWizard( wiz ) ) { with( wiz.page.items ) { document.writeln( firstName.value + " " + lastName.value ); document.writeln( street.value ); document.writeln( city.value + ", " + province.value ); document.writeln( postalCode.value ); } }-->

This example uses the next element to conditionally choose which wizard page should be displayed next:

<!--SCRIPT

// This is a class we define for convenience that // sets up a single wizard page. This class // is available to users in the file // /site/system/utils/wizard.ssc.

class wizardPage( type, title, explanation, question, choices, selected, next, help ) { this.type = type; this.title = title; this.explanation = explanation;

306

Page 327: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

this.question = question; this.choices = choices; this.selected = selected; this.next = next; this.help = help; } var wiz; // This function gets executed when the user hits // the Next button from the "wiz.start" page. // It determines whether the next page should be // "page1", or "page2".

function whichpage() { var pagestr = "page"; pagestr += ( wiz.start.selected + 1 ); return pagestr; } function CreateCustomerId( name ) { return 12345678; } // On this first page, the user chooses whether // they are a new or returning // customer. If new, "page1" is displayed next, // otherwise "page2" is displayed next.

var choices; choices[0] = ’New Customer’; choices[1] = ’Returning Customer’; wiz.start = new wizardPage( ’choice’, ’Welcome’, ’If you are a new customer select "New Customer". Otherwise, select "Returning Customer".’, ’What kind of customer are you?’, choices, 0, whichpage ); // From "page1" control passes to "productpage".

307

Page 328: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

site methods

wiz.page1 = new wizardPage( ’text’, ’New Customer’, "Before you can purchase anything, you must have a customer ID. In order to get this, you must give us your name.", ’Please enter your name.’, null, null, ’productpage’ ); // From "page2" control passes to "productpage".

wiz.page2 = new wizardPage( ’text’, ’Returning Customer’, ’Welcome back. Before you can purchase anything, you must identify yourself by providing your customer ID’ , ’Please enter your customer ID.’, null, null, ’productpage’ ); var products; products[0] = "hat"; products[1] = "shirt"; products[2] = "pogo stick"; products[3] = "ball of yarn";

wiz.productpage = new wizardPage( ’choice’, ’Product’, ’We have various products available for our customers. To place an order, select a product from the &following list.’, ’Choose a product.’, products ); if( site.CreateWizard( wiz ) ) { var id; if( whichpage() == "page1" ) { id = CreateCustomerId( wiz.page1.value ); } else { id = wiz.page2.value; } document.writeln( "Customer #" + id + " ordered a " + wiz.productpage.value ); }

308

Page 329: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

tilde

-->

DeleteConnection methodSyntax site.DeleteConnection(connName)

Description Deletes the persistent connection defined by connName.

CreateConnection and DeleteConnectionYou cannot delete a connection that a script is actively referencing. Because of this, CreateConnection and DeleteConnection should not be used in the same script unless the connection object has gone out of scope, or has been set to null at the time DeleteConnection is called.

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 87.

DeleteDocument methodSyntax 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 (~) may also be used.

For information on the * and ? wildcards see “Wildcards” on page 73.

309

Page 330: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

site methods

ed

ay tion

CreateDocument and DeleteDocumentYou cannot delete a document that a script is actively referencing. Because of this, CreateDocument and DeleteDocument should not be used in the same script unless the document object has gone out of scope, or has been set to null at the time DeleteDocument is called.

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 126.

GetConnection methodSyntax site.GetConnection(connName | connId)

Description Returns the connection object representing the persistent connection callconnName[string], or having id connId[integer].

Note:Connection IDs are not persistent. If you restart Dynamo, connection IDs mnot be the same. For this reason, Sybase recommends the use of connecnames whenever possible.

Return Connection object representing the specified connection, or null if the connection cannot be retrieved.

Typical reason for null to be returned include:

310

Page 331: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

of

s true.

st of and

• The specified connection does not exist.

• A successful connection to the database could not be made.

Example This example changes the database to which “myConnection” connects:

<!--SCRIPT myConn = site.GetConnection ( "myConnection" ); myConn.database = "newDatabaseName"; -->

See also “connection object” on page 87.

GetConnectionIdList methodSyntax site.GetConnectionIdList( [true|false] )

Description Returns an array of IDs of connection objects. If true is specified, the list connection IDs will include IDs representing the special connections <no connection> and <inherited>. If false is specified, the list of connection IDdoes not include IDs representing the special connections. The default is

Return Array of integers.

Example To display a list of connection IDs.

<!--SCRIPT document.WriteLn( site.GetConnectionIdList() );-->

See also “connection object” on page 87.

GetConnectionNameList methodSyntax site.GetConnectionNameList( [true|false] )

Description Returns an array of names of connection objects. If true is specified, the liconnection names includes the two special connections <no connection><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() );

311

Page 332: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

site methods

) age

r this

ent

ed.

ted

-->

See also “connection object” on page 87.

GetDocument methodSyntax 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 p73.

Note:IDs are not guaranteed to be the same after restarting the Web server. Foreason, Sybase recommends that you use the document name to identifydocuments.

Return Document object representing the specified document, or null if the documcould 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 126.

GetErrorCode methodSyntax site.GetErrorCode( )

Description Returns the current error code.

Return Integer. Returns an error code associated with the last operation perform

Example This example displays information as to why the connection was not creasuccessfully:

312

Page 333: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

ted

<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 269.

“connection properties” on page 90.

“GetErrorInfo method” on page 277.

“GetState method” on page 278.

“GetErrorInfo method” on page 101.

“GetState method” on page 102.

GetErrorInfo methodSyntax 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 creasuccessfully:

<HTML> <TITLE>sample.stm</TITLE><BODY><!--SCRIPT myConn = new Connection( ’connection1’, ’’, ’ASA 6.0 Sample’, ’basUser’, ’badPassword’ ); if( myConn == null ) {

313

Page 334: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

site methods

o the

ially

document.writeln( "Error Code: " + site.GetErrorCode() ); document.writeln( "Error Message: " + site.GetErrorInfo() ); document.writeln( "Error State: " + site.GetState() ); }--></BODY></HTML>>

See also “connection object” on page 87.

“query object” on page 269.

“query properties” on page 271.

“connection properties” on page 90.

GetEventList methodSyntax 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 tparameters of the OnEvent method. The only difference is the handlerScript property, which always has an absolute path, regardless of how it was initspecified 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++; }

314

Page 335: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

-->

GetRootDocument methodSyntax 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 methodSyntax 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();

315

Page 336: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

site methods

an

document.WriteLn( queryCode );--></BODY></HTML>

Include methodSyntax 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 291.

“site properties” on page 292.

“GetGenerated method” on page 138.

OnEvent methodSyntax site.OnEvent(itemName, controlType, controlLabel, description,

handlerScript)

Description Adds an event handler to the management interface (typically for creatingicon 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).

316

Page 337: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

t is

t is

ror.

he

h

• text Any template.

• controlType is one of:

• Get Command that comes from the Web server when a documenrequested. Applies only to directory, image, script, and text item types.

• NewMenu Displays from a new menu option, within a menu.

• ContextMenu Menu that appears when you right-click.

• Icon Only for site, directory, and connectionFolder.

• Status404 Occurs when a request for a document is made thanot available.

• Parser Occurs when a request for a document generates an er

• SessionTimeOut Occurs just before a session times out. This controlType applies to the site itemType. The parameters controlLabel and description are not applicable.

• controlLabel is the visible name of the control. This does not apply to tcontrol type of Get, Status404, or SessionTimeOut.

• description is a comment for the control that displays as help on the Sybase Central status bar. This does not apply to the control type of Get or Status404.

• handlerScript is the script to trigger when the control is used. The patname is relative to the script from which the OnEvent method is called.

Return Boolean. This method returns true or false, indicating whether the methodsucceeded or not.

Example For example, the following code is added to the autoexec.ssc file in the System folder to create an icon to execute the wizard created in the site method CreateWizard example.

//Example Wizardsite.OnEvent( ’directory’,’Icon’,’Dynamo Example for Creating Wizards’,’Wizard Example’,’NewLink.ssc’ );

This example, if added to the autoexec.ssc file, would cause the execution of the cleanup.ssc script just before a session times out:

site.OnEvent( ’Site’, ’SessionTimeOut’, ’ ’, ’ ’, ’cleanup.ssc’ );

317

Page 338: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

site methods

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’);

Execute from /system/autoexec.ssc

You should only call the OnEvent method from /system/autoexec.ssc or from another script that is executed from within the autoexec script.

RenameDocument methodSyntax 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 73.

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:

<!--SCRIPTsite.RenameDocument("~/form.stm","~/Sample/test.stm");-->

ShowMessage methodSyntax site.ShowMessage (title, message)

Description Displays a message with an OK box. This method is supported only fromwithin Sybase Central.

Example This example displays the message “Task complete”.

<!--SCRIPT site.ShowMessage("Request status", "Task complete");-->

318

Page 339: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

String objectObject 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 );-->

String methodsThe String object has these methods:

charAt methodSyntax 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));-->

319

Page 340: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

String methods

indexOf methodSyntax 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 methodSyntax 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.

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 methodSyntax 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 stringis split into an array of chars.

320

Page 341: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

t the

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 methodSyntax 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.

Example This example returns “hello”:

<!--SCRIPT myString = new String( "Hello world, hello" ); sampleString = myString.substring( 13 ); document.WriteLn( sampleString );-->

substring methodSyntax String.substring( start, end )

Description Returns a substring value that is extracted from the string object starting astart 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 );

321

Page 342: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

String methods

-->

toLowerCase methodSyntax 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 methodSyntax String.toString( )

Description Returns the string value of the object.

Return String.

Example This example returns “Hello world, hello”:

<!--SCRIPT myString = new String( "Hello world, hello" ); document.WriteLn( myString.toString() );-->

toUpperCase methodSyntax 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();

322

Page 343: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

document.WriteLn( sampleString );-->

valueOf methodSyntax 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() );-->

system objectObject 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 190.

“errorString property” on page 191.

323

Page 344: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

system properties

system propertiesThe system object has these properties:

errorNumber propertySyntax 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 191.

errorString propertySyntax system.errorString

Attributes This property is read-only.

Description A string containing an error message for the error code of the last systemmethod 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 190.

system methodsThe system object has these methods:

324

Page 345: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

CHAPTER 3 DynaScript Predefined Objects

Exec methodSyntax 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 methodSyntax 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 methodSyntax 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 path = system.GetEnv( "PATH" );-->

325

Page 346: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

system methods

SetEnv methodSyntax 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 );-->

326

Page 347: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Index

Symbols* 73+ 41+= 41.. 73? 40, 73~ 73

Numerics404 (not found) messages 316

Aabs method (Math object) 256absolute paths 73acos method (Math object) 256ActiveX objects 59AddRecipient method (outgoing mail piece object)

244AddReplyTo method (outgoing mail piece object)

247apostrophe

special character 62appendChild method (DOMNode object) 181appendData method (DOMCharacterData object)

148arguments object 57Array object

about 76methods 77properties 77

arraysabout 67

asin method (Math object) 256AskQuestion method (site object) 293atan method (Math object) 256

atan2 method (Math object) 257AttachData method (outgoing mail piece object) 248AttachDocument method (outgoing mail piece object)

248AttachFile method (outgoing mail piece object) 249attachment object

about 80methods 82properties 80

attachments property (incoming mail piece object) 228attributes property (DOMNode object) 174autoCommit property (connection object) 90Autoexec.ssc 292

Bbackslash

special character 62base classes

about 69body property (incoming mail piece object) 228body property (outgoing mail piece object) 239, 244Boolean literals 35Boolean object

about 86methods 86

BORDER attribute (FORMATTING tag) 13break statements

about 48built-in functions 58

CCACHED_OUTPUT_TIMEOUT attribute

(DOCUMENT tag) 9cachedOutputTimeOut property (document object)

127callee property (arguments object) 57

327

Page 348: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Index

CallStaticMethod method (java object) 217, 218, 220CDATA

FORMATTING tag 13ceil method (Math object) 257chained mode 88ChangeCurrentDirectory method (FTP object) 198charAt method (String object) 319childNodes property (DOMNode object) 174class statements

about 50, 69, 70classes

about 66, 69instances 72

cloneNode method (DOMNode object) 181Close method (file object) 193Close method (query object) 274, 275COLUMN_TAG attribute (FORMATTING tag) 13COMMAND attribute (EXECUTE tag) 13comment statements

about 55comments

HTML 34Commit method (connection object) 97COMPONENT (Dynamo tag) 4COMPONENT_NAME attribute (COMPONENT tag) 5conditional SQL tags 28Connect method (connection object) 98Connect method (FTP object) 198connected property (connection object) 90connection object

about 87methods 97properties 90

connection property (query object) 271CONNECTION_NAME attribute (SQL tag) 23CONNECTION_NAME attribute (SQL_INSERT tag) 26CONNECTION_OBJECT attribute (COMPONENT tag)

5CONNECTION_OBJECT attribute (SQL tag) 23CONNECTION_OBJECT attribute (SQL_INSERT tag)

26connectionId property (document object) 127connectionName property (document object) 128connections

site object 291temporary 87

328

connectionType property (connection object) 91connectParameters property (connection object) 91CONTENT_TYPE attribute (DOCUMENT tag) 9contentType property (document object) 128continue statement

about 48control characters in strings 36controls

creating 316conventions

about xviiisyntax xviii

cookies for sessions 288CopyDocument method (site object) 293cos method (Math object) 257count property (mailList object) 224createAttribute method (DOMDocument object) 153createCDATASection method (DOMDocument object)

153createComment method (DOMDocument object) 154CreateComponent method 215CreateComponent method (connection object) 98CreateComponent method (java object) 215CreateConnection method (site object) 294CreateDirectory method (FTP object) 199CreateDocument method (site object) 296createDocumentFragment method (DOMDocument

object) 154createElement method (DOMDocument object) 155createEntityReference method (DOMDocument object)

155CreateObject function (built-in) 59CreateObject method (java object) 217createProcessingInstruction method (DOMDocument

object) 155CreatePropertySheet method (site object) 297CreateQuery method (connection object) 99createTextNode method (DOMDocument object) 156CreateWizard method (site object) 301cursorType property (query object) 272

DDATA

in HTML 8

Page 349: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Index

DATA (Dynamo tag) 8data property (DOMCharacterData object) 147data property (DOMProcessingInstruction object)

186database property (connection object) 92databaseType property (connection object) 92dataSource property (connection object) 92dataSourceList property (connection object) 93datatypes for variables 37Date object

about 104methods 106

declarationvariables 37

Delete method (file object) 193Delete method (incoming mail piece object) 233DeleteConnection method (site object) 309deleteData method (DOMCharacterData object) 148DeleteDocument method (site object) 309DeleteFile method (FTP object) 199derived classes

about 70description property (connection object) 93description property (document object) 128Disconnect method (connection object) 100Disconnect method (FTP object) 200Disconnect method (mailList object) 225doctype property (DOMDocument object) 151DOCUMENT (Dynamo tag) 9document object

about 126methods 136properties 127

Document Type DefinitionDOMDocumentType object 158

documentationconventions xviiionline xvii

documentElement property (DOMDocument object)152

documentssite object 291

DOMAttribute objectabout 143methods 146properties 144

DOMCDATASection objectabout 146

DOMCharacterData objectabout 146methods 148properties 147

DOMComment objectabout 150

DOMDocument objectabout 151constructor 151methods 153properties 151

DOMDocumentFragment objectabout 157

DOMDocumentTypetemporary 158

DOMDocumentType objectabout 158properties 158

DOMElement objectabout 160methods 161properties 161

DOMEntity objectabout 166properties 166temporary 166

DOMEntityReference objectabout 168

DOMImplementation objectabout 169methods 169

DOMImplementationstemporary 169

DOMNamedNodeMap objectabout 170methods 171properties 170

DOMNode objectabout 173methods 181properties 174

DOMNodeList objectabout 183methods 184

Page 350: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Index

properties 183DOMNotation object

about 184methods 185properties 185

DOMProcessingInstruction objectabout 185methods 187properties 186

DOMText objectabout 187methods 188properties 188temporary 187

do-while statementabout 45

DSN, UID, PWD attribute (SQL tag) 23DSN, UID, PWD attribute (SQL_INSERT tag) 26dynamic content

Dynamo tags 8dynamic files

type property 292Dynamo tags

about 1COMPONENT 4conditional 28DATA 8DOCUMENT 9DynaScript equivalent 3ELSE 11ELSEIF 11ENDIF 12EVALUATE 12EXECUTE 13FORMATTING 13IF 19INCLUDE 19LABEL 20MAILPIECE 21SCRIPT 22SQL 23SQL_ERROR_CODE 29SQL_ERROR_INFO 30SQL_INSERT 25SQL_ON_ ERROR 28SQL_ON_NO_ERROR 28

330

SQL_ON_NO_ROWS 28SQL_ON_ROWS 28SQL_STATE 31syntax 1

Dynamo tags vs DynaScript 3DynaScript

calling Jaguar components 98objects 66

DynaScript vs Dynamo tags 3

EE property (Math object) 252ELSE (Dynamo tag) 11ELSEIF (Dynamo tag) 11encapsulation

about 66, 68ENDIF (Dynamo tag) 12entities property (DOMDocumentType object) 158eof property (file object) 190errorNumber property (file object) 190errorNumber property (system object) 324errorString property (file object) 191escape 65escape function (built-in) 58escaping characters in strings 36eval function (built-in) 58EVALUATE (Dynamo tag) 12Exec(cmd) method (system object) 325EXECUTE (Dynamo tag) 13Execute method (query object) 274exists function (Dynamo built-in) 61exit statement

about 56exp method (Math object) 258exponential literals 35ExportTo method (document object) 137EXPR attribute (ELSEIF tag) 11EXPR attribute (EVALUATE tag) 12expressions

about 38

Page 351: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Index

Ffile object

about 188methods 193properties 189

firstChild property (DOMNode object) 175floating-point literals 35floor method (Math object) 258for statements

about 44for-in statements

about 48FORMAT_AS attribute (FORMATTING tag) 13formatString function (built-in) 61FORMATTING

XML 13formatting

data placeholders 8FORMATTING (Dynamo tag) 13

nesting 17forms

passing variables 133Forward method (incoming mail piece object) 233FROM attribute (MAILPIECE tag) 22from property (incoming mail piece object) 229from property (outgoing mail piece object) 240FTP object

about 197methods 198

Function objectabout 210methods 212properties 211

function statementsabout 52

functionsabout 56arguments object 57built-in 58defining classes 69syntax 52, 53

GgetAttribute method (DOMElement object) 161

getAttributeNode method (DOMElement object) 162GetColumnCount method (query object) 275GetColumnLabel method (query object) 275GetConnection method (site object) 310GetConnectionIdList method (site object) 311GetConnectionNameList method (site object) 311GetContents method (attachment object) 82GetCWD method (system object) 325getDate method (Date object) 106getDay method (Date object) 106GetDirectory method (document object) 137GetDocument method (site object) 312getElementsByTagName method (DOMDocument

object) 156getElementsByTagName method (DOMElement object)

162GetEmpty method (query object) 276Getenv(env) method (system object) 325GetErrorCode method (attachment object) 83GetErrorCode method (connection object) 100GetErrorCode method (FTP object) 200GetErrorCode method (incoming mail piece object)

234GetErrorCode method (mailList object) 226GetErrorCode method (outgoing mail piece object)

250GetErrorCode method (query object) 277GetErrorCode method (site object) 312GetErrorInfo method (attachment object) 84GetErrorInfo method (connection object) 101GetErrorInfo method (FTP object) 201GetErrorInfo method (incoming mail piece object)

235GetErrorInfo method (mailList object) 226GetErrorInfo method (outgoing mail piece object) 250GetErrorInfo method (query object) 277GetErrorInfo method (site object) 313GetEventList method (site object) 314GetFilePtr method (File object) 194getFullYear method (Date object) 107GetGenerated method (document object) 138

passing parameters 138GetHomeInterface method 218, 220getHours method (Date object) 107getMilliseconds method (Date object) 107getMinutes method (Date object) 108

Page 352: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Index

getMonth method (Date object) 108getNamedItem method (DOMNamedNodeMap object)

171GetRootDocument method (site object) 315GetRowCount method (query object) 277getSeconds method (Date object) 108GetServerVariable method (document object) 138GetState method (connection object) 102GetState method (query object) 278GetState method (site object) 315GetSupportedMoves method (connection object) 103getTime method (Date object) 109getTimezoneOffset method (Date object) 109getUTCDate method (Date object) 110getUTCDay method (Date object) 110getUTCFullYear method (Date object) 111getUTCHours method (Date object) 111getUTCMilliseconds method (Date object) 111getUTCMinutes method (Date object) 112getUTCMonth method (Date object) 112getUTCSeconds method (Date object) 113GetValue method (query object) 278getYear method (Date object) 113

HhasChildNodes method (DOMNode object) 182hasFeature method (DOMImplementation object) 169headers property (incoming mail piece object) 229HTML

comments 34HTML headers for functions 56

Iid property (document object) 129identifiers

about 36IF (Dynamo tag) 19if-else statements

about 44implementation property (DOMDocument object) 152import statements

about 54, 57

332

ImportFrom method (document object) 140INCLUDE 19

in HTML 19INCLUDE (Dynamo tag) 19Include method (site object) 316IncludeGenerated method (document object) 140INDEX attribute (LABEL tag) 19, 21indexed and named members 72indexOf method (String object) 320inheritance

about 66, 68, 70insertBefore method (DOMNode object) 182insertData method (DOMCharacterData object) 149inserting data 26instances

creating 66, 72integer literals 35interface

customizing 291isFinite function (built-in) 58isNan function (built-in) 59isolationLevel property (connection object) 93item method (DOMNamedNodeMap object) 171item method (DOMNodeList object) 184

JJaguar

calling components 98COMPONENT tag 4

JaguarL creating a component 215java object

about 212methods 214

JavaScripttags 34

JavaScript Authoring GuideURL 33

join method (Array object) 77

LLABEL (Dynamo tag) 20lastChild property (DOMNode object) 176

Page 353: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Index

lastIndexOf method (String object) 320lastModified property (document object) 129length property (arguments object) 57length property (Array object) 77length property (DOMCharacterLength object) 147length property (DOMNamedNodeMap object) 171length property (DOMNodeList object) 184length property (Function object) 211LIST attribute (FORMATTING tag) 13literals

about 34boolean 35floating-point numbers 35integers 35strings 35

LN10 property (Math object) 253LN2 property (Math object) 253location property (document object) 130log method (Math object) 258LOG10E property (Math object) 254LOG2E property (Math object) 254logical literals 35

Mmail

sending 21, 251mail piece object (incoming)

about 227methods 233properties 228

mail piece object (outgoing)about 238methods 244properties 239

mailListmethods 225

mailList objectabout 223properties 224

MAILPIECE (Dynamo tag) 21Math

methods 255Math object

about 252

properties 252max method (Math object) 259MAX_VALUE property (Number object) 262MAXROWS attribute (FORMATTING tag) 13members

named and indexed 72methods

about 67inline vs. global 69

mimeType property (attachment object) 81min method (Math object) 259MIN_VALUE property (Number object) 263mode property (file object) 192mode property (recipient object) 268Move method (query object) 279MoveFirst method (query object) 280MoveLast method (query object) 281MoveNext method (query object) 282MovePrevious method (query object) 283MoveRelative method (query object) 284multiple values

passing 133

NNAME attribute (DATA tag) 8NAME attribute (FORMATTING tag) 13NAME attribute (LABEL tag) 19, 21name property (attachment object) 81name property (connection object) 94name property (document object) 130name property (DOMAttribute object) 144name property (DOMDocumentType object) 159name property (file object 192name property (recipient object) 269named and indexed members 72NaN property (Number object) 263NEGATIVE_INFINITY property (Number object)

264nesting

FORMATTING tag 17new features

documentation xviinew operator

about 51, 72

Page 354: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Index

NewConn.ssc 291NewFold.ssc 291NewTemp1.ssc 291nextSibling property (DOMNode object) 176nodeName property (DOMNode object) 176nodeType property (DOMNode object) 177nodeValue property (DOMNode object) 179normalize method (DOMElement object) 163notationName property (DOMEntity object) 167notations property (DOMDocumentType object) 160Number

methods 264Number object

about 261properties 262

OObject object

about 265methods 266

objectsabout 66Array 76arrays 67attachment 80base classes 69Boolean 86class statement 50connection 87Date 104document 126DOMAttribute 143DOMCDATASection 146DOMCharacterData 146DOMComment 150DOMDocument 151DOMDocumentFragment 157DOMDocumentType 158DOMElement 160DOMEntity 166DOMEntityReference 168DOMImplementation 169DOMNamedNodeMap 170DOMNode 173

334

DOMNodeList 183DOMNotation 184DOMProcessingInstruction 185DOMText 187encapsulation 68file 188for-in statement 48FTP 197Function 210function statement 52inheritance 68, 70instances 72java 212mail piece (incoming) 227mail piece (outgoing) 238mailList 223Math 252methods 67new operator 51Number 261Object 265polymorphism 68predefined 75properties 66query 269recipient 267session 288site 291String 319system 323this keyword 51var statement 52with statement 49

OnEvent method (site object) 316Open method (file object) 194Opened method (query object) 285operators

about 39arithmetic 40comparison 41conditional 40new 51string 41

ownerDocument property (DOMNode object) 179

Page 355: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Index

Pparent property (document object) 131parentNode property (DOMNode object) 180parse method (Date object) 114parseFloat function (built-in) 59parseInt function (built-in) 59passing parameters 138passing values 133passing variables 56password property (connection object) 95path 73PI property (Math object) 254PKG attribute (COMPONENT tag) 5polymorphism

about 66, 68POSITIVE_INFINITY property (Number object)

264pow method (Math object) 260predefined objects

about 75Array 76attachment 80Boolean 86connection 87Date 104document 126DOMAttribute 143DOMCDATASection 146DOMCharacterData 146DOMComment 150DOMDocument 151DOMDocumentFragment 157DOMDocumentType 158DOMElement 160DOMEntity 166DOMEntityReference 168DOMImplementation 169DOMNamedNodeMap 170DOMNode 173DOMNodeList 183DOMNotation 184DOMProcessingInstruction 185DOMText 187file 188FTP 197Function 210

java 212mail piece (incoming) 227mail piece (outgoing) 238mailList 223Math 252Number 261Object 265query 269recipient 267session 288site 291String 319system 323

prettyPrint method (DOMDocument object) 157previousSibling property (DOMNode object) 180properties

about 66property sheets

creating 297publicId property (DOMEntity object) 167publicId property (DOMNotation object) 185PutData method (FTP object) 201PutDataWithAppend method (FTP object) 202PutDocument method (FTP object) 203PutDocumentWithAppend method (FTP object) 204PutFile method (FTP object) 205PutFileWithAppend method (FTP object) 205

QQUERY attribute (DATA tag) 8query object

about 269methods 274properties 271

Rrandom method (Math object) 260Read method (file object) 195ReadChar method (file object) 195ReadLine method (file object) 196recipient object

about 267

Page 356: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Index

properties 268recipients property (incoming mail piece object) 230recursion (callee property 57REDIRECT attribute (DOCUMENT tag) 9Redirect method (incoming mail piece object) 235redirect property (document object) 131Refresh method (query object) 285relative paths 73removeAttribute method (DOMElement object) 164removeAttributeNode method (DOMElement object) 164removeChild method (DOMNode object) 182RemoveDirectory method (FTP object) 206removeNamedItem method (DOMNamedNodeMap object)

172RenameDocument method (site object) 318RenameFile method (FTP object) 207replaceChild method (DOMNode object) 183replaceData method (DOMCharacterData object) 149Reply method (incoming mail piece object) 236replyTo property (incoming mail piece object) 230RESULTSET_TAG (FORMATTING TAG) 13ResultsToXMLString method (query object) 286Retrieve method (incoming mail piece object) 237RetrieveCurrentDirectory method (FTP object) 206RetrieveData method (FTP object) 207RetrieveDirectoryListing method (FTP object) 208RetrieveDocument method (FTP object) 208RetrieveFile method (FTP object) 209RetrieveFileWithAppend method (FTP object) 210return statements

about 53, 56reverse method (Array object) 78Rollback method (connection object) 103round method (Math object) 260ROW_TAG attribute (FORMATTING tag) 13

SSaveAsDocument method (attachment object) 84SaveAsFile method (attachment object) 85scoping

methods 67variables 38

SCRIPT (Dynamo tag) 22script language

336

literals 34objects 66operators 38, 39overview 33statements 43tags 34variables 36

scriptsfunctions 56importing 54, 57objects 66overview 33tags 34

Seek(offset) method (file object) 196semi-colons in statements 44Send method (outgoing mail piece object) 251sender property (incoming mail piece object) 231sender property (outgoing mail piece object) 242server property (connection object) 95server variables 138session object

about 288properties 290

setAttribute method (DOMElement object) 165setAttributeNode method (DOMElement object) 165setDate method (Date object) 114SetEnv(env,value,overwrite) method (system object)

326setFullYear method (Date object) 115setHours method (Date object) 115setMilliseconds method (Date object) 116setMinutes method (Date object) 116setMonth method (Date object) 117setNamedItem method (DOMNamedNodeMap object)

172setSeconds method (Date object) 118SetSQL method (query object) 287setTime method (Date object) 118setUTCDate method (Date object) 119setUTCFullYear method (Date object) 120setUTCHours method (Date object) 121setUTCMilliseconds method (Date object) 121setUTCMinutes method (Date object) 122setUTCMonth method (Date object) 122setUTCSeconds method (Date object) 123setYear method (Date object) 123

Page 357: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Index

ShowMessage method (site object) 318simulateCursors property (connection object) 95sin method (Math object) 261site object

about 291methods 293properties 292

size property (document object) 131size property (incoming mail piece object) 232SMTPHOST attribute (MAILPIECE tag) 22smtpHost property (outgoing mail piece object) 243sort method (Array object) 78source property (document object) 132special characters in strings 36specified property (DOMAttribute object) 145split method (String object) 320splitText method (DOMText object) 188SQL

condition tags 28SQL (Dynamo tag) 23SQL as HTML comment tags

DATA 8SQL_ERROR_CODE (Dynamo tag) 29SQL_ERROR_INFO (Dynamo tag) 30SQL_INSERT (Dynamo tag) 25SQL_ON_ ERROR (Dynamo tag) 28SQL_ON_NO_ERROR (Dynamo tag) 28SQL_ON_NO_ROWS (Dynamo tag) 28SQL_ON_ROWS (Dynamo tag) 28SQL_STATE (Dynamo tag) 31sqlEscape function (built-in) 61sqrt method (Math object) 261SQRT1_2 property (Math object) 255SQRT2 property (Math object) 255STARTROW attribute (FORMATTING tag) 13statements

about 43break 48class 50comment 55continue 48do-while 45exit 56for 44for-in 48function 52

if-else 44import 54return 53switch 46this 51var 52while 45with 49

STATUS attribute (DOCUMENT tag) 9status property (document object) 132status404 316String

methods 319string literals 35String object

about 319stringError property (system object) 324STRIP_TRAILING_BLANKS (FORMATTING tag)

13stripTrailingBlanks property (query object) 273stubs

generating 215SUBJECT attribute (MAILPIECE tag) 22subject property (incoming mail piece object) 232substring method (String object) 321substringData method (DOMCharacterData object)

150switch statement

about 46syntax

Dynamo tags 1syntax conventions xviiisystem folder

Autoexec.ssc 291NewConn.ssc 291NewFold.ssc 291NewTemp1.ssc 291

system objectabout 323methods 324properties 324

systemId property (DOMEntity object) 168systemId property (DOMNotation object) 185

Page 358: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Index

TtagName property (DOMElement object) 161tags

Dynamo tags 1Jaguar 4JavaScript vs Dynamo 34scripts 34

tan method (Math object) 261target property (DOMProcessingInstruction object) 186temporary

connections 87DOMDocumentTypes 158DOMEntitys 166DOMImplementations 169DOMTexts 187

this keywordabout 51

tilde 73timeOut property (session object) 290TO attribute (MAILPIECE tag) 22toDOMDocument function (built-in) 62toGMTString method (Date object) 124toLocaleString method (Date object) 124toLowerCase method (String object) 322toString method (Array object) 79toString method (Boolean object) 86toString method (Date object) 124toString method (Function object) 212toString method (Number object) 264toString method (Object object) 266toString method (String object) 322toUpperCase method (String object) 322toUTCString method (Date object) 125toXMLString function (built-in) 62trailing blanks

stripping them 13type property (document object) 133type property(site object) 292typeof function (built-in) 64typing of variables 37

Uunescape function (built-in) 59URL

338

JavaScript guide 33USE_CDATA attribute (FORMATTING tag) 13userId property (connection object) 97

Vvalue property (document object) 133value property (DOMAttribute object) 145valueOf method (Boolean object) 87valueOf method (Date object) 125valueOf method (Number object) 265valueOf method (Object object) 267valueOf method (String object) 323values

passing 133var statements

about 52variables

about 36assigning values 37checking, 61data types 37declaration 37passing by value and reference 56scope 38

WWeb authoring tools

using with PowerDynamo 34while statements

about 45wildcards 73with statements

about 49wizards

creating 301Write method (document object) 142Write(s) method (file object) 196WriteLine(s) method (file object) 197WriteLn method (document object) 142

Page 359: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Index

XXML

FORMATTING 13ResultsToXML method 286

xmlEscape function (built-in) 65

Page 360: PowerDynamo - Unione Parmense Degli Industriali · Contents Paths ..... 73 Wildcards..... 73

Index

340