0% found this document useful (0 votes)
3 views108 pages

Scripting

The Wonderware Application Server Scripting Guide provides comprehensive information on scripting within the Application Server environment, including syntax, script types, and execution methods. It covers both simple and complex scripts, detailing their structure, required syntax, and various functions available for scripting. Additionally, the guide includes examples and technical support contact information for users seeking assistance.

Uploaded by

Elbari Omar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views108 pages

Scripting

The Wonderware Application Server Scripting Guide provides comprehensive information on scripting within the Application Server environment, including syntax, script types, and execution methods. It covers both simple and complex scripts, detailing their structure, required syntax, and various functions available for scripting. Additionally, the guide includes examples and technical support contact information for users seeking assistance.

Uploaded by

Elbari Omar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Wonderware - Application Server

Scripting Guide
© 2017 Schneider Electric Software, LLC. All rights reserved.
No part of this documentation shall be reproduced, stored in a ret rieval system, or transmitted by any
means, electronic, mechanical, photocopying, rec ording, or otherwise, without the prior written
permission of Schneider Electric Soft ware, LLC. No liability is assumed with respect to the use of the
information contained herein.
Although precaution has been taken in the preparation of this documentation, Schneider Electric
Software, LLC assumes no responsibility for errors or omissions. The information in this documentation
is subject to change without notice and does not represent a commitment on the part of Schneider
Electric Software, LLC. The software described in this documentation is furnished under a license
agreement. This software may be used or copied only in accordance wit h the terms of such license
agreement.
ArchestrA, A vantis, DYNS IM, eDNA, EYESIM, Foxboro, Foxboro E vo, I/A S eries, InBatch, InduS oft,
InStep, IntelaTrac, InTouch, PIPEPHASE, PRiSM, PRO/ II, PROVIS ION, ROMeo, Schneider Electric,
SIM4ME, SimCentral, SimSci, Skelta, SmartGlance, Spiral Soft ware, VIS UAL FLA RE, WindowMaker,
WindowViewer, and Wonderware are trademarks of Schneider Electric SE, its subsidiaries, and
affiliated companies. An extensive listing of Schneider Electric Soft ware, LLC trademarks can be found
at: [Link] All other brands may be trademarks of
their respective owners.
Schneider Electric Soft ware, LLC
26561 Rancho Park way South
Lake Forest, CA 92630 U.S.A.
(949) 727-3200
[Link]
Publication date: 2/24/2017
Wonderware - Application Server Scripting Guide

Contents
Chapter 1 Common Scripting Environment ....................................................................... 9
Script Editing Styles and Syntax................................................................................................. 9
Required Syntax for Expressions and Scripts .............................................................................. 9
Simple Scripts......................................................................................................................... 10
Script Execution Types ............................................................................................................ 10
Startup Scripts .................................................................................................................. 10
OnScan Scripts ................................................................................................................. 10
Execute Scripts ................................................................................................................. 10
OffScan Scripts ................................................................................................................. 11
Shutdown Scripts .............................................................................................................. 11
Deployment Scripts ........................................................................................................... 11
Working with QuickScript Editor Features ................................................................................. 12
Color Indicators for Script Elements .................................................................................... 12
Autocomplet e.................................................................................................................... 13
Accepting Autocomplete Suggestions ................................................................................. 17
Multi-level Undo and Redo ................................................................................................. 17
Dynamic Referencing Considerations ................................................................................. 17
Run-Time Client Script Behavior ........................................................................................ 18
Opening a Client Application Window ................................................................................. 18
Closing a Client Application Window................................................................................... 18
Minimizing a Client Application Window .............................................................................. 19
Maximizing or Restoring a Client Application Window .......................................................... 19
Visual Indication of Script Errors ......................................................................................... 19
Line Numbers ................................................................................................................... 19
Log Functions ................................................................................................................... 19

Chapter 2 QuickScript .NET Functions ............................................................................ 21


Script Functions ...................................................................................................................... 21
Graphic Client Functions .................................................................................................... 21
GetCPQuality() ............................................................................................................ 21
GetCP TimeStamp() ..................................................................................................... 22
HideGraphic().............................................................................................................. 22
HideS elf().................................................................................................................... 23
Logoff() ....................................................................................................................... 23
ShowGraphic () ............................................................................................................ 24
ShowLoginDialog() ...................................................................................................... 33
Math Functions ................................................................................................................. 33
Abs() .......................................................................................................................... 33
ArcCos() ..................................................................................................................... 34
ArcSin() ...................................................................................................................... 34
ArcTan() ..................................................................................................................... 35
Cos() .......................................................................................................................... 35
Exp() .......................................................................................................................... 35
Int() ............................................................................................................................ 36

3
Wonderware - Application Server Scripting Guide Contents

Log()........................................................................................................................... 36
Log10() ....................................................................................................................... 36
LogN() ........................................................................................................................ 37
Pi() ............................................................................................................................. 37
Round() ...................................................................................................................... 37
Sgn() .......................................................................................................................... 38
Sin() ........................................................................................................................... 38
Sqrt() .......................................................................................................................... 39
Tan() .......................................................................................................................... 39
Trunc ()........................................................................................................................ 39
Miscellaneous Functions .................................................................................................... 40
ActivateA pp() .............................................................................................................. 40
DateTimeGMT() .......................................................................................................... 41
IsBad()........................................................................................................................ 42
IsGood() ..................................................................................................................... 42
IsInitializing() ............................................................................................................... 43
IsUnc ertain() ............................................................................................................... 43
IsUsable() ................................................................................................................... 43
LogCustom() ............................................................................................................... 44
LogDataChangeE vent() ............................................................................................... 45
LogE rror() ................................................................................................................... 45
LogMessage() ............................................................................................................. 46
LogTrace() .................................................................................................................. 46
LogWarning() .............................................................................................................. 47
SendKeys() ................................................................................................................. 48
SetAttributeV T() .......................................................................................................... 49
SetBad() ..................................................................................................................... 50
SetGood() ................................................................................................................... 50
SetInitializing()............................................................................................................. 51
SetUncertain() ............................................................................................................. 51
SignedAlarmAck()........................................................................................................ 51
SignedWrite() .............................................................................................................. 55
WriteStatus() ............................................................................................................... 59
WWControl() ............................................................................................................... 60
String Functions ................................................................................................................ 60
DText() ....................................................................................................................... 60
StringASCII()............................................................................................................... 61
StringChar() ................................................................................................................ 61
StringCompare().......................................................................................................... 62
StringCompareNoCase().............................................................................................. 62
StringFromGMTTimeToLocal() ..................................................................................... 63
StringFromIntg() .......................................................................................................... 63
StringFromReal() ......................................................................................................... 64
StringFromTime() ........................................................................................................ 65
StringFromTimeLoc al() ................................................................................................ 65
StringInString() ............................................................................................................ 66
StringLeft () .................................................................................................................. 67
StringLen() .................................................................................................................. 67
StringLower() .............................................................................................................. 68
StringMid() .................................................................................................................. 68
StringReplace() ........................................................................................................... 69
StringRight()................................................................................................................ 70
StringSpace() .............................................................................................................. 70
StringTest() ................................................................................................................. 71
StringToIntg() .............................................................................................................. 72
StringToReal()............................................................................................................. 72
StringTrim() ................................................................................................................. 73

4
Contents Wonderware - Application Server Scripting Guide

StringUpper() .............................................................................................................. 74
Text().......................................................................................................................... 74
WWStringFromTime() .................................................................................................. 75
System Functions.............................................................................................................. 75
CreateObject()............................................................................................................. 75
Now() ......................................................................................................................... 76
WWDDE Functions ........................................................................................................... 76
WWExecute() .............................................................................................................. 76
WWPoke() .................................................................................................................. 77
WWRequest() ............................................................................................................. 78
Chapter 3 QuickScript .NE T Variables .................................................................................... 81
Numbers and Strings ......................................................................................................... 83
QuickScript .NET Cont rol Structures......................................................................................... 84
IF … THE N … ELSEIF … ELSE … ENDIF ......................................................................... 84
IF … THE N … ELSEIF … ELSE … ENDIF and Attribut e Quality .......................................... 85
FOR … TO … S TEP … NE XT Loop ................................................................................... 86
FOR EACH … IN … NE XT ................................................................................................ 87
TRY ... CATCH ................................................................................................................. 87
WHILE Loop ..................................................................................................................... 88
QuickScript .NET Operators..................................................................................................... 89
Parentheses ( ) ................................................................................................................. 91
Negation ( - )..................................................................................................................... 91
Complement ( ~ ) .............................................................................................................. 91
Power ( ** ) ....................................................................................................................... 91
Multiplication ( * ), Division ( / ), Addition ( + ),Subtraction ( - ) .............................................. 91
Modulo (MOD) .................................................................................................................. 91
Shift Left (SHL), Shift Right (S HR) ...................................................................................... 92
Bitwise AND ( & ) .............................................................................................................. 92
Exclusive OR (^) and Inclusive OR ( | ) ............................................................................... 92
Assignment ( = ) ................................................................................................................ 92
Comparisons ( <, >, <=, >=, ==, <> )................................................................................... 92
AND, OR, and NOT ........................................................................................................... 92

Chapter 4 Sample QuickScript .NET Scripts ................................................................... 95


Sample Scripts ....................................................................................................................... 96
Accessing an Excel Spreadsheet Using anImport ed Type Library .............................................. 97
Accessing an Excel Spreadsheet Using Creat eObject ............................................................... 97
Accessing an Office XP Excel Spreads heet Using an Imported Type Library ............................... 98
Calling a Web Service to Get the Temperature for a Specified Zip Code ..................................... 98
Calling a Web Service to Send an E -mail Message ................................................................... 98
Creating a Look-up Table and Doing a Look-up on It ................................................................. 99
Creating an XML Document and Saving it to Disk ..................................................................... 99
Executing a SQL Parameterized INSERT Command ............................................................... 100
Filling a String Array and Using It ........................................................................................... 100
Filling a Two-Dimensional Integer Array and Using It ............................................................... 100
Formatting a Number Using a .NE T Format 'Picture' ................................................................ 100
Formatting a Time Using a .NE T Format 'Picture' .................................................................... 101

5
Wonderware - Application Server Scripting Guide Contents

Getting the Directories Under the C Drive ............................................................................... 101


Loading an XML Document from Disk and Doing Look-ups on It .............................................. 101
Querying a SQL Server Dat abase .......................................................................................... 101
Reading a Performance Count er ............................................................................................ 101
Reading a Text File from Disk ................................................................................................ 102
Sharing a SQL Connection or Any Other .NE T Object ............................................................. 102
Using DDE to Access an Excel Spreadsheet .......................................................................... 102
Using Micros oft Exchange to Send an E-mail Message ........................................................... 102
Using Screen-Scraping to Get the Temperature for a City ........................................................ 103
Using SMTP to Send an E-mail Message ............................................................................... 103
Writing a Text File to Disk ...................................................................................................... 103
Dynamically Binding an Indirect Variable to a Reference ......................................................... 104

Index ....................................................................................................................................... 105

6
Contact Us
Contact Schneider Electric Software Technical Support
Avanti s Technical Support
Listing of regional and local country contacts: [Link]
Technical support: [Link] [Link]/
For A [Link], A vantis Approvals, [Link], and Condition Manager:
 Email: [Link]@[Link]
 Phone (8:30 a.m. to 5:00 p.m. Monday to Friday, Eastern Time):
o Toll-Free U.S. and Canada: 1-888-262-7111
o Toll-Free EMEA: 1-800-4670-6466
o Direct dial: 1-905-632-0635
For A vantis. XA:
 Email: [Link]@[Link]
 Phone (8:30 a.m. to 5:00 p.m. Monday to Friday, Eastern Time):
o Toll-Free U.S. and Canada: 1-800-991-8000
o Toll-Free EMEA: 1-800-4670-6466
o Direct dial: 1-905-632-4122
SimSci Technical Support
Listing of regional and local country contacts: [Link] -[Link]/support/simsci/
Technical support: [Link] [Link]/
 Phone (USA 8:00 a.m. to 5:00 p.m. Central Time)
o Toll-Free U.S. and Canada: 1-800-746-7241
 Email U.S. and Canada: [Link]@[Link]
Wonderware Technical Support
Listing of regional and local country contacts: [Link] -support/
Technical support: [Link]
 Priority email for Customer FIRS T Members: custfirstsupport@[Link]
 Email for customers without a support agreement: wwsupport@[Link]
 Phone
o Toll-Free North America and Latin Americ a: 1-800-966-3371
o Direct dial: 1-949-639-8500
InStep Technical Support
Cont act page: [Link]
Technical support: [Link] [Link]/
 Email: instepsupport@[Link]
 Phone (USA 8:00 a.m. to 5:00 p.m. Central Time)
o 1-312-894-7870
Schneider Electric – Smart Water Software Technical Support
 Help desk email: DK-HSO-Support@[Link]
 Help desk telephone hotline: +45 88 30 20 77 (09:00 to 16:00 Monday to Thurs day, Friday 09:00 to
15:00, Central European Time)
Contact Schneider Electric Software Learning Services
Cont act Software Learning Services for assistance regarding classes, schedule, offerings, frequently
asked questions, tuition, policies, and more.
 Email: [Link]@[Link]
 Toll-Free U.S. and Canada: 1-866-998-7246
 Direct: 1-949-639-8508
 Fax: 1-949-639-1847
Wonderware - Application Server Scripting Guide

C HAPTER 1
Common Scripting Environment
This section describes common styles, syntax, commands, and behaviors of Application Server scripts.

In This Chapter
Script Editing Styles and Syntax ...................................................................................................... 9
Required Syntax for Expressions and Scripts ................................................................................... 9
Simple Scripts .............................................................................................................................. 10
Script Execution Types.................................................................................................................. 10
Working with QuickScript Editor Features ....................................................................................... 12

Script Editing Styles and Syntax


Application Server supports two types of scripts:
 Simple scripts can perform assignments, comparisons, simple math functions, and similar actions.
Simple scripts are described in this section.
 Complex scripts can perform logical operations using conditional branching with IF -THEN-ELSE
type control structures. For more information about complex control structures, see Quick Script
.NET Control Structures on page 84.
Both single and multi-line comments are supported. Single-line comments start with a " ’ " in the line
but require no ending " ’ " in the line. Multi-line comments start with a "{" and end with a "}" and can
span multiple lines.
White space rules apply for space and indention. Indent using spaces, or the TAB key. Individual
statements are indicated by a semicolon marking the end of the statement.

Required Syntax for Expressions and Scripts


The syntax in scripts is similar to the algebraic syntax of a calculator. Most statements are presented
using the following form:
a = (b - c) / (2 + x) * xyz;
This statement places the value of the expression to the right of the equal sign (= ) in the variable
location named "a."
 A single entity must appear to the left of the assignment
operator =.
 The operands in an expression can be constants or variables.
 Statements must end with a semicolon (;).
Entities can be concatenated by using the plus (+ ) operator. For ex ample, if a data change script such
as the one below is created, each time the value of "Number" changes, the indirect entity "Setpoint"
changes accordingly:
Number=1;

9
Wonderware - Application Server Scripting Guide Common Scripting Environment

Setpoint = "Setpoint" + Text(Number, "#");


Where the result is "Setpoint1."

Simple Scripts
Simple scripts implement logic such as assignments, math, and functions. An example of this type of
scripting is:
React_temp = 150;
ResultTag = (Sample1 + Sample2)/2;
{this is a comment}

Script Execution Types


This section describes the script execution types supported by InTouch Omni.
 Startup Scripts on page 10
 OnScan Scripts on page 10
 Execute Scripts on page 10
 OffScan Scripts on page 11
 Shutdown Scripts on page 11
 Deployment Scripts on page 11

Startup Scripts
Startup scripts are called when an object containing the script is loaded into memory, such as during
deployment, plat form, or engine start.
Startup instantiat es COM objects and .NE T objects. Depending on load and other factors, assignments
to object attributes from the Startup metho d may fail. Attributes that reside off-object are not available
to the Startup method.

OnScan Scripts
OnScan scripts are called the first time an AppE ngine calls this object to execute after the object’ s
scan state changes to OnScan. The OnScan method initiates local object attribute values and provides
more flexibility in the creation of .NE T or COM objects.
Attributes that are off-engine are not available to the OnScan method.

Execute Scripts
Execute scripts are called each time the AppE ngine performs a scan and the object is OnScan.
The Execute script method is the work hors e of the scripting execution types. Use the Execute method
for your run-time scripting to ensure that all attributes and values are available to the script.
®
If the quality check-box is checked, the Execute method is similar to InTouc h scripts with the following
conditional trigger types:
 Periodic: When going OnScan, a script with a periodic trigger executes immediately (at the next
scheduled scan period of the AppEngine). It then executes periodically whenever the elapsed time
evaluates as true.
 Data Change: Executes when a data value or quality changes bet ween scans.

10
Common Scripting Environment Wonderware - Application Server Scripting Guide

For the following trigger types, data changes between each scan are not evaluat ed, only the value at
the beginning of eac h script is used for evaluati on purposes. For example, if a Boolean attribute
changes from True to False to True again during a scan cycle, this change is not evaluated as a data
change as the value is True at the beginning of each scan cycle.
 OnTrue: Executes if the expression valid ates from a false on one scan to a true on the next scan.
 OnFalse: Executes if the ex pression validates from a true on one scan to a false on the next scan.
These scripts also have time-based considerations. A trigger period of 0 means that the script
executes every scan.
Time-based scripts, WhileTrue, WhileFalse, and Periodic are evaluated and ex ecuted based on the
elapsed time from a timestamp generated from the previous execution, not on an elapsed time counter.
It is possible that a change in the system clock can change the interval between execution of these
scripts.
 WhileTrue: Executes scan to scan as long as the expression validates as true at the beginning of
the scan.
 WhileFalse: Executes scan to scan as long as the expression validat es as false at the beginning of
the scan.
For example, a periodic script is set to run every 60 minutes. The script executes at 11:13 AM. We
expect it to execute 60 minutes later at 12:13 PM. However, a time synchronization event occurred and
the node’s time is adjusted from 11:33 AM to 11:30 AM.
The script still executes when the system time reaches 12:13 PM. But because of the time change, the
actual (True) time period that elapsed bet ween executions is 63 minutes.

OffScan Scripts
OffScan scripts are called when the object is taken OffScan. This script type is primarily used to clean
up the object and account for any needs to address as a result of the object no longer exec uting.
If an object is taken OffScan, either directly, or indirectly because its engine is taken OffScan, all
in-progress asynchronous scripts for that object are requested to shut down by setting a Boolean
shutdown attribute for the script to true. A well-written script checks this attribute before and after
time-consuming operations. If the script takes more than 30 seconds to complete, a warning appears in
the logger that the script is not responding to the shutdown comm and. However, the script is allowed to
complete and is not terminated by forc e. This all takes place on the engine’s main thread and could
potentially hang the engine. During this time, the script might also time out and as a result exit before
executing all its logic.

Shutdown Scripts
Shutdown scripts are called when the object is about to be removed from memory, usually as a result
of the AppEngine stopping. Shutdown scripts are primarily used to destroy COM objects and .NE T
objects and to free memory.

Deployment Scripts
Deploying objects is both a critical and a load-intensive process for a Galaxy. Implementing scripting in
the Startup and OnScan methods can adversely affect a Galaxy’s deployment and redundancy
performance.
While objects are being deployed, their St artup and, if deployed OnScan scripts are ex ecuted. These
scripts must complete within the deployment time-out period for the deployment to be successful.

