<<

Solutions Business Manager SBM ModScript Reference Guide Copyright © 2001–2020 Micro Focus or one of its affiliates.

The only warranties for products and services of Micro Focus and its affiliates and licensors (“Micro Focus”) are as may be set forth in the express warranty statements accompanying such products and services. Nothing herein should be construed as constituting an additional warranty. Micro Focus shall not be liable for technical or editorial errors or omissions contained herein. The information contained herein is subject to change without notice. Except as specifically indicated otherwise, this document contains confidential information and a valid license is required for possession, use or copying. If this work is provided to the U.S. Government, consistent with FAR 12.211 and 12.212, Commercial Computer , Computer Software Documentation, and Technical Data for Commercial Items are licensed under vendor's standard commercial license.

Part number: Product version: 11.7.1

Publication date: 2020-02-27

2 Solutions Business Manager (SBM) Table of Contents Chapter 1: Welcome to SBM ModScript ...... 17 Terminology and Naming Conventions ...... 17

Chapter 2: Introduction to SBM ModScript ...... 21 SBM ModScript Basics ...... 22 General Information ...... 22

Working With Scripts From Within SBM Composer ...... 22

SBM ModScript Elements ...... 23

Supported Language Elements ...... 24

Differences Between SBM On-Demand and SBM On-Premise ...... 24

Differences Between SBM Platform-as-a-Service and SBM On-Premise ...... 27

SBM ModScript Contexts ...... 27 Transition-Related Contexts ...... 28 Handling Errors within Transition Contexts...... 30

Script Features by Transition Method ...... 30

Direct Access Contexts ...... 31 HTML Template Direct Access Context ...... 32

URL Direct Access Context ...... 33

Other Contexts ...... 34 Notification Context ...... 35

Self-Registration Context ...... 35

Database Import Contexts ...... 35

RunModScript (SOAP) Context ...... 36

Chapter 3: Programming SBM ModScript ...... 37 Working with SBM Records ...... 37 Identifying Records by TS_ID and Table ID ...... 37

Identifying Records by Item Name ...... 38

Identifying Internal Field Values ...... 38

Working with SBM Database Fields ...... 39

Setting Script Application Paths ...... 40

SBM ModScript Reference Guide 3 Shell Properties ...... 40 Shell Properties by Context ...... 40 Common Shell Properties ...... 41

Shell Properties for Transition Contexts ...... 41

Shell Properties for Other Contexts ...... 47

Shell Property Descriptions ...... 50 Common Shell Properties ...... 51

Browser Redirection Shell Properties ...... 52

Client Version Shell Properties ...... 52

Current Item Shell Properties ...... 52

Current Item (ID-based) Shell Properties ...... 53

Database Import Shell Properties ...... 53

HTTP Request Header Shell Properties...... 56

LastErrorMessage Shell Properties ...... 57

PostData Shell Properties ...... 57

Registration Shell Properties ...... 58

Rerun Shell Properties ...... 58

Retry Shell Properties ...... 58

RunModScript (SOAP) Shell Properties ...... 59

Runtime Parameter Shell Properties...... 59

Transition Shell Properties ...... 60

URL Shell Properties ...... 60

User Shell Properties ...... 61

Extension Functions ...... 62 Ext.AcquireLock()...... 63

Ext.AppendTextFile() ...... 64

Ext.CmdLineWait() ...... 65

Ext.CreateAppRecord() ...... 66

Ext.CreateAppRecordList()...... 67

Ext.CreateProjectBasedRecord() ...... 68

4 Solutions Business Manager (SBM) Ext.CreateVarRecord() ...... 69

Ext.DateToDbLong() ...... 69

Ext.DbLongToDate() ...... 70

Ext.DirtyTableCache() ...... 71

Ext.EncodeHTML() ...... 72

Ext.EncodeJavaScript() ...... 73

Ext.EncodeURL() ...... 74

Ext.FileExists() ...... 74

Ext.GetCharacterSet() ...... 75

Ext.GetCompatibilityVersion() ...... 76

Ext.HasLock() ...... 77

Ext.IsStringValidUTF8() ...... 77

Ext.LoadString() ...... 78

Ext.LockIsAvailable() ...... 79

Ext.LogErrorMsg() ...... 80

Ext.LogInfoMsg() ...... 81

Ext.LogWarningMsg() ...... 81

Ext.NewTask() ...... 82

Ext.NewTaskWait() ...... 84

Ext.OutputStreamExists() ...... 85

Ext.PrimaryTableId() ...... 86

Ext.ReadTextFile() ...... 86

Ext.ReleaseLock() ...... 87

Ext.SetCompatibilityVersion() ...... 88

Ext.SetContentType() ...... 89

Ext.SetCookie() ...... 90

Ext.SetCookieExists() ...... 91

Ext.ShellHasProp() ...... 91

Ext.Sleep()...... 92

SBM ModScript Reference Guide 5 Ext.SolutionIdForPrefix() ...... 93

Ext.SolutionIdForTable()...... 94

Ext.TableDatabaseName() ...... 94

Ext.TableDisplayName() ...... 95

Ext.TableId() ...... 96

Ext.TableSingularName() ...... 98

Ext.TeamTrackDLLName() ...... 98

Ext.UnencodeURL() ...... 99

Ext.WriteStream() ...... 100

Ext.WriteTextFile() ...... 101

Free Functions ...... 101 Concatenation Operator ...... 102

SBM AppScript Conversion Functions ...... 103

CreateObject() ...... 107

CreateLocale() ...... 108

CreateUserLocale() ...... 109

CreateSystemLocale()...... 110

CreateTimeZone() ...... 110

CreateUserTimeZone() ...... 111

CreateUTCTimeZone() ...... 112

ExitScript() ...... 113

include() ...... 113

Math Functions ...... 114

ScriptEngineVersion() ...... 117

TimeMillisDate() ...... 118

TimeMillisNow() ...... 119

TimeTDate() ...... 120

TimeTNow() ...... 121

Language Types ...... 121 Map ...... 122

6 Solutions Business Manager (SBM) Pair, Map_Pair, and Dictionary_Pair ...... 123

Range types ...... 124

string ...... 125

u32string ...... 131

char32_t Unicode Utilities ...... 136

Vector ...... 137

Working with Application Objects ...... 138 Creating SBM Application Objects ...... 138

Inheritance ...... 139

Object Types ...... 139 ADLog ...... 141 Message() ...... 141

AppDb ...... 142 ColName() ...... 143

ExecuteSQL() ...... 144

GetConnectionInfo()...... 145

ReadFolderItems() ...... 146

GetDbType() ...... 147

IsMSSQL() ...... 148

IsOracle() ...... 149

ReadIntWithSQL() ...... 150

ReadTextWithSQL() ...... 151

ReadIntegersWithSQL() ...... 152

ReadTextValsWithSQL() ...... 153

ReadIntegerPairsWithSQL() ...... 154

ReadDynaSQL() ...... 155

WriteBlobToFile() ...... 157

UpdateBlobFromFile() ...... 158

UserId() ...... 159

AppRecord ...... 159

SBM ModScript Reference Guide 7 Add() ...... 161

Delete() ...... 162

Fields()...... 163

GetDisplayName()...... 164

GetFieldValue() ...... 164

GetFieldValue-type-() ...... 166

GetId()...... 168

GetUUID() ...... 169

GetName() ...... 169

GetRecTableId() ...... 170

GetSchemaColumns() ...... 171

HasVariableDBFields() ...... 173

IsFieldEqual() ...... 174

IsLocked() ...... 175

Lock() ...... 175

Read() ...... 176

ReadWithWhere() ...... 177

ReadByColumn() ...... 178

ReadByColumnAndColumn() ...... 180

ReadByUUID() ...... 181

SetFieldValue() ...... 182

SetName() ...... 183

Unlock() ...... 184

Update() ...... 185

UpdateWithLock() ...... 186

AppRecordList ...... 187 Count() ...... 187

DeleteRecord() ...... 188

FindRecord() ...... 189

8 Solutions Business Manager (SBM) Length() ...... 189

Read() ...... 190

ReadByColumn() ...... 191

ReadByColumnAndColumn() ...... 192

ReadWithWhere() ...... 193

clear() ...... 195

empty() ...... 196

erase_at() ...... 196

size() ...... 197

Update() ...... 198

Change ...... 198 GetTime() ...... 201

GetUserName() ...... 202

ChangeList ...... 203

DbImport ...... 203 SrcColumn() ...... 203

SrcType()...... 204

SrcLabel() ...... 205

DestFldId() ...... 206

SrcData()...... 207

Dictionary ...... 207

Field...... 209 AppendJournalText() ...... 209

GetDbValue-type-() ...... 210

GetDbValue() ...... 211

GetDisplayValue() ...... 212

GetRequiredFlag()...... 213

GetSelectionList() ...... 214

GetType() ...... 215

GetTypeString() ...... 215

SBM ModScript Reference Guide 9 GetValue-type-() ...... 216

GetValue() ...... 217

IsAuto() ...... 218

IsBlank() ...... 219

IsDbBlank() ...... 219

IsSelected() ...... 220

Select() ...... 221

SetBlankValue()...... 221

SetValue() ...... 222

Folder ...... 223 AddItem() ...... 224

Contains() ...... 224

DeleteItem() ...... 225

FolderItem ...... 226

FolderItemList ...... 226 Contains() ...... 226

Incident ...... 227

Lib ...... 227 SetLibraryName() ...... 228

LoadLibrary() ...... 229

FreeLibrary() ...... 229

IsLibraryLoaded() ...... 230

CallLibraryFunction() ...... 231

Locale ...... 233 Collate() ...... 233

CollateCaseInsensitive() ...... 234

GetName() ...... 235

GetId()...... 236

Parse-type-() ...... 237

Format-type-() ...... 238

10 Solutions Business Manager (SBM) GetDayOfWeekName()...... 239

GetMonthName() ...... 240

GetAMPMName() ...... 241

Log ...... 242 Open() ...... 243

Close() ...... 244

SetBackUpLogFile() ...... 245

SetMaxSize() ...... 245

SetWantTimeStamp() ...... 246

SetReportingLevel() ...... 247

IsOpen() ...... 248

GetFileName() ...... 249

GetReportingLevel() ...... 249

Message() ...... 250

Project...... 252

ProjectBasedRecord...... 252 GetProjectId() ...... 252

StartSubmitToProject() ...... 253

StartSubmitToProjectUsingTransition() ...... 254

FinishSubmitToProject() ...... 255

FinishSubmitToProjectUsingTransition() ...... 256

QuickSubmitToProject() ...... 257

QuickSubmitToProjectUsingTransition() ...... 258

Regex ...... 259 Compile() ...... 260

Matches() ...... 261

MatchesAgain() ...... 262

ReplaceAll() ...... 263

ReplaceFirst() ...... 264

GetLastError() ...... 265

SBM ModScript Reference Guide 11 GroupCount() ...... 266

GroupVal() ...... 267

Split() ...... 268

RESTDataSource ...... 269 GetURLParameters()...... 269

Get()...... 270

Post() ...... 273

Call() ...... 275

UseSBMProxy() ...... 279

bool UseSBMProxy() ...... 279

SchemaColumn...... 280

SQLColumnDef ...... 281

TempFile ...... 282 GetFileName() ...... 282

TimeMillis ...... 283 ParseDateText() ...... 285

ParseDateText() - Custom Format...... 286

FormatDateText() ...... 287

FormatDateText() - Custom Format ...... 289

ToTimePoint() ...... 290

Add() ...... 291

TruncateToDateOnly() ...... 292

ToVariant() ...... 293

TimePoint ...... 294

TimeT ...... 296 ParseDateText() ...... 297

ParseDateText() - Custom Format...... 298

FormatDateText() ...... 300

FormatDateText() - Custom Format ...... 301

ToTimePoint() ...... 302

12 Solutions Business Manager (SBM) Add() ...... 303

TruncateToDateOnly() ...... 305

ToVariant() ...... 306

TimeZone ...... 306 CreateUserTimeZone()...... 307

CreateUTCTimeZone() ...... 307

CreateTimeZone() ...... 308

GetName() ...... 309

GetID() ...... 310

Transition ...... 311 GetType() ...... 311

TreeItem...... 312 FindParent() ...... 313

GetFullName() ...... 313

HasChild() ...... 314

IsParent() ...... 315

TreeList ...... 315

UGBase ...... 316 GetDisplayName()...... 316

Member() ...... 317

UniqueName() ...... 318

User ...... 318

VarFieldList ...... 319 ApplyProjectStateOverrides()...... 319

FindField() ...... 320

FindSysField() ...... 321

SelectAll() ...... 321

Variant ...... 322

VarRecord ...... 326 GetDisplayIssueId() ...... 327

SBM ModScript Reference Guide 13 GetFieldValue() ...... 327

GetItemNumber() ...... 330

GetItemPrefix() ...... 331

GetStateId() ...... 331

SetFieldValue() ...... 332

StartTransition() ...... 334

StartTransitionWithLock() ...... 336

FinishTransition() ...... 337

QuickTransition() ...... 338

StartSubmitToAux() ...... 339

FinishSubmitToAux() ...... 340

QuickSubmitToAux()...... 341

Constants ...... 342 ADLogLevelConstants ...... 342

SBM AppScript Conversion Constants...... 343

DateFormatConstants ...... 345

DateFormatFromLocaleConstants ...... 346

DateTimeAttributeConstants ...... 347

DBTypeConstants ...... 347

FieldRequiredConstants ...... 350

FieldTypeConstants ...... 350

HTTPVerbConstants ...... 351

LogLevelConstants ...... 352

Nothing ...... 353

RegexOptionBitsConstants...... 353

SQLColumnDefOutputHint ...... 354

string_npos ...... 355

TimeFormatConstants ...... 355

TransitionTypeConstants...... 356

14 Solutions Business Manager (SBM) UnicodeCharTypeConstants ...... 356

Chapter 4: Additional SBM ModScript Features ...... 359 Including Other Scripts ...... 359

Calling Functions in a DLL from SBM ModScript ...... 360 Creating the SBM Library Object ...... 360

Loading the Library in SBM ModScript ...... 361

Calling Your Function ...... 362

Unloading the DLL ...... 362

Keeping a Library Loaded Across Script Executions ...... 363

Avoiding Exceptions...... 363

Using Date/Time Keywords ...... 364 Available Date/Time Keywords ...... 364

Chapter 5: SBM ModScript Samples ...... 367 Sample One: Read/Write Fields ...... 367

Sample Two: Launch .BAT File...... 368

Sample Three: URL Title Search ...... 370

Sample Four: Self-Registration Validation ...... 373

Sample Five: RESTDataSource ...... 374

SBM ModScript Reference Guide 15 16 Solutions Business Manager (SBM) Chapter 1: Welcome to SBM ModScript

This document describes SBM ModScript for Solutions Business Manager. SBM ModScript is modeled after ChaiScript and contains extensions to support SBM. Audience and Scope This guide describes how to write and implement SBM ModScripts. This guide is intended for programmers who wish to use SBM ModScript to implement custom features in SBM. Users should also be familiar with administering SBM and with the SBM database schema document, which is available at the Documentation Center. For SBM ModScript use cases, sample scripts, and to read questions from community members, visit https://www.serenacentral.com/.

CAUTION: Support for development efforts with custom programs written using SBM ModScript is provided by Professional Services. Questions regarding SBM ModScript operations as documented will be handled by Customer Support. Navigating this book This guide is organized as follows: • Chapter 2: Introduction to SBM ModScript [page 21] – An overview of the scripting language used by SBM ModScript and describes the eight SBM ModScript contexts available in SBM. Elements of ChaiScript that are not supported in SBM ModScript are also discussed.

• Chapter 3: Programming SBM ModScript [page 37] – Detailed information about all SBM ModScript elements, including Shell properties, "Ext" functions, and object types.

• Chapter 4: Additional SBM ModScript Features [page 359] – Provides instructions for calling functions in a DLL from SBM ModScript and for including scripts within scripts.

• Chapter 5: SBM ModScript Samples [page 367] – Contains script samples for reading from and writing to fields, launching a .bat file, and performing a URL title search. Terminology and Naming Conventions The following terminology conventions are used throughout SBM documentation to discuss the following elements: • Items: Generic term that encompasses both primary and auxiliary items, including issues, incidents, contacts, and problems. Reports are also referred to generically as items.

• Primary Items: Items like issues and incidents, which are stored in a Primary table and follow a workflow process.

SBM ModScript Reference Guide 17 Chapter 1: Welcome to SBM ModScript

• Auxiliary Items: Items like contacts, companies, and problems, which are stored in an Auxiliary table and do not follow a workflow process.

The following formatting and naming conventions are used throughout the SBM ModScript documentation for methods and functions: • Throughout Chapter 3: Programming SBM ModScript [page 37], most methods are described using the following format: ▪ Description: A brief summary of the method.

▪ Function signature: A code block with one or more signatures for each method. For example:

Each function signature is composed of the following: 1. Return – The data type returned by the method. In the signature above, the AppRecord.ReadWithWhere function returns bool. If there is no return, void is used at the beginning of the signature.

2. Function name – The name of the function. The signature above shows the ReadWithWhere function.

3. Parameters – The function parameters are enclosed in parenthesis; multiple parameters are separated by a comma. In the signature above, the ReadWithWhere function takes two parameters: whereClause and params. The second parameter, [Vector params], is an optional argument that returns a Vector of SQL bind parameters. ▪ Optional parameters are enclosed in square brackets [ ].

▪ When the type of the parameter is Variant, the type is omitted to simplify the signature.

▪ Output parameters are identified using & notation. This indicates that the object must be created before being passed to the function.

▪ Parameters: Lists the parameters, their respective data types, and a brief description.

▪ Return: Provides the data type of the return and a brief description.

▪ Technical Details: Denotes the version of SBM in which the method was first introduced or extended, if applicable.

▪ Example: A code snippet that contains a valid example of the method.

▪ Notes: Detailed usage notes, important considerations, and tips are provided in this section.

18 Solutions Business Manager (SBM) Operators are symbols such as +, =, ==, <, and >. They are used for copying and comparing objects, as well as math-related functions. The that way operators are invoked is handled differently than the way that functions are invoked. The following format is used throughout the SBM ModScript documentation for operators: TimeT& operator=( TimeT v ) Example: var t1 = TimeT(); //Uses TimeT constructor var t2 = TimeTNow(); //Gets current time t1 = t2; // Uses = operator to copy t2 to t1

The operator = method for TimeT is invoked using the "=" symbol. The value to the left of the symbol is acted on; the value to the right is the parameter that is passed to the method. In the example, the return value is ignored, but it could have been used for stringing operators and functions together.

SBM ModScript Reference Guide 19 Chapter 1: Welcome to SBM ModScript

20 Solutions Business Manager (SBM) Chapter 2: Introduction to SBM ModScript

SBM ModScript is a programming language built around ChaiScript. Designers can create and edit scripts that are executed with transitions, on notifications, and in other contexts. For details on ChaiScript, see http://chaiscript.com/. You can follow the SBM ModScript blog series on https://www.serenacentral.com/blogs/ entry/sbm-modscript-table-of-contents for articles on SBM ModScript. Entries include: • Background on SBM ModScript, see Part 1 - An Introduction to ModScript.

• An example script containing several key features in SBM ModScript, see Part 2 - Transition Related Items. The example includes: ▪ Function definitions

▪ Regular expressions

▪ List iteration

▪ Defining constants

▪ Transitioning SBM items

▪ Reading lists of SBM items

▪ Using the from_json() function

▪ Multi-line comments

• Information about adding methods to existing classes, see Part 3 - Adding Methods to a Class.

• Details on interacting with JSON, see Part 4 - JSON.

• Using algorithms and lambdas, see Part 5 - Algorithms and Lambdas.

• Calling a DLL from SBM ModScript, see Part 6 - Invoking DLLs.

• An example of directly invoking a SBM ModScript via a REST call-in, see Part 7 - REST Call Into ModScript.

• Details on making REST calls, see Part 8 - REST Callouts.

• Details on using SQL queries with SBM ModScript, see Part 9 - SQL Queries.

• Information on using regular expressions in SBM ModScript, see Part 10 - Regular Expressions.

• A review of how to invoke transitions on primary and auxiliary items in SBM ModScript, see Part 11 - Transitions.

• Experimental options on class inheritance, see Part 12 - Class Inheritance.

SBM ModScript Reference Guide 21 Chapter 2: Introduction to SBM ModScript

• An example utility function for Base64 encoding a string, see Part 13 - Base64Encode.

• A function which may be helpful in debugging by writing the underlying type of a variable, see Part 14 - Checking the Type of a Variable.

• Implementing the singleton design pattern, see Part 15 - Singletons. SBM ModScript Basics

Beginning in version 11.3, SBM supports a scripting language called SBM ModScript, which offers a degree of power and flexibility beyond that available through the standard administration interfaces. SBM ModScript is accessible from the same contexts as SBM AppScript—you can associate scripts that implement custom features with transitions, notifications, and the self-registration form. You can also set up scripts that run when a user visits a special SBM URL. SBM ModScript is modeled after ChaiScript and contains extensions to support SBM. Programmers can use SBM ModScript to implement custom features in an SBM system. General Information Consider the following information when you work with SBM ModScript: • Once a script has been written, the administrator adds it to the SBM process app via SBM Composer. Next, the administrator associates the script with specific SBM transitions, notifications, or the Self-Registration form. SBM provides privilege settings controlling administrative access to the content and setup parameters of all scripts.

• SBM ModScript scripts execute within the component of your SBM system, where they can directly access the SBM database and generate HTML for display in the browser interface.

• The SBM ModScript engine provides standard functions returning its version number as well as the SBM build number: ▪ ScriptEngineVersion()

▪ ScriptEngineMajorVersion()

▪ ScriptEngineMinorVersion()

Scripts designed to run on more than one version of SBM can use this information to determine what features are available at runtime. These functions are part of core ChaiScript and they are documented in any standard ChaiScript reference.

• SBM ModScript is not a "COM" interface. The CreateObject function can only be used to create SBM objects. There is no direct interface to other Windows applications, though SBM ModScript can call Windows applications, including those written using the SBM C++-based API. Working With Scripts From Within SBM Composer You create and edit scripts using the script editor within SBM Composer. This section describes the SBM Composer script editor and validation pane.

22 Solutions Business Manager (SBM) For information on working with scripts from within SBM Composer, see the SBM Composer Guide. In particular, see "Working with Scripts" and "About Actions". Note: Professional Services can develop and install scripts for customers who choose not to use in-house resources or third-party consultants. Call your sales representative for pricing information. • Script Editor To validate the script, click the Validate Script button in the upper left corner of the SBM Composer window. You can view the results in the Validation pane. Note: To edit an existing script, you must have the script checked out.

• Validation Output Pane The Validation Output pane displays the status and results when you validate a script. The Validation Output pane occupies the same space as the Validation Results, below the script editor. When both the Validation Results and Validation Output pane are open, you can arrange them by dragging, just as you can arrange editor tabs in the editor pane.

• Using the Script Validation TabScripts are shown under the Scripts heading in App Explorer. After you add a script or change a script in the script editor, right-click in the script editor and then select Validate. ▪ If the script is valid, the Script Validation tab displays "This script is valid."

▪ If the script has errors, the Script Validation tab displays "INVALID SCRIPT" and a description of the error or errors that were found. SBM ModScript Elements The following elements make up SBM ModScript functionality: • Context – An SBM event that triggers script execution, together with specific SBM objects related to that event, such as the current user or current item. Any of these objects can be accessed as properties of the Shell object. For details, refer to SBM ModScript Contexts [page 27].

• Shell – The SBM application object, like the Explorer Document object. A Shell contains all SBM data accessible to the script. It contains only properties, not functions. For details, refer to Shell Properties [page 40].

• Ext – Another SBM application object containing extensions to the ChaiScript built-in functions. These functions provide features or conversions not available in core ChaiScript. Ext contains only functions, not data. For details, refer to Extension Functions [page 62].

• Object Types – SBM–specific object types, such as User and Field, are supported. For details, refer to Working with Application Objects [page 138].

SBM ModScript Reference Guide 23 Chapter 2: Introduction to SBM ModScript

Supported Language Elements SBM ModScript supports all ChaiScript elements, except multi-threading using the ChaiScript keywords future and async. These are not supported in SBM ModScript. All of the SBM AppScript functions are supported in SBM ModScript. For details on converting existing SBM AppScripts to SBM ModScript, refer to the SBM ModScript Transition Guide. Differences Between SBM On-Demand and SBM On- Premise

In SBM on-demand, certain actions would not be safe and are prevented as described below.

Functions that are not supported in SBM on-demand: • AppRecord ▪ ReadWithWhere

▪ Add

▪ Update

▪ UpdateWithLock

▪ Delete

▪ SetFieldValue

▪ SetName

▪ Lock

▪ Unlock

• Change ▪ Not used in an on-demand environment.

• AppRecordList ▪ Update

▪ ReadWithWhere

• AppDb ▪ ExecuteSQL

▪ GetConnectionInfo

▪ ReadDynaSQL

▪ ReadFolderItems

▪ ReadIntWithSQL

24 Solutions Business Manager (SBM) ▪ ReadIntegerPairsWithSQL

▪ ReadIntegersWithSQL

▪ ReadTextWithSQL

▪ ReadTextValsWithSQL

▪ WriteBlobToFile

▪ UpdateBlobFromFile

• Ext ▪ NewTask

▪ NewTaskWait

▪ CmdLineWait

▪ ReadTextFile

▪ WriteTextFile

▪ AppendTextFile

▪ FileExists

▪ AcquireLock

▪ ReleaseLock

▪ LockIsAvailable

▪ HasLock

▪ Sleep

• VarRecord ▪ StartTransition

▪ StartTransitionWithLock

▪ FinishTransition

▪ QuickTransition

▪ StartSubmitToAux

▪ FinishSubmitToAux

▪ QuickSubmitToAux

• ProjectBasedRecord ▪ StartSubmitToProject

▪ FinishSubmitToProject

SBM ModScript Reference Guide 25 Chapter 2: Introduction to SBM ModScript

▪ QuickSubmitToProject

• Log The Log class is not supported in SBM On-Demand.

• Field ▪ AppendJournalText

▪ SetBlankValue

▪ SetValue

Functions that behave differently in SBM on-demand: • CreateObject ▪ AppRecord-based objects can only be created if they are based on a table that is from the current user's namespace, such as a primary or auxiliary table, or from a system table that has a TS_NAMESPACEID column (rows from namespace- striped tables can only be read if they match the current user's namespace).

▪ SBMLibrary is not allowed on-demand.

• Ext.CreateAppRecord ▪ AppRecord-based objects can only be created if they are based on a table that is from the current user's namespace, such as a primary or auxiliary table, or from a system table that has a TS_NAMESPACEID column (rows from namespace- striped tables can only be read if they match the current user's namespace).

• Ext.CreateVarRecord, Ext.CreateProjectBasedRecord ▪ The record must be for a table that is valid for the user's namespace.

• Ext ▪ Functions that refer to table data, such as TableDatabaseName, must refer to a table from the user's namespace or a system table.

• AppRecord.Read, AppRecord.ReadByColumn, AppRecord.ReadByColumnAndColumn ▪ No data is read from tables that are not directly tied to the namespace or have a TS_NAMESPACEID column. No records are returned in namespace-striped tables in which the TS_NAMESPACEID is not the current user's namespace.

• AppRecordList.Read, AppRecordList.ReadByColumn, AppRecordList.ReadByColumnAndColumn ▪ No data is read from tables that are not directly tied to the namespace or have a TS_NAMESPACEID column. No rows are returned in namespace-striped tables in which the TS_NAMESPACEID is not the current user's namespace.

26 Solutions Business Manager (SBM) Differences Between SBM Platform-as-a-Service and SBM On-Premise

In SBM Platform-as-a-Service, certain actions would not be safe and are prevented as described below.

Functions that are not supported in SBM Platform-as-a-Service: • AppDb ▪ GetConnectionInfo

▪ WriteBlobToFile

▪ UpdateBlobFromFile

• Ext ▪ NewTask

▪ NewTaskWait

▪ CmdLineWait

▪ ReadTextFile

▪ WriteTextFile

▪ AppendTextFile

▪ FileExists

• Log The Log class is not supported in SBM Platform-as-a-Service.

Functions that behave differently in SBM Platform-as-a-Service: • CreateObject ▪ SBMLibrary is not allowed inSBM Platform-as-a-Service. SBM ModScript Contexts Every script runs in response to a specific SBM event. The event typically involves a specific user, item, or other SBM objects. Together, the event and the objects make up the script's "context." When the script runs, the SBM objects can be accessed as properties of the Shell object. There are eight contexts available in SBM: • Transition-Related Contexts [page 28] ▪ Pre-Transition

▪ Post-Transition

▪ Pre-State

SBM ModScript Reference Guide 27 Chapter 2: Introduction to SBM ModScript

▪ Post-State

• Direct Access Contexts [page 31] ▪ HTML Template Direct Access Context [page 32]

▪ URL Direct Access Context [page 33]

• Other Contexts [page 34] ▪ Notification Context [page 35]

▪ Self-Registration Context [page 35]

▪ Database Import Contexts [page 35]

▪ RunModScript (SOAP) Context [page 36] Transition-Related Contexts In transition-related contexts, a script executes as a transition executes. For each context, a workflow setting determines which script, if any, executes. Pre-Transition and Post- Transition scripts can be associated with transitions at the workflow level at which the transition is created. Pre-State scripts and Post-State scripts can be associated with states at the workflow level at which the state is created. The four transition-related contexts in order of execution are: • Pre-Transition – Execute as the Transition form is generated and can display special messages at the top of the form or pre-populate fields with data.

• Post-Transition – Execute after the form is submitted and can validate form field values or perform other post-processing.

• Post-State – When a transition causes an item to change state, the old state's Post- State script executes immediately after the Post-Transition script (if any). In other words, Post-State scripts run as an item leaves a state.

• Pre-State – When a transition causes an item to change state, the new state's Pre- State script, if any, is executed. In other words, Pre-State scripts run as an item enters a state. Note: Pre-State and Post-State contexts are similar to Post-Transition contexts in that they can perform the same types of post-processing tasks.

When a transition executes, it proceeds through the stages shown in the following diagram. After all associated scripts have executed successfully, the transition is complete and new field values are written to the database. Note that scripts only execute as configured by the workflow.

28 Solutions Business Manager (SBM) Note: When invalid values are provided by the user on a form, the script runs again when the user is prompted to provide valid values if a rule like If form is invalid, rerun this script is defined for a Pre-Transition script. If the rule is set to don't rerun, the script is not automatically run again. This applies to pre- transition Web services as well. If you have configured a pre-trans Web service and a pre-transition script, the Web service runs before the script. Both action types can re-run or not re-run if the form has an error, and they will run in the same order if both are marked for rerun.

SBM ModScript Reference Guide 29 Chapter 2: Introduction to SBM ModScript

Note: For efficiency, the second "Auto" resolution is skipped if there are no scripts to run after the form is submitted (i.e., there is no corresponding Post- Transition, Post-State, or Pre-State script). When there are no such scripts, the two "Auto" resolution steps are redundant because they would execute back to back.

Handling Errors within Transition Contexts Scripts using the transition inform you when parsing or runtime errors occur. If a parsing or runtime error occurs on a Pre-Transition script, a warning displays at the top of the form, but users may continue the transition. On Post-Transition, Pre-State, and Post-State contexts, users are warned of the error and cannot complete the transition until the script is fixed or removed from the transition.

Script Features by Transition Method Transitions can be executed manually by users in the browser interface, automatically by transition actions such as triggers or sub-tasking, by special transitions such as post item or Create Subtask transitions, or in response to external programs. When a script runs because a transition was executed, certain browser-based features may not be available to the script depending on how the transition was executed, as shown in the following table. Table 1.

Transition Shell object Redirect† Write Reject transition by Method contains HTML† writing to browser Shell.RedoMessage() properties?

Standard Yes Yes Pre- Post-Transition, Pre- transition by user Transition State, and Post-State only only

Post Item or Yes No Pre- Post-Transition, Pre- Publish Problem Transition State, and Post-State transition only only

Copy transition Yes Yes Pre- Post-Transition, Pre- Transition State, and Post-State only only

Mass updates Yes No Pre- Post-Transition, Pre- Transition State, and Post-State only only**

30 Solutions Business Manager (SBM) Transition Shell object Redirect† Write Reject transition by Method contains HTML† writing to browser Shell.RedoMessage() properties?

Actions N/A N/A N/A Post-Transition, Pre- (Transition State, and Post-State Trigger, only*** Subtasks, etc.)

API Call, External N/A N/A N/A Post-Transition, Pre- Post Transition, or State, and Post-State E-mail only Submission

† When Shell.Rerun() is True, a script may not redirect or write HTML. ** Mass updates enable users to transition multiple items at once. Each item runs its own Pre-Transition, Post-Transition, Pre-State, and Post-State script and can be rejected individually based on script logic. Each error message returned in Shell.RedoMessage() is logged in the Windows Event Viewer and all messages are displayed together on the mass update results page. The first item receives special treatment, however. If any of its scripts write to Shell.RedoMessage(), the form is redisplayed with that error message, and the entire mass update fails. Redirect is not available because each item's script might specify a different redirect location and because mass updates depend on a built-in redirect. *** Transitions that execute based on actions, such as Triggers or subtasking, behave similarly to mass updates. Depending on project and workflow settings, a transition may execute a batch of other transitions, each of which may run a script. If none of the scripts reject their items by writing to Shell.RedoMessage(), the Last Transition Sequence displays information to the user about the executed batch of transition. If some transitions are rejected, all Shell.RedoMessage() values are displayed on an error page in the browser and each is sent to the Event Viewer. Direct Access Contexts Direct access contexts are quite different from transition-related contexts and do not require any administrative setup. These contexts do not execute in response to an SBM event. They are invoked when the server receives a URL of a certain form or encounters a certain HTML template tag. The following direct access contexts are available. • HTML Template – This context can call a script from any SBM HTML template and embed the output in the browser page or manipulate that result using JavaScript. For details, refer to HTML Template Direct Access Context [page 32].

• URL – Any script can be called directly by accessing the proper URL and the script's HTML output is displayed in the browser. For details, refer to URL Direct Access Context [page 33].

SBM ModScript Reference Guide 31 Chapter 2: Introduction to SBM ModScript

If an HTML template contains the server-side instruction "$SCRIPT" (with proper parameters), the server runs the specified script. The $SCRIPT instruction has three valid forms where "..." denotes zero or more optional comma-separated parameters: • $SCRIPT( scriptName ... ) – Script names are visible in the Scripts editor in SBM Composer. Invoking scripts by name is the recommended form. Because the same script name can be used in multiple solutions, SBM tries to determine the current solution using parameters that are passed in as context. For example, if the template is an item view, the item is in a table that is associated with a solution; therefore, that solution is used. If possible, SBM uses that solution to find the script by the provided name. If a script for the contextual solution cannot be found, any script with the provided name is used instead.

• $SCRIPT( scriptID ... ) – Every script in your SBM database has a name and a TS_ID column in the TS_MACROS table of the database. TS_IDs are assigned when the script is added to the SBM ModScript database and never change. Scripts should only be invoked by TS_ID if there is a name conflict or if you need to allow the script's name to be edited without breaking an HTML template.

• $SCRIPT(SCRIPTUUID, uuid, ... ) – Scripts can be requested by UUID using SCRIPTUUID in the first parameter (all uppercase), followed by the script's UUID in the second parameter. The UUID for the script can be found in the TS_MACROS table of the database.

To interpret the first $SCRIPT parameter, the SBM server determines whether all characters are digits. If so, the parameter is taken as the script's TS_ID. Otherwise, the parameter is taken as the script's name, unless the first parameter is SCRIPTUUID.

HTML Template Direct Access Context Every SBM browser page is generated from an HTML template containing HTML and proprietary server-side instructions. If an HTML template contains the server-side instruction $SCRIPT(), with proper parameters, the server runs the specified script. In the outgoing HTML, the entire $SCRIPT instruction is replaced by the script's output. If the script's output is valid HTML, it is visible in the browser. For an example of $SCRIPT() usage, see below. To view an HTML template, browse to an SBM URL containing the parameter "Template=name", where "name" is the file name of the template, excluding the "htm" extension. For example, the URL for the About page is as follows:

http://server/workcenter/tmtrack.dll?StdPage&Template=about

If the HTML template contains a $SCRIPT tag, the output of that script is visible on the page. Any optional parameters following the name/ID are inserted into a Dictionary object which is passed to the script. The Dictionary of optional parameters is accessible from within the script as "Shell.Params()." Shell.Params() supports the methods and properties of a Dictionary. The value of the Nth optional parameter is associated with a key called "paramN." For example, the first optional parameter is "param1."

32 Solutions Business Manager (SBM) Example: Using $SCRIPT() in HTML Create a script called myScript:

var sText1; var sText2; Shell.Params().Item( "param1" ); Shell.Params().Item( "param2" );

Ext.WriteStream( ""); Ext.WriteStream( "Script Test" ); Ext.WriteStream( "" );

Ext.WriteStream( "Param1: " ); Ext.WriteStream( "

" &&& EncodeHTML(sText1) &&& "

" ); Ext.WriteStream( "
" );

Ext.WriteStream( "Param2: " ); Ext.WriteStream( "

" &&& EncodeHTML(sText2) &&& "

" ); Ext.WriteStream( "
" );

Ext.WriteStream( "" ); Ext.WriteStream( "" );

Create an HTML file called scripttest.htm, and add the following text to it:

$SCRIPT( myScript, Godzilla, King Kong );

Save this file in the SBM installation templates directory. Use the following URL to test the $SCRIPT mechanism:

http://server/workcenter/tmtrack.dll?StdPage&Template=scripttest

URL Direct Access Context A script can generate HTML output to be viewed in the browser without using an HTML template. A URL can invoke a script directly and display the output in the browser. In this case, the script must generate valid HTML for an entire browser page, including the start and end tags. Such scripts are invoked by browsing to a URL in one of the following formats, where "..." denotes zero or more optional URL parameters of the form "¶m=value.>

http://server/workcenter/tmtrack.dll?ScriptPage&scriptName=name… http://server/workcenter/tmtrack.dll?ScriptPage&scriptID=number… http://server/workcenter/tmtrack.dll?ScriptPage&scriptUUID=uuid…

When requesting a script in the URL context, the script name can be passed unambiguously by using the following optional parameters: • ScriptSolutionID – You can optionally provide ScriptSolutionID to specify the solution ID for the script. If the script is not found by that name in the specified solution, SBM searches other solutions and the first script found with that name is used.

SBM ModScript Reference Guide 33 Chapter 2: Introduction to SBM ModScript

• ScriptAppInternalName – You can optionally provide ScriptAppInternalName to specify the internal application name. The internal name is created by SBM Composer and stored in TS_SOLUTIONS.TS_NAME in the database. When ScriptAppInternalName is included, SBM finds the solution with that name, and searches for the script in that solution. If a solution is not found with that name, or if no script is found for that solution, SBM searches for any script with the specified name instead.

Any optional parameters following the name/ID are inserted into a Dictionary object which is passed to the script. This Dictionary object is identical to the one constructed in the HTML template context, with the exception that the key names are taken from the URL parameter names, rather than being generated sequentially as "param1," "param2," etc. Note: URL parameter names are converted to lower case before being stored in the Shell.Params() dictionary. To retrieve parameter values, you must supply parameter names in lower case, such as Shell.Params().Item("msg") . For example, the following script generates an entire browser page displaying a message given by a URL parameter:

Ext.WriteStream(""); Ext.WriteStream("Script Test"); Ext.WriteStream("

" &&& Shell.Params().Item("msg")); Ext.WriteStream("

"); Ext.WriteStream("");

If this script is named "myScript," you can invoke it by browsing to the following URL:

http://server/workcenter/tmtrack.dll? →ScriptPage&scriptName=myScript&msg=This%20is%20a%20message

For details on using the URL context with an HTTP POST, refer to PostData Shell Properties [page 57]. For a detailed example of directly invoking a SBM ModScript via a URL, see https://www.serenacentral.com/blogs/entry/sbm-modscript-part-7-rest-call-into- modscript. Other Contexts The following contexts execute in response to miscellaneous SBM events: • Notification context – Provides the option of running a script when certain conditions are met. Scripts using the notification context are executed based on rules applied to a notification generated by the Notification Server. For details on creating notifications, refer to the SBM Application Administrator Guide. For information about the Notification Server, refer to the SBM Installation and Configuration Guide. For details on the Notification context, refer to Notification Context [page 35].

• Self-Registration context – Executes when users submit the Self-Registration form. For details, refer to Self-Registration Context [page 35].

• Database import contexts – Provides the option of running a script when importing data from a generic ODBC database. For details, refer to Database Import Contexts [page 35].

34 Solutions Business Manager (SBM) • RunModscript (SOAP) context – Used by the RunModScript Web service SOAP call. For details, refer to RunModScript (SOAP) Context [page 36].

Notification Context Notifications are often used to send e-mail when a given condition is met. However, instead of sending e-mail, the notification mechanism can call a script. For example, the Notification "any item changes state" may run a script for any state change in the workflow. Notification scripts lend themselves to integration with other applications because they can call external applications to import and/or export data when various SBM events occur. If a notification script writes a non-empty string to Shell.RedoMessage(), it is considered to have failed. The notification is retried until the script succeeds or the maximum number of retries is reached. Notification scripts run once per subscriber, with Shell.User() equal to the subscriber. If there are no subscribers, the script runs once with Shell.User() equal to the global constant Nothing. This differs from all other contexts, in which Shell.User() is the currently authenticated user.

Self-Registration Context Self-Registration context is intended for form validation on the external user Self- Registration form. For example, a Self-Registration script might enforce a minimum length for passwords. The script runs after the user clicks the Submit button and can reject the form if needed. For details about setting up Self-Registration, refer to the SBM System Administrator Guide.

Database Import Contexts Database import contexts include the Pre-DbImport and Post-DbImport contexts, which execute scripts before and after importing data from a generic ODBC database. The process is as follows: 1. Read or initialize the destination record.

2. Run the Pre-DbImport script, if defined.

3. Map fields in the source database to destination fields. Note: If a Pre-DbImport script modified a mapped SBM field, the source to destination mapping will not have an effect. The script change takes precedence.

4. Run the Post-DbImport script, if defined.

5. If updating existing items, validate any changed items and bypass the update if the Update only if change detected option is enabled.

6. Add or update the destination record to the SBM database.

For details on importing data, refer to the SBM System Administrator Guide.

SBM ModScript Reference Guide 35 Chapter 2: Introduction to SBM ModScript

RunModScript (SOAP) Context The RunModScript (SOAP) context provides Shell properties when calling the RunModScript Web service, which is available in the sbmappservices72 WSDL. For details about the RunModScript call, refer to the SBM Web Services Developer's Guide.

36 Solutions Business Manager (SBM) Chapter 3: Programming SBM ModScript

SBM ModScript programming elements include Shell properties, "Ext" functions, and object types. SBM ModScript programming requires some knowledge of identifying and working with SBM database records. • Working with SBM Database Records [page 37]

• Working with SBM Database Fields [page 39]

• Setting Script Application Paths [page 40]

• Shell Properties [page 40]

• Extension Functions [page 62]

• Free Functions [page 101]

• Language Types [page 121]

• Working with Application Objects [page 138]

• Object Types [page 139]

• Constants [page 342] Working with SBM Database Records SBM database records can be identified by name or by a pair of numeric codes. The VarRecord Object is best used to represent these database records. For details, refer to VarRecord [page 326]. Note: The SBM schema document is available from the Documentation Center to assist you in working with database records through SBM ModScript.

Identifying Records by TS_ID and Table ID The most efficient way to identify an SBM record is by its TS_ID and table ID. Every table in the SBM database contains an integer column named TS_ID. All TS_ID values are unique within their table. In turn, each table is assigned a unique numeric ID, stored in the TS_ID column of the TS_TABLES table. Any row in the SBM database can be uniquely identified by its table ID and its TS_ID. For example, to identify the project record for an SBM Project named "My Project," you can supply the table ID for the Projects table and the TS_ID of the row containing "My Project." The TS_TABLES table contains a row with "Projects" as the TS_NAME value. That row describes the Projects table; it has a TS_DBNAME of "TS_PROJECTS" and a TS_ID of 8. In the TS_PROJECTS table, the row with a TS_NAME of "My Project" may have a TS_ID of 47. In that case, the "My Project" project is uniquely identified by a table ID of 8 and a TS_ID of 47. SQL statements attempting to query the Projects table should use the database name "TS_PROJECTS" given in the TS_DBNAME column of TS_TABLES.

SBM ModScript Reference Guide 37 Chapter 3: Programming SBM ModScript

Since there are typically multiple Primary and Auxiliary tables, primary and auxiliary items must be identified by both their table ID and TS_ID. The table ID is often thought of as the item type. For example, an issue would reside in the Issues table, being a different type of primary item than an incident which resides in the Incidents table. Shell Properties [page 40] contains a detailed listing of all table IDs and TS_IDs that are passed to a script at runtime. Working with Application Objects [page 138] lists many object methods that use table IDs and/or TS_IDs as parameters or return values. Note: Valid TS_ID and table ID values are positive numbers. Other values typically indicate an error or a result of "none."

Identifying Records by Item Name You can identify SBM records by name. All Primary and Auxiliary tables and many system tables have a column corresponding to record name. System tables without such a column do not have a meaningful name concept and their records are considered to have a name of empty string. Though record name uniqueness is not enforced, many SBM installations use unique names for certain record types, such as projects. For those record types, a script may want to look up a record by name. Record names are often supplied as Shell properties and sometimes appear as object method parameters or return values. For system tables (tables without variable fields), the name column is always called TS_NAME. Some system tables, such as the TS_RECORDLOCKS table, do not have a TS_NAME column, because they are internal objects. In those tables, all record name values are considered to be empty string. For Primary and Auxiliary tables, the name column has a database name of TS_TITLE that corresponds to a variable field defined in the TS_FIELDS table. Every Primary or Auxiliary table has a minimum set of "system fields" required for basic SBM operations, and these system fields have positive numbers in the TS_SYSCODE column of the TS_FIELDS table. The record name is one such system field, having a TS_SYSCODE value of 4. A list of syscode values can be found in the SBM schema document available from the Documentation Center. To find the column corresponding to a record's name in a Primary or Auxiliary table, locate the row of the TS_FIELDS table with a TS_SYSCODE of 4 and TS_TABLEID matching the desired table's ID. That row corresponds to the table's record name field. That row's TS_DBNAME value is the database name of the given table's record name column. That row's TS_NAME value is the display name of the given table's record name column. Note that the database name of this column never changes and can thus be hard coded in SQL statements. The display name may be changed at any time by the SBM administrator. Identifying Internal Field Values Certain methods require that you pass the internal ID for specific field values. For example, the input for the SetValue method for the Field object requires the internal database value. The following list describes the internal value format for most SBM field types: • Binary/Trinary: Internal values are 0, 1, and 2, representing the first, second, and third values.

38 Solutions Business Manager (SBM) • Date/Time: Internal value is a number representing seconds since Jan 1 1970 in GMT or just elapsed seconds for elapsed time. Important: See also Ext.SetCompatibilityVersion() [page 88].

• Folder: The TS_ID for the folder specified in the TS_FOLDERS table.

• Multi-Group: Comma-separated list (with leading and trailing commas) of TS_IDs from the TS_GROUPS table.

• Multi-Relational: Comma-separated list (with leading and trailing commas) of TS_IDs from the relational table.

• Multi-Selection: Comma-separated list (with leading and trailing commas) of TS_IDs from the TS_SELECTIONS table.

• Multi-User: Comma-separated list (with leading and trailing commas) of TS_IDs from the TS_USERS table. Important: If the Groups and Users selection mode is enabled for the field, the value can also include group identifiers (TS_IDs from the TS_GROUPS table), which are in the form G1, G2, and so forth.

• Numeric: Same as display value.

• Single Relational: The TS_ID of the item in the relational table.

• Single Selection: The TS_ID of the selection from the TS_SELECTIONS table.

• Summation: Same as display value.

• Text: Same as display value.

• User: The TS_ID of value from the TS_USERS table.

Related Topics Identifying Records by TS_ID and Table ID [page 37] Identifying Records by Item Name [page 38] Working with SBM Database Fields There are two types of fields in the database depending on the type of table you are working with: • System table: System tables are automatically created for every SBM database and are used by SBM internally. System table fields cannot be renamed. When writing scripts where you specify field names for system tables, enter the name without the TS_ prefix or the field will not be found.

• All other tables: Non-system tables, such as primary or auxiliary tables, include system fields that are automatically added to every table, as well as fields that are added by users. Both types of fields are considered variable fields, which can be renamed.

SBM ModScript Reference Guide 39 Chapter 3: Programming SBM ModScript

Field names for variable fields should be provided in uppercase characters for database name characters (without the TS_ prefix) or in lowercase/mixed-case characters for display names (for Title, for example).

Keep this distinction in mind as you work with functions that require you to specify field names (such as GetFieldValue and SetFieldValue). Setting Script Application Paths

When you write scripts that call applications or DLLs outside of SBM, you can create an optional ScriptAppPath registry setting that contains a semicolon-separated list of directories that store executable files and DLLs that are called in SBM ModScripts. If ScriptAppPath is not found, the path list in the standard Windows environment variable PATH is used. Optionally, you can place DLLs and executables in the companyName/productName/bin directory on your SBM Web server. To create the optional SBM registry setting on a Windows Web server:

1. Launch the Registry Editor on the Web server. Note: If your system uses multiple Web servers, the registry setting must be added to each.

2. Navigate to the HKEY_LOCAL_MACHINE/Software/TEAMSHARE/TEAMTRACK directory.

3. Add a new string value called ScriptAppPath.

4. Modify the setting and add the directory in which the executable or DLL you are calling in your script is stored. Multiple directories should be separated by semi- colons. Note: ScriptAppPath conforms to the same syntax as the Windows environment variable PATH. Folder paths are separated by semicolons, environment variables are surrounded by '%' characters, and spaces do not need to be escaped or quoted. Unlike path, any quotes in ScriptAppPath are interpreted literally as part of the folder name. Shell Properties "Shell" is the SBM application object, like the Internet Explorer "Document." The Shell contains all SBM data accessible to the script. It contains only properties, no methods. These properties, plus output stream access as noted in the following table, compose the entire interface between the SBM application and any script that it calls. Shell Properties by Context The set of Shell properties available depends on the context. Tables in Common Shell Properties [page 41], Shell Properties for Transition Contexts [page 41], and Shell Properties for Other Contexts [page 47] explain which context each shell can be used with. Each shell is more fully described in Shell Property Descriptions [page 50]. The "I/O" column in each table indicates whether the property is an input or an output. A script reads from "I" properties to get information from SBM; writing to "I" properties has no effect. Writing to "O" properties passes information back to SBM. "I/O" properties are for both reading and writing.

40 Solutions Business Manager (SBM) [output stream] is not a Shell property. This row indicates contexts in which Ext.OutputStreamExists() returns True, meaning scripts can write to the current output stream using Ext.WriteStream(). This output stream is always an HTTP connection to the user's browser.

Common Shell Properties The following table lists Shell properties for all SBM ModScript contexts.

Name Variant Data Format Input (I)/Output (O)

Context() string I

Db() AppDb I

RESTTimeout() int I

ScriptId() int I

ScriptFileName() string I

ScriptName() string I

string GetLastErrorMessage() N/A I

SetLastErrorMessage(message) N/A I

ClearLastErrorMessage() N/A I

Shell Properties for Transition Contexts The following table lists Shell properties for Pre-Transition, Post-Transition, Pre-State, and Post-State contexts. Transitions are often executed from a browser, operating on a single item. However, it is possible to transition multiple items at once or to initiate a transition without using a browser. In those cases, there are special considerations, and properties relating to the browser may not be available.

Name Variant Input/ Contexts Transition Data output types Format (I/O)

[output stream] n/a O Pre-Transition Standard, Copy, Mass Update

SBM ModScript Reference Guide 41 Chapter 3: Programming SBM ModScript

Name Variant Input/ Contexts Transition Data output types Format (I/O)

Browser Redirection Shell Properties [page 52]

RedirectHTTP() string O Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update State

RedirectURL() string O Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update State

Client Version Shell Properties [page 52]

ClientBrand() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update State

ClientVersion() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update State

Current Item Shell Properties [page 52]

Item() VarRecord I, O Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

Project() Project I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

SolutionId() int I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

42 Solutions Business Manager (SBM) Name Variant Input/ Contexts Transition Data output types Format (I/O)

SolutionName() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

SolutionPrefix() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

HTTP Request Header Shell Properties [page 56]

ContentType() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

HTTPAuthorization() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

HTTPCookie() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

HTTPUserAgent() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

RemoteAddr() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

RequestMethod() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

SBM ModScript Reference Guide 43 Chapter 3: Programming SBM ModScript

Name Variant Input/ Contexts Transition Data output types Format (I/O)

ServerSoftware() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

ServerProtocol() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

RemoteUser() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

Referer() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

Rerun Shell Properties [page 58]

Rerun() bool I Pre-Transition Standard, Copy, Mass Update

Retry Shell Properties [page 58]

RedoMessage() string O Post-Transition, Standard, Pre-State, Post- Copy, State Mass Update, API, Actions

Transition Shell Properties [page 60]

FromStateId() int I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

44 Solutions Business Manager (SBM) Name Variant Input/ Contexts Transition Data output types Format (I/O)

FromStateName() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

MassTransPreForm() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update State

ToStateId() int I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

ToStateName() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

TransitionId() int I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

TransitionName() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

TransitionType() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

URL Shell Properties [page 60]

URLPath() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update State

SBM ModScript Reference Guide 45 Chapter 3: Programming SBM ModScript

Name Variant Input/ Contexts Transition Data output types Format (I/O)

URLPort() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update State

URLProtocol() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update State

URLQuery() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update State

URLServer() string I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update State

User Shell Properties [page 61]

User() User I Pre-Transition, Standard, Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

ActingAsAnotherUserID() int (Not a I Pre-Transition, Standard, Variant) Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

IsActingAsAnotherUser() bool (Not I Pre-Transition, Standard, a Variant) Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

NamespaceID() int (Not a I Pre-Transition, Standard, Variant) Post-Transition, Copy, Pre-State, Post- Mass Update, State API, Actions

46 Solutions Business Manager (SBM) Name Variant Input/ Contexts Transition Data output types Format (I/O)

NamespacePrefix() string I Pre-Transition, Standard, (Not a Post-Transition, Copy, Variant) Pre-State, Post- Mass Update, State API, Actions

UserToken() string I Pre-Transition, Standard, (Not a Post-Transition, Copy, Variant) Pre-State, Post- Mass Update, State API, Actions

Shell Properties for Other Contexts The following table lists Shell properties for Database Import, URL Direct, Notification, RunModScript (SOAP), and Self-Registration contexts.

Name Variant Input/ Contexts Data output Format (I/O)

[output stream] n/a O HTML Template, URL

Browser Redirection Shell Properties [page 52]

RedirectURL() string O HTML Template, URL, Self- Registration

RedirectHTTP() string O HTML Template, URL, Self- Registration

Client Version Shell Properties [page 52]

ClientBrand() string I HTML Template, URL, Self- Registration

ClientVersion() string I HTML Template, URL, Self- Registration

Current Item (ID-based) Shell Properties [page 53]

Item() VarRecord I, O Pre-DbImport, Post-DbImport

SBM ModScript Reference Guide 47 Chapter 3: Programming SBM ModScript

Name Variant Input/ Contexts Data output Format (I/O)

ItemId() int I Notification

Project() Project I Pre-Dbimport, Post-DbImport

TableId() int I Notification

Database Import Shell Properties [page 53]

ImportAction() string I Pre-DbImport, Post-DbImport

ImportCommand() int O Pre-DbImport, Post-DbImport

ImportID() int I Pre-DbImport, Post-DbImport

ImportLog() TSLog I, O Pre-DbImport, Post-DbImport

ImportName() string I Pre-DbImport, Post-DbImport

Source() Dictionary I Pre-DbImport, Post-DbImport

SourceDb() AppDb I Pre-DbImport, Post-DbImport

HTTP Request Header Shell Properties [page 56]

ContentType() string I HTML Template, URL

HTTPAuthorization() string I HTML Template, URL

HTTPCookie() string I HTML Template, URL

HTTPUserAgent() string I HTML Template, URL

RemoteAddr() string I HTML Template, URL

RemoteUser() string I HTML Template, URL

RequestMethod() string I HTML Template, URL

ServerSoftware() string I HTML Template, URL

48 Solutions Business Manager (SBM) Name Variant Input/ Contexts Data output Format (I/O)

ServerProtocol() string I HTML Template, URL

Referer() string I HTML Template, URL

Registration Shell Properties [page 58]

LoginId() string I Self-Registration

Password() string I Self-Registration

RegistrationMethod() int I Self-Registration

Contact() VarRecord IO Self-Registration

Retry Shell Properties [page 58]

RedoMessage() string O Self-Registration, Notification

Runtime Parameter Shell Properties [page 59]

Params() Dictionary I HTML Template, URL, RunModScript (SOAP)

RunModScript (SOAP) Shell Properties [page 59]

Outputs() Vector O RunModScript (SOAP) (Not a Variant)

URL Shell Properties [page 60]

PostData() string I URL

URLPath() string I HTML Template, URL, Self- Registration, Notification

SBM ModScript Reference Guide 49 Chapter 3: Programming SBM ModScript

Name Variant Input/ Contexts Data output Format (I/O)

URLPort() string I HTML Template, URL, Self- Registration, Notification

URLProtocol() string I HTML Template, URL, Self- Registration, Notification

URLQuery() string I HTML Template, URL, Self- Registration, Notification

URLServer() string I HTML Template, URL, Self- Registration, Notification

User Shell Properties [page 61]

User() User I HTML Template, URL, Notification, Pre-DbImport, Post-DbImport, RunModScript (SOAP)

ActingAsAnotherUserID() int (Not a I HTML Template, URL, Notification, Variant) Pre-DbImport, Post-DbImport, RunModScript (SOAP)

IsActingAsAnotherUser() bool (Not I HTML Template, URL, Notification, a Variant) Pre-DbImport, Post-DbImport, RunModScript (SOAP)

NamespaceID() int (Not a I HTML Template, URL, Notification, Variant) Pre-DbImport, Post-DbImport, RunModScript (SOAP)

NamespacePrefix() string I HTML Template, URL, Notification, (Not a Pre-DbImport, Post-DbImport, Variant) RunModScript (SOAP)

UserToken() string I HTML Template, URL, Notification, (Not a Pre-DbImport, Post-DbImport, Variant) RunModScript (SOAP)

Shell Property Descriptions The following topics provide detailed descriptions of all Shell Properties.

50 Solutions Business Manager (SBM) • Common Shell Properties [page 51]

• Browser Redirection Shell Properties [page 52]

• Client Version Shell Properties [page 52]

• Current Item Shell Properties [page 52]

• Current Item (ID-based) Shell Properties [page 53]

• Database Import Shell Properties [page 53]

• HTTP Request Header Shell Properties [page 56]

• LastErrorMessage Shell Properties [page 57]

• PostData Shell Properties [page 57]

• Registration Shell Properties [page 58]

• Rerun Shell Properties [page 58]

• Retry Shell Properties [page 58]

• Runtime Parameter Shell Properties [page 59]

• Transition Shell Properties [page 60]

• URL Shell Properties [page 60]

• User Shell Properties [page 61]

Common Shell Properties

Common shell property accessors are defined for all contexts.

Shell.RESTTimeout() Variant& containing int (editable). The timeout value used during REST calls. Can be used to change the timeout for the subsequent REST calls in the script. To change the default value (30 seconds), you must add a new entry to the TS_SYSTEMSETTINGS table called DefaultRESTTimeout with TS_DATATYPE set to 1 and specify the desired timeout in the TS_LONGVALUE column. Shell.ScriptName() Variant& containing string (read-only). The script's name as stored in the database and shown in the Scripts editor in SBM Composer. Shell.ScriptId() Variant& containing int (read-only). This is the script's TS_ID. For details on the TS_ID, refer to Identifying Records by TS_ID and Table ID [page 37]. Shell.ScriptFileName() Variant& containing string (read-only). This is the file name from which the script was most recently read and parsed.

SBM ModScript Reference Guide 51 Chapter 3: Programming SBM ModScript

Shell.Context() Variant& containing string (read-only). Identifies the current context. Possible values are pre-transition, post-transition, pre-state, post-state, HTML template, URL, notification, self registration, pre-DbImport, post-DbImport, and RunModScript (SOAP). For details on contexts, refer to SBM ModScript Contexts [page 27]. Shell.Db() Variant& containing AppDb object. The current SBM database object. It provides global data related to the SBM database, as well as database I/O functionality. See AppDb [page 142].

Browser Redirection Shell Properties

Browser Redirection shell property accessors are defined when the browser can be redirected.

Shell.RedirectURL() Variant& containing string (editable). If the script writes a URL string to this property, the browser is redirected there when the script exits. The server generates an HTTP 302 response containing header values appropriate for most uses. Shell.RedirectHTTP() Variant& containing string (editable). If the script writes an entire HTTP response string to this property, the browser is sent this HTTP response verbatim when the script exits. This is an advanced feature for special situations, such as when writing cookie values into the redirect response. Care must be taken to ensure that the HTTP string is complete, syntactically valid, and accepted by all browsers in use.

Client Version Shell Properties

Client Version shell property accessors are defined for scripts that run when users are connected to a browser or using the SBM API.

Shell.ClientBrand() Variant& containing string (read-only). The browser's product brand. Possible values are Explorer, Navigator, Mobile, API. Browsers that cannot be recognized as supporting advanced features, such as JavaScript, are classified as Mobile. A value of "API" means the script is running in response to an SBM API call by an external program, not a browser. Shell.ClientVersion() Variant& containing string (read-only). The browser's release version. If Shell.ClientBrand() is API, this is the SBM API version of the external program and is formatted v.r where v is the API version and r is the API revision.

Current Item Shell Properties

Current Item shell property accessors are defined when there is a current item, unless using the ID-based model.

52 Solutions Business Manager (SBM) Shell.Project() Variant& containing Project object. The SBM project to which Shell.Item() belongs. See Project [page 252]. Shell.SolutionName() Variant& containing string (read-only). The name of the application bound to the Primary table containing Shell.Item(). Application names are not unique. Shell.SolutionPrefix() Variant& containing string (read-only). The prefix identifying the application bound to the Primary table containing Shell.Item(). Shell.SolutionId() Variant& containing int (read-only). The TS_ID of the application bound to the Primary table containing Shell.Item(). For details on the TS_ID, refer to Identifying Records by TS_ID and Table ID [page 37]. Shell.Item() Variant& containing VarRecord object, will be ProjectBasedRecord if item is a primary item. The current item in use, such as the item being transitioned. See VarRecord [page 326] and ProjectBasedRecord [page 252].

Current Item (ID-based) Shell Properties

Current Item shell property accessors are defined when there is a current item and only TS_IDs available.

Shell.ItemId() Variant& containing int (read-only). The TS_ID of the current item in use. Shell.TableId() Variant& containing int (read-only). The TS_ID of the table containing the current item.

Database Import Shell Properties

Database import shell property accessors are defined when importing data from a generic ODBC database.

Shell.ImportAction() Variant& containing string (read-only). Specifies the operation of the data import on the current item. Possible values are add (add a new item) and update (update an existing item). Shell.ImportCommand() Variant& containing int (editable). Applies a command to the currently running script. Possible values are: • 0 (Continue) – The default value, which allows the data import to continue running.

SBM ModScript Reference Guide 53 Chapter 3: Programming SBM ModScript

• 1 (Bypass import Item) – Stops all actions on the current item and moves on to the next item. The current item will not be added or updated if this value is set.

• 2 (Kill Import) – Stops the data import for all items.

Shell.ImportId() Variant& containing int (read-only). ID of the current Import Option Set record. Shell.ImportLog() Variant& containing Log object. The Log object is a complex object used to log messages into the DBImport log file. The logging levels defined in the Log object are minimal, average, and verbose. The message function defined in the Log object logs messages directly into the DbImport log using the following syntax: Message ( Logging Level ( Int ), Message ( String ) ) For example:

var Log = Shell.ImportLog(); Log.Message ( Log.MINIMAL, "Message Logged at Minimal Logging Level" ); Log.Message ( Log.AVERAGE, "Message Logged at Average Logging Level" ); Log.Message ( Log.VERBOSE, "Message Logged at Verbose Logging Level" );

See Log [page 242]. Shell.ImportName() Variant& containing string (read-only). Name of the current Import Option Set record. Shell.Source() Variant& containing Dictionary (key(string), object (DbImport) (read-only). Key The key string contains the source column name and optionally the destination (SBM) field ID. Keys that contain only the source column name are unmapped source values available for processing via the script. All mapped keys will use the '.' as a separator followed by the SBM field database name. For example, issuetype.ISSUETYPE, state.STATE, title.TITLE, color.COLOR_SINGLE_SELECTION, issueid.ISSUEID, id. See Dictionary [page 207] and DbImport [page 203]. The following example will iterate through all values contained within the Source Dictionary:

var source = Shell.Source(); for ( dbImport : source ) { //do something with dbImport }

Value DbImport DbImport is a class that contains values representing the source database values: SrcColumn string The database column from the source database.

54 Solutions Business Manager (SBM) SrcType integer The database column type from the source database. The following database data types are supported: • 1 SQL_CHAR

• 2 SQL_NUMERIC

• 3 SQL_DECIMAL

• 4 SQL_INTEGER

• 5 SQL_SMALLINT

• 6 SQL_FLOAT

• 7 SQL_REAL

• 8 SQL_DOUBLE

• 9 SQL_DATE

• 10 SQL_TIME

• 11 SQL_TIMESTAMP

• 12 SQL_VARCHAR

• 91 SQL_TYPE_DATE

• 92 SQL_TYPE_TIME

• 93 SQL_TYPE_TIMESTAMP

• -1 SQL_LONGVARCHAR

• -5 SQL_BIGINT

• -6 SQL_TINYINT

SrcData string/integer The actual data from the source database. SrcLabel string If an "Int" type value maps to a reference table, this string value represents the label from the source database. DestFldId integer If mapped, this value represents the destination (SBM) field ID. Shell.SourceDb() Variant& containing AppDB object. The source database object. Provides database I/O functionality. See AppDb [page 142].

SBM ModScript Reference Guide 55 Chapter 3: Programming SBM ModScript

HTTP Request Header Shell Properties

HTTP Request Header shell properties are optional. If a header is not found, the value is empty.

Shell.ContentType() Variant& containing string (read-only). A list of the MIME types supported by the requesting user agent. Shell.HTTPAuthorization() Variant& containing string (read-only). Contains SBM authentication information for the current request. This information is available only if your system uses basic authentication. Shell.HTTPCookie() Variant& containing string (read-only). Contains SBM cookie information for the current request. Cookies are returned in a semicolon-separated list in the form "Name=Value" or "Cookie Name=Value." For details in setting cookies using SBM ModScript, refer to Ext.SetCookie() [page 90]. Shell.HTTPUserAgent() Variant& containing string (read-only). Contains information about the user agent, including the name and version number. Shell.Referer() Variant& containing string (read-only). The URL of the referring document. Shell.RemoteAddr() Variant& containing string (read-only). The Internet Protocol (IP) address of the requesting machine. Shell.RemoteUser() Variant& containing string (read-only). The network ID of the user making the request if the user has been authenticated. This information is only available if the user has been authenticated through NT Challenge/Response or a similar authentication method. Shell.RequestMethod() Variant& containing string (read-only). The HTTP request method. Shell.ServerSoftware() Variant& containing string (read-only). The name and software version of the Web server. Shell.ServerProtocol() Variant& containing string (read-only). The name and version of the protocol the request uses in the form protocol/majorVersion/.minorVersion. For example, HTTP/1.1 may be returned.

56 Solutions Business Manager (SBM) LastErrorMessage Shell Properties

LastErrorMessage shell property accessors provide a central, single text value to help identify "what went wrong" in certain functions. This is a mechanism to get an error message back to the script for complex actions like running transitions or REST calls.

SetLastErrorMessage( value ) value (input). Example:

Shell.SetLastErrorMessage("Some error message");

GetLastErrorMessage() string (output). Example:

var errMsg = Shell.GetLastErrorMessage(); if ( !myRec.StartTransition( 7 ) ) { Ext.WriteStream( "Error occurred starting transition: " &&& Shell.GetLastErrorMessage() ); }

ClearLastErrorMessage() Example:

Shell.ClearLastErrorMessage();

PostData Shell Properties

The PostData Shell property is available if the script is accessed via "ScriptPage" (URL Direct Access Context), and if the Content Type passed to the URL is "application/json", and if the HTTP call is a POST. The included POST data will be available via PostData.

Shell.PostData() Variant& containing string (read-only). The POST data from the HTTP call. You can use an HTTP POST to send JSON data to your script in the URL Direct Access Context. The POST body of the HTTP message is added as a string-Variant to the shell object with Shell.PostData() to provide the body. First, note the following requirements: • To protect from data overflow, this is limited to HTTP requests with a body of size X, where X is controlled by an entry in the TS_SYSTEMSETTINGS table named "ScriptPostDataMax" (otherwise, the default value is 10485760 bytes). If this value is not present in TS_SYSTEMSETTINGS, you can add it manually by following the steps described here.

• The request must be a POST (not a PUT, etc.)

SBM ModScript Reference Guide 57 Chapter 3: Programming SBM ModScript

• The HTTP header for the request must have a "Content-Type" of "application/json".

SBM ModScript has from_json(), which will convert the string from JSON to int and string values, with JSON object becoming a Map and JSON array becoming a Vector. As there is no implicit conversion from Variant to string, and since the values on the Shell are Variant, the Variant must be explicitly converted to string while being passed to from_json(). For example:

var y = from_json( Shell.PostData().to_string() );

An example of using the parsed values after calling from_json() is available in Sample Five: RESTDataSource [page 374].

Registration Shell Properties

Registration shell property accessors are defined when registering a new user.

Shell.LoginId() Variant& containing string (read-only). The user's login ID. Shell.Password() Variant& containing string (read-only). The user's password. Shell.RegistrationMethod() Variant& containing string (read-only). Indicates the registration method in use. Possible values are manual and automatic and correspond to options available on the External User tab of the Settings dialog box in SBM System Administrator. Shell.Contact() Variant& containing VarRecord object. A Contact record representing the new user. Changes made to this object are stored in the database after the script exits. See VarRecord [page 326].

Rerun Shell Properties

Rerun shell property accessors are defined for Pre-Transition scripts.

Shell.Rerun() Variant& containing bool (read-only). This flag is true if SBM re-runs the script because a form is invalid. For example, a form may be rejected when a user provides invalid data or does not provide a value for a required field. When the form re-opens for the user to provide valid data, the script can be re-run if the Re-run Pre-transition Script if Form Is Invalid option is enabled for the transition where the script is defined.

Retry Shell Properties

Retry shell property accessors are defined when an operation can be retried or rejected. Retry shell properties are available for Post-Transition, Pre-State, Post-State, Notification and Self-Registration contexts.

58 Solutions Business Manager (SBM) Shell.RedoMessage() Variant& containing string (editable). If the script writes a non-empty string to this property, the current operation is rejected and may be retried. Form-based operations are rejected similarly to when required fields are missing. The user is redirected to the same form (still maintaining any data they entered) and has another chance to submit the form. The string in Shell.RedoMessage() is used as an error message, appearing at the top of the form and in the Windows Event Viewer. If the script does not write to Shell.RedoMessage(), the form is processed normally. If an API program submits or transitions an item and a script associated with the transition fails, Shell.RedoMessage() is returned to the API and is available in the GetErrorMessage call. The message is also logged in the Windows Event Viewer as well. However, since there is no interface, the message is not displayed to the user and the user may not have an opportunity to fix the problem. Non-form operations, such as notifications, use Shell.RedoMessage() as a failure message and may offer some other retry mechanism. For example, when a notification calls a script that writes to Shell.RedoMessage(), the message indicates a failure and causes the notification to be retried (according to optional retry settings). Note: If a script rejects a Copy, Post Item, or Create Subtask transition by writing a non-empty string to Shell.RedoMessage(), a new item is not created by the transition process.

RunModScript (SOAP) Shell Properties

RunModScript (SOAP) Shell properties available when calling the RunModScript Web service.

Shell.Outputs() Vector&. Used to provide output data to the Web service caller. Each entry must be a Pair object representing a name-value pair. Shell.Params() Variant& containing Dictionary (read-only). Provides values sent in the SOAP body as "data" entries in the "inputs" element.

Runtime Parameter Shell Properties

Runtime Parameter shell property accessors are defined when optional params are passed to URL or HTML template context.

Shell.Params() Variant& containing Dictionary object (read-only). This is a Dictionary of name/value string pairs containing runtime parameters. These parameters typically come from HTML templates or from URL strings. For example, when accessing the following URL:

http://server/workcenter/tmtrack.dll?ScriptPage&scriptName=myScript&x=10

SBM ModScript Reference Guide 59 Chapter 3: Programming SBM ModScript

...Shell.Params() contains one item whose key is "x" and value is "10" (as a string). All parameter names are stored in lower case. For example, "x=10" becomes the key "x" with the value "10".

Transition Shell Properties

Transition shell property accessors are defined when there is a current transition.

Shell.TransitionName() Variant& containing string (read-only). The name of the current transition. Shell.TransitionId() Variant& containing int (read-only). The TS_ID of the current transition. For details on the TS_ID, refer to Identifying Records by TS_ID and Table ID [page 37]. Shell.TransitionType() Variant& containing string (read-only). Identifies the type of the current transition. Possible values are: Regular, Copy, Update, Delete, Post Item, Create Subtask, Publish Problem, and Post to External Database. Shell.FromStateName() Variant& containing string (read-only). The name of the state from which the transition begins. Shell.FromStateId() Variant& containing int (read-only). The TS_ID of the state from which the transition begins. For details on the TS_ID, refer to Identifying Records by TS_ID and Table ID [page 37]. Shell.ToStateName() Variant& containing string (inread-onlyput). The name of the state to which the item is transitioned. Shell.ToStateId() Variant& containing int (read-only). The TS_ID of the state to which the transition travels. For details on the TS_ID, refer to Identifying Records by TS_ID and Table ID [page 37]. Shell.MassTransPreForm() Variant& containing bool (read-only). Detects if a pre-transition script is running while the mass transition form is being initiated.

URL Shell Properties

URL property accessors are defined when there is a current URL.

Shell.Params() Variant& containing Dictionary (read-only). Provides values sent in the URL as name-value pairs.

60 Solutions Business Manager (SBM) Shell.URLProtocol() Variant& containing string (read-only). Returns http or https. Shell.URLServer() Variant& containing string (read-only). Returns the server name for the current URL. Shell.URLPort() Variant& containing string (read-only). Returns the TCP/IP port for the current URL (often omitted, defaults to 80). Shell.URLPath() Variant& containing string (read-only). Returns /tmtrack/tmtrack.dll. Shell.URLQuery() Variant& containing string (read-only). Returns ScriptPage&ScriptName=myScript.

User Shell Properties

User shell property accessors are defined when there is a current user.

Shell.User() Variant& containing User object. The "current user" for the script and is always the logged-in user, except when used with the Notification context. In the Notification context, the script is executed once per subscriber, with Shell.User() referring to the subscriber being processed. If there are no subscribers, the script is executed one time with Shell.User() equal to the value Nothing. See User [page 318]. Shell.UserToken() string (read-only). Returns the user's SSO token in Base64-encoded format. Example:

var token = Shell.UserToken();

Shell.IsActingAsAnotherUser() bool (read-only). Returns true if the user is currently being impersonated. Example:

var impersonated = Shell.IsActingAsAnotherUser();

Shell.ActingAsAnotherUserID() int (read-only). If the shell context has a User property, and if the user is being impersonated, this returns the actual user's ID. Example:

var actualId = Shell.ActingAsAnotherUserID();

SBM ModScript Reference Guide 61 Chapter 3: Programming SBM ModScript

Shell.NamespacePrefix() string (read-only). Returns the namespace table prefixes for the user (this prefix is added to the dbname of every primary and auxiliary table when a process app is deployed to a namespace). Shell.NamespaceID() int (read-only). Returns the user's namespace ID. Extension Functions "Ext" is another SBM application object containing extensions to ChaiScript's built-in functions. These functions provide features or conversions not available in core ChaiScript. "Ext" contains merely functions, not data. For example, the extension function Ext.AcquireLock() provides a resource lock for multiple threads running a script at the same time. The following "Ext" functions are available with SBM ModScript. • Ext.AcquireLock() [page 63]

• Ext.AppendTextFile() [page 64]

• Ext.CmdLineWait() [page 65]

• Ext.CreateAppRecord() [page 66]

• Ext.CreateAppRecordList() [page 67]

• Ext.CreateProjectBasedRecord() [page 68]

• Ext.CreateVarRecord() [page 69]

• Ext.DateToDbLong() [page 69]

• Ext.DbLongToDate() [page 70]

• Ext.DirtyTableCache() [page 71]

• Ext.EncodeHTML() [page 72]

• Ext.EncodeJavaScript() [page 73]

• Ext.EncodeURL() [page 74]

• Ext.FileExists() [page 74]

• Ext.GetCharacterSet() [page 75]

• Ext.GetCompatibilityVersion() [page 76]

• Ext.HasLock() [page 77]

• Ext.IsStringValidUTF8() [page 77]

• Ext.LoadString() [page 78]

62 Solutions Business Manager (SBM) • Ext.LockIsAvailable() [page 79]

• Ext.LogErrorMsg() [page 80]

• Ext.LogInfoMsg() [page 81]

• Ext.LogWarningMsg() [page 81]

• Ext.NewTask() [page 82]

• Ext.NewTaskWait() [page 84]

• Ext.OutputStreamExists() [page 85]

• Ext.PrimaryTableId() [page 86]

• Ext.ReadTextFile() [page 86]

• Ext.ReleaseLock() [page 87]

• Ext.SetCompatibilityVersion() [page 88]

• Ext.SetContentType() [page 89]

• Ext.SetCookie() [page 90]

• Ext.SetCookieExists() [page 91]

• Ext.ShellHasProp() [page 91]

• Ext.Sleep() [page 92]

• Ext.SolutionIdForPrefix() [page 93]

• Ext.SolutionIdForTable() [page 94]

• Ext.TableDatabaseName() [page 94]

• Ext.TableDisplayName() [page 95]

• Ext.TableId() [page 96]

• Ext.TableSingularName() [page 98]

• Ext.TeamTrackDLLName() [page 98]

• Ext.UnencodeURL() [page 99]

• Ext.WriteStream() [page 100]

• Ext.WriteTextFile() [page 101] Ext.AcquireLock()

(SBM On-Premise/PaaS only) A mutex-locking function called by a concurrent script when it needs to use a shared resource that should only be accessed by one script at a time.

SBM ModScript Reference Guide 63 Chapter 3: Programming SBM ModScript

Function Signature

bool Ext.AcquireLock( [msTimeout] )

Parameters

Parameter Type Description

msTimeout int Optional. The number of milliseconds to wait for the lock to be available. Defaults to an infinite wait. While the script is waiting, its execution is frozen. This may cause performance problems for long scripts or scripts that occur repeatedly. The wait occurs until other scripts have released the lock. All scripts share the same mutex.

Return

Type Description

bool Returns true if a lock was acquired successfully. Returns false if the time-out period passed. If false, the script should not execute sensitive operations because another concurrent script has the lock.

Technical Details SBM ModScript version: 11.3. Notes For example, if a script needs to read a serial number from a file, increment the number, and write it back, the script should call this function before accessing the file. When the script is done with the serial number file, it should call Ext.ReleaseLock() [page 87] to allow other scripts access once again. If all scripts using this file call these locking functions before and after use, then the file is never accessed by more than one script at a time. In this example, the serial numbers read and written by concurrent scripts are guaranteed valid for a single Web server configuration. Note that SBM automatically releases the lock when the script finishes execution. To determine if a lock is available, refer to Ext.LockIsAvailable() [page 79]. Related Topics Extension Functions [page 62] Ext.AppendTextFile()

(SBM On-Premise only) Writes the string contents to the file referred to by string fileName, appending to the file's previous contents.

64 Solutions Business Manager (SBM) Function Signature

Variant Ext.AppendTextFile( fileName, contents )

Parameters

Parameter Type Description

fileName string Specifies a fully-qualified path and file name. The fileName can be any valid file path, including a path to a network device. Note: This function may fail due to permissions settings. Verify that accounts that will execute the script have permission to write to the destination file.

contents Variant The value to be appended to the file contents.

Return

Type Description

Variant Returns the parameter "contents".

Technical Details SBM ModScript version: 11.3. Notes The file is opened, written, and closed; if it doesn't exist, it is created first. Concurrent scripts cannot access the file for reading or writing until this write operation finishes. To overwrite a file's contents rather than appending them, refer to Ext.WriteTextFile() [page 101]. Related Topics Extension Functions [page 62] Ext.CmdLineWait()

(SBM On-Premise only) Executes the string cmdLine in the operating system's command line interpreter and waits for the command to finish.

Function Signature

int Ext.CmdLineWait( cmdLine )

SBM ModScript Reference Guide 65 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

cmdLine string This argument can contain redirect symbols, pipe characters, wildcards, and anything else legal at a command line prompt. The Operating System account that is executing the script on the server requires privilege to perform any command is invoked.

Return

Type Description

int The command line interpreter's return value, which is the exit code of the program or batch file called.

Technical Details SBM ModScript version: 11.3. Notes For the return value, a program that does not generate a runtime error and does not call the "exit" statement has an exit code of zero. A batch file has an exit code of zero if its last executing line is not a runtime error or an "exit" statement. If a runtime error occurs in a program or batch file, the exit code is an OS error number, usually a large negative number. If an "exit" statement executes, its numeric parameter is the exit code. When a batch file uses the DOS "exit" statement with the "/B" option, the "exit" parameter is ignored, and the exit code is zero. Note: The "return" statement offered in C/C++ (and other programming languages) is not the same thing as the "exit" statement, and its parameter value has no effect on the exit code. When searching for applications or batch files, the ScriptAppPath registry setting is not used, but the OS %Path% variable is. Refer also to Ext.NewTask() [page 82] and Ext.NewTaskWait() [page 84]. Related Topics Extension Functions [page 62] Ext.CreateAppRecord()

Creates a new AppRecord object of a subtype appropriate for the database table specified by tableId.

Function Signature

AppRecord Ext.CreateAppRecord( tableId [, fieldType] )

66 Solutions Business Manager (SBM) Parameters

Parameter Type Description

tableId int A value from TS_TABLES. See Ext.TableId() [page 96].

fieldType int Optional. When creating field objects, specifies the data type to be stored in the field. See FieldTypeConstants [page 350].

Return

Type Description

AppRecord The newly-created AppRecord object.

Technical Details SBM ModScript version: 11.3. Notes When a primary table is specified, the new object is a ProjectBasedRecord. When an auxiliary table is specified, a VarRecord is created. For other tables, an AppRecord subtype is created if one exists in SBM ModScript (for example, a Change object for the TS_CHANGES table). Otherwise, a generic AppRecord object is created. When the table that is specified is not primary or auxiliary, the AppRecord that is created will have a schema related to that table. This means AppRecord.GetFieldValue() will work if the specfied field is from that table's schema. Use AppRecord.GetSchemaColumns() to list the columns in the schema for the AppRecord. Related Topics Extension Functions [page 62] Ext.CreateAppRecordList()

Creates list objects that can hold multiple items from the given table.

Function Signature

AppRecordList Ext.CreateAppRecordList( tableId )

Parameters

Parameter Type Description

tableId int A value from TS_TABLES. See Ext.TableId() [page 96].

SBM ModScript Reference Guide 67 Chapter 3: Programming SBM ModScript

Return

Type Description

AppRecordList The newly created AppRecordList object. Objects on the list are of type AppRecord, though they may represent objects of any AppRecord subtype.

Technical Details SBM ModScript version: 11.3. Notes This function is analogous to Ext.CreateAppRecord() [page 66]. Related Topics Extension Functions [page 62] AppRecordList [page 187] Ext.CreateProjectBasedRecord()

Returns objects that are of the subtype ProjectBasedRecord.

Function Signature

ProjectBasedRecord Ext.CreateProjectBasedRecord( tableId )

Parameters

Parameter Type Description

tableId int A value from TS_TABLES. See Ext.TableId() [page 96].

Return

Type Description

ProjectBasedRecord The newly-created ProjectBasedRecord object containing a field list with all variable fields defined for the given table. The fields are created empty and can be written to individually or populated for a specific item using the Read() method. The returned object supports all functionality for a primary table item.

Technical Details SBM ModScript version: 11.3.

68 Solutions Business Manager (SBM) Notes This function is similar to Ext.CreateAppRecord() [page 66]. It may only be used on primary tables—a runtime error occurs if this function is called on a non-primary table. Related Topics Extension Functions [page 62] ProjectBasedRecord [page 252] Ext.CreateVarRecord()

Returns objects of the subtype VarRecord.

Function Signature

VarRecord Ext.CreateVarRecord( tableId )

Parameters

Parameter Type Description

tableId int A value from TS_TABLES. See Ext.TableId() [page 96].

Return

Type Description

VarRecord The newly-created VarRecord object containing a field list with all variable fields defined for the given table. The fields are created empty and can be written to individually or populated for a specific item using the Read() method.

Technical Details SBM ModScript version: 11.3. Notes This function is similar to Ext.CreateAppRecord() [page 66]. It may only be used on tables that hold variable field objects—a runtime error occurs if this function is called on a non- primary/auxiliary table. Related Topics Extension Functions [page 62] Ext.DateToDbLong()

Converts the variant date value date to the int format used in an SBM database.

SBM ModScript Reference Guide 69 Chapter 3: Programming SBM ModScript

Function Signature

Variant Ext.DateToDbLong( Variant date )

Parameters

Parameter Type Description

date Variant Use this parameter to convert the variant date value to the number of seconds since midnight, Jan. 1, 1970. This is not the same as converting date to an int using other built-in operators; that conversion yields the number of days since midnight Dec. 31, 1899. Important: See also Ext.SetCompatibilityVersion() [page 88].

Return

Type Description

Variant Returns the int date value.

Technical Details SBM ModScript version: 11.3. Notes Use TimeT or TimeMillis as the preferred way to interact with dates. Related Topics Extension Functions [page 62] Ext.DbLongToDate()

Converts the int value to the variant date value format used in an SBM database.

Function Signature

Variant Ext.DbLongToDate( dateInt )

70 Solutions Business Manager (SBM) Parameters

Parameter Type Description

dateInt int Use this argument to convert the int date value from the number of seconds since midnight, Jan. 1, 1970 to a Variant storing a date. This is not the same as converting dateInt to a Date using other built-in operators; that conversion interprets dateInt as the number of days since midnight Dec. 31, 1899. Important: See also Ext.SetCompatibilityVersion() [page 88].

Return

Type Description

Variant The variant date value.

Technical Details SBM ModScript version: 11.3. Notes Use TimeT or TimeMillis as the preferred way to interact with dates. Related Topics Extension Functions [page 62] Ext.DirtyTableCache()

Clears Application Engine cache for a specified table

Function Signature

bool Ext.DirtyTableCache( tableId )

Parameters

Parameter Type Description

tableId int A value from TS_TABLES. See Ext.TableId() [page 96].

SBM ModScript Reference Guide 71 Chapter 3: Programming SBM ModScript

Return

Type Description

bool Returns true if the table was cached. Throws an exception if the table does not exist.

Technical Details SBM ModScript version: 11.6.1. Notes Occasionally, SBM ModScript might be part of an extended series of operations, such as orchestrations, triggered transitions, etc. If one of those actions changes one of the cached tables, and this script needs to see that data, you can use Ext.DirtyTableCache() to ensure that the Application Engine cache is clean. Use the following SQL to identify tables that Application Engine caches (if TS_CACHESTATUS=1, the table is cached by Application Engine):

select TS_ID,TS_NAME,TS_DBNAME,TS_CACHESTATUS from TS_TABLES

Related Topics Extension Functions [page 62] Ext.EncodeHTML()

Escapes HTML values in a string.

Function Signature

string Ext.EncodeHTML( value )

Parameters

Parameter Type Description

value string The text that may have HTML characters that need to be escaped.

Return

Type Description

string The HTML-encoded version of the string value.

72 Solutions Business Manager (SBM) Technical Details SBM ModScript version: 11.3. Example

Ext.WriteStream( Ext.EncodeHTML( "a < b" ));

Notes None. Related Topics Extension Functions [page 62] Ext.EncodeJavaScript()

Escapes JavaScript values in a string.

Function Signature

string Ext.EncodeJavaScript( value )

Parameters

Parameter Type Description

value string The text that may have JavaScript characters that need to be escaped.

Return

Type Description

string The JavaScript-encoded version of the string value.

Technical Details SBM ModScript version: 11.3. Example

Ext.WriteStream( Ext.EncodeJavaScript( "a < b" ));

Notes None.

SBM ModScript Reference Guide 73 Chapter 3: Programming SBM ModScript

Related Topics Extension Functions [page 62] Ext.EncodeURL()

Escapes special character values in a URL string.

Function Signature

string Ext.EncodeURL( urlString )

Parameters

Parameter Type Description

urlString string The text that may have characters that need to be escaped.

Return

Type Description

string The URL-encoded version of the string urlString.

Technical Details SBM ModScript version: 11.3. Notes For example, & is converted to %26. To convert hex-encoded sequences to ASCII equivalents, use Ext.UnencodeURL() [page 99]. Related Topics Extension Functions [page 62] Ext.FileExists()

(SBM On-Premise only) Determines whether the file specified in fileName exists.

Function Signature

bool Ext.FileExists( fileName )

74 Solutions Business Manager (SBM) Parameters

Parameter Type Description

fileName string Use the fileName parameter to provide a fully-qualified path and file name. The fileName can be any valid file path, including a path to a network device. Note: This function may fail due to permissions settings. Verify that accounts that will execute the script have permission to read the destination folder.

Return

Type Description

bool Returns true if the file exists; false otherwise.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Extension Functions [page 62] Ext.GetCharacterSet()

(Deprecated—always returns "UTF-8")

Function Signature

string Ext.GetCharacterSet()

Parameters

Parameter Type Description

None

SBM ModScript Reference Guide 75 Chapter 3: Programming SBM ModScript

Return

Type Description

string "UTF-8"

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Extension Functions [page 62] Ext.GetCompatibilityVersion()

Gets the compatibility version. Refer to Ext.SetCompatibilityVersion().

Function Signature

string Ext.GetCompatibilityVersion()

Parameters

Parameter Type Description

None

Return

Type Description

string A string in the form majorVersion.minorVersion (for example, "11.3").

Technical Details SBM ModScript version: 11.3. Notes If the version is not set using Ext.SetCompatibilityVersion() or ConvertedFromAppScript(), the return value is 11.3. For details about the compatibility version, see Ext.SetCompatibilityVersion() [page 88].

76 Solutions Business Manager (SBM) Related Topics Extension Functions [page 62] Ext.SetCompatibilityVersion() [page 88] Ext.HasLock()

(SBM On-Premise/PaaS only) Determines if the current script has a mutex lock.

Function Signature

bool Ext.HasLock()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if the current script has a lock; otherwise, false.

Technical Details SBM ModScript version: 11.3. Notes For details on acquiring script locks, refer to Ext.AcquireLock() [page 63]. For details on releasing locks, refer to Ext.ReleaseLock() [page 87]. Related Topics Extension Functions [page 62] Ext.IsStringValidUTF8()

Returns true if string contents are valid UTF8.

Function Signature

bool Ext.IsStringValidUTF8( string s )

SBM ModScript Reference Guide 77 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

s string Use this parameter to provide a string to evaluate.

Return

Type Description

bool Returns true if the contents are valid UTF8. Example:

var encoded = Ext.IsStringValidUTF8(utf8String);

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Extension Functions [page 62] Ext.LoadString()

If your SBM user interface uses multiple languages, this function returns the specified string ID in the language specified by each user.

Function Signature

string Ext.LoadString( stringId [, arg0-5 ] )

Parameters

Parameter Type Description

stringId string Use this parameter to specify a record in the String Identifiers table. For example, Ext.LoadString( "IDS_REPORTS_MYREPORTS" ) returns the string associated with the My Reports text in the browser interface.

78 Solutions Business Manager (SBM) Parameter Type Description

arg (up to 6) string Use up to six optional parameters, which can be a string identifier, in which case it will be loaded like stringId. Otherwise, the value will be treated as literal text, integer, double, etc. These values will be used to format a string using the text loaded from stringId as the format, with entries like {0} that correspond to arg0 etc.

Return

Type Description

string Returns the translated string associated with the stringId.

Technical Details SBM ModScript version: 11.3. Notes For example, if your system provides English and German, the Ext.LoadString( stringId ) function returns strings such as error messages in each user's specified language. This function does not interact the SLS; therefore the strings that are available will be limited to the values in TS_STRINGIDENTIFIERS. Related Topics Extension Functions [page 62] Ext.LockIsAvailable()

(SBM On-Premise/PaaS only) Determines if the mutex lock is available to be acquired.

Function Signature

bool Ext.LockIsAvailable( )

Parameters

Parameter Type Description

None

SBM ModScript Reference Guide 79 Chapter 3: Programming SBM ModScript

Return

Type Description

bool Returns true if a concurrent script lock is available to be acquired. Returns false if the concurrent script lock is not available to be acquired.

Technical Details SBM ModScript version: 11.3. Notes For details on acquiring script locks, refer to Ext.AcquireLock() [page 63]. For details on releasing locks, refer to Ext.ReleaseLock() [page 87]. Note: Ext.LockIsAvailable() is now deprecated because it returns inaccurate results, but is included for compatibility with scripts converted from SBM AppScript. Related Topics Extension Functions [page 62] Ext.LogErrorMsg()

Writes an error message to the Application Event Log.

Function Signature

void Ext.LogErrorMsg( msg )

Parameters

Parameter Type Description

msg Variant Use this parameter to provide an error message that appears in the Windows Event Viewer.

Return

Type Description

None

Technical Details SBM ModScript version: 11.3.

80 Solutions Business Manager (SBM) Notes This differs from the Ext.LogInfoMsg() [page 81] and Ext.LogWarningMsg() [page 81] functions only in that it is labeled "Error" in the Event Viewer. Related Topics Extension Functions [page 62] Ext.LogInfoMsg()

Writes an info message to the Application Event Log.

Function Signature

void Ext.LogInfoMsg( msg )

Parameters

Parameter Type Description

msg Variant Use this argument to provide an info message that appears in the Windows Event Viewer.

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Notes This differs from the Ext.LogErrorMsg() [page 80] and Ext.LogWarningMsg() [page 81] functions only in that it is labeled "Information" in the Event Viewer. Related Topics Extension Functions [page 62] Ext.LogWarningMsg()

Writes a warning message to the Application Event Log.

Function Signature

void Ext.LogWarningMsg( msg )

SBM ModScript Reference Guide 81 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

msg Variant Use this argument to provide a warning message that appears in the Windows Event Viewer.

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Notes This differs from the Ext.LogErrorMsg() [page 80] and Ext.LogInfoMsg() [page 81] functions only in that it is labeled "Warning" in the Event Viewer. Related Topics Extension Functions [page 62] Ext.NewTask()

(SBM On-Premise only) Executes an external application as a new process, passing any given arguments.

Function Signature

int Ext.NewTask( appName, [ arg1-6 ] )

int Ext.NewTask( appName, Vector args )

82 Solutions Business Manager (SBM) Parameters

Parameter Type Description

appName string The appName can be any external application. • If appName does not contain a path component, it is searched for in the path list given by the optional SBM registry setting "ScriptAppPath." If not found, appName is then searched for in the path list given by the operating system's environment variable "Path." ScriptAppPath conforms to the same syntax as Path.

• Folder paths are separated by semicolons, environment variables are surrounded by '%' characters, and spaces do not need to be escaped or quoted.

• Unlike Path, any quotes in ScriptAppPath are interpreted literally as part of the folder name.

• If appName does not contain a file extension, the system tries .COM, .EXE, .BAT, and then .CMD. Arguments following appName are optional.

For details on using ScriptAppPath, refer to Setting Script Application Paths [page 40].

arg (up to 6) Variant Optional. Between 0-6 parameters to pass to the command. For more than 6 parameters, use the Vector signature.

args Vector Parameters to pass to the command.

Return

Type Description

int Returns the operating system handle of the new process. This handle is useless within SBM ModScript, but occasionally a script may have some reason to pass the handle to another program. The application's exit code is unavailable because this function generally returns before the application exits.

Technical Details SBM ModScript version: 11.3. Notes The new process runs concurrently; the script does not wait for it to exit.

SBM ModScript Reference Guide 83 Chapter 3: Programming SBM ModScript

Related Topics Extension Functions [page 62] Ext.NewTaskWait()

(SBM On-Premise only) Executes an external application, passing any given arguments and awaiting the results.

Function Signature

int Ext.NewTaskWait( appName, [ arg1-6 ] )

int Ext.NewTaskWait( appName, Vector args )

Parameters

Parameter Type Description

appName The appName can be any external application. • If appName does not contain a path component, it is searched for in the path list given by the optional SBM registry setting "ScriptAppPath." If not found, appName is then searched for in the path list given by the operating system's environment variable "Path." ScriptAppPath conforms to the same syntax as Path.

• Folder paths are separated by semicolons, environment variables are surrounded by '%' characters, and spaces do not need to be escaped or quoted.

• Unlike Path, any quotes in ScriptAppPath are interpreted literally as part of the folder name.

• If appName does not contain a file extension, the system tries .COM, .EXE, .BAT, and then .CMD. Arguments following appName are optional.

For details on using ScriptAppPath, refer to Setting Script Application Paths [page 40].

arg (up to 6) Variant Optional. Between 0-6 parameters to pass to the command. For more than 6 parameters, use the Vector signature.

args Vector Parameters to pass to the command.

84 Solutions Business Manager (SBM) Return

Type Description

int Returns the application's exit code. For details about exit codes, refer to Ext.CmdLineWait() [page 65].

Technical Details SBM ModScript version: 11.3. Notes While the script is waiting, its execution is frozen. This may cause performance problems for long scripts or scripts that occur repeatedly. Related Topics Extension Functions [page 62] Ext.OutputStreamExists()

Checks if an output stream exists, such as an HTTP connection to the user's browser. If so, scripts can write to it.

Function Signature

bool Ext.OutputStreamExists()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if the output stream exists; false otherwise.

Technical Details SBM ModScript version: 11.3. Notes For details, refer to Ext.WriteStream() [page 100].

SBM ModScript Reference Guide 85 Chapter 3: Programming SBM ModScript

Related Topics Extension Functions [page 62] Ext.PrimaryTableId()

Provides the TS_ID of a primary table for a specific application.

Function Signature

int Ext.PrimaryTableId( applicationPrefixOrId )

Parameters

Parameter Type Description

applicationPrefixOrId Variant If applicationPrefixOrID is a non-numeric string, it is taken as the application's prefix, such as TTT. Because application prefixes do not need to be unique, the first table with the prefix encountered is returned. If applicationPrefixOrID is numeric, it is taken as the application's TS_ID.

Return

Type Description

int Returns the TS_ID of the primary table for the specified application.

Technical Details SBM ModScript version: 11.3. Notes For details on the TS_ID, refer to Identifying Records by TS_ID and Table ID [page 37]. For details on getting a table ID using its database name, refer to Ext.TableId() [page 96]. Related Topics Extension Functions [page 62] Ext.ReadTextFile()

(SBM On-Premise only) Opens, reads, and closes a file.

Function Signature

string Ext.ReadTextFile( fileName )

86 Solutions Business Manager (SBM) Parameters

Parameter Type Description

fileName string Specifies a fully-qualified path and file name. The fileName can be any valid file path, including a path to a network device. Note: This function may fail due to permissions settings. Verify that accounts that will execute the script have permission to read the destination file.

Return

Type Description

string Returns string holding entire contents of file referred to by fileName.

Technical Details SBM ModScript version: 11.3. Notes Concurrent scripts can read the same file simultaneously. Important: This function assumes that the file is encoded in UTF-8.

Related Topics Extension Functions [page 62] Ext.ReleaseLock()

(SBM On-Premise/PaaS only) Releases a mutex-lock acquired by the current script.

Function Signature

bool Ext.ReleaseLock()

Parameters

Parameter Type Description

None

SBM ModScript Reference Guide 87 Chapter 3: Programming SBM ModScript

Return

Type Description

bool Returns true if the lock was released successfully. Returns false if the lock was not released.

Technical Details SBM ModScript version: 11.3. Notes Every call to Ext.AcquireLock() must eventually be followed by a call to Ext.ReleaseLock(). Statements between these two calls are executed by at most one concurrent script at a time. If a script terminates without releasing an acquired lock, the SBM ModScript system automatically releases it so concurrent scripts do not halt indefinitely. For details on acquiring locks, refer to Ext.AcquireLock() [page 63]. For details on determining if a concurrent script is available to be acquired, refer to Ext.LockIsAvailable() [page 79]. Related Topics Extension Functions [page 62] Ext.SetCompatibilityVersion()

Controls how Variants interact with dates.

Function Signature

bool Ext.SetCompatibilityVersion( majorVersion [, minorVersion] )

Parameters

Parameter Type Description

majorVersion int This is the major version number for the version of SBM with which you want the script to be compatible.

CAUTION: Do not use a version number containing a period as an argument (for example, 11.4)). SBM ModScript interprets a single argument as a major version number with a default minor version of 0, throwing away the period and everything after it.

minorVersion int Optional; 0 by default. This is the minor version number for the version of SBM with which you want your script to be compatible.

88 Solutions Business Manager (SBM) Return

Type Description

bool Returns true.

Technical Details SBM ModScript version: 11.3. Notes The SBM ModScript default compatibility version is 11.3. Scripts converted from SBM AppScript using the conversion utility will invoke ConvertedFromAppScript(), which will set the compatibility value to 0.0 (which is the default for SBM AppScript). The script may proceed to invoke Ext.SetCompatibilityVersion() to change the value again. The compatibility version controls how Variant interacts with dates: • A value of 7.0 or higher will cause Variant to process date strings as ISO 8601 and store them as a double, which holds the number of days since Dec 30, 1899.

• A compatibility version less than 7.0 will cause Variant to process date strings using the system locale and store them as an integer number of seconds since Jan 1, 1970 (GMT).

Tip: The preferred option for interacting with dates is with either the TimeT [page 296] or TimeMillis [page 283] classes.

Related Topics Extension Functions [page 62] Ext.GetCompatibilityVersion() [page 76] SBM AppScript Conversion Functions [page 103] Ext.SetContentType()

Sets the content type HTTP header for the output from a URL Direct access.

Function Signature

void Ext.SetContentType( value )

Parameters

Parameter Type Description

value string The content-type value. ModScript always appends "; charset=UTF-8".

SBM ModScript Reference Guide 89 Chapter 3: Programming SBM ModScript

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Example

// set content type to "application/json; charset=UTF-8" Ext.SetContentType("application/json");

Notes Only used in the URL Direct context. Related Topics Extension Functions [page 62] Ext.SetCookie()

Allows SBM ModScript to set HTTP cookies.

Function Signature

bool Ext.SetCookie( sNameValue )

Parameters

Parameter Type Description

sNameValue string Use this parameter to add a cookie name that does not exist or update the value of a cookie name that exists.

Return

Type Description

bool Returns true if the cookie is successfully added or modified; false otherwise.

Technical Details SBM ModScript version: 11.3.

90 Solutions Business Manager (SBM) Notes Name-values are returned by Shell.HTTPCookie() in the form "Name=Value" or "CookieName=CookieValue." For details, refer to HTTP Request Header Shell Properties [page 56]. Related Topics Extension Functions [page 62] Ext.SetCookieExists()

Determines if cookies are available in the context.

Function Signature

bool Ext.SetCookieExists()

Parameters

Parameter Type Description

None

Return

Type Description

bool If true, SBM ModScript can set cookies; false otherwise.

Technical Details SBM ModScript version: 11.3. Notes For details, refer to Ext.SetCookie() [page 90]. Related Topics Extension Functions [page 62] Ext.ShellHasProp()

Determines if Shell has a specified property.

Function Signature

bool Ext.ShellHasProp( propName )

SBM ModScript Reference Guide 91 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

propName string The name of the property to check.

Return

Type Description

bool Returns true if the string is the name of an existing shell property; false otherwise.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Extension Functions [page 62] Ext.Sleep()

(SBM On-Premise/PaaS only) Freezes script execution and the thread that called the script for the specified number of milliseconds.

Function Signature

void Ext.Sleep( milliseconds )

Parameters

Parameter Type Description

milliseconds int Specifies the number of milliseconds for which a script execution should sleep.

Return

Type Description

None

92 Solutions Business Manager (SBM) Technical Details SBM ModScript version: 11.3. Notes After the delay has elapsed, execution continues normally. If milliseconds is zero or negative, the thread relinquishes the remainder of its current time slice and there is no additional delay. For long-running scripts, consider using this method to prevent resource starvation of other processes. Related Topics Extension Functions [page 62] Ext.SolutionIdForPrefix()

Provides the TS_ID of the specified prefix string.

Function Signature

int Ext.SolutionIdForPrefix( applicationPrefix )

Parameters

Parameter Type Description

applicationPrefix Specifies an application prefix string, such as "UBG". Because application prefixes do not need to be unique, the first table with the prefix encountered is returned.

Return

Type Description

int Returns the TS_ID of the first application encountered in the database with the specified prefix.

Technical Details SBM ModScript version: 11.3. Notes For details on the TS_ID, refer to Identifying Records by TS_ID and Table ID [page 37]. Related Topics Extension Functions [page 62]

SBM ModScript Reference Guide 93 Chapter 3: Programming SBM ModScript

Ext.SolutionIdForTable()

Provides the TS_ID of an application with the specified primary table.

Function Signature

int Ext.SolutionIdForTable( table )

Parameters

Parameter Type Description

table Variant Returns the TS_ID of the application with the specified primary table. If table is a non-numeric string, it is taken as the table's database name, such as "UBG_ISSUES". If it is numeric, it is taken as the table's TS_ID.

Return

Type Description

int Returns the TS_ID of the application. 0 if not found.

Technical Details SBM ModScript version: 11.3. Notes For details on the TS_ID, refer to Identifying Records by TS_ID and Table ID [page 37]. Related Topics Extension Functions [page 62] Ext.TableDatabaseName()

Returns the database name of the specified table.

Function Signature

string Ext.TableDatabaseName( table )

94 Solutions Business Manager (SBM) Parameters

Parameter Type Description

table Variant Specifies a table's display name in order to return the table's database name. If table is a non-numeric string, it is taken as the table's display name, such as "Issues". Otherwise, the parameter is converted to a number and taken as the table's ID. Use caution when using the display name because it can be changed in SBM Composer.

Return

Type Description

string Returns the database name of the table if the display name exists. If not, an empty string is returned.

Technical Details SBM ModScript version: 11.3. Notes This method can be used to return the database name of a table, which can be helpful when building SQL statements. Related Topics Extension Functions [page 62] Ext.TableDisplayName()

Returns the display name of the specified table.

Function Signature

string Ext.TableDisplayName( table )

Parameters

Parameter Type Description

table Specifies a tables's database name or TS_ID. If a non- numeric string, it is taken as the table's database name, such as "UBG_ISSUES". Otherwise, the parameter is converted to a number and taken as the table's ID.

SBM ModScript Reference Guide 95 Chapter 3: Programming SBM ModScript

Return

Type Description

string Returns the display name of the table if the database name exists. If not, an empty string is returned.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Extension Functions [page 62] Ext.TableDatabaseName() [page 94] Ext.TableId()

Returns the numeric ID of the specified table.

Function Signature

int Ext.TableId( tableName [, string nameType] )

Parameters

Parameter Type Description

tableName Variant Specifies a table display name or database name. If the optional nameType parameter is omitted or equals "database", the tableName parameter is taken as the table's database name, such as "UBG_ISSUES". If the nameType parameter equals "display", tableName is taken as the table's display name, such as "Issues". Use caution when using the display name because it can be changed in SBM Composer.

96 Solutions Business Manager (SBM) Parameter Type Description

nameType string Behavior depends on the value: • "database": (default) The tableName value is taken as the TS_TABLES.TS_DBNAME of the table.

• "display": The tableName value is taken as the TS_TABLES.TS_NAME of the table.

• "project": The tableName value is taken as the TS_ID, internal name, or UUID, of a project. If a matching project is found, the corresponding table ID is returned.

• "workflow": The tableName value is taken as the TS_ID, internal name, or UUID, of a workflow. If a matching workflow is found, the corresponding table ID is returned.

Return

Type Description

int Returns the numeric ID of the specified table. If the table does not exist, returns zero. Examples:

var myTableId = Ext.TableId( "APP_WORKFLOW", "workflow" ) );

var myTableId = Ext.TableId( 8, "workflow" ) );

var myTableId = Ext.TableId( "f4c6fa0d-5484-4dd3-b443-5363c4573a18", "project" ) );

Technical Details SBM ModScript version: 11.3. Notes The nameType can be "project" or "workflow", which will look for the project or workflow by ID, Internal Name, or UUID, and return the related table id. This is useful when you are submitting to a project, because this value can be passed to CreateProjectBasedRecord() to create an item for the table that the project is related to. Related Topics Extension Functions [page 62]

SBM ModScript Reference Guide 97 Chapter 3: Programming SBM ModScript

Ext.TableSingularName()

Returns the singular name of the specified table.

Function Signature

string Ext.TableSingularName( table )

Parameters

Parameter Type Description

table Variant Specifies a tables's database name or TS_ID. If a non- numeric string, it is taken as the table's database name, such as "UBG_ISSUES". Otherwise, the parameter is converted to a number and taken as the table's ID.

Return

Type Description

string Returns the singular name of the specified table. Returns an empty string if the specified table does not exist.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Extension Functions [page 62] Ext.TeamTrackDLLName()

Provides the name of the SBM DLL.

Function Signature

string Ext.TeamTrackDLLName()

98 Solutions Business Manager (SBM) Parameters

Parameter Type Description

None

Return

Type Description

string Returns "tmtrack.dll".

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Extension Functions [page 62] Ext.UnencodeURL()

Converts URL-encoded version of urlString from hex-encoded sequences.

Function Signature

string Ext.UnencodeURL( urlString )

Parameters

Parameter Type Description

urlString string Use this parameter to provide a string to unencode.

Return

Type Description

string The unencoded version of the string.

Technical Details SBM ModScript version: 11.3.

SBM ModScript Reference Guide 99 Chapter 3: Programming SBM ModScript

Notes For example, %26 becomes &. To convert a string to hex-encoded sequences, use Ext.EncodeURL() [page 74]. Related Topics Extension Functions [page 62] Ext.WriteStream()

Writes to the current output stream.

Function Signature

bool Ext.WriteStream( value )

Parameters

Parameter Type Description

value Variant The value should be properly encoded, depending on the context. For instance, if the context is pre-transition script, the output is the transition form; therefore, the value should be HTML or potentially JavaScript.

Return

Type Description

bool Returns true if the write operation succeeded; false otherwise.

Technical Details SBM ModScript version: 11.3. Notes If a user has executed a transition in a browser, then an output stream exists for the pre- transition script. However, if an external program initiates a transition using the SBM API, there is no browser connection and thus no output stream. For details, refer to Ext.OutputStreamExists() [page 85]. Related Topics Extension Functions [page 62]

100 Solutions Business Manager (SBM) Ext.WriteTextFile()

(SBM On-Premise only) Writes the string contents to the file referred to by string fileName, overwriting the file's previous contents.

Function Signature

Variant Ext.WriteTextFile( fileName, contents )

Parameters

Parameter Type Description

fileName string Specifies a fully-qualified path and file name. The fileName can be any valid file path, including a path to a network device. Note: This function may fail due to permissions settings. Verify that accounts that will execute the script have permission to write to the destination file.

contents Variant The value to be written to the file.

Return

Type Description

Variant Returns the string parameter "contents".

Technical Details SBM ModScript version: 11.3. Notes The file is opened, written, and closed; if it doesn't exist, it is created first. Concurrent scripts cannot access the file for reading or writing until this write operation finishes. To append to a file's contents rather than overwrite them, refer to Ext.AppendTextFile() [page 64]. Related Topics Extension Functions [page 62] Free Functions SBM ModScript includes the following free functions. • Concatenation Operator [page 102]

SBM ModScript Reference Guide 101 Chapter 3: Programming SBM ModScript

• SBM AppScript Conversion Functions [page 103]

• CreateObject() [page 107]

• CreateLocale() [page 108]

• CreateUserLocale() [page 109]

• CreateSystemLocale() [page 110]

• CreateTimeZone() [page 110]

• CreateUserTimeZone() [page 111]

• CreateUTCTimeZone() [page 112]

• ExitScript() [page 113]

• include() [page 113]

• Math Functions [page 114]

• ScriptEngineVersion() [page 117]

• TimeMillisDate() [page 118]

• TimeMillisNow() [page 119]

• TimeTDate() [page 120]

• TimeTNow() [page 121] Concatenation Operator

The &&& operator concatenates two values into a string.

Function Signature

string operator &&&( Variant v1 , Variant v2 )

string operator &&&( int v1 , Variant v2 )

string operator &&&( uint32_t v1 , Variant v2 )

string operator &&&( int64_t v1 , Variant v2 )

string operator &&&( uint64_t v1 , Variant v2 )

string operator &&&( double v1 , Variant v2 )

string operator &&&( string v1 , Variant v2 )

102 Solutions Business Manager (SBM) Parameters

Parameter Type Description

v1 Variant The first value to concatenate. int uint32_t int64_t uint64_t double string

v2 Variant The second value to concatenate.

Return

Type Description

string The result of the concatenated values.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Free Functions [page 101] SBM AppScript Conversion Functions

Functions for converting SBM AppScript to SBM ModScript.

Description These functions were added solely for the purpose of converting SBM AppScript and generally should not be used otherwise. See also SBM AppScript Conversion Constants [page 343]. Important: Because SBM AppScript was modeled after VBScript, the functions below model VBScript unless comments below indicate otherwise. Refer to the VBScript documentation for detail on the functions below.

SBM ModScript Reference Guide 103 Chapter 3: Programming SBM ModScript

Operators Tip: Operators listed below that are prefaced with vb are based on corresponding non-prefixed VBScript operators.

• Variant vbEQV( arg1 , arg2 )

• Variant vbIMP( arg1 , arg2 )

• bool is( arg1 , arg2 )

• Variant vbAND( arg1 , arg2 )

• Variant vbOR( arg1 , arg2 )

• Variant !vbNOT!( arg )

• Variant vbXOR( arg1 , arg2 )

Consider using SBM ModScript native operators such as &&, ||, &, |, and ! instead. Functions • Variant CreateObject( arg )

• Variant ScriptEngineCompat(): Invokes SBM AppScript ScriptEngine().

• Variant ScriptEngineMajorVersionCompat(): Invokes SBM AppScript ScriptEngineMajorVersion().

• Variant ScriptEngineMinorVersionCompat(): Invokes SBM AppScript ScriptEngineMinorVersion().

• Randomize()

• ConvertedFromAppScript( int arg1 , int arg2 ): Placed into converted scripts by the SBM AppScript conversion utility. Invokes Ext.SetCompatibilityVersion( 0, 0 ), which is the SBM AppScript default. For details, see Ext.SetCompatibilityVersion() [page 88].

Variant Type Checking Functions • Variant VarType( arg )

• Variant TypeName( arg )

• Variant IsArray( arg )

• Variant IsDate( arg )

• Variant IsEmpty( arg )

• Variant IsNull( arg )

• Variant IsNumeric( arg )

• Variant IsObject( arg )

104 Solutions Business Manager (SBM) Variant Type Conversion Functions • Variant CBool( arg )

• Variant CByte( arg )

• Variant CDate( arg )

• Variant CDbl( arg )

• Variant CInt( arg )

• Variant CLng( arg )

• Variant CSng( arg )

• Variant CStr( arg )

• Variant Hex( arg )

• Variant Oct( arg )

Variant Date Functions • Variant Date()

• Variant Now()

• Variant Time()

• Variant DateAdd( arg1 , arg2 , arg3 )

• Variant DateDiff( arg1 , arg2 , arg3 , [arg4,[arg5]] )

• Variant DatePart( arg1 , arg2 , [arg3,[arg4]] )

• Variant DateSerial( arg1 , arg2 , arg3 )

• Variant DateValue( arg )

• Variant FormatDateTime( arg1 , [arg2] )

• Variant Year( arg )

• Variant Month( arg )

• Variant Day( arg )

• Variant Hour( arg )

• Variant Minute( arg )

• Variant Second( arg )

• Variant Weekday( arg1 , [arg2] )

• Variant MonthName( arg1 , [arg2] )

SBM ModScript Reference Guide 105 Chapter 3: Programming SBM ModScript

• Variant WeekdayName( arg1 , [arg2,[arg3]] )

• Variant TimeSerial( arg1 , arg2 , arg3 )

• Variant TimeValue( arg )

It is recommended that you use the corresponding functions listed in TimeT [page 296], TimePoint [page 294], TimeMillis [page 283], and Locale [page 233]. Variant Math Functions • Variant Abs( arg )

• Variant Atn( arg )

• Variant Cos( arg )

• Variant Exp( arg )

• Variant Fix( arg )

• Variant Int( arg )

• Variant Log( arg )

• Variant Rnd( )

• Variant Sgn( arg )

• Variant Sin( arg )

• Variant Sqr( arg )

• Variant Tan( arg )

It is recommended that you use the corresponding functions listed in Math Functions [page 114]. Variant String Functions • Variant Asc( arg )

• Variant AscB( arg )

• Variant AscW( arg )

• Variant Chr( arg )

• Variant ChrB( arg )

• Variant ChrW( arg )

• Variant Concat( arg1, arg2 )

• Variant FormatNumber( arg1 , [arg2,[arg3,[arg4,[arg5]]]] )

• Variant FormatPercent( arg1 , [arg2,[arg3,[arg4,[arg5]]]] )

• Variant InStr( arg1 , arg2 , [arg3,[arg4]] )

106 Solutions Business Manager (SBM) • Variant InStrB( arg1 , arg2 , [arg3,[arg4]] )

• Variant InStrRev( arg1 , arg2 , [arg3,[arg4]] )

• Variant LCase( arg )

• Variant UCase( arg )

• Variant Left( arg1 , arg2 )

• Variant LeftB( arg1 , arg2 )

• Variant Right( arg1 , arg2 )

• Variant RightB( arg1 , arg2 )

• Variant Mid( arg1 , arg2 , [arg3] )

• Variant MidB( arg1 , arg2 , [arg3] )

• Variant Len( arg )

• Variant LenB( arg )

• Variant LTrim( arg )

• Variant RTrim( arg )

• Variant Trim( arg )

• Variant Replace( arg1 , arg2, arg3, [arg4,[arg5,[arg6]]] )

• Variant Space( arg )

• Variant StrComp( arg1 , arg2, [arg3] )

• Variant String( arg1 , arg2 )

• Variant StrReverse( arg )

Object Types • ExitDo: An exception type to handle SBM AppScript's Exit Do command.

• ExitFor: An exception type to handle SBM AppScript's Exit For command.

• ClonedByVal: ChaiScript always passes parameters by reference in function calls. This object helps emulate SBM AppScript's Pass By Value. CreateObject()

Creates a Lib or Dictionary object.

Function Signature

Variant CreateObject( value )

SBM ModScript Reference Guide 107 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

value string A string that represents the type of object to create. • To create a Lib object, use "SBMLibrary". See Lib [page 227].

• To create a Dictionary object, use "Scripting.Dictionary". See Dictionary [page 207].

Return

Type Description

Variant Returns a Variant wrapping the desired object.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Free Functions [page 101] CreateLocale()

Creates a specified locale, such as "en_US".

Function Signature

Locale CreateLocale( value )

Parameters

Parameter Type Description

value string A string that specifies the locale.

108 Solutions Business Manager (SBM) Return

Type Description

Locale Returns a Locale.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Free Functions [page 101] CreateUserLocale() [page 109] CreateSystemLocale() [page 110] CreateUserLocale()

Returns the current user's locale.

Function Signature

Locale CreateUserLocale()

Parameters

Parameter Type Description

None

Return

Type Description

Locale The current user's locale that is specified in the user profile. If the user does not have a specified locale in his or her profile, the system locale is returned.

Technical Details SBM ModScript version: 11.3. Notes None.

SBM ModScript Reference Guide 109 Chapter 3: Programming SBM ModScript

Related Topics Free Functions [page 101] CreateLocale() [page 108] CreateSystemLocale() [page 110] CreateSystemLocale()

Returns the default locale for the system.

Function Signature

Locale CreateSystemLocale()

Parameters

Parameter Type Description

None

Return

Type Description

Locale The current system locale. This is the default locale, configured in SBM System Administrator, which is used as the default locale for users who do not have one specified.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Free Functions [page 101] CreateLocale() [page 108] CreateUserLocale() [page 109] CreateTimeZone()

Creates the specified TimeZone.

110 Solutions Business Manager (SBM) Function Signature

TimeZone CreateTimeZone( value )

Parameters

Parameter Type Description

value string A string that specifies the TimeZone, such as "MST", "America/Denver", "US/Mountain".

Return

Type Description

TimeZone The specified TimeZone.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Free Functions [page 101] CreateUserTimeZone() [page 111] CreateUTCTimeZone() [page 112] CreateUserTimeZone()

Returns the current user's TimeZone.

Function Signature

TimeZone CreateUserTimeZone()

Parameters

Parameter Type Description

None

SBM ModScript Reference Guide 111 Chapter 3: Programming SBM ModScript

Return

Type Description

TimeZone The user's current TimeZone that is set in the user profile. If not specified, the system TimeZone is used.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Free Functions [page 101] CreateTimeZone() [page 110] CreateUTCTimeZone() [page 112] CreateUTCTimeZone()

Returns a TimeZone set to Coordinated Universal Time (UTC).

Function Signature

TimeZone CreateUTCTimeZone()

Parameters

Parameter Type Description

None

Return

Type Description

TimeZone The UTC TimeZone.

Technical Details SBM ModScript version: 11.3. Notes None.

112 Solutions Business Manager (SBM) Related Topics Free Functions [page 101] CreateTimeZone() [page 110] CreateUserTimeZone() [page 111] ExitScript()

Gracefully exits the script from wherever it is invoked.

Function Signature

void ExitScript()

Parameters

Parameter Type Description

None

Return

Type Description

None

Technical Details SBM ModScript version: 11.4. Notes None. Related Topics Free Functions [page 101] include()

Used to include scripts within other scripts.

Function Signature

void include( string value )

SBM ModScript Reference Guide 113 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

value string The name of the script to include.

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Notes Use include() to write utility scripts to use repeatedly within multiple scripts. The include("scriptname") function executes like other SBM ModScript functions; the referenced script is not executed until the function call is reached; therefore, functions defined in the included script will not be available until the call to include() has been executed. For details, see Including Other Scripts [page 359]. Related Topics Free Functions [page 101] Math Functions

Mathematical functions.

Description For more information, refer to http://en.cppreference.com/w/cpp/numeric/math. Basic Operations • double abs( double arg )

• double fabs( double arg )

• double fmod( double arg1 , double arg2 )

• double remainder( double arg1 , double arg2 )

• double remquo( double arg1 , double arg2 , int& arg3 )

• double fdim( double arg1 , double arg2 )

• double fma( double arg1 , double arg2 , double arg3 )

• double fmax( double arg1 , double arg2 )

114 Solutions Business Manager (SBM) • double fmin( double arg1 , double arg2 )

• double nan( string arg )

Nearest Integer Floating Point Operations • double ceil( double arg )

• double floor( double arg )

• double trunc( double arg )

• double round( double arg )

• int lround( double arg )

• int64_t llround( double arg )

• double rint( double arg )

• int lrint( double arg )

• int64_t llrint( double arg )

• double nearbyint( double arg )

Exponential Functions • double exp( double arg )

• double exp2( double arg )

• double expm1( double arg )

• double log( double arg )

• double log10( double arg )

• double log1p( double arg )

• double log2( double arg )

Power Functions • double pow( double arg1 , double arg2 )

• double sqrt( double arg )

• double cbrt( double arg )

• double hypot( double arg1 , double arg2 )

Trigonometric Functions • double cos( double arg )

• double sin( double arg )

• double tan( double arg )

SBM ModScript Reference Guide 115 Chapter 3: Programming SBM ModScript

• double acos( double arg )

• double asin( double arg )

• double atan( double arg )

• double atan2( double arg1 , double arg2 )

Hyperbolic Functions • double cosh( double arg )

• double sinh( double arg )

• double tanh( double arg )

• double acosh( double arg )

• double asinh( double arg )

• double atanh( double arg )

Error and Gamma Functions • double erf( double arg )

• double erfc( double arg )

• double tgamma( double arg )

• double lgamma( double arg )

Floating Point Manipulation Functions • double frexp( double arg , int& arg2 )

• double ldexp( double arg , int arg2 )

• double modf( double arg , double& arg2 )

• double scalbn( double arg , int arg2 )

• double scalbln( double arg , int arg2 )

• int ilogb( double arg )

• double logb( double arg )

• double copysign( double arg , double arg2 )

• double nextafter( double arg , double arg2 )

• double nexttoward( double arg , double arg2 )

Classification and Comparison • int fpclassify( double arg )

• bool isfinite( double arg )

116 Solutions Business Manager (SBM) • bool isinf( double arg )

• bool isnan( double arg )

• bool isnormal( double arg )

• bool signbit( double arg )

• bool isgreater( double arg1 , double arg2 )

• bool isgreaterequal( double arg1 , double arg2 )

• bool isless( double arg1 , double arg2 )

• bool islessequal( double arg1 , double arg2 )

• bool islessgreater( double arg1 , double arg2 )

• bool isunordered( double arg1 , double arg2 ) ScriptEngineVersion()

Returns information about the ChaiScript engine.

Function Signature

string ScriptEngine()

string ScriptEngineVersion()

int ScriptEngineMajorVersion()

int ScriptEngineMinorVersion()

string ScriptEngineBuildVersion()

Parameters

Parameter Type Description

None

SBM ModScript Reference Guide 117 Chapter 3: Programming SBM ModScript

Return

Type Description

string • ScriptEngine(): Returns "ChaiScript". int • ScriptEngineVersion(): Returns the ChaiScript version number.

• ScriptEngineMajorVersion(): Returns the ChaiScript major version number.

• ScriptEngineMinorVersion(): Returns the ChaiScript minor version number.

• ScriptEngineBuildVersion(): Returns SBM version.

Technical Details SBM ModScript version: 11.3. Example

Ext.WriteStream( ScriptEngine() ); Ext.WriteStream( ScriptEngineVersion() ); Ext.WriteStream( ScriptEngineMajorVersion() ); Ext.WriteStream( ScriptEngineMinorVersion() ); Ext.WriteStream( ScriptEngineBuildVersion() );

Result:

ChaiScript 6.0.0 6 0 1140000059

Notes ScriptEngineMajorVersionCompat() and ScriptEngineMinorVersionCompat() exist to provide backward compatibility for converted AppScripts. For details, refer to SBM AppScript Conversion Functions [page 103]. Related Topics Free Functions [page 101] TimeMillisDate()

Returns a TimeMillis set to current date (time truncated to midnight UTC).

118 Solutions Business Manager (SBM) Function Signature

TimeMillis TimeMillisDate()

Parameters

Parameter Type Description

None

Return

Type Description

TimeMillis The current date (with the time truncated to midnight UTC).

Technical Details SBM ModScript version: 11.4. Notes None. Related Topics Free Functions [page 101] TimeMillisNow() [page 119] TimeMillisNow()

Returns a TimeMillis set to current time.

Function Signature

TimeMillis TimeMillisNow()

Parameters

Parameter Type Description

None

SBM ModScript Reference Guide 119 Chapter 3: Programming SBM ModScript

Return

Type Description

TimeMillis The current date/time with millisecond precision.

Technical Details SBM ModScript version: 11.4. Notes None. Related Topics Free Functions [page 101] TimeMillisDate() [page 118] TimeTDate()

Returns a TimeT set to current date (time truncated to midnight UTC).

Function Signature

TimeT TimeTDate()

Parameters

Parameter Type Description

None

Return

Type Description

TimeT The current date (with the time truncated to midnight UTC).

Technical Details SBM ModScript version: 11.4. Notes None. Related Topics Free Functions [page 101]

120 Solutions Business Manager (SBM) TimeTNow() [page 121] TimeTNow()

Returns a TimeT set to current time.

Function Signature

TimeT TimeTNow()

Parameters

Parameter Type Description

None

Return

Type Description

TimeT The current date/time.

Technical Details SBM ModScript version: 11.4. Notes None. Related Topics Free Functions [page 101] TimeTDate() [page 120] Language Types For each type, a general explanation and methods are provided. • Map [page 122]

• Pair, Map_Pair, and Dictionary_Pair [page 123]

• Range types [page 124]

• string [page 125]

• u32string [page 131]

• char32_t Unicode Utilities [page 136]

SBM ModScript Reference Guide 121 Chapter 3: Programming SBM ModScript

• Vector [page 137] Map Description The Map class is a case sensitive key-value container, where the keys are strings. Keys will all be unique. Constructors • Map() – Creates an empty Map object.

• Map(Map m) – Creates a Map with a copy of m.

Operators • object& operator[]( string key ) – Accesses value at location key, performing an insert if key does not already exist.

• Map& operator =( Map m ) – Copies the values from Map m. Returns this object.

• bool operator ==( Map m ) – Returns true if both Maps contain the same number of entries, and each entry is equal to the corresponding entry in the other Map.

Methods • object& at( string key ) – Accesses value at location key. Throws exception if not found.

• void clear() – Empties the Map.

• bool empty() – Returns true if the Map is empty.

• size_t size() – Returns the count of items in the Map.

• size_t count( string key ) – Returns 1 if key is found inside the container; otherwise, 0.

• size_t erase( string key ) – Removes specified elements from the container, if one exists. Returns 1 if key is found inside the container; otherwise, 0.

• void insert( Map m ) – Copies values from m into this Map. Ignores values from m with keys that are already in this map.

• void insert( Map_Pair p ) – Inserts value p into this Map. Ignores p if the key value is already in this map.

Map_Pair The entries in a Map are of type Map_Pair, which holds a string and a value. Constructors (Map_Pair) • Map_Pair() – Creates an empty Map_Pair object.

• Map_Pair(Map_Pair mp) – Creates a Map_Pair with a copy of mp.

122 Solutions Business Manager (SBM) • Map_Pair(string key, object v) – Creates a Map_Pair initialized with key and v.

Methods (Map_Pair) • string& first() – Accesses the string used as the key for the entry.

• object& second() – Accesses the object used as the value for the entry. Pair, Map_Pair, and Dictionary_Pair Description The Pair class stores two objects. Pair Constructors In Pair, both first and second can store any object type. It is convenient in a situation in which you need to store two items, such as the AppDb "WithSQL" functions that use a Vector of Pairs for the SQL parameters. • Pair() – Creates an empty Pair object.

• Pair(Pair p) – Creates a Pair with a copy of p.

• Pair(object first, object second) – Creates a Pair initialized with first and second.

Pair Methods • object& first() – Accesses the first object in the Pair.

• object& second() – Accesses the second object in the Pair.

Map_Pair Constructors The entries in a Map will be of type Map_Pair. In Map_Pair, first is a string; second is any object type. • Map_Pair() – Creates an empty Map_Pair object.

• Map_Pair(Map_Pair p) – Creates a Map_Pair with a copy of p.

• Map_Pair(string first, object second) – Creates a Map_Pair initialized with first and second.

Map_Pair Methods • string& first() – Accesses the first object in the Map_Pair.

• object& second() – Accesses the second object in the Map_Pair.

Dictionary_Pair Constructors Dictionary is a class for supporting dictionary objects in scripts that are converted from SBM AppScript to SBM ModScript, in general, use ChaiScript's Map instead. Entries in Dictionary will be of type Dictionary_Pair. In Dictionary_Pair, first is a string; second is a Variant. • Dictionary_Pair() – Creates an empty Dictionary_Pair object.

SBM ModScript Reference Guide 123 Chapter 3: Programming SBM ModScript

• Dictionary_Pair(Dictionary_Pair p) – Creates a Dictionary_Pair with a copy of p.

• Dictionary_Pair(string first, Variant second) – Creates a Dictionary_Pair initialized with first and second.

Dictionary_Pair Methods • string& first() – Accesses the first object in the Dictionary_Pair.

• Variant& second() – Accesses the second object in the Dictionary_Pair. Range types Description The Range classes provide iteration for containers. The underlying container must persist while interacting with a Range based on that container. Classes The following classes are Range classes. In general, these classes are not used directly; instead, invoke range(container) to create a Range for a container. • Map_Range – Provides iteration for the Map class. Entries will be of type Map_Pair.

• String_Range – Provides iteration for the String class. Entries will be of type char.

• u32string_Range – Provides iteration for the u32string class. Entries will be of type char32_t, allowing iteration by code point.

• Vector_Range – Provides iteration for the Vector class. Entries will be the items that were in the Vector.

• CAppRecordList_Range – Provides iteration for the AppRecordList class. Entries will be AppRecord or child classes.

• Dictionary_Range – Provides iteration for the Dictionary class. Entries will be of type Dictionary_Pair.

Constructors In general, a Range is generated using range(container). Methods • bool empty() – Returns true if Range is empty.

• void pop_front() – Removes item from the beginning of the Range (this does not affect the underlying container). Throws exception if Range is empty.

• void pop_back() – Removes item from the end of the Range (this does not affect the underlying container). Throws exception if Range is empty.

• object& front() – Returns item from the front of the Range. Throws exception if Range is empty.

• object& back() – Returns item from the end of the Range. Throws exception if Range is empty.

124 Solutions Business Manager (SBM) Notes A quick way to access the last item in an AppRecordList (or any container) is range(myList).back(); Ranges are used frequently in algorithms. For more information, see Part 5 - Algorithms and Lambdas. A Range can be iterated using a ChaiScript for loop. string Description The string class stores a text value in UTF-8. Constructors • string() – Creates an empty string object.

• string(string s) – Creates a string with a copy of s.

Operators • char& operator[]( int index ) – Accesses value at location index. Throws an exception if index is out of range.

• string& operator =( string s ) – Copies the values from string s. Returns this object.

• string& operator =( char32_t c ) – Sets the value to the code point c. Returns this object.

• string& operator +=( string s ) – Appends the value from string s. Returns this object.

• string& operator +=( char c ) – Appends the character c. Returns this object.

• bool operator ==( string s ) – Returns true if both strings contain identical text.

• bool operator !=( string s ) – Returns true if the strings represent different text.

• bool operator <=( string s ) – Compares two strings lexicographically.

• bool operator >=( string s ) – Compares two strings lexicographically.

• bool operator <( string s ) – Compares two strings lexicographically.

• bool operator >( string s ) – Compares two strings lexicographically.

Methods • size_t find(string s) – Finds the first instance of s, returning the 0-based index. When not found, returns string_npos.

• size_t find(string s, size_t index) – Finds the first instance of s starting at offset index, returning the 0-based index. When not found, returns string_npos.

SBM ModScript Reference Guide 125 Chapter 3: Programming SBM ModScript

• size_t rfind(string s) – Finds the last instance of s, returning the 0-based index. When not found, returns string_npos.

• size_t rfind(string s, size_t index) – Finds the last instance of s starting at offset index, returning the 0-based index. When not found, returns string_npos.

• size_t find_first_of(string s) – Finds the first matching character from the characters in s, returning the 0-based index. When not found, returns string_npos.

• size_t find_first_of(string s, size_t index) – Finds the first matching character from the characters in s starting at offset index, returning the 0-based index. When not found, returns string_npos.

• size_t find_first_not_of(string s) – Finds the first non-matching character from the characters in s, returning the 0-based index. When not found, returns string_npos.

• size_t find_first_not_of(string s, size_t index) – Finds the first non-matching character from the characters in s starting at offset index, returning the 0-based index. When not found, returns string_npos.

• size_t find_last_of(string s) – Finds the last matching character from the characters in s, returning the 0-based index. When not found, returns string_npos.

• size_t find_last_of(string s, size_t index) – Finds the last matching character from the characters in s starting at offset index, returning the 0-based index. When not found, returns string_npos.

• size_t find_last_not_of(string s) – Finds the last non-matching character from the characters in s, returning the 0-based index. When not found, returns string_npos.

• size_t find_last_not_of(string s, size_t index) – Finds the last non-matching character from the characters in s starting at offset index, returning the 0-based index. When not found, returns string_npos.

1 • void insert_at(int index, char c) – Inserts character c at position index. Throws an exception if index is out of range.

1 • void insert32(int index, char32_t c) – Inserts the code point c before the code point at position index. Throws an exception if index is out of range.

1 • void erase_at(int index) – Removes character at position index. Throws an exception if index is out of range.

• void push_back(char c) – Appends character c.

• void append32(char32_t c) – Appends the code point c.

• void clear() – Empties the string.

• bool empty() – Returns true if the string is empty.

• size_t size() – Returns the length of the string in bytes.

126 Solutions Business Manager (SBM) • size_t length() – Returns the length of the string in bytes.

• int length32() – Returns the count of code points in the string.

• string substr(size_t index, size_t len)1 – Returns a substring starting at offset index with length of len. The value string_npos can be used for the len parameter to return the remaining string contents. Throws an exception if index plus len is out of range.

• string substr32(int index, int count) – Returns a substring starting with the code point at index and containing up to count code points. The value string_npos can be used for the count parameter to return the remaining string contents. Throws an exception if index is out of range.

1 • string mid( size_t index ) – Returns a substring starting at offset index. Does not throw an exception.

• string mid( size_t index, size_t len )1 – Returns a substring starting at offset index with length up to len. Does not throw an exception.

• string mid32( int index ) – Returns a substring starting with the code point at index. Does not throw an exception.

• string mid32( int index, int count ) – Returns a substring starting with the code point at index and containing up to count code points. Does not throw an exception.

1 • string left( size_t len ) – Returns a substring with up to the first len characters. Does not throw an exception.

• string left32( int count ) – Returns a substring containing up to count code points. Does not throw an exception.

1 • string right( size_t len ) – Returns a substring with up to the last len characters. Does not throw an exception.

• string right32( int count ) – Returns a substring containing up to the last count code points. Does not throw an exception.

• char32_t at32( int index ) – Returns the code point at position index. Throws an exception if index is out of range.

• string& replace( size_t start, size_t count, string newStr )1 – Replaces the part of the string indicated by [start, start + count) with the text in newStr (newStr can be empty).

• string& replace32( int start, int count, string newStr ) – Replaces the part of the string indicated by [start, start + count) (as code points) with the text in newStr (newStr can be empty).

• string& replaceAll( string oldStr, string newStr ) – Replaces each instance of oldStr with the text in newStr (newStr can be empty).

• string& replaceFirst( string oldStr, string newStr ) – Replaces the first instance of oldStr with the text in newStr (newStr can be empty).

SBM ModScript Reference Guide 127 Chapter 3: Programming SBM ModScript

• string& replaceFirst( string oldStr, string newStr, startPosition ) – Replaces the first instance of oldStr with the text in newStr (newStr can be empty), starting at index startPosition.

• string& replaceLast( string oldStr, string newStr ) – Replaces the last instance of oldStr with the text in newStr (newStr can be empty).

• string& truncate( size_t newLength ) – Shortens the string text value to the new length. The new string may be shorter than newLength if truncation would break a Unicode code–point sequence.

• string& truncate32( int count ) – Shortens the string text up to count code points.

• string ltrim() – Removes whitespace from the beginning of the string, returning a new string.

• string& ltrim_self() – Removes whitespace characters from the beginning of this string.

• string& ltrim_self( string s ) – Removes any characters found in s from the beginning of this string.

• string rtrim() – Removes whitespace from the end of the string, returning a new string.

• string& rtrim_self() – Removes whitespace characters from the end of this string.

• string& rtrim_self( string s ) – Removes any characters found in s from the end of this string.

• string trim() – Removes whitespace from the beginning and end of the string, returning a new string.

• string& trim_self() – Removes whitespace characters from the beginning and end of this string.

• string& trim_self( string s ) – Removes any characters found in s from the beginning and end of this string.

• string& reverse_self() – Reverses the ordering of this string, keeping Unicode code–points together.

• string& toLowerASCII() – All ASCII characters will be converted to ASCII lower case equivalent values.

• string& toLower( Locale l ) – All characters will be converted to lower case equivalent values using the rules from the Locale provided.

• string& toUpperASCII() – All ASCII characters will be converted to ASCII upper case equivalent values.

• string& toUpper( Locale l ) – All characters will be converted to upper case equivalent values using the rules from the Locale provided.

• void reserve( size_t v ) – Pre-allocates a buffer of size v for future use.

128 Solutions Business Manager (SBM) • bool u_normalizeNFC() – Applies the NFC (composed) Unicode normalization. Returns true if the string was normalized.

• bool u_normalizeNFD() – Applies the NFD (decomposed) Unicode normalization. Returns true if the string was normalized.

• u32string to_u32string() – Returns the contents of the string encoded as UTF-32. See u32string [page 131].

1These functions can break a UTF-8 multibyte sequence. Consider using the equivalent function with "32" in the suffix. String Iteration The string class represents text in UTF-8. If you iterate a string using the for( c : s ) syntax, the loop will iterate the string byte by byte, potentially breaking code points. This can be resolved one of two ways: • Use for( c : s.to_u32string() ). This will create a temporary u32string allowing you to iterate code point by code point.

• Use the UTF-8 iteration functions below: ▪ char32_t utf8_next( int& index ) – Used for iterating a string by code point, this will return the code point at index, then move index forward to the next code point. Throws exception if index is out of bounds. For example, the following will output each of the four code points in order:

var s = "über"; if ( !s.empty() ) { for ( var index = 0; index < s.length(); ) { var c = s.utf8_next( index ); Ext.WriteStream( c.to_string() ); } }

▪ char32_t utf8_prev( int& index ) – Used for iterating a string by code point, this will move index backward to the previous code point, then return the code point at that index. Throws exception if index is out of bounds. For example, the following will output each of the four code points in reverse order:

var s = "über"; if ( !s.empty() ) { for ( var index = int(s.length()); index > 0; ) { var c = s.utf8_prev( index ); Ext.WriteStream( c.to_string() ); } }

▪ void utf8_skipForward( int& index, int count ) – Used for iterating a string by code point, this will move index forward count code points. Throws exception if index is out of bounds. For example, the following will output the fourth code point of the string:

SBM ModScript Reference Guide 129 Chapter 3: Programming SBM ModScript

var s = "über"; var index = 0; s.utf8_skipForward( index, 3 ); Ext.WriteStream( s.at32( index ).to_string() );

▪ void utf8_skipBackward( int& index, int count ) – Used for iterating a string by code point, this will move index backward count code points. Throws exception if index is out of bounds. For example, the following will output the second code point in the string:

var s = "über"; var index = int( s.length() );// index must be an int s.utf8_skipBackward( index, 3 ); Ext.WriteStream( s.at32( index ).to_string() );

Unicode Utility Methods • bool utf8_isSingle( int index ) – Returns true if the byte at index is a single-byte UTF-8 sequence. Throws exception if index is out of bounds.

• bool utf8_isLead( int index ) – Returns true if the byte at index is the first byte in a multi-byte UTF-8 sequence. Throws exception if index is out of bounds.

• bool utf8_isTrail( int index ) – Returns true if the byte at index is a trailing byte in a multi-byte UTF-8 sequence. Throws exception if index is out of bounds.

• int utf8_cpLength( int index ) – Returns the length of the UTF-8 sequence at index. Throws exception if index is out of bounds.

• bool u_isUpperCase( int index ) – Returns true if the code point at position index is an upper case letter character (equivalent to java.lang.Character.isUpperCase()). Throws exception if index is out of bounds.

• bool u_isLowerCase( int index ) – Returns true if the code point at position index is a lower case letter character (equivalent to java.lang.Character.isLowerCase()). Throws exception if index is out of bounds.

• bool u_isSpace( int index ) – Returns true if the code point at position index is a white space character; similar to C/POSIX isspace(). Throws exception if index is out of bounds.

• bool u_isSpaceChar( int index ) – Returns true if the code point at position index is a space character (equivalent to java.lang.Character.isSpaceChar()). Throws exception if index is out of bounds.

• bool u_isWhitespace( int index ) – Returns true if the code point at position index is a white space character (similar to java.lang.Character.isWhitespace()). Throws exception if index is out of bounds.

• bool u_isLetter( int index ) – Returns true if the code point at position index is a letter character (equivalent to java.lang.Character.isLetter()). Throws exception if index is out of bounds.

130 Solutions Business Manager (SBM) • bool u_isDigit( int index ) – Returns true if the code point at position index is a digit character (equivalent to java.lang.Character.isDigit()). Throws exception if index is out of bounds.

• bool u_isLetterOrDigit( int index ) – Returns true if the code point at position index is an alphanumeric character (letter or digit) (equivalent to java.lang.Character.isLetterOrDigit()). Throws exception if index is out of bounds.

• bool u_isPunctuation( int index ) – Returns true if the code point at index is a punctuation character. Throws exception if index is out of bounds.

• bool u_isBMP( int index ) – Returns true if the code point at index is in the Unicode Basic Multilingual Plane. Throws exception if index is out of bounds.

• bool u_isGraphic( int index ) – Returns true if the code point at index is a "graphic" character (printable, excluding spaces). Throws exception if index is out of bounds.

• bool u_isPrintable( int index ) – Returns true if the code point at index is a printable character. Throws exception if index is out of bounds.

• bool u_isBlank( int index ) – Returns true if the code point at index is a "blank" or "horizontal space", a character that visibly separates words on a line. Throws exception if index is out of bounds.

• bool u_isDefined( int index ) – Returns true if the code point at index is "defined", which usually means it is assigned a character in Unicode (equivalent to java.lang.Character.isDefined()). Throws exception if index is out of bounds.

• int u_charType( int index ) – Returns the Unicode general category of the code point at position index (equivalent to java.lang.Character.getType()). Return value can be tested against UnicodeCharTypeConstants. Throws exception if index is out of bounds. See UnicodeCharTypeConstants [page 356].

• int u_digit( int index, int radix ) – Returns the decimal digit value of the code point at position index in the specified radix. Throws exception if index is out of bounds.

• void u_toLower( int index ) – Changes code point at index to lower case using non-Locale-based Unicode mapping. Throws exception if index is out of bounds.

• void u_toUpper( int index ) – Changes code point at index to upper case using non-Locale-based Unicode mapping. Throws exception if index is out of bounds. u32string Description The utility string class that stores a text value in UTF-32. This is not the default string class, but can be used for working with Unicode string contents. See string.to_u32string() in string [page 125].

SBM ModScript Reference Guide 131 Chapter 3: Programming SBM ModScript

Constructors • u32string() – Creates an empty u32string object.

• u32string( u32string s ) – Creates a u32string with a copy of s.

Operators • char32_t& operator[]( int index ) – Accesses code point at location index. Throws an exception if index is out of range.

• u32string& operator =( u32string s ) – Copies the values from u32string s. Returns this object.

• u32string& operator =( char32_t c ) – Sets the value to the code point c. Returns this object.

• u32string& operator +=( u32string s ) – Appends the value from u32string s. Returns this object.

• u32string& operator +=( char32_t c ) – Appends the code point c. Returns this object.

• bool operator ==( u32string s ) – Returns true if both u32strings contain identical text.

• bool operator !=( u32string s ) – Returns true if the u32strings represent different text.

• bool operator <=( u32string s ) – Compares two u32strings lexicographically.

• bool operator >=( u32string s ) – Compares two u32strings lexicographically.

• bool operator <( u32string s ) – Compares two u32strings lexicographically.

• bool operator >( u32string s ) – Compares two u32strings lexicographically.

Methods • size_t find(u32string s, size_t index) – Finds the first instance of s starting at offset index, returning the 0-based index. When not found, returns string_npos.

• size_t rfind(u32string s, size_t index) – Finds the last instance of s starting at offset index, returning the 0-based index. When not found, returns string_npos.

• size_t find_first_of(u32string s, size_t index) – Finds the first matching code point from the char32_t values in s starting at offset index, returning the 0-based index. When not found, returns string_npos.

• size_t find_first_not_of(u32string s, size_t index) – Finds the first non- matching code point from the char32_t values in s starting at offset index, returning the 0-based index. When not found, returns string_npos.

• size_t find_last_of(u32string s, size_t index) – Finds the last matching code point from the char32_t values in s starting at offset index, returning the 0-based index. When not found, returns string_npos.

132 Solutions Business Manager (SBM) • size_t find_last_not_of(u32string s, size_t index) – Finds the last non-matching code point from the char32_t values in s starting at offset index, returning the 0-based index. When not found, returns string_npos.

• void insert_at(int index, char32_t c) – Inserts code point c at position index. Throws an exception if index is out of range.

• void erase_at(int index) – Removes code point at position index. Throws an exception if index is out of range.

• void push_back(char32_t c) – Appends code point c.

• void clear() – Empties the u32string.

• bool empty() – Returns true if the u32string is empty.

• size_t size() – Returns the length of the u32string in code points.

• size_t length() – Returns the length of the u32string in code points.

• u32string substr(size_t index, size_t len) – Returns a sub-u32string starting at offset index with length of len. The value string_npos can be used for the len parameter to return the remaining u32string contents. Throws an exception if index plus len is out of range.

• u32string mid( size_t index ) – Returns a sub-u32string starting at offset index. Does not throw an exception.

• u32string mid( size_t index, size_t len ) – Returns a sub-u32string starting at offset index with length up to len. Does not throw an exception.

• u32string left( size_t len ) – Returns a sub-u32string with up to the first len code points. Does not throw an exception.

• u32string right( size_t len ) – Returns a sub-u32string with up to the last len code points. Does not throw an exception.

• u32string& replace( size_t start, size_t count, u32string newStr ) – Replaces the part of the u32string indicated by [start, start + count) with the text in newStr (newStr can be empty).

• u32string& replaceAll( u32string oldStr, u32string newStr ) – Replaces each instance of oldStr with the text in newStr (newStr can be empty).

• u32string& replaceFirst( u32string oldStr, u32string newStr ) – Replaces the first instance of oldStr with the text in newStr (newStr can be empty).

• u32string& replaceFirst( u32string oldStr, u32string newStr, startPosition ) – Replaces the first instance of oldStr with the text in newStr (newStr can be empty), starting at index startPosition.

• u32string& replaceLast( u32string oldStr, u32string newStr ) – Replaces the last instance of oldStr with the text in newStr (newStr can be empty).

SBM ModScript Reference Guide 133 Chapter 3: Programming SBM ModScript

• u32string& truncate( size_t newLength ) – Shortens the u32string text value to the new length.

• u32string ltrim() – Removes whitespace from the beginning of the u32string, returning a new u32string.

• u32string& ltrim_self() – Removes whitespace from the beginning of this u32string.

• u32string& ltrim_self( u32string s ) – Removes any code points found in s from the beginning of this u32string.

• u32string rtrim() – Removes whitespace from the end of the u32string, returning a new u32string.

• u32string& rtrim_self() – Removes whitespace from the end of this u32string.

• u32string& rtrim_self( u32string s ) – Removes any code points found in s from the end of this u32string.

• u32string trim() – Removes whitespace from the beginning and end of the u32string, returning a new u32string.

• u32string& trim_self() – Removes whitespace from the beginning and end of this u32string.

• u32string& trim_self( u32string s ) – Removes any code points found in s from the beginning and end of this u32string.

• u32string& reverse_self() – Reverses the order of the code points in this u32string.

• u32string& toLowerASCII() – All ASCII code points will be converted to ASCII lower case equivalent values.

• u32string& toLower( Locale l ) – All code points will be converted to lower case equivalent values using the rules from the Locale provided.

• u32string& toUpperASCII() – All ASCII code points will be converted to ASCII upper case equivalent values.

• u32string& toUpper( Locale l ) – All code points will be converted to upper case equivalent values using the rules from the Locale provided.

• bool u_normalizeNFC() – Applies the NFC (composed) Unicode normalization. Returns true if the u32string was normalized.

• bool u_normalizeNFD() – Applies the NFD (decomposed) Unicode normalization. Returns true if the u32string was normalized.

• string to_string() – Returns the contents of the u32string encoded as UTF-8. See string [page 125].

Unicode Utility Methods • bool u_isUpperCase( int index ) – Returns true if the code point at position index is an upper case letter character (equivalent to java.lang.Character.isUpperCase()). Throws exception if index is out of bounds.

134 Solutions Business Manager (SBM) • bool u_isLowerCase( int index ) – Returns true if the code point at position index is a lower case letter character (equivalent to java.lang.Character.isLowerCase()). Throws exception if index is out of bounds.

• bool u_isSpace( int index ) – Returns true if the code point at position index is a white space character; similar to C/POSIX isspace(). Throws exception if index is out of bounds.

• bool u_isSpaceChar( int index ) – Returns true if the code point at position index is a space character (equivalent to java.lang.Character.isSpaceChar()). Throws exception if index is out of bounds.

• bool u_isWhitespace( int index ) – Returns true if the code point at position index is a white space character (similar to java.lang.Character.isWhitespace()). Throws exception if index is out of bounds.

• bool u_isLetter( int index ) – Returns true if the code point at position index is a letter character (equivalent to java.lang.Character.isLetter()). Throws exception if index is out of bounds.

• bool u_isDigit( int index ) – Returns true if the code point at position index is a digit character (equivalent to java.lang.Character.isDigit()). Throws exception if index is out of bounds.

• bool u_isLetterOrDigit( int index ) – Returns true if the code point at position index is an alphanumeric character (letter or digit) (equivalent to java.lang.Character.isLetterOrDigit()). Throws exception if index is out of bounds.

• bool u_isPunctuation( int index ) – Returns true if the code point at index is a punctuation character. Throws exception if index is out of bounds.

• bool u_isBMP( int index ) – Returns true if the code point at index is in the Unicode Basic Multilingual Plane. Throws exception if index is out of bounds.

• bool u_isGraphic( int index ) – Returns true if the code point at index is a "graphic" character (printable, excluding spaces). Throws exception if index is out of bounds.

• bool u_isPrintable( int index ) – Returns true if the code point at index is a printable character. Throws exception if index is out of bounds.

• bool u_isBlank( int index ) – Returns true if the code point at index is a "blank" or "horizontal space", a character that visibly separates words on a line. Throws exception if index is out of bounds.

• bool u_isDefined( int index ) – Returns true if the code point at index is "defined", which usually means it is assigned a character in Unicode (equivalent to java.lang.Character.isDefined()). Throws exception if index is out of bounds.

• int u_charType( int index ) – Returns the Unicode general category of the code point at position index (equivalent to java.lang.Character.getType()). Return value can be tested against UnicodeCharTypeConstants. Throws exception if index is out of bounds. See UnicodeCharTypeConstants [page 356].

SBM ModScript Reference Guide 135 Chapter 3: Programming SBM ModScript

• int u_digit( int index, int radix ) – Returns the decimal digit value of the code point at position index in the specified radix. Throws exception if index is out of bounds.

• void u_toLower( int index ) – Changes code point at index to lower case using non-Locale-based Unicode mapping. Throws exception if index is out of bounds.

• void u_toUpper( int index ) – Changes code point at index to upper case using non-Locale-based Unicode mapping. Throws exception if index is out of bounds.

char32_t Unicode Utilities Description A set of utility functions for identifying Unicode traits of char32_t code points. Unicode Utility Functions • string to_string( char32_t c ) – Returns a string containing the code point c.

• bool u_isUpperCase( char32_t c ) – Returns true if the code point c is an upper case letter character (equivalent to java.lang.Character.isUpperCase()).

• bool u_isLowerCase( char32_t c ) – Returns true if the code point c is a lower case letter character (equivalent to java.lang.Character.isLowerCase()).

• bool u_isSpace( char32_t c ) – Returns true if the code point c is a white space character; similar to C/POSIX isspace().

• bool u_isSpaceChar( char32_t c ) – Returns true if the code point c is a space character (equivalent to java.lang.Character.isSpaceChar()).

• bool u_isWhitespace( char32_t c ) – Returns true if the code point c is a white space character (similar to java.lang.Character.isWhitespace()).

• bool u_isLetter( char32_t c ) – Returns true if the code point c is a letter character (equivalent to java.lang.Character.isLetter()).

• bool u_isDigit( char32_t c ) – Returns true if the code point c is a digit character (equivalent to java.lang.Character.isDigit()).

• bool u_isLetterOrDigit( char32_t c ) – Returns true if the code point c is an alphanumeric character (letter or digit) (equivalent to java.lang.Character.isLetterOrDigit()).

• bool u_isPunctuation( char32_t c ) – Returns true if the code point c is a punctuation character.

• bool u_isBMP( char32_t c ) – Returns true if the code point c is in the Unicode Basic Multilingual Plane.

• bool u_isGraphic( char32_t c ) – Returns true if the code point c is a "graphic" character (printable, excluding spaces).

136 Solutions Business Manager (SBM) • bool u_isPrintable( char32_t c ) – Returns true if the code point c is a printable character.

• bool u_isBlank( char32_t c ) – Returns true if the code point c is a "blank" or "horizontal space", a character that visibly separates words on a line.

• bool u_isDefined( char32_t c ) – Returns true if the code point c is "defined", which usually means it is assigned a character in Unicode (equivalent to java.lang.Character.isDefined()).

• int u_charType( char32_t c ) – Returns the Unicode general category of the code point c (equivalent to java.lang.Character.getType()). Return value can be tested against UnicodeCharTypeConstants. See UnicodeCharTypeConstants [page 356].

• int u_digit( char32_t c, int radix ) – Returns the decimal digit value of the code point c in the specified radix.

• void u_toLower( char32_t c ) – Returns the lower case equivalent of code point c using non-Locale-based Unicode mapping.

• void u_toUpper( char32_t c ) – Returns the upper case equivalent of code point c using non-Locale-based Unicode mapping. Vector Description The Vector class stores a resizable array of objects. Constructors • Vector() – Creates an empty Vector object.

• Vector(Vector v) – Creates a Vector with a copy of v.

Operators • object& operator[]( int index ) – Accesses value at location index. Throws an exception if index is out of range.

• Vector& operator =( Vector v ) – Copies the values from Vector v. Returns this object.

• bool operator ==( Vector v ) – Returns true if both Vectors contain the same number of items, and each item is equal to the corresponding item in the other Vector.

Methods • void clear() – Empties the Vector.

• bool empty() – Returns true if the Vector is empty.

• size_t size() – Returns the count of items in the Vector.

SBM ModScript Reference Guide 137 Chapter 3: Programming SBM ModScript

• object& front() – Accesses value at the beginning of the Vector. Throws an exception if the Vector is empty.

• object& back() – Accesses value at the end of the Vector. Throws an exception if the Vector is empty.

• void push_back( object o ) – Inserts the value o at the end of the Vector.

• void pop_back() – Removes value from the end of the Vector. Do not invoke this on an empty Vector.

• void insert_at(int index, object o) – Inserts o at position index. Throws an exception if index is out of range.

• void erase_at(int index) – Removes object at position index. Throws an exception if index is out of range.

• void resize(size_t count) – Resizes the Vector to contain count elements. If the current size is greater than the count, the container is reduced to its first count elements. If the current size is less than count, additional elements are appended and default-initialized.

• void resize(size_t count, object o) – Resizes the Vector to contain count elements. If the current size is greater than the count, the container is reduced to its first count elements. If the current size is less than count, additional elements are appended and copied from o.

• void reserve( size_t count ) – Pre-allocates a buffer of size count for future use.

• size_t capacity() – Returns the current buffer size. Working with Application Objects In addition to the core ChaiScript data types, SBM ModScript includes SBM application object types whose methods and properties give access to SBM operations and quantities. • Creating SBM Application Objects [page 138]

• Inheritance [page 139] Creating SBM Application Objects SBM ModScript includes the core ChaiScript function CreateObject(), taking a single string parameter. If the parameter is "Scripting.Dictionary", then a new Dictionary object is returned. If the parameter begins with "SBM.", then an SBM object is returned. For example, the following statement creates a new User object:

var myUser = CreateObject( "SBM.User" );

Some SBM objects cannot be created with the CreateObject() function, because additional parameters are necessary. For example, the object type AppRecord is always associated with an SBM table and cannot be created without a numeric table ID. The CreateObject() function cannot accommodate the table ID parameter, so it cannot be used to create AppRecord objects. Instead, SBM ModScript provides the function Ext.CreateAppRecord()

138 Solutions Business Manager (SBM) which takes a table ID parameter. Refer to Extension Functions [page 62] for details on this and other special object creation functions. Inheritance SBM object types have a hierarchical inheritance structure compatible with but not generally seen in ChaiScript. If an object type S inherits from another object type B, then S is a "subtype" of B, and B is a "base type" for S. This means all methods and properties of B are available to S. It also means objects of type S are considered to be of type B as well, though objects of type B are not necessarily of type S. The following diagram shows the SBM inheritance hierarchy. Arrows point from base types to subtypes.

Figure 1. For example, AppRecord is a base type whose many subtypes include Field and Project. AppRecord has a method called GetName(), which returns a string. GetName() is not a method of Field or Project, but those types inherit it from AppRecord. Thus, GetName() can be called on objects of type Field and Project. In addition, objects of type Field and Project can be used anywhere an object of type AppRecord is expected. And, because AppRecord is a base type, any AppRecord might also be a Field or Project or some other subtype. "Inheritance" information is included for each object type, using similar arrow notation. For example, "AppRecord --> User" means the object type AppRecord is the base type for User. Object Types For each object type, a general explanation, an inheritance diagram, and detailed explanations of all properties and methods are provided. • ADLog [page 141]

SBM ModScript Reference Guide 139 Chapter 3: Programming SBM ModScript

• AppDb [page 142]

• AppRecord [page 159]

• AppRecordList [page 187]

• Change [page 198]

• ChangeList [page 203]

• DbImport [page 203]

• Dictionary [page 207]

• Field [page 209]

• Folder [page 223]

• FolderItem [page 226]

• FolderItemList [page 226]

• Incident [page 227]

• Lib [page 227]

• Locale [page 233]

• Log [page 242]

• Project [page 252]

• ProjectBasedRecord [page 252]

• Regex [page 259]

• RESTDataSource [page 269]

• SchemaColumn [page 280]

• LinkText [page 281]

• TempFile [page 282]

• TimeMillis [page 283]

• TimePoint [page 294]

• TimeT [page 296]

• TimeZone [page 306]

• Transition [page 311]

• TreeItem [page 312]

• TreeList [page 315]

140 Solutions Business Manager (SBM) • UGBase [page 316]

• User [page 318]

• VarFieldList [page 319]

• Variant [page 322]

• VarRecord [page 326] ADLog Description A class for logging to Active Diagnostics. Global Constant ADLog: The one global instance of this object. Methods • Message() [page 141]

Message()

Writes a message to Active Diagnostics.

Function Signature

void Message( string file, int line, int level, value )

void Message( string file, int line, int level, format, arg0-4)

void Message( int level, value )

void Message( int level, format, arg0-4)

Parameters

Parameter Type Description

file string Expected value: __FILE__ File and line provide context in the Active Diagnostics message to indicate with script and line number the message came from.

line int Expected value: __LINE__

level int Corresponds to values from ADLogLevelConstants [page 342].

SBM ModScript Reference Guide 141 Chapter 3: Programming SBM ModScript

Parameter Type Description

value Variant Value will be converted to a string and written to the log.

format string A format string with entries like {0} that correspond to arg0 etc. See notes below.

arg (up to 5) Variant A value that is formatted into the output text using the format parameter.

Return

Type Description

None Returns true if all applicable records are successfully updated; false otherwise.

Technical Details SBM ModScript version: 11.4. Example

ADLog.Message( __FILE__, __LINE__, ADLogLevelConstants.ERROR, "An informative error {0}", 5 );

Notes The signatures that take __FILE__ and __LINE__ are preferred, as they provide script location information in the log. The format parameter is a format string with places for up to five values in it. Those places are encoded in the string in {0} format, where the number is the zero-based index of the parameter to be placed in that location. Indexes can be repeated in the format string if that variable should be placed into the string more than one time. Literal "{" must be escaped by single ticks, literal single ticks must be escaped by single ticks. Related Topics ADLog [page 141] AppDb Description This object represents the current connection to the database. There is only one such object defined at a time. Scripts can use AppDb objects provided in the Shell but cannot create new AppDb objects.

142 Solutions Business Manager (SBM) Inheritance AppDb does not inherit from any object type. Methods • ColName() [page 143]

• ExecuteSQL() [page 144]

• GetConnectionInfo() [page 145]

• ReadFolderItems() [page 146]

• GetDbType() [page 147]

• IsMSSQL() [page 148]

• IsOracle() [page 149]

• ReadIntWithSQL() [page 150]

• ReadTextWithSQL() [page 151]

• ReadIntegersWithSQL() [page 152]

• ReadTextValsWithSQL() [page 153]

• ReadIntegerPairsWithSQL() [page 154]

• ReadDynaSQL() [page 155]

• WriteBlobToFile() [page 157]

• UpdateBlobFromFile() [page 158]

• UserId() [page 159]

ColName()

Converts the parameter to the form of a valid database column name, using the same transformation applied when you enter logical field names in SBM Composer.

Function Signature

string ColName( colname )

Parameters

Parameter Type Description

colname string Base name of field or column (without "TS_"). Can contain spaces, punctuation, and mixed case.

SBM ModScript Reference Guide 143 Chapter 3: Programming SBM ModScript

Return

Type Description

string A column name in legal database form, containing only upper case letters and underscores, prefixed with "TS_".

Technical Details SBM ModScript version: 11.3. Notes There is no database lookup of actual field or column names; it is a simple text transformation. For example, given "submit date?", this function returns "TS_SUBMIT_DATE". The "TS_" is prepended, alphanumeric characters are converted to uppercase, spaces are converted to underscores, and other characters are omitted. This function provides a measure of safety when working with column names, because the output is guaranteed to be of a legal form. However, because logical names can be changed at any time after a column's creation, passing a field's logical name to this function will not necessarily yield its actual database name. This function can assist an SBM ModScript programmer who recalls a column's "basic" database name but not the exact formatting rules for punctuation and spaces. An alternative to calling this function is to be sure of the exact column name by looking at the field's database name in SBM Composer or opening the database itself to see the desired column. Related Topics AppDb [page 142]

ExecuteSQL()

(SBM On-Premise/PaaS only) Executes SQL in the database. See important notes below.

Function Signature

void ExecuteSQL( sqlText [, Vector params] )

Parameters

Parameter Type Description

sqlText string The SQL to pass in.

params Vector An optional Vector storing SQL bind parameters, where each entry is a Pair, with the first value as the parameter type and the second value as the value to bind to the SQL parameter. Corresponds to DBTypeConstants [page 347]. See Pair, Map_Pair, and Dictionary_Pair [page 123].

144 Solutions Business Manager (SBM) Return

Type Description

None

Technical Details SBM ModScript version: 11.4.1. Example

Shell.Db().ExecuteSQL( "with uvh as ( select TS_ID from TS_USER_VIEWHISTORY with(nolock) where TS_USERID = ? and TS_TABLEID = ? and TS_ITEMID = ? ) update u set u.TS_TIMESTAMP=GETUTCDATE() from TS_USER_VIEWHISTORY u join uvh on u.TS_ID=uvh.TS_ID", [ Pair( DBTypeConstants.INTEGER, 8 ), Pair( DBTypeConstants.INTEGER, 1006 ), Pair( DBTypeConstants.INTEGER, 2 ) ] )

Notes Use caution when changing the database directly: • No change history is written by SBM based on changes you make to the database.

• For data that is cached by SBM components, changes made directly to the database will not invalidate the cache.

• Certain things are stored in multiple places. For example, Multi-Relational field values are stored as comma-separated values in primary/auxiliary tables, but also are maintained in the TS_USAGES table so that values are searched using an indexed query. Changing a value without ensuring that all related locations are updated can lead to undefined behavior.

Related Topics AppDb [page 142]

GetConnectionInfo()

(SBM On-Premise only) Provides information on the data source name, the name of the database, the name or IP address of the server that contains the database currently connected to SBM, and whether the connection is remote.

Function Signature

bool GetConnectionInfo( string& dsn, string& dname, string& srvname, bool& remote )

bool GetConnectionInfo( Variant& dsn, Variant& dbname, Variant& srvname, Variant& remote )

SBM ModScript Reference Guide 145 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

dsn string& (Output) The data source name from ODBC that the or connection is using to access the database. Variant&

dbname string& (Output) The full database name that the connection is or accessing. Variant&

srvname string& (Output) The server name that the connection is using to or access the DBMS. This could be a machine name or an IP Variant& address.

remote bool& or (Output) Always false. Variant&

Return

Type Description

bool Returns true if the method was successful; false if not.

Technical Details SBM ModScript version: 11.3. Extended in 11.4. Notes None. Related Topics AppDb [page 142]

ReadFolderItems()

(SBM On-Premise/PaaS only) Provides a list of items in a folder.

Function Signature

bool ReadFolderItems( FolderItemList& list, int folderId )

146 Solutions Business Manager (SBM) Parameters

Parameter Type Description

list FolderItemList& (Output) The list of items in the folder.

folderId int The parent folder of the items you wish to access.

Return

Type Description

bool Returns true if the method was successful; false if not. A successful read may return zero results if no items match the query. Check for results by calling the AppRecordList.empty() method.

Technical Details SBM ModScript version: 11.3. Notes Create a FolderItemList and pass in the TS_ID from the TS_Folders table of the folder you would like. Keep in mind that a folder ID is needed to retrieve this list and the folder table contains an inbox for every user so it may be a bit of processing to find the correct TS_ID from the TS_Folders table before this method can be used effectively. Related Topics AppDb [page 142]

GetDbType()

Returns the database connection type.

Function Signature

int GetDbType()

Parameters

Parameter Type Description

None

SBM ModScript Reference Guide 147 Chapter 3: Programming SBM ModScript

Return

Type Description

int • Oracle: 1

• SQL Server: 2

• Import Source DB possible values: ▪ Access: 3

▪ Sybase: 4

▪ DB2: 5

Technical Details SBM ModScript version: 11.3. Example

var myDbType = Shell.Db().GetDbType();

Notes None. Related Topics AppDb [page 142]

IsMSSQL()

Returns true if database connection is SQL Server.

Function Signature

bool IsMSSQL()

Parameters

Parameter Type Description

None

148 Solutions Business Manager (SBM) Return

Type Description

bool Returns true if database connection is SQL Server.

Technical Details SBM ModScript version: 11.3. Example if( Shell.Db().IsMSSQL() ){ Ext.WriteStream( "The Db is MSSQL" );}

Result:

The Db is MSSQL

Notes None. Related Topics AppDb [page 142]

IsOracle()

Returns true if database connection is Oracle.

Function Signature

bool IsOracle()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if database connection is Oracle.

Technical Details SBM ModScript version: 11.3.

SBM ModScript Reference Guide 149 Chapter 3: Programming SBM ModScript

Example

if(Shell.Db().IsOracle()){ Ext.WriteStream( "The Db is Oracle" );}

Result:

The Db is Oracle

Notes None. Related Topics AppDb [page 142]

ReadIntWithSQL()

(SBM On-Premise/PaaS only) Reads any single integer out of the database.

Function Signature

int ReadIntWithSQL( sqlText [, Vector params] )

Parameters

Parameter Type Description

sqlText string The SQL to pass in.

params Vector An optional Vector storing SQL bind parameters, where each entry is a Pair, with the first value as the parameter type and the second value as the value to bind to the SQL parameter. Corresponds to DBTypeConstants [page 347]. See Pair, Map_Pair, and Dictionary_Pair [page 123].

Return

Type Description

int The int value from the database.

Technical Details SBM ModScript version: 11.3.

150 Solutions Business Manager (SBM) Example

Shell.Db().ReadIntWithSQL( "select TS_SOLUTIONID from TS_TABLES where TS_ID=1000 and TS_TYPE=1" );

Or:

Shell.Db().ReadIntWithSQL( "select TS_ID from TS_TABLES where TS_DBNAME=? and TS_TYPE=?", [ Pair(DBTypeConstants.VARCHAR,"UBG_ISSUES"), Pair(DBTypeConstants.INTEGER,1)] );

Notes None. Related Topics AppDb [page 142]

ReadTextWithSQL()

(SBM On-Premise/PaaSonly) Reads any single varchar value, up to 256 characters, out of the database.

Function Signature

string ReadTextWithSQL( sqlText [, Vector params] )

Parameters

Parameter Type Description

sqlText string The SQL to invoke.

params Vector An optional Vector storing SQL bind parameters, where each entry is a Pair, with the first value as the parameter type and the second value as the value to bind to the SQL parameter. Corresponds to DBTypeConstants [page 347]. See Pair, Map_Pair, and Dictionary_Pair [page 123].

Return

Type Description

string The value that was read from the database.

Technical Details SBM ModScript version: 11.3.

SBM ModScript Reference Guide 151 Chapter 3: Programming SBM ModScript

Example

Shell.Db.ReadTextWithSQL( "select TS_DBNAME from TS_TABLES where TS_ID=1000 and TS_TYPE=1" );

Or:

Shell.Db.ReadTextWithSQL( "select TS_DBNAME from TS_TABLES where TS_ID=? and TS_TYPE=?", [ Pair(DBTypeConstants.INTEGER,1000), Pair(DBTypeConstants.INTEGER,1)] );

Notes None. Related Topics AppDb [page 142]

ReadIntegersWithSQL()

(SBM On-Premise/PaaS only) Reads multiple rows of a single integer column from the database, filling the Vector "out".

Function Signature

bool ReadIntegersWithSQL( sqlText, Vector& out, [, Vector params] )

Parameters

Parameter Type Description

sqlText string The SQL to invoke.

out Vector& The results of the query. Each entry in the Vector will be an int.

params Vector An optional Vector storing SQL bind parameters, where each entry is a Pair, with the first value as the parameter type and the second value as the value to bind to the SQL parameter. Corresponds to DBTypeConstants [page 347]. See Pair, Map_Pair, and Dictionary_Pair [page 123].

152 Solutions Business Manager (SBM) Return

Type Description

bool Returns true if successful; false otherwise. A successful read may return zero results if no items match the query. Check for results by calling the Vector.empty() method.

Technical Details SBM ModScript version: 11.3. Example var v = []; Shell.Db.ReadIntegersWithSQL( "select TS_SOLUTIONID from TS_TABLES where TS_TYPE=1", v ); Shell.Db.ReadIntegersWithSQL( "select TS_SOLUTIONID from TS_TABLES where TS_TYPE=?", v, [Pair(DBTypeConstants.INTEGER,1)] );

Notes None. Related Topics AppDb [page 142]

ReadTextValsWithSQL()

(SBM On-Premise/PaaS only) Reads multiple rows of a single text column from the database, filling the Vector "out".

Function Signature

bool ReadTextValsWithSQL( sqlText, Vector& out, [, Vector params] )

Parameters

Parameter Type Description

sqlText string The SQL to invoke.

out Vector& The results of the query. Each entry in the Vector will be a string.

SBM ModScript Reference Guide 153 Chapter 3: Programming SBM ModScript

Parameter Type Description

params Vector An optional Vector storing SQL bind parameters, where each entry is a Pair, with the first value as the parameter type and the second value as the value to bind to the SQL parameter. Corresponds to DBTypeConstants [page 347]. See Pair, Map_Pair, and Dictionary_Pair [page 123].

Return

Type Description

bool Returns true if successful; false otherwise. A successful read may return zero results if no items match the query. Check for results by calling the Vector.empty() method.

Technical Details SBM ModScript version: 11.3. Example

var v = []; Shell.Db.ReadTextValsWithSQL( "select TS_DBNAME from TS_TABLES where TS_TYPE=1", v ); Shell.Db.ReadTextValsWithSQL( "select TS_DBNAME from TS_TABLES where TS_TYPE=?", v, [Pair(DBTypeConstants.INTEGER,1)] );

Notes None. Related Topics AppDb [page 142]

ReadIntegerPairsWithSQL()

(SBM On-Premise/PaaS only) Reads multiple rows of two integer columns from the database, filling the Vector "out" with Pair values.

Function Signature

bool ReadIntegerPairsWithSQL( sqlText, Vector& out, [, Vector params] )

154 Solutions Business Manager (SBM) Parameters

Parameter Type Description

sqlText string The SQL to invoke.

out Vector& The results of the query. Each entry in the Vector will be a Pair of int values. See Pair, Map_Pair, and Dictionary_Pair [page 123].

params Vector An optional Vector storing SQL bind parameters, where each entry is a Pair, with the first value as the parameter type and the second value as the value to bind to the SQL parameter. Corresponds to DBTypeConstants [page 347]. See Pair, Map_Pair, and Dictionary_Pair [page 123].

Return

Type Description

bool Returns true if successful; false otherwise. A successful read may return zero results if no items match the query. Check for results by calling the Vector.empty() method.

Technical Details SBM ModScript version: 11.3. Example var v = []; Shell.Db().ReadIntegerPairsWithSQL( "select TS_ID, TS_SOLUTIONID from TS_TABLES where TS_TYPE=1", v ); Shell.Db().ReadIntegerPairsWithSQL( "select TS_ID, TS_SOLUTIONID from TS_TABLES where TS_TYPE=?", v, [Pair(DBTypeConstants.INTEGER,1)] );

Notes None. Related Topics AppDb [page 142]

ReadDynaSQL()

(SBM On-Premise/PaaS only) Reads multiple rows of a set of columns from the database, filling the Vector "out".

SBM ModScript Reference Guide 155 Chapter 3: Programming SBM ModScript

Function Signature

bool ReadDynaSQL ( sqlText, Vector sqlColumns, Vector& out [, Vector params] )

Parameters

Parameter Type Description

sqlText string The SQL to invoke.

sqlColumns Vector A Vector storing SQL output column definitions, where each entry is a SQLColumnDef [page 281].

out Vector& The results of the query. Each entry in the Vector will be a Vector; each entry in that Vector is specified by the type from the corresponding entry in sqlColumns. For instance, if sqlColumns has a DBConstants.INTEGER and a DBConstants.VARCHAR, each entry in the out Vector will be a Vector that contains an int and a string.

params Vector An optional Vector storing SQL bind parameters, where each entry is a Pair, with the first value as the parameter type and the second value as the value to bind to the SQL parameter. Corresponds to DBTypeConstants [page 347]. See Pair, Map_Pair, and Dictionary_Pair [page 123].

Return

Type Description

bool Returns true if successful; false otherwise. A successful read may return zero results if no items match the query. Check for results by calling the Vector.empty() method.

Technical Details SBM ModScript version: 11.4. Example

var out = []; // creates an empty Vector

Shell.Db().ReadDynaSQL( "select TS_ID,TS_NAME,TS_LASTLOGINDATE from TS_USERS where TS_STATUS=? order by TS_NAME", [ SQLColumnDef(DBTypeConstants.INTEGER,"TS_ID"), SQLColumnDef(DBTypeConstants.VARCHAR,"TS_NAME"),

156 Solutions Business Manager (SBM) SQLColumnDef(DBTypeConstants.BIGINT,"TS_LASTLOGINDATE", SQLColumnDefOutputHint.TimeT) ], out, [Pair(DBTypeConstants.INTEGER, 0)] ); for ( row : out ){ Ext.WriteStream( "${row[0]}\t${row[1]}\t${row[2].date}" ); }

Notes None. Related Topics AppDb [page 142]

WriteBlobToFile()

(SBM On-Premise only) Get the contents of a blob written to the file system.

Function Signature

bool WriteBlobToFile( blobID, filepath )

Parameters

Parameter Type Description

blobID int The TS_ID of the blob from the TS_BLOBS table.

filepath string The full file name and path to write the file to.

Return

Type Description

bool Returns true if successful; false otherwise.

Technical Details SBM ModScript version: 11.3. Example var blobWrite = Shell.Db().WriteBlobToFile( 36976, "C:\\AppScript\\BlobFile.txt" );

Notes A common case is to invoke WriteBlobToFile(), and then write changes to the file, finally updating the blob with the changes using UpdateBlobFromFile().

SBM ModScript Reference Guide 157 Chapter 3: Programming SBM ModScript

Use Ext.ReadTextFile, Ext.WriteTextFile, and Ext.AppendTextFile to interact with the file. Tip: Optionally, use with TempFile to ensure that the file is deleted once the script is completed.

Related Topics AppDb [page 142] UpdateBlobFromFile() [page 158] TempFile [page 282]

UpdateBlobFromFile()

(SBM On-Premise only) Put a file's contents into a blob.

Function Signature

bool UpdateBlobFromFile( blobID, filepath )

Parameters

Parameter Type Description

blobID int The TS_ID of the blob from the TS_BLOBS table.

filepath string The full file name and path to read the file from.

Return

Type Description

bool Returns true if successful; false otherwise.

Technical Details SBM ModScript version: 11.3. Example

var blobRead = Shell.Db.UpdateBlobFromFile( 36977, "C:\\AppScript\\BlobFile.txt" );

Notes A common case is to invoke WriteBlobToFile(), and then write changes to the file, finally updating the blob with the changes using UpdateBlobFromFile(). Use Ext.ReadTextFile, Ext.WriteTextFile, and Ext.AppendTextFile to interact with the file.

158 Solutions Business Manager (SBM) Related Topics AppDb [page 142] WriteBlobToFile() [page 157]

UserId()

Gets the current user's TS_ ID.

Function Signature

int UserId()

Parameters

Parameter Type Description

None

Return

Type Description

int The TS_ID of the current user from the TS_USERS table.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics AppDb [page 142] AppRecord Description AppRecord is the base object type for the majority of SBM objects. An AppRecord can represent any row of any table from the current Application Engine schema. The table is specified by a numeric table ID which must be supplied when the AppRecord is created using Ext.CreateAppRecord(). For details on Ext.CreateAppRecord, refer to Ext.CreateAppRecord() [page 66]. For details on working with SBM database records, refer to Working with SBM Database Records [page 37]. After an AppRecord has been created for a specific table, its methods can retrieve data from any row of that table. However, the AppRecord can never be used with a different table; you must create a separate AppRecord object for that purpose.

SBM ModScript Reference Guide 159 Chapter 3: Programming SBM ModScript

When discussions of AppRecord objects refer to the "table ID of the current item", it refers to the table ID that was specified when the AppRecord was created. Use Ext.TableId() to find the table ID for the desired table. AppRecord has child classes for certain tables, including VarRecord and ProjectBasedRecord for auxiliary and primary tables. Inheritance AppRecord does not inherit from any object type. Methods • Add() [page 161]

• Delete() [page 162]

• Fields() [page 163]

• GetDisplayName() [page 164]

• GetFieldValue() [page 164]

• GetFieldValue-type-() [page 166]

• GetId() [page 168]

• GetUUID() [page 169]

• GetName() [page 169]

• GetRecTableId() [page 170]

• GetSchemaColumns() [page 171]

• HasVariableDBFields() [page 173]

• IsFieldEqual() [page 174]

• IsLocked() [page 175]

• Lock() [page 175]

• Read() [page 176]

• ReadWithWhere() [page 177]

• ReadByColumn() [page 178]

• ReadByColumnAndColumn() [page 180]

• ReadByUUID() [page 181]

• SetFieldValue() [page 182]

• SetName() [page 183]

• Unlock() [page 184]

160 Solutions Business Manager (SBM) • Update() [page 185]

• UpdateWithLock() [page 186]

Add()

(SBM On-Premise/PaaS only) Adds a new row to a table.

Function Signature

int Add()

Parameters

Parameter Type Description

None

Return

Type Description

int The TS_ID of the record added, which is unique to this table. Zero means the record could not be added due to an error.

Technical Details SBM ModScript version: 11.3. Example

var tableId = Ext.TableId("TS_CONTACTS"); var myRecord = Ext.CreateAppRecord(tableId); var myRecord.SetFieldValue("CONTACTLASTNAME", "Smith"); var ret = myRecord.Add(); if (ret == 0){ Ext.LogErrorMsg("Error adding Contact."); }

Notes After creating an AppRecord from the desired table and setting any desired field values, use this method to add the record as a new row in its table. This is not for use with Primary tables, because those items must go through a Submit transition. However, it is possible to make a copy of a Primary table item using this method. Note: Changes to cached items written with the Add() method are not immediately available to other SBM servers that are connected to the same database. The other servers see these changes when the cache periodically synchronizes with the database. The time interval for cache updates can be configured and defaults to twenty seconds.

SBM ModScript Reference Guide 161 Chapter 3: Programming SBM ModScript

Related Topics AppRecord [page 159]

Delete()

(SBM On-Premise/PaaS only) Removes a record from the database.

Function Signature

bool Delete()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if the record is deleted from or marked as deleted in the database.

Technical Details SBM ModScript version: 11.3. Example

var tableId = Ext.TableId("TS_CONTACTS"); var myRecord = Ext.CreateAppRecord(tableId); var whereClause = "TS_CONTACTFIRSTNAME = 'Joe'"; if (myRecord.ReadWithWhere(whereClause)) { if (!myRecord.Delete()) { Ext.LogErrorMsg("Error Deleting Contact record."); } else { Ext.WriteStream( "The Contact record \"Joe\" was deleted" ); } }

Notes On most tables, this method removes the record from the database. On tables such as States and Users, the records are marked as deleted but remain in the database.

162 Solutions Business Manager (SBM) CAUTION: This method immediately deletes the record. The user is not asked to verify deletion.

Related Topics AppRecord [page 159]

Fields()

Returns a VarFieldList containing all fields for a VarRecord.

Function Signature

VarFieldList Fields()

Parameters

Parameter Type Description

None

Return

Type Description

VarFieldList The list of fields from this AppRecord. If there is no FieldList for this record, this method returns null. Use is_var_null() to check for null.

Technical Details SBM ModScript version: 11.3. Notes AppRecords from an Auxiliary or Primary table have a variable field list. That is, their fields can be defined using SBM Composer. The Fields() method returns a VarFieldList object containing all such fields. For AppRecords from tables without a variable field list, this method returns the global constant Nothing. See the VarFieldList object for details on manipulating field data. Note: It is not recommended to use this method with VarRecords (objects based on primary/auxiliary tables). For non-VarRecords, use the AppRecord.GetFieldValue() and AppRecord.SetFieldValue() methods. Related Topics AppRecord [page 159]

SBM ModScript Reference Guide 163 Chapter 3: Programming SBM ModScript

GetDisplayName()

Returns the display name of a record.

Function Signature

string GetDisplayName()

Parameters

Parameter Type Description

None

Return

Type Description

string This record's display name, formatted according to table settings.

Technical Details SBM ModScript version: 11.3. Notes Every database table has a display name format. SBM Composer enables you to define display name formats for Primary and Auxiliary tables. For other tables, the display name is found in the TS_NAME column. Related Topics AppRecord [page 159]

GetFieldValue()

Gets the value of any field.

Function Signature

bool GetFieldValue( name, string& value)

bool GetFieldValue( name, int& value)

bool GetFieldValue( name, int64_t& value)

bool GetFieldValue( name, double& value)

bool GetFieldValue( name, TimeT& value)

bool GetFieldValue( name, Variant& value)

164 Solutions Business Manager (SBM) Parameters

Parameter Type Description

name string The name of the field whose value will be retrieved from the variable field list or the AppRecord column. Field names for variable fields should be provided in uppercase characters for database names or in lowercase/mixed-case characters for display names (for Title, for example).

value string& (Output) Returns the internal value for a field or column. For Text fields, this is the exact value entered in the field; int& for selection fields, the value is the database ID for the int64_t& selection. For values that are not Variant or TimeT, this internally gets the value from the field as a Variant, and double& then tries to convert the value to the requested type. TimeT& TimeT can be used with Date/Time fields to get the Variant& internal date value. Note: If the field is a Multi-User field for which the Groups and Users selection mode is enabled, the value can include both pure integers (TS_IDs from the TS_USERS table) and group identifiers (TS_IDs from the TS_GROUPS table). The latter are in the form G1, G2, …

Return

Type Description

bool Returns true if the named field was found successfully; false otherwise.

Technical Details SBM ModScript version: 11.3. Example

//Create and retrieve Project record var tableId = Ext.TableId("TS_PROJECTS"); var myRecord = Ext.CreateAppRecord(tableId); var ok = myRecord.Read("Image Builder"); var value = 0; // initializes value as integer if ( ok ) { ok = myRecord.GetFieldValue( "parentid", value ); } if ( ok ) { Ext.LogInfoMsg ("Parent ID of Image Builder is " &&& value); }

SBM ModScript Reference Guide 165 Chapter 3: Programming SBM ModScript

else { Ext.LogErrorMsg( "Unable to get Parent ID of " + "Image Builder project" ); }

Notes Also see GetFieldValue-type-() [page 166]. If the calling AppRecord is an item from a Primary or Auxiliary table, its variable field list is searched. Otherwise, the schema for its table is searched. Related Topics AppRecord [page 159]

GetFieldValue-type-()

Gets the value of a field in the calling record's variable field list.

Function Signature

string GetFieldValueString( name )

int GetFieldValueInt( name )

int64_t GetFieldValueInt64( name )

double GetFieldValueDouble( name )

TimeT GetFieldValueTimeT( name )

Variant GetFieldValue( name )

Parameters

Parameter Type Description

name string The name of the field whose value will be retrieved from the calling record's variable field list or the AppRecord column. Field names for variable fields should be provided in upper case for database names (TITLE, for example) or in lower/ mixed-case for display names (Title, for example). For details on working with different types of database fields, refer to Working with SBM Database Fields [page 39].

166 Solutions Business Manager (SBM) Return

Type Description

string The internal value for the field. For Text fields, this is the exact value entered in the field. int int64_t double TimeT Variant

Technical Details SBM ModScript version: 11.3. Signatures where return is not Variant were added in 11.4 and moved from VarRecord to AppRecord in 11.6. Example Example with AppRecord:

//Create and retrieve Project record var tableId = Ext.TableId("TS_PROJECTS"); var myRecord = Ext.CreateAppRecord(tableId); var ok = myRecord.Read("Image Builder"); if ( ok != 0 ) { var value = myRecord.GetFieldValueInt( "parentid" ); Ext.LogInfoMsg ("Parent ID of Image Builder is " &&& value); }

Example with VarRecord:

// Create and retrieve Contact record var myRecord = Ext.CreateVarRecord (Ext.TableId ("TS_CONTACTS")); var ok = myRecord.ReadWithWhere ("TS_CONTACTFIRSTNAME like 'Joe'"); // If no e-mail address, supply default value if ( ok ) { var value = myRecord.GetFieldValueString( "EMAIL" ); if ( value == "" ) { ok = myRecord.SetFieldValue ( "EMAIL", "[email protected]" ); } } if ( !ok ) { Ext.LogErrorMsg ("Error in Joe's Email field"); }

SBM ModScript Reference Guide 167 Chapter 3: Programming SBM ModScript

Notes Also see GetFieldValue() [page 164]. Important: Only use this version of GetFieldValue() if you are sure that the field will be found. It is not recommended to use the Variant version of this method with dates; instead, use the GetFieldValueTimeT( name ) signature. Related Topics VarRecord [page 326]

GetId()

Retrieves the current AppRecord's TS_ID.

Function Signature

int GetId()

Parameters

Parameter Type Description

None

Return

Type Description

int TS_ID of the calling AppRecord.

Technical Details SBM ModScript version: 11.3. Example

//Create a Contact record var tableId = Ext.TableId ("TS_CONTACTS"); var myRecord = Ext.CreateAppRecord(tableId); var whereClause = "TS_CONTACTFIRSTNAME like 'Joe'"; var ContactTSID; if(myRecord.ReadWithWhere(whereClause)) { //Read the TS_ID of the record ContactTSID = myRecord.GetId(); }

Notes Note that TS_ID is uninitialized on a newly-created object. This method will only return a meaningful result if the calling object has been read from or written to the database.

168 Solutions Business Manager (SBM) Related Topics AppRecord [page 159]

GetUUID()

Returns the item's UUID, if applicable.

Function Signature

string GetUUID()

Parameters

Parameter Type Description

None

Return

Type Description

string The item's UUID.

Technical Details SBM ModScript version: 11.3. Example

var itemUUID = record.GetUUID();

Notes None. Related Topics AppRecord [page 159]

GetName()

Gets the calling AppRecord's "Name" system field.

Function Signature

string GetName()

SBM ModScript Reference Guide 169 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

None

Return

Type Description

string A text string from the associated Name field.

Technical Details SBM ModScript version: 11.3. Example

//Create a Contact record var tableId = Ext.TableId ("TS_CONTACTS"); var myRecord = Ext.CreateAppRecord(tableId); var whereClause = "TS_CONTACTFIRSTNAME like 'Joe'"; var name = ""; if(myRecord.ReadWithWhere(whereClause)) { /*On the contact record, this will return back the contact's full name */ name = myRecord.GetName(); }

Notes For more details on the Name system field, refer to Working with SBM Database Records [page 37]. Related Topics AppRecord [page 159]

GetRecTableId()

Returns the calling AppRecord's table ID.

Function Signature

int GetRecTableId()

170 Solutions Business Manager (SBM) Parameters

Parameter Type Description

None

Return

Type Description

int The calling AppRecord's table ID.

Technical Details SBM ModScript version: 11.3. Example

var tableId = Ext.TableId ("TS_CONTACTS"); var myRecord = Ext.CreateAppRecord(tableId); var result = myRecord.GetRecTableId(); if(result != tableId) { Ext.LogInfoMsg("Error was expecting 'Contacts' to be table " + tableId); }

Notes None. Related Topics AppRecord [page 159]

GetSchemaColumns()

Returns a Vector of SchemaColumn objects. Will not include fields for VarRecord or ProjectBasedRecord objects.

Function Signature

Vector GetSchemaColumns()

Parameters

Parameter Type Description

None

SBM ModScript Reference Guide 171 Chapter 3: Programming SBM ModScript

Return

Type Description

Vector Each entry will be a SchemaColumn object representing a column in the database that this item can interact with. For details, see SchemaColumn [page 280].

Technical Details SBM ModScript version: 11.3. Example

def getDBTypeNameText( type ) { switch( type ) { case(DBTypeConstants.BIGINT) { return "BigInteger"; } case(DBTypeConstants.INTEGER) { return "Integer"; } case(DBTypeConstants.SMALLINT) { return "SmallInteger"; } case(DBTypeConstants.TINYINT) { return "TinyInteger"; } case(DBTypeConstants.DOUBLE) { return "Double"; } case(DBTypeConstants.FLOAT) { return "Float"; } case(DBTypeConstants.DATETIME) { return "Datetime"; } case(DBTypeConstants.DECIMAL) { return "Decimal"; } case(DBTypeConstants.NUMERIC) { return "Numeric"; } case(DBTypeConstants.CHAR) { return "Char"; } case(DBTypeConstants.VARCHAR) { return "Varchar"; } case(DBTypeConstants.LONGVARCHAR) { return "LongVarchar"; } default {

172 Solutions Business Manager (SBM) return "Unknown type: ${schema.type}"; } } } var record = Ext.CreateAppRecord( Ext.TableId( "TS_USERS" ) ); for( schema : record.GetSchemaColumns() ){ Ext.WriteStream( schema.name + " | " + getDBTypeNameText( schema.type ) + " | " + schema.length + "
"); }

Result:

TS_ID | Integer | 4 TS_LOGINID | Varchar | 64 TS_PASSWORD | Varchar | 258 TS_NAME | Varchar | 64 TS_TELEPHONE | Varchar | 64 ...

Notes None. Related Topics AppRecord [page 159] SchemaColumn [page 280]

HasVariableDBFields()

Tests whether the calling AppRecord is from a table with variable fields.

Function Signature

bool HasVariableDBFields()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if the calling AppRecord's table has variable fields.

SBM ModScript Reference Guide 173 Chapter 3: Programming SBM ModScript

Technical Details SBM ModScript version: 11.3. Example Notes None. Related Topics AppRecord [page 159]

IsFieldEqual()

Tests for equivalence between the specified field and a value formatted as a string.

Function Signature

bool IsFieldEqual( fieldNameOrId, value )

Parameters

Parameter Type Description

fieldNameOrId string If a non-numeric string, the name of the field to be tested. Otherwise, it is converted to a number and taken as the integer TS_ID of the field to be tested.

value string The value to be compared to. The field's value will be formatted as a string and compared to this value.

Return

Type Description

bool Returns true if the field is found and is equal; false otherwise.

Technical Details SBM ModScript version: 11.3. Example Notes None. Related Topics AppRecord [page 159]

174 Solutions Business Manager (SBM) IsLocked()

Tests whether the calling AppRecord has been locked, meaning it is in use by another user.

Function Signature

bool IsLocked( [bool lockedByThisUser] )

Parameters

Parameter Type Description

lockedByThisUser bool Without an input parameter ( or with "false" as the input ), IsLocked() means "Does someone else have this record locked?" With "true" as the input parameter, the meaning is "May I (as the current user) update this record?"

Return

Type Description

bool Returns true if the record is locked by another user.

Technical Details SBM ModScript version: 11.3. Example Notes IsLocked() should return true if another user is using the item. If the item is locked by the current user who is calling IsLocked(), the return is false, which indicates that no one else can prevent an update to the item that was just locked. Related Topics AppRecord [page 159]

Lock()

(SBM On-Premise/PaaS only) Locks the calling AppRecord, so other users will not attempt to update it.

Function Signature

bool Lock( [bool stealLock] )

SBM ModScript Reference Guide 175 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

stealLock bool (Optional) Defaults to false, meaning if this item is already locked, no lock will be established. If true, any existing lock on this record will be broken, and changes made by the former lock holder are lost.

Return

Type Description

bool Returns true if the record is locked by another user.

Technical Details SBM ModScript version: 11.3. Example Notes None. Related Topics AppRecord [page 159]

Read()

Looks up a row in the AppRecord's table.

Function Signature

bool Read( recordIdOrName )

Parameters

Parameter Type Description

recordIdOrName string If this is an int or string that SBM ModScript can convert to an int, it is taken as the value to search for in the TS_ID int column. All other parameter types are converted to a string and searched for in the Name system field.

176 Solutions Business Manager (SBM) Return

Type Description

bool Returns true if the TS_ID or name was found, in which case the calling AppRecord object becomes a copy of that row in the table.

Technical Details SBM ModScript version: 11.3. Example

//Create a Contact record var tableId = Ext.TableId ("TS_CONTACTS"); var myRecord = Ext.CreateAppRecord(tableId); if(! myRecord.Read("Smith")) { Ext.LogErrorMsg("Error looking for Contact with " + "TS_CONTACTLASTNAME of 'Smith'"); }

Notes If the table is cached by Application Engine, the record may be read from the cache instead of the database. Related Topics AppRecord [page 159]

ReadWithWhere()

(SBM On-Premise/PaaS only) Used to find a record by passing in a string containing a SQL "where" clause, not including the keyword "where".

Function Signature

bool ReadWithWhere( whereClause [, Vector queryParams] )

Parameters

Parameter Type Description

whereClause string The SQL "where" clause to find the specific record in the table, not including the keyword "where".

SBM ModScript Reference Guide 177 Chapter 3: Programming SBM ModScript

Parameter Type Description

queryParams Vector queryParams is an optional Vector storing SQL bind parameters, where each entry is a Pair, where the first value is the parameter type and the second value is the value to bind to the SQL parameter. See Pair, Map_Pair, and Dictionary_Pair [page 123]. For the type parameter, use DBTypeConstants [page 347].

Return

Type Description

bool Returns true if the method found the record, in which case the calling object becomes a copy of the record found. If more than one record is found, the first one is copied to the calling object.

Technical Details SBM ModScript version: 11.3. Example

var record = Ext.CreateAppRecord(Ext.TableId("TS_CONTACTS")); var whereClause = "TS_CONTACTFIRSTNAME = 'Joe'"; myRecord.ReadWithWhere(whereClause);

Or:

var record = Ext.CreateAppRecord(Ext.TableId("TS_GROUPS")); record.ReadWithWhere("TS_NAME = ?", [Pair(DBTypeConstants.VARCHAR,"Everyone")]);

Notes All fields will start with "TS_" and normal SQL syntax will apply. The calling object will become a copy of the first record found. This is the most general way of finding particular AppRecords. Related Topics AppRecord [page 159]

ReadByColumn()

Reads any record type by a column value.

Function Signature

bool ReadByColumn( columnName, value )

178 Solutions Business Manager (SBM) Parameters

Parameter Type Description

columnName string The database name of the column without the TS_ prefix.

value Variant Behavior depends on the Variant internal type: • string – ReadByColumn() will succeed if the column is a text column.

• int, int64_t, short, byte, or bool – ReadByColumn() will succeed if the column is an integer column.

• float or double – ReadByColumn() will succeed if the column is a floating point column.

Return

Type Description

bool Returns true if the item is read successfully; false if the item is not found.

Technical Details SBM ModScript version: 11.3. Example

var tableId = Ext.TableId( "TS_USERS" ); var record = Ext.CreateAppRecord( tableId ); if( record.ReadByColumn( "LOGINID", "joe" )){ var name = record.GetName(); Ext.WriteStream( "User is " + name ); }

Notes As the behavior depends on the Variant internal type, the functions CInt, CStr, and CDbl can be used to get a Variant with the desired internal type. If the table is cached by Application Engine, the record may be read from the cache instead of the database. Related Topics AppRecord [page 159]

SBM ModScript Reference Guide 179 Chapter 3: Programming SBM ModScript

ReadByColumnAndColumn()

Reads any record type by two column values.

Function Signature

bool ReadByColumnAndColumn( columnName, value, column2Name, value2 )

Parameters

Parameter Type Description

columnName string The name of the column without the "TS_" prefix.

value Variant Value must be an int, int64_t, short, byte, bool, or string that can be converted to an int.

column2Name string The name of the second column without the "TS_" prefix.

value2 Variant Behavior depends on the Variant internal type: • string – ReadByColumn() will succeed if the column is a text column.

• int, int64_t, short, byte, or bool – ReadByColumn() will succeed if the column is an integer column.

• float or double – Not supported.

Return

Type Description

bool Returns true if the item is read successfully; false if the item is not found.

Technical Details SBM ModScript version: 11.3. Example

var tableId = Ext.TableId( "USR_APP_NAME" ); var record = Ext.CreateAppRecord( tableId ); var read = record.ReadByColumnAndColumn( "SUBMITTER", 27, "TITLE", "myTitle" ); if(read){ var name = record.GetName(); var itemId = record.GetId();

180 Solutions Business Manager (SBM) Ext.WriteStream( "The item is " + name + " " + itemId ); }

Notes As the behavior depends on the Variant internal type, the functions CInt, CStr, and CDbl can be used to get a Variant with the desired internal type. If the table is cached by Application Engine, the record may be read from the cache instead of the database. Related Topics AppRecord [page 159]

ReadByUUID()

Reads the item using the UUID column, if it exists.

Function Signature

ReadByUUID( itemUUID )

Parameters

Parameter Type Description

itemUUID string The UUID value that is passed in.

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Example var uuidRead = record.ReadByUUID(itemUUID);

Notes If the table is cached by Application Engine, the record may be read from the cache instead of the database. Related Topics AppRecord [page 159]

SBM ModScript Reference Guide 181 Chapter 3: Programming SBM ModScript

SetFieldValue()

(SBM On-Premise/PaaS only) Sets the value of any column.

Function Signature

bool SetFieldValue( name, string& value )

bool SetFieldValue( name, int& value )

bool SetFieldValue( name, int64_t& value )

bool SetFieldValue( name, double& value )

bool SetFieldValue( name, TimeT& value )

bool SetFieldValue( name, Variant& value )

Parameters

Parameter Type Description

name string The name of the column whose value will be set in the AppRecord schema.

value string& (Input/Output) The new value for the column. The value must be specified as it is stored in the database. For int& example, for integer columns that are a foreign key to the int64_t& TS_USERS table, the value must be the database ID for the user. TimeT values should only be used with columns double& that represent dates, either as a native database date or TimeT& as a integer that represents dates in Unix Epoch time format. Variant&

Return

Type Description

bool Returns true if the column value was successfully set; false otherwise.

Technical Details SBM ModScript Variant version added in 11.3. TimeT version added in 11.4. Others added in 11.6.

182 Solutions Business Manager (SBM) Example Notes This SetFieldValue() method specifically relates to AppRecords that are used for system table records. For auxiliary and primary table records, see SetFieldValue() [page 332].

CAUTION: It is strongly recommended that you consult the SBM schema document before using the SetFieldValue method.

Related Topics AppRecord [page 159]

SetName()

(SBM On-Premise/PaaS only) Sets the "name" value of the calling object.

Function Signature

void SetName( newName )

Parameters

Parameter Type Description

newName string Text to be used as the new name for the item.

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Example

//Create a Company record var myRecord = Ext.CreateAppRecord( Ext.TableId ( "TS_COMPANIES" )); var whereClause = "TS_NAME = 'ABC'" var bOk = myRecord.ReadWithWhere( whereClause ); if( bOk ) { //Set the name of the company to "XYZ" myRecord.SetName("XYZ"); //Commit change to database

SBM ModScript Reference Guide 183 Chapter 3: Programming SBM ModScript

myRecord.UpdateWithLock( true ); }

Notes This method sets the "name" value of the calling object. For system tables, this is the "TS_NAME" column. For primary and auxiliary tables, this is the column that corresponds to the "name" system field. For more details on the "name" system field, refer to Working with SBM Database Records [page 37]. Related Topics AppRecord [page 159]

Unlock()

(SBM On-Premise/PaaS only) Unlocks the calling AppRecord, signaling that it is available for other users.

Function Signature

bool Unlock( [bool currentUserOnly] )

Parameters

Parameter Type Description

currentUserOnly bool (Optional) Defaults to false. If true, only the current user's lock is unlocked. If false, any user's lock on this record is removed.

Return

Type Description

bool Returns true if the record was successfully unlocked or was not locked to begin with.

Technical Details SBM ModScript version: 11.3. Example Notes None. Related Topics AppRecord [page 159]

184 Solutions Business Manager (SBM) Update()

(SBM On-Premise/PaaS only) This method updates the item in the database using the values from the item.

Function Signature

bool Update()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if the record is updated in the database.

Technical Details SBM ModScript version: 11.3. Example

// Create a Contact record var tableId = Ext.TableId("TS_CONTACTS"); var myRecord = Ext.CreateAppRecord(tableId); var whereClause = "TS_CONTACTFIRSTNAME = 'Joe'"; if( myRecord.ReadWithWhere(whereClause) ) { // Get a lock, set the value, update and unlock var locked = myRecord.Lock(); myRecord.SetFieldValue("CONTACTLASTNAME", "Smith"); myRecord.Update(); var unlocked = myRecord.Unlock(); }

Notes The values of all fields in the calling AppRecord are written to the database. Any fields that the current user has privileges to update may be modified and the Update method commits them to the database. This method modifies an existing record, based on the TS_ID of the calling AppRecord. To add a new record, see the Add() method.

SBM ModScript Reference Guide 185 Chapter 3: Programming SBM ModScript

For VarRecords, this method replicates the functionality of the system Update transition. Note: During Post-Transition, Post-State, and Pre-State scripts, it is not necessary to call Shell.Item().Update() because the system always calls Update after the script finishes. However, if you create any other AppRecord objects, you will need to call Update on those each of those objects; the system always calls Update only for Shell.Item(). Changes to cached items written with this method are not immediately available to other SBM servers that are connected to the same database. The other servers see these changes when the cache periodically synchronizes with the database. The time interval for cache updates can be configured and defaults to twenty seconds. Related Topics AppRecord [page 159] UpdateWithLock() [page 186]

UpdateWithLock()

(SBM On-Premise/PaaS only) Updates the record that has been previously locked with Lock() function.

Function Signature

bool UpdateWithLock( [bool stealLock] )

Parameters

Parameter Type Description

stealLock bool Optional parameter that allows the user to skip the Lock() function and steal the lock during the update. Defaults to false. If true, any other user's existing lock will be broken, causing that user's changes to be lost.

Return

Type Description

bool Returns true if the record was successfully updated; false otherwise.

Technical Details SBM ModScript version: 11.3. Notes None.

186 Solutions Business Manager (SBM) Related Topics AppRecord [page 159] Update() [page 185] AppRecordList Description An AppRecordList contains a list of AppRecords of any subtype. The AppRecord objects on a single AppRecordList need not be from the same table or of the same AppRecord subtype, though homogeneous lists are easier to work with. AppRecordList, and all child classes, can be iterated using ChaiScript's for loop. See example in ReadWithWhere() [page 193]. Inheritance AppRecordList does not inherit from any object type. Methods • Count() [page 187]

• DeleteRecord() [page 188]

• FindRecord() [page 189]

• Length() [page 189]

• Read() [page 190]

• ReadByColumn() [page 191]

• ReadByColumnAndColumn() [page 192]

• ReadWithWhere() [page 193]

• LinkText [page 195]

• empty() [page 196]

• erase_at() [page 196]

• size() [page 197]

• Update() [page 198]

Count()

Returns the number of items in the list.

Function Signature

int Count()

SBM ModScript Reference Guide 187 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

None

Return

Type Description

int The number of items in the list.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics AppRecordList [page 187]

DeleteRecord()

Removes the specified record from the list.

Function Signature

void DeleteRecord( recordId )

Parameters

Parameter Type Description

recordId int The TS_ID of the record to delete from the list.

Return

Type Description

None

Technical Details SBM ModScript version: 11.3.

188 Solutions Business Manager (SBM) Notes None. Related Topics AppRecordList [page 187]

FindRecord()

Find a specific record in the current list by matching its name or TS_ID.

Function Signature

AppRecord FindRecord( Variant recordIdOrName )

Parameters

Parameter Type Description

recordIdOrName Variant If this parameter is a non-numeric string, it is taken as the desired record's name. Otherwise, it is converted to an integer and taken as the desired record's TS_ID.

Return

Type Description

AppRecord The first AppRecord in the list that matches the given name or ID. If there is no match, returns null. Use is_var_null() to check for null.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics AppRecordList [page 187]

Length()

Returns the number of items in the list.

Function Signature

int Length()

SBM ModScript Reference Guide 189 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

None

Return

Type Description

int The number of items in the list.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics AppRecordList [page 187]

Read()

Fills the AppRecordList from its table.

Function Signature

bool Read()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if successful; false otherwise. A successful read may return zero results if no items match the query. Check for results by calling the AppRecordList.empty() method.

190 Solutions Business Manager (SBM) Technical Details SBM ModScript version: 11.3. Example

var prjList = Ext.CreateAppRecordList( Ext.TableId( "TS_PROJECTS" )); var readOK = prjList.Read();

Notes None. Related Topics AppRecordList [page 187]

ReadByColumn()

Reads any record list type by a column value.

Function Signature

bool ReadByColumn( columnName, value )

Parameters

Parameter Type Description

columnName string The name of the column without the "TS_" prefix.

value Variant Behavior depends on the Variant internal type: • string – ReadByColumn() will succeed if the column is a text column.

• int, int64_t, short, byte, or bool – ReadByColumn() will succeed if the column is an integer column.

• float or double – ReadByColumn() will succeed if the column is a floating point column.

Return

Type Description

bool Returns true if successful; false otherwise. A successful read may return zero results if no items match the query. Check for results by calling the AppRecordList.empty() method.

SBM ModScript Reference Guide 191 Chapter 3: Programming SBM ModScript

Technical Details SBM ModScript version: 11.3. Notes As the behavior depends on the Variant internal type, the functions CInt, CStr, and CDbl can be used to get a Variant with the desired internal type. If the table is cached by Application Engine, the record may be read from the cache instead of the database. Related Topics AppRecordList [page 187]

ReadByColumnAndColumn()

Reads any record list type by two column values.

Function Signature

bool ReadByColumnAndColumn( columnName, value, column2Name, value2 )

Parameters

Parameter Type Description

columnName string The name of the column without the "TS_" prefix.

value Variant Value must be an int, int64_t, short, byte, bool, or string that can be converted to an int.

column2Name string The name of the second column without the "TS_" prefix.

value2 Variant Behavior depends on the Variant internal type: • string – ReadByColumn() will succeed if the column is a text column.

• int, int64_t, short, byte, or bool – ReadByColumn() will succeed if the column is an integer column.

• float or double – Not supported.

192 Solutions Business Manager (SBM) Return

Type Description

bool Returns true if successful; false otherwise. A successful read may return zero results if no items match the query. Check for results by calling the AppRecordList.empty() method.

Technical Details SBM ModScript version: 11.3. Notes As the behavior depends on the Variant internal type, the functions CInt, CStr, and CDbl can be used to get a Variant with the desired internal type. If the table is cached by Application Engine, the record may be read from the cache instead of the database. Related Topics AppRecordList [page 187]

ReadWithWhere()

(SBM On-Premise/PaaS only) An alternative to Read(), this method uses SQL to select only certain records from the calling AppRecordList's table, rather than reading the entire table.

Function Signature

bool ReadWithWhere( whereClause )

bool ReadWithWhere( whereClause, orderBy )

bool ReadWithWhere( whereClause, orderBy , AppRecord templateRec )

bool ReadWithWhere( whereClause, Vector params )

bool ReadWithWhere( whereClause, Vector params, orderBy )

bool ReadWithWhere( whereClause, Vector params, orderBy, AppRecord templateRec )

SBM ModScript Reference Guide 193 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

whereClause string A SQL "where clause" specifying the records to find. SBM will build a SQL string requesting all fields for the calling AppRecordList's table. The string contents of whereClause will appear after the word "where" in this SQL statement.

params Vector Params is an optional Vector storing SQL bind parameters, where each entry is a Pair, with the first value as the parameter type and the second value as the value to bind to the SQL parameter. See Pair, Map_Pair, and Dictionary_Pair [page 123]. For the type parameter, use DBTypeConstants [page 347].

orderBy string Identifies a column used for ordering the AppRecordList. To use the templateRec parameter without the orderBy parameter, use an empty string as a parameter for the orderBy parameter.

templateRec AppRecord Optional. Identifies which fields are read into all AppRecords in the AppRecordList. Using this parameter may improve performance when using AppRecordOjbects which contain a VarFieldList from Primary or Auxiliary tables. To use this optional parameter, create a VarRecord against the Primary table you are doing your ReadWithWhere against. Get the VarFieldList of that VarRecord through the Fields() method. Call SelectAll, and pass it false to clear all fields. Then, explicitly turn on the fields you wish to read by finding the Field on the VarFieldList, and then calling that Field's Select() method and passing it true.

Return

Type Description

bool Returns true if successful; false otherwise. A successful read may return zero results if no items match the query. Check for results by calling the AppRecordList.empty() method.

194 Solutions Business Manager (SBM) Technical Details SBM ModScript version: 11.3. Example

/*ReadWithWhere with optional "params" parameter and using DBTypeConstants*/ var list = Ext.CreateAppRecordList(Ext.TableId("UBG_ISSUES")); list.ReadWithWhere("TS_ID between ? and ?", [ Pair(DBTypeConstants.INTEGER,3), Pair(DBTypeConstants.INTEGER,20)], "TS_TITLE ASC" ); for (item : list) { Ext.WriteStream("Item: " + item.GetName()); }

Notes None. Related Topics AppRecordList [page 187]

clear()

Removes all records from the list.

Function Signature

void clear()

Parameters

Parameter Type Description

None

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Notes None.

SBM ModScript Reference Guide 195 Chapter 3: Programming SBM ModScript

Related Topics AppRecordList [page 187]

empty()

Returns true if the list is empty.

Function Signature

bool empty()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if the list is empty; false if there are items in the list.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics AppRecordList [page 187]

erase_at()

Removes the item at specified index from the list.

Function Signature

void erase_at( int index )

Parameters

Parameter Type Description

index int The zero-based index of the item to remove from the list.

196 Solutions Business Manager (SBM) Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics AppRecordList [page 187] size()

Returns the number of items in the list.

Function Signature

size_t size()

Parameters

Parameter Type Description

None

Return

Type Description

size_t The number of items in the list.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics AppRecordList [page 187]

SBM ModScript Reference Guide 197 Chapter 3: Programming SBM ModScript

Update()

(SBM On-Premise/PaaS only) Perform a database update on all records in the list.

Function Signature

bool Update()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if all applicable records are successfully updated; false otherwise.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics AppRecordList [page 187] Change Description (SBM On-Premise/PaaS only) Each time users modify an SBM table in the system using a browser, it is logged as a Change object in the TS_CHANGES table. This class is mainly used in conjunction with the ChangeList class. Once a change list is found for a table record, the ChangeList is a list of Change objects. This class can be used to access member variables that describe the change. You can read and write with this class by using the inherited AppRecord methods. All of the methods listed on this class directly relate to fields on the Changes table. Please see the SBM schema document for details of each of the fields. Inheritance AppRecord [page 159] -> Change

198 Solutions Business Manager (SBM) Properties • int Action() – Numeric code classifying the type of change, as listed in the Action Codes table.

Code Description

0 A record was submitted

1 A record was modified

2 A record was deleted

3 An attachment was added

4 An attachment was updated

5 An attachment was deleted

• int FldId() – TS_ID of the field that was modified during this change.

• int FldType() – Data type of the field that was modified during this change. ID Types are listed in the following table.

Type Description

100 Numeric field (integer or floating point)

101 Text field

103 Date/Time field

104 Drop-down Selection field

105 Binary/Trinary field

106 The system-defined State field (a selection field)

107 User field (a selection field)

108 System-defined Project field (a selection field)

SBM ModScript Reference Guide 199 Chapter 3: Programming SBM ModScript

Type Description

109 Calculated Summation fields

110 Multi-Selection field

111 Contact Selection field

113 Incident Selection field

116 Folder link Selection field

122 Relational field

123 Sub-Relational field

124 System field

125 Multi-Relational field

126 Multi-User field

127 Multi-Group field

• int IssueId() – TS_ID of the record that was modified. Use in conjunction with the TableId property to find the record.

• string NewChar() – If the modified field's data type was text, this field holds the field's value after the change. Check the Type property to determine whether this property is valid.

• int NewInt() – If the modified field's data type was an integer, this field holds the field's value after the change. Check the Type property to determine whether this property is valid.

• double NewReal() – If the modified field's data type was a floating point number, this field holds the field's value after the change. Check the Type property to determine whether this property is valid.

• string PriorChar() – If the modified field's data type was text, this field holds the field's value before the change. Check the Type property to determine whether this property is valid.

200 Solutions Business Manager (SBM) • int PriorInt() – If the modified field's data type was an integer, this field holds the field's value before the change. Check the Type property to determine whether this property is valid.

• double PriorReal() – If the modified field's data type was a floating point number, this field holds the field's value before the change. Check the Type property to determine whether this property is valid.

• int TableId() – Table ID of the record that was modified. Use in conjunction with the IssueId property to find the record.

• int64_t Time() – Returns the time that change was made, as the number of seconds since the beginning of Jan. 1, 1970. To get the time as a formatted string, use the GetTime property. To convert it to a Date quantity, use the TimeT [page 296] class.

• int Type() – Identifies the database type of the quantity that changed, according to the data types listed in the following table. If the quantity was an integer, then its old and new values are available in the PriorInt and NewInt properties. If it was a floating point number, then PriorReal and NewReal are valid. If it was text, then PriorChar and NewChar are valid.

ID Description

0 Modification to an integer

1 Modification to a floating point

2 Modification to a Text field

• int UserId() – TS_ID of the user who made the change. Use the GetUserName method if the name of the user is needed.

Methods • GetTime() [page 201]

• GetUserName() [page 202]

GetTime()

Returns the date and time of the change, formatted as a string.

Function Signature

string GetTime( [Variant format] )

SBM ModScript Reference Guide 201 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

format Variant (Optional) If int, a code telling how to format the date/time. If a User object, that user's date/time format preference will be used. If omitted, the format defaults as indicated in the following list. Valid int format codes: • 1 – mm/dd/YYYY hh:mm:ss pp (default)

• 2 – dd/mm/YYYY hh:mm:ss pp

("pp" denotes the AM/PM indicator)

Return

Type Description

string The date the change was created in the given format.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Change [page 198]

GetUserName()

Returns the display name of the user who made the change.

Function Signature

string GetUserName()

Parameters

Parameter Type Description

None

202 Solutions Business Manager (SBM) Return

Type Description

string The display name of the user who made the change.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Change [page 198] ChangeList Description A ChangeList is an AppRecordList that holds Change objects. Typically, a ChangeList represents the history of an SBM item, using the ReadWithWhere() method to read all Change records for a specific item. Inheritance AppRecordList [page 187] -> ChangeList DbImport Description (SBM On-Premise/PaaS only) DbImport is a class that contains values representing the source database values. For details on using DbImport, refer to Database Import Shell Properties [page 53]. Methods • SrcColumn() [page 203]

• SrcType() [page 204]

• SrcLabel() [page 205]

• DestFldId() [page 206]

• SrcData() [page 207]

SrcColumn()

The database column from the source database.

SBM ModScript Reference Guide 203 Chapter 3: Programming SBM ModScript

Function Signature

string SrcColumn()

Parameters

Parameter Type Description

None

Return

Type Description

string The name of column from the source database.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics DbImport [page 203]

SrcType()

The database column type from the source database.

Function Signature

int SrcType()

Parameters

Parameter Type Description

None

Return

Type Description

int The column type from the source database. See notes below.

204 Solutions Business Manager (SBM) Technical Details SBM ModScript version: 11.3. Notes The following database data types are supported: • 1 SQL_CHAR

• 2 SQL_NUMERIC

• 3 SQL_DECIMAL

• 4 SQL_INTEGER

• 5 SQL_SMALLINT

• 6 SQL_FLOAT

• 7 SQL_REAL

• 8 SQL_DOUBLE

• 9 SQL_DATE

• 10 SQL_TIME

• 11 SQL_TIMESTAMP

• 12 SQL_VARCHAR

• 91 SQL_TYPE_DATE

• 92 SQL_TYPE_TIME

• 93 SQL_TYPE_TIMESTAMP

• -1 SQL_LONGVARCHAR

• -5 SQL_BIGINT

• -6 SQL_TINYINT

Related Topics DbImport [page 203]

SrcLabel()

If an "Int" type value maps to a reference table, this string value represents the label from the source database.

Function Signature

string SrcLabel()

SBM ModScript Reference Guide 205 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

None

Return

Type Description

string The referenced label.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics DbImport [page 203]

DestFldId()

If mapped, this value represents the destination (SBM) field ID.

Function Signature

int DestFldId()

Parameters

Parameter Type Description

None

Return

Type Description

int The TS_ID of the field that this column is mapped to in the SBM database.

Technical Details SBM ModScript version: 11.3.

206 Solutions Business Manager (SBM) Notes None. Related Topics DbImport [page 203]

SrcData()

The actual data from the source database.

Function Signature

Variant& SrcData()

Parameters

Parameter Type Description

None

Return

Type Description

Variant& The data read from the database.

Technical Details SBM ModScript version: 11.3. Notes Changing this value will modify the data that is written to the database during the import. Related Topics DbImport [page 203] Dictionary Description A class for supporting dictionary objects in scripts that are converted from SBM AppScript to SBM ModScript. A dictionary is a case sensitive key-value container. In general, use ChaiScript's Map instead. Dictionary can be iterated using ChaiScript's for loop. See example below. Constructors • Dictionary(): Creates a dictionary object.

SBM ModScript Reference Guide 207 Chapter 3: Programming SBM ModScript

• Optionally, use CreateObject() [page 107] with "Scripting,Dictionary".

Operators • Variant& operator[]( key ): Accesses value at location key. Inserts value if not found.

Methods • Variant& at( key ): Accesses value at location key. Throws exception if not found.

• uint64_t size(): Returns the count of items in the container.

• bool empty(): Returns if the container is empty.

• void clear(): Removes all items from the container.

• size_t count( key ): Returns 1 if key is found inside the container; otherwise, 0.

• void insert( Dictionary_Pair entry ): Inserts entry into the container. Dictionary_Pair is the data type that represents an entry.

• void Add( key , value ): Adds an entry to the container. Throws if key is already in the dictionary.

• bool Remove( key ): Removes the entry with key. Returns true if found.

• void RemoveAll(): Removes all items from the container.

• int Count(): Returns the count of items in the container.

• Variant& Item( key ): Accesses value at location key. Inserts value if not found.

• void Key( key ): Inserts key if not found.

• void SetKey( keyOrig , keyNew ): Moves entry from keyOrig to keyNew.

• bool Exists( key ): Returns true if key is found.

• Vector Keys(): Returns a Vector of keys.

• Vector Items(): Returns a Vector of values.

Example

var dict = Dictionary(); dict.Add( "key1", "val1" ); dict.Add( "key2", "val2" ); dict.Add( "key3", 3 );

for ( entry : dict ) { Ext.WriteStream( "${entry.first()}: ${entry.second()}\n" ); }

208 Solutions Business Manager (SBM) Field Description A Field object represents a variable field, from a primary or auxiliary item. Field objects are typically retrieved using the VarRecord method GetFieldValue() or the VarFieldList method FindField(). Field methods allow you to read and write the field's value and control whether it will be processed when the item is updated in the database. Inheritance AppRecord [page 159] -> Field Methods • AppendJournalText() [page 209]

• GetDbValue-type-() [page 210]

• GetDbValue() [page 211]

• GetDisplayValue() [page 212]

• GetRequiredFlag() [page 213]

• GetSelectionList() [page 214]

• GetType() [page 215]

• GetTypeString() [page 215]

• GetValue-type-() [page 216]

• GetValue() [page 217]

• IsAuto() [page 218]

• IsBlank() [page 219]

• IsDbBlank() [page 219]

• IsSelected() [page 220]

• Select() [page 221]

• SetBlankValue() [page 221]

• SetValue() [page 222]

AppendJournalText()

(SBM On-Premise/PaaS only) Appends text to a journal entry.

Function Signature

bool AppendJournalText( value )

SBM ModScript Reference Guide 209 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

value string The text to append as a journal entry.

Return

Type Description

bool Returns true if the field is a Journal Text field (and hence the text was appended); false if not.

Technical Details SBM ModScript version: 11.3. Notes If the field is a Journal Text field, the parameter is appended as a new journal entry. Otherwise, nothing happens. You create a Journal Text field in SBM Composer by selecting a field type of Text and a display style of Journal. Journal Text fields have a type code of 101 (Text) and an attribute value of 2 (Journal) or 3 (read-only Journal). Related Topics Field [page 209]

GetDbValue-type-()

Gets the field's internal value as it is currently stored in the database.

Function Signature

string GetDbValueString()

int GetDbValueInt()

int64_t GetDbValueInt64()

double GetDbValueDouble()

TimeT GetDbValueTimeT()

Variant GetDbValue()

210 Solutions Business Manager (SBM) Parameters

Parameter Type Description

None

Return

Type Description

string The internal database value for the field. For Text fields, this is the exact value entered in the field. For values that are not Variant or int TimeT, this internally gets the value from the field as a Variant, and int64_t then tries to convert the value to the requested type. double TimeT can be used with Date/Time fields to get the internal date value. TimeT Note: If the field is a Multi-User field for which the Groups Variant and Users selection mode is enabled, the value can include both pure integers (TS_IDs from the TS_USERS table) and group identifiers (TS_IDs from the TS_GROUPS table). The latter are in the form G1, G2, …

Technical Details SBM ModScript version: 11.4. Notes The value does not reflect any changes that are waiting to be stored, such as editing that has occurred on a transition form. When an Update() executes, this value is recorded in the change history as the "prior" value. To get the current value reflecting all changes, use the GetValue() method. Related Topics Field [page 209]

GetDbValue()

Gets the field's internal value as it is currently stored in the database.

Function Signature

void GetDbValue(Variant& val)

SBM ModScript Reference Guide 211 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

val Variant& (Output) The internal database ID for the value. For Text fields, this is the exact value entered in the field. The Variant must be created before being passed to this function.

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Notes The value does not reflect any changes that are waiting to be stored, such as editing that has occurred on a transition form. When an Update() executes, this value is recorded in the change history as the "prior" value. To get the current value reflecting all changes, use the GetValue() method. Related Topics Field [page 209]

GetDisplayValue()

Gets the current value of this field, reflecting any changes that may have been made since the last database Update().

Function Signature

string GetDisplayValue( [bool checkPrivs [, string format]] )

void GetDisplayValue( Variant& val, [bool checkPrivs [, string format]] )

Parameters

Parameter Type Description

checkPrivs bool Optional. Defaults to true if omitted. If true, the value will only be supplied if the current user has sufficient privileges to see this field.

212 Solutions Business Manager (SBM) Parameter Type Description

format string Optional. For File or URL fields, the value "json" indicates that the output should be a JSON string value.

val Variant& (Output) This field's current value as a formatted string.

Return

Type Description

string The field's current value as a formatted string.

Technical Details SBM ModScript version: 11.3. Extended in 11.4. Notes This is the display value as shown on the browser, and not the internal value stored in the database. For example, for a selection field, the value of the selection (None) is 0 in the database. This function will return the string (None), while GetValue and GetDbValue will return 0. To get the value most recently stored in the database, use the method GetDbValue(). If this field comes from an item that was directly read out of the database and you wish to use checkPrivs, you must call the ApplyProjectStateOverrides() VarFieldList method. Related Topics Field [page 209]

GetRequiredFlag()

Used to check whether or not a field is required.

Function Signature

int GetRequiredFlag()

Parameters

Parameter Type Description

None

SBM ModScript Reference Guide 213 Chapter 3: Programming SBM ModScript

Return

Type Description

int Returns a value that corresponds to the constant FieldRequiredConstants. For details, see FieldRequiredConstants [page 350].

Technical Details SBM ModScript version: 11.3. Notes This method is only useful when Field is part of a FieldList from an item that is in the process of being transitioned. Related Topics Field [page 209] StartSubmitToProject() [page 253] StartTransition() [page 334]

GetSelectionList()

Returns a list of all possible selection values for single and multi-select fields.

Function Signature

AppRecordList GetSelectionList()

Parameters

Parameter Type Description

None

Return

Type Description

AppRecordList All possible selections, as AppRecord objects from the TS_SELECTIONS table.

Technical Details SBM ModScript version: 11.3.

214 Solutions Business Manager (SBM) Notes None. Related Topics Field [page 209]

GetType()

Returns a code that identifies the type of data stored in a field.

Function Signature

int GetType()

Parameters

Parameter Type Description

None

Return

Type Description

int A code that identifies the type of data stored in the field. See FieldTypeConstants [page 350].

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Field [page 209]

GetTypeString()

Returns a string that identifies the type of data stored in a field.

Function Signature

string GetTypeString()

SBM ModScript Reference Guide 215 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

None

Return

Type Description

string A string that identifies the type of data stored in the field.

Technical Details SBM ModScript version: 11.3. Notes For example, if GetType() returns 106, GetTypeString() returns a string like "State". Related Topics Field [page 209]

GetValue-type-()

Gets the field's internal value without checking privileges, including changes made to the value during the transition if in a transition context.

Function Signature

string GetValueString()

int GetValueInt()

int64_t GetValueInt64()

double GetValueDouble()

TimeT GetValueTimeT()

Variant GetValue()

Parameters

Parameter Type Description

None

216 Solutions Business Manager (SBM) Return

Type Description

string The internal value. For Text fields, this is the exact value entered in the field. For values that are not Variant or TimeT, this internally gets int the value from the field as a Variant, and then tries to convert the int64_t value to the requested type. double TimeT can be used with Date/Time fields to get the internal date value. TimeT Note: If the field is a Multi-User field for which the Groups Variant and Users selection mode is enabled, the value can include both pure integers (TS_IDs from the TS_USERS table) and group identifiers (TS_IDs from the TS_GROUPS table). The latter are in the form G1, G2, …

Technical Details SBM ModScript version: 11.4. Notes This reflects any changes that are made during a transition. When an Update() executes, this value is recorded in the change history as the "new" value. To get the original value, use the GetDbValue() method. Related Topics Field [page 209]

GetValue()

Gets the field's internal value without checking privileges, including changes made to the value during the transition if in a transition context.

Function Signature

void GetValue( Variant& val )

Parameters

Parameter Type Description

val Variant& (Output) The internal database ID for the value. For Text fields, this is the exact value entered in the field. The Variant must be created before being passed to this function.

SBM ModScript Reference Guide 217 Chapter 3: Programming SBM ModScript

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Notes This reflects any changes that are made during a transition. When an Update() executes, this value is recorded in the change history as the "new" value. To get the original value, use the GetDbValue() method. Related Topics Field [page 209]

IsAuto()

Determines whether this field is set to be automatically populated.

Function Signature

bool IsAuto()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if this field is automatically populated; false if not.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Field [page 209]

218 Solutions Business Manager (SBM) IsBlank()

Determines whether a field does not contain data.

Function Signature

bool IsBlank()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if this field contains no data; false if it does.

Technical Details SBM ModScript version: 11.3. Notes Use this method to help you determine whether a field does not contain data. This typically occurs when a field is uninitialized, meaning it does not have a default value or values entered by users. Related Topics Field [page 209]

IsDbBlank()

Determines whether a field does not contain data stored in the database.

Function Signature

bool IsDbBlank()

Parameters

Parameter Type Description

None

SBM ModScript Reference Guide 219 Chapter 3: Programming SBM ModScript

Return

Type Description

bool Returns true if this field contains data; false if not.

Technical Details SBM ModScript version: 11.3. Notes Use this method to help you determine whether a field does not contain data stored in the database. This typically occurs when a field is uninitialized, meaning it does not have a default value or values entered by users. Related Topics Field [page 209]

IsSelected()

Determines whether a field has been selected for Update() processing by the Select() method.

Function Signature

bool IsSelected()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if selected; false if not.

Technical Details SBM ModScript version: 11.3. Notes If not selected, the field is ignored during the next database update. See the Select() method for more details.

220 Solutions Business Manager (SBM) Related Topics Field [page 209]

Select()

Sets or clears a field's select flag to control processing during the next Update().

Function Signature

void Select( selectFlag )

Parameters

Parameter Type Description

selectFlag bool If true, the field will be processed during the next Update(). If false, it will be skipped unless overridden by the VarFieldList method SelectAll().

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Notes When an item is updated in the database, all of its selected fields are checked for changes. Only fields that have changed are updated in the database. Since checking all fields can be an expensive operation, you can deselect some fields if you know they have not changed. Note that you can override the select flag using the VarFieldList method SelectAll(). Related Topics Field [page 209]

SetBlankValue()

(SBM On-Premise/PaaS only) Removes data from a field, returning it to an uninitialized state.

Function Signature

void SetBlankValue()

SBM ModScript Reference Guide 221 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

None

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Notes After the data is removed using SetBlankValue(), the field contains a special code that represents a lack of data, which can be detected by IsBlank(). Related Topics Field [page 209]

SetValue()

Sets or changes a field's value to the internal value supplied.

Function Signature

void SetValue( string& value )

void SetValue( int& value )

void SetValue( int64_t& value )

void SetValue( double& value )

void SetValue( TimeT& value )

void SetValue( Variant& value )

222 Solutions Business Manager (SBM) Parameters

Parameter Type Description

value string& The internal value for the field. For Text fields, this is the exact value entered in the field. int& TimeT can be used with Date/Time fields to set the internal int64_t& date value. double& TimeT& Variant&

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Extended in 11.4. Notes None. Related Topics Field [page 209] Folder Description Folder objects provide a convenient interface for examining folder contents and adding or removing folder items. A Folder object describes a single folder and corresponds to a record in the TS_FOLDERS table. To examine the folder hierarchy or generate the full folder name, use inherited TreeItem methods. To generate a list of items in an folder, see FolderItemList. Inheritance AppRecord [page 159] -> TreeItem [page 312] -> Folder Methods • AddItem() [page 224]

• Contains() [page 224]

• DeleteItem() [page 225]

SBM ModScript Reference Guide 223 Chapter 3: Programming SBM ModScript

AddItem()

(SBM On-Premise/PaaS only) Adds an AppRecord item to a folder.

Function Signature

bool AddItem( AppRecord rec )

Parameters

Parameter Type Description

rec AppRecord The item to add to the folder.

Return

Type Description

bool Returns true if the item is added successfully; false if not.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Folder [page 223]

Contains()

Used to determine whether a given item is in the current folder.

Function Signature

bool Contains( tableId, recId )

Parameters

Parameter Type Description

tableId int Table ID of the item to search for.

recId int TS_ID of the item to search for.

224 Solutions Business Manager (SBM) Return

Type Description

bool Returns true if this folder contains the item; false if not.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Folder [page 223]

DeleteItem()

(SBM On-Premise/PaaS only) Removes an AppRecord item from a folder.

Function Signature

bool DeleteItem( AppRecord rec )

Parameters

Parameter Type Description

rec AppRecord The item to remove from the folder.

Return

Type Description

bool Returns true if removed successfully; false if not.

Technical Details SBM ModScript version: 11.3. Notes The item is not deleted from the system, just from the folder. Related Topics Folder [page 223]

SBM ModScript Reference Guide 225 Chapter 3: Programming SBM ModScript

FolderItem Description The TS_FOLDERITEMS table identifies the contents of all folders. Each record identifies one item of one folder by associating three TS_IDs: the folder's ID, the table ID of the item stored in the folder, and the TS_ID of the item. A folder has one entry in the TS_FOLDERITEMS table for each primary item, auxiliary item, and report it contains, and one entry in the TS_URLSTORE table for each URL it contains. Though it is possible to supply the table ID of a system table other than TS_REPORTS, folder items created this way are not supported and will yield undefined behavior when accessed by a user. Inheritance AppRecord [page 159] -> FolderItem Properties (SBM On-Premise/PaaS only)

Property Type Description

FolderId int TS_ID of the folder.

TableId int Table ID of the item stored in this folder.

RecId int TS_ID of the item stored in this folder.

FolderItemList Description A FolderItemList is an AppRecordList that holds objects of type FolderItem. Typically, the ReadWithWhere() method is used to fill the list with all items from a given folder. Inheritance AppRecordList [page 187] -> FolderItemList Methods • Contains() [page 226]

Contains()

(SBM On-Premise/PaaS only) Used to determine whether a folder contains an item.

Function Signature

bool Contains( tableId, recId )

226 Solutions Business Manager (SBM) Parameters

Parameter Type Description

tableId int Table ID of the item to search for.

recId int TS_ID of the item to search for.

Return

Type Description

bool Returns true if the item is found in the list.

Technical Details SBM ModScript version: 11.3. Notes This method searches a folder for a given item from a given table. This method assumes the list contains only FolderItem objects from a single folder and thus tells you whether that folder contains the item. Related Topics FolderItemList [page 226] Incident Description Not commonly used, as this maps to a specific primary table that may not exist in your database. An incident is simply a ProjectBasedRecord from the Incident Management application's primary table. Objects of type incident can be created using CreateObject(), and SBM will automatically look up the Incidents table. Inheritance AppRecord [page 159] -> VarRecord [page 326] -> ProjectBasedRecord [page 252] -> Incident Lib Description (SBM On-Premise only) A class for loading and invoking a custom DLL. For details on usage and examples, refer to Calling Functions in a DLL from SBM ModScript [page 360].

SBM ModScript Reference Guide 227 Chapter 3: Programming SBM ModScript

Constructors None. Use CreateObject() [page 107] with "SBMLibrary". Methods • SetLibraryName() [page 228]

• LoadLibrary() [page 229]

• FreeLibrary() [page 229]

• IsLibraryLoaded() [page 230]

• CallLibraryFunction() [page 231]

SetLibraryName()

(SBM On-Premise only) Sets the DLL name.

Function Signature

void SetLibraryName( name )

Parameters

Parameter Type Description

name string The name—and optionally the path—of the DLL. For details, refer to Loading the Library in SBM ModScript [page 361].

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Notes This method tells the SBM library object which DLL you are going to load and call functions in. Related Topics Lib [page 227] Loading the Library in SBM ModScript [page 361]

228 Solutions Business Manager (SBM) LoadLibrary()

(SBM On-Premise only) Loads the DLL.

Function Signature

bool LoadLibrary()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if the DLL was successfully loaded; returns false otherwise.

Technical Details SBM ModScript version: 11.3. Notes Typically, failure to load the DLL means the DLL could not be located; therefore, check paths and spelling. This function throws a runtime exception if SetLibraryName() has not previously been called for this object or if any arguments were passed to this function. This function may also throw a runtime exception if the operating system is unable to load the DLL. Check the event viewer for detailed information. Related Topics Lib [page 227] Loading the Library in SBM ModScript [page 361]

FreeLibrary()

(SBM On-Premise only) Unloads a previously loaded DLL.

Function Signature

bool FreeLibrary()

SBM ModScript Reference Guide 229 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if the DLL was successfully unloaded; returns false otherwise.

Technical Details SBM ModScript version: 11.3. Notes If false is returned, you may check the event viewer for more detailed information. This function throws a runtime exception if SetLibraryName() has not previously been called for this object or if any arguments were passed to this function. Related Topics Lib [page 227] Unloading the DLL [page 362] Keeping a Library Loaded Across Script Executions [page 363]

IsLibraryLoaded()

(SBM On-Premise only) Verifies if the library has already been loaded.

Function Signature

bool IsLibraryLoaded()

Parameters

Parameter Type Description

None

230 Solutions Business Manager (SBM) Return

Type Description

bool Returns true if the library is already loaded; returns false otherwise.

Technical Details SBM ModScript version: 11.3. Notes This function throws a runtime exception if SetLibraryName() has not previously been called for this object or if any arguments were passed to this function. Related Topics Lib [page 227] Keeping a Library Loaded Across Script Executions [page 363]

CallLibraryFunction()

(SBM On-Premise only) Invokes the function from the library identified by name.

Function Signature

int CallLibraryFunction( name, String& argStr1-7 )

int CallLibraryFunctionInt( name, Vector& argVect )

Variant CallLibraryFunction( name, [Variant& argVar1-7] )

Variant CallLibraryFunction( name, Vector& argVect )

Parameters

Parameter Type Description

name string The function to be invoked.

argStr String& (Input/Ouput) Takes between one and seven string parameters that are both input and output, requiring the strings to be created before being passed in to this function.

SBM ModScript Reference Guide 231 Chapter 3: Programming SBM ModScript

Parameter Type Description

argVect Vector& (Input/Ouput) All entries in the Vector will be converted to string and passed as input/output parameters to the DLL. If the DLL sets any of the parameters to a new value, the engine attempts to convert the string back to the original data type of the object inside the Vector. See example below.

argVar Variant& (Input/Ouput) Takes between one and seven optional Variant parameters that are both input and output. All parameters will be converted to string before being passed to the DLL. All params must be created before they are passed in to this function.

Return

Type Description

int Returns the integer that the DLL function returned.

Variant Returns the integer that the DLL function returned.

Technical Details SBM ModScript version: 11.3. The string and CallLibraryFunctionInt signatures were added in 11.4. Example

var v = [1,1.1,"2.5"]; lib.CallLibraryFunction( "Add", v ); // DLL added 3 values and set first parameter to result Ext.WriteStream( v[0] );

Result:

4

Assuming the DLL added the three values passed in, and returned the result by setting the first argument to the new value, the result was converted from "4.6" to the integer found at v[0]. Notes None. Related Topics Lib [page 227]

232 Solutions Business Manager (SBM) Calling Your Function [page 362] Locale Description Provides functions that create a locale. Inheritance Locale does not inherit from any object type. Global Methods Free functions that create a Locale. • Locale CreateUserLocale(): Returns current user's locale.

• Locale CreateSystemLocale(): Returns default locale for system, which is set in SBM System Administrator.

• Locale CreateLocale( v ): Creates locale specified by "v", such as "en_US".

Methods • Collate() [page 233]

• LinkText [page 234]

• GetName() [page 235]

• GetId() [page 236]

• Parse-type-() [page 237]

• Format-type-() [page 238]

• GetDayOfWeekName() [page 239]

• GetMonthName() [page 240]

• GetAMPMName() [page 241]

Collate()

Compares two strings using Locale rules.

Function Signature

int Collate( string a, string b)

SBM ModScript Reference Guide 233 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

a string The first string to be compared.

b string The second string to be compared.

Return

Type Description

int Returns -1 if a collates lower than b, 0 if they are equal, and 1 if a collates higher than b.

Technical Details SBM ModScript version: 11.6.1. Example None. Notes None. Related Topics Locale [page 233]

CollateCaseInsensitive()

Compares two strings using case insensitive Locale rules. Useful for sorting strings.

Function Signature

int CollateCollateCaseInsensitive( string a, string b)

Parameters

Parameter Type Description

a string The first string to be compared.

b string The second string to be compared.

234 Solutions Business Manager (SBM) Return

Type Description

int Returns -1 if a collates lower than b, 0 if they are equal, and 1 if a collates higher than b.

Technical Details SBM ModScript version: 11.6.1. Example None. Notes None. Related Topics Locale [page 233]

GetName()

Returns a locale name.

Function Signature

string GetName()

Parameters

Parameter Type Description

None

Return

Type Description

string The locale name.

Technical Details SBM ModScript version: 11.3.

SBM ModScript Reference Guide 235 Chapter 3: Programming SBM ModScript

Example

var loc = CreateLocale("en_UK"); Ext.WriteStream( loc.GetName() );

Result:

English (UK)

Notes None. Related Topics Locale [page 233]

GetId()

Returns the ID of a locale.

Function Signature

string GetId()

Parameters

Parameter Type Description

None

Return

Type Description

string The locale ID.

Technical Details SBM ModScript version: 11.3. Example

var loc = CreateLocale("en_UK"); Ext.WriteStream( loc.GetID() );

Result:

en_UK

236 Solutions Business Manager (SBM) Notes None. Related Topics Locale [page 233]

Parse-type-()

Uses locale awareness to parse the text value in "value".

Function Signature

bool ParseInt( value, int& out )

bool ParseInt64( value, int64_t& out )

bool ParseDouble( value, double& out )

Parameters

Parameter Type Description

value string The value to parse.

out int& (Output) The value that receives the parsed number. int64_t& double&

Return

Type Description

bool Returns true if the value was successfully parsed.

Technical Details SBM ModScript version: 11.3. Example var germanLocale = CreateLocale("de_DE"); var intV = 0; var intR = germanLocale.ParseInt("2345", intV ); Ext.WriteStream( "int: result: ${intR}, expected: 2345, parsed: ${intV}" ); var int64V = 0ll; var int64R = germanLocale.ParseInt64("422564125658", int64V ); Ext.WriteStream( "int64_t: result: ${int64R}, expected: 422564125658, parsed: ${int64V}" );

SBM ModScript Reference Guide 237 Chapter 3: Programming SBM ModScript

var dblV = 0.0; var dblR = germanLocale.ParseDouble("234,2342", dblV ); Ext.WriteStream( "double: result: ${dblR}, expected: 234.2342, parsed: ${dblV}" );

Result:

int: result: true, expected: 2345, parsed: 2345 int64_t: result: true, expected: 422564125658, parsed: 422564125658 double: result: true, expected: 234.2342, parsed: 234.2342

Notes Check the return value for success before using "out". Related Topics Locale [page 233]

Format-type-()

Uses locale awareness to create a text value from the number stored in "value".

Function Signature

string FormatInt( string value, bool useGrouping )

string FormatInt64( string value, bool useGrouping )

string FormatDouble( string value, bool useGrouping [, int minFractionDigits, int maxFractionDigits ] )

Parameters

Parameter Type Description

value string The value to parse.

useGrouping bool Indicates if the output string should have groupings like thousands separators; the rules for these separators are defined in the locale.

minFractionDigits int Indicates the minimum number of digits to be printed after the decimal point.

maxFractionDigits int Indicates the maximum number of digits to be printed after the decimal point.

238 Solutions Business Manager (SBM) Return

Type Description

string The resultant text value.

Technical Details SBM ModScript version: 11.3. Example var germanLocale = CreateLocale("de_DE"); var intR = germanLocale.FormatInt( 23912, false ); Ext.WriteStream( "int: result: ${intR}, expected: 23912" ); var int64R = germanLocale.FormatInt64( 52954845625ll, true ); Ext.WriteStream( "int64_t: result: ${int64R}, expected: 52.954.845.625" ); var dblR = germanLocale.FormatDouble( 1251239.2564, true, 5, 7 ); Ext.WriteStream( "double: result: ${dblR}, expected: 1.251.239,25640" );

Result: int: result: 23912, expected: 23912 int64_t: result: 52.954.845.625, expected: 52.954.845.625 double: result: 1.251.239,25640, expected: 1.251.239,25640

Notes maxFractionDigits must be >= minFractionDigits. If the value for maxFractionDigits is less than the value of minFractionDigits, then maxFractionDigits will be set to the value of minFractionDigits. Use -1 to indicate default behavior if only minFractionDigits or maxFractionDigits should be specified. Related Topics Locale [page 233]

GetDayOfWeekName()

Returns Locale-correct name for that day of week; day should be 0-6 (0 is Sunday).

Function Signature

string GetDayOfWeekName( int day )

string GetDayOfWeekName( int day, int hint )

SBM ModScript Reference Guide 239 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

day int An int that represents the day of the week; 0-6 (0 is Sunday).

hint int Values from DateFormatFromLocaleConstants [page 346]. Indicates if the day of week name is abbreviated or not.

Return

Type Description

string The Locale-correct name for the day of the week.

Technical Details SBM ModScript version: 11.4. Example

var v1 = TimeMillis( 1516667515006ll ).ToTimePoint( CreateTimeZone("MST") ); var dayOfWeek = v1.getDayOfWeek(); var fr = CreateLocale("fr"); // Create French locale Ext.WriteStream( fr.GetDayOfWeekName(dayOfWeek) ); // Output day of week using French locale

Result:

lundi

Notes Hint will be a value from DateFormatFromLocaleConstants [page 346] to determine if the name should be FULL, MEDIUM, or SHORT. Related Topics Locale [page 233]

GetMonthName()

Returns Locale-correct name for that month; month should be 0-11 (0 is January).

Function Signature

string GetMonthName( int month )

string GetMonthName( int month, int hint )

240 Solutions Business Manager (SBM) Parameters

Parameter Type Description

day int An int that represents the month; 0-11 (0 is January).

hint int Values from DateFormatFromLocaleConstants [page 346]. Indicates if the month name is abbreviated or not.

Return

Type Description

string The Locale-correct name for the month.

Technical Details SBM ModScript version: 11.4. Example var v1 = TimeT( 1516667515 ).ToTimePoint( CreateTimeZone("MST") ); var month = v1.getMonth(); var fr = CreateLocale("fr"); // Create French locale // Output month using French locale Ext.WriteStream( fr.GetMonthName(month, DateFormatFromLocaleConstants.MEDIUM) );

Result: janv.

Notes Hint will be a value from DateFormatFromLocaleConstants [page 346] to determine if the name should be FULL, MEDIUM, or SHORT. Related Topics Locale [page 233]

GetAMPMName()

Returns Locale-correct name for AM or PM.

Function Signature

string GetAMPMName( bool isAM )

SBM ModScript Reference Guide 241 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

isAM bool Pass true for AM.

Return

Type Description

string The Locale-correct name for AM or PM.

Technical Details SBM ModScript version: 11.4. Example

var v1 = TimeT( 1516667515 ).ToTimePoint( CreateTimeZone("MST") ); var hours = v1.getHours(); var fr = CreateLocale("fr"); // Create French locale // Output am/pm using French locale Ext.WriteStream( fr.GetAMPMName(hours<12) );

Result:

PM

Notes None. Related Topics Locale [page 233] Log Description (SBM On-Premiseonly) A class for writing output messages and appending an output log file. Optionally, datestamps can be pre-pended to output messages. Constructors • Log(): Creates a log object.

Level Accessors You can use the following functions to return the desired log level or you can use LogLevelConstants [page 352].

242 Solutions Business Manager (SBM) • int NONE(): Returns the constant value 1. Used with SetReportingLevel.

• int MINIMAL(): Returns the constant value 2. Used with SetReportingLevel.

• int AVERAGE(): Returns the constant value 3. Used with SetReportingLevel.

• int VERBOSE(): Returns the constant value 4. Used with SetReportingLevel.

Methods • Open() [page 243]

• Close() [page 244]

• SetBackUpLogFile() [page 245]

• SetMaxSize() [page 245]

• SetWantTimeStamp() [page 246]

• SetReportingLevel() [page 247]

• IsOpen() [page 248]

• GetFileName() [page 249]

• GetReportingLevel() [page 249]

• Message() [page 250]

Open()

(SBM On-Premise only) Opens the log object pointing to file "s".

Function Signature

bool Open( s )

Parameters

Parameter Type Description

s string "s" contains the file name and sub-path (if desired) to be appended to the Application Engine "log" folder path.

Return

Type Description

bool Returns true if successful.

SBM ModScript Reference Guide 243 Chapter 3: Programming SBM ModScript

Technical Details SBM ModScript version: 11.3. Example See Message() [page 250]. Notes If a sub-path is requested, that folder must already exist on the OS. Related Topics Log [page 242]

Close()

(SBM On-Premise only) Closes the log.

Function Signature

void Close()

Parameters

Parameter Type Description

None

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Example See Message() [page 250]. Notes None. Related Topics Log [page 242]

244 Solutions Business Manager (SBM) SetBackUpLogFile()

(SBM On-Premise only) If called with a true value and the log size exceeds value provided to SetMaxSize(), the log will rename the file with a date stamp in the new name, and start a fresh file with the original name.

Function Signature

bool SetBackUpLogFile( bool value )

Parameters

Parameter Type Description

value bool If set to false, when the value provided to SetMaxSize() is reached, all previous log data will be lost. This is the default behavior if SetBackUpLogFile() is not set.

Return

Type Description

bool Returns the bool value passed in. The default is false.

Technical Details SBM ModScript version: 11.3. Example See Message() [page 250]. Notes See SetMaxSize() for the size that triggers this behavior. Related Topics Log [page 242]

SetMaxSize()

(SBM On-Premise only) Sets the number of bytes the log file should grow to before it is truncated.

Function Signature

int SetMaxSize( value )

SBM ModScript Reference Guide 245 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

value int The max log size that can be reached.

Return

Type Description

int Returns the int value passed in. The default is 20971520 bytes.

Technical Details SBM ModScript version: 11.3. Example See Message() [page 250]. Notes • If SetBackUpLogFile has been called with a true value, the file will be saved with a new name.

• If SetBackUpLogFile has been called with a false value, the old data will be lost when it is truncated.

Related Topics Log [page 242]

SetWantTimeStamp()

(SBM On-Premise only) Adds timestamps to log entries.

Function Signature

bool SetWantTimeStamp( bool value )

Parameters

Parameter Type Description

value bool Pass true to add timestamps to log entries. The default is true.

246 Solutions Business Manager (SBM) Return

Type Description

bool Returns the bool value passed in.

Technical Details SBM ModScript version: 11.3. Example See Message() [page 250]. Notes None. Related Topics Log [page 242]

SetReportingLevel()

(SBM On-Premise only) Sets the log reporting level.

Function Signature

int SetReportingLevel( int value )

Parameters

Parameter Type Description

value int An integer value, from 1 to 4; constant values are available by using the member functions NONE through VERBOSE, or using the LogLevelConstants global, which has members NONE through VERBOSE. See LogLevelConstants [page 352]. The default is LogLevelConstants.AVERAGE.

Return

Type Description

int Returns the int value passed in.

Technical Details SBM ModScript version: 11.3.

SBM ModScript Reference Guide 247 Chapter 3: Programming SBM ModScript

Example See Message() [page 250]. Notes Calls to "Message" functions with a higher value will be ignored. This allows code to be written that writes frequent log messages at the VERBOSE level, but perhaps most of those messages can be ignored most of the time when not debugging, so the log level is set to MINIMAL unless the script writer is debugging. Related Topics Log [page 242]

IsOpen()

(SBM On-Premise only) Checks to see if the log is open.

Function Signature

bool IsOpen()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if the log is open.

Technical Details SBM ModScript version: 11.3. Example See Message() [page 250]. Notes None. Related Topics Log [page 242]

248 Solutions Business Manager (SBM) GetFileName()

(SBM On-Premise only) Returns the file name of the log that has been opened.

Function Signature

string GetFileName()

Parameters

Parameter Type Description

None

Return

Type Description

string The file name of the log (including the full system path).

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Log [page 242]

GetReportingLevel()

(SBM On-Premise only) Returns the current logging level.

Function Signature

int GetReportingLevel()

Parameters

Parameter Type Description

None

SBM ModScript Reference Guide 249 Chapter 3: Programming SBM ModScript

Return

Type Description

int The current logging level that is set. Ranges from 1 to 4, corresponding to values from LogLevelConstants [page 352]. The default is LogLevelConstants.AVERAGE.

Technical Details SBM ModScript version: 11.3. Example See Message() [page 250]. Notes Constant values are available by using the member functions NONE through VERBOSE, or by using the LogLevelConstants global, which has members NONE through VERBOSE. See SetReportingLevel() [page 247]. Related Topics Log [page 242]

Message()

(SBM On-Premise only) Writes a message to the log using the level provided.

Function Signature

Message( int level, value )

Message( int level, string format, arg0-4 )

Parameters

Parameter Type Description

level int Corresponds to values from LogLevelConstants [page 352].

value Variant Value will be converted to a string and written to the log.

format string A format string with entries like {0} that correspond to arg0 etc. See notes below.

arg (up to 5) Variant A value that is formatted into the output text using the format parameter.

250 Solutions Business Manager (SBM) Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Example

//Basic example of working with the Log class var filePath = "Script.log"; //Creates a Log Object var myLog = Log(); //Opens the Log Object var isOpened = myLog.Open( filePath ); myLog.Message(LogLevelConstants.NONE, "Is log opened " + isOpened); //Starts a new Log file when MaxSize is reached var backUpFileSet = myLog.SetBackUpLogFile(true); //Sets the number of bytes the log file should grow to before it is truncated var maxSize = myLog.SetMaxSize(10485760); //Adds timestamps to the entries var wantTimeStamp = myLog.SetWantTimeStamp(true); //Returns the current logging level myLog.Message(LogLevelConstants.NONE, "Log reporting level: " + myLog.GetReportingLevel()); //Sets the log reporting level to Minimal reportLevel = myLog.SetReportingLevel(LogLevelConstants.MINIMAL); myLog.Message(myLog.NONE(), "Message level NONE" ); myLog.Message(LogLevelConstants.MINIMAL,"Message level MINIMAL" ); myLog.Message(LogLevelConstants.VERBOSE(), "Message level VERBOSE" ); //Logs the message with frmt (format string) myLog.Message(LogLevelConstants.AVERAGE, "Testing the {0} {1} to check that '{0}' {1}s to {0}. {2}, {3}, {4}", "STRING", "FORMAT", 2, 3, 4); //Closes the Log Object myLog.Close();

Notes If the log is set to a lower level than the level passed in, this message will be ignored and not written to the log. See SetReportingLevel() [page 247]. The "format" parameter is a format string with places for up to five values in it. Those places are encoded in the string in {0} format, where the number is the zero-based index of the parameter to be placed in that location. Indexes can be repeated in the format string if that variable should be placed into the string more than one time. Literal "{" must be escaped by single ticks, literal single ticks must be escaped by single ticks. Related Topics Log [page 242]

SBM ModScript Reference Guide 251 Chapter 3: Programming SBM ModScript

Project Description A project represents any SBM project and is stored in the TS_PROJECTS table. To examine the project hierarchy or generate the full project name, use inherited TreeItem methods. Inheritance AppRecord [page 159] -> TreeItem [page 312] -> Project ProjectBasedRecord Description A ProjectBasedRecord is any record from a primary table. It thus represents items that belong to a project and can be transitioned. ProjectBasedRecord objects require a table ID at creation using Ext.CreateProjectBasedRecord(). Inheritance AppRecord [page 159] -> VarRecord [page 326] -> ProjectBasedRecord Methods • GetProjectId() [page 252]

• StartSubmitToProject() [page 253]

• StartSubmitToProjectUsingTransition() [page 254]

• FinishSubmitToProject() [page 255]

• FinishSubmitToProjectUsingTransition() [page 256]

• QuickSubmitToProject() [page 257]

• QuickSubmitToProjectUsingTransition() [page 258]

GetProjectId()

Identifies the calling record's project.

Function Signature

int GetProjectId()

Parameters

Parameter Type Description

None

252 Solutions Business Manager (SBM) Return

Type Description

int TS_ID of the calling record's project.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics ProjectBasedRecord [page 252]

StartSubmitToProject()

(SBM On-Premise/PaaS only) Starts a submit transition for an item using a project ID, project UUID, or project internal name.

Function Signature

bool StartSubmitToProject( project )

Parameters

Parameter Type Description

project int or Can be project ID, project UUID, or project internal name. string

Return

Type Description

bool Returns true if transition was started. If false, use Shell.GetLastErrorMessage() for more information.

Technical Details SBM ModScript version: 11.3. Example var projectRecord = Ext.CreateProjectBasedRecord( projectTableId ); projectRecord.StartSubmitToProject(projectId);

SBM ModScript Reference Guide 253 Chapter 3: Programming SBM ModScript

Notes • StartSubmitToProject() is not required, script can simply invoke QuickSubmitToProject() if all required field values have already been set on the item. StartSubmitToProject() will initialize fields as if the transition form has been opened on the end user interface. Fields will respond correctly to GetRequiredFlag().

• Sets Shell.LastErrorMessage() on error (returns false).

Related Topics ProjectBasedRecord [page 252]

StartSubmitToProjectUsingTransition()

(SBM On-Premise/PaaS only) Starts a submit transition for an item, specifying the project and transition to use.

Function Signature

bool StartSubmitToProjectUsingTransition( project , trans )

Parameters

Parameter Type Description

project int or Can be project ID, project UUID, or project internal name. string

trans int or Can be transition ID, transition UUID, or transition internal string name.

Return

Type Description

bool Returns true if transition was started. If false, use Shell.GetLastErrorMessage() for more information.

Technical Details SBM ModScript version: 11.6. Example

var projectRecord = Ext.CreateProjectBasedRecord( projectTableId ); projectRecord.StartSubmitToProjectUsingTransition( projectId , transId );

254 Solutions Business Manager (SBM) Notes • StartSubmitToProjectUsingTransition() is not required, script can simply invoke QuickSubmitToProjectUsingTransition() if all required field values have already been set on the item. StartSubmitToProjectUsingTransition() will initialize fields as if the transition form has been opened on the end user interface. Fields will respond correctly to GetRequiredFlag().

• This method is used when the default submit transition is not the desired transition. Otherwise, use StartSubmitToProject().

• Sets Shell.LastErrorMessage() on error (returns false).

Related Topics ProjectBasedRecord [page 252]

FinishSubmitToProject()

(SBM On-Premise/PaaS only) Finishes a submit transition for an item.

Function Signature

bool FinishSubmitToProject( [ signedUserID, signedUserPwd ] )

Parameters

Parameter Type Description

signedUserID string Optional. Provides the user name portion of the signature if the transition requires a user's signature.

signedUserPwd string Optional, required if signedUserID is provided. Provides the password portion of the signature if the transition requires a user's signature.

Return

Type Description

bool Returns true if transition completed successfully. If false, use Shell.GetLastErrorMessage() for more information.

Technical Details SBM ModScript version: 11.3.

SBM ModScript Reference Guide 255 Chapter 3: Programming SBM ModScript

Example

projectRecord.SetFieldValue( "title", "My Title"); projectRecord.FinishSubmitToProject("UserName", "pass");

Notes • StartSubmitToProject() should have been invoked. See notes on StartSubmitToProject().

• StartSubmitToProject() sets the project field on the item, so FinishSubmitToProject() does not require the project to be specified.

• Sets Shell.LastErrorMessage() on error (returns false).

Related Topics ProjectBasedRecord [page 252]

FinishSubmitToProjectUsingTransition()

(SBM On-Premise/PaaS only) Finish a submit transition for an item using a non-default transition.

Function Signature

bool FinishSubmitToProjectUsingTransition( trans [, signedUserID, signedUserPwd ] )

Parameters

Parameter Type Description

trans int or Can be transition ID, transition UUID, or transition internal string name.

signedUserID string Optional. Provides the user name portion of the signature if the transition requires a user's signature.

signedUserPwd string Optional, required if signedUserID is provided. Provides the password portion of the signature if the transition requires a user's signature.

Return

Type Description

bool Returns true if transition completed successfully. If false, use Shell.GetLastErrorMessage() for more information.

256 Solutions Business Manager (SBM) Technical Details SBM ModScript version: 11.6. Example projectRecord.SetFieldValue( "title", "My Title"); projectRecord.FinishSubmitToProjectUsingTransition(transId , "UserName", "pass");

Notes • StartSubmitToProjectUsingTransition() should have been invoked. See notes on StartSubmitToProjectUsingTransition().

• StartSubmitToProjectUsingTransition() sets the project field on the item, so FinishSubmitToProjectUsingTransition() does not require the project to be specified.

• This method is used when the default submit transition is not the desired transition. Otherwise, use FinishSubmitToProject().

• Sets Shell.LastErrorMessage() on error (returns false).

Related Topics ProjectBasedRecord [page 252]

QuickSubmitToProject()

(SBM On-Premise/PaaS only) Identical to FinishSubmitToProject() except StartSubmitToProject() is not required, and thus, the project must be specified.

Function Signature

bool QuickSubmitToProject( project [, signedUserID, signedUserPwd ] )

Parameters

Parameter Type Description

project int or Can be project ID, project UUID, or project internal name. string

signedUserID string Optional. Provides the user name portion of the signature if the transition requires a user's signature.

signedUserPwd string Optional, required if signedUserID is provided. Provides the password portion of the signature if the transition requires a user's signature.

SBM ModScript Reference Guide 257 Chapter 3: Programming SBM ModScript

Return

Type Description

bool Returns true if transition completed successfully. If false, use Shell.GetLastErrorMessage() for more information.

Technical Details SBM ModScript version: 11.3. Example

var projectRecord = Ext.CreateProjectBasedRecord(projectTableId); projectRecord.SetFieldValue( "title" , "My Title" ); projectRecord.QuickSubmitToProject( projectID );

Notes All field value changes must be in place on the item first. Related Topics ProjectBasedRecord [page 252]

QuickSubmitToProjectUsingTransition()

(SBM On-Premise/PaaS only) Identical to FinishSubmitToProjectUsingTransition() except StartSubmitToProjectUsingTransition() is not required, and thus, the project must be specified.

Function Signature

bool QuickSubmitToProjectUsingTransition( project, trans [, signedUserID, signedUserPwd ] )

Parameters

Parameter Type Description

project int or Can be project ID, project UUID, or project internal name. string

trans int or Can be transition ID, transition UUID, or transition internal string name.

signedUserID string Optional. Provides the user name portion of the signature if the transition requires a user's signature.

258 Solutions Business Manager (SBM) Parameter Type Description

signedUserPwd string Optional, required if signedUserID is provided. Provides the password portion of the signature if the transition requires a user's signature.

Return

Type Description

bool Returns true if transition completed successfully. If false, use Shell.GetLastErrorMessage() for more information.

Technical Details SBM ModScript version: 11.6. Example var projectRecord = Ext.CreateProjectBasedRecord(projectTableId); projectRecord.SetFieldValue( "title" , "My Title" ); projectRecord.QuickSubmitToProjectUsingTransition( projectID , transId );

Notes • All field value changes must be in place on the item first.

• This method is used when the default submit transition is not the desired transition. Otherwise, use QuickSubmitToProject().

• Sets Shell.LastErrorMessage() on error (returns false).

Related Topics ProjectBasedRecord [page 252] Regex Description Constructor for Regex object. A Regex object cannot be stored in a Variant. Inheritance Regex does not inherit from any object type. Methods • Compile() [page 260]

• Matches() [page 261]

• MatchesAgain() [page 262]

SBM ModScript Reference Guide 259 Chapter 3: Programming SBM ModScript

• ReplaceAll() [page 263]

• ReplaceFirst() [page 264]

• GetLastError() [page 265]

• GroupCount() [page 266]

• GroupVal() [page 267]

• Split() [page 268]

Compile()

Compiles a regular expression.

Function Signature

bool Compile( string pattern [, int options] )

Parameters

Parameter Type Description

pattern string Holds the regular expression pattern to be compiled.

options int Indicates regular expression behavior, such as case sensitivity. See RegexOptionBitsConstants [page 353]. Bits can be combined using the bitwise OR operator: | .

Return

Type Description

bool Returns false if Compile() fails.

Technical Details SBM ModScript version: 11.3. Example

var regex = Regex(); //To test for a valid phone number var subCheck = "(\\+\\d{1,2}\\s*)?\\(?\\d{3}\\)?\\s*[\\.-]?\\s*\\d{3}\\s*[\\.-]?\\s*\\d{4}"; var testNumbers = "123-456-7890 | (123)456-7890 | 123 456 7890 | 123,456,7890 |

260 Solutions Business Manager (SBM) +91 (123) 456-7890"; regex.Compile(subCheck, RegexOptionBitsConstants.IGNORECASE | RegexOptionBitsConstants.MULTILINE); if ( regex.Matches(testNumbers) ) { Ext.WriteStream("Matches:
${regex.GroupVal(0)}"); while( regex.MatchesAgain() ) { Ext.WriteStream("
${regex.GroupVal(0)}"); } }

Result:

Matches: 123-456-7890 (123)456-7890 123 456 7890 +91 (123) 456-7890

Notes None. Related Topics Regex [page 259]

Matches()

Executes a search for a match in a string.

Function Signature

bool Matches( string value [, int offset, int& start, int& end] )

Parameters

Parameter Type Description

value string Holds the string to be searched.

offset int The index that denotes where in the string to start the search; use 0 to start at the beginning.

start int& (Output) If a match was found, the zero-based index of the beginning of the matched-text.

end int& (Output) If a match was found, the zero-based index of the end of the matched-text.

SBM ModScript Reference Guide 261 Chapter 3: Programming SBM ModScript

Return

Type Description

bool Returns true if a match was found.

Technical Details SBM ModScript version: 11.3. Example

var regex = Regex(); //To test for a valid phone number var subCheck = "(\\+\\d{1,2}\\s*)?\\(?\\d{3}\\)?\\s*[\\.-]?\\s*\\d{3}\\s*[\\.-]?\\s*\\d{4}"; var testNumbers = "123-456-7890 | (123)456-7890 | 123 456 7890 | 123,456,7890 | +91 (123) 456-7890"; regex.Compile(subCheck, RegexOptionBitsConstants.IGNORECASE | RegexOptionBitsConstants.MULTILINE); if ( regex.Matches(testNumbers) ) { Ext.WriteStream("Matches:
${regex.GroupVal(0)}"); while( regex.MatchesAgain() ) { Ext.WriteStream("
${regex.GroupVal(0)}"); } }

Result:

Matches: 123-456-7890 (123)456-7890 123 456 7890 +91 (123) 456-7890

Notes An integer zero-based index offset that denotes where to start in the value passed in and output integer references of start and end can be provided, which identifies where the match started and ended in the value passed in. The offset makes it possible to invoke this call multiple times to find all matches in the value passed in. Related Topics Regex [page 259]

MatchesAgain()

Once Matches() has been called, use MatchesAgain to find the next match.

262 Solutions Business Manager (SBM) Function Signature

bool MatchesAgain( [int& start, int& end] )

Parameters

Parameter Type Description

start int& (Output) If a match was found, the zero-based index of the beginning of the matched-text.

end int& (Output) If a match was found, the zero-based index of the end of the matched-text.

Return

Type Description

bool Returns true if the compiled regular expression matches the value passed in.

Technical Details SBM ModScript version: 11.3. Example See the example in Matches() [page 261]. Notes None. Related Topics Regex [page 259]

ReplaceAll()

Replaces all matched parts of a string with a replacement value using the compiled regex.

Function Signature

string ReplaceAll( string value, string replacement )

SBM ModScript Reference Guide 263 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

value string The string to be searched.

replacement string The value inserted into the string in the matched locations.

Return

Type Description

string A string where all matches for the compiled Regex in "value" are replaced with "replacement".

Technical Details SBM ModScript version: 11.3. Example

var r = Regex(); // Regex object 'r' r.Compile("\\d+"); // Compile regex expression "\d+" var changed = r.ReplaceAll("12ab3d456e78", "ABC"); // Replace each group of digits in the first string "value" with the replacement string Ext.WriteStream( changed );

Result:

ABCabABCdABCeABC

Notes None. Related Topics Regex [page 259]

ReplaceFirst()

Replaces the first matched part of a string with a replacement value using the compiled regex.

Function Signature

string ReplaceFirst( string value, string replacement )

264 Solutions Business Manager (SBM) Parameters

Parameter Type Description

value string The string to be searched.

replacement string The value inserted into the string in the first matched location.

Return

Type Description

string A string where the first match for the compiled Regex in "value" is replaced with "replacement".

Technical Details SBM ModScript version: 11.6.1. Example var r = Regex(); // Regex object 'r' r.Compile("\\d+"); // Compile regex expression "\d+" var changed = r.ReplaceFirst("12ab3d456e78", "ABC"); // Replace the first group of digits in the string "value" with the replacement string Ext.WriteStream( changed );

Result:

ABCab3d456e78

Notes None. Related Topics Regex [page 259]

GetLastError()

Provides an error message explanation if Compile() or Matches() fails.

Function Signature

string GetLastError()

SBM ModScript Reference Guide 265 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

None

Return

Type Description

string The text of the last error message.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics Regex [page 259]

GroupCount()

After calling Matches(), if the regex pattern used parenthesis to denote grouping, GroupCount() returns the number of groups.

Function Signature

int GroupCount()

Parameters

Parameter Type Description

None

Return

Type Description

int The number of groups.

Technical Details SBM ModScript version: 11.3.

266 Solutions Business Manager (SBM) Example var r = Regex(); r.Compile("(\\d+)[^\\d]*(\\d+)"); r.Matches("12ab3d456e78"); Ext.WriteStream( r.GroupCount() );

Result:

3

Notes None. Related Topics Regex [page 259]

GroupVal()

After calling Matches(), if the regex pattern used parenthesis to denote grouping, this returns the group specified.

Function Signature

string GroupVal( int group )

Parameters

Parameter Type Description

group int Value 0 will return the full text matched by the regex; groups 1-n (see GroupCount() [page 266]) will return the groupings that the regex pattern identified using parentheses.

Return

Type Description

string The specified group.

Technical Details SBM ModScript version: 11.3. Example var r = Regex(); r.Compile("(\\d+)[^\\d]*(\\d+)"); r.Matches("12ab3d456e78");

SBM ModScript Reference Guide 267 Chapter 3: Programming SBM ModScript

for ( var i = 0; i < r.GroupCount(); ++i ) { Ext.WriteStream( r.GroupVal(i) ); }

Result:

12ab3 12 3

Notes None. Related Topics Regex [page 259]

Split()

Splits the string into parts using the regular expression as a delineator.

Function Signature

Vector Split( string value, bool trim )

Parameters

Parameter Type Description

value string The string to be searched.

trim bool If true, the resulting strings in the Vector will have the whitespace trimmed.

Return

Type Description

Vector A Vector containing substrings as its elements.

Technical Details SBM ModScript version: 11.6.1. Example

var r = Regex(); r.Compile( "\\d+" ); var v = r.Split( "12ab3d456e78", true );

268 Solutions Business Manager (SBM) for ( s : v ) { Ext.WriteStream( s ); }

Result: ab d e

Notes None. Related Topics Regex [page 259] RESTDataSource Description This class reads records from the TS_RESTDATASOURCE table and invokes the described REST call. You can define REST Data Sources in SBM Composer, and then bind them to endpoints that are configurable per environment in Application Repository. You can set up a server to host custom behavior written in any programming language (C#, Java, Groovy, Python, etc.) and SBM ModScript can interact with that server, either gathering data or invoking actions to be taken based on activity occurring in SBM. Because you can run SBM ModScripts during a transition, during a notification, or trigger them by a simple URL, this is a powerful integration point. For more details on working with the RESTDataSource object, see https://www.serenacentral.com/blogs/entry/sbm-modscript-part-8-rest-callouts. Inheritance AppRecord [page 159] -> RESTDataSource Methods • GetURLParameters() [page 269]

• Get() [page 270]

• Post() [page 273]

• Call() [page 275]

• UseSBMProxy() [page 279]

• bool UseSBMProxy() [page 279]

GetURLParameters()

Returns a Map containing the URL parameters that are specified in the RESTDataSource definition. They can be overriden when invoking Get(), Post(), or Call().

SBM ModScript Reference Guide 269 Chapter 3: Programming SBM ModScript

Function Signature

Map GetURLParameters()

Parameters

Parameter Type Description

None

Return

Type Description

Map Map that contains the URL parameters.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics RESTDataSource [page 269]

Get()

Invokes a REST call using GET.

Function Signature

bool Get( string& out [ , string accept, string contentType ] )

bool Get( string& out, Vector params [ , string accept, string contentType ] )

bool Get( string& out, Vector params, Vector pathParams [ , string accept, string contentType ] )

bool Get( string& out, Vector params, Vector pathParams, Vector headers [ , Vector& responseHeaders ] )

270 Solutions Business Manager (SBM) Parameters

Parameter Type Description

out string& (Output) Filled with the resulting data from the REST call. If JSON, consider using from_json to parse this value.

accept string Optional. Sent as the HTTP Accept header value.

contentType string Optional. Sent as the HTTP Content-Type header value.

params Vector An optional Vector of Pair values of URL parameters (values that occur after the ? in the URL). Values will be bound to the URL parameters in a "first=second" format. Values that match URL parameters from the RESTDataSource URL will override the values from the URL, while values that do not match existing URL parameters will be appended to the URL. See Pair, Map_Pair, and Dictionary_Pair [page 123]. To remove all params from the URL, send [ Nothing ]. To remove specific params, send [ Pair( "paramToRemove" , Nothing ) ]; send multiple Pairs to specify multiple values and/or remove multiple URL parameters.

pathParams Vector An optional Vector of string values of URL path parameters (values that occur after the server:port and before the ? in the URL). Values from the Vector will appear in order with / separators between them. The pathParams from the RESTDataSource URL will be processed in order while the pathParams Vector is processed in order; the values from the pathParams Vector will override the corresponding values from the RESTDataSource URL unless the Vector value is a blank string (indicates the value is kept from the RESTDataSource URL). Use the Nothing object to delete pathParams from the URL. If there are more values in the Vector than the RESTDataSource URL, they will be appended to the URL.

headers Vector An optional Vector of Pair values that are sent as HTTP headers in a "name: value" format. Values will be header-encoded. See Pair, Map_Pair, and Dictionary_Pair [page 123].

SBM ModScript Reference Guide 271 Chapter 3: Programming SBM ModScript

Parameter Type Description

responseHeaders Vector& (Output) An optional Vector that is filled in with Pair(string,string) objects representing the HTTP headers that are received. See Pair, Map_Pair, and Dictionary_Pair [page 123].

Return

Type Description

bool Returns true if the call succeeds. On failure, Shell.GetLastErrorMessage() will provide more information.

Technical Details SBM ModScript version: 11.3. Extended in 11.4. Example

var result = " "; //Create AppRecord of RESTDATASOURCE table var restSource = Ext.CreateAppRecord(Ext.TableId("TS_RESTDATASOURCE")); restSource.ReadByColumn("TS_NAME", "JSONPlaceHolder1"); if (!restSource.Get(result)){ // write an error to Event Viewer Ext.LogErrorMsg("Rest call failed in script " + __FILE__ + ":\n" + Shell.GetLastErrorMessage() );

// write an error to Active Diagnostics ADLog.Message( __FILE__, __LINE__, ADLogLevelConstants.ERROR, "Rest call failed:\n" + Shell.GetLastErrorMessage() );

Shell.RedoMessage() = "Rest call failed";

ExitScript(); }

Notes The default timeout is 30 seconds. To override the default timeout value, you must add a new entry to the TS_SYSTEMSETTINGS table called DefaultRESTTimeout with TS_DATATYPE set to 1 and specify the desired timeout in the TS_LONGVALUE column. Override the default timeout by changing the value of Shell.RESTTimeout()—the expected value is an integer number of seconds. Tip: To view a script that provides sample code for using params and pathParams, refer to the RESTDataSource.tscm script in the installDir\SBM\Application Engine\ModScript_Examples directory on the Application Engine server or see Sample Five: RESTDataSource [page 374].

272 Solutions Business Manager (SBM) Related Topics RESTDataSource [page 269]

Post()

Invokes a REST call using POST.

Function Signature

bool Post( string& out, sPostData [ , string accept, string contentType ] )

bool Post( string& out, sPostData, Vector params [ , string accept, string contentType ] )

bool Post( string& out, sPostData, Vector params , Vector pathParams [ , string accept, string contentType ] )

bool Post( string& out, sPostData, Vector params, Vector pathParams, Vector headers [ , Vector& responseHeaders ] )

Parameters

Parameter Type Description

out string& (Output) Filled with the resulting data from the REST call. If JSON, consider using from_json to parse this value.

sPostData string Data to send in the POST call. Potentially, to send well- formatted JSON, set up the data to send in Maps and Vectors, and then call to_json to prepare a JSON value to pass into this parameter.

accept string Optional. Sent as the HTTP Accept header value.

contentType string Optional. Sent as the HTTP Content-Type header value.

SBM ModScript Reference Guide 273 Chapter 3: Programming SBM ModScript

Parameter Type Description

params Vector An optional Vector of Pair values of URL parameters (values that occur after the ? in the URL). Values will be bound to the URL parameters in a "first=second" format. Values that match URL parameters from the RESTDataSource URL will override the values from the URL, while values that do not match existing URL parameters will be appended to the URL. See Pair, Map_Pair, and Dictionary_Pair [page 123]. To remove all params from the URL, send [ Nothing ]. To remove specific params, send [ Pair( "paramToRemove" , Nothing ) ]; send multiple Pairs to specify multiple values and/or remove multiple URL parameters.

pathParams Vector An optional Vector of string values of URL path parameters (values that occur after the server:port and before the ? in the URL). Values from the Vector will appear in order with / separators between them. The pathParams from the RESTDataSource URL will be processed in order while the pathParams Vector is processed in order; the values from the pathParams Vector will override the corresponding values from the RESTDataSource URL unless the Vector value is a blank string (indicates the value is kept from the RESTDataSource URL). Use the Nothing object to delete pathParams from the URL. If there are more values in the Vector than the RESTDataSource URL, they will be appended to the URL.

headers Vector An optional Vector of Pair values that are sent as HTTP headers in a "name: value" format. Values will be header-encoded. See Pair, Map_Pair, and Dictionary_Pair [page 123].

responseHeaders Vector& (Output) An optional Vector that is filled in with Pair(string,string) objects representing the HTTP headers that are received. See Pair, Map_Pair, and Dictionary_Pair [page 123].

Return

Type Description

bool Returns true if the call succeeds. On failure, Shell.GetLastErrorMessage() will provide more information.

274 Solutions Business Manager (SBM) Technical Details SBM ModScript version: 11.3. Extended in 11.4. Example

var result = " "; //Create AppRecord of RESTDATASOURCE table var restSource = Ext.CreateAppRecord(Ext.TableId("TS_RESTDATASOURCE")); restSource.ReadByColumn("TS_NAME", "JSONPlaceHolder1"); var sPostData = //Use Map with to_json to format JSON post data ["name": "myObjName", "value1": 17, "value2": 5.7, "arrayData": [1,2,"3",4] //Use Vector for JSON array ].to_json(); if (!restSource.Post(result, sPostData)){ // write an error to Event Viewer Ext.LogErrorMsg("Rest call failed in script " + __FILE__ + ":\n" + Shell.GetLastErrorMessage() );

// write an error to Active Diagnostics ADLog.Message( __FILE__, __LINE__, ADLogLevelConstants.ERROR, "Rest call failed:\n" + Shell.GetLastErrorMessage() );

Shell.RedoMessage() = "Rest call failed";

ExitScript(); }

Notes Default timeout is 30 seconds. To override the default timeout value, you must add a new entry to the TS_SYSTEMSETTINGS table called DefaultRESTTimeout with TS_DATATYPE set to 1 and specify the desired timeout in the TS_LONGVALUE column. Override the default timeout by changing the value of Shell.RESTTimeout()—the expected value is an integer number of seconds. Tip: To view a script that provides sample code for using params and pathParams, refer to the RESTDataSource.tscm script in the installDir\SBM\Application Engine\ModScript_Examples directory on the Application Engine server or see Sample Five: RESTDataSource [page 374]. Related Topics RESTDataSource [page 269]

Call()

Invokes a REST call using a specified HTTP verb.

Function Signature

bool Call( verb, string& out, sPostData [, string accept, string contentType ] )

bool Call( verb, string& out, sPostData, Vector params

SBM ModScript Reference Guide 275 Chapter 3: Programming SBM ModScript

[, string accept, string contentType ] )

bool Call( verb, string& out, sPostData, Vector params, Vector pathParams [, string accept, string contentType ] )

bool Call( verb, string& out, sPostData, Vector params, Vector pathParams, Vector headers [, Vector& responseHeaders ] )

Parameters

Parameter Type Description

verb string or value Specifies the HTTP verb. Use a string to from specify a custom verb; otherwise, use HTTPVerbConstants HTTPVerbConstants. See HTTPVerbConstants [page 351].

out string& (Output) Filled with the resulting data from the REST call. If JSON, consider using from_json to parse this value.

sPostData string Data to send in the body of the call. Potentially, to send well-formatted JSON, set up the data to send in Maps and Vectors, and then call to_json to prepare a JSON value to pass into this parameter. Not sent if the verb is GET or HEAD.

accept string Optional. Sent as the HTTP Accept header value.

contentType string Optional. Sent as the HTTP Content-Type header value.

276 Solutions Business Manager (SBM) Parameter Type Description params Vector An optional Vector of Pair values of URL parameters (values that occur after the ? in the URL). Values will be bound to the URL parameters in a "first=second" format. Values that match URL parameters from the RESTDataSource URL will override the values from the URL, while values that do not match existing URL parameters will be appended to the URL. See Pair, Map_Pair, and Dictionary_Pair [page 123]. To remove all params from the URL, send [ Nothing ]. To remove specific params, send [ Pair( "paramToRemove" , Nothing ) ]; send multiple Pairs to specify multiple values and/ or remove multiple URL parameters. pathParams Vector An optional Vector of string values of URL path parameters (values that occur after the server:port and before the ? in the URL). Values from the Vector will appear in order with / separators between them. The pathParams from the RESTDataSource URL will be processed in order while the pathParams Vector is processed in order; the values from the pathParams Vector will override the corresponding values from the RESTDataSource URL unless the Vector value is a blank string (indicates the value is kept from the RESTDataSource URL). Use the Nothing object to delete pathParams from the URL. If there are more values in the Vector than the RESTDataSource URL, they will be appended to the URL. headers Vector An optional Vector of Pair values that are sent as HTTP headers in a "name: value" format. Values will be header-encoded. See Pair, Map_Pair, and Dictionary_Pair [page 123]. responseHeaders Vector& (Output) An optional Vector that is filled in with Pair(string,string) objects representing the HTTP headers that are received. See Pair, Map_Pair, and Dictionary_Pair [page 123].

SBM ModScript Reference Guide 277 Chapter 3: Programming SBM ModScript

Return

Type Description

bool Returns true if the call succeeds. On failure, Shell.GetLastErrorMessage() will provide more information.

Technical Details SBM ModScript version: 11.4. Example

var result = " "; //Create AppRecord of RESTDATASOURCE table var restSource = Ext.CreateAppRecord(Ext.TableId("TS_RESTDATASOURCE")); restSource.ReadByColumn("TS_NAME", "JSONPlaceHolder1"); var sPostData = //Use Map with to_json to format JSON post data ["name": "myObjName", "value1": 17, "value2": 5.7, "arrayData": [1,2,"3",4] //Use Vector for JSON array ].to_json(); if (!restSource.Call(HTTPVerbConstants.PUT , result, sPostData)){ // write an error to Event Viewer Ext.LogErrorMsg("Rest call failed in script " + __FILE__ + ":\n" + Shell.GetLastErrorMessage() );

// write an error to Active Diagnostics ADLog.Message( __FILE__, __LINE__, ADLogLevelConstants.ERROR, "Rest call failed:\n" + Shell.GetLastErrorMessage() );

Shell.RedoMessage() = "Rest call failed";

ExitScript(); }

Notes Use with HTTPVerbConstants.PUT to invoke a REST PUT call. Default timeout is 30 seconds. To override the default timeout value, you must add a new entry to the TS_SYSTEMSETTINGS table called DefaultRESTTimeout with TS_DATATYPE set to 1 and specify the desired timeout in the TS_LONGVALUE column. The SBMProxy only allows certain HTTP verbs; therefore, use UseSBMProxy( false ) if necessary. Override the default timeout by changing the value of Shell.RESTTimeout()—the expected value is an integer number of seconds. Tip: To view a script that provides sample code for using params and pathParams, refer to the RESTDataSource.tscm script in the installDir\SBM\Application Engine\ModScript_Examples directory on the Application Engine server or see Sample Five: RESTDataSource [page 374].

278 Solutions Business Manager (SBM) Related Topics RESTDataSource [page 269]

UseSBMProxy()

Sets whether to use SBMProxy or not.

Function Signature

void UseSBMProxy( bool value )

Parameters

Parameter Type Description

value bool Specify false to bypass; specify true to use SBMProxy.

Return

Type Description

None

Technical Details SBM ModScript version: 11.4. Notes By default, RESTDataSource calls go through the SBMProxy. This enables features such as OAUTH2 authentication. However, if desired, SBMProxy can be bypassed via UseSBMProxy( false ). Related Topics RESTDataSource [page 269] bool UseSBMProxy()

Returns whether SBMProxy will be used or not; true by default.

Function Signature

bool UseSBMProxy()

SBM ModScript Reference Guide 279 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns whether SBMProxy will be used or not; true by default.

Technical Details SBM ModScript version: 11.4. Notes None. Related Topics RESTDataSource [page 269] SchemaColumn Description Provides information about columns for AppRecord.GetSchemaColumns(). See GetSchemaColumns() [page 171]. Inheritance SchemaColumn does not inherit from any object type. Properties

Property Type Description

string name The database name of the column without the TS_ prefix.

length int • fixed-length text fields: The number of unicode code points that are supported.

• non-Fixed length text fields: 0

• numeric: The number of bytes in the underlying data member.

280 Solutions Business Manager (SBM) Property Type Description

type int The number of bytes in the underlying data member.

SQLColumnDef Description Provides information about a single column. See also AppDB.ReadDynaSQL. Inheritance SQLColumnDef does not inherit from any object type. Constructors • SQLColumnDef() – Creates a SQLColumnDef object.

• SQLColumnDef( DBTypeConstants dbType, string name ) – Creates a SQLColumnDef object and populates members.

• SQLColumnDef( DBTypeConstants dbType, string name, SQLColumnDefOutputHint hint ) – Creates a SQLColumnDef object and populates members.

Properties

Property Type Description

int dbType Must have a value from DBTypeConstants, used to identify the type of column in the db that is bound to.

string name Used for database column binding.

SQLColumnDefOutputHint outputHint Used to help determine what type of object to return for the column. See SQLColumnDefOutputHint [page 354].

Example var out = []; // creates an empty Vector

Shell.Db().ReadDynaSQL( "select TS_ID,TS_NAME,TS_LASTLOGINDATE from TS_USERS where TS_STATUS=? order by TS_NAME", [ SQLColumnDef(DBTypeConstants.INTEGER,"TS_ID"), SQLColumnDef(DBTypeConstants.VARCHAR,"TS_NAME"), SQLColumnDef(DBTypeConstants.BIGINT,"TS_LASTLOGINDATE", SQLColumnDefOutputHint.TimeT) ], out, [Pair( DBTypeConstants.INTEGER, 0)] );

SBM ModScript Reference Guide 281 Chapter 3: Programming SBM ModScript

for ( row : out ){ Ext.WriteStream( "${row[0]}\t${row[1]}\t${row[2].date}" ); }

TempFile Description (SBM On-Premise only) A class that creates a temporary file that exists for the scope of the object. This can be used in conjunction with executing a command-line executable or PowerShell script that needs to write output to a file. Constructors • TempFile(): Creates a temporary file in the installDir\SBM\Application Engine\tmp folder. This file will be deleted when this object goes out of scope.

Methods • GetFileName() [page 282]

GetFileName()

Gets the full file name with path.

Function Signature

string GetFileName()

Parameters

Parameter Type Description

None

Return

Type Description

string The full file path.

Technical Details SBM ModScript version: 11.4.

282 Solutions Business Manager (SBM) Example var f = TempFile(); Ext.WriteTextFile( f.GetFileName(), "Information\n" ); Ext.AppendTextFile( f.GetFileName(), "More Info\n" ); Ext.WriteStream( Ext.ReadTextFile( f.GetFileName() ) );

Example with PowerShell:

// create a temporary file, will get cleaned up var file = TempFile();

// execute PowerShell script, passing in TempFile’s file path Ext.NewTaskWait( "powershell", "d:\\myPowerShell.ps1 -filePath \"" + file.GetFileName() + "\"" );

// read from the file var s = Ext.ReadTextFile( file.GetFileName() );

// do something with PowerShell output Ext.WriteStream( s );

PowerShell:

# pull $filePath parameter from command line arguments param ([Parameter(Mandatory=$true)][string]$filePath )

# write data to the file at the provided path Add-Content $filePath "PowerShell output data"

Notes None. Related Topics TempFile [page 282] TimeMillis Description Stores a point in time as milliseconds in UnixEpoch format. Inheritance TimeMillis does not inherit from any object type. Global Methods Free functions that create a TimeMillis. • TimeMillis TimeMillisNow() – Returns a TimeMillis set to current time.

• TimeMillis TimeMillisDate() – Returns a TimeMillis set to current date (time truncated to midnight UTC).

SBM ModScript Reference Guide 283 Chapter 3: Programming SBM ModScript

Constructors • TimeMillis() – Creates a TimeMillis with date equal to 0.

• TimeMillis( milliseconds ) – Creates a TimeMillis with date equal to milliseconds.

• TimeMillis( TimeT ) – Creates a TimeMillis with date equal to the date in TimeT.

Operators • TimeMillis& operator=( TimeMillis v ): Copies the values from TimeMillis v. Returns this object.

• bool operator ==( TimeMillis v ): Returns true if both TimeMillis objects represent the same moment in time.

• bool operator !=( TimeMillis v ): Returns true if the TimeMillis objects represent different moment in time.

• bool operator <=( TimeMillis v ): Returns true if the TimeMillis on the left represents the same moment in time or an earlier moment in time than the TimeMillis on the right of the operator.

• bool operator >=( TimeMillis v ): Returns true if the TimeMillis on the left represents the same moment in time or a later moment in time than the TimeMillis on the right of the operator.

• bool operator <( TimeMillis v ): Returns true if the TimeMillis on the left represents an earlier moment in time than the TimeMillis on the right of the operator.

• bool operator >( TimeMillis v ): Returns true if the TimeMillis on the left represents a later moment in time than the TimeMillis on the right of the operator.

Properties

Property Type Description

date int64 Number of milliseconds since 1/1/1970 UTC (GMT).

Methods • ParseDateText() [page 285]

• ParseDateText() - Custom Format [page 286]

• FormatDateText() [page 287]

• FormatDateText() - Custom Format [page 289]

• ToTimePoint() [page 290]

• Add() [page 291]

• TruncateToDateOnly() [page 292]

284 Solutions Business Manager (SBM) • ToVariant() [page 293]

ParseDateText()

Parses a human-readable date string into a TimeMillis using built-in date formats. None of the built-in formats recognize milliseconds.

Function Signature

void ParseDateText( value, int attrib )

void ParseDateText( value, int attrib, TimeZone tz, Locale loc, int dateformat, int timeformat )

Parameters

Parameter Type Description

value string The text to parse.

attrib int See DateTimeAttributeConstants [page 347] for values.

tz TimeZone The time zone used to determine the point in time represented by the text. If not provided, the current user's time zone is used.

loc Locale The locale used during parsing. Especially important if dateformat is set to DateFormatConstants.FROM_LOCALE. Helps identify keywords such as "AM" and "PM".

dateformat int The date format. See DateFormatConstants [page 345].

timeformat int The time format. See TimeFormatConstants [page 355]. Ignored if dateformat is DateFormatConstants.FROM_LOCALE.

Return

Type Description

None

Technical Details SBM ModScript version: 11.4.

SBM ModScript Reference Guide 285 Chapter 3: Programming SBM ModScript

Example

var t = TimeMillis(); t.ParseDateText( "12/24/2018 11:59:59 pm", DateTimeAttributeConstants.DATETIME, CreateTimeZone("MST"), CreateLocale("en_US"), DateFormatConstants.MM_DD_YYYY, TimeFormatConstants.TWELVE_HOUR ); Ext.WriteStream( t.date );

Result:

1545721199000

Notes None. Related Topics TimeMillis [page 283]

ParseDateText() - Custom Format

Parses a human-readable date string into a TimeMillis using a custom format.

Function Signature

bool ParseDateText( value, string format )

bool ParseDateText( value, string format, TimeZone tz, Locale loc )

Parameters

Parameter Type Description

value string The text to parse.

format string A string with symbols and literals. See notes below.

tz TimeZone Timezone used to determine the point in time represented by the text. If not provided, the current user's timezone is used.

loc Locale Locale used during parsing. Especially important if dateformat is set to DateFormatConstants.FROM_LOCALE. Helps identify keywords such as "AM", "PM", month names, etc.

286 Solutions Business Manager (SBM) Return

Type Description

bool Returns true if date parsing was successful.

Technical Details SBM ModScript version: 11.4. Example var t = TimeMillis(); t.ParseDateText( "2/2/2018 5:22:06:205 PM", "M/d/y h:m:s:Sa" ); Ext.WriteStream( t.date ); Ext.WriteStream( t.FormatDateText( "MM/dd/yyyy HH:mm:ss:SSS z" ) );

Result:

1517617326205 02/02/2018 17:22:06:205 MST

Notes Format value is a string with symbols and literals (literals can be escaped inside single tick ( ' ) values if necessary). Symbols are described in ICU documentation. When formatting, the number of times a symbol occurs determines the length of values during output. For instance, "M" will output January as "1", but "MM" will output January as "01". When parsing, it is often best to provide the simplest option "M", which will work with both "1" and "01". TimeMillis is measured in milliseconds and can therefore parse and format millisecond values meaningfully. Related Topics TimeMillis [page 283]

FormatDateText()

Formats a date into a human-readable string using built-in date formats. None of the built-in formats recognize milliseconds.

Function Signature

string FormatDateText( attrib ) string FormatDateText( attrib, TimeZone tz, Locale loc, int dateformat, int timeformat, int dateFormatPref )

SBM ModScript Reference Guide 287 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

attrib int See DateTimeAttributeConstants [page 347] for values.

tz TimeZone Timezone used to convert the point in time represented by the TimeT to text. If not provided, the current user's timezone is used.

loc Locale Locale used during formatting. Especially important if dateformat is set to DateFormatConstants.FROM_LOCALE. If not provided, the current user's preference is used.

dateformat int See DateFormatConstants [page 345]. Note that when the dateformat parameter is DateFormatConstants.FROM_LOCALE, the timeformat parameter is ignored. If not provided, the current user's preference is used.

timeformat int See TimeFormatConstants [page 355]. If not provided, the current user's preference is used.

dateFormatPref int See DateFormatFromLocaleConstants [page 346]. Only used when dateformat is set to DateFormatConstants.FROM_LOCALE. Indicates whether to use the terse or verbose format of the locale. If not provided, the current user's preference is used.

Return

Type Description

string The date in human-readable text format.

Technical Details SBM ModScript version: 11.4. Example

var t = TimeMillis(1545721199278ll); var s = t.FormatDateText( DateTimeAttributeConstants.DATETIME, CreateTimeZone("MST"), CreateLocale("en_US"), DateFormatConstants.FROM_LOCALE, 0, DateFormatFromLocaleConstants.FULL ); Ext.WriteStream( s );

288 Solutions Business Manager (SBM) Result:

Monday, December 24, 2018 11:59:59 PM

Notes None. Related Topics TimeMillis [page 283]

FormatDateText() - Custom Format

Formats a date into a human-readable string using a custom date format.

Function Signature

string FormatDateText( string format )

string FormatDateText( string format, TimeZone tz, Locale loc )

Parameters

Parameter Type Description

format string A string with symbols and literals. See notes below.

tz TimeZone The time zone used to convert the point in time represented by the TimeT to text. If not provided, the current user's timezone is used.

loc Locale Locale used during formatting. Especially important if dateformat is set to DateFormatConstants.FROM_LOCALE. Indicates language to use for keywords such as "AM", "PM", month names, day of week names, etc.

Return

Type Description

string The date in human-readable text format.

Technical Details SBM ModScript version: 11.4.

SBM ModScript Reference Guide 289 Chapter 3: Programming SBM ModScript

Example

var t = TimeMillis(1545721199999ll); Ext.WriteStream( t.FormatDateText( "EEEE, MMMM d, yyyy h:mm:ss:SSS a z" ) );

Result:

Monday, December 24, 2018 11:59:59:999 PM MST

Notes Format value is a string with symbols and literals (literals can be escaped inside single tick ( ' ) values if necessary). Symbols are described in ICU documentation. When formatting, the number of times a symbol occurs determines the length of values during output. For instance, "M" will output January as "1", but "MM" will output January as "01". When parsing, it is often best to provide the simplest option "M", which will work with both "1" and "01". TimeMillis is measured in milliseconds and can therefore parse and format millisecond values meaningfully. Related Topics TimeMillis [page 283]

ToTimePoint()

Resolves date into a TimePoint that represents year/month/day/etc. based on the specified TimeZone.

Function Signature

TimePoint ToTimePoint( TimeZone tz )

Parameters

Parameter Type Description

tz TimeZone The time zone used to convert the point in time represented by the TimeT to the TimePoint.

Return

Type Description

TimePoint A breakdown of the fields in a date (year, month, day, etc.) See TimePoint [page 294].

Technical Details SBM ModScript version: 11.4.

290 Solutions Business Manager (SBM) Example var t = TimeMillis(1545721199999ll); var tp = t.ToTimePoint( CreateTimeZone("MST") ); Ext.WriteStream( "${tp.getDate()}/${tp.getMonth()}/${tp.getFullYear()} " + "${tp.getHours()}:${tp.getMinutes()}:${tp.getSeconds()}:${tp.getMilliseconds()}" );

Result:

11/24/2018 23:59:59:999

Notes None. Related Topics TimeMillis [page 283]

Add()

Adds or subtracts to date using TimeZone rules (to subtract use negative values).

Function Signature

void Add( TimeZone tz, int years, int months int days, int hours, int minutes, int seconds, int millis )

Parameters

Parameter Type Description

tz TimeZone The time zone used to determine the point in time represented by the text. If not provided, the current user's timezone is used.

years int The number of years to add or subtract from the current date. (Use negative values to subtract).

months int The number of months to add or subtract from the current date. (Use negative values to subtract).

days int The number of days to add or subtract from the current date. (Use negative values to subtract).

hours int The number of hours to add or subtract from the current date. (Use negative values to subtract).

SBM ModScript Reference Guide 291 Chapter 3: Programming SBM ModScript

Parameter Type Description

minutes int The number of minutes to add or subtract from the current date. (Use negative values to subtract).

seconds int The number of seconds to add or subtract from the current date. (Use negative values to subtract).

millis int The number of milliseconds to add or subtract from the current date. (Use negative values to subtract).

Return

Type Description

None

Technical Details SBM ModScript version: 11.4. Example

var t = TimeMillis(1545721199999ll); t.Add( CreateTimeZone("MST"), -1, 0, 0, 1, -60, 0, 1 ); Ext.WriteStream( t.FormatDateText( "EEEE, MMMM d, yyyy h:mm:ss:SSS a z" ) );

Result:

Monday, December 25, 2017 12:00:00:000 AM MST

Notes None. Related Topics TimeMillis [page 283]

TruncateToDateOnly()

Rounds date down to midnight UTC.

Function Signature

void TruncateToDateOnly()

292 Solutions Business Manager (SBM) Parameters

Parameter Type Description

None

Return

Type Description

None

Technical Details SBM ModScript version: 11.4. Example var t = TimeMillis(1545721199999ll); t.TruncateToDateOnly(); Ext.WriteStream( t.FormatDateText( "EEEE, MMMM d, yyyy h:mm:ss:SSS a z", CreateUTCTimeZone(), CreateLocale("en_UK") ) );

Result:

Tuesday, December 25, 2018 12:00:00:000 AM GMT+00:00

Notes None. Related Topics TimeMillis [page 283]

ToVariant()

Returns a Variant initialized with date.

Function Signature

Variant ToVariant()

Parameters

Parameter Type Description

None

SBM ModScript Reference Guide 293 Chapter 3: Programming SBM ModScript

Return

Type Description

Variant Variant that internally represents the date.

Technical Details SBM ModScript version: 11.4. Notes None. Related Topics TimeMillis [page 283] TimePoint Description Provides a breakdown of a point in time based on a time zone. Inheritance TimePoint does not inherit from any object type. Constructors • TimePoint(): Creates a TimePoint populated with the current moment in time and UTC timezone.

• TimePoint( TimePoint v ): Creates a TimePoint copying the values from "v".

• TimePoint( TimeZone tz ): Creates a TimePoint populated with the current moment in time and uses "tz" as the timezone.

• TimePoint( TimeMillis v, TimeZone tz ): Creates a TimePoint populated with the moment in time from "v" and uses "tz" as the timezone. TimeT can implicitly convert to a TimeMillis, allowing this function to be used with TimeT values as well.

Operators • TimePoint& operator=( TimePoint v ): Copies the values from TimePoint v. Returns this object.

• bool operator ==( TimePoint v ): Returns true if both TimePoints represent the same moment in time, regardless of TimeZone.

• bool operator !=( TimePoint v ): Returns true if the TimePoints represent different moment in time, regardless of TimeZone.

• bool operator <=( TimePoint v ): Returns true if the TimePoint on the left represents the same moment in time or an earlier moment in time than the TimePoint on the right of the operator, regardless of TimeZone.

294 Solutions Business Manager (SBM) • bool operator >=( TimePoint v ): Returns true if the TimePoint on the left represents the same moment in time or a later moment in time than the TimePoint on the right of the operator, regardless of TimeZone.

• bool operator <( TimePoint v ): Returns true if the TimePoint on the left represents an earlier moment in time than the TimePoint on the right of the operator, regardless of TimeZone.

• bool operator >( TimePoint v ): Returns true if the TimePoint on the left represents a later moment in time than the TimePoint on the right of the operator, regardless of TimeZone.

Methods • int getFullYear(): returns the year

• int getMonth(): returns the month: 0-11

• int getDate(): returns the date: 1-31

• int getHours(): returns the hour of day: 0-23

• int getMinutes(): returns the minutes: 0-59

• int getSeconds(): returns the seconds: 0-59

• int getMilliseconds(): returns the milliseconds: 0-999

• int getDayOfWeek(): returns the day of week: 0-6 (Sunday=0)

• int getDayOfYear(): returns the day of year: 1-366

• void set( TimeMillis v, TimeZone tz ): Populates a TimePoint with the moment in time from "v" and uses "tz" as the timezone. TimeT can implicitly convert to a TimeMillis, allowing this function to be used with TimeT values as well.

• TimeZone getTimeZone(): Returns the TimeZone that the TimePoint has been initialized with.

• TimeMillis to_TimeMillis(): Returns the TimeMillis value that the TimePoint was initialized with. This value is what is used for all comparison operators such as "==".

Example var v1 = TimeMillis( 1516667515006ll ).ToTimePoint( CreateTimeZone("MST") ); var dayOfWeek = v1.getDayOfWeek(); var fr = CreateLocale("fr"); // Create French locale Ext.WriteStream( fr.GetDayOfWeekName(dayOfWeek) ); // Output day of week using French locale

Result: lundi

SBM ModScript Reference Guide 295 Chapter 3: Programming SBM ModScript

TimeT Description Stores a point in time as seconds in UnixEpoch format. Inheritance TimeT does not inherit from any object type. Global Methods Free functions that create a TimeT. • TimeT TimeTNow() – Returns a TimeT set to current time.

• TimeT TimeTDate() – Returns a TimeT set to current date (time truncated to midnight UTC).

Constructors • TimeT() – Creates a TimeT with date equal to 0.

• TimeT( seconds ) – Creates a TimeT with date equal to seconds.

Operators • TimeT& operator=( TimeT v ): Copies the values from TimeT v. Returns this object.

• bool operator ==( TimeT v ): Returns true if both TimeTs represent the same moment in time.

• bool operator !=( TimeT v ): Returns true if the TimeTs represent different moment in time.

• bool operator <=( TimeT v ): Returns true if the TimeT on the left represents the same moment in time or an earlier moment in time than the TimeT on the right of the operator.

• bool operator >=( TimeT v ): Returns true if the TimeT on the left represents the same moment in time or a later moment in time than the TimeT on the right of the operator.

• bool operator <( TimeT v ): Returns true if the TimeT on the left represents an earlier moment in time than the TimeT on the right of the operator.

• bool operator >( TimeT v ): Returns true if the TimeT on the left represents a later moment in time than the TimeT on the right of the operator.

Properties

Property Type Description

date int64 Number of seconds since midnight 1/1/1970 UTC (GMT).

296 Solutions Business Manager (SBM) Methods • ParseDateText() [page 297]

• ParseDateText() - Custom Format [page 298]

• FormatDateText() [page 300]

• FormatDateText() - Custom Format [page 301]

• ToTimePoint() [page 302]

• Add() [page 303]

• TruncateToDateOnly() [page 305]

• ToVariant() [page 306]

ParseDateText()

Parses a human-readable date string into a TimeT using built-in date formats.

Function Signature

void ParseDateText( value, int attrib )

void ParseDateText( value, int attrib, TimeZone tz, Locale loc, int dateformat, int timeformat )

Parameters

Parameter Type Description

value string The text to parse.

attrib int See DateTimeAttributeConstants [page 347] for values.

tz TimeZone The time zone used to determine the point in time represented by the text. If not provided, the current user's time zone is used.

loc Locale The locale used during parsing. Especially important if dateformat is set to DateFormatConstants.FROM_LOCALE. Helps identify keywords such as "AM" and "PM".

dateformat int The date format. See DateFormatConstants [page 345].

SBM ModScript Reference Guide 297 Chapter 3: Programming SBM ModScript

Parameter Type Description

timeformat int The time format. See TimeFormatConstants [page 355]. Ignored if dateformat is DateFormatConstants.FROM_LOCALE.

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Example

var t = TimeT(); t.ParseDateText( "12/24/2018 11:59:59 pm", DateTimeAttributeConstants.DATETIME, CreateTimeZone("MST"), CreateLocale("en_US"), DateFormatConstants.MM_DD_YYYY, TimeFormatConstants.TWELVE_HOUR ); Ext.WriteStream( t.date );

Result:

1545721199

Notes None. Related Topics TimeT [page 296]

ParseDateText() - Custom Format

Parses a human-readable date string into a TimeT using a custom format.

Function Signature

bool ParseDateText( value, string format )

bool ParseDateText( value, string format, TimeZone tz, Locale loc )

298 Solutions Business Manager (SBM) Parameters

Parameter Type Description

value string The text to parse.

format string A string with symbols and literals. See notes below.

tz TimeZone Timezone used to determine the point in time represented by the text. If not provided, the current user's timezone is used.

loc Locale Locale used during parsing. Especially important if dateformat is set to DateFormatConstants.FROM_LOCALE. Helps identify keywords such as "AM", "PM", month names, etc.

Return

Type Description

bool Returns true if date parsing was successful.

Technical Details SBM ModScript version: 11.4. Example var t = TimeT(); t.ParseDateText( "2/2/2018 5:22:06:205 PM", "M/d/y h:m:s:Sa" ); Ext.WriteStream( t.date ); Ext.WriteStream( t.FormatDateText( "MM/dd/yyyy HH:mm:ss:SSS z" ) );

Result:

1517620926 02/02/2018 17:22:06:000 PST

Notes Format value is a string with symbols and literals (literals can be escaped inside single tick ( ' ) values if necessary). Symbols are described in ICU documentation. When formatting, the number of times a symbol occurs determines the length of values during output. For instance, "M" will output January as "1", but "MM" will output January as "01". When parsing, it is often best to provide the simplest option "M", which will work with both "1" and "01". Keep in mind that TimeT is measured in seconds, therefore millisecond values will always be zero.

SBM ModScript Reference Guide 299 Chapter 3: Programming SBM ModScript

Related Topics TimeT [page 296]

FormatDateText()

Formats a date into a human-readable string using built-in date formats.

Function Signature

string FormatDateText( attrib )

string FormatDateText( attrib, TimeZone tz, Locale loc, int dateformat, int timeformat, int dateFormatPref )

Parameters

Parameter Type Description

attrib int See DateTimeAttributeConstants [page 347] for values.

tz TimeZone Timezone used to convert the point in time represented by the TimeT to text. If not provided, the current user's timezone is used.

loc Locale Locale used during formatting. Especially important if dateformat is set to DateFormatConstants.FROM_LOCALE. If not provided, the current user's preference is used.

dateformat int See DateFormatConstants [page 345]. Note that when the dateformat parameter is DateFormatConstants.FROM_LOCALE, the timeformat parameter is ignored. If not provided, the current user's preference is used.

timeformat int See TimeFormatConstants [page 355]. If not provided, the current user's preference is used.

dateFormatPref int See DateFormatFromLocaleConstants [page 346]. Only used when dateformat is set to DateFormatConstants.FROM_LOCALE. Indicates whether to use the terse or verbose format of the locale. If not provided, the current user's preference is used.

300 Solutions Business Manager (SBM) Return

Type Description

string The date in human-readable text format.

Technical Details SBM ModScript version: 11.3. Example var t = TimeT(1545721199ll); var s = t.FormatDateText( DateTimeAttributeConstants.DATETIME, CreateTimeZone("MST"), CreateLocale("en_US"), DateFormatConstants.FROM_LOCALE, 0, DateFormatFromLocaleConstants.FULL ); Ext.WriteStream( s );

Result:

Monday, December 24, 2018 11:59:59 PM

Notes None. Related Topics TimeT [page 296]

FormatDateText() - Custom Format

Formats a date into a human-readable string using a custom date format.

Function Signature

string FormatDateText( string format )

string FormatDateText( string format, TimeZone tz, Locale loc )

Parameters

Parameter Type Description

format string A string with symbols and literals. See notes below.

tz TimeZone The time zone used to convert the point in time represented by the TimeT to text. If not provided, the current user's timezone is used.

SBM ModScript Reference Guide 301 Chapter 3: Programming SBM ModScript

Parameter Type Description

loc Locale Locale used during formatting. Especially important if dateformat is set to DateFormatConstants.FROM_LOCALE. Indicates language to use for keywords such as "AM", "PM", month names, day of week names, etc.

Return

Type Description

string The date in human-readable text format.

Technical Details SBM ModScript version: 11.4. Example

var t = TimeT(1545721199ll); Ext.WriteStream( t.FormatDateText( "EEEE, MMMM d, yyyy h:mm:ss a z" ) );

Result:

Monday, December 24, 2018 11:59:59 PM MST

Notes Format value is a string with symbols and literals (literals can be escaped inside single tick ( ' ) values if necessary). Symbols are described in ICU documentation. When formatting, the number of times a symbol occurs determines the length of values during output. For instance, "M" will output January as "1", but "MM" will output January as "01". When parsing, it is often best to provide the simplest option "M", which will work with both "1" and "01". Keep in mind that TimeT is measured in seconds, therefore millisecond values will always be zero. Related Topics TimeT [page 296]

ToTimePoint()

Resolves date into a TimePoint that represents year/month/day/etc. based on the specified TimeZone.

Function Signature

TimePoint ToTimePoint( TimeZone tz )

302 Solutions Business Manager (SBM) Parameters

Parameter Type Description

tz TimeZone The time zone used to convert the point in time represented by the TimeT to the TimePoint.

Return

Type Description

TimePoint A breakdown of the fields in a date (year, month, day, etc.) See TimePoint [page 294].

Technical Details SBM ModScript version: 11.4. Example var t = TimeT(1545721199ll); var tp = t.ToTimePoint( CreateTimeZone("MST") ); Ext.WriteStream( "${tp.getDate()}/${tp.getMonth()}/${tp.getFullYear()} " + "${tp.getHours()}:${tp.getMinutes()}:${tp.getSeconds()}" );

Result:

11/24/2018 23:59:59

Notes None. Related Topics TimeT [page 296]

Add()

Adds or subtracts to date using TimeZone rules (to subtract use negative values).

Function Signature

void Add( TimeZone tz, int years, int months int days, int hours, int minutes, int seconds )

SBM ModScript Reference Guide 303 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

tz TimeZone The time zone used to determine the point in time represented by the text. If not provided, the current user's timezone is used.

years int The number of years to add or subtract from the current date. (Use negative values to subtract).

months int The number of months to add or subtract from the current date. (Use negative values to subtract).

days int The number of days to add or subtract from the current date. (Use negative values to subtract).

hours int The number of hours to add or subtract from the current date. (Use negative values to subtract).

minutes int The number of minutes to add or subtract from the current date. (Use negative values to subtract).

seconds int The number of seconds to add or subtract from the current date. (Use negative values to subtract).

Return

Type Description

None

Technical Details SBM ModScript version: 11.3. Example

var t = TimeT(1545721199ll); t.Add( CreateTimeZone("MST"), -1, 0, 0, 1, -60, 1 ); Ext.WriteStream( t.FormatDateText( "EEEE, MMMM d, yyyy h:mm:ss a z" ) );

Result:

Monday, December 25, 2017 12:00:00 AM MST

304 Solutions Business Manager (SBM) Notes None. Related Topics TimeT [page 296]

TruncateToDateOnly()

Rounds date down to midnight UTC.

Function Signature

void TruncateToDateOnly()

Parameters

Parameter Type Description

None

Return

Type Description

None

Technical Details SBM ModScript version: 11.4. Example var t = TimeT(1545721199ll); t.TruncateToDateOnly(); Ext.WriteStream( t.FormatDateText( "EEEE, MMMM d, yyyy h:mm:ss a z", CreateUTCTimeZone(), CreateLocale("en_UK") ) );

Result:

Tuesday, December 25, 2018 12:00:00 AM GMT+00:00

Notes None. Related Topics TimeT [page 296]

SBM ModScript Reference Guide 305 Chapter 3: Programming SBM ModScript

ToVariant()

Returns a Variant initialized with date.

Function Signature

Variant ToVariant()

Parameters

Parameter Type Description

None

Return

Type Description

Variant Variant that internally represents the date.

Technical Details SBM ModScript version: 11.4. Notes None. Related Topics TimeT [page 296] TimeZone Description Provides functions that create a TimeZone. You can create a TimeZone for the user you are acting as, or you use the UTC TimeZone, or a TimeZone delineating string. Inheritance TimeZone does not inherit from any object type. Methods • CreateUserTimeZone() [page 307]

• CreateUTCTimeZone() [page 307]

• CreateTimeZone() [page 308]

• GetName() [page 309]

306 Solutions Business Manager (SBM) • GetID() [page 310]

CreateUserTimeZone()

Returns the current user's TimeZone.

Function Signature

TimeZone CreateUserTimeZone()

Parameters

Parameter Type Description

None

Return

Type Description

TimeZone A TimeZone object based on the user's preferred time zone.

Technical Details SBM ModScript version: 11.3. Example var tz = CreateUserTimeZone(); // result assumes user has MST time zone var loc = CreateLocale("en_US"); var t = TimeT(1517620926); Ext.WriteStream( t.FormatDateText("yyyy-MM-dd hh:mm:ss a", tz, loc ) );

Result:

2018-02-02 06:22:06 PM

Notes This method creates a TimeZone object using the user's time zone. The TimeZone will change depending on who is logged in because the specified time zone depends on the user. Related Topics TimeZone [page 306]

CreateUTCTimeZone()

Returns the UTC TimeZone.

SBM ModScript Reference Guide 307 Chapter 3: Programming SBM ModScript

Function Signature

TimeZone CreateUTCTimeZone()

Parameters

Parameter Type Description

None

Return

Type Description

TimeZone A TimeZone object based on the UTC time zone.

Technical Details SBM ModScript version: 11.3. Example

var tz = CreateUTCTimeZone(); var loc = CreateLocale("en_US"); var t = TimeT(1517620926); Ext.WriteStream( t.FormatDateText("yyyy-MM-dd hh:mm:ss a", tz, loc ) );

Result:

2018-02-03 01:22:06 AM

Notes None. Related Topics TimeZone [page 306]

CreateTimeZone()

Creates a TimeZone specified by value.

Function Signature

TimeZone CreateTimeZone( value )

308 Solutions Business Manager (SBM) Parameters

Parameter Type Description

value string Specifies the TimeZone using a value like "MST", "America/ Denver", "US/Mountain".

Return

Type Description

TimeZone A TimeZone object based on the text that is provided.

Technical Details SBM ModScript version: 11.3. Example var tz = CreateTimeZone("MST"); var loc = CreateLocale("en_US"); var t = TimeT(1517620926); Ext.WriteStream( t.FormatDateText("yyyy-MM-dd hh:mm:ss a", tz, loc ) );

Result:

2018-02-02 06:22:06 PM

Notes None. Related Topics TimeZone [page 306]

GetName()

Gets the time zone name.

Function Signature

string GetName()

Parameters

Parameter Type Description

None

SBM ModScript Reference Guide 309 Chapter 3: Programming SBM ModScript

Return

Type Description

string The name of the time zone.

Technical Details SBM ModScript version: 11.3. Example

var tz = CreateTimeZone("MST"); Ext.WriteStream( tz.GetName() );

Result:

GMT-07:00

Notes None. Related Topics TimeZone [page 306]

GetID()

Gets the time zone ID.

Function Signature

string GetID()

Parameters

Parameter Type Description

None

Return

Type Description

string The ID of the time zone.

Technical Details SBM ModScript version: 11.3.

310 Solutions Business Manager (SBM) Example var tz = CreateTimeZone("MST"); Ext.WriteStream( tz.GetId() );

Result:

MST

Notes None. Related Topics TimeZone [page 306] Transition Description Identifies the type of transition. Inheritance AppRecord [page 159] ->Transition Methods • GetType() [page 311]

GetType()

Returns the transition type.

Function Signature

int GetType()

Parameters

Parameter Type Description

None

Return

Type Description

int The transition type that corresponds to TransitionTypeConstants [page 356].

SBM ModScript Reference Guide 311 Chapter 3: Programming SBM ModScript

Technical Details SBM ModScript version: 11.3. Example

var transRecordList = Ext.CreateAppRecordList( Ext.TableId("TS_TRANSITIONS")); transRecordList.ReadByColumn("PROJECTID", 2); // actually workflow id for ( tran : transRecordList ){ if( tran.GetType() == TransitionTypeConstants.REGULAR) { Ext.WriteStream( tran.GetName() + "
" ); } }

Result:

Submit Need More Info Info Provided Defer ...

Notes None. Related Topics Transition [page 311] TreeItem Description TreeItem is an object type for internal use and supports the concept of hierarchical relationships ("trees"). Nested objects, such as projects, workflows, and folders inherit from TreeItem so they can support the following methods. TreeItem objects are never merely of type TreeItem; they must be a subtype of TreeItem. Inheritance AppRecord [page 159] -> TreeItem Properties

Property Type Description

SubList TreeList List of all TreeItem objects that are children of this TreeItem.

Methods • FindParent() [page 313]

312 Solutions Business Manager (SBM) • GetFullName() [page 313]

• HasChild() [page 314]

• IsParent() [page 315]

FindParent()

Retrieve the ancestor TreeItem object, given the ancestor's TS_ID.

Function Signature

TreeItem FindParent( id )

Parameters

Parameter Type Description

id int TS_ID of this item's ancestor TreeItem.

Return

Type Description

TreeItem TreeItem object representing the ancestor. If the parent is not found, returns null. Use is_var_null() to check for null.

Technical Details SBM ModScript version: 11.3. Notes Searches the ancestors of this TreeItem for a matching item. Related Topics TreeItem [page 312]

GetFullName()

Returns the full path name from the root of the tree to this item.

Function Signature

string GetFullName(delimiter)

SBM ModScript Reference Guide 313 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

delimiter string Optional. Defaults to a single space if omitted. The delimiter appears between each node of the tree. For example, a delimiter of "|" on a Project TreeItem might return "Base Project|Main Project|ACME Project".

Return

Type Description

string The full path name from the root of the tree to this TreeItem.

Technical Details SBM ModScript version: 11.3. Notes This method is used on subtype objects and can be used to generate full project names, workflow names, and folder names. Related Topics TreeItem [page 312]

HasChild()

Find out if another TreeItem is a descendent of this one.

Function Signature

bool HasChild( id )

Parameters

Parameter Type Description

id int TS_ID of the TreeItem to test for descendent status.

Return

Type Description

bool Returns true if the given TreeItem is a descendent of this one; false if not.

314 Solutions Business Manager (SBM) Technical Details SBM ModScript version: 11.3. Notes None. Related Topics TreeItem [page 312]

IsParent()

Find out if another TreeItem is an ancestor of this one.

Function Signature

bool IsParent( id )

Parameters

Parameter Type Description

id int TS_ID of the TreeItem to test for parent status.

Return

Type Description

bool Returns true if the given TreeItem is an ancestor of this one; false if not.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics TreeItem [page 312] TreeList Description A TreeList is an AppRecordList that holds TreeItem objects. Typically, a TreeList is obtained by referencing the SubList property of a TreeItem, and it represents a sub-tree of projects or folders. The tree can be traversed using TreeItem methods.

SBM ModScript Reference Guide 315 Chapter 3: Programming SBM ModScript

Inheritance AppRecordList [page 187] -> TreeList UGBase Description UGBase is an object type for internal use and supports concepts useful to users and groups. UGBase objects are never merely of type UGBase; they must be of type User. The type Group also inherits from UGBase and is created when Ext.CreateAppRecord is invoked using the group's table ID. Inheritance AppRecord [page 159] -> UGBase Methods • GetDisplayName() [page 316]

• Member() [page 317]

• UniqueName() [page 318]

GetDisplayName()

Returns the full name of the user or group.

Function Signature

string GetDisplayName()

Parameters

Parameter Type Description

None

Return

Type Description

string The full name of the user or group.

Technical Details SBM ModScript version: 11.3. Example

Ext.WriteStream( Shell.User().GetDisplayName() );

316 Solutions Business Manager (SBM) Result:

Chad Support

Notes None. Related Topics UGBase [page 316]

Member()

Used to determine whether a user is a member of a group.

Function Signature

bool Member( id )

Parameters

Parameter Type Description

id int If object is a User, TS_ID of the group to test for membership. If object is a Group, TS_ID of the user to test for membership.

Return

Type Description

bool True if the user belongs to the group.

Technical Details SBM ModScript version: 11.3. Example

Ext.WriteStream( Shell.User().Member( 6 ).to_string() );

Result: true

Notes None.

SBM ModScript Reference Guide 317 Chapter 3: Programming SBM ModScript

Related Topics UGBase [page 316]

UniqueName()

Gets the unique name for the user or group.

Function Signature

string UniqueName()

Parameters

Parameter Type Description

Return

Type Description

string This user's login name.

Technical Details SBM ModScript version: 11.3. Example

Ext.WriteStream( Shell.User().UniqueName() );

Result:

chad

Notes If the object is a group, this method returns the name of the group. If the object is a user, this method returns user's login ID. Related Topics UGBase [page 316] User Description This type represents an SBM user. All methods are inherited from the UGBase object type. Inheritance AppRecord [page 159] -> UGBase [page 316] -> User

318 Solutions Business Manager (SBM) VarFieldList Description Primary and Auxiliary tables allow the user to add columns, and these user-defined columns are known as "variable fields." A VarFieldList is a list of Field objects representing the variable fields of a primary or auxiliary item. Note that Field is a subtype of AppRecord. It is possible to create your own VarFieldList object, in which case it will contain any Field objects you choose to add to it, not necessarily corresponding to the variable fields for any existing table. Inheritance AppRecordList [page 187] -> VarFieldList Methods • ApplyProjectStateOverrides() [page 319]

• FindField() [page 320]

• FindSysField() [page 321]

• SelectAll() [page 321]

ApplyProjectStateOverrides()

Applies the field ordering and privilege sections from the item's current state to the item's field list.

Function Signature

void ApplyProjectStateOverrides()

Parameters

Parameter Type Description

None

Return

Type Description

None

Technical Details SBM ModScript version: 11.3.

SBM ModScript Reference Guide 319 Chapter 3: Programming SBM ModScript

Notes After calling ApplyProjectStateOverrides(), VarRecord.GetFieldValue() will then honor the current user's privileges. Related Topics VarFieldList [page 319]

FindField()

Finds the first field on the list that matches the given name or TS_ID.

Function Signature

Field FindField(fldNameOrId)

Parameters

Parameter Type Description

fldNameOrId Variant If a non-numeric string, the name of the field to be looked up. If all uppercase, it is taken as the field's database name. Otherwise, it is taken as the display name. The search is not case sensitive; case is only used to determine whether to search by database name or display name. Note that the database name cannot be changed, but the logical name can be changed. If not a non-numeric string, it is converted to an int and taken as the desired field's TS_ID.

Return

Type Description

Field object The first Field on the list to match the given name or ID. If no Field objects matched, it returns null. Check for null using is_var_null().

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics VarFieldList [page 319]

320 Solutions Business Manager (SBM) FindSysField()

Finds a field by syscode.

Function Signature

Field FindSysField(syscode)

Parameters

Parameter Type Description

syscode int The system code of the field to be found.

Return

Type Description

Field object The Field on the list matching the given syscode. If no Field objects matched, it returns null. Check for null using is_var_null().

Technical Details SBM ModScript version: 11.3. Notes System Fields are fields that have special built-in meaning to SBM. Every syscode field is unique within the field's table and identifies it by number. The SBM schema document lists all the system codes for each table. Related Topics VarFieldList [page 319]

SelectAll()

Can force all fields to be examined for changes (or ignored) on the next Update(), overriding the effect of the Field method Select().

Function Signature

void SelectAll( [selectFlag] )

SBM ModScript Reference Guide 321 Chapter 3: Programming SBM ModScript

Parameters

Parameter Type Description

selectFlag bool Optional. Defaults to true if not supplied. The value to which all Fields' select flags will be set.

Return

Type Description

None

Technical Details SBM ModScript version: 11.3 Notes Each Field object on the list has a "select flag" that indicates whether it will be skipped for performance reasons on the next Update(). If a Field's value is known not to have changed, it is often deselected. SelectAll() sets all fields' select flags to true or false, causing all fields to be examined or ignored, respectively. Related Topics VarFieldList [page 319] Variant Description A class that wraps multiple data types, especially for scripts that are converted from SBM AppScript to SBM ModScript. Variant is supported in SBM ModScript in order to ease conversion from SBM AppScript. Variant is modeled after VBScript's "Variant". The following data types can be represented by Variant:

Data Types Variant Data Type

bool Boolean

double Double

float Single

short Integer

322 Solutions Business Manager (SBM) Data Types Variant Data Type

int Long

int64_t Int64

uint64_t UInt64

string String

Variant date Date

AppRecord (and child classes) Object

AppDb Object

AppRecordList (and child classes) Object

Lib Object

Dictionary Dictionary

Log Object

DbImport Object

Constructors • Variant(): Creates an empty Variant object.

• Variant( Variant v ): Copies v; if v is an object, the new Variant will contain a reference to the object.

• Variant( bool v ): Copies v.

• Variant( double v ): Copies v.

• Variant( short v ): Copies v.

• Variant( int v ): Copies v.

• Variant( int64_t v ): Copies v.

• Variant( uint64_t v ): Copies v.

• Variant( string v ): Copies v.

SBM ModScript Reference Guide 323 Chapter 3: Programming SBM ModScript

Operators Copy operators: • Variant& operator =( Variant v ): Sets current Variant to value v; if v is an object, the current Variant will contain a reference to the object.

• Variant& operator =( bool v ): Sets current Variant to value v.

• Variant& operator =( double v ): Sets current Variant to value v.

• Variant& operator =( short v ): Sets current Variant to value v.

• Variant& operator =( int v ): Sets current Variant to value v.

• Variant& operator =( int64_t v ): Sets current Variant to value v.

• Variant& operator =( uint64_t v ): Sets current Variant to value v.

• Variant& operator =( string v ): Sets current Variant to value v.

Math operators: • Variant operator +( Variant v1 , Variant v2 ): Adds the value v1 to the value v2 and returns a Variant of the results.

• Variant operator -( Variant v1 , Variant v2 ): Subtracts the value v2 from the value v1 and returns a Variant of the results.

• Variant operator /( Variant v1 , Variant v2 ): Divides the value v1 by the value v2 and returns a Variant of the results. Throws exception if v equals 0.

• Variant operator *( Variant v1 , Variant v2 ): Multiplies the value v1 by the value v2 and returns a Variant of the results.

• Variant operator %( Variant v1 , Variant v2 ): Divides the value v1 by the value v2 and returns a Variant of the remainder. Throws exception if v equals 0.

• Variant operator ^( Variant v1 , Variant v2 ): Performs a bitwise exclusive OR using the value v1 and value v2 and returns a Variant of the results.

324 Solutions Business Manager (SBM) Comparison operators: • bool operator ==( Variant v1 , Variant v2 ): Returns true if v1 is equal to v2.

• bool operator !=( Variant v1 , Variant v2 ): Returns true if v1 is not equal to v2.

• bool operator <( Variant v1 , Variant v2 ): Returns true if v1 is less than v2.

• bool operator >( Variant v1 , Variant v2 ): Returns true if v1 is greater than v2.

• bool operator <=( Variant v1 , Variant v2 ): Returns true if v1 is less than or equal to v2.

• bool operator >=( Variant v1 , Variant v2 ): Returns true if v1 is greater than or equal to v2.

Note: Variant can compare strings to numbers such as "1"==1.

Other operators: • Variant& operator +=( Variant v ): Adds the value v to the current Variant.

• Variant& operator ++(): Increments the value of the current Variant by one.

SBM AppScript conversion operators: • Variant operator vbEQV( Variant v1 , Variant v2 ): Performs SBM AppScript EQV.

• Variant operator vbIMP( Variant v1 , Variant v2 ): Performs SBM AppScript IMP.

• Variant operator vbAND( Variant v1 , Variant v2 ): Performs SBM AppScript AND.

• Variant operator vbOR( Variant v1 , Variant v2 ): Performs SBM AppScript OR.

• Variant operator vbXOR( Variant v1 , Variant v2 ): Performs SBM AppScript XOR.

• Variant operator !vbNOT!( Variant v ): Performs SBM AppScript NOT.

• Variant operator is( Variant v1 , Variant v2 ): Performs SBM AppScript is.

Methods Conversion methods: • string to_string()

• int to_int()

• bool to_bool()

• double to_double()

• float to_float()

• long to_long()

SBM ModScript Reference Guide 325 Chapter 3: Programming SBM ModScript

• unsigned_int to_unsigned_int()

• unsigned_long to_unsigned_long()

• long_long to_long_long()

• unsigned_long_long to_unsigned_long_long()

• size_t to_size_t()

• int8_t to_int8_t()

• int16_t to_int16_t()

• int32_t to_int32_t()

• int64_t to_int64_t()

• uint8_t to_uint8_t()

• uint16_t to_uint16_t()

• uint32_t to_uint32_t()

• uint64_t to_uint64_t()

Note: Variant can be implicitly converted to and from every data type that it can internally represent. (Variant will not be implicitly converted to string, but can be explicitly converted using to_string(). VarRecord Description A VarRecord is any record that has variable fields. In other words, it represents any primary or auxiliary item. The item's fields are not defined by the database schema. They are added by designers using SBM Composer. VarRecord objects require a table ID at creation, using Ext.CreateVarRecord(). Inheritance AppRecord [page 159] -> VarRecord Methods • GetDisplayIssueId() [page 327]

• GetFieldValue() [page 327]

• GetItemNumber() [page 330]

• GetItemPrefix() [page 331]

• GetStateId() [page 331]

• SetFieldValue() [page 332]

• StartTransition() [page 334]

326 Solutions Business Manager (SBM) • StartTransitionWithLock() [page 336]

• FinishTransition() [page 337]

• QuickTransition() [page 338]

• StartSubmitToAux() [page 339]

• FinishSubmitToAux() [page 340]

• QuickSubmitToAux() [page 341]

GetDisplayIssueId()

Returns the item's display ID, consisting of a prefix indicating the item's type and a serial number within the item's project.

Function Signature

string GetDisplayIssueId()

Parameters

Parameter Type Description

None

Return

Type Description

string The item's display ID.

Technical Details SBM ModScript version: 11.3. Notes Item types and their prefixes are defined when an SBM designer configures a workflow. See GetItemNumber() and GetItemPrefix() for the components of the display ID. Related Topics VarRecord [page 326]

GetFieldValue()

Gets the value of a field in the calling record's variable field list.

SBM ModScript Reference Guide 327 Chapter 3: Programming SBM ModScript

Function Signature

bool GetFieldValue( name, string& value [, Variant& fieldList [, Variant& field] ])

bool GetFieldValue( name, int& value [, Variant& fieldList [, Variant& field] ])

bool GetFieldValue( name, int64_t& value [, Variant& fieldList [, Variant& field] ])

bool GetFieldValue( name, double& value [, Variant& fieldList [, Variant& field] ])

bool GetFieldValue( name, TimeT& value [, Variant& fieldList [, Variant& field] ])

bool GetFieldValue( name, Variant& value [, Variant& fieldList [, Variant& field] ])

Parameters

Parameter Type Description

name string The name of the field whose value will be retrieved from the calling record's variable field list. Field names for variable fields should be provided in upper case for database names (TITLE, for example) or in lower/ mixed-case for display names (Title, for example). For details on working with different types of database fields, refer to Working with SBM Database Fields [page 39].

value string& (Output) The internal value for the field. For Text fields, this is the exact value entered in the field. For values that int& are not Variant or TimeT, this internally gets the value int64_t& from the field as a Variant, and then tries to convert the value to the requested type. double& TimeT can be used with Date/Time fields to get the TimeT& internal date value. Variant& Note: If the field is a Multi-User field for which the Groups and Users selection mode is enabled, the value can include both pure integers (TS_IDs from the TS_USERS table) and group identifiers (TS_IDs from the TS_GROUPS table). The latter are in the form G1, G2, …

328 Solutions Business Manager (SBM) Parameter Type Description

fieldList Variant& (Output) Optional. If supplied and equal to the global constant Nothing, this parameter will refer to the calling record's VarFieldList when this method returns. If supplied and not equal to Nothing, this parameter is taken to be the calling record's VarFieldList. Do not set this parameter's value yourself. Always pass a variable set to Nothing and then reuse the variable for subsequent calls to GetFieldValue() and SetFieldValue() on the same VarRecord object. If this parameter is omitted, no functionality changes, but efficiency may suffer.

field Variant& (Output) Optional. If supplied and equal to the global constant Nothing, this parameter will refer to the Field object on the calling record's VarFieldList whose name matches the name input parameter when this method returns. If supplied and not equal to Nothing, this parameter is taken to be that Field object. As with the fieldList parameter, you should never set this value yourself. Always pass a variable equal to Nothing and reuse the variable in subsequent calls to GetFieldValue() and SetFieldValue() on the same VarRecord object and the same value for the name input parameter. Passing this parameter only affects the efficiency of repeated GetFieldValue() and SetFieldValue() calls.

Return

Type Description

bool True if the named field was found in the calling record's VarFieldList and its value was successfully retrieved.

Technical Details SBM ModScript version: 11.3. Signatures where value is not Variant& were added in 11.4. Example var value = ""; // initialize value as a string var fieldList = Variant(); var field = Variant(); fieldList = Nothing; field = Nothing; // Create and retrieve Contact record var myRecord = Ext.CreateAppRecord (Ext.TableId ("TS_CONTACTS")); var ok = myRecord.ReadWithWhere ("TS_CONTACTFIRSTNAME = 'Joe'");

SBM ModScript Reference Guide 329 Chapter 3: Programming SBM ModScript

// If no e-mail address, supply default value if ( ok ) { ok = myRecord.GetFieldValue ( "EMAIL", value, fieldList, field); } if ( ok && value == "" ) { ok = myRecord.SetFieldValue ( "EMAIL", "[email protected]", fieldList, field); } if ( !ok ) { Ext.LogErrorMsg ("Error in Joe's email field"); }

Notes The fieldList and field parameters are optional. If supplied, they can boost efficiency for repeated calls to GetFieldValue() and SetFieldValue(). Note that fields not contained in a variable field list (i.e., system table fields) cannot be accessed with this method. Also see GetFieldValue-type-() [page 166]. Note: A GetFieldValue method is also included in the SBM JavaScript Library.

Related Topics VarRecord [page 326]

GetItemNumber()

Returns the numeric portion of the item's display ID.

Function Signature

int GetItemNumber()

Parameters

Parameter Type Description

None

Return

Type Description

int The item's display ID.

Technical Details SBM ModScript version: 11.3. Notes See GetDisplayIssueId() for entire display ID.

330 Solutions Business Manager (SBM) Related Topics VarRecord [page 326]

GetItemPrefix()

Returns the prefix of the item's display ID, indicating the item's type. Item types and their prefixes are defined when an SBM designer configures a workflow.

Function Signature

string GetItemPrefix()

Parameters

Parameter Type Description

None

Return

Type Description

string The prefix of the item's display ID.

Technical Details SBM ModScript version: 11.3. Notes Item types and their prefixes are defined when an SBM designer configures a workflow. See GetDisplayIssueId() for entire display ID. Related Topics VarRecord [page 326]

GetStateId()

Identifies the calling record's state within a workflow.

Function Signature

int GetStateId()

Parameters

Parameter Type Description

None

SBM ModScript Reference Guide 331 Chapter 3: Programming SBM ModScript

Return

Type Description

int TS_ID of the record's state within the item's workflow. If the record is not from a primary table, then it does not have a workflow and the return value is -1.

Technical Details SBM ModScript version: 11.3. Notes None. Related Topics VarRecord [page 326]

SetFieldValue()

(SBM On-Premise/PaaS only) Sets the value of a field in the calling record's VarFieldList.

Function Signature

bool SetFieldValue( name, string& value [, Variant& fieldList, Variant& field ])

bool SetFieldValue( name, int& value [, Variant& fieldList, Variant& field ])

bool SetFieldValue( name, int64_t& value [, Variant& fieldList, Variant& field ])

bool SetFieldValue( name, double& value [, Variant& fieldList, Variant& field ])

bool SetFieldValue( name, TimeT& value [, Variant& fieldList, Variant& field ])

bool SetFieldValue( name, Variant& value [, Variant& fieldList, Variant& field ])

Parameters

Parameter Type Description

name string The name of the field whose value will be changed in the calling record's variable field list. Field names for variable fields should be provided in upper case for database names (TITLE, for example) or in lower/ mixed-case for display names (Title, for example). For details on working with different types of database fields, refer to Working with SBM Database Fields [page 39].

332 Solutions Business Manager (SBM) Parameter Type Description

value string& (Input/Output) A value in internal database format to be written to the named field in the calling record's int& VarFieldList. For values other than Variant and TimeT, int64_t& value will be internally converted to Variant. double& TimeT can be used with Date/Time fields to set the internal date value. TimeT& Variant&

fieldList Variant& (Output) Optional. If supplied and equal to the global constant Nothing, this parameter will refer to the calling record's VarFieldList when this method returns. If supplied and not equal to Nothing, this parameter is taken to be the calling record's VarFieldList. Do not set this parameter's value yourself. Always pass a variable set to Nothing and then reuse the variable for subsequent calls to GetFieldValue() and SetFieldValue() on the same VarRecord object. If this parameter is omitted, no functionality changes, but efficiency may suffer.

field Variant& (Output) Optional. If supplied and equal to the global constant Nothing, this parameter will refer to the Field object on the calling record's VarFieldList whose name matches the name input parameter when this method returns. If supplied and not equal to Nothing, this parameter is taken to be that Field object. As with the fieldList parameter, you should never set this value yourself. Always pass a variable equal to Nothing and reuse the variable in subsequent calls to GetFieldValue() and SetFieldValue() on the same VarRecord object and the same value for the name input parameter. Passing this parameter only affects the efficiency of repeated GetFieldValue() and SetFieldValue() calls.

Return

Type Description

bool True if the field was changed.

Technical Details SBM ModScript version: 11.3. Signatures where value is not Variant& were added in 11.4.

SBM ModScript Reference Guide 333 Chapter 3: Programming SBM ModScript

Example

var value = ""; // initialize value as a string var fieldList = Variant(); var field = Variant(); fieldList = Nothing; field = Nothing; // Create and retrieve Contact record var myRecord = Ext.CreateAppRecord (Ext.TableId ("TS_CONTACTS")); var ok = myRecord.ReadWithWhere ("TS_CONTACTFIRSTNAME like 'Joe'"); // If no e-mail address, supply default value if ( ok ) { ok = myRecord.GetFieldValue ( "EMAIL", value, fieldList, field); } if ( ok && value == "" ) { ok = myRecord.SetFieldValue ( "EMAIL", "[email protected]", fieldList, field); } if ( !ok ) { Ext.LogErrorMsg ("Error in Joe's Email field"); }

Notes This SetFieldValue() method specifically relates to VarRecords that are used for auxiliary and primary table records. For system table records, see SetFieldValue() [page 182]. If the field is a journal field, consider using Field.AppendJournalText() to add a single journal entry. Tip: For elapsed-time fields, the value that you retrieve from a GetFieldValue() call is not compatible with a call to SetFieldValue(), because a standalone number in an elapsed-time field is interpreted as hours rather than seconds. To get around this, provide SetFieldValue() with the string "00:00:" plus the number of seconds retrieved by GetFieldValue(). For example:

"00:00:" & elapsedTime

SBM converts the seconds into the correct hours, minutes, and seconds for you. Related Topics VarRecord [page 326]

StartTransition()

(SBM On-Premise/PaaS only) Starts a transition on an item.

Function Signature

bool StartTransition( trans [, bool stealLock ] )

334 Solutions Business Manager (SBM) Parameters

Parameter Type Description

trans Variant Can be transition ID, 0 (will use default Update transition for item), transition UUID, or transition internal name.

stealLock bool Optional. If true, any item lock on this item will be stolen by this transition. If it was locked, the user who had the item locked (in transition) will not be able to complete their transition. Does not guarantee that the transition succeeds, as scripts can steal locks from each other.

Return

Type Description

bool Returns true if transition was started. If false, use Shell.GetLastErrorMessage() for more information.

Technical Details SBM ModScript version: 11.3. Example var varRecord = Ext.CreateVarRecord( tableId ); var read = varRecord.Read( itemTitle ); if ( !varRecord.StartTransition( transitionId )){ // write an error to Active Diagnostics ADLog.Message( __FILE__, __LINE__, ADLogLevelConstants.ERROR, "StartTransition failed:\n" + Shell.GetLastErrorMessage() ); ExitScript(); }

Notes • VarRecord must have been read before invoking this function.

• StartTransition() is not required, script can simply invoke QuickTransition() if all required field values have already been set on the item. StartTransition() will initialize fields as if the transition form has been opened on the end user interface. Fields will respond correctly to GetRequiredFlag().

• Sets Shell.LastErrorMessage() on error (returns false).

• Locks item, use AppRecord.Unlock() if you do not wish to complete the transition. Re-read item to get it re-initialized if transition is not desired to be completed.

Related Topics VarRecord [page 326]

SBM ModScript Reference Guide 335 Chapter 3: Programming SBM ModScript

StartTransitionWithLock()

(SBM On-Premise/PaaS only) Identical to StartTransition(), assumes AppRecord.Lock() has been invoked.

Function Signature

bool StartTransitionWithLock( trans [, bool stealLock ] )

Parameters

Parameter Type Description

trans Variant Can be transition ID, 0 (will use default Update transition for item), transition UUID, or transition internal name.

stealLock bool Optional. If true, any item lock on this item will be stolen by this transition. If it was locked, the user who had the item locked (in transition) will not be able to complete their transition. Does not guarantee that the transition succeeds, as scripts can steal locks from each other.

Return

Type Description

bool True if transition was started. If false, use Shell.GetLastErrorMessage() for more information.

Technical Details SBM ModScript version: 11.3. Example

var varRecord = Ext.CreateVarRecord( tableId ); var read = varRecord.Read( itemTitle ); var gotLock = varRecord.Lock( true ); if ( !varRecord.StartTransitionWithLock( transId )){ // write an error to Active Diagnostics ADLog.Message( __FILE__, __LINE__, ADLogLevelConstants.ERROR, "StartTransitionWithLock failed:\n" + Shell.GetLastErrorMessage() ); ExitScript(); }

Notes Use FinishTransition() to complete the transition.

336 Solutions Business Manager (SBM) Related Topics VarRecord [page 326]

FinishTransition()

(SBM On-Premise/PaaS only) Finishes a transition on an item after StartTransition() has been invoked and field values have been set.

Function Signature

bool FinishTransition( trans [, bool stealLock ] [, signedUserID, signedUserPwd ] )

Parameters

Parameter Type Description

trans Variant Can be transition ID, 0 (will use default Update transition for item), transition UUID, or transition internal name.

stealLock bool Optional. If true, any item lock on this item will be stolen by this transition. If it was locked, the user who had the item locked (in transition) will not be able to complete their transition. Does not guarantee that the transition succeeds, as scripts can steal locks from each other.

signedUserID string Optional. Provides the user name portion of the signature if the transition requires a user's signature.

signedUserPwd string Optional, required if signedUserID is provided. Provides the password portion of the signature if the transition requires a user's signature.

Return

Type Description

bool Returns true if transition completed successfully. If false, use Shell.GetLastErrorMessage() for more information.

Technical Details SBM ModScript version: 11.3. Example

// StartTransition was called previously if ( !varRecord.FinishTransition( transitionId )){

SBM ModScript Reference Guide 337 Chapter 3: Programming SBM ModScript

// write an error to Active Diagnostics ADLog.Message( __FILE__, __LINE__, ADLogLevelConstants.ERROR, "FinishTransition failed:\n" + Shell.GetLastErrorMessage() ); ExitScript(); }

Example with signature provided:

var finished = varRecord.FinishTransition( transId, true, "userName", "userPass" );

Notes • VarRecord must have been read before invoking this function.

• StartTransition() should have been invoked. See StartTransition() [page 334].

• Sets Shell.LastErrorMessage() on error (returns false).

Related Topics VarRecord [page 326]

QuickTransition()

(SBM On-Premise/PaaS only) Identical to FinishTransition() except that StartTransition() is not required.

Function Signature

bool QuickTransition( trans [, bool stealLock ] [, signedUserID, signedUserPwd ] )

Parameters

Parameter Type Description

trans Variant Can be transition ID, 0 (will use default Update transition for item), transition UUID, or transition internal name.

stealLock bool If true, any item lock on this item will be stolen by this transition. If it was locked, the user who had the item locked (in transition) will not be able to complete their transition. Does not guarantee that the transition succeeds, as scripts can steal locks from each other.

signedUserID string Optional. Provides the user name portion of the signature if the transition requires a user's signature.

signedUserPwd string Optional, required if signedUserID is provided. Provides the password portion of the signature if the transition requires a user's signature.

338 Solutions Business Manager (SBM) Return

Type Description

bool Returns true if transition completed successfully. If false, use Shell.GetLastErrorMessage() for more information.

Technical Details SBM ModScript version: 11.3. Example var varRecord = Ext.CreateVarRecord( tableId ); var read = varRecord.Read( itemTitle ); if ( !varRecord.QuickTransition( transitionId, true, "userName", "userPass" )){ // write an error to Active Diagnostics ADLog.Message( __FILE__, __LINE__, ADLogLevelConstants.ERROR, "QuickTransition failed:\n" + Shell.GetLastErrorMessage() ); ExitScript(); }

Notes All field value changes must be in place on the item first. Related Topics VarRecord [page 326]

StartSubmitToAux()

(SBM On-Premise/PaaS only) Starts the submit of a new item into an auxiliary table.

Function Signature

bool StartSubmitToAux()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if transition completed successfully. If false, use Shell.GetLastErrorMessage() for more information.

SBM ModScript Reference Guide 339 Chapter 3: Programming SBM ModScript

Technical Details SBM ModScript version: 11.3. Example

var varRecord = Ext.CreateVarRecord( auxTableId ); var start = varRecord.StartSubmitToAux();

Notes • StartSubmitToAux() is not required, script can simply invoke QuickSubmitToAux() if all required field values have already been set on the item. StartSubmitToAux() will initialize fields as if the transition form has been opened on the end user interface. Fields will respond correctly to GetRequiredFlag().

• Sets Shell.LastErrorMessage() on error (returns false).

Related Topics VarRecord [page 326]

FinishSubmitToAux()

(SBM On-Premise/PaaS only) Finishes the submit into an auxiliary table.

Function Signature

bool FinishSubmitToAux()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if transition completed successfully. If false, use Shell.GetLastErrorMessage() for more information.

Technical Details SBM ModScript version: 11.3. Example

var submitted = varRecord.FinishSubmitToAux();

340 Solutions Business Manager (SBM) Notes • StartSubmitToAux() should have been invoked. See notes on StartSubmitToAux().

• Sets Shell.LastErrorMessage() on error (returns false).

Related Topics VarRecord [page 326]

QuickSubmitToAux()

(SBM On-Premise/PaaS only) Identical to FinishSubmitToAux except StartSubmitToAux is not required.

Function Signature

bool QuickSubmitToAux()

Parameters

Parameter Type Description

None

Return

Type Description

bool Returns true if transition completed successfully. If false, use Shell.GetLastErrorMessage() for more information.

Technical Details SBM ModScript version: 11.3. Example var varRecord = Ext.CreateVarRecord( auxTableId ); varRecord.SetFieldValue( "title" , "my title" ); var submit = varRecord.QuickSubmitToAux();

Notes All field value changes must be in place on the item first. Related Topics VarRecord [page 326]

SBM ModScript Reference Guide 341 Chapter 3: Programming SBM ModScript

Constants SBM ModScript includes the following constants. • ADLogLevelConstants [page 342]

• SBM AppScript Conversion Constants [page 343]

• DateFormatConstants [page 345]

• DateFormatFromLocaleConstants [page 346]

• DateTimeAttributeConstants [page 347]

• DBTypeConstants [page 347]

• FieldRequiredConstants [page 350]

• FieldTypeConstants [page 350]

• HTTPVerbConstants [page 351]

• LogLevelConstants [page 352]

• Nothing [page 353]

• RegexOptionBitsConstants [page 353]

• SQLColumnDefOutputHint [page 354]

• string_npos [page 355]

• TimeFormatConstants [page 355]

• TransitionTypeConstants [page 356]

• UnicodeCharTypeConstants [page 356] ADLogLevelConstants Description Global constant object. Used for ADLog.Message(). • ADLogLevelConstants.TRACE

• ADLogLevelConstants.DEBUG

• ADLogLevelConstants.INFO

• ADLogLevelConstants.WARN

• ADLogLevelConstants.ERROR

• ADLogLevelConstants.FATAL

342 Solutions Business Manager (SBM) Technical Details SBM ModScript version: 11.4. Example

ADLog.Message( __FILE__, __LINE__, ADLogLevelConstants.ERROR, "An informative error {0}", 5 );

SBM AppScript Conversion Constants Description Global constant objects. Used for functions that exist for converting SBM AppScript to SBM ModScript. Also see SBM AppScript Conversion Functions [page 103]. VarType Constants • vbEmpty

• vbNull

• vbInteger

• vbLong

• vbSingle

• vbDouble

• vbCurrency

• vbDate

• vbString

• vbObject

• vbError

• vbBoolean

• vbVariant

• vbDataObject

• vbByte

• vbArray

Comparison Constants • vbBinaryCompare

• vbTextCompare

• vbDatabaseCompare

SBM ModScript Reference Guide 343 Chapter 3: Programming SBM ModScript

Date Format Constants • vbGeneralDate

• vbLongDate

• vbShortDate

• vbLongTime

• vbShortTime

Date and Time Constants • vbSunday

• vbMonday

• vbTuesday

• vbWednesday

• vbThursday

• vbFriday

• vbSaturday

• vbUseSystemDayOfWeek

First Week of the Year Constants • vbFirstJan1

• vbFirstFourDays

• vbFirstFullWeek

• vbUseSystem

String Constants • vbCr

• vbCrLf

• vbLf

• vbNewLine

• vbNullChar

• vbTab

Tristate Constants • vbTrue

• vbFalse

344 Solutions Business Manager (SBM) • vbUseDefault

• TristateTrue

• TristateFalse

• TristateUseDefault

Color Constants • vbBlack

• vbRed

• vbGreen

• vbYellow

• vbBlue

• vbMagenta

• vbCyan

• vbWhite

Technical Details SBM ModScript version: 11.3. DateFormatConstants Description Identifies the format of the text while parsing dates, or what output format to use when formatting dates with TimeT.ParseDateText(), TimeT.FormatDateText(), TimeMillis.ParseDateText(), and TimeMillis.FormatDateText(). • DateFormatConstants.FROM_LOCALE

• DateFormatConstants.MM_DD_YYYY

• DateFormatConstants.DD_MM_YYYY

• DateFormatConstants. DD_MM_YYYY_DOTS

• DateFormatConstants. YYYY_MM_DD

• DateFormatConstants.XML

• DateFormatConstants.TIMESTAMP

Technical Details SBM ModScript version: 11.3.

SBM ModScript Reference Guide 345 Chapter 3: Programming SBM ModScript

Example

var t = TimeT(1517620926); var s = t.FormatDateText( DateTimeAttributeConstants.DATETIME, CreateTimeZone("MST"), CreateLocale("en_US"), DateFormatConstants.FROM_LOCALE, TimeFormatConstants.TWELVE_HOUR, DateFormatFromLocaleConstants.SHORT ); Ext.WriteStream( s );

Result:

2/2/18 6:22:06 PM

DateFormatFromLocaleConstants Description Identifies the format of the text while parsing dates, or what output format to use when formatting dates with TimeT.ParseDateText(), TimeT.FormatDateText(), TimeMillis.ParseDateText(), and TimeMillis.FormatDateText(). Value is ignored when date format is not FROM_LOCALE. • DateFormatFromLocaleConstants.DEFAULT

• DateFormatFromLocaleConstants.FULL

• DateFormatFromLocaleConstants.LONG

• DateFormatFromLocaleConstants.MEDIUM

• DateFormatFromLocaleConstants.SHORT

Technical Details SBM ModScript version: 11.3. Example

var t = TimeT(1517620926); var s = t.FormatDateText( DateTimeAttributeConstants.DATETIME, CreateTimeZone("MST"), CreateLocale("en_US"), DateFormatConstants.FROM_LOCALE, TimeFormatConstants.TWELVE_HOUR, DateFormatFromLocaleConstants.SHORT ); Ext.WriteStream( s );

Result:

2/2/18 6:22:06 PM

346 Solutions Business Manager (SBM) DateTimeAttributeConstants Description Identifies the format of the text while parsing dates, or what output format to use when formatting dates with TimeT.ParseDateText(), TimeT.FormatDateText(), TimeMillis.ParseDateText(), and TimeMillis.FormatDateText(). • DateTimeAttributeConstants.DATEONLY

• DateTimeAttributeConstants.DATETIME

• DateTimeAttributeConstants.TIMEONLY

• DateTimeAttributeConstants.ELAPSED

Technical Details SBM ModScript version: 11.3. Example var t = TimeT(1517620926); var s = t.FormatDateText( DateTimeAttributeConstants.DATETIME, CreateTimeZone("MST"), CreateLocale("en_US"), DateFormatConstants.FROM_LOCALE, TimeFormatConstants.TWELVE_HOUR, DateFormatFromLocaleConstants.SHORT ); Ext.WriteStream( s );

Result:

2/2/18 6:22:06 PM

DBTypeConstants Description Global const object for database types, used in SchemaColumn, SQLColumnDef, and SQL parameters. • DBTypeConstants.BIGINT

• DBTypeConstants.INTEGER

• DBTypeConstants.SMALLINT

• DBTypeConstants.TINYINT

• DBTypeConstants.DOUBLE

• DBTypeConstants.FLOAT

• DBTypeConstants.DATETIME

• DBTypeConstants.DECIMAL

SBM ModScript Reference Guide 347 Chapter 3: Programming SBM ModScript

• DBTypeConstants.NUMERIC

• DBTypeConstants.CHAR

• DBTypeConstants.VARCHAR

• DBTypeConstants.LONGVARCHAR

Technical Details SBM ModScript version: 11.3. Example

def getDBTypeNameText( type ) { switch( type ) { case(DBTypeConstants.BIGINT) { return "BigInteger"; } case(DBTypeConstants.INTEGER) { return "Integer"; } case(DBTypeConstants.SMALLINT) { return "SmallInteger"; } case(DBTypeConstants.TINYINT) { return "TinyInteger"; } case(DBTypeConstants.DOUBLE) { return "Double"; } case(DBTypeConstants.FLOAT) { return "Float"; } case(DBTypeConstants.DATETIME) { return "Datetime"; } case(DBTypeConstants.DECIMAL) { return "Decimal"; } case(DBTypeConstants.NUMERIC) { return "Numeric"; } case(DBTypeConstants.CHAR) { return "Char"; } case(DBTypeConstants.VARCHAR) { return "Varchar"; } case(DBTypeConstants.LONGVARCHAR) { return "LongVarchar"; } default { return "Unknown type: ${schema.type}"; } }

348 Solutions Business Manager (SBM) }

var record = Ext.CreateAppRecord( Ext.TableId( "TS_USERS" ) ); for( schema : record.GetSchemaColumns() ){ Ext.WriteStream( schema.name + " | " + getDBTypeNameText( schema.type ) + " | " + schema.length + "
"); }

Result:

TS_ID | Integer | 4 TS_LOGINID | Varchar | 64 TS_PASSWORD | Varchar | 258 TS_NAME | Varchar | 64 TS_TELEPHONE | Varchar | 64 TS_EMAIL | Varchar | 128 TS_STATUS | TinyInteger | 1 TS_FIELDSMASK | TinyInteger | 1 TS_NOTESMASK | TinyInteger | 1 TS_NUMNOTES | SmallInteger | 2 TS_CHGMASK | TinyInteger | 1 TS_NUMCHGS | SmallInteger | 2 TS_FILEMASK | Integer | 4 TS_NUMFILES | Integer | 4 TS_BROWSERMASK | Integer | 4 TS_ACCESSTYPE | TinyInteger | 1 TS_MAILCC | LongVarchar | 0 TS_HOMEPAGERPT | Integer | 4 TS_DATEPREFERENCE | TinyInteger | 1 TS_TIMEPREFERENCE | TinyInteger | 1 TS_OTHERUSER | Integer | 4 TS_FOLDERPROFILE | LongVarchar | 0 TS_STATECHANGEHISTORY | TinyInteger | 1 TS_MANAGEINCIDENTOPTIONS | TinyInteger | 1 TS_LICENSING | TinyInteger | 1 TS_PASSWORDPRIVILEGEOPTIONS | SmallInteger | 2 TS_PREFTABLEID | Integer | 4 TS_PASSWORDSETDATE | BigInteger | 8 TS_PASSWORDLENGTHOPTION | SmallInteger | 2 TS_GENERALMASK | TinyInteger | 1 TS_MEMO | LongVarchar | 0 TS_CONTACTID | Integer | 4 TS_CREATELOGINDATE | BigInteger | 8 TS_ALIASES | Varchar | 128 TS_TABORDER | LongVarchar | 0 TS_CHECKOLDPASSWORDS | SmallInteger | 2 TS_SPECIALCHAR | TinyInteger | 1 TS_LOCALE | Varchar | 32 TS_TIMEZONE | Varchar | 32 TS_CALENDARID | Integer | 4 TS_UUID | Varchar | 64 TS_NAMESPACEID | Integer | 4 TS_TERMSACCEPTED | BigInteger | 8

SBM ModScript Reference Guide 349 Chapter 3: Programming SBM ModScript

TS_AVATARRESOURCEID | Integer | 4 TS_TITLE | Varchar | 128 TS_MOBILEPHONE | Varchar | 64 TS_PREFERREDCONTACTMETHOD | TinyInteger | 1 TS_DATE_FORMAT | TinyInteger | 1 TS_TIMED | TinyInteger | 1 TS_LDAPSTATUS | TinyInteger | 1

FieldRequiredConstants Description Global constant object. Used for Field.GetRequiredFlag(). • FieldRequiredConstants.NOT_REQUIRED

• FieldRequiredConstants.REQUIRED

• FieldRequiredConstants.APPEND_REQUIRED (specifically for journal text fields)

Technical Details SBM ModScript version: 11.3. FieldTypeConstants Description Global constant object. Used for Field.GetType() result. • FieldTypeConstants.NUMERIC

• FieldTypeConstants.TEXT

• FieldTypeConstants.DATETIME

• FieldTypeConstants.SELECTION

• FieldTypeConstants.BINARY – May also be a trinary field

• FieldTypeConstants.STATE

• FieldTypeConstants.USER

• FieldTypeConstants.PROJECT

• FieldTypeConstants.SUMMATION

• FieldTypeConstants.MULTIPLE_SELECTION

• FieldTypeConstants.CONTACT

• FieldTypeConstants.INCIDENT

• FieldTypeConstants.FOLDER

• FieldTypeConstants.RELATIONAL

350 Solutions Business Manager (SBM) • FieldTypeConstants.SUBRELATIONAL

• FieldTypeConstants.MULTIPLE_RELATIONAL

• FieldTypeConstants.MULTIPLE_USERGROUP

• FieldTypeConstants.MULTIPLE_GROUP

• FieldTypeConstants.DATETIME_VCACTIONS – Used when fake fields are created for the AppRecord based class VCAction (for the TS_VCACTIONS table).

• FieldTypeConstants.MANY_RELATIONAL – Used in XML definitions in query views for advanced reports for columns that provide both table and item id; each row can point to a different table.

• FieldTypeConstants.TABLE – Used by multi-table reports to display the table for the result.

• FieldTypeConstants.FEED – Used by multi-table reports to display the feed for the result.

• FieldTypeConstants.FILE

• FieldTypeConstants.URL

• FieldTypeConstants.INT64 – Used in import from 64 bit integer columns, used when fake fields are created for various AppRecord-based classes that have 64-bit integer members in the schema (generally for Unix Epoch date columns).

• FieldTypeConstants.PAUSE_STATUS

Technical Details SBM ModScript version: 11.3. HTTPVerbConstants Description Global const object for RESTDataSource.Call(). • HTTPVerbConstants.GET

• HTTPVerbConstants.POST

• HTTPVerbConstants.PUT

• HTTPVerbConstants.DELETE

• HTTPVerbConstants.PATCH

• HTTPVerbConstants.HEAD

Technical Details SBM ModScript version: 11.4.

SBM ModScript Reference Guide 351 Chapter 3: Programming SBM ModScript

Example

var result = " "; //Create AppRecord of RESTDATASOURCE table var restSource = Ext.CreateAppRecord(Ext.TableId("TS_RESTDATASOURCE")); restSource.ReadByColumn("TS_NAME", "JSONPlaceHolder1"); var sPostData = //Use Map with to_json to format JSON post data ["name": "myObjName", "value1": 17, "value2": 5.7, "arrayData": [1,2,"3",4] //Use Vector for JSON array ].to_json(); if (!restSource.Call(HTTPVerbConstants.PUT , result, sPostData)){ // write an error to Event Viewer Ext.LogErrorMsg("Rest call failed in script " + __FILE__ + ":\n" + Shell.GetLastErrorMessage() );

// write an error to Active Diagnostics ADLog.Message( __FILE__, __LINE__, ADLogLevelConstants.ERROR, "Rest call failed:\n" + Shell.GetLastErrorMessage() );

Shell.RedoMessage() = "Rest call failed";

ExitScript(); }

LogLevelConstants Description Global constant object. Used for Log.GetReportingLevel(), Log.SetReportingLevel(), and Log.Message(). • LogLevelConstants.NONE

• LogLevelConstants.MINIMAL

• LogLevelConstants.AVERAGE

• LogLevelConstants.VERBOSE

Technical Details SBM ModScript version: 11.3. Example

//Basic example of working with the Log class var filePath = "Script.log"; //Creates a Log Object var myLog = Log(); //Opens the Log Object var isOpened = myLog.Open( filePath ); myLog.Message(LogLevelConstants.NONE, "Is log opened " + isOpened); //Starts a new Log file when MaxSize is reached var backUpFileSet = myLog.SetBackUpLogFile("True");

352 Solutions Business Manager (SBM) //Sets the number of bytes the log file should grow to before it is truncated var maxSize = myLog.SetMaxSize(10485760); //Adds timestamps to the entries var wantTimeStamp = myLog.SetWantTimeStamp("True"); //Returns the current logging level myLog.Message(LogLevelConstants.NONE, "Log reporting level: " + myLog.GetReportingLevel()); //Sets the log reporting level to Minimal reportLevel = myLog.SetReportingLevel(LogLevelConstants.MINIMAL); myLog.Message(myLog.NONE(), "Message level NONE" ); myLog.Message(LogLevelConstants.MINIMAL,"Message level MINIMAL" ); myLog.Message(LogLevelConstants.VERBOSE(), "Message level VERBOSE" ); //Logs the message with frmt (format string) myLog.Message(LogLevelConstants.AVERAGE, "Testing the {0} {1} to check that '{0}' {1}s to {0}. {2}, {3}, {4}", "STRING", "FORMAT", 2, 3, 4); //Closes the Log Object myLog.Close();

Nothing Description A constant used for representing an empty Variant. Technical Details SBM ModScript version: 11.3. Notes Variant variables can be compared to Nothing using the is operator.

RegexOptionBitsConstants Description Constant object that contains bits for Regex.Compile() options. Values can be combined using bit or operator "|". • RegexOptionBitsConstants.IGNORECASE

• RegexOptionBitsConstants.MULTILINE

• RegexOptionBitsConstants.DOT_MATCHES_ALL – Defines whether the dot (.) in the regular expression matches newline characters.

• RegexOptionBitsConstants.DEFAULT – Equal to IGNORECASE. To turn off all options, pass the number 0 as the parameter.

Technical Details SBM ModScript version: 11.3.

SBM ModScript Reference Guide 353 Chapter 3: Programming SBM ModScript

Example

var regex = Regex(); //To test for a valid phone number var subCheck = "(\\+\\d{1,2}\\s*)?\\(?\\d{3}\\)?\\s*[\\.-]?\\s*\\d{3}\\s*[\\.-]?\\s*\\d{4}"; var testNumbers = "123-456-7890 | (123)456-7890 | 123 456 7890 | 123,456,7890 | +91 (123) 456-7890"; regex.Compile(subCheck, RegexOptionBitsConstants.IGNORECASE | RegexOptionBitsConstants.MULTILINE); if ( regex.Matches(testNumbers) ) { Ext.WriteStream("Matches:
${regex.GroupVal(0)}"); while( regex.MatchesAgain() ) { Ext.WriteStream("
${regex.GroupVal(0)}"); } }

Result:

Matches: 123-456-7890 (123)456-7890 123 456 7890 +91 (123) 456-7890

SQLColumnDefOutputHint Description Global const object for SQL column definitions, used in SQLColumnDef. • SQLColumnDefOutputHint.None – Output will be default for the column type.

• SQLColumnDefOutputHint.TimeT – Used to inform SBM ModScript that the output for this column should be a TimeT object.

• SQLColumnDefOutputHint.VariantDate – Used to inform SBM ModScript that the output for this column should be a Variant storing a Date.

Technical Details SBM ModScript version: 11.4. Example

var out = []; // creates an empty Vector

Shell.Db().ReadDynaSQL( "select TS_ID,TS_NAME,TS_LASTLOGINDATE from TS_USERS where TS_STATUS=? order by TS_NAME", [ SQLColumnDef(DBTypeConstants.INTEGER,"TS_ID"), SQLColumnDef(DBTypeConstants.VARCHAR,"TS_NAME"),

354 Solutions Business Manager (SBM) SQLColumnDef(DBTypeConstants.BIGINT,"TS_LASTLOGINDATE", SQLColumnDefOutputHint.TimeT) ], out, [Pair(DBTypeConstants.INTEGER, 0)] ); for ( row : out ){ Ext.WriteStream( "${row[0]}\t${row[1]}\t${row[2].date}" ); }

string_npos Description A constant used for comparing to the results of string.find(). Technical Details SBM ModScript version: 11.3. Example

if ( "abc123".find( "def" ) == string_npos ) { Ext.WriteStream( "not found" ); }

TimeFormatConstants Description Identifies the format of the text while parsing dates, or what output format to use when formatting dates with TimeT.ParseDateText(), TimeT.FormatDateText(), TimeMillis.ParseDateText(), and TimeMillis.FormatDateText(). Ignored when DateFormatConstants is used with FROM_LOCALE. • TimeFormatConstants.TWELVE_HOUR

• TimeFormatConstants.TWENTYFOUR_HOUR

Technical Details SBM ModScript version: 11.3. Example var t = TimeT(1517620926); var s = t.FormatDateText( DateTimeAttributeConstants.DATETIME, CreateTimeZone("MST"), CreateLocale("en_US"), DateFormatConstants.MM_DD_YYYY, TimeFormatConstants.TWELVE_HOUR, DateFormatFromLocaleConstants.SHORT ); Ext.WriteStream( s );

Result:

02/02/2018 06:22:06 PM

SBM ModScript Reference Guide 355 Chapter 3: Programming SBM ModScript

TransitionTypeConstants Description Global constant object. Corresponds to return value of Tranition.GetType(). • TransitionTypeConstants.REGULAR

• TransitionTypeConstants.UPDATE

• TransitionTypeConstants.DELETE

• TransitionTypeConstants.EXTERNALPOST

• TransitionTypeConstants.SUBMITPROBLEM

• TransitionTypeConstants.COPY

• TransitionTypeConstants.POST

• TransitionTypeConstants.SUBTASK

Technical Details SBM ModScript version: 11.3. UnicodeCharTypeConstants Description Global constants for u_charType() functions. • UnicodeCharTypeConstants.UNASSIGNED

• UnicodeCharTypeConstants.UPPERCASE_LETTER

• UnicodeCharTypeConstants.LOWERCASE_LETTER

• UnicodeCharTypeConstants.TITLECASE_LETTER

• UnicodeCharTypeConstants.MODIFIER_LETTER

• UnicodeCharTypeConstants.OTHER_LETTER

• UnicodeCharTypeConstants.NON_SPACING_MARK

• UnicodeCharTypeConstants.ENCLOSING_MARK

• UnicodeCharTypeConstants.COMBINING_SPACING_MARK

• UnicodeCharTypeConstants.DECIMAL_DIGIT_NUMBER

• UnicodeCharTypeConstants.LETTER_NUMBER

• UnicodeCharTypeConstants.OTHER_NUMBER

• UnicodeCharTypeConstants.SPACE_SEPARATOR

356 Solutions Business Manager (SBM) • UnicodeCharTypeConstants.LINE_SEPARATOR

• UnicodeCharTypeConstants.PARAGRAPH_SEPARATOR

• UnicodeCharTypeConstants.CONTROL_CHAR

• UnicodeCharTypeConstants.FORMAT_CHAR

• UnicodeCharTypeConstants.PRIVATE_USE_CHAR

• UnicodeCharTypeConstants.SURROGATE

• UnicodeCharTypeConstants.DASH_PUNCTUATION

• UnicodeCharTypeConstants.START_PUNCTUATION

• UnicodeCharTypeConstants.END_PUNCTUATION

• UnicodeCharTypeConstants.CONNECTOR_PUNCTUATION

• UnicodeCharTypeConstants.OTHER_PUNCTUATION

• UnicodeCharTypeConstants.MATH_SYMBOL

• UnicodeCharTypeConstants.CURRENCY_SYMBOL

• UnicodeCharTypeConstants.MODIFIER_SYMBOL

• UnicodeCharTypeConstants.OTHER_SYMBOL

• UnicodeCharTypeConstants.INITIAL_PUNCTUATION

• UnicodeCharTypeConstants.FINAL_PUNCTUATION

Technical Details SBM ModScript version: 11.6.1.

SBM ModScript Reference Guide 357 Chapter 3: Programming SBM ModScript

358 Solutions Business Manager (SBM) Chapter 4: Additional SBM ModScript Features

Additional SBM ModScript features include the $INCLUDE( scriptname) tag, which enables you to include scripts within scripts, and the ability to call functions in DLL from a script. You can also Date/Time keywords in SetFieldValue to set Date/Time values dynamically. • Including Other Scripts [page 359]

• Calling Functions in a DLL from SBM ModScript [page 360]

• Using Date/Time Keywords [page 364] Including Other Scripts You can use the include("scriptname") function to include scripts within scripts. This enables you to write utility scripts to use repeatedly within multiple scripts. The include("scriptname") function executes like other ModScript functions; the referenced script is not executed until the function call is reached. Use include statements at the top of your script to ensure that functions defined in the included scripts are defined prior to any line in the script that uses those functions. Using include The following information pertains to the include("scriptname") function: • Include the name of the script as the argument for the include function. The script name should be identical to the name provided when adding or editing a script in SBM Composer. The script name is case sensitive; it must match the name of the script with respect to the proper case.

• The calling script's solution ID is used to find the requested script first. If no script is found with the requested name in that solution, any script with the requested name is used.

• If the script used in the include function does not exist, the script fails.

• Using include("scriptname") maintains line numbers in error messages, and also, if an error occurs in the code from the included script, the call stack of the error message provides the included script's name.

• You can only include a script once within a script. For example, if your main script includes include("script A") twice, the first include("script A") function is executed; the second include("script A") function is ignored.

• It is a good practice to use the include("scriptname") function at the beginning of a main script rather than later in the main script. Functions defined in included scripts will not exist in the current runtime until the include is processed (however, if the included script includes logic that is not encapsulated in a function definition, that include should be placed in the location of the script where that logic should be executed).

SBM ModScript Reference Guide 359 Chapter 4: Additional SBM ModScript Features

Also see include() [page 113]. Calling Functions in a DLL from SBM ModScript SBM ModScript enables you to load a DLL, call a function within a DLL, and unload the DLL within SBM using the Lib class. For details, see Lib [page 227]. For details on using this feature, refer to the following topics: • Creating the SBM Library Object [page 360]

• Loading the Library in SBM ModScript [page 361]

• Calling Your Function [page 362]

• Unloading the DLL [page 362]

• Keeping a Library Loaded Across Script Executions [page 363]

• Avoiding Exceptions [page 363]

For a detailed example of calling a DLL from SBM ModScript, see https://www.serenacentral.com/blogs/entry/sbm-modscript-part-6-invoking-dlls. Creating the SBM Library Object SBM ModScript can load a DLL and call any function within the DLL as long as the function has the following interface:

extern "C"__declspec( dllexport ) int function_name( SBMScriptArg*, int, ReallocArg_t );

where the first argument is an array of SBMScriptArg objects, the second parameter is the number of objects in the array, and the third is a callback function pointer back into SBM to resize any of single SBMScriptArg in the array. The extern "C" portion prevents function name mangling, which enables SBM to find this function in the DLL. The declspec portion defines your function as a dll export. When building your libraries, you must include a header file with the following definition:

struct SBMScriptArg { char* pData; int size; }; typedef int (*ReallocArg_t)( SBMScriptArg* pArg, int newSize );

It does not matter what you name the function as long as it has the correct interface. Each SBMScriptArg is both input and output for the DLL. To change the value of the SBMScriptArg, the ReallocArg function can be used to ensure that the buffer size is big enough for your output. All input and output are strings; integers can be converted to text using functions like std::to_string( n ). Tip: When creating your DLL, remember to export the functions by listing them in your .def file as well as declaring them for export with __declspec(dllexport).

Example:

360 Solutions Business Manager (SBM) // the following setArg functions can be used to set an SBMScriptArg to a new value void setArg( const char* s, size_t len, SBMScriptArg& arg, ReallocArg_t reallocArg ) { assert( len < INT_MAX ); // reallocArg will check if size is already big enough reallocArg( &arg, static_cast( len + 1 ) ); memcpy( arg.pData, s, len ); arg.pData[len] = 0; } inline void setArg( const char* s, SBMScriptArg& arg, ReallocArg_t r ) { setArg( s, s ? strlen( s ) : 0, arg, r ); } inline void setArg( const std::string& s, SBMScriptArg& arg, ReallocArg_t r ) { setArg( s.c_str(), s.size(), arg, r ); } template inline void setArgT( T n, SBMScriptArg& arg,ReallocArg_t r ) { setArg( std::to_string( n ), arg, r ); }

Loading the Library in SBM ModScript To load a DLL in SBM ModScript, you first need to create an SBM Library object using the CreateObject function call.

var sbmLib = CreateObject("SBMLibrary");

Once the object is created, tell the object which DLL you want to call functions in by calling SetLibraryName on the SBMLibrary object. You can specify the path in one of three ways. • Absolute path – You may specify an absolute path to the DLL that you wish to load. For example:

var path = "d:/ScriptTestTools/build/Release/Win32DllTest.dll"; sbmLib.SetLibraryName(path);

• DLL name – You may specify the DLL alone and rely on the ScriptAppPath registry setting to find the library. The ScriptAppPath is a string value in the SBM home registry key that contains a semicolon-separated list of directories in which SBM should look for executables and DLLs that SBM ModScript will use. For example, if HKEY_LOCAL_MACHINE/Software/TEAMSHARE/TEAMTRACK/ScriptAppPath is set to "d:/ScriptTestTools/build/Release", the above example could be re-written as: sbmLib.SetLibraryName("Win32DllTest.dll"); For details on using ScriptAppPath, refer to Setting Script Application Paths [page 40].

SBM ModScript Reference Guide 361 Chapter 4: Additional SBM ModScript Features

• DLL name without the extension – SBM ModScript also assumes an extension of .dll for any library name. Therefore, the above example could also be written as:

sbmLib.SetLibraryName("Win32DllTest");

Additionally, if you are going to use an absolute path to specify the library to load, you must also include the extension. The extension is not assumed when using an absolute path; it is only assumed if you are going to rely on the ScriptAppPath. Once you have told the library object which library you want to load, call LoadLibrary to actually get the library loaded. For example:

sbmLib.LoadLibrary();

LoadLibrary() returns a boolean which indicates the success or failure of the operation. To avoid experiencing a runtime exception, always check the return value of LoadLibrary() prior to calling any functions in the DLL. For example:

if (sbmLib.LoadLibrary()){ sbmLib.CallLibraryFunction( "my_function" ); }

Calling Your Function Once the library is loaded, you can call your function like any other function call on an object. The function can take as many parameters as you like because they are converted into a Vector of strings when passed to the DLL function. The function also returns an integer. A typical function call might look like the following example:

var v1 = "1"; // Must be string var v2 = to_string(2); sbmLib.CallLibraryFunction( "MyDllFunction", v1, v2 ); // The DLL exports MyDllFunction Ext.WriteStream( "script: " + v1 ); // The DLL can change v1 and v2 Ext.WriteStream( "script: " + to_int(v2) ); // Strings can be converted to integers

The parameters are input and output, and are converted to UTF-8 strings that are sent to the DLL. Up to seven arguments can be passed to the DLL and if more are needed, a Vector can be passed instead. The parameters need to be declared before the CallLibraryFunction, as they are both input and output. If a Vector is not used, all parameters should either be all strings or all Variants. Example of using a Vector:

var v = ["1","2"]; // creates a Vector sbmLib.CallLibraryFunction( "MyDllFunction", v ); // The DLL exports MyDllFunction Ext.WriteStream( "script: " + v[0] ); // The DLL can change values inside v Ext.WriteStream( "script: " + to_int(v[1]) ); // Strings can be converted to integers

Unloading the DLL To unload the DLL when you are finished with it, call the FreeLibrary function of the library object. For example:

362 Solutions Business Manager (SBM) sbmLib.FreeLibrary();

You do not need to pass any parameters to FreeLibrary() because it attempts to free the library that was specified by SetLibraryName(). Keeping a Library Loaded Across Script Executions For performance reasons, you may wish to keep a DLL loaded after your script has finished executing. That way the DLL is already loaded the next time the script executes. To do this, simply check to see if the library has been loaded by calling IsLibraryLoaded() before calling LoadLibrary(). If the library is not loaded, call LoadLibrary() to load it for the first time. As long as your script doesn't call FreeLibrary(), it remains loaded for the next time your script executes.

CAUTION: If you plan to leave the library loaded, always check to see if the library is already loaded before calling LoadLibrary() to avoid loading the library multiple times. Technically the library is never loaded more than once. All subsequent calls to LoadLibrary() on an already loaded DLL result in a reference count being incremented. In general, it is not a good practice to call LoadLibrary() over and over without calling FreeLibrary(). For example: var sbmLib = CreateObject( "SBMLibrary" ); var path = "d:/powderhorn/Tools/ScriptTestTools/build/Release/Win32DllTest.dll" sbmLib.SetLibraryName( path ); if ( !sbmLib.IsLibraryLoaded()) { if ( ! sbmLib.LoadLibrary() ) { Ext.WriteStream( " Test Failed: " + "Unable to load library on " ); Ext.WriteStream( path ); Ext.WriteStream( "\r\n" ); } else { Ext.WriteStream( "Library load succeeded on "); Ext.WriteStream( path ); Ext.WriteStream( "
\r\n" ); } } else { Ext.WriteStream( "Library already loaded
" ); }

Avoiding Exceptions If you attempt to call a function on a library that was not successfully loaded, SBM ModScript throws a runtime exception. To avoid this, a good practice is to verify that the library is loaded before calling a function. For example: if( sbmLib.IsLibraryLoaded() ) { var arg2 = 10;

SBM ModScript Reference Guide 363 Chapter 4: Additional SBM ModScript Features

sbmLib.CallLibraryFunction( "TestFunction", "arg1", arg2 ); }

For more information, see Lib [page 227]. Using Date/Time Keywords SBM provides Date/Time keywords that enable you to enter or modify dates and use dates in queries. You can use Date/Time keywords to set Date/Time field values. Note: You cannot use Date/Time keywords for values in Date/Time fields that are set to display elapsed time or as a stopwatch. For Time Only fields, now is the only available keyword. These settings are made by your administrator. Available Date/Time Keywords The following table describes the date/time keywords in SBM. When you use these Date/ Time keywords, be sure to type them exactly as shown.

Date/time keyword Description

now Current date and time. If you use this keyword in a date only field, it is recognized as startof_today.

startof_today, These Date/Time keywords return the beginning of a startof_yesterday, time period. startof_tomorrow, startof_thisweek, startof_nextweek, startof_lastweek, startof_thismonth, startof_lastmonth, startof_nextmonth, startof_thisyear, startof_lastyear, startof_nextyear

endof_today, These Date/Time keywords return the end of a time endof_yesterday, period. endof_tomorrow, endof_thisweek, endof_nextweek, endof_lastweek endof_thismonth, endof_lastmonth, endof_nextmonth, endof_thisyear, endof_lastyear, endof_nextyear

364 Solutions Business Manager (SBM) Date/time keyword Description

Plus Specifies a date of today plus a number of days. For example, to receive a date of 30 days from today, use "plus 30" in a date search or query-at-runtime field. The value after the keyword must be an integer up to 5,000 that specifies the number of calendar days to offset. The following Plus keywords are available by clicking the Date/Time Keywords link on forms: • Plus 7

• Plus 30

• Plus 365

Minus Specifies a date of today minus a number of days. For example, to specify today minus 30 days, use "minus 30." The value after the keyword must be an integer up to -1,000 that specifies the number of calendar days to offset. The following Minus keywords are available by clicking the Date/Time Keywords link on forms: • Minus 7

• Minus 30

SBM ModScript Reference Guide 365 Chapter 4: Additional SBM ModScript Features

366 Solutions Business Manager (SBM) Chapter 5: SBM ModScript Samples

Several SBM ModScript examples are provided to illustrate basic SBM ModScript capabilities. These scripts are also installed in the installDir\SBM\Application Engine\ModScript_Examples directory. In the following examples, the scripts were formatted to fit this page. To view the scripts in their original format, refer to the .tscm files in the \ModScript_Examples directory. • Sample One: Read/Write Fields [page 367]

• Sample Two: Launch .BAT File [page 368]

• Sample Three: URL Title Search [page 370]

• Sample Four: Self-Registration Validation [page 373]

• Sample Five: RESTDataSource [page 374] Sample One: Read/Write Fields This sample script copies the value of the Title field to be copied to the Description field. It can be used in the pre-transition, post-transition, pre-state, or post-state contexts. Note: To use this script, you must add it to SBM using the Scripts editor in SBM Composer. You must then associate it with a transition or state in the workflow in which the state or transition was defined. Read/Write Field Script Contents ' SBM ModScript Example: ReadWriteFields.tscm

/* ModScript Example: ReadWriteFields.tscm ------This script reads from a field and writes its value to another field.

Requirements: This script relies on Shell.Item(), which only exists in pre-transition, post-transition, pre-state, and post-state contexts.*/

// MODIFY THESE CONSTANTS FOR YOUR DATABASE // ------// Names of the fields we will work with add_global_const( "title", "FLDNAME_SRC" ); // add a global constant called "FLDNAME_SRC" with the value "title". // The keyword "global" could also be used, but then the value is not constant add_global_const( "description", "FLDNAME_DEST" ); // add a global constant called "FLDNAME_DEST" with the value "description".

// Read from one field, write back to another field

SBM ModScript Reference Guide 367 Chapter 5: SBM ModScript Samples

def ReadWriteFields() { var fldValue = Variant(); // since fields can have lots of different data types, // we can only get their value as a Variant. When passing a var as an output-parameter //to a function that takes a Variant, we need to ensure we create a Variant to pass in.

// Read from the source field if ( !( Shell.Item().GetFieldValue( FLDNAME_SRC, fldValue ) )) { // Error finding the field or reading from it Ext.LogErrorMsg( "Cannot read from field \"" + FLDNAME_SRC + "\"" ); // ModScript can concat values with + or &&&, but + will add if both the left and right // values can be cast to numbers, where-as &&& will always concatenate return; }

// Write to the destination field if ( !( Shell.Item().SetFieldValue( FLDNAME_DEST, fldValue ) )) { // Error finding the field or writing to it Ext.LogErrorMsg( "Cannot write to field \"" &&& FLDNAME_DEST &&& "\"" ); // ModScript can use backslash to escape double quotes return; } }

// Find the item being transitioned if ( Ext.ShellHasProp( "Item" ) ) { ReadWriteFields(); } else { // There is no current item, so write a message to the event viewer Ext.LogErrorMsg( "ModScript error: Shell.Item() does not exist." ); }

Sample Two: Launch .BAT File This sample script launches a .bat file during a transition. It can be used in the pre- transition, post-transition, pre-state, or post-state contexts. Note: To use this script, you must add it to SBM using the Scripts editor in SBM Composer. You must then associate it with a transition or state in the workflow in which the state or transition was defined. Make sure that you remove any arrows that are used to indicate line breaks first. Launch .BAT File Script Contents ' SBM ModScript Example: Launch.tscm

/* ModScript Example: Launch.tscm ------This script runs a .BAT file, passing the values of selected fields. The script waits for the .BAT file to finish before exiting. By replacing "NewTaskWait" with "NewTask", the script can be made to exit immediately, leaving the .BAT running in the background.

Requirements:

368 Solutions Business Manager (SBM) This script relies on Shell.Item(), which only exists in pre-transition, post-transition, pre-state, and post-state contexts.

Note: if reading a drop-down list field, do not use the GetFieldValue() function. Instead, retrieve the actual Field object, and use its GetDisplayValue() method. */

// MODIFY THIS CONSTANT FOR YOUR DATABASE // ------// Name of the field we will work with add_global_const( "Title", "FLDNAME" ); // add a global constant called "FLDNAME" with the value "Title". →The keyword "global" could also be used, but then the value is not constant

// MODIFY THIS CONSTANT FOR YOUR SYSTEM // ------// Path to the .BAT file add_global_const( "C:\\ModScript\\run.bat", "PATH" ); // add a global constant called "PATH" with the value "C:\ModScript\run.bat" →(notice backslashes were escaped by backslash)

// Gather params from item fields, pass them to .BAT file. def LaunchBatchFile() { var issueID; var fldValue = Variant(); var exitCode;

// Construct display ID from item type and item ID issueID = Shell.Item().GetDisplayIssueId();

// Read the field if ( !Shell.Item().GetFieldValue( FLDNAME, fldValue ) ) { // Error finding the field or reading from it Ext.LogErrorMsg( "Cannot read from field \"" &&& FLDNAME &&& "\"" ); return; }

// Run the .BAT file with params exitCode = Ext.NewTaskWait( PATH, issueID, "\"" &&& fldValue &&& "\"" );

/* NOTE: When params are passed to a .BAT file, they are concatenated into a command-line-style string separated by spaces. Inside the .BAT file, the params are parsed using spaces and quotes. Thus, if fldValue contains quotes, there can be problems receiving the data. To work around this problem, call a .EXE file instead of a .BAT file. */

if ( exitCode < 0 ) { // Negative exit code means OS-level error, such as .BAT file not found. Ext.LogErrorMsg( "Error launching \"" &&& PATH &&& "\" with params:\r\n " &&& issueID &&& "\r\n " &&& fldValue &&& "\r\n" ); } }

SBM ModScript Reference Guide 369 Chapter 5: SBM ModScript Samples

// Find the item being transitioned if ( Ext.ShellHasProp( "Item" ) ) { LaunchBatchFile(); } else { // There is no current item, so write a message to the event viewer Ext.LogErrorMsg( "ModScript error: Shell.Item() does not exist." ); }

.BAT File Script Contents The following contents must be added to the .bat file called by the Launch .BAT File script example.

@ECHO off REM --- run.bat REM --- This is an example batch program to be called REM --- from the SBM ModScript example "Launch.tsc" REM --- It appends a new line to C:\out.txt each time it runs ECHO Launched run.bat, params (if any): %* >> C:\out.txt

Sample Three: URL Title Search This sample script searches for specific words in the Title field of all items the user has privileges to view within the Issues table. This sample can only be used in the URL context. The URL Title Search Results dialog box displays the results of this script.

Note: To use this script, you must add it to SBM using the Scripts editor in SBM Composer. Make sure that you remove any arrows that are used to indicate line breaks first.

370 Solutions Business Manager (SBM) Title Search Script Contents ' SBM ModScript Example: SearchTitle.tscm

/* ModScript Example: SearchTitle.tscm ------Perform a search specified by the URL, display hyperlinked list of resulting items.

Requirements: This script is designed for URL context, in which the user enters a URL specifying the desired search. Note that a user-friendly HTML form could generate the URL from a user-supplied search string.

Sample URL: To search for Issues whose titles contain "monkey", "http://...tmtrack.dll?ScriptPage&scriptName=SearchTitle&find=monkey" (where "..." is replaced by your system's path to the SBM IIS DLL) */

// MODIFY THESE CONSTANTS FOR YOUR DATABASE // ------add_global_const( "Issues", "TBL_NAME" ); // add a global constant called "TBL_NAME" →with the value "Issues". The keyword "global" could also be used, but then the →value is not constant add_global_const( "TS_TITLE", "COL_NAME" ); // add a global constant called "COL_NAME" →with the value "TS_TITLE".

// Use SQL to find findMe in title column of Issues table // Resulting list goes into global itemList // Return true for successful SQL operation, false for failure def getItemList() { itemList = Ext.CreateAppRecordList( tableID ); sqlWhereClause = COL_NAME &&& " like '%" &&& findMe &&& "%'"; return itemList.ReadWithWhere( sqlWhereClause ); }

// Generate HTML for entire body of result page def resultHTML() { var numItems = itemList.Length();

// Heading shows search string and # items found Ext.WriteStream( "

Search Results

" &&& "

Found " &&& numItems &&& " " &&& →(numItems == 1 ? "item" : "items") &&& " containing " &&& → Ext.EncodeHTML( findMe ) &&& "

" );

// HTML "definition list" (

) containing an entry for each found item Ext.WriteStream( "
" ); for ( item : itemList ) { itemHTML ( item ); } Ext.WriteStream( "
" );

SBM ModScript Reference Guide 371 Chapter 5: SBM ModScript Samples

}

def itemHTML( item ) { // Generate

element as the title of this list entry Ext.WriteStream( "
" &&& →Ext.EncodeHTML( item.GetDisplayIssueId() ) &&& "
" );

// Generate

element for each field to be listed for this entry textFldHTML ( item, "Title" ); selFldHTML ( item, "State" ); textFldHTML ( item, "Description" ); Ext.WriteStream( "" ); }

def textFldHTML( item, fldName ) { var fldVal = Variant(); // since fields can have lots of different data types, we can only →get their value as a Variant. When passing a var as an output-parameter to a function →that takes a Variant, we need to ensure we create a Variant to pass in. if ( !( item.GetFieldValue( fldName, fldVal ) )) { fldVal = "[none]"; } Ext.WriteStream( "

" &&& Ext.EncodeHTML( fldName ) &&& ": " &&& →Ext.EncodeHTML( fldVal ) &&& "
" ); }

// Generate HTML for a selection field's name and value def selFldHTML( item, fldName ) { var fldObj = item.Fields().FindField( fldName ); var fldVal = Variant(); // since fields can have lots of different data types, we can only get their value as a Variant. When passing a var as an output-parameter to a function that takes a Variant, we need to ensure we create a Variant to pass in. if ( fldObj.is_var_null() ) { fldVal = "[none]"; } else { fldObj.GetDisplayValue( fldVal ); } Ext.WriteStream( "

" &&& Ext.EncodeHTML( fldName ) &&& ": " &&& →Ext.EncodeHTML( fldVal ) &&& "
" ); }

// Generate HTML for an error page (search did not execute) def errorHTML() { Ext.WriteStream( "

SQL Error

Unable to search for " &&& →Ext.EncodeHTML( findMe ) &&& "

" →&&& "

SQL \"where\" clause:
" &&& →Ext.EncodeHTML( sqlWhereClause ) &&& "

" ); }

// Start the HTML, take care of entire , open the def openHTML() { Ext.WriteStream( "Title Search for \"" &&& →Ext.EncodeHTML( findMe ) &&& "\" in " →&&& TBL_NAME &&& " table" ); }

372 Solutions Business Manager (SBM) // End the and the page def closeHTML() { Ext.WriteStream( "" ); }

// Declare all vars // Several subroutines below will use these global vars global findMe; global tableID; global itemList; global sqlWhereClause; if ( Shell.Context() == "URL" ) { // Get params findMe = Shell.Params().Item( "find" ); tableID = Ext.TableId( TBL_NAME, "display" ); // Build the HTML page openHTML(); if ( getItemList() ) { resultHTML(); } else { errorHTML(); } closeHTML(); } else { // They are running this in the wrong context (e.g., post-transition) Ext.LogErrorMsg( "ModScript error: this script must run in URL context." ); }

Sample Four: Self-Registration Validation This sample is an example of a script that can be run from the self-registration context. Note: To use this script, you must add it to SBM System Administrator under Options | Settings | External User | Registration Form Settings | Form Validation Script. Sample Self-Registration Script Contents ' SBM ModScript Example: SelfRegValidationExample.tscm

/* ModScript Example: SelfRegValidationExample.tsc Purpose: Perform additional password validation for self-registration form.

Context: Registration Form Settings for the "Self-Registration by External Users" feature.

Implementation: Verify that the password is at least 5 characters. */

/* Validate that the Shell contains the properties that are expected to be there in the context of the self-registration form.*/

SBM ModScript Reference Guide 373 Chapter 5: SBM ModScript Samples

if ( !( Ext.ShellHasProp( "RegistrationMethod" ) && Ext.ShellHasProp( "Password" ) ) ) { Shell.RedoMessage() = "Missing shell properties, is this a Self-Registration context?"; } else { /* Only verify the password if the registration mode is "automatic". In 'manual' registration mode the form doesn't ask for a login id and password. In automatic mode, Shell.registrationMethod is 1 and in manual mode, Shell.registrationMethod is 0. */

if ( Shell.RegistrationMethod() == "automatic" ) { if ( Shell.Password().to_string().size() < 5 ) { // could also use Len( Shell.Password() ), but using this to demo that // Variants can be converted to the ChaiScript string class Shell.RedoMessage() = "Password must be at least 5 characters"; } } }

Sample Five: RESTDataSource This sample provides code for working with the RESTDataSource object. Sample RESTDataSource Script Contents ' SBM ModScript Example: RESTDataSource.tscm

/* ModScript Example: RESTDataSource.tscm ------Use a RESTDataSource object. These can be created in Composer and bound to a URL, or bound to an endpoint that can have a different URL per runtime environment. This script will invoke the SBM JSON API "GetItemsByListingReport" function to get a list of items using a report.

Requirement: Deploy a RESTDataSource named "AE" pointing to the SBM AE server. Create a listing report in table "UBG_ISSUES" with a reference name "ModScript1" which takes Active/Inactive as a query-at-runtime value.

Logic: Read a row from TS_RESTDATASOURCE, invoke it via Post with JSON post data, providing URL parameters and URL path parameters, parse the JSON into an object, process the object and display items. */

var rest = Ext.CreateAppRecord( Ext.TableId( "TS_RESTDATASOURCE" ) );

/* Assumes you have created a RESTDataSource called "AE" that points to the AE server. RESTDataSource objects can use Endpoints, which can help with deploying to test and production systems. */ rest.Read( "AE" );

374 Solutions Business Manager (SBM) /* Now, invoke the RESTDataSource to invoke the AE JSON API in order to read items using a listing report. Here we assume you have a listing report with a reference name "ModScript1" which takes Active/Inactive as a query-at-runtime value. We'll use Map and Vector to build the JSON options we want to send to the JSONAPI; to_json() will convert our Maps, Vectors, Strings, etc to a well formatted JSON string. We will send the URL parameters (values that come after the "?" in the URL) via a Vector of Pairs. We will set up the URL path (the part of the URL that comes before the "?") using another Vector; each value will be separated by a "/". */ var result = ""; if ( !rest.Post( result, ["fixedFields":false, "fields":[["dbname":"TITLE"], ["dbname":"STATE"]]].to_json(), [Pair("HasRuntimeParams",1), Pair("F_ACTIVEINACTIVE",0)], ["jsonapi","GetItemsByListingReport","UBG_ISSUES","ModScript1"] ) ) { // write an error to Event Viewer Ext.LogErrorMsg("Rest call failed in script " + __FILE__ + ":\n" + Shell.GetLastErrorMessage() );

// write an error to Active Diagnostics ADLog.Message( __FILE__, __LINE__, ADLogLevelConstants.ERROR, "Rest call failed:\n" + Shell.GetLastErrorMessage() );

Shell.RedoMessage() = "Rest call failed"; ExitScript(); }

// Parse the response, assuming we received JSON var resultObj = from_json(result);

/* While debugging, writing the JSON out might help you understand what you are parsing. Convert back to json to get nice formatting (may be ignored by the browser): Ext.WriteStream(result.to_json() &&& "
"); */

/* Sometimes, you can get lost in your JSON object; do I have a map, a vector, or perhaps a string or integer? Printing out the data type of what "from_json" created might guide you in the code to write to process that object: Ext.WriteStream( resultObj.get_type_info().name() ); */ if ( resultObj.is_type(Map_type) && // we can check if we got a map object using this call. resultObj.count("items")>0 && resultObj["items"].is_type(Vector_type) ) { Ext.WriteStream( "

" ); for(entry : resultObj["items"]) { // ChaiScript supports in-string script processing using ${ codeGoesHere } Ext.WriteStream( "
${entry["id"]["itemIdPrefixed"]}
\n"); for(value : entry["fields"]) { Ext.WriteStream("
${value.first()}: "); if ( value.second().is_type(Map_type) && value.second().count("value")>0 ) {

SBM ModScript Reference Guide 375 Chapter 5: SBM ModScript Samples

Ext.WriteStream( value.second()["value"] ); } Ext.WriteStream("

\n"); } } }

Ext.WriteStream( "

" );

376 Solutions Business Manager (SBM)