11
Wonderware - Application Server Scripting Guide Common Scripting Environment

Placing large numbers of scripts, or scripts that require heavy processing power into the Startup or
OnScan script methods can slow or cause a deployment or failover to fail. In addition to the load that is
placed on the system at deployment time, the type of scripting done in the Start up and OnScan
methods is also important becaus e these scripts execute in a sequence.
During deployment and restart, the Startup and OnScan script methods do not execute objects based
on execution order. Objects are started up and placed on scan based on their alphanumeric tag name
within their hosting A rea.
Follow the recommendation below for each type of script method to help determine what scripting
practices to follow in each script method.
Do not place the following types of scripting in the Startup or OnScan methods:
 Database access
 File system access, .csv, .xml, .txt, and so on
 Off-object referencing
 Dynamic referencing

Working with QuickScript Editor Features


The QuickScript edit or provides a number of features to enhance scripting speed and accuracy.

Color Indicators for Script Elements


The QuickScript .NE T editor uses different text colors to identify different script elements. The following
table shows the text colors associated with script elements.

Element Color

Keywords Blue
Syntax highlight ed while typing.

Comments (bot h single line and Green


multi-line)
Syntax highlight ed while typing.

Strings Purple
Syntax highlight ed while typing.

Function names, numeric constants, Black


operators, semicolons, dim
See descriptions for Attribute names
variables, alias variables, and so on
and Reserved words.

Attributes, InTouch Tags, Reference Maroon, bold face


Strings

Reserved words Red, non-bold face

.NET type names Teal, non-bold face

12
Common Scripting Environment Wonderware - Application Server Scripting Guide

Autocomplete
QuickScript autocomplete incorporates several features for use while authoring object and client
scripts:
 Provides an autocomplete Attribute reference when you type a generic object name, such as "me."
Run-time attributes appear in an autocom plete list box. Typing "InTouch:" displays an
autocomplete list of tagnames from the most recently selected ViewApp templat e.
 Provides method parameter help in an autocomplete list box including context -specific suggestions
covering definitions, keywords, script elements, and programmatic constructs such as try ... catch
or while ... endwhile.
 Automatic word completion of Attribute references, methods, programmatic constructs, and other
script elements.
These features serve as convenient documentation of method parameters and scripting syntax as well
as an enhanc ed input method.
Autocomplet e displays a context-sensitive list of options for script elements, keywords, object and
attribute names, and programmatic constructs. Press Ctrl+space to display all available autocomplete
options and variables for the selected location in the script. You can identify the cont ext from the icons
displayed with the list items.

Icon Represents

MxBoolean attribute

MxInteger attribute

MxFloat attribute

MxDouble attribute

MxString attribut e

MxTime attribute

MxElapsedTime attribut e

MxReference attribute

MxStatus attribute

MxDataTypeEnum attribute

13
Wonderware - Application Server Scripting Guide Common Scripting Environment

Icon Represents

MxSecurityClassification attribute

MxDataQuality attribute

MxQualifiedE num attribute

MxQualifiedStruct attribute

MxInternationalizedString attribute

.Net Method

.Net Property

.Net Field or Variable

.Net Namespace

.Net Struct

.Net Class

.Net Interface

.Net Enumeration

.Net Enum Value

QuickScript Keyword

14
Common Scripting Environment Wonderware - Application Server Scripting Guide

Icon Represents

Cont ained object name, or any partial attribute


name such as a attribute, field attribute, or
primitive that has a dot in the name, or any
attribute of Mx type MxNone, or if there are
several type choices among objects and
attributes.
If the attribut e cannot be exactly or
unambiguously returned, this icon will appear.
Partial name example: For [Link].a1, typing
"[Link]" will show the blue ball icon for alarm.
MxNone example: input/output extension
attribute WriteValue.

Rectangle

Rounded rectangle

Line

Horiz ontal or vertical line

Text

Ellipse

Curve

Closed curve

Button

Polygon

Polyline

Connect

15
Wonderware - Application Server Scripting Guide Common Scripting Environment

Icon Represents

Image

Group or embedded symbol

Alarm control

Edit box

Arc

Pie

Chord

Circle

Status

Radio buttons

Checkbox

Edit box

Combo box

Calendar

Date picker

List box

16
Common Scripting Environment Wonderware - Application Server Scripting Guide

Accepting Autocomplete Suggestions


Insert an item at the edit or caret from the autocomplete list box —without an end line or tab
appended—by doing one of the following:
 Double-click the item
 Highlight (select) the item and press the Enter key or the Tab key.
Type a space, period, comma, open or closed parent hesis, or other punctuation used in the
QuickScript .NET programming language (: ; [ ] = < > - + / *), and the item highlighted in the
autocomplete list box will be inserted at the editor caret with the additional character appended.

Multi-level Undo and Redo


You can selectively undo a history of changes to your script. The number of changes that can be
undone is limited only by the amount of available memory.
An undone change can be redone. Redo mirrors undo changes.
A single undo typically is comprised of sequences of typing or deleting, which can be interru pted by
interaction with an autocomplete list or by moving the cursor with the mouse, or by clicking elsewhere
in the script.
All pending undo and redo actions will be lost if you close the object editor, switch to another script
within the object editor, or switch among Start up, OnScan, Execute, OffScan, and S hutdown scripts.

Dynamic Referencing Considerations


Dynamic reference scripting is one the biggest causes of deployment [Link] StartUp and On Scan
execution types.
Rather than placing dynamic referencing scripts in the Startup or OnScan methods, perform dynamic
referencing in the Execute method. There are several advantages to using the Execute method with
dynamic reference scripting:
 Deployment is faster.
 Deployment is more reliable.
 Deterministic execution order is guaranteed.
 Off-object and off-engine attributes are available.
 After a failover occurs, the startup of the redundant engine is more stable and can be faster.
To create a simple dynamic reference script example
1. Create a Boolean attribute.

The attribute shows if the referencing script is complete. In this example you create Ref_Done.
IO_Item1 and IO_Item2 are the I/O points referenced in this example.
2. Create the script. The script in this example is called Set_Refs. The script has a trigger type of
WhileTrue with a 0 trigger period.

The script is shown below:

17
Wonderware - Application Server Scripting Guide Common Scripting Environment

If Me.Set_Refs.ExecutionCnt == 2 then
[Link] = "[Link]." + [Link] + ".Item1";
[Link] = "[Link]." + [Link] + ".Item1";
[Link] = "[Link]." + [Link] + ".Item2";
[Link] = "[Link]." + [Link] + ".Item2";
Me.Ref_Done = True;
Endif;
This script allows the system to stabilize after going on scan before setting the referenc es. The
script executes on the first two scans of the object when the Boolean attribute Ref_Done is false.
As the script is executed, a check is made against the exec ution count. If the count equals 2, the
script performs the referencing operations. After the reference attributes are set on the attribut es,
the Ref_Done attribute is set to True. At this point the expression for the script is no longer true.
The three attributes set in this script are checkpointed, eliminating the need to run this script except
on deployment. The next time the object is started, placed on scan, or failed over, there is no need
to recreate the references to the items.

Run-Time Client Script Behavior


In Advanced Communication Management, script references to InTouch tags and object attributes are
suspended from receiving data changes when the application window containing embedded
®
ArchestrA objects is minimized in InTouch WindowViewer. Suspending data updates to hidden
objects reduces the amount of net work traffic and improves the overall performance of a client
application.
While Showing scripts of embedded symbols do not execute during the period when the window
containing the symbols is minimized. Script execution resumes after restoring or maximizing a window
that had been previously closed or minimiz ed.

Opening a Client Application Window


In Advanced Communication Management, when a client application window containing embedded
ArchestrA objects opens in WindowViewer, the following script events occur:
 Register all ArchestrA and InTouch references used in embedded symbol scripts, if not re gistered
already.
 Advise all ArchestrA and InTouch references in embedded symbol scripts within the window, if not
advis ed already.
 Execute the OnShow script on all embedded symbol scripts within the window.
 Execute named scripts if their trigger conditions are met.

Closing a Client Application Window


In Advanced Communication Management, when a client application wi ndow containing embedded
ArchestrA objects is closed, the following script events occur:
 Execute OnHide scripts of all embedded symbols within the window.
 Stop running client scripts.
 Unadvise all ArchestrA and InTouch references in the Window if there ar e no other open windows
using the references.
 Unregister all ArchestrA and InTouch references in the Window if there are no other open windows
using the references.

18
Common Scripting Environment Wonderware - Application Server Scripting Guide

Minimizing a Client Application Window


In Advanced Communication Management, when an open window containing embedded ArchestrA
objects is minimized in WindowViewer, the following script events occur:
 Stop running client scripts associated with ArchestrA objects embedded in the window.
 Unadvise all ArchestrA and InTouch references in the Window if there are no other open windows
using the references.
 OnHide scripts of embedded symbols do not execute when a window is minimized.

Maximizing or Restoring a Client Application Window


In Advanced Communication Management, after maximizing or restoring a window from
WindowViewer that had been previously minimized or closed, the following script events occur:
 Advise all ArchestrA and InTouch script references in the window, if not advised already.
 Execute named scripts if their trigger conditions are met.

Visual Indication of Script Errors


Verification errors in script text are marked with a red "squiggly" underline. The u nderline appears after
approximately 2.5 seconds of keyboard inactivity.
Hovering over the error with the mous e cursor will display the error message as a tooltip. The tooltip
error message is identical to the message shown when clicking the script verific ation button.

Note: In addition to error tooltips, the script editor will also display the variable name and type in a
tooltip when hovering over a variable name in the script.

In some cases, more than one error will be underlined. This is not always possible becaus e some
errors prevent the compiler from continuing past the error.

Line Numbers
The script editor displays line numbers in the left margin.
 Line numbers of up to four digits will display when the script editor is not zoomed.
 The line number may appear clipped for scripts longer than 9999 lines or when the script editor is
zoomed.
 Use the right-click context menu Go To function to go to a specific line in the script.

Log Functions
QuickScript .NET functions include several log functions to capture and display information in the
logger under different log flags.
 LogCustom() on page 44
 LogE rror() on page 45
 LogMessage() on page 46
 LogTrace() on page 46
 LogWarning() on page 47

19
Wonderware - Application Server Scripting Guide Common Scripting Environment

Important: To use the LogCustom function, you must enable Log Custom in the System Management
Cons ole (SMC) Log Flag Editor. To us e the LogTrace function, you must enable Log Trace in the SMC
Log Flag Editor.

20
Wonderware - Application Server Scripting Guide

C HAPTER 2
QuickScript .NET Functions
For information about other functions in this category, see third-party documentation.
Keep in mind the following limitations when you use the script functions:
 Be aware of the .NE T datatypes.
 Starting a GUI application from within a server script is not supported.
 Although QuickScript supports import libraries built with .NE T CLR version 2.0.50727, it does not
support any of the new language features introduced with .NE T 2.0, such as generics.

In This Chapter
Script Functions ............................................................................................................................ 21
QuickScript .NET Variables ........................................................................................................... 81
QuickScript .NET Cont rol Structures .............................................................................................. 84
QuickScript .NET Operators .......................................................................................................... 89

Script Functions
This section describes the script functions included in the InTouc h Omni development environment.
The function documentation is organized into a set of folders that repres ents the same organization of
the functions in the Script Function Browser.
 Graphic Client Functions on page 21
 Math Functions (see "Math Functions" on page 33)
 Miscellaneous Functions (see "Miscellaneous Functions" on page 40)
 String Functions on page 60
 System Functions on page 75
 WWDDE Functions on page 76
The Type folder contains a set of Microsoft .NE T script functions, which are not documented. Refer to
Microsoft .NE T documentation for descriptions of the functions.

Graphic Client Functions


Use graphic client functions to hide and show symbols, open and close popup windows, log in and log
off users, or to query custom properties contained in a symbol.

GetCPQuality()
Returns the Quality value of a custom property. This function is available within any ArchestrA graphic
client script.

21
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Syntax
Int GetCPQuality(String name)
Where String name is the name of the custom property whose quality is to be retrieved.
This script function takes the name of a custom property on the symbol. This argument is of type string
and it can be a referenc e or a constant.
If the custom property is type constant, GOOD is the quality always returned.

Note: For use with custom properties only. It does not apply to InTouch tags.

Return Value
The Get CPQuality() script function returns a value 0 -255 of type Int eger, as per the OPC quality
standard. 192 is GOOD.
Example
cp2 = GetCPQuality("cp1");
Where cp1 and cp2 are custom properties and the data type of cp2 is Int eger.

GetCPTimeStamp()
Returns the time stamp of a custom property. This function is available within any ArchestrA graphic
client script.
Syntax
DateTime GetCPTimeStamp(String name)
Where String name is the name of the custom property whos e time stamp is to be retrieved.
This script function takes the name of a custom property on the symbol. This argument is of type string
and it can be a referenc e or a constant.

Note: For use with custom properties only. It does not apply to InTouch tags.

Return Value
The Get CP TimeStamp() script function ret urns the time stamp of the custom property’s current value of
type DateTime. If the custom property value is a constant, then the return value is the time the value
was creat ed.
Example
cp2 = GetCPTimeStamp("cp1");
Where cp1 and cp2 are custom properties and the data type of cp2 is DateTime.

HideGraphic()
Closes an open graphic pop-up window shown in the ShowGraphic() script with the given identity
name.
The HideGraphic() function has been extended to close InTouch Windows identified with a given
identity name. This function is available wit hin any ArchestrA graphic client script.
Category
Graphic Client
Syntax
HideGraphic(string identity);

22
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Parameter
Identity
The unique name of the instance that shows the graphic.
Examples
HideGraphic("i1");
Where "i1" is string Identity.
HideGraphic("InTouch:Window1");
Where "InTouch:Window1" is the string identity.
See Also
ShowGraphic (), HideSelf()

HideSelf()
Closes the displayed graphic for which this client script is configured. This script function is available
within any ArchestrA graphic client script.
Category
Graphic Client
Syntax
HideSelf();
Remarks
You must call the script function within the symbol to hide the popup.
Example
HideSelf();
See Also
ShowGraphic (), HideGraphic()

Logoff()
Action script that automatically logs off the current user from a ViewApp.
Action scripts are graphic animations that are triggered by a user action such as a mouse click.
Category
Miscellaneous
Syntax
LogOff() ;
Parameter
None
Trigger
On Left-Click/Key/Touc h Down

23
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Additional Information
A log off button can be added that uses the Logoff() method to allow the user to log off from the
ViewApp.
Example
Logoff() ;
See Also
ShowLoginDialog() on page 33

ShowGraphic()
Shows a graphic within a pop-up window. The ShowGraphic() function has been extended to call
InTouch Windows. This function is available within any ArchestrA graphic client script.
Category
Graphic Client
Syntax
Show a graphic within a pop-up window
Dim graphicInfo as [Link];
[Link] = "<Identity>";
[Link] = "<SymbolName>";
ShowGraphic( graphicInfo );
Call an InTouch window
Dim graphicInfo as [Link];
[Link] = "<InTouch:WindowName>";
ShowGraphic( graphicInfo );
Parameter
GraphicInfo
Data Type
[Link] Info
Examples
Show graphic within a pop-up window
ShowGraphic (graphicInfo);
Show an InTouch window
Dim graphicInfo0 as [Link];
[Link] = "InTouch:Window1";
ShowGraphic( graphicInfo0 );
[Link] Properties
Any string properties can be a conc atenation of strings and/or custom properties.
Identity
A unique name that identifies which instance has opened the graphic.
Data Type
String
Additional Information
Mandatory
The same Identity is used in the HideGraphic() script function to close the pop-up window.

24
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Valid Range
The name cannot contain more than 329 characters.
The name must contain at least one letter.
Valid characters are alphanumeric and special characters ($, #, _).
Example
[Link] = "i1";
GraphicName
The name of the graphic to show.
Data Type
String
Valid Range
The name cannot contain more than 329 characters.
The name must contain at least one letter.
Valid characters are alphanumeric and special characters ($, #, _).
Additional Information
Mandatory
Browse using the Di splay Galaxy Browser or directly type the graphic name.
Galaxy name can come from:
o Graphic Toolbox, for example:
"Symbol_001"
o Instances, absolute or hierarchical, for example:
"Userdefined_001.Symbol1", "Userdefined_001.Pump_001.S1"
o Relative reference, for example:
"Me.Symbol_001"
If you type any invalid character or exceed the character limit, the system shows a warning
message at run time. There is no validation at design time.
The graphic name can be a concatenation of constant strings and reference strings. For
example:"Pump_001" + ".Symbol_001"; cp1 + ".Symbol_001", where the value of
cp1 = "Pump_001"; or Obj1.Str1 + ".Symbol_001", where the value of Obj.Str1
= "Pump_001".
Example
[Link] = "S1";
OwningObject
The owning object of the graphic shown by the ShowGraphic() script function
Data Type
String
Default Value
Empty
Additional Information
Optional
Can be a concat enation of constant strings and reference strings.
Can be browsed using the Di splay Automation Object Brow ser, or you can type the name of the
owning object.
Example
[Link] = "UserDefined_001";
HasTitleBar
Determines if the graphic is shown with a title bar.

25
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Data Type
Boolean
Default Value
True
Example
[Link] = false;
WindowTitle
Specifies the title shown in the window title bar.
Data Type
String
Default Value
Empty
Valid Range
Limit 1024 characters
Additional Information
Can be a constant string, a reference, or an ex pression.
If you change the owning object for an Aut omationObject graphic, the window title is updated
accordingly.
If the WindowTitle parameter is empty, the value of the Identity parameter is shown on the title bar.
Example
[Link] = "Graphic01";
WindowType
Specifies whether window type is modal or modeless.
Data Type
Enum
Default Value
Modeless
Valid Range
0, 1
Enumerations

WindowType Integer

Modal 0

Modeless 1

Examples
[Link] = [Link].<windowtype>;
[Link] = 1;
HasCloseButton
Determines if the pop-up window has a close button.
Data Type
Boolean
Default Value
True
26
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Example
[Link] = false;
Resizable
Determines if the pop-up window is resizable.
Data Type
Boolean
Default Value
False
Example
[Link] = true;
WindowLocation
Specifies the loc ation of the pop-up window.
Data Type
Enum
Default Value
Cent er
Valid Range
One of 0–12
Enumerations

WindowLocation Integer

Cent er 0

Above 1

TopLeftCorner 2

Top 3

TopRight Corner 4

LeftOf 5

LeftSide 6

RightSide 7

Right Of 8

BottomLeftCorner 9

Bottom 10

BottomRightCorner 11

Below 12

Additional Information
If you have selected Desktop as the window relative position, Above, LeftOf, RightOf, and Below
are invalid.

27
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

For more information about the behavior of the WindowLocation parameter, see Chapter 16,
"Working with the Show/ Hide Graphics Script Functions,"in the Creating and Managing ArchestrA
Graphics User’s Guide.
Examples
[Link] = [Link].<WindowLocation>;
[Link] = 1;
WindowRelativePosition
Specifies the relative position of the pop-up window.
Data Type
Enum
Default Value
Desktop
Valid Range
One of 0–8
Enumerations

WindowRelativePosition Integer

Desktop 0

Window 1

ClientArea 2

ParentGraphic 3

ParentElement 4

Mouse 5

DesktopXY 6

WindowXY 7

ClientAreaXY 8

Examples
[Link] =
[Link].<WindowRelativePosition>;
[Link] = 1;
RelativeTo
Specifies the size of the pop-up window relative to the graphic, desktop, or customized width and
height.
Data Type
Enum
Default Value
Graphic
Valid Range
One of 0–2

28
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Enumerations

RelativeTo Integer

Graphic 0

Desk Top 1

CustomizedWidt hHeight 2

Additional Information
If you enter [Link]. CustomizedWidthHeight, you can include the values of the
height and width in the script. Otherwis e, the default values are used.
Examples
[Link] = [Link].<RelativeTo>;
[Link] = 1;
X
The horizont al position of the pop -up window.
Data Type
Integer
Default Value
0
Valid Range
-2,147,483,648 through 2,147,483,647
Additional Information
If X is beyond the integer range, an overflow message appears in the Logger at run time.
This parameter is applicable only if the value of the WindowRelativePosition parameter is
DesktopXY, WindowXY, or ClientAreaXY.
Unlike the ShowSymbol animation, there is no boundary for this value.
Examples
graphicInfo.X = 100;
Y
Specifies the vertical position of the pop -up window.
Data Type
Integer
Default Value
0
Valid Range
-2,147,483,648 through 2,147,483,647
Additional Information
If Y is beyond integer range, a proper overflow message will appear in the Logger at run time.
This value is applicable only if WindowRelativePosition is DesktopXY, WindowXY, or
ClientAreaXY.
Unlike the ShowSymbol animation, there is no boundary for thi s value.
Examples
graphicInfo.Y = 100;

29
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Width
Specifies the width of the pop-up window.
Data Type
Integer
Default Value
100
Valid Range
0–10000
Additional Information
Applicable only if RelativeTo is CustomizedWidthHeight
You can specify either the height or the width of the pop -up window. The system calculates the
other, based on the aspect ratio of the symbol.
If you enter an out-of-boundary value, the system shows an "Out of range" message at run time. If
the value > 10000, it is set at 10000. If the value < 0, it is set at 0.
Examples
[Link] = 500;
Height
Specifies the height of the pop-up window.
Data Type
Integer
Default Value
100
Valid Range
0–10000
Additional Information
Applicable only if RelativeTo is the value of the CustomizedWidthHeight parameter.
You can specify either the height or the width of the pop -up window. The system calculates the
other, based on the aspect ratio of the symbol.
If you enter an out-of-boundary value, the system shows an "Out of range" message at run time. If
the value > 10000, it is set at 10000. If the value < 0, it is set at 0.
Examples
[Link] = 500;
TopMost
Sets a value that indicates whether the ShowGraphic appears in the top most z-order window. A
ShowGraphic whose Topmost property is set to true appears above all windows whose TopMost
properties are set to fals e (same as Windows Task Manager).
Data Type
Boolean
Default Value
False
Additional Information
ShowGraphic windows whose Topmost properties are set to true appear above all windows whose
Topmost properties are set to false. In a group of windows that have the Topmost property set to
true, the active window is the topmost window.

30
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Note: Do not create scripts that launch a non-TopMost Modal dialog from a TopMost dialog. Users
will not be able to interact with the View if the Modal dialog is completely hidden by any TopMost
window.

Example
[Link] = true;
ScalePercentage
Sets the scaling percentage of the pop-up window and the graphic it contains.
Data Type
Integer
Default Value
100
Valid Range
0–1000
Additional Information
If you enter an out-of-boundary value, the system shows an "Out of range" message at run time. If
the value > 1000, it is set at 1000. If the value < 0, it is set at 0.
Examples
[Link] = 150;
KeepOnMonitor
Specifies that a pop-up window should appear entirely within the boundaries of an application
window.
Data Type
Boolean
Default Value
True
Example
[Link] = true;
StretchGraphicToFitWindowSize
Determines if the graphic is scaled to the current size of the pop-up window.
Data Type
Boolean
Default Value
True
Additional Information
Applicable only if the value of the ScalePercent age parameter is greater than 100.
Examples
[Link] = false;
StretchWindowToScreenWidth
Determines if the pop-up window is scaled to the same width as the screen.
Data Type
Boolean
Default Value
False

31
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Additional Information
Applicable only if the WindowRelativePosition parameter is Desktop, Window, Client Area,
ParentGraphic, or ParentElement.
Examples
[Link] = true;
StretchWindowToScreenHeight
Determines if the pop-up window is scaled to the same height as the screen.
Data Type
Boolean
Default Value
False
Additional Information
Applicable only if the WindowRelativePosition parameter is Desktop, Window, Client Area,
ParentGraphic, or ParentElement.
Examples
[Link] = true;
CustomProperties
Sets the custom properties of the symbol being shown.
Data Type
CustomPropertyValueP air[] array
Additional Information
The first three parameters are custom property name, value, and Is Constant.
Both custom property and the value can be a constant string, reference, or concatenation of
strings.
If the parameter IsConstant = True, the value is treated as a constant. Otherwise, the value is
treated as a referenc e.
The array index starts at 1.
Examples
Dim cpValues [4] as [Link];
cpValues[1] = new [Link]("CP1", 20, true);
cpValues[2] = new [Link]("CP2", [Link],
true);
cpValues[3] = new [Link]("CP3", "CP"+var1, CP2 +
"001" + ".Speed", true);
cpValues[4] = new [Link]("CP3", "InTouch:Tag1",
false);
[Link] = cpValues;
Remarks
Any parameter that has default value in the GraphicInfo is optional. If no input value specified for these
parameters, the default values are used at run time. Any parameter except the Enum data type can be
a constant, reference, or expression.
For more information, see Chapter 16, "Working with the Show/ Hide Graphics Script Functions,"in the
Creating and Managing ArchestrA Graphics User’s Guide.
Examples for ShowGraphic
Basic script example:
Dim graphicInfo as [Link];
[Link] = "Script_001";
[Link] = "Symbol_001";

32
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

ShowGraphic( graphicInfo );
Advanced script example:
Dim graphicInfo as [Link];
Dim cpValues [2] as [Link];
cpValues[1] = new [Link]("CP1", 20, true);
cpValues[2] = new [Link]("CP2", "[Link]",
false);
[Link] = "i1";
[Link] = "S1";
[Link] = "UserDefined_001";
[Link] = "Graphic01";
[Link] = false;
[Link]=cpValues;
ShowGraphic( graphicInfo );
Where "i1" is string Identity and the symbol "S1" contains custom property CP1 and CP2.
See Also
ShowGraphic (), HideSelf()

ShowLoginDialog()
Action script that shows a login dialog box with fields to enter a username and password. A typical
login interface includes a login button that is selected by the user to show the Login dialog box with
fields to enter a username and password.
Action scripts are graphic animations that are triggered by a user action such as a mouse click.
Category
Miscellaneous
Syntax
ShowLoginDialog() ;
Parameter
None
Trigger
On Left-Click/Key/Touc h Down
Additional Information
A log off button can be added that uses the Logoff() method to allow the user to log off from the
ViewApp.
Example
ShowLoginDialog() ;
See Also
Logoff() on page 23

Math Functions
Use math functions to return the ans wer to the specified mathematical expression.

Abs()
Returns the absolute value (unsigned equivalent) of a specified number.

33
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Category
Math
Syntax
Result = Abs( Number );
Parameter
Number
Any number or numeric attribut e.
Examples
Abs(14); ' returns 14
Abs(-7.5); ' returns 7.5

ArcCos()
Returns an angle between 0 and 180 degrees whose cosine is equal to the number specified.
Category
Math
Syntax
Result = ArcCos( Number );
Parameter
Number
Any number or numeric attribut e with a value bet ween -1 and 1 (inclusive).
Examples
ArcCos(1); ' returns 0
ArcCos(-1); ' returns 180
See Also
Cos(), Sin(), Tan(), ArcSin(), ArcTan()

ArcSin()
Returns an angle between -90 and 90 degrees whose sine is equal to the number specified.
Category
Math
Syntax
Result = ArcSin( Number );
Parameter
Number
Any number or numeric attribut e with a value bet ween -1 and 1 (inclusive).
Examples
ArcSin(1); ' returns 90
ArcSin(-1); ' returns -90
See Also
Cos(), Sin(), Tan(), Arc Cos(), ArcTan()

34
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

ArcTan()
Returns an angle between -90 and 90 degrees whose tangent is equal to the number specified.
Category
Math
Syntax
Result = ArcTan( Number );
Parameter
Number
Any number or numeric attribut e.
Examples
ArcTan(1); ' returns 45
ArcTan(0); ' returns 0
See Also
Cos(), Sin(), Tan(), Arc Cos(), ArcSin()

Cos()
Returns the cosine of an angle in degrees.
Category
Math
Syntax
Result = Cos( Number );
Parameter
Number
Any number or numeric attribut e.
Examples
Cos(90); ' returns 0
Cos(0); ' returns 1
This example shows how to use the function in a math equation:
Wave = 50 * Cos(6 * Now().Second);
See Also
Sin(), Tan(), Arc Cos(), ArcSin(), ArcTan()

Exp()
Returns the result of the ex ponent e raised to a power.
Category
Math
Syntax
Result = Exp( Number );
Parameter
Number
Any number or numeric attribut e.

35
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Example
Exp(1); ' returns 2.718...

Int()
Returns the next integer less than or equal to a specified number.
Category
Math
Syntax
IntegerResult = Int( Number );
Parameter
Number
Any number or numeric attribut e.
Remarks
When handling negative real (float) numbers, this function returns the integer farthest from zero.
Examples
Int(4.7); ' returns 4
Int(-4.7); ' returns -5

Log()
Returns the natural log (base e) of a number.
Category
Math
Syntax
RealResult = Log( Number );
Parameter
Number
Any number or numeric attribut e.
Remarks
Natural log of 0 is undefined.
Examples
Log(100); ' returns 4.605...
Log(1); ' returns 0
See Also
LogN(), Log10()

Log10()
Returns the base 10 log of a number.
Category
Math
Syntax
Result = Log10( Number );

36
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Parameter
Number
Any number or numeric attribut e.
Example
Log10(100); ' returns 2
See Also
Log(), LogN()

LogN()
Returns the values of the logarithm of x to base n.
Category
Math
Syntax
Result = LogN( Number, Base );
Parameters
Number
Any number or numeric attribut e.
Base
Integer to set log base. You could also specify an integer attribute.
Remarks
Base 1 is undefined.
Examples
LogN(8, 3); ' returns 1.89279
LogN(3, 7); ' returns 0.564
See Also
Log(), Log10()

Pi()
Returns the value of Pi.
Category
Math
Syntax
RealResult = Pi();
Example
Pi(); ' returns 3.1415926

Round()
Rounds a real number to a specified precision and returns the result.
Category
Math

37
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Syntax
RealResult = Round( Number, Precision );
Parameters
Number
Any number or numeric attribut e.
Precision
Sets the precision to which the number is rounded. This value can be any number or a numeric
attribute.
Examples
Round(4.3, 1); ' returns 4
Round(4.3, .01); ' returns 4.30
Round(4.5, 1); ' returns 5
Round(-4.5, 1); ' returns -4
Round(106, 5); ' returns 105
Round(43.7, .5); ' returns 43.5
See Also
Trunc ()

Sgn()
Determines the sign of a value (whether it is positive, zero, or negative) and returns the result.
Category
Math
Syntax
IntegerResult = Sgn( Number );
Parameter
Number
Any number or numeric attribut e.
Return Value
If the input number is positive, the result is 1. Negative numbers ret urn a -1, and 0 returns a 0.
Examples
Sgn(425); ' returns 1;
Sgn(0); ' returns 0;
Sgn(-37.3); ' returns -1;

Sin()
Returns the sine of an angle in degrees.
Category
Math
Syntax
Result = Sin( Number );
Parameter
Number
Angle in degrees. Any number or numeric attribute.

38
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Examples
Sin(90); ' returns 1;
Sin(0); ' returns 0;
This example shows how to use the function in a math ex pression:
wave = 100 * Sin (6 * Now().Second);
See Also
Cos(), Tan(), ArcCos(), ArcSin(), ArcTan()

Sqrt()
Returns the square root of a number.
Category
Math
Syntax
RealResult = Sqrt( Number );
Parameter
Number
Any number or numeric attribut e.
Example
This example takes the value of [Link] and returns the square root as the value of x:
x=Sqrt([Link]);

Tan()
Returns the tangent of an angle given in degrees.
Category
Math
Syntax
Result = Tan( Number );
Parameter
Number
The angle in degrees. Any number or numeric attribute.
Examples
Tan(45); ' returns 1;
Tan(0); ' returns 0;
This example shows how to use the function in a math ex pression:
Wave = 10 + 50 * Tan(6 * Now().Second);
See Also
Cos(), Sin(), ArcCos(), ArcSin(), ArcTan()

Trunc()
Trunc ates a real (floating point ) number by simply eliminating the portion to the right of the decimal
point, including the decimal point, and returns the result.

39
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Category
Math
Syntax
NumericResult = Trunc( Number );
Parameter
Number
Any number or numeric attribut e.
Remarks
This function accomplishes the same result as placing the contents of a float type attribute into an
integer type attribut e.
Examples
Trunc(4.3); ' returns 4;
Trunc(-4.3); ' returns -4;
See Also
Round()

Miscellaneous Functions
Functions in the miscellaneous group perform a variety of purposes, such as logging data or querying
attributes.

ActivateApp()
Restores, minimizes, maximizes, or closes another currently running Windows application.
Category
Miscellaneous
Syntax
ActivateApp( TaskName );
Parameter
Task Name
The task this function activates.
Remarks
Task Name is the exact text string, including spac es, that appears on the Task Bar or in Windows Task
Manager. You can see the task name by opening Task Manager.
Example
ActivateApp("Calculator");

Filtering Events
To get only specific events, filters can be introduced before getting events from the event service. The
filtering should be done before the StartRequestingE vent () method is called.
The following datatypes are supported when filtering the events.
 Integer
 Float
 String

40
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

 Bool
 DateTime
 Double
 Short
 Array
The following table shows the comparison types that are supported for filtering events.

Compari son Keyword Description

eq Means EqualTo. Returns all the events matching the filtered criteria.

beginswith Means StartsWith. Returns all the events matching the filtered criteria. Applies only to
string data type filtering

lt Means Lesser Than. Applies to all support ed data types excluding string. It does not
support arrays.

le Means Lesser or Equal. Applies to all supported data types excluding string. It does not
support arrays.

gt Means Great er Than. Applies to all supported data types excluding string. It does not
support arrays.

ge Means Great er or Equal. Applies to all supported data types excluding string. It does not
support arrays.

between Checks will be made only to paired supplied values. Returns all the events matching the
filtered criteria. It supports numeric and date datatypes.

neg, nbegins, nlt, nle, ngt, A keyword 'n' before the comparis on keyword Means NOT of.
nge, nbetween

DateTimeGMT()
Returns a number representing the number of days and fractions of days since January 1, 1970, in
Coordinated Universal Time (UTC), regardless of the local time zone.
Category
Miscellaneous
Syntax
Result=DateTimeGMT();

41
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Parameters
None
Example
MessageTag = StringFromTime(DateTimeGMT() * 86400.0, 3);

IsBad()
Returns a Boolean value indicating if the quality of the specified attribute is Bad.
Category
Miscellaneous
Syntax
BooleanResult = IsBad( Attribute1, Attribute2, … );
Parameter(s)
Attribute1, Attribute2, ...AttributeN
Names of one or more attribut es for which you want to determine Bad quality. You can include a
variable-lengt h list of attributes.
Return Value
If any of the specified attributes has Bad quality, then true is returned. Otherwise, false is returned.
Examples
IsBad([Link]);
IsBad([Link], [Link]);
See Also
IsGood(), IsInitializing(), IsUncertain(), IsUsable()

IsGood()
Returns a Boolean value indicating if the quality of the specified attribute is Good.
Category
Miscellaneous
Syntax
BooleanResult = IsGood( Attribute1, Attribute2, … );
Parameter(s)
Attribute1, Attribute2, and so on
Name of the attribut e(s) for which you want to determine Good quality. You can include a
variable-lengt h list of attributes.
Return Value
If all of the specified attributes have Good quality, then true is returned. Otherwise, false is returned.
Examples
IsGood([Link]);
IsGood([Link], [Link]);
See Also
IsBad(), IsInitializing(), IsUncertain(), IsUsable()

42
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

IsInitializing()
Returns a Boolean value indicating if the quality of the specified attribute is Initializing.
Category
Miscellaneous
Syntax
BooleanResult = IsInitializing( Attribute1, Attribute2, … );
Parameter(s)
Attribute1, Attribute2, and so on
Name of the attribut e(s) for which to determine Initializing quality. You can include a variable-length
list of attributes.
Return Value
If any of the specified attributes has Initializing quality, then true is ret urned. Otherwise, false is
returned.
Examples
IsInitializing([Link]);
IsInitializing([Link], [Link]);
See Also
IsBad(), IsGood(), IsUncertain(), IsUsable()

IsUncertain()
Returns a Boolean value indicating if the quality of the specified attribute is Unc ertain.
Category
Miscellaneous
Syntax
BooleanResult = IsUncertain( Attribute1, Attribute2, … );
Parameter(s)
Attribute1, Attribute2, and so on
Name of the attribut e(s) to determine Uncertain quality. You can include a variable-length list of
attributes.
Return Value
If all of the specified attributes have Uncert ain quality, then true is returned. Otherwise, false is
returned.
Examples
IsUncertain([Link]);
IsUncertain([Link], [Link]);
See Also
IsBad(), IsGood(), IsInitializing(), IsUsable()

IsUsable()
Returns a Boolean value indicating if the specified attribute is usable for calculations.

43
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Category
Miscellaneous
Syntax
BooleanResult = IsUsable( Attribute1, Attribute2, … );
Parameter(s)
Attribute1, Attribute2, ...AttributeN
Name of one or more attributes for which you want to determine unusable quality. You can include
a variable-length list of attributes.
Return Value
If all of the specified attributes have either Good or Uncert ain quality, then true is returned. Otherwise,
false is returned.
Remarks
To qualify as usable, the attribut e must have Good or Unc ertain quality. In addition, each float or
double attribute cannot be a NaN (not a number).
Examples
IsUsable([Link]);
IsUsable([Link], [Link]);
See Also
IsBad(), IsGood(), IsInitializing(), IsUncertain()

LogCustom()
Writes a user-defined custom flag message in the Log Viewer.
Category
Miscellaneous
Syntax
LogCustom( CustomFlag, msg );
Parameter
CustomFlag
Creates a new log flag based on the first parameter string. The first call creates the custom flag.
msg
The message to writ e to the Log Viewer. Actual string or a string attribute.
Remarks
The log flag is disabled by default.
The message is always logged under the component "[Link]". For ex ample,
"WinPlatform_001.script1: msg", which identifies what object and what script within the object logged
the error.
LogCustom() is similar to LogMessage(), but displays the message in the custom log flag when Log
Custom is enabled.
The parameter help tooltip and Function Browser sample parameter list will show "LogCustom(
CustomFlag, msg )" rather than "LogCustom( CustomFlag, Message )". "Message" is a reserved
keyword.
Example
LogCustom([Link], "User-defined message.";

44
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

This statement writes to the Log Viewer as follows:


10/24/2005 12:49:14 PM ScriptRuntime
<[Link]>: <LogFlag EditBox1> User-defined message.

LogDataChangeEvent()
Logs an application change event to the Galaxy Historian.

Note: The LogDataChangeE vent() function works only in object scripts, not in symbol scripts.

Category
Miscellaneous
Syntax
LogDataChangeEvent(AttributeName, Description, OldValue, NewValue, TimeStamp);
Parameters
AttributeName
Attribute name as a tag name.
Description
Description of the object.
OldValue
Old value of the attribute.
NewValue
New value of the attribute.
TimeStamp
The time stamp associated with the logged event. The timestamp can be UTC or local time. The
TimeStamp parameter is optional. The timestamp of the logged event defaults to Now() if a
TimeStamp parameter is not included.
Remarks
A symbol script still compiles if the LogDat aChangeE vent() function is included. However, a warning
message is written to the log at run time that the function is inoperable.
Example
This example logs an event when a pump starts or stops with a timestamp of the current time when the
event occurred.
LogDataChangeEvent([Link], "Pump04", OldState, NewState);

LogError()
Writes a user-defined error message in the Log Viewer with a red error log flag.
Category
Miscellaneous
Syntax
LogError( msg );
Parameter
msg
The message to writ e to the Log Viewer. Actual string or a string attribute.

45
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Remarks
The log flag is enabled by default.
The message is always logged under the component "[Link]". For ex ample,
"WinPlatform_001.script1: msg", which identifies what object and what script within the object logged
the error.
LogE rror() is similar to LogMessage(), but displays the message in red.
The parameter help tooltip and Function Browser s ample parameter list will show "LogE rror( msg )"
rather than "LogE rror( Message )". "Message" is a reserved keyword.
Example
LogError("User-defined error message.");
This statement writes to the Log Viewer as follows:
10/24/2005 12:49:14 PM ScriptRuntime
<[Link]>: User-defined error message.

LogMessage()
Writes a user-defined message to the Log Viewer.
Category
Miscellaneous
Syntax
LogMessage( msg );
Parameter
msg
The message to writ e to the Log Viewer. Actual string or a string attribute.
Remarks
This is a very powerful function for troubleshooting scripting. By strategically placing LogMessage()
functions in your scripts, you can determine the order of script execution, performance of scripts, and
identify the value of attributes both before they are changed and after they are affected by the script.
Each message posted to the Log Viewer is stamped with the exact date and time. The message
always begins with the component " [Link]" so you can tell what object and what script
within the object posted the message to the log.
Examples
LogMessage("Report Script is Running");
The above statement writes the following to the Log Viewer:
10/24/2005 12:49:14 PM ScriptRuntime <[Link]>:Report Script is
Running.
MyTag=MyTag + 10;
LogMessage("The Value of MyTag is " + Text(MyTag, "#"));

LogTrace()
Writes a user-defined trace message in the Log Viewer.
Category
Miscellaneous
Syntax
LogTrace( msg );

46
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Parameter
msg
The message to writ e to the Log Viewer. Actual string or a string attribute.
Remarks
The log flag is disabled by default.
The message is always logged under the component "[Link]". For ex ample,
"WinPlatform_001.script1: msg", which identifies what object and what script within the object logged
the error.
LogTrace() is similar to LogMessage(), but displays the message as Trace when Log Trac e is enabled.
The parameter help tooltip and Function Browser sample parameter list will show "LogTrace( msg )"
rather than "LogTrace( Message )". "Message" is a reserved keyword.
Example
LogTrace("User-defined trace message.");
This statement writes to the Log Viewer as follows:
10/24/2005 12:49:14 PM ScriptRuntime
<[Link]>: User-defined trace message.

LogWarning()
Writes a user-defined error message in the Log Viewer with a yellow warning log flag.
Category
Miscellaneous
Syntax
LogWarning( msg );
Parameter
msg
The message to writ e to the Log Viewer. Actual string or a string attribute.
Remarks
The log flag is disabled by default.
The message is always logged under the component "[Link]". For ex ample,
"WinPlatform_001.script1: msg", which identifies what object and what script within the object logged
the error.
LogWarning() is similar to LogMessage(), but displays the message as a yellow warning message.
The parameter help tooltip and Function Browser sample parameter list will show "LogWarning( msg )"
rather than "LogWarning( Message )". "Message" is a reserved keyword.
Example
LogWarning("User-defined warning message.")
This statement writes to the Log Viewer as follows:
10/24/2005 12:49:14 PM ScriptRuntime
<[Link]>: User-defined warning message.

47
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

SendKeys()
Sends keystrokes to an application. To the receiving application, the keys appear to be entered from
the keyboard. You can use SendKeys() wit hin a script to enter data or send commands to an
application. Most keyboard keys can be used in a SendKeys() statement. Each key is represent ed by
one or more characters, such as A for the letter A or {E NTER} for the Enter key.
Category
Miscellaneous
Syntax
SendKeys( KeySequence );
Parameter
KeySequence
Any key sequence or a string attribute.
Remarks
To specify more than one key, concatenate the codes for eac h character. For example, to specify the
dollar sign ($) key followed by a (b), enter $b.
The following lists the valid send key codes for unique keyboard keys:

Key Code

BACKSPACE {BACKSPACE}or {BS }

BREAK {BREAK}

CAPSLOCK {CAPSLOCK }

DELE TE {DELE TE } or {DEL}

DOWN {DOW N}

END {END}

ENTER {ENTE R} or tilde (~ )

ESCAPE {ESCAPE} or {ESC}

F1...F12 {F1}...{F12}

HOME {HOME}

INSE RT {INSERT}

LEFT {LEFT}

NUMLOCK {NUMLOCK }

PAGE DOWN {PGDN}

PAGE UP {PGUP }

PRTSC {PRTS C}

RIGHT {RIGHT}

48
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Key Code

TAB {TAB}

UP {UP}

HOME {HOME}

Special keys (SHIFT, CTRL, and A LT) have their own key codes:

Key Code

SHIFT + (plus)

CTRL ^ (caret )

ALT % (percent)

Enhancements to the Microsoft Hardware Abstraction Layer in Windows prevents the SendKeys()
function from operating on some computers.
Examples
To use two special keys together, use a second set of parentheses. The following statement holds
down the CTRL key while pressing the ALT key, followed by p:
SendKeys ("^(%(p))");
Commands can be preceded by the ActivateApp() command to direct the keystrokes to the proper
application.
The following statement gives the computer focus to Calc ulator and sends the key combination 1234:
ActivateApp("Calculator");
SendKeys("^(1234)");

SetAttributeVT()
Sets the value and timestamp of an object attribute.
Category
Miscellaneous
Syntax
SetAttributeVT( Attribute, Value, TimeStamp);
Parameter
Attribute
Name of the object attribute whose value and timestamp are modified. The specified attribute must
belong to the object to which the script is attached.
Value
Value of the attribute, which can be a referenc e. The quality is always set to Good.
TimeStamp
Timestamp that can be a reference, a variable, or a string interpreted as the computer’s local time
or UTC. The timestamp is converted internally to UTC format before the attribute’s value is sent to
the run-time component.

49
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Remarks
Timestamp can be set only for object attributes that support a timestamp. At compile time, the script
cannot detect whether the attribute specified with the SetAttributeV T() function supports a timestamp or
not. No warning is issued if the attribut e does not support a timestamp.
Example
This example sets an integer value and timestamp for an attribute that indicates pump RPM.
SetAttributeVT([Link], [Link], LCLTIME);

SetBad()
Sets the quality of an attribute to Bad.
Category
Miscellaneous
Syntax
SetBad( Attribute );
Parameter
Attribute
The attribute for which you want to set the quality to Bad.
Remarks
The specified attribute must be within the object to which the script is attached.
Example
SetBad([Link]);
See Also
SetGood(), SetInitializing(), Set Uncert ain()

SetGood()
Sets the quality of an attribute to Good.
Category
Miscellaneous
Syntax
SetGood( Attribute );
Parameter
Attribute
The attribute for which you want to set the quality to Good.
Remarks
The specified attribute must be within the object to which the script is attached.
Example
SetGood([Link]);
See Also
SetBad(), SetInitializing(), SetUncertain()

50
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

SetInitializing()
Sets the quality of an attribute to Initializing.
Category
Miscellaneous
Syntax
SetInitializing( Attribute );
Parameter
Attribute
The attribute for which you want to set the quality to Initializing.
Remarks
The specified attribute must be within the object to which the script is attached.
Example
SetInitializing([Link]);
See Also
SetBad(), SetGood(), SetUncertain()

SetUncertain()
Sets the quality of an attribute to Uncertain.
Category
Miscellaneous
Syntax
SetUncertain( Attribute );
Parameter
Attribute
The attribute for which you want to set the quality to Uncertain.
Remarks
The specified attribute must be within the object to which the script is attached.
Example
SetUncertain([Link]);
See Also
SetBad(), SetGood(), SetInitializing()

SignedAlarmAck()
Acknowledges one or more alarms on ArchestrA attributes, optionally requiring a signature if any of the
indicated alarms falls within a designated priority range.
This function is support ed only for client scripting and not object scripting.
Category
Miscellaneous

51
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Syntax
int SignedAlarmAck(String Alarm_List,
Boolean Signature_Reqd_for_Range,
Integer Min_Priority,
Integer Max_Priority,
String Default_Ack_Comment,
Boolean Ack_Comment_Is_Editable,
String TitleBar_Caption,
String Message_Caption
);
Parameters
Alarm_List
The list of alarms to be acknowledged. The list must be a single text string with each alarm name
separated by a spac e or a comma.
Data Type
String
Valid Range
Limit 1024 characters
Additional Information
Can be a constant string, a reference, or an ex pression.
Only alarms on ArchestrA attributes are supported.
If there is any invalid alarm in the list, then none of the alarms are acknowledged.
Examples
Example 1:
"UD1.analog_001.HiHi"
The collection is repres ented as a text string, with alarms separated by blanks and/or commas.
Example 2:
"UD1.analog_001.HiHi [Link]"
Example 3:
"UD1.analog_001.HiHi, [Link]"
Example 4, an array of strings such as:
[Link][1] = "[Link]"
[Link][2] = "[Link]"
uses the function as follows:
SignedAlarmAck([Link][ ], ...)
The script passes to the function the following single string:
"[Link], [Link]"
Signature_Reqd_for_Range
Indicates whether a signature is required for acknowledging alarms.
Data Type
Bool
Additional Information
Can be a constant, a reference, or an expression.
Min_Priority
Represents the minimum priority value of the range for which the signat ure is required.

52
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Data Type
Integer
Valid Range
1-999; must be less than or equal to the Max_P riority value.
Additional Information
Can be a constant, a reference, or an expression.
Max_Priority
Represents the maximum priority value of the range for which the signature is required.
Data Type
Integer
Valid Range
1-999; must be great er than or equal to the Min_P riority value.
Additional Information
Can be a constant, a reference, or an expression.
Default_Ack _Comment
Comment to be shown in the Acknowledge Alarms dialog box.
Data Type
String
Valid Range
Limit 200 characters
Additional Information
Can be a constant, a reference or an expression.
If the parameter is empty, then no default comment is shown in the Acknowledge Alarms dialog
box.
Ack _Comment_Is_ Editable
Indicates whether the run-time user can modify the acknowledgement comment.
Data Type
Bool
Additional Information
Can be a constant, a reference, or an expression.
If set to False, the Comment box in the Acknowledge Alarms dialog box is unavailable.
TitleBar_Caption
Shows a title in the title bar of the Acknowledge Alarms dialog box.
Data Type
String
Valid Range
Limi 1024 characters
Additional Information
Can be a constant, a reference, or an expression.
If the TitleBar_Caption is empty, the default title, Acknowledge Alarms, is shown.
Message_Caption
Shows a customizable message to the run-time user in the Acknowledge Alarms dialog box.
Data Type
String

53
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Valid Range
Limit 250 characters
Additional Information
Can be a constant, a reference, or an expression.
Use the parameter to provide more information on the alarm to the run-time user.
This message is not propagated to the event record.
Return Values
Return values indicate success or failure status. A non -zero value indicates type of failure.

-1 The user canceled the operation.


The function writes a message to the Logger indicating us er
cancellation.

-2 No alarms are waiting for acknowledgement.


0 The function is successful and the following are all true:
 The function parameters are valid.
 The user credentials are valid (or no credentials are
needed).
 The user did not cancel the operation.
 Function wrote to the .AckMsg attributes of the indicated
alarms.

1 The function failed due to any error that is not covered by the
other specified return values.
2 One or more parameters were not coerced to the appropriate
data type at run time.
Example: Parameter is a reference wit h Boolean as the
expected data type. At run time, reference is to a String data
type that cannot be coerced to True or False.
The function writes a message to the Logger.

3 The Alarm_List parameter was not valid at run time.


 String was null, empty or contained no attribute references.
 Cont ained one or more items that were not valid attribute
references.
 Cont ained one or more attribute references that did not
exist or did not identify valid alarm primitives.
If Alarm_List contains a mixture of valid and invalid references,
the function does nothing. The function does not attempt to
operate on the valid references, and returns this error status.

54
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

4 The Min_Priority or MaxPriority values do not fall within the


range of 1 to 999.
The function writes a message to the Logger indicating which
parameter was out of range and showing the actual value.

5 The Min_Priority value is great er than the Max_P riority value.


The function writes a message to the Logger identifying the
problem and showing the actual values.

Note: A return value of zero does not indicate if the alarms are acknowledged, only that the function
wrot e to the AckMsg attributes. The alarms may not be acknowledged due to insufficient permission or
if the alarms have already been acknowledged.

Remarks
For more information about using the SignedAlarmAck() function, see "Signature Security for
Acknowledging Alarms" in Chapter 11, "Adding and Maintaining Symbol Scripts,"in the Creating and
Managing ArchestrA Graphics User’s Guide.
Examples
Dim n as Integer;
n = SignedAlarmAck("UD1.analog_001.HiHi [Link]", true, 1, 250,
"Acknowledged by script", true, "Acking Tank Alarms", "Acknowledge the tank
alarms");
Using an array of strings:
dim arr[2] as String;
arr[1] = "UD1.analog_001.HiHi";
arr[2] = "[Link]";
n = SignedAlarmAck(arr[], true, 200, 500, "Acked by script", true, "Acking
Tank Alarms", "Please acknowledge the tank alarms.");

SignedWrite()
Performs a write to an A utomationObject attribute that has a Secured Write or Verified Write security
classification.
Category
Miscellaneous
Syntax
int SignedWrite(string Attribute,
object Value,
string ReasonDescription,
Bool Comment_Is_Editable,
Enum Comment_Enforcement,
string[] Predefined_Comment_List
);
Brackets [ ] indicate an array.
Parameters
Attribute
The attribute to be updated.

55
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Data Type
String
Additional Information
Can be a constant string, a reference, or an ex pression.
Supports bound and nested bound references.
For detailed examples of Attribute paramet er uses, see "Examples of Using the Attribute
Parameter in the SignedWrite() Function" in Chapter 3, "Managing Symbols,"in the Creating and
Managing ArchestrA Graphics User’s Guide.
Examples
Example 1:
"UserDefined_001.temp"
Example 2:
"Pump15" + ".valve4"
Example 3:
With UDO_7 containing two string attributes, namestrA and namestrB set to the values "Tank1"
and " Tank5" respectively, the following script writes to [Link] or [Link] according to
whet her strselect is "A" or "B":
Dim strselect As String;
Dim x As Indirect;
{ logic to set strselect to "A" or "B" }
[Link] ("UDO_7.namestr" + strselect);
SignedWrite(x + ".Level", 243, "Set " + x + " Level", true, 0, null);
Value
The value to be written.
Data Type
Object
Valid Range
Must match data type of the attribut e being updated.
Additional Information
Can be a constant value, a reference, an expression, or NULL if nothing is to be ent ered.
Reas onDescription
Text that explains the purpose of the target attribut e and the impact of changing it.
Data Type
String
Valid Range
Maximum of 256 characters.
Additional Information
Can be a constant string, a reference, or an ex pression.
The ReasonDescription is passed to the indicated Attribute as part of the write operation. The
object also includes the user’s write comment, if any. A Field Attribute description is used for the
Reas onDescription parameter only if the attribute is a Field Attribute and it has a description (is not
null). Otherwise, the Short Description for the corresponding ApplicationObject is used for the
Reas onDescription parameter.
Comment_is _Editable
Indicates whether user can edit the write comment.
Data Type
Bool

56
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Additional Information
Can be a constant value, a reference, or an expression.
If set to True: The comment text box is enabled with exceptions. If Comment_Is_E ditable is true
and if the Comment_ Enforc ement parameter is PredefinedOnly, the comment t ext box is disabled.
At run time, the user can only select a comment from the predefined comment list.
If the Comment _ Enforcement parameter is not PredefinedOnly, the comment list and box are
enabled. You can select a comment from the comment list and modify it in the comment box.
If the predefined list is empty, the comment list is not shown in the dialog box.
If set to False: The predefined comment list does not appear in the Secured Write or Verified Write
dialog boxes. The editable comment text box is disabled.
Comment_E nforcement
Cont ains choices of Optional, Mandatory and PredefinedOnly.
Data Type
Enum
Enumerations
Optional = 0
The run-time user can enter a comment or leave it blank.
Mandatory = 1
The run-time user must add a comment, either by selecting from the comment list or by entering a
comment in the comment box.
PredefinedOnly = 2
The run-time user can select a comment from the comment list only. The comment text box is
disabled.
Additional Information
Can be a constant, a reference, or an expression.
Predefined_Comment_List
An array of strings that can be used as predefined comments.
Data Type
String[]
Valid Range
Maximum of 20 comments, each with a maximum of 200 characters.
Additional Information
The array can be empty (number of elements is 0).
Can be a constant, a reference, an expression, or NULL if empty. Can reference an attribut e that
contains an array of strings.
If no predefined comment is entered, the predefined comment list is disabled at run time.
If Comment_Is_Edit able is False, the predefined comment is still placed in the editable comment
text box, but the user cannot modify it at run time.
Return Values
Return values indicate success or failure status. A non -zero value indicates type of failure.

57
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

0 The function returns a value of 0 (meaning success) if the


following are all true:
 The function parameters were valid.
 The write operation was successfully placed on the queue
for Secured and Verified Writes.
 If the user cancels the operation, a message is written to
the Logger indicating user cancellation.

1 The function failed due to any error that is not covered by the
other specified return values. This includes any error that is not
covered by the other specified return values. If there is a
failure, a specific message is logged in the Logger.

2 One or more parameters were not coerced to the appropriate


data type at run time.
Example: Parameter is a reference wit h Boolean as the
expected data type. At run time, reference is to a String data
type that cannot be coerced to True or False. The function
returns this value and writes a message to the Logger.

3 The attribute parameter was not valid at run time.


 Attribute string was null, empty, or contained no attribute
reference.
 Attribute string contained an item that was not a valid
attribute reference.
 Attribute string contained an attribute reference that did not
exist.
 Attribute string contained an attribute reference that was
not of the Secured Write or Verified Write security
classification.
The function writes a message to the Logger identifying the
error and the invalid attribute string.

4 The Comment_Enforcement paramet er value was out of the


range of valid enumerat ors.
Remarks
The SignedWrite() function is support ed only for client scripting and not for object scripting.
A return value of 0 does not indicat e whether the attribute was updated, only that the function placed
an ent ry on the queue to write to the attribute. The operator may decide to cancel the operation after
the Secured Write or Verified write dialog box is present ed. In this case the attribute is not updated and
a message is placed in the Logger indicating that the user canceled the operation. E ven if the user
enters valid credentials and clicks OK, the attribute still might not have been updated because of
inadequate permission or data coercion problems.
The SignedWrite() function supports the custom property passed as the first parameter with opened
and closed quot ation marks, "".

58
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

If you configure the custom property CP as shown in the following script, the function attempts to
resolve CP and determine if it has a reference. If it has a reference, then the reference is retrieved and
the write is performed on the reference.
SignedWrite("CP", value, reason, editable, enforcement, null);
For more information about using the SignedWrite() function, see "Working with the SignedWrite()
Function for Sec ured and Verified Writes" in Chapter 3, "Managing Symbols,"in the Creating and
Managing ArchestrA Graphics User’s Guide.
Examples
SignedWrite ("UserDefined_001.temp", 185, "This will change the oven
temperature", true, 1, null);
The following example shows the user an array of predefined comments:
Dim n as Integer;
n = SignedWrite("UserDefined_001.temp", 185, "This will change the oven
temperature", true, 1, UserDefined_001.OvenCommentArray[ ]);
where UserDefined_001.OvenCommentArray is an attribute containing an array of strings.

WriteStatus()
Returns the enumerated write status of the last write to the specified attribute.
Category
Miscellaneous
Syntax
Result = WriteStatus( Attribute );
Parameter
Attribute
The attribute for which you want to ret urn write status.
Return Value
The return statuses are:
 MxStatusOk
 MxStatusPending
 MxStatusWarning
 MxStatusCommunicationE rror
 MxStatusConfigurationError
 MxStatusOperationalError
 MxStatusSecurityError
 MxStatusSoftwareE rror
 MxStatusOtherError
Remarks
If the attribut e has never been written to, this function returns MxStatusOk. This function always returns
MxStatusOk for attributes that do not support a calculated (non-Good) quality.
Example
WriteStatus([Link]);

59
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

WWControl()
Restores, minimizes, maximizes, or closes an application.
Category
Miscellaneous
Syntax
WWControl( AppTitle, ControlType );
Parameters
AppTitle
The name of the application title to be controlled. Actual string or a string attribute.
Cont rolType
Determines how the application is controlled. Possible values are shown below. These actions are
identical to clicking on their corresponding selections in the application's Control Menu. Actual
string or a string attribut e.
"Restore" = Activates and shows the application's window.
"Minimize" = Activates a window and shows it as an icon.
"Maximize" = Activates and shows the application's window.
"Close" = Closes an application.
Example
WWControl("Calculator","Restore");
See Also
ActivateApp()

String Functions
Use string functions to work with character strings and string values.

DText()
Returns one of two possible strings, depending on the value of the Discrete paramet er.
Category
String
Syntax
StringResult = DText( Discrete, OnMsg, OffMsg );
Parameters
Discrete
A Boolean value or Boolean attribute.
OnMsg
The message that is shown when the value of Discrete equals true.
OffMsg
The message shown when Discrete equals false.
Example
StringResult = DText([Link] > 150, "Too hot", "Just right");

60
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

StringASCII()
Returns the ASCII value of the first character in a specified string.
Category
String
Syntax
IntegerResult = StringASCII( Char );
Parameter
Char
Alphanumeric character or string or string attribut e.
Remarks
When this function is processed, only the single character is tested or affected. If the string provided to
StringASCII contains more than one character, only the first character of the string is tested.
Examples
StringASCII("A"); ' returns 65;
StringASCII("A Mixer is Running"); ' returns 65;
StringASCII("a mixer is running"); ' returns 97;
See Also
StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringInString(), StringLeft(),
StringLen(), StringLower(), StringMid(), StringReplace(), StringRight(), StringSpac e(), StringTest(),
StringToI ntg(), StringToReal(), StringTrim(), StringUpper(), Text()

StringChar()
Returns the character corresponding to a specified ASCII code.
Category
String
Syntax
StringResult = StringChar( ASCII );
Parameter
ASCII
ASCII code or an integer attribute.
Remarks
Use the StringChar function to add ASCII characters not normally represented on the keyboard to a
string attribut e.
This function is also useful for SQL commands. The where expression sometimes requires double
quotation marks around string values, so use StringChar(34).
Example
In this example, a [Carriage Return (13)] and [Line Feed (10)] are added to the end of StringAttribute
and passed to ControlString. Inserting characters out of the normal 32 -126 range of displayable ASCII
characters can be very useful for creating control codes for external devices such as printers or
modems.
ControlString = StringAttribute+StringChar(13)+StringChar(10);

61
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

StringCompare()
Compares a string value with another string.
Category
String
Syntax
StringCompare( Text1, Text2 );
Parameters
Text1
First string in the comparison.
Text2
Second string in the comparison.
Return Value
The return value is zero if the strings are identical, -1 if Text1’s value is less than Text2, or 1 if Text1’s
value is greater than Text2.
Example
Result = StringCompare ("Text1","Text2"); (or)
Result = StringCompare (MText1,MText2);
Where Result is an Integer or Real tag and MText1 and MText2 are Memory Message
tags.
See Also
StringASCII(), StringChar(), StringFromReal(), StringFromTime(), StringFromTimeLocal(),
StringInString(), StringLeft(), StringLen(), StringLower(), StringMid(), StringReplace(), StringRight (),
StringSpace(), StringTest(), StringToIntg(), StringToReal(), St ringTrim(), StringUpper(), Text()

StringCompareNoCase()
Compares a string value with another string and ignores the case.
Category
String
Syntax
SStringCompareNoCase( Text1, Text2 );
Parameters
Text1
First string in the comparison.
Text2
Second string in the comparison.
Return Value
The return value is zero if the strings are identical (ignoring case), -1 if Text1’s value is less than Text2
(ignoring case), or 1 if Text1’s value is greater than Text2 (ignoring case).
Example
Result = StringCompareNoCase ("Text1","TEXT1"); (or)
Result = StringCompareNoCase (MText1,MText2);
Where Result is an Integer or Real tag and MText1 and MText2 are Memory Message
tags.

62
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

See Also
StringASCII(), StringChar(), StringFromReal(), StringFromTime(), StringFromTimeLocal(),
StringInString(), StringLeft(), StringLen(), StringLower(), StringMid(), StringReplace(), StringRight (),
StringSpace(), StringTest(), StringToIntg(), StringToReal(), StringTrim(), StringUpper(), Text()

StringFromGMTTimeToLocal()
Converts a time value (in seconds since Jan-01-1970) to a particular string representation. This is the
same as StringFromTime().
Category
String
Syntax
MessageResult=StringFromGMTTimeToLocal(SecsSince1-1-70,StringType);
Parameters
SecsSince1-1-70
Is converted to the StringTy pe specified and the result is stored in MessageResult.
StringType
Determines the display method:
1 = Displays the date in the same format set from the windows control Panel. (Similar to that
displayed for $DateString.)
2 = Displays the time in the same format set from the Windows control Panel. (Similar to that
displayed for $TimeString.)
3 = Displays a 24-character string indicating both the date and time: "Wed Jan 02 02: 03:55 1993"
4 = Displays the short form for the day of the week: "Wed"
5 = Displays the long form for the day of the week: "Wednesday"
Remarks
Any adjustments necessary due to Daylight Savings Time are automatically applied to the return result.
Therefore, it is not necessary to make any manual adjustments to the input value to convert to DS T.
Example
This example assumes that the time zone on the local node is Pacific Standard Time (UTC-0800). The
UTC time passed to the function is 12:00:00 AM on Friday, 1/2/1970. Since PST is 8 hours behind
UTC, the function will return the following results:
StringFromGMTTimeToLocal(86400, 1); ' returns "1/1/1970"
StringFromGMTTimeToLocal(86400, 2); ' returns "04:00:00 PM"
StringFromGMTTimeToLocal(86400, 3); ' returns "Thu Jan 01 16:00:00 1970"
StringFromGMTTimeToLocal(86400, 4); ' returns "Thu"
StringFromGMTTimeToLocal(86400, 5); ' returns "Thursday"
See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(),
StringFromTimeLoc al(), StringInString(), StringLeft(), StringLen(), StringLower(), StringMid(),
StringReplace(), StringRight (), StringS pace(), StringTest(), StringToIntg(), StringToReal(), StringTrim(),
StringUpper(), Text()

StringFromIntg()
Converts an integer value into its string repres entation in another base and returns the result.

63
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Category
String
Syntax
SringResult = StringFromIntg( Number, numberBase );
Parameters
Number
Number to convert. Any number or an integer attribut e.
numberB ase
Base to use in conversion. Any number or an integer attribut e.
Examples
StringFromIntg(26, 2); ' returns "11010"
StringFromIntg(26, 8); ' returns "32"
StringFromIntg(26, 16); ' returns "1A"
See Also
StringASCII(), StringChar(), StringFromReal(), StringFromTime(), StringInString(), StringLeft(),
StringLen(), StringLower(), StringMid(), StringReplace(), StringRight(), StringSpac e(), StringTest(),
StringToI ntg(), StringToReal(), StringTrim(), StringUpper(), Text()

StringFromReal()
Converts a real value into its string repres entation, either as a floating-point number or in exponential
notation, and returns the result.
Category
String
Syntax
StringResult = StringFromReal( Number, Precision, Type );
Parameters
Number
Converted to the Precision and Type specified. Any number or a float attribute.
Precision
Specifies how many decimal places is shown. Any number or an integer attribute.
Type
A string value that determines the display method. Possible values are:
f = Display in floating-point notation.
e = Display in exponential notation with a lowercase "e."
E = Display in exponential not ation with an uppercase "E" followed by a plus sign and at least three
exponential digits.

Examples
StringFromReal(263.355, 2,"f"); ' returns "263.36";
StringFromReal(263.355, 2,"e"); ' returns "2.63e2";
StringFromReal(263.355, 2,"E"); ' returns "2.63 E+002";

64
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromTime(), StringInString(), StringLeft(),
StringLen(), StringLower(), StringMid(), StringReplace(), StringRight(), StringSpac e(), StringTest(),
StringToI ntg(), StringToReal(), StringTrim(), StringUpper(), Text()

StringFromTime()
Converts a time value (in seconds since January 1, 1970) into a particular string representation and
returns the result.
Category
String
Syntax
StringResult = StringFromTime( SecsSince1-1-70, StringType );
Parameters
SecsSince1-1-70
Converted to the StringType specified.
StringType
Determines the display method. Possible values are:
1 = Shows the dat e in the same format set from the Windows Control Panel.
2 = Shows the time in the same format set from the Windows Control Panel.
3 = Shows a 24-character string indicating both the date and time: "Wed Jan 02 02:03:55 1993"
4 = Shows the short form for a day of the week: "Wed"
5 = Shows the long form for a day of the week: "Wednesday"
Remarks
The time value is UTC equivalent: number of elapsed seconds since January 1, 1970 GMT. The value
returned reflects the local time.
Examples
StringFromTime(86400, 1); ' returns "1/2/1970"
StringFromTime(86400, 2); ' returns "12:00:00 AM"
StringFromTime(86400, 3); ' returns "Fri Jan 02 00:00:00 1970"
StringFromTime(86400, 4); ' returns "Fri"
StringFromTime(86400, 5); ' returns "Friday"
See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringInString(),
StringLeft(), StringLen(), StringLower(), StringMid(), StringReplace(), StringRight(), StringSpace(),
StringTest(), StringToIntg(), StringToReal(), StringTrim(), StringUpper(), Text()

StringFromTimeLocal()
Converts a time value (in seconds since Jan-01-1970) into a particular string represention. The value
returned also represents local time.
Category
String
Syntax
MessageResult=StringFromTimeLocal(SecsSince1-1-70,

65
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

StringType);
Parameters
SecsSince1-1-70
Is converted to the StringTy pe specified and the result is stored in MessageResult.
StringType
Determines the display method:
1 = Displays the date in the same format set from the windows control Panel. (Similar to that
displayed for $DateString.)
2 = Displays the time in the same format set from the Windows control Panel. (Similar to that
displayed for $TimeString.)
3 = Displays a 24-character string indicating both the date and time: "Wed Jan 02 02: 03:55 1993"
4 = Displays the short form for the day of the week: "Wed"
5 = Displays the long form for the day of the week: "Wednesday"
Remarks
Any adjustments necessary due to Daylight Savings Time will automatically be applied to the return
result. Therefore, it is not necessary to make any manual adjustments for DS T to the input value.
Example
StringFromTimeLocal (86400, 1); ' returns "1/2/1970"
StringFromTimeLocal (86400, 2); ' returns "12:00:00 AM"
StringFromTimeLocal (86400, 3); ' returns "Fri Jan 02 00:00:00 1970"
StringFromTimeLocal (86400, 4); ' returns "Fri"
StringFromTimeLocal (86400, 5); ' returns "Friday"
See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringInString(),
StringLeft (), StringLen(), StringLower(), StringMid(), StringReplace(), StringRight(), StringSpace(),
StringTest(), StringToIntg(), StringToReal(), StringTrim(), StringUpper(), Text()

StringInString()
Returns the position in a string of text where a specified string first occurs.
Category
String
Syntax
IntegerResult = StringInString( Text, SearchFor, StartPos, CaseSens );
Parameters
Text
The string that is searched. Actual string or a string attribute.
SearchFor
The string to be searched for. Actual string or a string attribute.
StartPos
Determines the position in the text where the search begins. Any number or an integer attribut e.
CaseSens
Determines whet her the search is case-sensitive.
0 = Not case-sensitive
1 = Case-sensitive

66
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Any number or an integer attribute.


Remarks
If multiple occurrences of SearchFor are found, the location of the first is returned.
Examples
StringInString("The mixer is running", "mix", 1, 0) ' returns 5;
StringInString("Today is Thursday", "day", 1, 0) ' returns 3;
StringInString("Today is Thursday", "day", 10, 0) ' returns 15;
StringInString("Today is Veteran's Day", "Day", 1, 1) ' returns 20;
StringInString("Today is Veteran's Day", "Night", 1, 1) ' returns 0;
See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringLeft(),
StringLen(), StringLower(), StringMid(), StringReplace(), StringRight(), StringSpac e(), StringTest(),
StringToI ntg(), StringToReal(), StringTrim(), StringUpper(), Text()

StringLeft()
Returns a specified number of characters in a string value, starting with the leftmost string character.
Category
String
Syntax
StringResult = StringLeft( Text, Chars );
Parameters
Text
Actual string or a string attribute.
Chars
Number of characters to return or an integer attribute.
Remarks
If Chars is set to 0, the entire string is returned.
Examples
StringLeft("The Control Pump is On", 3) ' returns "The";
StringLeft("Pump 01 is On", 4) ' returns "Pump";
StringLeft("Pump 01 is On", 96) ' returns "Pump 01 is On";
StringLeft("The Control Pump is On", 0) ' returns "The Control Pump is On";
See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringInString(),
StringLen(), StringLower(), StringMid(), StringReplace(), StringRight(), StringSpac e(), StringTest(),
StringToI ntg(), StringToReal(), StringTrim(), StringUpper(), Text()

StringLen()
Returns the number of characters in a string.
Category
String
Syntax
IntegerResult = StringLen( Text );

67
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Parameter
Text
Actual string or a string attribute.
Remarks
All the characters in the string attribute are counted, including blank spaces and those not normally
shown on the screen.
Examples
StringLen("Twelve percent") ' returns 14;
StringLen("12%") ' returns 3;
StringLen("The end." + StringChar(13)) ' returns 9;
The carriage ret urn character is ASCII 13.
See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringInString(),
StringLeft(), StringLower(), StringMid(), StringReplace(), StringRight(), StringSpac e(), StringTest(),
StringToI ntg(), StringToReal(), StringTrim(), StringUpper(), Text()

StringLower()
Converts all uppercase characters in text string to lowerc ase and returns the result.
Category
String
Syntax
StringResult = StringLower( Text );
Parameter
Text
String to be converted to lowercase. Actual string or a string attribute.
Remarks
Lowercas e characters, symbols, numbers, and other special characters are not affected.
Examples
StringLower("TURBINE") ' returns "turbine";
StringLower("22.2 Is The Value") ' returns "22.2 is the value";
See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringInString(),
StringLeft(), StringLen(), StringMid(), StringReplace(), StringRight(), StringSpace(), StringTest(),
StringToI ntg(), StringToReal(), StringTrim(), StringUpper(), Text()

StringMid()
Extracts a specific number of characters from a starting point within a string and returns the extracted
character string as the result.
Category
String
Syntax
StringResult = StringMid( Text, StartChar, Chars );

68
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Parameters
Text
Actual string or a string attribute to extract a range of characters.
StartChar
The position of the first character within the string to extract. Any number or an integer attribute.
Chars
The number of characters within the string to return. Any number or an integer attribute.
Remarks
This function is slightly different than the StringLeft() function and StringRight() function in that it allows
you to specify both the start and end of the string that is to be extracted.
Examples
StringMid("The Furnace is Overheating",5,7); ' returns "Furnace";
StringMid("The Furnace is Overheating",13,3); ' returns "is ";
StringMid("The Furnace is Overheating",16,50); ' returns "Overheating"
See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringInString(),
StringLeft(), StringLen(), StringLower(), StringReplace(), StringRight(), StringS pace(), StringTest(),
StringToI ntg(), StringToReal(), StringTrim(), StringUpper(), Text()

StringReplace()
Replaces or changes specific parts of a provided string and returns the result.
Category
String
Syntax
StringResult = StringReplace( Text, SearchFor, ReplaceWith, CaseSens,
NumToReplace, MatchWholeWords );
Parameters
Text
The string in which characters, words, or phrases will be replaced. Actual string or a string
attribute.
SearchFor
The string to search for and replac e. Actual string or a string attribute.
ReplaceWith
The replacement string. Actual string or a string attribute.
CaseSens
Determines whet her the search is case-sensitive. (0=no and 1=yes) Any number or an integer
attribute.
NumToReplace
Determines the number of occurrences to replace. Any number or an int eger attribute. To indicate
all occurrences, set this value to -1.
MatchWholeWords
Determines whet her the function limits its replacement to whole words. (0=no and 1=yes) Any
number or an int eger attribute. If MatchWholeWords is turned on (set to 1) and the SearchFor is
set to "and", the "and" in "handle" are not replaced. If the MatchWholeWords is turned off (set to 0),
it is replaced.

69
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Remarks
Use this function to replace characters, words, or phrases within a string.
The StringReplace() function does not recognize special characters, such as @ # $ % & * ( ). It reads
them as delimiters. For example, if the function StringReplace() (abc#,abc#,1234,0,1,1) is processed,
there is no replacement. The # sign is read as a delimiter instead of a char acter.
Examples
StringReplace("In From Within","In","Out",0,1,0) ' returns "Out From Within"
(replaces only the first one);
StringReplace("In From Within","In","Out",0,-1,0) ' returns "Out From without"
(replaces all occurrences);
StringReplace("In From Within","In","Out",1,-1,0) ' returns "Out From Within"
(replaces all that match case);
StringReplace("In From Within","In","Out",0,-1,1) ' returns "Out From Within"
(replaces all that are whole words);
See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringInString(),
StringLeft(), StringLen(), StringLower(), StringMid(), StringRight(), StringSpace(), StringTest(),
StringToI ntg(), StringToReal(), StringTrim(), StringUpper(), Text()

StringRight()
Returns the specified number of characters starting at the right -most character of text.
Category
String
Syntax
StringResult = StringRight( Text, Chars );
Parameters
Text
Actual string or a string attribute.
Chars
The number of characters to return or an integer attribute.
Remarks
If Chars is set to 0, the entire string is returned.
Examples
StringRight("The Pump is On", 2) ' returns "On";
StringRight("The Pump is On", 5) ' returns "is On";
StringRight("The Pump is On", 87) ' returns "The Pump is On";
StringRight("The Pump is On", 0) ' returns "The Pump is On";
See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringInString(),
StringLeft(), StringLen(), StringLower(), StringMid(), StringReplace(), StringSpace(), StringTest(),
StringToI ntg(), StringToReal(), StringTrim(), StringUpper(), Text()

StringSpace()
Generat es a string of spaces either within a string attribute or within an expression and ret urns the
result.

70
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Category
String
Syntax
StringResult = StringSpace( NumSpaces );
Parameter
NumSpaces
Number of spac es to return. Any number or an integer attribute.
Examples
All spaces are represented by the "×" character:
StringSpace(4) ' returns "××××";
"Pump" + StringSpace(1) + "Station" ' returns "Pump×Station";
See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringInString(),
StringLeft(), StringLen(), StringLower(), StringMid(), StringReplace(), StringRight(), StringTest(),
StringToI ntg(), StringToReal(), StringTrim(), StringUpper(), Text()

StringTest()
Tests the first character of text to determine whet her it is of a certain type and returns the result.
Category
String
Syntax
DiscreteResult = StringTest( Text, TestType );
Parameters
Text
String that function acts on. Actual string or a string attribute.
TestType
Determines the type of test. Possible values are:
1 = Alphanumeric character ('A -Z', 'a-z' and '0-9')
2 = Numeric character ('0- 9')
3 = Alphabetic character ('A-Z' and 'a-z')
4 = Uppercase character ('A-Z')
5 = Lowercase character ('a'-'z')
6 = Punctuation character (0x21-0x2F)
7 = ASCII characters (0x00 - 0x7F)
8 = Hexadecimal characters ('A -F' or 'a-f' or '0-9')
9 = Printable character (0x20-0x7E)
10 = Control character (0x00-0x1F or 0x7F)
11 = White Space characters (0x09-0x0D or 0x20)

71
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Remarks
StringTest() function returns true to DiscreteResult if the first character in Text is of the type specified
by TestType. Otherwise, false is returned. If the StringTest() function contains more than one
character, only the first character of the attribute is tested.
Examples
StringTest("ACB123",1) ' returns 1;
StringTest("ABC123",5) ' returns 0;
See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringInString(),
StringLeft(), StringLen(), StringLower(), StringMid(), StringReplace(), StringRight(), StringSpace(),
StringToI ntg(), StringToReal(), StringTrim(), StringUpper(), Text()

StringToIntg()
Converts the numeric value of a string to an integer value and returns the result.
Category
String
Syntax
IntegerResult = StringToIntg( Text );
Parameter
Text
String that function acts on. Actual string or a string attribute.
Remarks
When this statement is evaluated, the system reads the first character of the string for a numeric value.
If the first character is other than a number, the string's value is equated to zero (0). Blank spaces are
ignored. If the first character is a number, the system continues to read the subsequent characters until
a non-numeric value is detected.
Examples
StringToIntg("ABCD"); ' returns 0;
StringToIntg("22.2 is the Value"); ' returns 22 (since integers are whole
numbers);
StringToIntg("The Value is 22"); ' returns 0;
See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringInString(),
StringLeft(), StringLen(), StringLower(), StringMid(), StringReplace(), StringRight(), StringSpace(),
StringTest(), StringToReal(), StringTrim(), StringUpper(), Text()

StringToReal()
Converts the numeric value of a string to a real (floating point) value and returns the result.
Category
String
Syntax
RealResult = StringToReal( Text );

72
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Parameter
Text
String that function acts on. Actual string or a string attribute.
Remarks
When this statement is evaluated, the system reads the first character of the string for a numeric value.
If the first character is other than a number (blank spaces are ignored), the string's value is equated to
zero (0). If the first character is found to be a number, the system continues to read the subsequent
characters until a non-numeric value is encountered.
Examples
StringToReal("ABCD"); ' returns 0;
StringToReal("22.261 is the value"); ' returns 22.261;
StringToReal("The Value is 2"); ' returns 0;
See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringInString(),
StringLeft(), StringLen(), StringLower(), StringMid(), StringReplace(), StringRight(), StringSpace(),
StringTest(), StringToIntg(), StringTrim(), StringUpper(), Text()

StringTrim()
Removes unwanted spaces from text and returns the res ult.
Category
String
Syntax
StringResult = StringTrim( Text, TrimType );
Parameter
Text
String that is trimmed of spaces. Actual string or a string attribut e.
TrimType
Determines how the string is trimmed. Possible values are:
1 = Remove leading spaces to the left of the first non-space character
2 = Remove trailing spaces to the right of the last non-spac e character
3 = Remove all spaces except for single spaces between words
Remarks
The text is searched for white-spaces (AS CII 0x09-0x 0D or 0x20) that are to be removed. TrimType
determines the met hod used by the function:
Examples
All spaces are represented by the "×" character.
StringTrim("×××××This×is×a××test×××××", 1) ' returns "This×is×a××test×××××";
StringTrim("×××××This×is×a××test×××××", 2) ' returns "×××××This×is×a××test";
StringTrim("×××××This×is×a××test×××××", 3) ' returns "This×is×a×test";
The StringReplace() function can remove ALL spaces from a specified a string attribute. Simply
replace all the space characters with a "null."

73
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringInString(),
StringLeft(), StringLen(), StringLower(), StringMid(), StringReplace(), StringRight(), StringSpace(),
StringTest(), StringToIntg(), StringToReal(), StringUpper(), Text()

StringUpper()
Converts all lowercase text characters to uppercase and returns the result.
Category
String
Syntax
StringResult = StringUpper( Text );
Parameter
Text
String to be converted to uppercase. Actual string or a string attribute.
Remarks
Uppercas e characters, symbols, numbers, and other special characters are not affected.
Examples
StringUpper("abcd"); ' returns "ABCD";
StringUpper("22.2 is the value"); ' returns "22.2 IS THE VALUE";
See Also
StringASCII(), StringChar(), StringFromIntg(), StringFromReal(), StringFromTime(), StringInString(),
StringLeft(), StringLen(), StringLower(), StringMid(), StringReplace(), StringRight(), StringSpace(),
StringTest(), StringToIntg(), StringToReal(), StringTrim(), Text()

Text()
Converts a number to text based on a specified format.
Category
String
Syntax
StringResult = Text( Number, Format );
Parameters
Number
Any number or numeric attribut e.
Format
Format to use in conversion. Actual string or a string attribute.
Examples
Text(66,"#.00"); ' returns 66.00;
Text(22.269,"#.00"); ' returns 22.27;
Text(9.999,"#.00"); ' returns 10.00;
The following example shows how to use this function within another function:
LogMessage("The current value of FreezerRoomTemp is:" + Text (FreezerRoomTemp,
"#.#"));
In the following example, MessageTag is set to "One=1 Two=2".
MessageTag = "One + " + Text(1,"#") + StringChar(32) + "Two +" + Text(2,"#");

74
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

See Also
StringFromIntg(), StringToIntg(), StringFromReal(), StringToReal()

WWStringFromTime()
Converts a time value given in local time into UTC time (Coordinated Universal Time), and displays the
result as a string.
Category
String
Syntax
MessageResult = wwStringFromTime(SecsSince1-1-70,StringType);
Parameters
SecsSince1-1-70
Integer Type. Number of Seconds elapsed since Jan 01 00:00: 00 1970.
StringType
Determines the display method:
1 = Displays the date in the same format set from the windows control Panel. (Similar to that
displayed for $DateString.)
2 = Displays the time in the same format set from the Windows control Panel. (Similar to that
displayed for $TimeString.)
3 = Displays a 24-character string indicating both the date and time: "Wed Jan 02 02: 03:55 1993"
4 = Displays the short form for the day of the week: "Wed"
5 = Displays the long form for the day of the week: "Wednesday"
Remarks
Any adjustments necessary due to Daylight Savings Time will automatically be applied to the return
result. Therefore, it is not necessary to make any manual adjustments for DS T to the input value.
Example
This example assumes that the time zone on the local node is Pacific Standard Time (UTC-0800). The
local time passed to the function is 04:00:00 PM on Thursday, 1/1/1970. Since PS T is 8 hours behind
UTC, the function will return the following results:
wwStringFromTime(57600, 1) will return "1/2/70"
wwStringFromTime(57600, 2) will return "12:00:00 AM"
wwStringFromTime(57600, 3) will return "Fri Jan 02 00:00:00 1970"
wwStringFromTime(57600, 4) will return "Fri"
wwStringFromTime(57600, 5) will return "Friday"

System Functions
Use system functions to interact with the operating system or other core system functions, such as
ActiveX objects.

CreateObject()
Creates an ActiveX (COM) object.
Category
System

75
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Syntax
ObjectResult = CreateObject( ProgID );
Parameter
ProgI D
The program ID (as a string) of the object to be created.
Example
CreateObject("[Link]");

Now()
Returns the current time.
Category
System
Syntax
TimeValue = Now();
Remarks
The return value can be formatted using .NE T functions.

WWDDE Functions
Use WWDDE functions when working wit h the DDE protocol.

WWExecute()
Using the DDE protocol, execut es a command to a specified application and topic and returns the
status.
Category
WWDDE
Syntax
Status = WWExecute( Application, Topic, Command );
Parameters
Application
The application to which you want to send an exec ute command. Actual string or a string attribute.
Topic
The topic within the application. Actual string or a string attribute.
Command
The command to send. Actual string or a string attribute.
Return Value
Status is an Integer attribute to which 1, -1, or 0 is written. The WWExecute() function returns 1 if the
application is running, the topic exists, and the command was sent successfully. It returns 0 when the
application is busy, and -1 when there is an error.
Remarks
Note: The three WWDDE functions Execute(), Poke() and Request() exist for legacy purposes.

The Command string is sent to a specified application and topic.

76
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Important: The following applies to using WWExecute() in synchronous scripts:


1. Never loop them (call them over and over).
2. Never call several of them in a row and in the same script.
3. Never use them to call a lengthy task in another DDE application.
All three actions, though, are appropriate in asynchronous scripts.

Examples
The following statement executes a macro in Excel:
Macro="Macro1!TestMacro";
Command="[Run(" + StringChar(34) + Macro + StringChar(34)
+ ",0)]";
WWExecute("excel","system",Command);
When WWExecute("excel","system",Command); is processed, the following is sent to Excel
(and TestMacro runs ):
[Run("Macro1!TestMacro")];
The following script executes a macro in Microsoft Access:
WWExecute("MSAccess","system","MyMacro");

WWPoke()
Using the DDE protocol, pokes a value to a specified application, topic, and item and returns the
status.
Category
WWDDE
Syntax
Status = WWPoke( Application, Topic, Item, TextValue );
Parameters
Application
The application to which you want to send the Poke command. Actual string or a string attribute.
Topic
The topic within the application. Actual string or a string attribute.
Item
The item to poke within the topic. Actual string or a string attribute.
TextValue
The value to poke. If the value you want to send is a number, you can convert it using the Text (),
StringFromIntg(), or StringFromReal() functions. Actual string or a string attribute.
Return Value
Status is an Integer attribute to which 1, -1, or 0 is written. The WWPoke() function returns 1 if the
application is running, the topic and item exist, and the value was sent successfully. It returns 0 if the
application is busy, and -1 if there is an error.
Remarks
Note: The three WWDDE functions Execute(), Poke() and Request() exist for legacy purposes.

The value TextValue is sent to the particular application, topic, and item specified.

77
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Important: The following applies to using WWRequest() in synchronous scripts:


1. Never loop them (call them over and over).
2. Never call several of them in a row and in the same script.
3. Never use them to call a lengthy task in another DDE application. All three actions, though, are
appropriate in asynchronous scripts.

Example
The following statement converts a value to text and pokes the result to an Excel spreadsheet cell:
String=Text(Value,"0");
WWPoke("excel","[[Link]]sheet1","r1c1",String);
The behavior for WWPoke() from within the application "View" to "View" is undefine d and is not
supported. The WWPoke() command is not guaranteed to succeed in this instance, and the command
will probably time-out without the desired results.
See Also
Text(), StringFromIntg(), StringFromReal()

WWRequest()
Using the DDE protocol, makes a one -time request for a value from a particular application, topic, and
item and returns the status.
Category
WWDDE
Syntax
Status = WWRequest( Application, Topic, Item, Attribute );
Parameters
Application
The application from which you want to request data. Actual string or a string attribute.
Topic
The topic within the application. Actual string or a string attribute.
Item
The item within the topic. Actual string or a string attribut e.
Attribute
A string attribute, enclos ed in quotation marks, that contains the requested value from the
application, topic, and item. Actual string or a string attribute.
Return Value
Status is an integer attribute to which 1, -1, or 0 is written. The WWRequest() function returns 1 if the
application is running, the topic and item exist, and the value was returned successfully. It returns 0 if
the application is busy, and -1 if there is an error.
Remarks
Note: The three WWDDE functions Execute(), Poke() and Request() exist for legacy purposes.

The DDE value in the particular application, topic, and item is returned into Attribute.
The value is returned as a string into a string attribute. If the value is a number, you can then convert it
using the StringToInt g() or StringToReal() functions.

78
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Important: Never do the following when using WWRequest() in synchronous scripts:


1. Loop scripts (call them over and over).
2. Call several of scripts in a row and in the same script.
3. Use scripts to call a lengthy task in another DDE application.
All three actions can be done in asynchronous scripts.

Example
The following statement requests a value from an Excel spreadsheet cell and converts the res ulting
string into a value:
WWRequest("excel","[[Link]]sheet1","r1c1",Result);
Value=StringToReal(Result);
See Also
StringToI ntg(), StringToReal()

79
Wonderware - Application Server Scripting Guide

C HAPTER 3
QuickScript .NET Variables
QuickScript .NET variables must be declared before they can be used in QuickScript .NET scripts.
Variables can be us ed on both the left and right side of statements and expressions.
Local variables or attributes can be used together in the same script. Variables declared within the
script body lose their value after the script is executed. Those declared in the script body cannot be
accessed by other scripts.
Variables declared in the Declarations area maintain their values throughout the lifetime of the object
that the script is associated with.
Each variable must be declared in the script by a separate DIM statement followed by a semicolon.
Enter DIM statements in the Declarations area of the Script tab page. The DIM statement syntax is as
follows:
DIM <variable_name> [ ( <upper_bound>
[, <upper_bound >[, < upper_bound >]] ) ]
[ AS <data_type> ];
where:

DIM Required keyword.

<variable_name> Name that begins with a letter (A-Z or a-z) and whos e remaining characters can be any
combination of letters (A-Z or a-z), digits (0-9) and underscores (_). The variable name is
limited to 255 Unicode characters.

<upper_bound> Referenc e to the upper bound (a number bet ween 1 and 2,147,483,647, inclusive) of an
array dimension. Three dimensions are supported in a DIM statement, each being nested
in the syntax structure. After the upper bound is specified, it is fixed after the declaration. A
statement similar to Visual Basic’s ReDim is not support ed.
The lower bound of each array dimension is always 1.

AS Optional keyword for declaring the variable’s datatype.

81
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

<data_type> Any one of the following 11 datatypes: Boolean, Discrete, Integer, ElapsedTime, Float,
Real, Double, String, Message, Time or Object.

Data_type can also be a .Net data_type like System. Xml. XmlDocument or a type defined in
an imported script library

If you omit the AS clause from the DIM statement, the variable, by default, is declared as
an Integer datatype. For example:

DIM LocVar1;

is equivalent to:

DIM LocVar1 AS Integer;

In contrast to attribute names, variable names must not contain dots. Variable names and the data type
identifiers are not case sensitive. If there is a naming conflict between a declared variable and anot her
named entity in the script (for example, attribute name, alias or name of an object leveraged by the
script), the variable name takes precedence over the other named entities. If the variable name i s the
same as an alias name, a warning message appears when the script is validated to indicat e that the
alias is ignored.
The syntax for specifying the entire array is "[ ]" for bot h local array variables and for attribute
references. For example, to assign an attribute array to a local array, the syntax is:
locarr[] = [Link][];
DIM statements can be located any where in the script body, but they must prec ede the first referencing
script statement or expression. If a local variable is referenced before the DIM statement, script
validation done when you save the object containing the script prompts you to define it.

Caution: The validation mentioned above occurs only when you save the object c ontaining the script.
This is not the script syntax validation done when you click the Validate Script button.

Do not cascade DIM statements. For example, the following examples are invalid:
DIM LocVar1 AS Integer, LocVar2 AS Real;
DIM LocVar3, LocVar4, LocVar5, AS Message;
To declare multiple variables, you must enter separate DIM statements for each variable.
When used on the right side of an equation, declared local variables always cause expressions on the
left side to have Good quality. For example :
dim x as integer;
dim y as integer;
x = 5;
y = 5;
[Link] = 5;
[Link] = x;
[Link] = x+y;
In each case of [Link], quality is Good.
When you use a variable in an expression to the right of the operator, its Quality is treated as Good for
the purpose of data quality propagation.

82
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

You can use null to indicate that there is no object currently assigned to a variable. Using null has the
same meaning as the keyword "null" in C# or "nothing" in Visual Basic. Assigning null to a variable
makes the variable eligible for garbage collection. You may not use a variable whose value is null. If
you do, the script terminates and an error message appears in the logger. You may, however, test a
variable for null. For example:
IF myvar == null THEN ...
It is not possible to pass attributes as parameters for system objects. To work around this issue, use a
local variable as an intermediary or explicitly convert the attribut e to a string using an appropriate
function call when calling the system object.

In This Chapter
Numbers and Strings .................................................................................................................... 83

Numbers and Strings


Allowed format for integer constants in decimal format is as follows:
IntegerConst = 0 or [sign] <non-zero_digit> <digit>*;
where:
sign :: = + | -
non-zero_digit ::= 1-9
digit ::= 0-9
For example, an int eger constant is a zero or consists of an optional sign followed by one or more
digits. Leading zeros are not allowed. Integer constants outside the range –2147483648 to
2147483647 cause an overflow error.
Prepending either 0x or 0X causes a literal int eger constant to be int erpreted as hexadecimal
notation. The +/- sign is supported.
The acceptable float for int egers in hexadecimal is as follows:
IntegerHexConst = [<sign>] <0><x (or X)> <hexdigit>*
where:
sign ::= + or -
hexdigit ::= 0-9, A-F, a-f (only eight hexdigits [32-bits] are allowed)
Allowed format for floats is as follows:
FloatConst ::= [<sign>] <digit>* .<digit>+ [<exponent>;]
or
[<sign>] <digit>+ [.<digit>* [<exponent>]];
where:
sign ::= + or -
digit ::= 0-9 (can be one or more decimal digits)
exponent = e (or E) followed by a sign and then digit(s)
Float constants are applicable as values for variables of type float, real, or double. For example, float
constants do not take the number of bytes into account. Script validation detects an overflow when a
float, real, or double variable has been assigned a float constant that exceeds the maximum value.
If no digits appear before the period (.), at least one must appear after it. If neither an exponent part nor
the period appears, a period is assumed to follow the last digit in the string.
If an attribute reference exists that has a format similar to a float constant with an exponent (such as
"5E3"), then use the Attribute qualifier, as follows:
Attribute("5E3")

83
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Strings must be surrounded by double quot ation marks. They are referred to as quoted strings. T he
double-double quote indicates a single double -quote in the string. For ex ample, the string:
Joe said, "Look at that."
can be represent ed in QuickScript .NET as:
"Joe said, ""Look at that."""

QuickScript .NET Control Structures


QuickScript .NET provides five primary control structures in the scripting environment:
 IF … THEN … ELSEIF … ELSE … ENDIF
 FOR … TO … STEP … NEXT Loop
 FOR EACH … IN … NEXT
 TRY ... CATCH
 WHILE Loop

IF … THEN … ELSEIF … ELSE … ENDIF


IF-THE N-ELSE -ENDIF conditionally executes various instructions based on the state of an expression.
The syntax is as follows:
IF <Boolean_expression> THEN;
[statements];
[ { ELSEIF;
[statements] } ];
[ ELSE;
[statements] ];
ENDIF;
Where Boolean_expression is an expression that can be evaluated as a Boolean.
Depending on the data type ret urned by the ex pression, the expression is evaluated to constitute a
True or False state according to the following table:

Data Type Mapping

Boolean, Discrete Directly used (no mapping needed).

Integer Value = 0 evaluated as False


Value != 0 evaluat ed as True.

Float, Real Value = 0 evaluated as False


Value != 0 evaluat ed as True.

Double Value = 0 evaluated as False


Value != 0 evaluat ed as True.

String, Message Cannot be mapped. Using an expression that


results in a string type as the Boolean_expression
results in a script validation error.

84
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Data Type Mapping

Time Cannot be mapped. Using an expression that


results in a time type as the Boolean_expression
results in a script validation error.

ElapsedTime Cannot be mapped. Using an expression that


results in an elapsed time type as the
Boolean_expression res ults in a script validation
error.

Object Using an expression that results in an object type.


Validates, but at run time, the object is converted to
a Boolean. If the type cannot be converted to a
Boolean, a run-time exception is raised.

The first block of statements is executed if Boolean_expression evaluates to True. Optionally, a second
block of statements can be defined after the keyword ELSE. This block is executed if the
Boolean_expression evaluates to False.
To help decide between multiple alt ernatives, an optional ELSEIF clause can be used as often as
needed. The ELSEIF clause mimics switch statements offered by other programming languages.
Example:
IF value == 0 Then
Message = "Value is zero";
ELSEIF value > 0 Then;
Message = "Value is positive";
ELSEIF value < 0 then;
Message = "Value is negative";
ELSE;
{Default. Should never occur in this example};
ENDIF;
The following syntax is also supported:
IF <Boolean_expression> THEN;
[statements];
[ { ELSEIF;
[statements] } ];
[ ELSE;
[statements] ];
ENDIF;
ENDIF;
This approac h nests a brand new IF compound statement wit hin a previous one and requires an
additional ENDIF.
See "Sample Scripts" on page 126 for more ideas about using this type of control structure.

IF … THEN … ELSEIF … ELSE … ENDIF and Attribute Quality


When an attribute value is copied to another attribute of the same type, the attribute’s quality is also
copied. This can be especially relevant when working with I/O attributes. For ex ample, the following
two statements copy both value and quality:
me.Attr2 = me.Attr1;
[Link] = [Link];

85
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

If only the value needs to be copied and the attribute has the quality BAD, you can use a temporary
variable to hold the value. For example:
Dim temp as Integer;
temp = me.Attr1;
me.Attr2 = temp;
If there is a comparison such as Attr1 <> Attr2 and one of the attributes has the BA D quality BAD, then
the statements within the IF control block are not executed. For example, assuming Attr1 has the
quality BAD:
if me.Attr1<> me.Attr2 then
me.Attr2 = me.Attr1;
endif;
In this script, the statement me.Attr2 = me.Attr1 is not executed because Attr1 has the quality BAD
and comparing a BA D quality value with a good quality value is not defined/not possible.
The recommended approach is to first verify the quality of Attr1, as shown in the following example:
if(IsBad(me.Attr1)) then
LogMessage("Attr1 quality is bad, its value is not copied to Attr2");
else
if me.Attr1<> me.Attr2 then
me.AttrA2 = me.Attr1;
endif;
endif;
An alternative method of verifying quality is to use the "==" operat or:
if Me.Attr1 == TRUE then
Or, you can add the " value" property to the simplified IF THE N statement:
if [Link] then
Using any of the above methods to verify data quality will ens ure that your scripts execute correctly.

FOR … TO … STEP … NEXT Loop


FOR-NE XT performs a function (or set of fu nctions) within a script several times during a single
execution of a script. The general format of the FOR-NE XT loop is as follows:
FOR <analog_var> = <start_expression> TO <end_expression> [STEP
<change_expression>];
[statements];
[EXIT FOR;];
[statements];
NEXT;
Where:
 analog_var is a variable of type Int eger, Float, Real, or Double.
 start_expression is a valid expression to initialize analog_var to a value for exec ution of the loop.
 end_expression is a valid expression. If analog_var is greater than end_expression, execution of
the script jumps to the statement immediately following the NE XT statement.
This holds true if loop is incrementing up, otherwise, if loop is decrementing, loop termination
occurs if analog_var is less than end_expression.
 change_expression is an expression that defines the increment or decrement value of analog_var
after execution of the NE XT statement. The change_expression can be either positive or negative .
o If change_expression is positive, start_expression must be less than or equal to
end_expression or the statements in the loop do not execute.

86
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

o If change_expression is negative, start_ex pression must be greater than or equal to


end_expression for the body of the loop to be executed.
 If S TEP is not set, then change_expression defaults to 1 for increasing increments, and defaults to
-1 for decreasing increments.
Exit the loop from within the body of the loop with the E XIT FOR statement.
The FOR loop is executed as follows:
1. analog_var is set equal to start_expression.
2. If change_expression is positive, the system tests to see if analog_var is greater than
end_expression. If so, the loop exits. If change_expression is negative, the system tests to see if
analog_var is less than end_expression. If so, program execution exits the loop.
3. The statements in the body of the loop are executed. The loop can potentially be exited via the
E XIT FOR statement.
4. analog_var is incremented by 1,-1, or by change_expression if it is specified.
5. Steps 2 through 4 are repeated.

Note: FOR-NE XT loops can be nested. The number of levels of nesting possible depends on memory
and resource availability.

See "Sample Scripts" on page 126 for ideas about using this type of cont rol structure.

FOR EACH … IN … NEXT


FOR EACH loops can be used only wit h collections exposed by OLE Automation servers. A
FOR-EACH loop performs a function (or set of functions) within a script several times during a single
execution of a script. The general format of the FOR-EA CH loop is as follows:
FOR EACH <object_variable> IN <collection_object >
[statements];
[EXIT FOR;];
[statements];
NEXT;
Where:
 object_variable is a dimmed variable.
 collection_object is a variable holding a collection object.
As in the case of the FOR … TO loop, it is possible to exit the execution of the loop through the
statement E XIT FOR from within the loop.
See "Sample Scripts" on page 126 for ideas about using this type of cont rol structure.

TRY ... CATCH


TRY ... CATCH provides a way to handle some or all possible errors that may occur in a given block of
code, while still running rat her than terminating the program. The TRY part of the code is known as the
try block. Deal with any exceptions in the CA TCH part of the code, known as the catch block.
The general format for TRY ... CA TCH is as follows:
TRY
[try statements] ’guarded section
CATCH
[catch statements]
ENDTRY
Where:

87
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

tryStatements
Statement(s) where an error can occur. Can be a compound statement. The tryStatement is a
guarded section.
catchStatements
Statement(s) to handle errors occurring in the associated Try block. Can be a compound
statement.

Note: Statements inside the Catch block may reference the reserved ERROR variable, which is a
.NET [Link] thrown from the Try block. The statements in the Catch block run only if an
exception is thrown from the Try block.

TRY ... CATCH is executed as follows:


1. Run-time error handling starts with TRY. Put code that might result in an error in the try block.
2. If no run-time error occurs, the script will run as usual. Catch block statements will be ignored.
3. If a run-time error occurs, the rest of the try block does not execute.
4. When a run-time error occurs, the program immediately jumps to the CA TCH statement and
executes the catch block.
The simplest kind of exception handling is to stop the program, write out the exception message,
and continue the program.
The error variable is not a string, but a .NET object of [Link]. This means you can
determine the type of exception, even with a simple CA TCH statement. Call the Get Type() method
to determine the exception type, and then perform the operation you want, similar to executing
multiple catch blocks.
Example:
dim command = new [Link];
dim reader as [Link];
[Link] = new [Link];
try
[Link] = "Integrated Security=SSPI";
[Link]="select * from [Link]";
[Link]();
reader = [Link]();

while [Link]()
[Link] = [Link](0);
LogMessage([Link]);
endWhile;
catch
LogMessage(error);
endtry;
if reader <> null and not [Link] then
[Link]();
endif;
if [Link] == [Link] then
[Link]();
endif;

WHILE Loop
WHILE loop performs a function or set of functions within a script several times during a single
execution of a script while a condition is true. The general format of the WHILE loop is as follows:
WHILE <Boolean_expression>

88
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

[statements]
[EXIT WHILE;]
[statements]
ENDWHILE;
Where: Boolean_ex pression is an expression that can be evaluat ed as a Boolean as defined in the
description of IF…THE N statements.
It is possible to exit the loop from the body of the loop through the E XIT W HILE statement.
The WHILE loop is executed as follows:
1. The script evaluates whether the Boolean_expression is true or not. If not, prog ram execution exits
the loop and continues after the ENDWHILE statement.
2. The statements in the body of the loop are executed. The loop can be exited through the E XIT
WHILE statement.
3. Steps 1 through 2 are repeated.

Note: WHILE loops can be nested. The number of levels of nesting possible depends on memory and
resource availability.

See "Sample Scripts" on page 126 for ideas about using this type of cont rol structure.

QuickScript .NET Operators


The following QuickScript .NE T operat ors require a single operand:

Operator Short De scription

~ Complement

- Negation

NOT Logical NOT

The following QuickScript .NE T operat ors require two operands:

Operator Short De scription

+ Addition and concat enation

- Subtraction

& Bitwise AND

* Multiplication

** Power

/ Division

^ Exclusive OR

| Inclusive OR

< Less than

89
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Operator Short De scription

<= Less than or equal to

<> Not equal to

= Assignment

== Equivalency (is equivalent to); not supported for entire array compares. Arrays
must be compared one element at a time using ==.

> Greater than

>= Greater than or equal to

AND Logical A ND

MOD Modulo

OR Logical OR

SHL Left shift

SHR Right shift

The following table shows the precedence of QuickScript .NET operators:

Precedence Operator

1 (highest) ( )

2 - (negation), NOT, ~

3 **

4 *, /, MOD

5 +, - (subtraction)

6 SHL, SHR

7 <, >, <=, >=

8 ==, <>

9 &

10 ^

11 |

12 =

13 AND

14 (lowest) OR

The arguments of the listed operat ors can be numbers or attribut e values. Putting parentheses around
an argument is optional. Operator names are not case-sensitive.

90
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

Parentheses ( )
Parentheses specify the correct order of evaluation for the operat or(s ). They can also make a complex
expression easier to read. Operator(s) in parentheses are evaluated first, preempting the other rules of
precedence that apply in the absence of parent hes es. If the precedence is in question or needs to be
overridden, use parentheses.
In the example below, parentheses add B and C toget her before multiplying by D:
( B + C ) * D;

Negation ( - )
Negation is an operator that acts on a single component. It converts a positive integer or real number
into a negative number.

Complement ( ~ )
This operator yields the one's complement of a 32-bit integer. It converts each zero-bit to a one-bit and
each one-bit to a zero-bit. The one's complement operator is an operator that acts on a single
component, and it accepts an integer operand.

Power ( ** )
The Power operator ret urns the result of a number (the base) raised to the power of a second number
(the power). The base and the power can be any real or integer numbers, subject to the following
restrictions:
 A zero base and a negative power are invalid.
Example: "0 ** - 2" and "0 ** -2.5"
 A negative base and a fractional power are invalid.
Example: "-2 ** 2.5" and "-2 ** -2.5"
 Invalid operands yield a zero result.
The result of the operation should not be so large or so small that it cannot be represented as a real
number. Example:
1 ** 1 = 1.0
3 ** 2 = 9.0
10 ** 5 = 100,000.0

Multiplication ( * ), Division ( / ), Addition ( + ),Subtraction ( - )


These binary operators perform basic mathematical operations. The plus (+) can also concat enate
String dat atypes.
For example, in the data change script below, each time the value of "Number" changes, "Setpoint"
changes as well:
Number=1;
[Link] = "Setpoint" + Text(Number, "#" );
Where: The result is "Setpoint1."

Modulo (MOD)
MOD is a binary operat or that divides an integer quantity to its left by an integer quantity to its right.
The remainder of the quotient is the result of the MOD operation. Example:
97 MOD 8 yields 1
63 MOD 5 yields 3

91
Wonderware - Application Server Scripting Guide QuickScript .NET Functions

Shift Left (SHL), Shift Right (SHR)


SHL and SHR are binary operators that use only integer operands. The binary content of the 32-bit
word referenced by the quantity to the left of the operator is shifted (right or left) by the number of bit
positions specified in the quantity to the right of the operat or.
Bits shifted out of the word are lost. Bit positions vacated by the shift are zero -filled. The shift is an
unsigned shift.

Bitwise AND ( & )


A bitwise binary operator compares 32-bit integer words with each other, bit for bit. Typically, this
operator masks a set of bits. The operation in this example "masks out" (sets to zero) the upper 24 bits
of the 32-bit word. For example:
result = name & 0xff;

Exclusive OR (^) and Inclusive OR ( | )


The ORs are bit wise logical operators compare 32-bit integer words to each ot her, bit for bit. The
Exclusive OR compare the status of bits in corresponding locations. If the corres ponding bits are the
same, a zero is the result. If the corresponding bits differ, a one is the result. Example:
0 ^ 0 yields 0
0 ^ 1 yields 1
1 ^ 0 yields 1
1 ^ 1 yields 0
The Inclusive OR ex amines the corres ponding bits for a one condition. If eit her bi t is a one, the result is
a one. Only when both corresponding bits are zeros is the result a zero. For example:
0 | 0 yields 0
0 | 1 yields 1
1 | 0 yields 1
1 | 1 yields 1

Assignment ( = )
Assignment is a binary operator which accepts integer, real, or any type of operand. Each statement
can contain only one assignment operator. Only one name can be on the left side of the assignment
operator.
Read the equal sign (=) of the assignment operator as "is assigned to" or "is set to."

Note: Do not confuse the equal sign with the equivalency sign (==) used in comparisons.

Comparisons ( <, >, <=, >=, ==, <> )


Comparisons in IF -THE N-E LSE statements execute various instructions based on the state of an
expression.

AND, OR, and NOT


These operators work only on discrete attributes. If these operators are used on i ntegers or real
numbers, they are converted as follows:
 Real to Discrete: If real is 0.0, discrete is 0, otherwise discrete is 1.
 Integer to Discrete: If integer is 0, discrete is 0, otherwise discrete is 1.

92
QuickScript .NET Functions Wonderware - Application Server Scripting Guide

If the statement is: "Disc1 = Real1 AND Real2;" and Real1 is 23.7 and Real2 is 0.0, Disc1 has 0
assigned to it, since Real1 is converted to 1 and Real2 is converted to 0.
When assigning the floating-point result of a mathematical operation to an integer, Application Server
rounds the value to the nearest integer instead of truncating it. This means that an operation like
IntAttr = 32/60 results in IntAttr having a value of 1, not 0. If truncation is needed, use the
Trunc() function.

93
Wonderware - Application Server Scripting Guide

C HAPTER 4
Sample QuickScript .NET Scripts
This section includes sample scripts to help you to understand the QuickScript .NET scripting
language.

Important Note: The sample scripts provided wit h a number of the Application Server scripting
functions should work as written in most Windows operating system and installed software
environments, but might not work with all possible hardware, operating system, and softwar e
combinations. We recommend that you modify the example scripts as necessary to fit your specific
environment.

Important Note: Some sample scripts include references to public websites as examples. You may
need to replace those URLs with a current and verified URLs.

95
Wonderware - Application Server Scripting Guide Sample QuickScript .NET Scripts

In This Chapter
Sample Scripts ............................................................................................................................. 96
Accessing an Excel Spreadsheet Using anImport ed Type Library .................................................... 97
Accessing an Excel Spreadsheet Using Creat eObject ..................................................................... 97
Accessing an Office XP Excel Spreads heet Using an Imported Type Library ..................................... 98
Calling a Web Service to Get the Temperature for a Specified Zip Code ........................................... 98
Calling a Web Service to Send an E -mail Message ......................................................................... 98
Creating a Look-up Table and Doing a Look-up on It ....................................................................... 99
Creating an XML Document and Saving it to Disk ........................................................................... 99
Executing a SQL Parameterized INSERT Command ..................................................................... 100
Filling a String Array and Using It ................................................................................................. 100
Filling a Two-Dimensional Integer Array and Using It..................................................................... 100
Formatting a Number Using a .NE T Format 'Picture' ..................................................................... 100
Formatting a Time Using a .NE T Format 'Picture'.......................................................................... 101
Getting the Directories Under the C Drive ..................................................................................... 101
Loading an XML Document from Disk and Doing Look-ups on It .................................................... 101
Querying a SQL Server Dat abase ................................................................................................ 101
Reading a Performance Count er.................................................................................................. 101
Reading a Text File from Disk ...................................................................................................... 102
Sharing a SQL Connection or Any Other .NE T Object ................................................................... 102
Using DDE to Access an Excel Spreadsheet ................................................................................ 102
Using Micros oft Exchange to Send an E-mail Message ................................................................. 102
Using Screen-Scraping to Get the Temperature for a City ............................................................. 103
Using SMTP to Send an E-mail Message ..................................................................................... 103
Writing a Text File to Disk............................................................................................................ 103
Dynamically Binding an Indirect Variable to a Reference ............................................................... 104

Sample Scripts
The sample scripts include:
 Accessing an Excel Spreadsheet Using an Imported Type Library
 Accessing an Excel Spreadsheet Using Creat eObject
 Accessing an Office XP Excel Spreads heet Using an Imported Type Library
 Calling a Web Service to Get the Temperature for a Specified Zip Code
 Calling a Web Service to Send an E -mail Message
 Creating a Look -up Table and Doing a Look -up on It
 Creating an X ML Document and Saving it to Disk

96
Sample QuickScript .NET Scripts Wonderware - Application Server Scripting Guide

 Executing a SQL Parameterized INSERT Command


 Filling a String Array and Using It
 Filling a Two-Dimensional Integer Array and Using It
 Formatting a Number Using a .NET Format 'Picture'
 Formatting a Time Using a .NET Format 'Picture'
 Getting the Directories Under the C Drive
 Loading an X ML Document from Disk and Doing Look -ups on It
 Querying a SQL Server Dat abase
 Reading a Performance Count er
 Reading a Text File from Disk
 Sharing a SQL Connection or Any Other .NET Object
 Using DDE to Access an Excel Spreadsheet
 Using Micros oft Exchange to Send an E-mail Message
 Using S MTP to Send an E-mail Message
 Using Screen-Scraping to Get the Temperature for a Cit y
 Creating a Look -up Table and Doing a Look -up on It
 Dynamically Binding an Indirect Variable to a Ref erence

Accessing an Excel Spreadsheet Using anImported Type


Library
dim app as Excel._Application;
dim wb as Excel._Workbook;
dim ws as Excel._WorkSheet;
app = new [Link];
wb = [Link]();
ws = [Link];
ws.get_Range("A1").Value = 1000;
ws.get_Range("A2").Value = 1000;
ws.get_Range("A3").Value = "=A1+A2";
LogMessage(ws.get_Range("A3").Value);
[Link](false);

Accessing an Excel Spreadsheet Using CreateObject


dim app as object;
dim wb as object;
dim ws as object;
app = CreateObject("[Link]");
wb = [Link]();
ws = [Link];
[Link].("A1").value = 20;
[Link].("A2").value = 30;
[Link].("A3").value = "=A1*A2";
LogMessage([Link]("A3").Value);
[Link](false);

97
Wonderware - Application Server Scripting Guide Sample QuickScript .NET Scripts

Accessing an Office XP Excel SpreadsheetUsing an Imported


Type Library
dim app as [Link];
dim ws as [Link];
dim wb as [Link];
dim a1 as [Link];
dim a2 as [Link];
dim a3 as [Link];
app = new Excel._ExcelApplicationClass;
wb = [Link];
ws = [Link];
a1 = [Link]("A1");
a2 = [Link]("A2");
a3 = [Link]("A3");
[Link] = 1000;
[Link] = 2000;
[Link] = "=A1*A2";
LogMessage([Link]);
[Link](true, "c:\[Link]", false);

Calling a Web Service to Get the Temperature for a Specified


Zip Code
Note: This sample script includes a reference to a public website as an example. You may need to
replace that URL wit h a current and verified URL.

' Requires input string uda [Link] and output float uda [Link].
' First, generate a wrapper for the web service (.Net SDK must be installed).
' To generate wrapper, run the following commands from the DOS prompt:
' set path=%path%;C:\Program Files\Microsoft Visual Studio
.NET\FrameworkSDK\Bin
' wsdl [Link]
' csc /target:library [Link]
' Next import the generated [Link] library into your galaxy.
' Now write your script:
dim wr as WeatherRetriever;
wr = new WeatherRetriever;
[Link] = [Link]([Link]);

Calling a Web Service to Send an E-mail Message


Note: This sample script includes a reference to a public website as an example. You may need to
replace that URL wit h a current and verified URL.

' First, generate a wrapper for the web service (.Net SDK must be installed).
' To generate wrapper, run the following commands from the DOS prompt:
' set path=%path%;C:\Program Files\Microsoft Visual Studio
.NET\FrameworkSDK\Bin
' wsdl /namespace:SendMail
[Link]
' csc /target:library [Link]
' Next import the generated [Link] library into your galaxy.
' Now write your script:
dim m as [Link];
m = new [Link];

98
Sample QuickScript .NET Scripts Wonderware - Application Server Scripting Guide

[Link]
(
{to: } "<type valid email address here>",
{from: } "<type valid email address here>",
{subject: } "Reminder to self",
{body: } "Pick up eggs and milk on your way home."
);

Creating a Look-up Table and Doing a Look-up on It


dim zipcodes as [Link];
zipcodes = new [Link];
zipcodes["Irvine"] = 92618;
zipcodes["Mission Viejo"] = 92692;
LogMessage(zipcodes["Irvine"]);

Creating an XML Document and Saving it to Disk


dim doc as [Link];
dim catalog as [Link];
dim book as [Link];
dim title as [Link];
dim author as [Link];
dim lastName as [Link];
dim firstName as [Link];
' create new XML document rooted in catalog
doc = new [Link];
catalog = [Link]("catalog");
[Link](catalog);
' add a book to the catalog
book = [Link]("book");
title = [Link]("title");
author = [Link]("author");
lastName = [Link]("lastName");
firstName = [Link]("firstName");
[Link](lastName);
[Link](firstName);
[Link](title);
[Link](author);
[Link](book);
[Link]("isbn", "0385503822");
[Link] = "The Summons";
[Link] = "Grisham";
[Link] = "John";
' add another book
book = [Link]("book");
title = [Link]("title");
author = [Link]("author");
lastName = [Link]("lastName");
firstName = [Link]("firstName");
[Link](lastName);
[Link](firstName);
[Link](title);
[Link](author);
[Link](book);
[Link]("isbn", "044023722X");
[Link] = "A Painted House";
[Link] = "Grisham";

99
Wonderware - Application Server Scripting Guide Sample QuickScript .NET Scripts

[Link] = "John";
' save the XML document to disk
[Link]("c:\[Link]");

Executing a SQL Parameterized INSERT Command


dim connection as [Link];
dim command as [Link];
dim regionId as [Link];
dim regionDesc as [Link];
dim commandText as string;
connection = new
[Link]("server=(local);uid=sa;database=northwin
d");
[Link]();
commandText = "INSERT INTO Region (RegionID, RegionDescription) VALUES (@id,
@desc)";
command = new [Link](commandText, connection);
regionId = [Link]("@id", [Link], 4);
regionDesc = [Link]("@desc", [Link], 50);
[Link]();
[Link] = 5;
[Link] = "Europe";
[Link]();
[Link] = 6;
[Link] = "South America";
[Link]();
[Link]();

Filling a String Array and Using It


dim numbers[3] as string;
dim s as string;
numbers[1] = "one";
numbers[2] = "two";
numbers[3] = "three";
LogMessage(numbers[3]);
for each s in numbers[]
LogMessage(s);
next;

Filling a Two-Dimensional Integer Array and Using It


dim x[2,3] as integer;
dim i as integer;
x[1, 1] = 1;
x[1, 2] = 2;
x[1, 3] = 3;
x[2, 1] = 4;
x[2, 2] = 5;
x[2, 3] = 6;
LogMessage(x[2, 3]);
for each i in x[]
LogMessage(i);
next;

Formatting a Number Using a .NET Format 'Picture'


dim i as integer;
i = 1234;

100
Sample QuickScript .NET Scripts Wonderware - Application Server Scripting Guide

LogMessage("Total cost: " + [Link]("$#,###,###.00"));

Formatting a Time Using a .NET Format 'Picture'


dim t as time;
t = Now();
LogMessage("The current time is: " + [Link]("hh:mm:ss") + ".");

Getting the Directories Under the C Drive


dim dir as [Link];
for each dir in [Link]("c:\").GetDirectories()
LogMessage([Link]);
next;

Loading an XML Document from Disk and Doing Look-ups on


It
dim doc as [Link];
dim node as [Link];
doc = new [Link];
[Link]("c:\[Link]");
' find the title of the book whose isbn is 044023722X
node = [Link]("/catalog/book[@isbn='044023722X']/title");
LogMessage([Link]);
' find all titles written by Grisham
for each node in
[Link]("/catalog/book[author/lastName='Grisham']/title")
LogMessage([Link]);
next;

Querying a SQL Server Database


dim connection as [Link];
dim command as [Link];
dim reader as [Link];
connection = new
[Link]("server=(local);uid=sa;database=northwin
d");
[Link]();
command = new [Link]("select * from customers",
connection);
reader = [Link]();
while [Link]()
LogMessage(reader("CompanyName"));
endwhile;
[Link]();
[Link]();

Reading a Performance Counter


' Requires output float UDA [Link].
' Declarations
dim counter as [Link];
' Startup
counter = new [Link];
[Link] = "Processor";

101
Wonderware - Application Server Scripting Guide Sample QuickScript .NET Scripts

[Link] = "% Processor Time";


[Link] = "0";
' Execute
[Link] = [Link]();

Reading a Text File from Disk


dim sr as [Link];
sr = [Link]("c:\[Link]");
while [Link]() > -1
LogMessage([Link]());
endwhile;
[Link]();

Sharing a SQL Connection or Any Other .NET Object


In Us erDefined_001 do this:
dim connection as [Link];
’ Startup
connection = new
[Link]("server=(local);uid=sa;database=northwin
d");
[Link]();
[Link]
("NorthwindConnection", connection);
’ Shutdown
[Link]("NorthwindConnection", Null);
[Link]();
Then in UserDefined_002, UserDefined_003, and so on, do this:
dim connection as [Link];
connection = [Link]
("NorthwindConnection");
if connection <> null then
[Link](connection);
' use the connection
[Link](connection);
endif;

Using DDE to Access an Excel Spreadsheet


WWPoke("excel", "sheet1", "r1c1", "Hello");
WWRequest("excel", "sheet1", "r1c1", [Link]);
' Note: use "" to embed double quotation marks in strings
WWExecute("excel", "sheet1",
"[SELECT(""R1C1"")][[Link](,""Bold"")]");

Using Microsoft Exchange to Send an E-mail Message


The following compatibility notes apply to use of this script:
 The script will not work on Microsoft Office 2010 or later due to changes in MAPI handling.
 The script is support ed only for 32-bit versions of Microsoft Office.
 If you are using Microsoft Office 2007, you must download and install Microsoft Collaboration Data
Objects (CDO) 1.2.1. Additional information on CDO 1.2.1 is available at:
[Link] [Link]?id=3671
dim session as object;

102
Sample QuickScript .NET Scripts Wonderware - Application Server Scripting Guide

dim msg as object;


dim sProfileInfo as string;
sProfileInfo = "<type valid Microsoft Exchange Server Name here>" +
StringChar(10) + "<type valid Exchange Server user name here>";
session = CreateObject("[Link]");
[Link](, , False,False , , True, sProfileInfo);
msg = [Link]();
[Link]("<type valid email address here>");
[Link]();
[Link] = "Reminder to self";
[Link] = "Pick up eggs and milk on your way home.";
[Link]();
[Link]();

Using Screen-Scraping to Get the Temperature for a City


Note: This sample script includes a reference to a public websit e as an example. You may need to
replace that URL wit h a current and verified URL.

' Screen-scraping involves downloading a web page,


' then using a regular expression to retrieve the desired data.
' Requires input string UDA [Link], e.g. "Los Angeles,CA"
' and output float UDA [Link].
dim request as [Link];
dim reader as [Link];
dim regex as [Link];
dim match as [Link];
request = [Link]
(
"[Link] +
[Link]([Link])
);
reader = new
[Link]([Link]().GetResponseStream());
regex = new [Link]("<br><br>(.*)&deg;F<br>");
match = [Link]([Link]());
[Link] = [Link](1);

Using SMTP to Send an E-mail Message


[Link]
(
{from: } "<type valid email address here>",
{to: } "<type valid email address here>",
{subject: } "Reminder to self",
{body: } "Pick up eggs and milk on your way home."

);

Writing a Text File to Disk


dim sw as [Link];
sw = [Link]("C:\[Link]");
[Link]("one");
[Link]("two");
[Link]("three");
[Link]();

103
Wonderware - Application Server Scripting Guide Sample QuickScript .NET Scripts

Dynamically Binding an Indirect Variable to a Reference


You can dynamically bind a variable of type Indirect to an arbitrary reference string and then use it for
get/set purposes. For example:
' Assume reference obj1.Attr1 has value of 7
dim x as indirect;
dim s as string;
s = "obj1.Attr1";
[Link](s); ' where s is any expression that returns a string.
' The string should be an ArchestrA reference.
obj2.Attr2 = x; ' sets obj2.Attr2 to the reference x is bound to
' (obj1.Attr1 in this example, which has value of 7)
x = 1234; ' sets obj1.Attr1 (in this example) to 1234
IF WriteStatus(x) == MxStatusOk THEN
' ... do something
endif;

You cannot use .BindTo with an Indirect local variable to an attribute on another engine.
An unbound indirect returns no data.
If the Galaxy has Advanced Communication Management enabled, we do not recommend that you use
references that are part of an ActiveOnDemand DIObject scan group in a script with an Indirect. The
reference activation process is not in sync with the script execution, so using a function such as the
IsUseable() function always returns false.
For example, the following scripting is NOT recommended.
In the declarations section:
Dim pPump as Indirect;
In Script Body section
[Link]("Pump_001.State"); 'Pump_001 is part of a DIObject scan group that
has ActiveOnDemand enabled
IF IsUsable(pPump)
THEN Do this….' this will not execute
ELSE
Do that…
ENDIF;
[Link]("Pump_002.State");'Pump_002 is part of a DIObject scan group that
has ActiveOnDemand enabled
IF IsUsable(pPump)
THEN Do this….' this will not execute
ELSE
Do that…
ENDIF;
In the script, only Pump_002 is executing all of the time.

Important: If you have an existing application that uses the same Indirect variable with scripting more
than one time for the items extended to device integration (DI) items or for DI items directly, and you
enable Advanced Communication Management in the IDE, these scripts behave differentl y or do not
execute as expected.

104
Wonderware - Application Server Scripting Guide

Index
CreateObject() • 75
Creating a Look-up Table and Doing a Look-up
A on It • 99
Abs() • 33
Creating an XML Document and Saving it to
Accepting Autocomplete Suggestions • 17
Disk • 99
Accessing an Excel Spreadsheet Using
anImported Type Library • 97
Accessing an Excel Spreadsheet Using D
CreateObject • 97 DateTimeGMT() • 41
Accessing an Office XP Excel Deployment Scripts • 11
SpreadsheetUsing an Imported Type Library deployment timeout period • 11
• 98 deployment timeout period, scripts • 11
ActivateA pp() • 40 description • 18
and system resources • 11 DText() • 60
AND, OR, and NOT • 92 dynamic reference scripting • 17
ArcCos() • 34 dynamic references • 17
ArcSin() • 34 dynamic referencing • 17
ArcTan() • 35 Dynamic Referencing Considerations • 17
Assignment ( = ) • 92 Dynamically Binding an Indirect Variable to a
Autocomplet e • 13 Referenc e • 104

B E
Bitwise AND ( & ) • 92 entries • 9
errors • 17
Exclusive OR (^) and Inclusive OR ( | ) • 92
C Execute method • 17
Calling a Web Service to Get the Temperature
Execute Scripts • 10
for a Specified Zip Code • 98
Executing a SQL Parameterized INSERT
Calling a Web Service to Send an E -mail
Command • 100
Message • 98
Exp() • 35
Closing a Client Application Window • 18
closing a client application window cont aining
scripts • 18 F
Color Indicators for Script Elements • 12 Filling a String Array and Using It • 100
Common Scripting Environment • 9 Filling a Two-Dimensional Integer Array and
Comparisons ( <, >, <=, >=, ==, <> ) • 92 Using It • 100
Complement ( ~ ) • 91 Filtering E vents • 40
Cont act Us • 7 FOR … TO … S TEP … NE XT Loop • 86
converting • 91 FOR EACH … IN … NE XT • 87
Cos() • 35

105
Wonderware - Application Server Scripting Guide Index

Formatting a Number Using a .NE T Format


'Picture' • 100
Formatting a Time Using a .NE T Format
M
Math Functions • 33
'Picture' • 101
Maximizing or Restoring a Client Application
Window • 19
G memory load and scripts • 11
GetCPQuality() • 21 memory load during deployment • 11
GetCP TimeStamp() • 22 memory types • 91
Getting the Directories Under the C Drive • 101 message types • 91
Graphic Client Functions • 21 message types, concatenating • 91
Minimizing a Client Application Window • 19
minimizing a client application window
H containing scripts • 19
HideGraphic() • 22
Miscellaneous Functions • 40
HideS elf() • 23
Modulo (MOD) • 91
Multi-level Undo and Redo • 17
I Multiplication ( * ), Division ( / ), Addition ( +
IF … THE N … ELSEIF … ELSE … ENDIF • 84 ),Subtraction ( - ) • 91
IF … THE N … ELSEIF … ELSE … ENDIF and
Attribute Quality • 85 N
Int() • 36
Negation ( - ) • 91
IsBad() • 42
Now() • 76
IsGood() • 42
Numbers and Strings • 83
IsInitializing() • 43
IsUnc ertain() • 43
IsUsable() • 43 O
OffScan Scripts • 11
OnScan Scripts • 10
L
OnScan scripts system resources • 11
Line Numbers • 19
Opening a Client Application Window • 18
Loading an XML Document from Disk and
opening a client application window containing
Doing Look-ups on It • 101
scripts • 18
Log Functions • 19
order of evaluation, operators • 91
Log() • 36
Log10() • 36
LogCustom() • 44 P
LogDataChangeE vent() • 45 Parentheses ( ) • 91
LogDataChangeE vent() script function • 45 Pi() • 37
LogE rror() • 45 positive integers • 91
LogMessage() • 46 Power ( ** ) • 91
LogN() • 37
Logoff() • 23
LogTrace() • 46
Q
Querying a SQL Server Dat abase • 101
LogWarning() • 47
QuickScript .NET Cont rol Structures • 84
QuickScript .NET Functions • 21
QuickScript .NET Operators • 89

106
Index Wonderware - Application Server Scripting Guide

QuickScript .NET Variables • 81 StringChar() • 61


StringCompare() • 62
StringCompareNoCase() • 62
R
StringFromGMTTimeToLocal() • 63
raising to the power • 91
StringFromIntg() • 63
Reading a Performance Count er • 101
StringFromReal() • 64
Reading a Text File from Disk • 102
StringFromTime() • 65
real numbers • 91
StringFromTimeLoc al() • 65
reference scripting • 17
StringInString() • 66
referencing • 17
StringLeft () • 67
Required Syntax for Expressions and Scripts •
StringLen() • 67
9
StringLower() • 68
resource load and scripts • 11
StringMid() • 68
resources and deployment • 11
StringReplace() • 69
restoring a client application window containing
StringRight() • 70
scripts • 19
StringSpace() • 70
Round() • 37
StringTest() • 71
Run-Time Client Script Behavior • 18
StringToIntg() • 72
StringToReal() • 72
S StringTrim() • 73
Sample QuickScript .NET Scripts • 95 StringUpper() • 74
Sample Scripts • 96 System Functions • 75
Script Editing Styles and Syntax • 9 system resources, startup scripts • 11
Script Execution Types • 10
Script Functions • 21 T
SendKeys() • 48
Tan() • 39
SetAttributeV T() • 49
Text() • 74
SetAttributeV T() script function • 49
timestamps • 45, 49
SetBad() • 50
Trunc () • 39
SetGood() • 50
TRY ... CATCH • 87
SetInitializing() • 51
Types category • 21
SetUncertain() • 51
Types category, script function • 21
Sgn() • 38
Sharing a SQL Connection or Any Other .NE T
Object • 102 U
Shift Left (SHL), Shift Right (S HR) • 92 Using DDE to Access an Excel Spreadsheet •
ShowGraphic () • 24 102
ShowLoginDialog() • 33 Using Micros oft Exchange to Send an E-mail
Shutdown Scripts • 11 Message • 102
SignedAlarmAck() • 51 Using Screen-Scraping to Get the Temperature
SignedWrite() • 55 for a City • 103
Simple Scripts • 10 Using SMTP to Send an E-mail Message • 103
Sin() • 38
Sqrt() • 39
V
Startup Scripts • 10
Vista security restrictions • 40
String Functions • 60
Visual Indication of Script Errors • 19
StringASCII() • 61

107
Wonderware - Application Server Scripting Guide Index

W
WHILE Loop • 88
Working with QuickScript Editor Features • 12
WriteStatus() • 59
Writing a Text File to Disk • 103
WWControl() • 60
WWDDE Functions • 76
WWExecute() • 76
WWPoke() • 77
WWRequest() • 78
WWStringFromTime() • 75

108

You might also like