Hp Man SM9.30 Programming Guide PDF
Comments
Description
HP Service ManagerFor the supported Windows® and UNIX® operating systems Software Version: 9.30 Programming Guide Document Release Date: July 2011 Software Release Date: July 2011 Programming Guide Legal Notices Warranty The only warranties for HP products and services are set forth in the express warranty statements accompanying such products and services. Nothing herein should be construed as constituting an additional warranty. HP shall not be liable for technical or editorial errors or omissions contained herein. The information contained herein is subject to change without notice. Restricted Rights Legend Confidential computer software. Valid license from HP required for possession, use or copying. Consistent with FAR 12.211 and 12.212, Commercial Computer Software, Computer Software Documentation, and Technical Data for Commercial Items are licensed to the U.S. Government under vendor's standard commercial license. Copyright Notice © Copyright 1994-2011 Hewlett-Packard Development Company, L.P. Trademark Notices Adobe™ is a trademark of Adobe Systems Incorporated. Java is a registered trademark of Oracle and/or its affiliates. Microsoft® and Windows® are U.S. registered trademarks of Microsoft Corporation. Oracle® is a registered US trademark of Oracle Corporation, Redwood City, California. UNIX® is a registered trademark of The Open Group. For a complete list of open source and third party acknowledgements, visit the HP Software Support Online web site and search for the product manual called HP Service Manager Open Source and Third Party License Agreements. Page 2 of 396 HP Service Manager (9.30) Programming Guide Documentation Updates The title page of this document contains the following identifying information: l l l Software Version number, which indicates the software version. Document Release Date, which changes each time the document is updated. Software Release Date, which indicates the release date of this version of the software. To check for recent updates or to verify that you are using the most recent edition of a document, go to: http://h20230.www2.hp.com/selfsolve/manuals This site requires that you register for an HP Passport and log on. To register for an HP Passport ID, go to: http://h20229.www2.hp.com/passport-registration.html Or click the New users - please register link on the HP Passport log on page. You will also receive updated or new editions if you subscribe to the appropriate product support service. Contact your HP sales representative for details. Page 3 of 396 HP Service Manager (9.30) Programming Guide Support Visit the HP Software Support Online web site at: http://www.hp.com/go/hpsoftwaresupport This web site provides contact information and details about the products, services, and support that HP Software offers. HP Software online support provides customer self-solve capabilities. It provides a fast and efficient way to access interactive technical support tools needed to manage your business. As a valued support customer, you can benefit by using the support web site to: l l l l l l l l Search for knowledge documents of interest Submit and track support cases and enhancement requests Download software patches Manage support contracts Look up HP support contacts Review information about available services Enter into discussions with other software customers Research and register for software training Most of the support areas require that you register as an HP Passport user and sign in. Many also require a support contract. To register for an HP Passport ID, go to: http://h20229.www2.hp.com/passport-registration.html To find more information about access levels, go to: http://h20230.www2.hp.com/new_access_levels.jsp Page 4 of 396 HP Service Manager (9.30) Contents Programming Guide Contents Overview System language Data types List: Data types Data type: Primitive Data type: Number Data type: Character Data type: Time Data type: Boolean Data type: Label Data type: Compound Data type: File/Record File variables Data type: Offset Data type: Array Data type: Structure Data type: Operator Arithmetic operators Logical operators Relational operators Data Type: Expression Data type: Pseudo field Data type: Global variable Data type: Local variable Reserved words Literals 1 5 19 21 21 22 22 23 23 24 25 25 26 26 26 27 27 28 29 31 32 32 32 32 33 33 33 34 Page 5 of 396 HP Service Manager (9.30) Programming Guide Contents Variables Creating variables Global variables List: Default variables Variable pools Statements Assignment statements List: Command line calls Generic command line calls Direct command line calls Call a RAD application Locate a RAD function RAD Debugger Start RAD Debugger RAD Debugger commands 34 35 35 36 38 39 40 40 41 42 51 52 53 53 53 Introduction to JavaScript in Service Manager Language overview Learning JavaScript Basic rules of JavaScript Structure of a JavaScript application Expressions and operators JavaScript objects and properties Built-in objects and functions Conditional statements While and loop statements Break and continue statements Exception handling statements 57 57 57 58 58 59 59 59 59 60 60 61 Where can I use JavaScript in Service Manager? What is the ScriptLibrary? ScriptLibrary editing environment Calling a function in the ScriptLibrary Example: Function to control close button label in Change Management 63 63 64 64 66 Page 6 of 396 HP Service Manager (9.30) Programming Guide Contents The log4js script API Details Performance impact Examples of calling JavaScript from different Service Manager tools Format Control Links Trigger scripts Triggers example Using RAD functions in JavaScript JavaScript function: parse_evaluate() RAD functions: parse() and evaluate() JavaScript global properties Query operators JavaScript return code properties Order of execution of JavaScript versus RAD language Corresponding JavaScript syntax for RAD language tasks 66 67 68 68 68 69 71 71 73 73 73 74 74 75 76 77 System Language reference Deleted RAD applications List: RAD functions RAD function: add.graphnodes(xml) RAD function: cache.flush RAD function: cleanup RAD function: contents RAD function: copyright RAD function: currec RAD function: current.device RAD function: current.format RAD function: cursor.field.contents RAD function: cursor.field.name.set RAD function: cursor.field.name RAD function: cursor.field.readonly RAD function: cursor.line 79 79 81 87 87 88 89 89 89 90 90 90 90 91 91 91 Page 7 of 396 HP Service Manager (9.30) target RAD function: get.name RAD function: get.owner RAD function: get.30) .graph.id RAD function: get.id RAD function: get.base.graph.form.timezoneoffset RAD function: get.Programming Guide Contents RAD function: date RAD function: day RAD function: dayofweek RAD function: dayofyear RAD function: delete RAD function: denull RAD function: descriptor RAD function: evaluate RAD function: evaluate.action RAD function: get.dateformat RAD function: get.graph.query RAD function: exists RAD function: fduplicate RAD function: filename RAD function: frestore RAD function: genout RAD function: get.graphnode.uid RAD function: gui RAD function: index RAD function: insert RAD function: iscurrent RAD function: jscall RAD function: lioption RAD function: lng RAD function: locks RAD function: logoff 92 92 93 93 94 94 95 95 95 96 96 97 97 98 98 99 99 100 100 100 100 101 101 101 101 102 104 104 105 107 107 108 Page 8 of 396 HP Service Manager (9.lock. timezone RAD function: setsort RAD function: shutdown RAD function: simple.selection("rows") RAD function: multiselect.selection("fieldcontents") RAD function: multiselect.Programming Guide Contents RAD function: logon RAD function: mandant RAD function: max RAD function: messages RAD function: min RAD function: modtime RAD function: month RAD function: multiselect.selection("selections") RAD function: multiselect.file.selection("selected") RAD function: multiselect.selection("fieldname") RAD function: multiselect.selection("tablename") RAD function: null RAD function: nullsub RAD function: operator RAD function: option RAD function: parse RAD function: perf RAD function: printer RAD function: policyread RAD function: processes RAD function: prof RAD function: recordcopy RAD function: recordtostring RAD function: round RAD function: same RAD function: scmsg RAD function: set.load 108 109 109 110 112 112 113 113 114 114 115 115 115 115 116 116 117 117 117 118 118 121 122 123 124 124 125 126 126 127 127 128 Page 9 of 396 HP Service Manager (9.30) . get("languagecode") RAD function: sysinfo.get("ClientOSName") RAD function: sysinfo.get("ActiveLicenses") RAD function: sysinfo.30) .get("Quiesce") 128 129 129 130 131 131 132 132 133 134 134 135 135 136 136 137 138 138 138 138 139 139 139 139 140 140 140 140 141 141 141 142 Page 10 of 396 HP Service Manager (9.get("Mode") RAD function: sysinfo.get("ActiveNamedUsers") RAD function: sysinfo.get("MaxLicenses") RAD function: sysinfo.get("ClientVersion") RAD function: sysinfo.get("Environment") RAD function: sysinfo.get("ClientPID") RAD function: sysinfo.Programming Guide Contents RAD function: str RAD function: stradj RAD function: strchrcp RAD function: strchrin RAD function: strclpl RAD function: strclpr RAD function: strcpy RAD function: strdel RAD function: strins RAD function: strpadl RAD function: strpadr RAD function: strrep RAD function: strtrml RAD function: strtrmr RAD function: substr RAD function: substrb RAD function: sysinfo.get("ActiveFloatUsers") RAD function: sysinfo.get("ClientNetAddress") RAD function: sysinfo.get("PrevLabel") RAD function: sysinfo.get("PrintOption") RAD function: sysinfo.get("MaxFloatUsers") RAD function: sysinfo.get("Display") RAD function: sysinfo. get("TotalSystemProcs") RAD function: sysinfo.get("RecList") RAD function: sysinfo.get("ServerNetAddress") RAD function: sysinfo.get("TotalFloatUsers") RAD function: sysinfo.get("TotalProcs") RAD function: sysinfo.get("TotalNamedUsers") RAD function: sysinfo.30) .get("ServerNetPort") RAD function: sysinfo.get("TotalUserProcs") RAD function: time RAD function: tod RAD function: tolower RAD function: toupper RAD function: translate RAD function: trunc RAD function: type RAD function: val RAD function: version RAD function: year List: rtecalls() rtecall("alalnum") function rtecall("counter") function rtecall("datemake") function rtecall("escstr") function rtecall("filecopy") function rtecall("fileinit") function rtecall("filldate") function rtecall("getnumber") function rtecall("getrecord") function 142 142 142 143 143 143 143 143 144 144 144 144 144 145 145 146 146 147 147 148 149 150 150 152 153 153 154 155 156 157 157 158 Page 11 of 396 HP Service Manager (9.get("Telephony") RAD function: sysinfo.get("ThreadID") RAD function: sysinfo.get("TotalLicenses") RAD function: sysinfo.get("ServerPID") RAD function: sysinfo.Programming Guide Contents RAD function: sysinfo. move RAD routine: as.copy RAD routine: as.get.cm3.sort RAD routine: axces.delete RAD routine: as.insert RAD routine: as.30) .write 159 160 161 161 162 163 164 165 166 166 167 167 168 169 169 170 171 172 173 174 174 175 176 178 178 179 180 181 181 182 183 184 Page 12 of 396 HP Service Manager (9.options RAD routine: as.apm RAD routine: axces.Programming Guide Contents rtecall("getunique") function rtecall("isalnum") function rtecall("isalpha") function rtecall("islower") function rtecall("isnumeric") function rtecall("isupper") function rtecall("log") function rtecall("passchange") function rtecall("policycheck") function rtecall("qbeform") function rtecall("recdupl") function rtecall("recordexists") function rtecall("refresh") function rtecall("rfirst") function rtecall("rgoto") function rtecall("rid") function rtecall("scantable") function rtecall("sort") function rtecall("statusupdate") function rtecall("transtart") function rtecall("transtop") function rtecall("trigger") function List: RAD routines RAD routine: as.name RAD routine: as.cts. scmsg 201 201 201 202 203 204 Page 13 of 396 HP Service Manager (9.fields RAD routine: wmi.forms JavaScript object: system.approval RAD routine: fill.fc RAD routine: marquee.sap.database RAD routine: axces.files JavaScript object: system.check 185 185 186 186 187 188 188 189 190 190 191 191 192 192 193 193 194 195 195 197 197 198 198 199 199 200 JavaScript and Service Manager reference JavaScript global System objects JavaScript object: system.publish RAD routine: marquee.stored RAD routine: scauto.intoout RAD routine: axces.fax RAD routine: axces.array RAD routine: validate.software RAD routine: axces.receive RAD routine: axces.email RAD routine: axces.sm RAD routine: axces.email.inventory.cm3 RAD routine: axces.fc RAD routine: publish RAD routine: query.30) .functions JavaScript object: system.functions.hybrid.rm RAD routine: axces.page RAD routine: axces.send RAD routine: message.write RAD routine: database RAD routine: es.fc RAD routine: post.Programming Guide Contents RAD routine: axces.move.evin RAD routine: axces.inventory RAD routine: sort.fc RAD routine: getnumb. threads JavaScript object: system.library JavaScript object: system.vars List: JavaScript global methods JavaScript global method: base64Decode JavaScript global method: base64Encode JavaScript global method: compile JavaScript global method: doHTTPRequest JavaScript global method: doSOAPRequest JavaScript global method: execute JavaScript global method: help JavaScript global method: makeSCWebURL JavaScript global method: print JavaScript global method: Quit JavaScript global method: RCtoString JavaScript global method: readFile JavaScript global method: stripHtml JavaScript global method: writeAttachmentToFile JavaScript global method: writeFile JavaScript global method: xmlstring Service Manager defined JavaScript objects JavaScript object: Attachment JavaScript object: Datum JavaScript object: Header JavaScript object: SCDatum JavaScript object: SCFile JavaScript method: SCFile.Programming Guide Contents JavaScript object: system.user JavaScript object: system.record JavaScript object: system.oldrecord JavaScript object: system.30) .deleteAttachment( attachID ) 205 206 206 207 207 208 208 209 209 210 211 212 213 214 216 217 218 220 221 221 223 223 224 225 227 227 228 230 232 233 235 238 Page 14 of 396 HP Service Manager (9.sysinfo JavaScript object: system.users JavaScript object: system. doCount() JavaScript method: SCFile.getNext() JavaScript method: SCFile.insertAttachment( attachObj ) JavaScript method: SCFile.doSave() JavaScript method: SCFile.30) .getAttachments() JavaScript method: SCFile.join() JavaScript method: SCFile.doAction() JavaScript method: SCFile.getLastRC() JavaScript method: SCFile.getPrev() JavaScript method: SCFile.length() JavaScript method: SCFile.getLast() JavaScript method: SCFile.getText() JavaScript method: SCFile.doPurge() JavaScript method: SCFile.doDelete() JavaScript method: SCFile.getType() JavaScript method: SCFile.pop() JavaScript method: SCFile.doRemove() JavaScript method: SCFile.setFields() JavaScript method: SCFile.doInsert() JavaScript method: SCFile.JSDate() JavaScript method: SCFile.getFirst() JavaScript method: SCFile.deleteAttachments() JavaScript method: SCFile.doUpdate() JavaScript method: SCFile.getPurgedRowCount() JavaScript method: SCFile.isRecord() JavaScript method: SCFile.setOrderBy() 239 240 242 243 244 245 247 248 250 251 252 253 254 255 256 257 258 259 260 261 263 264 265 267 268 269 270 271 273 274 275 277 Page 15 of 396 HP Service Manager (9.push() JavaScript method: SCFile.doSelect() JavaScript method: SCFile.Programming Guide Contents JavaScript method: SCFile.getXML() JavaScript method: SCFile.getMessages() JavaScript method: SCFile.getSize() JavaScript method: SCFile.getAttachment( attachID ) JavaScript method: SCFile. getPosition() JavaScript object: XML JavaScript method: XML.getNodeValue() JavaScript method: XML.toArray() JavaScript method: SCFile.unshift() JavaScript method: SCFile.getDocumentElement() JavaScript method: XML.getPrefix() JavaScript method: XML.createNode() JavaScript method: XML.getParentNode() JavaScript method: XML.appendNode() JavaScript method: XML.getCount() JavaScript method: SCRecordList.getValue() JavaScript method: XML.shift() JavaScript method: SCFile.getNodeType() JavaScript method: XML.Programming Guide Contents JavaScript method: SCFile.getFirstChildElement() JavaScript method: XML.getNodeName() JavaScript method: XML.getFirstAttribute() JavaScript method: XML.getNextAttribute() JavaScript method: XML.getNextSiblingElement() JavaScript method: XML.setValue() JavaScript method: SCFile.updateAttachment( attachObj ) JavaScript object: SCRecordList JavaScript method: SCRecordList.getText() JavaScript method: XML.getName() JavaScript method: XML.getQualifiedName() JavaScript method: XML.addAttribute() JavaScript method: XML.getAttributeNode() JavaScript method: XML.setType() JavaScript method: scfile_setrecord JavaScript method: SCFile.importNode() 280 281 282 283 284 285 286 288 289 289 290 292 295 297 299 300 303 305 307 310 313 315 318 322 323 324 327 330 334 336 338 341 Page 16 of 396 HP Service Manager (9.getAttributeValue() JavaScript method: XML.addElement() JavaScript method: XML.30) . toXMLString() JavaScript method: xmlDoc.setAttributeValue() JavaScript method: XML.setValue() JavaScript method: XML.Programming Guide Contents JavaScript method: XML.addDuration() JavaScript method: XMLDate.toSCDuration() List: JavaScript functions JavaScript function: add_graphnodes JavaScript function: get_graph_action JavaScript function: get_graph_id JavaScript function: get_graph_node_id JavaScript function: get_graph_target List: JavaScript functions in the ScriptLibrary JavaScript function: addToGroup JavaScript function: checkAllowedOption JavaScript function: checkVersionString 343 345 348 350 352 355 357 357 359 361 362 362 363 363 364 364 365 365 366 366 367 367 368 369 369 369 369 369 370 370 375 376 Page 17 of 396 HP Service Manager (9.getISOTime() JavaScript method: XMLDate.insertBefore() JavaScript object: XMLDate JavaScript method: XMLDate.getSCDateTimeString() JavaScript method: XMLDate.isDocumentElement() JavaScript method: XML.JSDate() JavaScript method: XMLDate.getISODay() JavaScript method: XMLDate.getDatum() JavaScript method: XMLDate.30) .setText() JavaScript method: XML.getISODate() JavaScript method: XMLDate.getISOMonth() JavaScript method: XMLDate.setNodeValue() JavaScript method: XML.getGMTSCDateTimeString() JavaScript method: XMLDate.getISOYear() JavaScript method: XMLDate.setContent() JavaScript method: XML.getDate() JavaScript method: XMLDate.getISODateTimeString() JavaScript method: XMLDate. Programming Guide Contents JavaScript function: isInGroup JavaScript function: removeFromGroup JavaScript function: returnGroupMembers JavaScript function: returnMyGroups List: JavaScript examples Example: Getting a list of logged-on users Example: Iterating through a complex XML document Example: Query a record using the SCFile object Example: Testing a file name Example: Updating a field with the current date and time 380 381 386 387 390 391 392 393 394 394 Page 18 of 396 HP Service Manager (9.30) . The main components of this document are: l l l l l System language (RAD) JavaScript and Service Manager Where to use JavaScript in Service Manager System language reference that describes the RAD functions. industry-standard programming language that eliminates the need for a separate programming skill set. and it provides an overview of JavaScript functionality in Service Manager. using both examples and descriptions of JavaScript's objects. and reduces user reliance on proprietary tools. It assumes that the reader is familiar with object-oriented programming.30) . instead. RAD is the Service Manager system language that enables administrators and implementers to manipulate Service Manager processes and workflows. and RAD routines JavaScript and Service Manager reference that describes the JavaScript global system objects.Chapter 1 Overview This document is intended for Service Manager system administrators and implementers. and JavaScript examples Page 19 of 396 HP Service Manager (9. the JavaScript interface is an alternative to the RAD language for tailoring. JavaScript is a widely supported. the Service Manager System language (RAD). JavaScript functions. System administrators and implementers can use the standard JavaScript scripting language and RAD to customize their Service Manager applications. JavaScript functions in the ScriptLibrary. and JavaScript. and functions. properties. It provides a brief introduction to RAD. Service Manager defined JavaScript objects. rtecalls. JavaScript global methods. JavaScript in Service Manager does not invalidate the current Service Manager RAD tool set. methods. Programming Guide Chapter 1: Overview Page 20 of 396 HP Service Manager (9.30) . The first command panel. where execution begins. Data types The Service Manager data type specifies the expected format of a field's data. The key to Service Manager’s remarkable flexibility can be found in the proper use of the system language. and the way values are stored in memory. Page 21 of 396 HP Service Manager (9.Chapter 2 System language The System language (RAD) provides the ability for administrators to manipulate the Service Manager processes and workflows using a programming language with a syntax that is similar to the C programming language. Data types can be either primitive or compound.30) . Note: System Administrators and implementers should only use types 1 through 4 or 8 to 10. then the $error exit is taken. and those used as exits. execution of the panel is complete. is always labeled start. The parameter panel defines local variables passed to it by a calling application. When that exit is defined as $normal. Execution continues at a panel’s normal exit (or another exit depending on conditions). The field value within the exit is a label name of another panel. Normally. The values are denoted either by literals or variables. The System language creates RAD applications that contain application panels (records) linked together in a logical flow. In general. the exit variables are $normal (in the normal exit) and $error (in the error exit). When the function is complete. Each panel performs a specific function. They also can be obtained as a result of operations. the operations that can be performed on the values. Defining a data type enables the system to manipulate the data appropriately. Administrators and implementers use this language daily to apply Service Manager to a specific purpose or enterprise. The data type determines the possible range of values of the set. two kinds of local variables exist: those used within an application. If an error is encountered. the application exits to another panel. Note: You must have a RAD license to view and modify the RAD applications with the RAD editor. time 3 (date/time) Boolean (logical) label File/record Offset 4 Primitive 5 6 7 Primitive Compound Compound Used to define exits. used to define a table or record. It is used within the code for the go to statements. Used for variables visible to the whole system. Certain functions ( val() and type() ) allow the user to determine or modify the numeric representation of a data type. Page 22 of 396 HP Service Manager (9. Array 8 Compound Structure 9 Compound Operator 10 Primitive Primitive Expression 11 Pseudo field Global variable Local variable 12 Compound 13 Compound 14 Compound Used for variables only visible to the RAD application Data type: Primitive Primitive data types consist of one element. thus changing the data type. Used to represent true or false. Used for absolute dates and times as well as relative time intervals.Programming Guide Chapter 2: System language List: Data types Data type number character Numeric Compound representation / Primitive 1 2 Primitive Primitive Primitive Purpose Used for all numeric type data. Service Manager internally represents each data type by its numeric representation. Used in expressions. it converts input data into output data. This is the compiled version of a label. Used to represent multiple fields of the same data type.30) . Used to represent a collection of fields of the same or different data types. Used for character strings. Used to represent parsed Rapid Application Development (RAD) language expressions. Used similarly to functions. can treat any special or reserved character as a literal character by preceding it with a backslash.0E0 32. can contain a double quotation mark. a positive or negative number.1 = -32.30) .257E05 Furthermore. can be any combination of letters. A number indicates an amount and can be either a whole number.10 = 3.21E1 -32.0 = 1E0 = 1. can present a literal backslash (\) by containing a double backslash (\\) can be any length. such as two hexadecimal digits preceded by a backslash. digits spaces. or special characters. but it must be preceded by a backslash (\) to enable the system to distinguish between double quotation marks as part of the string and a double quote at the beginning or end of the string. A character string: l l l l must be enclosed in double quotation marks. then more digits which are optionally followed by the letter E and an exponent.0E0 -1 = -1.Programming Guide Chapter 2: System language Data type: Number The number data type is a primitive data type represented by the number 1 in the database dictionary. Enter numbers with an optional sign (+ or -) followed by digits which are optionally followed by a decimal point. For example. l l l l Page 23 of 396 HP Service Manager (9.257E05 = 125700 = 1. can contain any special characters including those used as operators.21E1 1. The following number formats display valid numbers accepted by RAD. including zero.1 = 32. A character data type is typically expressed as a character string.25700E5 Data type: Character The character data type is a primitive data type represented by the number 2 in the database. or a floating point number.1 1. "Vendor=\"473\"" denotes the string: Vendor="437" can contain non-characters.10 = -3.0 = -1E0 = -1. each bullet shows different representations of the same number: l l l l l 1 = 1. Description Integer Valid literal examples 1 Negative Integer -1 Fixed Point Floating Point 32. The use of time is optional in absolute time. `18:00:00' is 6 p. The following table presents examples: Description Alphabetic Numeric Alphanumeric Special Mixed Mixed Mixed Hexadecimal Containing backslash Literal examples "abcde" "12379" "a1276b45" "$%=+*#@/" "$vendor" "$12379@6:54" "A1276%#B" "\01\ff\c2" "C:\\Program Files\\HP\\ Service Manager 7. SS=seconds. it defaults to 00:00:00. Note that absolute time is stored as GMT notation.30) . It determines the order of date (MM/DD/YY). l l l l Page 24 of 396 HP Service Manager (9. In all of the examples in this topic. DDD=day.00\\Server\\RUN\\sm. MM=minutes. MM/DD/YY is collectively referred to as date and HH:MM:SS is collectively referred to as time. `00:00:00' is midnight. length of zero) character string is not the same as a character string with a NULL value. the default is :00. If you do not use seconds. YY=year. Enter relative time in the following format: `DDD HH:MM:SS' The use of seconds is optional. The following rules govern the use of the time data type: l l Time must be enclosed in single quotation marks. DD=day.ini" "Enter the \"uid\" in the Unique ID field" Containing double quote Data type: Time The Time data type is a primitive data type represented by the number 3 in the database dictionary. Furthermore. Time is recorded on a 24-hour clock. 'MM/DD/YY' is `MM/DD/YY 00:00:00'. For example. The format's sequence is affected by the set.timezone() function. the following acronyms apply: MM=month.Programming Guide Chapter 2: System language l an empty (for example. If you omit time.m. HH=hours. Enter absolute time in the following format: `MM/DD/YY HH:MM:SS'. `12:00:00' is noon. If you omit days. '345 03:00' is 345 days and 3 hours. the default is 0.30) . NULL. Description Valid literal examples True False NULL Unknown t = T= true = TRUE = y = Y = yes = YES f = F = false = FALSE = n = N = no = NO Null = NULL u = U = unknown = UNKNOWN Data type: Label The label data type is a primitive data type represented by the number 5 in the database dictionary. The following examples are valid labels. false or unknown (of undetermined truth value). For example '12:00' is zero days and 12 hours. A Boolean indicates true. l l l $exit $normal <panel name> Page 25 of 396 HP Service Manager (9. unknown (t. Use the following to set a time variable to a 0 (zero) value: $time = `00:00' l The following date/time formats show valid times/dates accepted by RAD: Date/time format Absolute time Description Indicates a specific date and time Indicates an amount of time Valid literal examples `07/16/83 04:30:00' Relative time `197 05:00' (means 197 days and 5 hours) '1 00:00:00' (means 1 day) Relative time Indicates an amount of time Data type: Boolean The Boolean or logical data type is a primitive data type represented by the number 4 in the database dictionary.Programming Guide Chapter 2: System language l The use of days is optional in relative time. The following formats are accepted. Labels are used to define exits. f or u). false. The rules for forming a Boolean are as follows: l l Enter the Boolean directly as true. Enter the Boolean in either upper or lowercase characters. You may combine primitive data types to form compound data types. a select command panel retrieves the file’s records from the database and sets up the list. l l l For example: Page 26 of 396 HP Service Manager (9. You can move to the previous record in the list by using the previous (Read Previous Record) command panel. The contacts table has keys. Always create table variables on the rinit command panel. When executed. Each record is a structure and has the structure delimiter {[ ]}. a fdisp (File Display) command panel displays summary information from records in the list. l l A file is a particular kind of structure A structure is not a kind of file The term file is synonymous with the terms relation or table and is sometimes used interchangeably with the term table because of the legacy file system (P4) in the product (ServiceCenter / Service Manager). Any compound data type can have elements of any other valid data types. For additional information. and a descriptor. Table variables are the mechanism you use to make changes to tables. The select command panel always sets the current record to the first record that satisfies the selection query. A file is a set of related records treated as a single unit and is stored on disk. List: records selected from the file When executed. the data. Every table must have a table name and other descriptive data in the database dictionary. and the structure of an entire record as it would be stored in the database according to the dbdict. The rinit command panel binds the file variable to a file. fields with index numbers. Data type: File/Record The File/Record data type is a compound data type represented by the number 6 in the database dictionary. You can move to the next record in the list of records by using the next (Read Next Record) command panel. The record resides in memory for display or modification. but it is conceptually similar. The table variable stores one record at any given point in time. It is not an array.30) . For example. The field names in the structure are listed in the database dictionary. the name of the contacts table is contacts. A file variable has four parts: l File name in the database dictionary The RAD Database Manager requires this to be a single word without spaces or periods. A file variable contains the dbdict name. The file name of a file variable can be accessed either by using the pseudo field or using the RAD filename() function. File variables A file variable is an instance of a single record in a file. Current record A file variable can only contain one record from a file at a time. see the Database Management section in the Service Manager online help documentation. Descriptor The descriptor enables fields to be extracted by name.Programming Guide Chapter 2: System language Data type: Compound Compound data types consist of more than one element. The fdisp (File Display) command panel sets the current record to the record selected by the cursor when the user presses enter. l Note: Service Manager is case sensitive. 2842. to extract the value of the first customer number (2753) in the array $customer with value {2753.4}} {{[1.false]}. or the nth field. Data type: Offset The Offset data type is a legacy compound data type represented by the number 7 in the Database Dictionary."c".cust. The following table shows examples."b". Arrays are delimited by curly braces ({ }). and sequence."b"]}} {{[1."f"."b".Programming Guide Chapter 2: System language l l $file is a file variable lastname is a field name listed in the database dictionary for the file that $file has been bound to using the rinit command panel. Arrays store a list of elements of the same data type accessed by an index (element) number. Data type: Array The array data type is a compound data type represented by the number 8 in the database dictionary.2}.{[2. For example.{3. use any of the following equivalent syntaxes: Page 27 of 396 HP Service Manager (9. The term array is synonymous with the terms list. Description Literal examples Numeric Character Boolean Time Nested Structures {1.true]}. 2963}.{[3."h"} {true."a"]}. Elements in arrays can be of any data types (including arrays or structures). true.30) ."c".{[2.3} {"a".2. file names. The case for field names.unknown]}} {} Empty You can use either of the following equivalent syntaxes to access an element in an array: l l $array[element_number] element_number in $array For example."e". and other elements must match.CUST is not the same as status. Offset fields are not supported by RDBMS tables. vector. A fully qualified array name (array field in $file) can be used in place of an array variable."a". lastname in $file is a valid expression whose value is the lastname field in the current record in $file. unknown} {'12/7/42 00:00'. The number of items in an array can vary and does not have to be allocated in advance. STATUS. '1/3/62 00:00'} {{1. based on the index of the lastname field in the descriptor. "b". This effectively extends the array.line1 In addition. $x=part. the element is created and set to NULL. the 1 in $order. Field names are contained in the database dictionary and can only be used when associated with a file variable.false]} {[1.no in $order.line1. Tip: You can use the denull RAD function to remove any null values from the end of an array before assigning the array to a record or adding it to the database.30) . Note the following examples: l l l {[1.no in $file These commands do not work because the second command is not associated with a file variable.no. Structures are delimited with both curly braces and square brackets ({[ ]}).‘10/16/90 00:00’. elements of structures may be extracted using their numeric order in the structure .line1 with the value of {[672."a". Data type: Structure The Structure data type is a compound data type represented by the number 9 in the database dictionary. To delete an element from an array.no field within the structure $order. Assuming that the table contains a structure called part and within the structure and there is field called part.10.1. To insert a value into an array use the insert RAD function.line1 is the same as part."ball.Programming Guide Chapter 2: System language l l 1 in $customer $customer[1] If the accessed array element does not exist.no in $y Page 28 of 396 HP Service Manager (9. use the delete RAD function.0]} You can use either of the following syntaxes to extract an element from a structure: l l $structure[index of field] index of field in $structure For example. For example. use either of the following syntaxes: l l $order.line1[1] 1 in $order.true]} {[true. $y=part in $file $x=part. quantity and description.bearings"]} with the field names part. to extract the value of the part number (672) in the part.no. A structure is a group of named elements of (possibly) differing data types accessed by an index (element) number. this command works because it is associated with a file variable.part. Example: 5 mod 2 = 1 or 5 % 2 = 1 Indicates that two strings or two arrays are to be combined (concatenated) into a single string.Programming Guide Chapter 2: System language Data type: Operator The Operator data type is any expression that is parsed and returns a value. To distinguish subtraction from a minus sign.= (comparison). Arithmetic Addition Arithmetic Subtraction - Arithmetic Multiplication * Arithmetic Division / Arithmetic Exponentiation ** Arithmetic Modulus mod or % String Concatenate + Page 29 of 396 HP Service Manager (9. Type Name Character Description + Indicates that two numbers are to be added together Example: 49 + 51 = 100 Indicates that one number is to be subtracted from another number. You may specifically want the remainder for a division operation. the subtraction operator must be followed by a space. such as tod(). Service Manager uses several different operators: l l l l l arithmetic operators logical operators relational operators special operators string operators The following table presents a list of operators used in Service Manager.30) . gui(). rtecall(). An operator is a special symbol or function commonly used in expressions. Example: 40 .20 = 20 Indicates that one number is to be multiplied by another number Example: 5 * 5 = 25 Indicates that one number is to be divided by another number Example: 300 / 10 = 30 Indicates that the exponential value of a number is to be calculated Example: 2 **5 = 32 The modulus is the remainder of a division operation. or you may want to generate a circular number sequence within a given range. Example: 1 = 1 is TRUE Indicates that the value of one item is greater than the value of another item.Programming Guide Chapter 2: System language Example: "a" + "b" = "ab" {"a". "d". it returns a FALSE. If the expression is false. the system returns FALSE. If the expression is true. "b". Example: 400 < = 500 is TRUE 400 = < 500 is TRUE Indicates that the value of one item is equal to the value of another item. Example: 400 < 500 is TRUE Indicates that the value of one item is less than or equal to the value of another item.} + {"d". "e"} Logical not ! Inverts the Boolean value of the Boolean expression. "c". "b". "c". If both expressions are false. Example: not TRUE = FALSE ~ FALSE = TRUE (UNIX only) UNKNOWN = UNKNOWN ~ UNKNOWN = UNKNOWN Evaluates two expressions and returns a value of TRUE if both expressions are true. If one or both of the expressions is false. the system returns FALSE. Example: TRUE and TRUE = TRUE TRUE and FALSE = FALSE TRUE and UNKNOWN = UNKNOWN FALSE and UNKNOWN = FALSE Evaluates two expressions and returns a TRUE if either or both of the expressions is true. the system returns TRUE. Example: ‘08/01/83 00:00’ > ‘07/20/83 00:00’ is TRUE Logical and AND and & Logical or OR or | Relational Less Than < Relational Less Than or Equal To <= or =< Relational Equal To = Relational Greater than > Page 30 of 396 HP Service Manager (9. "e"} = {"a".30) . Example: TRUE or FALSE = TRUE FALSE | FALSE = FALSE FALSE OR UNKNOWN = UNKNOWN TRUE OR UNKNOWN = TRUE Indicates that the value of one item is less than the value of another item. $B=$C+$D This operator groups together expressions or statements. Page 31 of 396 HP Service Manager (9. Example "ab" ~ #"abc" is TRUE (UNIX only) This operator separates two or more statements on the same line Example $A=$B+$C. then addition and subtraction (both equal). Service Manager follows the standard order of operations: operators inside the parentheses are evaluated first. Example "abc"#"ab" is TRUE Indicates that the value of the first string does not start with the value of the second string.30) . followed by multiplication. division and modulus (all equal). The order of the operands affects this operation. Example: 600> =300 is TRUE 600= >300 is TRUE Indicates that the value of one item is not equal to the value of another item. The order of the operands affects this operation. Parentheses themselves are evaluated from left to right. Arithmetic operators have the following precedence: exponentiation. Example: 1 ~=2 is TRUE (UNIX only) Indicates that the value of the first string starts with the value of the second string.$z=1) ELSE ($y=3) Relational Not Equal To (¬ =) or (~=) or (<>) or (><) # Relational Starts With (Truncated Equals) Relational Does Not Start ¬# or ~# With (Truncated Not Equal To) Special Statement Separation . Special Parentheses () Arithmetic operators An arithmetic operator indicates actions to be performed under the terms of an arithmetic expression. Example 3*($x + $y) IF ($x=1) THEN ($y="z") ELSE ($y=3) IF ($x=1) THEN ($x=2. Operators with higher precedence are evaluated first.Programming Guide Chapter 2: System language Relational Greater Than or Equal To >= or => Indicates that the value of one item is greater than or equal to the value of another item. When the operators have equal precedence. they execute from left to right. $x=NULL is true if $x is null. the result is false. Here are examples of expressions: l l $X * 25 $Y > 32 Data type: Pseudo field The pseudo field data type is a legacy compound data type represented by the number 12 in the database dictionary. or unknown. l l Relational operators A relational operator makes a comparison. Data Type: Expression Expressions are sequences of operators and operands used to compute a value. The result is FALSE if substituting TRUE or FALSE for UNKNOWN always yields FALSE. Relational operators treat null operands according to the NULL substitution principle: l l l If the relation is true regardless of the value of the null operand. The logical operators are as follows (executed in the order shown): l l l not and or The unknown truth value is treated according to the Substitution Principle.30) . If the relation is false. An expression can also be used with a function call. then generates logical results on whether the comparison is true or false. the result is true. because it converts input data to output Page 32 of 396 HP Service Manager (9. The result is UNKNOWN if substituting TRUE or FALSE for UNKNOWN sometimes yields TRUE and sometimes yields FALSE. false. An operand can be checked for null using the special value NULL. then the result of the operation is TRUE if substituting TRUE or FALSE for UNKNOWN always yields TRUE. which dictates: l If UNKNOWN occurs as a logical operand. It determines whether the expression is true. A pseudo field is similar to a function. Otherwise. the result is unknown.Programming Guide Chapter 2: System language Logical operators A logical operator evaluates one or two Boolean expressions. An expression contains literals or variables. They can only be used for that purpose. Reserved words Reserved words have special meaning in Service Manager. Do not use them for any other purpose such as field names. and persist only within the currently executing RAD application. Format Month in $time +=1 This increments the current month by one. Use it to increment a date by a period of months. It can be placed on the left-hand side of the equals (=) sign in an assignment statement. The month pseudo field is useful for scheduling monthly reports. These variables are set when the operator logs on). since it calculates the number of days to add to each month.Programming Guide Chapter 2: System language data and can sometimes be assigned. is an abbreviation for logged on.30) . The name pseudo field is analogous to the filename function Factors Data type: Global variable The global variable data type is a compound data type represented by the number 13 in the database dictionary. The server automatically cleans up local variables when it exits a RAD application. or $lo. The server automatically cleans up global variables when a user logs off the system. This meaning is defined in RAD. Local variables begin with $L. Factors Name Explanation Accesses the file name in a specific file variable. Month Explanation Accesses the number of months from the beginning of the time base in a date. Pseudo fields were supported for legacy HP ServiceCenter data but are not supported by SQL tables. The following tables describe the pseudo fields. Data type: Local variable The local variable data type is a compound data type represented by the number 14 in the database dictionary. Global variables begin with $G. Here is a alphabetical list of reserved words: l l AND BEGIN Page 33 of 396 HP Service Manager (9. and persist throughout a user session ($lo. Service Manager has pre-defined pseudo-fields (Month and Name). Format $filename=Name in $file This sets $filename to the name of the file bound to $file. with one exception. Some simple examples are “23”. The server automatically cleans up local variables when it exits a RAD application. The data type and value of a variable can be different at different times and can have a primitive or compound data type as its value.” You can use a literal wherever you can use a variable. It is expressed as itself rather than as a variable's value or as the result of an expression.Programming Guide Chapter 2: System language l l l l l l l l l l l l l l l l DO ELSE END FALSE FOR IF IN ISIN NOT NULL OR STEP WHILE THEN TRUE UNKNOWN Literals A literal is an explicit value. and persist only within the currently executing RAD application. “2. and “John. A literal cannot be on the left side of an assignment statement. Variables A variable is a location in memory where a value can be stored.30) .5”. Service Manager contains three types of variables: l l l Local Global Thread Local variables begin with $L. Page 34 of 396 HP Service Manager (9. It is a named entity that refers to data to which you can assign values. interval Description Represents the eventin record. $variable=NULL. and persist throughout a user session ($lo. If the size of the record exceeds 32KB. An interval of time before a retry occurs if HP Service Manager denies the attempt to update an incident because the record is locked. Any variable can be set to a null value by assigning the value NULL into it.Programming Guide Chapter 2: System language Global variables begin with $G. The server automatically cleans up global variables when a user logs off the system. Global variables are treated as global among all applications executed within the process or task with two exceptions: a.register $axces. A variable's value is initialized to a null string. Event Services generates an error. Variable $axces $axces. or $lo. For example: ’00:02:00’ for two minutes. These variables are set when the operator logs on). When the variable is a parameter variable. If the RAD thread terminates. but may not include blanks. For example. Comment $axces. when the variable is created within a function. Data assigned to a variable has a data type. Represents the evlist field in the eventin record. Thread variables do not have a consistent naming scheme other than beginning with a dollar sign ($). Use this feature with discretion. Thread variables are only valid for the current RAD thread. When the variable is designated local (or something other than global) by an initial identifier.debug Page 35 of 396 HP Service Manager (9. b. Represents the event registration record. A variable name can be any length. If true. This data type becomes the variable's data type. is an abbreviation for logged on.lock. Creating variables The rules for creating variables are as follows: l A variable name must begin with a dollar sign ($) and an alphabetic character followed by zero or more alphanumeric characters that may include periods. l l l l l Global variables The following global variables are available when defining registration events. and the event reprocesses because the evtime field is not removed.fields $axces. then the server automatically cleans up all thread variables. For example. the eventin record is not updated. the evlist array in the eventin record is not removed before attempting to update the record.30) . Programming Guide Chapter 2: System language $axces.icm.availability.validation Used in events calling the application axces.profiles Definition List of personal profiles.filed $L.incident.environment $G.technicians $G. $G. This is the current file opened by the display application. the event status is error-fc. List of Incident Management views available to all the users as well as the views available to the logged on operator.pm. List of Service Manager operators that are neither self service only operators nor template operators. List of availability maps. $G.lists $G.open.environment Incident Management’s global environment record . List of assignment groups for Service Desk. If true. the application ignores any failed formatctrl validations. List of Service Desk views available to all the users as well as the views available to the logged on operator.operators $G. List of Incident Management statuses. The current user’s Incident Management personal profile record. The default value is NOT true.status $G. List of all global lists built at login. Variable $G.apm.categories $G.new $L. Global flag (Boolean) that determines whether or not to prompt you to save when you press OK or Cancel after you update a record. List of categories. The pre-updated state of a file undergoing an update while evaluating macro conditions.maps $G. If false.status $G.assignment List of assignment groups for Service Desk. Incident Management.groups $G. The current file being updated when evaluating macro conditions.save $G. $G.for. List of Configuration Management statuses.inboxes $L. Problem Management and Change Management.problem.failed.pm.assignment.prompt.30) . Problem Management and Change Management.pm. The out-of-box system includes the following global and local variables. Incident Management. List of technicians (operator table).global.inboxes $G.old Page 36 of 396 HP Service Manager (9.bypass. List: Default variables It is likely that the list of default variables varies from release to release. Partial-key time threshold for Incident Management .home $lo. ymd) in the operator record. “Feb”.limit $lo.startup $lo. List of abbreviated months (“Jan”.name $lo. Name of Home menu for GUI.groups $lo. Temporary variable that functions as a loop counter (variable is cleaned up in the login application).syslog $lo. dmy.ext $lo. Partial-key time threshold for Database Manager.appl.lvl $lo.time.timezone $lo.30) .limit $lo.uchgrps Page 37 of 396 HP Service Manager (9.abv $lo. HP copyright (copyright()) The number representing date order (mdy. Message levels affect on-screen messages only. List of change groups.copyright $lo. Device ID (current. User’s time zone. Level of messages to store in the message queue for the operator Level of messages to store in the message queue for the operator logged on. $lo. Determines whether syslog table is updated when processes start and end in the system.appl.order $lo. Application parameter values passed. Partial-key time threshold for Change Management. The company name as defined in the System Information Record as Menu Title under the Menu Information tab.manager) Application parameter names passed.ucapex $lo.time in Company Information record. List of months (“January”.date. Allows user to modify time zone based on capability.Programming Guide Chapter 2: System language $lo.company.device()) List of query group names in operator record.uallow. List of change approval groups. Name of main menu for text.i $lo.uallow.main $lo.cm. “Mar”).system.db.pm.startup.month.month.values $lo.zone $lo.msglog.appl.names $lo.name The name of the application responsible for managing the user’s menu (menu.limit $lo.device $lo. “February”. Set at login to value of the field called system. “March”).uapprovals $lo. List of user’s capability words. name User’s full name. Parameter $PHASE $GROUP. $lo. Parameter A parameter variable is defined on a parameter command panel. There are currently four variable pools: l Global A global variable is visible to the entire system. similar to the way a structure contains many pieces of information. It begins with $L. Thread A thread variable is only visible to the thread in which it was defined. Local A local variable is only visible to the RAD application in which it was defined... even when the threads are spawned by the same parent. can contain. Comments There is only one local variable. $SYSPUB. These are just a few examples. or $lo. Page 38 of 396 HP Service Manager (9. The same variable in different threads has different values.Programming Guide Chapter 2: System language $lo.LIST Thread $file $array $post These are just a few examples.LIST. such as $PHASE or $GROUP.file are two pieces of data that $L.30) .time $lo.ulogin.ufname $lo. Parameter variables are invisible to the debugger. $L. By convention. operator() Variable pools Variable pools are functional groupings of variables within Service Manager. It can contain many pieces of data. l l l Variable pool Global Global Global Global Local Variable $G. there are many thread variables. It may contain a value passed in from another application. User login time stamp. parameter variables are written in uppercase letters.user. there are many parameter variables. $MARQUEE. $L. For example. It begins with $G.env and $L. .if. For example.30) ..length=lng($string). The following assignment statements are used: assign. l l l A statement does not have a value.. initialize values. Example: traditional: $x=$x+1 increments $x by 1 shortcut: $x += 1 increments $x by 1 Decrement the left hand operand by the right hand operand. Example: for $I = 1 to 10 do ($J=$I*$I+$J) Specifies a condition to be tested and a statement to be executed if the condition is satisfied and a statement to be executed if the condition is not satisfied. Format these statements as follows: IF Boolean condition THEN statements Assignment Assign Assignment Increment += Assignment Decrement . RAD functions can be used in statements to further define selection criteria and/or execute commands.else..Programming Guide Chapter 2: System language Statements Statements are the smallest executable entities within Service Manager. The result of a RAD function can be assigned to a variable using the assign (=) assignment statement.... A statement is comprised of expressions combined with key words. They can be nested... for.then.. l l The following table lists all of the statements available in Service Manager. and perform calculations. Example: traditional: $x=$x-1 decrements $x by 1 shortcut: $x -= 1 decrements $x by 1 Allows you to perform a loop. Format this statement as follows: FOR variable name = initial value TO maximum value [DO] statement The brackets ([ ]) indicate that the DO keyword is optional. increment. A statement is governed by these rules. Type Name Character Description and Examples = Assigns the value of the right hand operand to the left hand operand. The following BASIC language statements perform processing and looping: IF. and decrement. Service Manager syntax rules must be followed. For example. You can set a variable.= Processing and looping FOR Processing and looping IF Page 39 of 396 HP Service Manager (9.to. $string. and increment the variable until the variable is greater than a maximum value.if. Example: $x=1 assigns 1 to $x Increment the left hand operand by the right hand operand. WHILE and FOR.then. perform a statement... then the expression.$y=$y . List: Command line calls You can use the Service Manager command line to navigate through the Service Manager system and to run applications. Format these statements as follows: WHILE (expression) [DO] statement Example: while ($x>6) do ($x=$x ."Chicago")="Seattle") then ($x=$x+1) else ($x=$x . wizards. and macros. It usually consists of three elements: l l l an assignment operator (typically an =) an expression to be assigned a destination variable On execution. Assignment statements An assignment statement assigns a value to a variable. therefore.1) Processing and looping WHILE Specifies a condition to be tested and a statement to be executed when the condition is TRUE. then the assignment operator.1. Page 40 of 396 HP Service Manager (9. HP recommends using a default value when the condition evaluates to UNKNOWN. Example: if (nullsub($location. Service Manager evaluates the expression and stores the resulting value in the variable. then neither statement is executed. The order for the assignment statements when read left to right is the destination variable first.1) The brackets ([ ]) indicate that the DO keyword is optional.1) If Boolean condition evaluates to UNKNOWN.Programming Guide Chapter 2: System language [ELSE statements] Example: if ($location="Seattle") then ($x=$x+1) else ($x=$x .30) . stored script.open. *qIM.ALL displays a list of all open incidents. Example *adatabase accesses Database Manager. Queries for a list of shortcut commands. Accesses a specified file.open.hr.execute Runs the specified script. #do presents a list of commands that start with “do. *socmq.” *a<application as specified name> *f<file name> database *q<query name> *s<script name> #<shortcut name> query. *fcontacts accesses the contacts file.quote opens an HR Request ticket.30) . Runs a stored query. non-applicable Page 41 of 396 HP Service Manager (9.Programming Guide Chapter 2: System language Generic command line calls RAD application called Command Function Runs the specified RAD routine. Displays the Audit Log form. Displays the Audit History form. Displays the Benchmark Configuration Record form.engine se.search.search.exerciser alert alertdefs alertlogs appr approvaldefs approvallogs asr database se.applications query. Displays the form for unloading an Audit Delta. Executes the “agentrev” query which displays a list of the schedule records for all SCAuto agents. Displays the Alert Definition form.exerciser auditdelta audithist auditonoff audlog audspec autoshut bm audit. Displays the RAD Application Comparison form.setup agmap agr agmap. Displays the Alert Log form.stored agentstat scauto.front database database database database database database bmconfig database Page 42 of 396 HP Service Manager (9.search.check.engine se. Executes the “ALERT STATUS REPORT” report via Report Exerciser.key Function Displays the system bulletin and any active “hot” incidents. Displays a currently-available SCAuto agents.engine report. ag encl.30) .search. Displays the Approval Definition form. Displays the Automatic Shutdown Information form. Displays the Alert Definition form.appl agcompare agentrev compare. Displays the form for accessing Benchmark field information.engine database se. Executes the “OPEN PROBLEM ANALYSIS REPORTS . Displays the RAD Editor prompt (formerly known as Application Generator). Displays the Approval Definition form.Programming Guide Chapter 2: System language Direct command line calls Command about RAD application called bulletin.sched report.unload. Form includes options for stopping agents Displays the Application Mapping form. Displays the Approval Log form.ASSIGNMENT GROUP” report via Report Exerciser. Displays the Audit Control form. Displays the Audit Specification Table form. Displays Change Management Event Definition form.open.Tasks form.menu cm3t se.search.engine cm3ropen cmc.search. Displays the Change Management Groups Definition form.access database cm3msg cm3profile database database cm3r se.search. Displays the Holiday Names form.search.30) .from.manage sc. Displays the search form for Change Management tasks.category.edit. callqueue chgqueue cls cm3grp sc. Displays the Change Management Task Category form.engine cm3topen cmcontrol cmt. Displays the Change Management Request Category form.exerciser comp se.engine cm3rcat cm3r.menu cm. Displays the Normal Working Hours form.from.Programming Guide Chapter 2: System language bmparms bulletin calduty calholiday call database database database database exercise Displays the Benchmark Parameters form. Executes the Menu Command List report via Report Exerciser. Displays the Incident queue. Displays the System Bulletin form.category. Displays the Change queue. Displays the Interaction) queue. Initiates the script for opening a new change request ticket.maint cm3renv se. Displays the Contract Management Configuration form.setup. Displays the System Information Definition form (system Company record).setup.config cmdlist report. Displays the Change Management Application Environment form. Displays the Application Exerciser form for testing/running a RAD application directly. Displays the search form for Change Management requests.maint cm3tenv se. Displays the Change Management (ChM) Security Profile form. Initiates the script for opening a new change task.manage pm.engine Page 43 of 396 HP Service Manager (9. Displays the Change Management Application Environment .search.open.engine cm3tcat cm3t. engine database database database database dbdict. Initiates the script for copying a database file.manager ds database Displays the Display Application Screen Definition form.maps database database Page 44 of 396 HP Service Manager (9. Displays the Event Services input queue. Displays the Distribution Group form. Displays the Display Application Event Definition form.file database se. Displays the Display Application Option Definition form.search.database.config database copy. Displays the Database Manager form.engine se. Displays the form for sending internal Service Manager broadcast mail. Displays the Currency form. Displays the Contacts search form. Displays the Currency Conversion search form. Displays the Alert search form. delmail database dist do database database doc menu.search. Displays the Event Filters form.exerciser evemail eventbld eventfltr eventin sca. Note: This command line call will only work if the menu forms are being displayed.utility database database Displays the RAD Application Comparison form.30) . edit gkn err database report. Displays the form for sending an email event. Displays the Schedule form.window axces. Displays the form for editing core knowledge. Displays the Data Map form. Displays the Approval search form. Displays the menu with options for maintaining the document engine. Executes the “EXCESSIVE REASSIGNMENT REPORT” report via Report Exerciser. Displays the Service Level Agreement Control form.Programming Guide Chapter 2: System language compare configure sla contacts copyfile createschd curalerts curapprovals curconvert currency datamap db dbdict de compare.build. Displays the Database Dictionary prompt.edit.applications sla. Initiates the wizard for building event mappings. Displays the Forms Designer prompt.page. Displays the Convert Incident Format form. Displays the Incident queue.maint forms. Displays the Format Control form.format database database Page 45 of 396 HP Service Manager (9.Programming Guide Chapter 2: System language eventmap eventout eventreg evfax evicmbld database database database sca. Displays the Help topic search form. Displays the Assignment Groups form.ctrl. or generic event.designer ke.gencore. Configuration Management.maps Displays the Event Map form. Displays the form for sending a paging event. Displays the Incident Management Environment Profile form. Initiates the script for the building of probsummary records.probsum imconvert imgroups improfile pm. Displays the Event Services output queue.window sca. evpage evwrite axces.access database database imassign imbuild database pm. Displays the form for sending a fax event. Displays the Incident Management Groups form.build.verify gl hd htopic imapplenv database pm.30) . Initiates a script for building Configuration Management event mappings.maint forms. Displays the Forms Designer form.window scauto. Displays the form for sending an Incident Management.designer database formatctrl forms gen core format. Displays the prompt for generating the core Knowledge Base. Displays the Configuration File form for database unloads.build.convert. Displays the Format Control form. Displays the Expense Line Information form.ctrl. Displays the global list form. Displays the Incident Management Security Profile form. Displays the Event Registration form.window expline faxinfo fc fd files database database format. Displays the Fax Configuration form. window report.query. Executes the Problem Response Analysis By Location report via Report Exerciser.transfer Initiates the Service Manager Upgrade Utility Load Transfer form.application link linklist edit.setup. location logmsg mailmsg mcf menu message model modelicm database modelven monitor database system. incidentqueue sc.clear.exerciser ircomp report. Displays the Background Processor Initialization Registry form. Executes the “Problem Response Analysis By Component” report via Report Exerciser.setup Allows for the clearing of availability information. database database database database database database database Displays the Location form. Displays the search form for Knowledgebase information. Displays the Model Vendor Information form. Displays the Kill Inactive Users Setup Parameters form.Programming Guide Chapter 2: System language imreset inact pm.upgrade.downtime kill.30) . Displays the Link File form. Executes the “Problem Response Analysis By Vendor” report via Report Exerciser.manage info database irassg report. Displays the system status form. Displays the “mail” type Message Class form.exerciser load transfer apm.load.exerciser knowledge get. Displays the Configuration Item (CI) Model search form.exerciser irloc report.search.link report.inactive. Displays the form for issuing an IR Query File form. Displays the Message form. Executes the “Problem Response Analysis By Assignment” report via Report Exerciser. Displays the Menu form. Executes the Link File Listing report via Report Exerciser.monitor Page 46 of 396 HP Service Manager (9. Displays the Capability Word form. Displays the Incident queue. Displays the “log” type Message Class form. Displays the Configuration Item (CI) Model search form.exerciser irq irvend ir. Displays the Notification Definition form. new incident note number ocmbldlvl apm.first Displays the generic Message Class form.access ocmlcat database ocmlcreate ocm. Executes the "Delivery Forecast for Next 7 Days" report via Report Exerciser. Displays the Request Management Line Item Category form. Displays the Message Type form. Displays a blank form to create a Service Desk interaction. Displays the Configuration Item (CI) Model search form.Programming Guide Chapter 2: System language msg msglog msgtype new call database database database cc. Displays the prompt for updating all of the level numbers for all components in the model file. Displays a blank incident form for ticket entry. Displays the Request Management Group Definition form.co.create ocmlenvir query. Executes the "Daily Receipt Journal" report via Report Exerciser.stored ocmlmast database ocmlphase database ocmlrec database Page 47 of 396 HP Service Manager (9. Displays the Request Management Catalog Select Categories form.first database database ocm.exerciser ocmdrj report.30) .lvls ocmco database ocmdeliv report. Displays the Request Management Line Item Phase form. Executes the "Daily Quote Log" report via Report Exerciser. Displays the Request Management Events form.bld. Displays the Request Management Receiving Log form. Displays the Request Management Line Items Application Environment form. Displays the search form for Request Management line items Displays the Request Management Line Item Category form.exerciser ocmdreqj report.category. Displays the Message Log form.exerciser ocmevents ocmgroups database database ocml ocml. Displays the Sequential Number form. Programming Guide Chapter 2: System language ocmo ocmo. Displays the Request Management Order Category form.exerciser ocmprofile ocmq database ocmq.stored ocmoopen ocmo. Displays the Request Management Order Phase form.DOCUMENT NUMBER" report via Report Exerciser. Displays the Request Management Order Category form.access ocmqphase database ocmvenper report.exerciser odr report.category. Displays the Request Management Quote Category form.create ocmqopen ocmq.create ocmodemand database ocmoenvir query. Displays the search form for Request Management quotes. Executes the "Vendor Performance Based on Line Item Dates" report via Report Exerciser.exerciser oncall oncallsched database database Page 48 of 396 HP Service Manager (9. Initiates the script for creating a new Request Management quote. Executes the "Print Purchase Orders" report via Report Exerciser. Displays the Request Management Profile form. Displays a list of orders that have been approved.category.access Displays the search form for Request Management orders. Displays the Request Management Background Order Generation Schedule Record form. Displays the On Call Schedule contact form. Displays the Request Management Orders Application Environment form.30) .access database ocmocavail database ocmocreate ocm. Initiates the script for creating a new Request Management order. Displays the Request Management Quote Phase form.access ocmqcat database ocmqcreate ocm. Executes the "OPEN PROBLEM ANALYSIS REPORTS . Displays the On Call Schedule calendar form. Displays the Request Management Quote Category form. ocmoappr ocmocat ocmo. Displays the Request Management Check Availability Order Generation Schedule Record.access ocmophase ocmpo database report. purge encl.writer database database mail.appl report.exerciser sla. Executes the "overspent contracts" query which displays a list of all service contracts that have exceeded their financial budget.access report. Executes the "Print of Application" report via Report Exerciser. Displays the Knowledgebase search form. Displays the prompt for changing the login password. Displays the Report Writer prompt. Displays the prompt for recalculating SLA information over a given time frame.access query.set.change report. Displays the Incident queue. password print password.exerciser prtmsg purgarch purgeaudit RAD rad re recalc partials database pa.Programming Guide Chapter 2: System language operator opn overspent database pm.exerciser cc.application database Page 49 of 396 HP Service Manager (9. Executes the "Print of Application" report via Report Exerciser. Displays the Application Exerciser form for testing/running a RAD application directly. Displays the prompt for selecting which type of internal Service Manager mail to read. Displays the Service Manager Message form.totals report review cc review im rmail report.appl encl.30) . Displays the Incident queue. Displays the "print" type Message Class form.main. Displays the Service Desk Interaction queue. Displays the RAD Editor prompt.schedule get.appl audit.manage apm. Displays the Purge/Archive form.exerciser printappl report. Displays the Schedule File form.setup.stored Displays the Operator form. Displays the RAD Editor prompt. Displays the Schedule File form.manage read mail run exercise rv rw sch schedule schmail scknowledge scmsg pm. Displays the Incident queue.recalc. Displays the Report Exerciser prompt. Displays the form for scheduling background mail.search. Displays the form for purging audit history. Displays the Report Exerciser prompt.setup. incidents search calls cc.scheduler database apm. Displays the Benchmark Utility form. Displays the Software Management form.objects servcont shutdown database system. Displays the search form for Service Desk interactions. Displays the system status form.incidents search incident search sla apm. Displays the Stored Query Maintenance form. Displays the search form for Service Level Agreements.Programming Guide Chapter 2: System language scr report. scripts search cal script.search. Initiates the process for shutting down the Service Manager server. Displays the Service Contract form. Displays the System Log form. Displays the Subtotal Definition form. Displays the Service Desk Groups form. Displays the prompt for confirming the sending of internal Service Manager mail.exerciser Executes the "shift change report" report via Report Exerciser.30) .search. Displays the Pending Knowledge Items form. Displays a list of the user’s change tasks.appl smapplenv smgroups smprofile software sol cans spool sq start startbm status stdptrs database database database database se.search. Displays the Service Desk Environment form.engine spool. Displays the Script Definition form. Displays the search form for Service Desk interactions.upgrade. Initiates the Upgrade Utility wizard.search. Displays the Terminal Configuration form.search. Displays the search form for Incident Management incidents.maint cc.main benchmark.status database subtotals syslog task terminals database database query. Displays the Service Desk Security Profile form.shutdown smail mail.stored database Page 50 of 396 HP Service Manager (9. Displays the Spoolheader form. Displays the Configuration File form for standard printers.send.problems sla.start system. Displays the Validity Table Specifications form.30) . Displays the Contacts form.engine database benchmark. you may need to pass the required parameters. Displays the search form for Knowledge Base information. Displays the Configuration Item Search form. Displays the current user access level and the options for changing this access.unload query. Displays a list of unload scripts. Displays the Incident queue. These parameters consist of a parameter name and a value. userstats report.Programming Guide Chapter 2: System language triggers tskqueue unload uoperprof upd userlevel database sc. Displays the Vendor/Manufacturer search form.access usrocmo ocmo.results Call a RAD application You can call a RAD application from the following places in Service Manager: l l l l l Display Options Format Control Scripts Processes Triggers When you call a RAD application.access database usrocma ocmo. Displays a list of the current Request Management orders.userstats usrcmr cm3r.avg.access us.search. Displays the prompt for executing the Usage Statistics report. Initiates the script for opening a new change request record.stored pm.userlevel Displays the triggers form. Displays the Operator Status Display form.main usrdir usricm usrknow database icm. Displays the Benchmark Results.manage us.setup. To find view the parameters: Page 51 of 396 HP Service Manager (9.access validity vendor viewbm se. Displays the search form for Request Management orders. Displays the Task queue. index("rtecall(\"rinit\"". str(contents(currec())))>0 Returns all the RAD application panels that contain the function “rinit” (to initialize a file). See "Locate a RAD function" (on page 52). 2. Click More or the More Actions icon and then select Expert Search. 4.30) . Use this syntax to search for all instances of all rtecall functions beginning with a particular letter (for example. the letter r). A query window displays. Locate the RAD you want to use. str(contents(currec())))>0 Returns all the RAD application panels that contain the function “jscall” (to call a JavaScript function). str(contents(currec())))>0 Example: index("rtecall(\"s". Click Tailoring > Database Manager. Click Search. index("rtecall(\"<function name>\"". Syntax index("<function name>". For this query to index("rtecall(\"<first letter>". Click View when you have the RAD application panel displayed. Show context-sensitive help debug information selected.Programming Guide Chapter 2: System language 1. 3. 5. Locate a RAD function 1. Type one of the following in the Query field: Desired search Search for a function that is not an rtecall function. Position the cursor on each parameter and then click Help to view the name of the field used as the parameter. Search for all instances of a particular rtecall function. str(contents(currec())))>0 Example: index("jscall". Note: To view field help. a backslash must precede each double quotation mark within the rtecall Example: parentheses. you must have the setting. Windows client: Preferences > HP Service Manager > Appearance. This displays a list of parameter to pass. A blank application file record displays. For this query to run str(contents(currec())))>0 properly. 2. Type =application in the Form field. 3. Page 52 of 396 HP Service Manager (9. Tracing allows you to see every panel that the RAD flow encounters. 2. The RAD Debugger command window opens. Type the desired command followed by a parameter. 7. Use the command by itself to display the status of the trace function. To turn application tracing off. and set break points. A record list of RAD panels matching the search criteria displays.screen t (trace) Turns tracing on or off. 3. a backslash must precede the first set of double quotation marks.Programming Guide Chapter 2: System language run properly. 6. Start RAD Debugger 1. repeat the same command combination a second time. A common use of this command is to display the name of the Display application Screen ID attached to the current form. The closed parenthesis is not necessary in this syntax. display values. Click Window > Show View > Other > HP Service Manager Administrator > RAD Debugger. Press Enter. include the name of a RAD application.30) . You may have multiple Page 53 of 396 HP Service Manager (9. Click Search. t on t off t ta Turns panel tracing on or off for a specific RAD application. RAD Debugger commands The following is a list of the commands used in the RAD Debugger to troubleshoot an application: Command d (display) Description Displays the contents of a variable. Double-click on a panel to display that instance of the function. d $L. str(contents(currec())))>0 Returns all the RAD application panels that contain a function that starts with the letter “s” such as “sort”. To turn application tracing on. RAD Debugger The RAD Debugger enables you to view and isolate RAD processes for the purpose of troubleshooting. The RAD Debugger uses its own command line language to trace. Information about the RAD flow opens in a separate window containing a scrollable text field. it (breakpoint) halts before executing the named panel and gives you an opportunity to perform debugging procedures such as displaying variables or executing statements. When the RAD flow encounters a panel with this label. A breakpoint is applied each time the RAD flow enters the named application. $MARQUEE. Displays all the global variables—those beginning with $G. Displays all the thread variables: those not beginning with a special code. you can save time by using tar rather than using ta to turn off each trace individually. Removes all breakpoints of any type. $CHART. Resumes the execution of the RAD flow after a breakpoint occurs. b init. $lo. bt rinit bv rb go c (continue) s (step) gl (globals) Set a breakpoint when a variable changes. the application stops running and returns you to the RAD Debugger.operator b ba Sets a breakpoint on a specific RAD application. When the RAD flow encounters a RAD command panel with this name. ba menu.Programming Guide Chapter 2: System language traces engaged at one time. Use the command by itself to display a list of the RAD applications being traced.. b Sets a panel breakpoint. v (variables) l (locals) sta (stack) re (relations) Displays only the variables which are table relations (file handles initialized by the rinit command panel). Displays all the local RAD variables: those beginning with $L.30) .. Enter the command combined with the name of a RAD panel to set the breakpoint. If you are tracing multiple applications. ta script. Execute the command by itself to display a list of all current breakpoints. either when it runs for the first time or when the flow returns to it from a subroutine. $SYSPUB.. Page 54 of 396 HP Service Manager (9.execute ta tar Removes all RAD specific panel traces.. Displays the current RAD stack. Repeat the command combination a second time to turn off the breakpoint. Steps through the RAD flow one panel at a time. Re-enter the same command combination to turn off the breakpoint.manager bt Sets a breakpoint on a specific type of RAD panel. Resume execution after a breakpoint. This is equivalent to issuing the globals (g).view a variable. Display name .30) . and locals (l) commands. x display h (help) Page 55 of 396 HP Service Manager (9. variables (v). Displays a brief summary of the RAD Debugger commands. Execute a statement.Programming Guide Chapter 2: System language m (memory) Displays all the variables in memory. Programming Guide Chapter 2: System language Page 56 of 396 HP Service Manager (9.30) . JavaScript: The Definitive Guide. Page 57 of 396 HP Service Manager (9. The principal benefit of using JavaScript is that it uses an industry-standard scripting language to execute commands instead of a proprietary language. any JavaScript that addresses output is not available in the Service Manager environment. Service Manager only supports server-side JavaScript. or core language. fully understand the programming language prior to attempting to use it with HP Service Manager. Unlike programming languages. 5th Edition by David Flanagan (ISBN: 0596101996). and delete database records.mozilla. server-side. These are helpful resources that contain information about JavaScript. C++. take the JavaScript tutorial(s) at W3 Schools. scripting languages do not use compilers to create executable program code. or Visual Basic®.org/js/spidermonkey/ Language overview JavaScript is a scripting language which is different from programming languages like Java™. JavaScript in Service Manager provides the ability to query. For best results.mozilla. Note: There is a difference between server-side and client-side JavaScript.5_Guide For information about the SpiderMonkey project refer to: http://www. scripting language that offers programming tools with easy syntax and built-in functionality. insert. Core JavaScript is the base JavaScript language with client-side and server-side JavaScript as extensions. and to make use of existing RAD variables and functions. dynamically typed.Chapter 3 Introduction to JavaScript in Service Manager Like RAD. It is a smaller. update.30) . l l l For JavaScript basics. Learning JavaScript HP does not endorse these references but provides them as a courtesy to our customers and partners. JavaScript within Service Manager is implemented using the Mozilla® SpiderMonkey (JavaScript–C) Engine.org/en/docs/Core_JavaScript_1. each time the script is executed. Therefore. JavaScript can be either client-side. The Mozilla SpiderMonkey (JavaScript-C) Engine project. it runs a syntax check to verify that the script is executable. refer to: http://developer. Because JavaScript is an interpreted language. For detailed information about the syntax of Mozilla SpiderMonkey JavaScript. Server-side JavaScript is used for accessing and manipulating data and is the only one available within Service Manager. The Compile button in the Script Library does not create an executable load module. it is loaded into an interpreter that runs the code. a – z. use "//" to start a single line comment or the combination of "/*" and "*/" to enclose a multi-line comment. Statements should end in a semicolon (. For example contact. ” this”. Boolean. such as “_class” for the “class” field."String literals" section for more information in http://developer.5_Guide. as in a--.org/en/docs/Core_JavaScript_1. Quotes within a string can be entered preceded by a backslash as well. Array. underscore or digits and must start with a letter or an underscore (“_”).> function <function name>(<parameters>) { <local variable declarations. You can decrement a variable in the same way. The variable name can contain A – Z. String. See the Core Language Features . either a single or double.Programming Guide Chapter 3: Introduction to JavaScript in Service Manager Basic rules of JavaScript The following rules apply to the basic syntax of JavaScript: n n n JavaScript is case-sensitive. Boolean) may be defined as an object. The data type does not have to be explicitly defined Are global variables when defined outside of a function. Variables created within a function are local variables.). and Number.> } <function calls.> <Statements. As an example you could define: var ArrayList=new Array(”test”.Literals . such as a = a + 1. o Assume the type of the data that is put into the variable. To increment a variable. Variables: o Must be defined before being used.30) . number. and are available anywhere in the current script context. Special characters that are displayed literally must be preceded by a backslash character (\). ” list”). and can be used only within that function.name becomes contact_name. Service Manager field names that are reserved words in JavaScript have to be preceded by an underscore.name) produces the following: Hello world US. Values that are not defined as a data type (string. For example: print(”Hello ” + ‘world ‘+ Country. you can use a++. n n n n n n Structure of a JavaScript application <Global variable declarations. To enter comments in the script. o n Strings have to be enclosed in quotation marks.> Page 58 of 396 HP Service Manager (9. such as Date.mozilla. Dots in Service Manager field names must be replaced by an underscore (_) in JavaScript. otherwise.org/en/docs/Core_JavaScript_1. } Page 59 of 396 HP Service Manager (9. The statement: var return = (parm. Boolean. 30 days). Function.method or Object. Each of these is described in detail in the Working With Objects – Predefined Core Objects section of: http://developer.mozilla. parameters. bitwise operators.property.30) . works in the same way as its much longer equivalent: var result=false. string operators.5_Guide The list of operators includes assignment operators. if (parm.org/en/docs/Core_JavaScript_1. The syntax you use to call methods and properties is: Object. arithmetic operators. Number. For more information about JavaScript objects and properties refer to the Details of the Object Model section in : http://developer.org/en/docs/Core_JavaScript_1.getDate()<= 30) { result = true. logical operators. } else { result=false. Each object may contain a set of properties that more closely define the object. comparison operators.5_Guide Conditional statements The following example returns true if the date entered is within the number of days in a month (here.Date.Programming Guide Chapter 3: Introduction to JavaScript in Service Manager Expressions and operators For more information on this topic refer to the Expressions and Operators section in: http://developer. and String. it returns false. Note the use of the conditional statement to shorten the "if" expressions.mozilla.mozilla. Math. Date. and special operators. JavaScript objects and properties The key to understanding JavaScript is learning the structure of its objects. Most JavaScript functionality is contained in objects. The objects contain methods. and events.getDate <= 30) ? true : false.5_Guide Built-in objects and functions Built-in objects described in this section are Array. var n = 0. ParmNumber > 1. i++) { ParmNumber = ParmNumber / 2.org/en/docs/Core_JavaScript_1. } return i.30) .toString + “ is not numeric.mozilla. i++. ensure that the exit condition will be met.While loop is available for those instances when you want to execute a statement (or block of statements) at least once. Break and continue statements The break statement terminates a "while" or "for" loop completely. } return i. refer to Statements – Loop Statements section in: http://developer. For detailed information about the for and while loop statements. Please repair Page 60 of 396 HP Service Manager (9.While loop the exit condition is checked after the statements are executed. while( ParmNumber > 1 ) { ParmNumber = ParmNumber / 2. x) { var i = 0.. Note: Both these statements violate the rules of structured programming but are nonetheless widely used in special cases. first using a "for" loop. In a Do. } Note: A Do. The following two examples demonstrate how these statements are used.. The continue statement terminates execution of the statements within a "while" or "for" loop and continues the loop in the next iteration. function break4error(parmArray. and then using a "while" loop: function DivisableByTwoFOR(ParmNumber) { for (var i=0. otherwise an infinite loop will occur. while (i < 10) { if (isNaN(parmArray[x])) { print(parmArray[i].Programming Guide Chapter 3: Introduction to JavaScript in Service Manager While and loop statements Note: Whenever programming a loop statement.5_Guide The following example shows how to check how many times a given number can be divided by 2. } function DivisableByTwoWHILE(ParmNumber) { var i = 0. exception handling should always be included in any JavaScript program. function SetFullName(FirstName. while (i < 10) { if (isNaN(parmArray[x])) { print(parmArray[i].30) . continue. var n = 0. Continuing with next number”).toString + “ is not numeric.LastName) { if (FirstName != null || LastName != null) { FullName=FirstName + “ “ + LastName return FullName } else { throw "InvalidName" } } try { // statements to try var MyName=SetFullName(First. } Modifying the above example. } n = n + parmArray[i]. break.Programming Guide Chapter 3: Introduction to JavaScript in Service Manager and run again”). Last) // function could throw exception } Page 61 of 396 HP Service Manager (9. the continue statement would work as follows: function break4error(parmArray. } n = n + parmArray[i]. } return n. i++. The following code provides an example of using exception handling statements for JavaScript. } return n. x) { var i = 0. } Exception handling statements As a best practice. i++. i++. refer to http://developer. Page 62 of 396 HP Service Manager (9.mozilla.org/en/docs/Core_JavaScript_1.Programming Guide Chapter 3: Introduction to JavaScript in Service Manager catch (e) { MyName="unknown" logMyErrors(e) // pass exception object to error handler } For detailed information about exception handling.5_Guide See Statements – Exception Handling Statements section.30) . library. Some of these stored JavaScript programs can be used to interface with 3rd party Web Services providers. You can access any script or function in the ScriptLibrary from any of the locations in HP Service Manager that support JavaScript. use one of the following statements: system. To call one of these functions. edit. These areas focus on providing maximum flexibility for users to tailor their environment through the use of JavaScript in Service Manager. edit. All of these JavaScripts are identified as SOAP packages within the ScriptLibrary. test. and store scripts and functions. and store scripts and functions that can be called and executed from anywhere within Service Manager. Note: HP advises that you store JavaScript in the ScriptLibrary and refer to it from other places.Chapter 4 Where can I use JavaScript in Service Manager? JavaScript can be used in several places throughout Service Manager. Integrations are typically performed through JavaScript stored in the Script Library as well. Note: Do not use Adminstrative Mode when entering the ScriptLibrary. It is a central place for you to create. compile.30) . The ScriptLibrary contains JavaScripts created by users.<scriptname>. such as real-time currency conversions.<functionname>( parameters ) Page 63 of 396 HP Service Manager (9. l l l l l l l l l l l Cascade updates Display Screens Display Options Format Control Interoperability (the ioaction table) Links Processes (Document Engine) ScriptLibrary Scripts Triggers Wizards What is the ScriptLibrary? The ScriptLibrary is a file within Service Manager used to create. test. since functions such as compile and execute are not available in that mode. compile. You can use JavaScript in these places in Service Manager. and they can also return values. It is a best practice to allow the recordsizelimit to default to 256K since SOAP scripts generated by HP‘s WSDL2JS utility can exceed 64K. Note: A record can contain more than one function.library. you must establish a record in the ScriptLibrary that contains the function to be called. First.ini file. Within the record you must know the name of the script as well as create a properly-constructed function. and properties as well as function names Teal: Comments Magenta: Curly braces.Programming Guide Chapter 4: Where can I use JavaScript in Service Manager? or library. The size value is controlled by the recordsizelimit parameter in the sm. Page 64 of 396 HP Service Manager (9. The defaulting is 256K. l The color codes that the script editor uses are: l l l l l Red: Keywords Green: Objects. Setting recordsizelimit to a smaller value can result in failure when using the WSDL2JS utility with complex files. methods.<scriptname>. return ret_val. punctuation characters Black: Default color Calling a function in the ScriptLibrary ScriptLibrary records contain functions that can be called from anywhere you can call JavaScript. Using this technique allows for more effective management of user JavaScript functions. Functions can use parameters as part of the calling structure. } function cube(value) { var ret_val = value * value * value. but changing this value will affect all records in the database.30) . This is an example of using more than one function. /* Sample script system. This is general record size in database. operators.<functionname>( parameters ) ScriptLibrary editing environment This is a list of guidelines for the size of scripts in the ScriptLibrary. l l The maximum size of a script allowed in the ScriptLibrary is 256K.functionTest */ function square(value) { var ret_val = value * value. respectively: system.<scriptname>. var y = system. " squared = ". The syntax for this function is: jscall( "script. " squared = ". .square(x).library. you can call any function that is defined previously within the same record by simply typing: <functionname>( parameters ) To call JavaScript from any RAD process panel.<script name>. " cubed = ". by using the following syntax: system. jscall("tzfunctions.functionTest. y = system.getTZforOperator".library.. . arg2. print(x. You can access any script or function in the ScriptLibrary from any tool within Service Manager that supports JavaScript.function" . y). print(x. y = system. argN ) The following statements illustrate a JavaScript call to the system library and a call to the script library via jscall().cube(x).functionTest: var x = 3. x = -2.library. x = 2.functionTest. you can use the jscall RAD function.square(x).<function name>(<Comma separated list of parameters>) The following is an example of calling the functions of system. /* The 3 -2 2 */ function calls produce the following output: squared = 9 squared = 4 cubed = 8 When working with the ScriptLibrary. “falcon”).tzfunctions.library. y). ensure that all inputs are available. } To call the function use the following syntax: system.library. print(x.library.Programming Guide Chapter 4: Where can I use JavaScript in Service Manager? return ret_val. Page 65 of 396 HP Service Manager (9.getTZforOperator(“falcon”). y). Executing the script will compile the code and then run it.<functionname>( parameters ) Within a ScriptLibrary record. Before executing the code. you can compile the JavaScript code to check for syntax errors.functionTest.30) . arg1 ..library. filename($L.display Example: $L. This code can serve as an example for Administrators who need to customize the Close button label for other special cases.filed) The log4js script The log4js is a logger type script similar to log4j. cm3t for Task currentPhase: current phase of the change or task file: the file record This function is currently called from display screen cm. Warning messages are logged.30) .view. Debug information is logged. The labels are Close Task. Everything is logged. $L. Close Change. in the out-of-box system. The function is getCloseLabel(filename.label=jscall("changeManagement. file) filename: name of the table we are currently on. or Close Phase. file)in the ScriptLibrary file changeManagement. Error messages are logged. currentPhase. cm3r for Change record.Programming Guide Chapter 4: Where can I use JavaScript in Service Manager? Example: Function to control close button label in Change Management Change Management uses the function getCloseLabel() to control what label to display on the Close button.filed). The log4js script allows developers to set the following logging levels.file. It provides a lightweight but useful script to log events in a Service Manager script that you want to debug .phase in $L.close. Included in this function is code to process a special case. Information messages are logged (default). current. Unplanned Changes. Fatal error messages are logged. The details are as follows: l l l l function getCloseLabel(filename. Page 66 of 396 HP Service Manager (9. It provides a means to trace information in the Message view while controlling the level of detail being logged. It allows developers to turn inline debugging on and off.getCloseLabel". log4js log level OFF ALL DEBUG INFO WARN ERROR FATAL Description Nothing is logged. currentPhase. log4js($loglevel.log)."my prefix"). The log4js script supports appending a prefix to each message.info("an info").setLevel("WARN").30) .debug Description Write a debug message. Sample code snippets myLogger. $prefix).setLevel("OFF"). myLogger. You can also use the following method to create an instance of the logger: var myLogger=new lib log4js. Constructor syntax: var samplelog = new lib.Log. Method $log. myLogger.WARN).log4js. Page 67 of 396 HP Service Manager (9.setLevel(lib.Log("INFO". background: server log foreground: Message view API methods: The following table lists the API methods for log4js.log4js.Programming Guide Chapter 4: Where can I use JavaScript in Service Manager? API Details The log4js should be initialized before it is used.log4js. myLogger. Type of Logger: Logger alertLogger Description Output information to Service Manager Message view or the server log file (default: <SM server installation directory>\logs\sm.INFO). You can also change the log level or turn off logging with this format: myLogger. For example: var myLogger=new lib.setLevel(lib.Log.log4js.error("an error").Log.Log(lib. depending on whether a background or foreground process calls the log4j functions.warn("a warning").OFF). myLogger. You can change the log level or turn off logging with: myLogger. and enter the following statements: Page 68 of 396 HP Service Manager (9.Programming Guide Chapter 4: Where can I use JavaScript in Service Manager? Method $log. Examples of calling JavaScript from different Service Manager tools The following examples offer suggestions about using JavaScript in some of the tailoring tools that support this functionality. Script name: log4js Package name: null Performance impact The log4js uses the standard Service Manager print method to write the Service Manager server log file or the Messages view.setPrefix $log.warn $log.setLogger Description Write an information message. Retrieve the log level. Format Control The following example can be used to verify whether or not the operator who was just entered in the assignee. “no assignee”) 2.getLogger $log. but keep in mind that when logging is turned on there is a performance impact so log4js should be used carefully. Get the prefix information.name field in the incident ticket is currently logged in.info $log. Click the JavaScript tab. Get logger information. validation will fail. Otherwise.fatal $log.old = nullsub(assignee.getPrefix $log. In the Calculations section of Format Control. 1. Set the logger information.setLevel $log. Set the prefix information.name in $file. which is useful for debugging your JavaScript.30) . enter true for Add and Update.error $log. Additional JavaScript examples can be found in the Programmer’s reference section of this document. in the initial column enter a condition of true. Write a fatal message. Set a log level. Then add the following in the calculation column: $assignee.getLevel $log. Write a warning message. Write an error message. assignee_name.issues. In this example. This lets variable values be exchanged between JavaScript and RAD expressions. Please try another assignee. Updates the device record. Properties such as the length property assume that the value is a function if it is enclosed in curly braces {}.vars. and how to update fields in that record. Note: In JavaScript. 4.old. var file = system. “IM1002”} does not work in JavaScript. Increases a counter in that configuration item called num. the JavaScript code: l l Queries the configuration item that was previously selected from a fill.$IsUser=usersString.vars.30) . and the toXMLString() function. var newAssignee = file. var usersString = usersXML. If the configuration item does not exist.indexOf(newAssignee). An array from Service Manager cannot be directly copied into a JavaScript array.CI (this new field has to be added in the device file). 3. Any RAD variable can be set and used by preceding it with system. as shown above.toXMLString().vars. To successfully convert a Service Manager array into a JavaScript array.on. This example uses the standard indexOf method for the String Object. or create a "while" loop or a "for" loop to move through the elements and do an element-by-element transfer. /* opens the device file */ var CIName=system. Enter the following in the Validation message field: The new assignee is not logged in at this time. Functions such as length may not work on null values. Adds the new ticket number to an array of issues in the device file called array.users. Links This example shows how to query a record from within Service Manager.Programming Guide Chapter 4: Where can I use JavaScript in Service Manager? var usersXML = system.$File. l l l l var CI_Record=new SCFile("device"). If the item is currently down.toArray method. system. And the following expression in the Validation column: $IsUser > 0 5. you can either use the SCFile. it shows how to transfer an array from Service Manager to JavaScript. in the Add and Update column: assignee.name in $file~=$assignee. In the Validation section enter the following.incidents. to search for the user who was entered as the new assignee in the XML object containing all logged-in users. Additionally. it issues an error message.vars. /* passes in the logical name from $File */ /* Selects the configuration item to update */ Page 69 of 396 HP Service Manager (9.logical_name. because the syntax of Service Manager {“IM1001”.$file. it sends an alert to the person who is opening the ticket. it is very important that you handle null values. length. } CI. } else { j=array_incidents. " + RCtoString( findCI_RC ) ).30) .Programming Guide Chapter 4: Where can I use JavaScript in Service Manager? function getConfigurationItem( CIName ) { var findCI_RC = CI_Record. /* get the incident ticket number */ var array_incidents = new Array().$File.num_issues_on_CI++."). /* increase counter */ var incNumber = system. if (i < 0) /* Check if incident is already in the list */ { /* If not.array_incidents[ind] != null) /* convert the SC array into a JS array (see paragraph below) */ { array_incidents[ind]=CI.number.vars. var ind = 0.is_down == true) { print("The configuration item is down at the moment. var temp_string = array_incidents. ind++. } var j=0. var i = temp_string.toString().array_incidents[ind]. } Page 70 of 396 HP Service Manager (9. return null. enter the incident number to the list */ if (array_incidents == null) { j=0.doSelect( "logical. Please check existing tickets if the cause for this issue is related to the down system.indexOf(incNumber). while(CI. if (findCI_RC==RC_SUCCESS) { return CI_Record. } else { print( "Could not find configuration Item.name=\""+ CIName + "\"" ). } } /* Increases the use counter that counts how often this item was affected by an incident ticket and enters the incident ticket number into the array of incidents */ function increaseUseCounter(CI) { if (CI. thus syntax errors are not caught until execution.record. system. return system. var incAssignee=NewRecord.Programming Guide Chapter 4: Where can I use JavaScript in Service Manager? array_incidents[j] = incNumber. /* This is the $L.g form contains a field for entering JavaScript (Script).vars. incAssignee..$L_new. Use the Compile icon in the ScriptLibrary to verify the syntax of your trigger script function.strings[2]="problem update".strings[1]="1".assignee_name.triggerXYZ( ). newSchedule.30) .triggerXYZ( system. newSchedule. increaseUseCounter(CI). a trigger sends a message to the assignment group identified in an incident record that the record has been updated and to whom it is assigned. } /* Insert a message schedule record into the schedule file */ function insertSchedule( incNumber. It then adds an activity note that the message has been sent. Adressees) { var newSchedule = new SCFile( "schedule" ). } CI.myTriggers. if (incAssignee==null) { incAssignee="no one at the moment".application= "message. newSchedule. newSchedule. newSchedule. For example.myTriggers. For example.number. HP recommends that the Script field contain single statements that invoke functions in the ScriptLibrary.. } /* Call previously defined functions to execute code */ CI=getConfigurationItem(CIName). return system. and they can access the value of the same record on disk using the global object called system. newSchedule.library. Trigger scripts can access the value of the current record in memory using the global object called system.bg"._class = "problem". Triggers example In this example.array_incidents = array_incidents. The user can indicate the failure of a trigger by returning the value of –1. var today=new Date().name= "message processor record". HP Service Manager does not allow you to compile JavaScript on this form.oldrecord ).library.new record passed in from the trigger */ var incNumber=NewRecord. A trigger script only needs to return a value if the trigger fails.record.doUpdate().oldrecord. CI. var NewRecord=system. Trigger scripts The triggers.expiration= today. Page 71 of 396 HP Service Manager (9. doInsert(). } } /* Inserts an activity with the information that the email notification to the assignment group members has been sent */ function addActivity(incNumber) { var newActivity = new SCFile( "activity" ).scheduleActivityUpdate ( newActivity.strings[5]="pm.type= "Update".assignment ). newSchedule. } } /* Selects the operators to send the message to */ Addressees = selectAddressees( NewRecord.type. } /* Selects the operators that are members of the assignment group to return to the calling function */ function selectAddressees(assignmentGroup) { var assignment = new SCFile( "assignment" ).". return null. return addressList.activityUpdates.Programming Guide Chapter 4: Where can I use JavaScript in Service Manager? newSchedule. newActivity.library.doSelect( " name=\""+ assignmentGroup + "\"" ).30) . " + RCtoString( findAssignment ) ).strings[3]="Problem " + incNumber + " has been updated.datestamp= today.description ). newActivity. newActivity. if ( findAssignee == RC_SUCCESS ) { addressList=assignment. var findAssignee = assignment. if (result == RC_CANT_HAVE || result == 51 ) { system. newActivity.operators.strings1=Adressees. } else { print( "Could not find assignment group. It is assigned to " + incAssignee + ". var today=new Date(). var result = newActivity. newActivity. newSchedule. newSchedule. var rc = newSchedule. if (Addressees != null) { Page 72 of 396 HP Service Manager (9.number= incNumber. newActivity.".strings[6]=" Soap-Windows XP".main".doAction("add").description[0]= "Notification email on the update has been sent to all members of the assignment group. To use a RAD function in a JavaScript. /* adds an activity to inform the user of the email being sent*/ addActivity(incNumber).file. Note: Because the class field name in the schedule file is in conflict with the class keyword used in JavaScript. It does not work for local variables. In addition.functions" and replace any periods (. RAD functions: parse() and evaluate() Returns the value of a given expression.functions. you can transfer local variables to thread variables before calling the parse_evaluate expressions. Example If in the useroptions table there is an expression $lo. Using RAD functions in JavaScript You can use most RAD functions in JavaScript. 10 ).Programming Guide Chapter 4: Where can I use JavaScript in Service Manager? /* adds the message to the schedule file for sending */ insertSchedule( incNumber. how to call a function from the Script Library.username="Sys. and how to insert a new record. Note: The expression works when the statement being evaluated and parsed contains thread or global variables. Note: The data is the character string to parse and the parse type is the numeric value normally passed into the parse function. Syntax system. it must be preceded by an underscore (_). } The example also shows (among other things) how to call a Document Engine Action. Addressees).) in the function name with an underscore (_). However.parse_evaluate(expression in $l. Syntax Page 73 of 396 HP Service Manager (9. 10 )) userIsSysAdmin = true. JavaScript function: parse_evaluate() Returns the value of a given expression. compare the following functions: l l l "RAD function: parse" (on page 117) "RAD function: evaluate" (on page 95) "JavaScript function: parse_evaluate()" (on page 73) Refer to "List: RAD functions" (on page 81) for a list of other RAD functions. simply prefix the function with "system. incAssignee.30) .functions. it shows how to use several functions within a single JavaScript and how to call them.parse_evaluate( exp .Admin." this example returns the value of that expression. For an example of how to do this. if (system. " this example returns the value of that expression.username="Sys. Note: The Query object has been deprecated. Query operator Description EQ LIKE NEQ GT GE LT LE ISIN Equals to Starts with Not equal to Greater than Greater or equal to Lower than Lower or equal to Is an element in the array Page 74 of 396 HP Service Manager (9. They are names representing values that are globally defined.Admin = true Note: The expression works when the statement being evaluated and parsed contains thread or global variables.30) . Example If in the useroptions table there is an expression $lo. 10))) $userIs. JavaScript global properties Global properties are predefined properties that are not part of any object. but older JavaScript code within the ScriptLibrary still uses the object. if (evaluate(parse(expression in $l. and Service Manager has a number of additional global properties. There are two categories of Service Manager-defined global properties: Query operators JavaScript return code properties Query operators These operators are used solely for constructing query expressions using the Query object.file. 10 ) Note: The data is the character string to parse and the parse type is the numeric value normally passed into the parse function.Sys.Programming Guide Chapter 4: Where can I use JavaScript in Service Manager? evaluate(parse(exp. However. The core JavaScript language has several global properties. such as NaN (Not a Number). It does not work for local variables. you can transfer local variables to thread variables before calling the parse and evaluate expressions.Admin. The operation failed. The operation failed because the file name is not valid. No more records are available in the result set. Check to make sure the file name is correct.doSelect(new QueryCond("number". Check to make sure the file name is correct. The operation failed because the resource is unavailable because some other user or process has the resource locked. EQ.log file for more information. The operation failed because the record was deleted by another user or process.Programming Guide Chapter 4: Where can I use JavaScript in Service Manager? Example: var q=new SCFile("probsummary") q. The insert operation failed because the file already contains a record with this unique key value. The query failed due to incorrect query syntax. The operation failed because the data supplied in a field or the record did not pass validity checks performed by the application. Check the permissions associated with the user who submitted the request. that the file exists. The operation failed. that the file exists. To print the error message rather than the return code. and that it is not read-only. and that it is not read-only. The update operation failed because the record was modified by another user or process since you read it. Check to make sure the file name is correct. The operation succeeded. JavaScript return code properties Use these properties (which are represented internally as integer values) to test the values returned by object methods such as SCFile.30) . "IM10002")). use the RCtoString function. and that it is not read-only. The request operation was not performed due to an authorization failure. Examine the contents of the Messages view or the sm. The operation failed. that the file exists. Return code RC_ERROR Description Some other error occurred. RC_SUCCESS RC_CANT_HAVE RC_NO_MORE RC_DUPLICATE_ KEY RC_MODIFIED RC_DELETED RC_BAD_QUERY RC_NOT_ AUTHORIZED RC_VALIDATION_ FAILED RC_UNABLE_TO_ WRITE_TO_FILE RC_UNABLE_TO_ CLOSE_FILE RC_UNABLE_TO_ DELETE_FILE RC_INVALID_ FILENAME Example: Page 75 of 396 HP Service Manager (9. execute on panel exec.and post-JavaScript and RAD expressions that are executed in the following order: l l Page 76 of 396 HP Service Manager (9.screen. followed by Javascript Executed on Cancel. immediately after the post expressions. n File Selection: The Select $L. so that expressions take precedence over JavaScript.expressions.expressions panel. Wizards: Wizards use JavaScript in 3 different areas: During File Selection.config.fill or us.statements. respectively. JavaScript code in Format Control is executed via the format.30) . the JavaScript expressions are executed after the RAD expressions.Programming Guide Chapter 4: Where can I use JavaScript in Service Manager? var rc = mySCFile.action application on the panel process. Actions. } else throw( "Error " + RCtoString(rc) + " occurred trying to insert a record" ).find.record.javascript panel.link on evaluate. on the eval. Display screens: In the display application on the panel prep. Cascade updates: The JavaScript in cascade updates is executed from the RAD application process. This is done in us.post. Triggers: The JavaScript in the triggers file is executed after the RAD application. The evaluate expressions panel is executed before the evaluate. Scripts: In script. This happens in us. n l Interoperability (ioaction file) : The ioaction file executes only JavaScript and not RAD expressions.update.file by information is processed first. The post JavaScript is executed after the fill or find was performed. l Format Control: The JavaScript is executed after calculations and before validations. followed by the information on the Format Control / Process Name tab. The JavaScript code is executed in the ioevents. if ( rc == RC_SUCCESS ) { print( "Insert succeeded" ). RAD expressions are processed before JavaScript expressions. the Expressions are run first. and Cancel Expressions.doInsert().cjavascript RAD. Order of execution of JavaScript versus RAD language This section lists all tailoring tools in which JavaScript can be directly entered and describes at what point in the process the JavaScript code will be executed.process.action. Cancel Expressions: First the Expressions Executed on Cancel are processed. then the JavaScript. This is controlled by the server binaries and not by RAD code. followed by the Initial Expressions and then the JavaScript. Display options: Display options have pre. Links: JavaScript in links is executed after the (initial) expressions. n l l l l l l Actions: In the Actions tab. but before the fill or find is executed. Service Manager task Create a file variable Select a record RAD panel / expression rinit JavaScript expression new SCFile(“filename”) select RC=ObjectName.30) . the ObjectName is the name of a Service Manager object such as a table. RAD application(s) 5. Post-RAD expression 5.Programming Guide Chapter 4: Where can I use JavaScript in Service Manager? 1. RAD application 4.doRemove() result=ObjectName. Initial RAD expression 2. Corresponding JavaScript syntax for RAD language tasks Most Service Manager tasks can be translated from RAD language to JavaScript by using the JavaScript expressions identified in the following table.fieldname Update a record rupdate Add a record Delete a record Refer to a field in a file Access an element of an array radd rdelete result=fieldname in filevariable result=rownumer in arrayname in filevariable result=ObjectName. Post-JavaScript 6. Initial JavaScript 3. Display Action l Processes: Process records have initial and final JavaScript and RAD expressions executed in the following order: 1.doUpdate() RC=ObjectName. Pre-RAD expressions 4.doInsert() RC=ObjectName. Pre-RAD expression 2. Next Process (if applicable) l Schedule: JavaScript in the schedule record is executed after the RAD application is called and before the check for deleting or rescheduling the schedule record. Pre-JavaScript 3.doSelect(“Query”) RC=ObjectName. Final RAD expression 7.arrayname[rownumber] Page 77 of 396 HP Service Manager (9. Post-RAD expressions 6. In the JavaScript expression. Final JavaScript 8. 30) .Programming Guide Chapter 4: Where can I use JavaScript in Service Manager? Send a message to screen Convert a field / Object to string call message application print(“message”) str() RC=ObjectName.getText() Page 78 of 396 HP Service Manager (9. parts apm.panel.problem.record apm.cost.flow agmap.launch.group.incident.query apm.profile apm.pass.position encl.inbox apm.print.sybase create category db2mvs.bigroup adl.initial apm.request.print.oracle convert.graph get.totals cm3t.backup display.panels agmap.repair.monthly.tapi.fields agmap.user apm.get.xref agmap.fc fix.backup agmap.add.remove.remove.flow.query apm.group apm.get.add.get.open.query apm.process.get.editor.assign.bulkupdate2 am.group apm.job apm.add.sqlserver convert. add.add.header cm.to.problem apm.get.open.condense.probassign.only agmap.save apm.downtime.add.Chapter 5 System Language reference This is the reference section for the system language.fields find.related.totals cm3r.set.sqlbasename display.initial.alias.appl.search.values apm.arrays agmap.setup ag.template.request.assignment apm.scm7 cm3r.db2mvs convert.serno Page 79 of 396 HP Service Manager (9.cigroup. In this section you will find a list of the RAD functions.totals cm3t.print.print.fla find.rename.SAV apm.get.illegal.inbox apm. and a list of RAD routines.assign. or it has been replaced with updated capabilities.assign. Deleted RAD applications The following RAD applications have been deleted from Service Manager 9.file.totals convert.group.condense agmap.query apm.post.30 because the functionality they provided is no longer supported by Service Manager.30) .form.parts apm.membership apm.reports am.group apm.group.update apm.group.initial. a list of the rtecalls. profile system.qbe.add.fill.problem.2 cau.edit.profiles cau.homesite trigger.add.check.remove.group apm.to.problem.main.delete.add.add.close cau.add.add.user rca.lists us.from.delete.delete.msgs pm.edit.user.dt.delete.user apm.problem.profile cau.operator apm.main apm.event cau.group cc.screlate.child.problem apm.create.arrow category.check.profile2 cau.profile rca.edit.edit.create.clean apm.find.rm.done.set.30) .group rca.expand.counter trigger.group apm.warnings isg.edit.close.green.add.record apm.admin apm.delete.edit.stub apm.record apm.group apm.edit.end.delete.sub apm.build.profile cc.record apm.remove.add.assign.edit.nls trigger.contract isg.add.delta us.group cc.fill.edit.log pmc.group rca.group rca.process.next.downtime apm.backup cau.thread.list apm.profile rca.add.user apm.copy.groups cau.delete.admin rca.group cc.delete isg.group append.profile apm.profile cc.msg.warnings label.to.profile rca.user.user cc.profile cc.profile apm.create.demon apm.profile apm.user cc.membership apm.calc.delete.email.saf.edit.shadowsite unconvert.user apm.user cau.delete.remove.contract isg.user rca.pending pm.edit.display login.delete.gen.groups cau.edit.group cau.screlate apm.build.get.rename big.delete.create.user rca.sql.assign.group cc.edit.profile apm.from.agi.link apm.group rca.sm.delete.message apm.cascade.build.send apm.admin cc.user Page 80 of 396 HP Service Manager (9.repair rca.cp.decide.related appl.pm.Programming Guide Chapter 5: System Language reference apm.profile cc.group apm. shell apm.user cc.user. For example.assignments cc.30) . Service Manager syntax rules must be followed." Returns a string containing the name of the current format.format cursor. tod()--returns the current date and time.call apm.load. For example: l l l operator()--returns the logged-on operator ID.device current.group us.get.Programming Guide Chapter 5: System Language reference apm.length=lng($string) In most cases.fix.end.flush cleanup contents copyright currec current.text xanadu. which means that it can be used in any expression on the right hand side of an equals sign.set List: RAD functions A RAD function is an operand.field. such as "SOAP-Windows Vista.text cc.fix. Returns a structure containing the current record in a file variable. RAD functions can be used in statements to further define selection criteria and/or execute commands.membership cc.make. Function add.remove.graphnodes(xml) Description Returns XML to the Run-Time Environment (RTE) for the expand action on a node in the graph diagram. If you prefer to work with JavaScript rather than RAD. initialize values. Returns a string with the type of system the user is using to log in to Service Manager. see "Using RAD functions in JavaScript" (on page 73) for more information.contents Page 81 of 396 HP Service Manager (9. the result of a RAD function can be assigned to a variable using the assign (=) assignment statement: $string.timezone. option()--returns GUI option number of the last displayoption selected. and perform calculations.fix. Frees the storage associated with a variable.to. Represents the current file handle in queries.stored. there is a JavaScript function that can do the same operation as a RAD function.required.errmsg us. Returns a string containing the contents of the input field in which the cursor was positioned when the last interrupt key cache. Removes the specified item from the memory cache. Returns a string with the HP copyright notice.queries apm. Functions provide a method of performing certain commands that will return a value when executed. Generates a formatted string based on a record and format name passed as parameters. Copies an entire file variable from one record to another.field. cursor. Returns true if the selected field is read-only. Executes a specific string as though it were a processing statement. cursor.line date day dayofweek dayofyear delete denull descriptor evaluate evaluate. relative to the screen. Returns an array with all trailing NULL entries deleted. Returns the base name of a form. Moves the cursor to a field.form. Returns the day of the month for a date regardless of the date format Returns a number from 1 to 7 representing the day of the week for a specific date.query exists fduplicate filename frestore genout get.field. stripping off the form extension for GUI or Web forms.Programming Guide Chapter 5: System Language reference was pressed. Returns a string containing the name of the file for a specified file variable.field. in which the cursor was positioned when the last interrupt key was pressed. Returns the date portion of a date/time variable and defaults time portion to ’00:00:00‘. Returns the database dictionary descriptor record for a file variable. Returns an array with specific elements deleted.name Returns a string containing the name of the field in which the cursor was positioned when the last interrupt key was pressed. Evaluates a query against a record. Returns the number of the line.set cursor.readonly cursor. Restores all fields in a file variable to their original database values. Checks for the existence of a field in a file.name Page 82 of 396 HP Service Manager (9.base. Returns the day of the year for a date regardless of the date format. Returns false if the selected field is not read only.name.30) . dateformat get.graph. Allows an application to create a subset of the current Mandanten values. Returns the activated action on a node in the graph diagram.uid gui index insert iscurrent jscall lioption lng locks logoff logon mandant max messages Page 83 of 396 HP Service Manager (9.graph.graphnode. Returns array of current outstanding locks.action get. Logs a user off.lock. Determines if the record with which you are working is identical to the version stored in the database. Returns the element number of an array or the position in a string that matches a specified string. Returns the value of the graph ID for the expand action on a node in the graph diagram.30) .Programming Guide Chapter 5: System Language reference get. Returns a 24-character identifier that is unique to an installation of Service Manager Determines whether or not Service Manager is running in GUI mode. Returns the number of elements in an array or characters in a string.id get. Indicates whether a given input value is a licensed option on the current system.owner get.timezoneoffset get.graph. informational. Returns the absolute time difference between GMT and the time zone of the operator.id Returns the date format of the current operator ID. Returns the value of the node ID for the expand action on a node in the graph diagram. Returns the name of the owner of a resource lock.target get. Enables you to invoke JavaScript from within RAD. The log is implemented as a wrap-around cache of the x most recent messages (error. Returns a modified array with a specified number of new elements inserted at a specified location. Logs a user on. Returns the target for an activated action on a node in the graph diagram. and action). get. Returns the largest value in a list of values or in an array. Provides logging functions for use in the memory message log. Programming Guide Chapter 5: System Language reference min modtime month Returns the smallest value in a list of values or in an array.selection("fieldcontents") Returns the contents of the fields associated with the multiselection." Returns an array of row numbers that were selected. Returns the month of year for a date regardless of the date format. otherwise returns false. Returns the time a record was last modified. Returns a number rounded to a specified number of digits. Returns true if the value of a variable is NULL. Returns the string of the name of the currently logged on operator.selection("rows") multiselect. Compares two compound or null values. Returns an evaluative expression from a given string value. Returns false if the value of a variable or field is not NULL. multiselect. Returns true if two values are identical. multiselect. Returns a text string matching the format of the message ID multiselect. Substitutes a null field with the value given. Returns the Table ID associated with the multiselection. Copies a set of fields from one record to another record.selection("tablename") null nullsub operator option parse perf policyread processes prof recordcopy recordtostring round same scmsg Page 84 of 396 HP Service Manager (9. The associated column name is set using the Forms Designer property "Selection Field.30) . Returns the value requested on various system performance profiles.selection("selections") multiselect.selection("selected") multiselect. Returns true or false if the provided file variable has multiple records selected. Returns the number of rows selected. Returns the number of the last option key pressed. Evaluates system performance and writes the information to disk.selection("fieldname") Returns the field name of the column associated with the multiselection. Takes the value of a field from an array and appends the value to a string. Returns array of current logged on processes. Reads the data policy from a datadict table. Returns a string from a portion of a string. Pads a string with trailing blanks until the string is a certain size. Clips a number of characters from the beginning of a string. replacing a specified character sequence with another string.get(“ActiveLicenses”) sysinfo. Inserts a substring into another string. Returns the total number of currently active named users.get(“ActiveFloatUsers”) sysinfo. Returns the total number of currently active floating users. Replaces part of a string with a substring.30) .Programming Guide Chapter 5: System Language reference number and message class specified. Extracts a substring from a multibyte character or binary string. Removes all leading blanks from a string. set. Makes a string a specific length by either clipping or adding trailing blanks. Sorts the fields of an array in a file. loads an unload file containing only data records of one file into a target file. Inserts copies of a string into another string. Returns the total number of currently active licenses.timezone setsort shutdown Sets time zone and other system parameters. Deletes a number of characters from a specific spot in a string. Replaces part of a string with copies of another string. simple file load str stradj strchrcp strchrin strclpl strclpr strcpy strdel strins strpadl strpadr strrep strtrml strtrmr substr substrb sysinfo. Returns a string of a string or non-string data variable. Clips a number of characters from the ending of a string. Shuts down Service Manager from inside the system. Returns a string. This function does not return any values. Removes all trailing blanks from a string.get(“ActiveNamedUsers”) Page 85 of 396 HP Service Manager (9. Pads a string with leading blanks until the string is a certain size. The function replaces any variables in the message with the text specified in an array of values. Returns the number of the current RAD thread. Returns “GUI” or “text”.get(“Mode”) sysinfo. Returns the version number of the client software as a string. Returns the server session language code value that is used for localized forms and messages. Returns the PID for RAD.get(“PrintOption”) sysinfo. Returns the Service Manager server port used by the connected client or the system name when called by a background process.get(“MaxLicenses”) sysinfo.get(“MaxFloatUsers”) sysinfo.Programming Guide Chapter 5: System Language reference sysinfo.get(“Quiesce”) sysinfo.get(“Display”) sysinfo. Returns “true” if telephony is enabled and “false” if telephony is disabled. Returns the label name of the last RAD panel that was executed.get(“RecList”) sysinfo.get(“ServerPID”) sysinfo. Returns “true” if record list is enabled and “false” if record list is disabled. Returns “true” if system is quiesced and “false” if system is not quiesced. Returns the name of the operating system that Service Manager is running on. Returns the name of the environment in which the client is operating.get(“ClientVersion”) sysinfo. Returns the maximum number of licenses used since the server started.get(“ClientNetAddress”) Returns the Service Manager client network IP address as a character string.get(“ClientOSName”) sysinfo.get(“TotalFloatUsers”) Page 86 of 396 HP Service Manager (9.get(“Telephony”) sysinfo. “server” or “client” depending on how the system is set. Returns the Service Manager server network IP address as a character string. depending on the type of client that is running. Returns the total number of floating users logged on since the server started.get(“Environment”) sysinfo. Returns a value that states the type of client being used.30) .get(“ThreadID”) sysinfo.get(“languagecode”) sysinfo. Returns the PID of the server as a number.get(“ServerNetAddress”) sysinfo. Returns the total number of floating users allowed.get(“ServerNetPort”) sysinfo.get(“PrevLabel”) sysinfo.get(“ClientPID”) sysinfo. Returns printing option information. sysinfo. graphnodes() Example add. Returns a non-string data type converted from a string. Returns the current date and time. replacing upper-case letters with lower-case letters.Programming Guide Chapter 5: System Language reference sysinfo. Returns the total number of named users allowed. Returns the full year for a date regardless of the date format.graphnodes(xml) Description A RAD function that returns XML to the Run-Time Environment (RTE) for the expand action on a node in the graph diagram.get(“TotalProcs”) Returns the total number licenses allowed. Returns a string translated from one character set to another.get(“TotalUserProcs”) time tod tolower toupper translate trunc type val version year RAD function: add. Function cache.flush( nType.get(“TotalNamedUsers”) sysinfo. Returns a string.graphnodes(xml) RAD function: cache. Returns the total number of executing system and user tasks. Returns the total user tasks. Returns the total number of system tasks. Returns the time portion of a date/time variable. Returns a list of version information.30) . Truncates the decimal digit number to a specified number of digits. Returns the numeric type of its argument.flush A RAD function that removes the specified item from the memory cache. pItem ) Page 87 of 396 HP Service Manager (9. sysinfo. Function add. replacing lower-case letters with upper-case letters.get(“TotalSystemProcs”) sysinfo.flush Format cache.get(“TotalLicenses”) sysinfo. Returns a string. functions call.flush( $L. but it is generally used on local and thread variables to clean up values before a user logs out. this is the parent RAD thread. Note that if flush type 3 does not use the pItem parameter. or global). Factors This function does not return a value. and 4 remove the item from the global shared memory cache. l l l l 1 flushes application/code records 2 flushes dbdicts 3 flushes formats 4 flushes SQL maps pItem is the name of the item to flush enclosed in quotation marks. Example cleanup($system) Page 88 of 396 HP Service Manager (9. Flush type 3 removes the item from the local format cache.30) . For global variables. this is the parent RAD program. "probsummary" ) To flush the local format cache: $L. Function cleanup Format cleanup(file variable). Note: This RAD function is not available as a JavaScript system. 2. For local variables.flush( 2.type = 3 cache. For thread variables. It cleans up (empties) the variable or field specified by setting the value to NULL. this is the user session. variables remain in memory until their defining environment ends. This is the preferred way to clean up both variables and fields in records as opposed to $x=NULL or field in $file=NULL. Factors This function returns no value. thread.Programming Guide Chapter 5: System Language reference Parameters nType is a number from 1 to 4 representing the type of flush operation.type ) RAD function: cleanup A RAD function that frees the storage associated with a variable. Example To flush the dbdict record for the probsummary table: cache. Flush types 1. You can use this function on any variable type (local. where file variable is the variable you want to cleanup. Unless you run this function. Function contents Format contents(file variable). Factors If you use the contents() function to compare two records.30) . Function currec Format currec() Example modtime(currec())>‘1/1/05’ Page 89 of 396 HP Service Manager (9. the arrays in one record may contain extra null values. as shown in the following example: denull(contents($save.P.variable) RAD function: copyright A RAD function that returns the HP copyright notice in a string. When used as a select statement.Programming Guide Chapter 5: System Language reference RAD function: contents A RAD function that returns a structure containing the contents of the current record in a file variable. it selects all records modified since the date you specify from the current file. If one record is displayed and the other is not. Note: Always test for null values first.rec))=denull(contents($rec)) Example contents($file. Using the denull function on an empty array of structures converts the array of structures to a simple array. Function copyright Format copyright() Example copyright() returns Copyright© 1994-2011Hewlett-Packard Development Company. always use the denull function on both records first to remove null values. RAD function: currec A RAD function that represents the current file handle on queries. L. where file variable is the contents you want to obtain. cursor.device is set to the value of current.device upon login.name.contents Format cursor. Example current.field.set A RAD function that sets the cursor to a specific field on a form.field. Example cursor.field.contents() returns a101a01. RAD function: cursor.device() Factors The value of $lo.format A RAD function that returns a string containing the name of the most recently displayed format.format( ) returns problem.set Format Page 90 of 396 HP Service Manager (9. the content of the current element is returned.contents A RAD function that returns a string containing the contents of the field where the cursor was last positioned when the user performed an action such as clicking Fill or Find.name. If the action opens a new form.field.30) . Function current.format() Example current.field. Function cursor.contents() Factors If the field is an array.device Format current.field.device() returns /dev/tty00 (on Unix) RAD function: current. Function cursor. or double-clicking on a QBE list.contents will return the focus on the pop up form.device A RAD function that returns a string containing the name of the device or Configuration item (CI) associated with the user that is currently logged on. Function current.open RAD function: cursor.format Format current.Programming Guide Chapter 5: System Language reference RAD function: current.field. Programming Guide Chapter 5: System Language reference cursor.field.name.set($field.name, $row.number) Parameters $field name is the field name $row.number is for arrays (optional) Factors l l This function returns no value. It is not necessary to use it in an assignment statement. If the field is an array, you can position the cursor on a specific row by specifying $row.number. Example cursor.field.name.set("address", 2) After execution, the cursor appears in the second row of the Address input field on the next form displayed. RAD function: cursor.field.name A RAD function that returns a string containing the name of the input field where the cursor was located when the user pressed an interrupt key, such as the Enter or option keys. To position the cursor in a specific field, use the cursor.field.name.set function. The function returns the field name as it is defined in the current form. Function cursor.field.name Format cursor.field.name(n) Factors Returns the fully-qualified field name if the function is called with an argument. Example cursor.field.name() returns number. cursor.field.name(1) returns header,number. RAD function: cursor.field.readonly A RAD function that returns true if the cursor is in a read-only field and false if the cursor is in a field that is not read-only. Function cursor.field.readonly Format cursor.field.readonly() RAD function: cursor.line A RAD function that returns the line number where the cursor was positioned when the user performed an action such as clicking Fill or Find, or double-clicking an item in a QBE list. If the action opens a new form, cursor.line returns the focus on the pop-up form. Function Page 91 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference cursor.line Format cursor.line(n) Factors l l $l=cursor.line() = the numeric value of the line where the cursor was positioned. $l=cursor.line(1) = the numeric value of the index of the array or structure where the cursor was last located, including consideration for vertical scrolling. If the cursor is in an array input field, $l contains the numeric value of the index of the array in which the cursor is positioned. If the cursor is not in an array input field, $l contains the numeric value, relative to the format in which the cursor is positioned, including accounting for vertical scrolling, which may be greater than the client's screen length. RAD function: date A RAD function that returns the date portion of a date and time variable. Function date Format date($date.time.variable) Factors l The date portion of a date and time value is midnight of that day, for example the time is 00:00:00. The function uses the local time zone to determine the date. The argument can be any absolute date and time value, or an absolute time, including tod. l Example $date.opened=date($date.time.variable) Where the $date.time.variable contains the current date and time or another valid date and time value. For example, if $date.time.variable = '08/01/08 10:10:10,' then $date.opened = '08/01/08 00:00:00' . RAD function: day A RAD function that returns the day of month for a date, regardless of the date format. Function day Format day=day($date) Where the value of $date is a date and time value. Factors Although the set.timezone function affects the way a date is presented, the day function always extracts the proper day value. Page 92 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference Example $mday=day(‘2/15/08’) After execution, the value of $mday is 15. RAD function: dayofweek A RAD function that returns the day of the week for a date, regardless of the date format. The dayofweek function returns 1-7, where 1 is Monday, 2 is Tuesday, 3 is Wednesday, 4 is Thursday, 5 is Friday, 6 is Saturday, and 7 is Sunday. Function dayofweek Format day=dayofweek($date) Where the value of $date is a date and time value. Factors The set.timezone function affects the way a date is presented, whereas the dayofweek function always extracts the proper day of week value. Examples From the RAD debugger type: d dayofweek(‘11/06/09’) This expression displays the day of the week of a specific date. (The command ’d’ stands for ’display.’) In this example, the value of dayofweek is 5 or Friday. From the RAD debugger type: x $Ltoday=dayofweek(‘11/06/09’) This expression executes the function. (The command ’x’ stands for ’execute.’) In this example, you want to assign the value to a variable. RAD function: dayofyear A RAD function that returns the day of year for a date, regardless of the date format. Function dayofyear Format $yday=dayofyear($date) Where: the $date variable is a date and time value. Example $yday=dayofyear('2/15/08') After execution, the value of $yday is 46 Page 93 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference RAD function: delete A RAD function that deletes one or more elements in an array and returns the updated array. Function delete Format delete(array, element number, [number of elements]) Where the array variable is the array, the element number is the index number of the first element to delete, and the [number of elements] is the number of elements to delete. The number of elements to delete is optional. The default value is one (1). Example delete({1,2,3},2) Returns {1,3} delete({1,2,3},2,2) Returns {1} RAD function: denull A RAD function that compresses an array by removing all trailing NULL entries and returns the compressed array. Function denull Format denull(array) Factors l l If the array contains a NULL entry in the middle of the array, that entry is not removed. Using denull on an empty array of structures converts the array of structures to a simple array. Note: Always test for NULL first. l Displaying arrays extends the length of the array to accommodate window size. Tip: It is a good practice to denull arrays before records are added or updated. You can use denull(contents()) to accomplish this, but you should first ensure that the contents do not include any empty array of structures or they will be converted to simple arrays. Example denull({1,2,3,,}) Returns {1,2,3}. Page 94 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference denull({1,,2,,}) Returns {1,,2}. RAD function: descriptor A RAD function that returns the database dictionary descriptor structure for the table specified. Function descriptor Format descriptor($filename) Parameters The $filename variable is used for the table whose descriptor structure you are requesting. RAD function: evaluate Evaluates an operator and may return a value. Function evaluate Format $e = evaluate($x) Factors l l An operator is created using the parse function. The evaluate function is also valuable when the statement to be evaluated is contained in a Service Manager field that is not qualified once the application is compiled. The parse flag is used to parse data in a form, which in turn converts the data to an operator (data type 10). Although an lvalue is always required, a value is not always assigned to the lvalue. l l Example $x=parse(“1+1”,1) returns two (2). $x=evaluate($x) RAD function: evaluate.query A RAD function that evaluates a query against a record. Both are passed as function parameters. Function evaluate.query() Format $L.rc=evaluate.query( <query>, <file variable> ) Function returns true - if the record matches the query false - if it does not match the query Page 95 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference unkown - if a comparison in the query encountered a NULL value or a field was referenced in the query that does not exist in the record null - if the function was called incorrectly Parameters The following parameters are valid for the evaluate.query function: Parameter query"<query>" Data type operator or character record Description Can be a previously parsed query or a string containing a query Must be a valid file variable record"<file variable>" Examples $x = evaluate.query( "true", $L.file ) This example returns TRUE for any valid file variable. $query = parse( "contact.name # \"S\" ", 4 ) $y = evaluate.query( $query, $L.filed ) This example returns TRUE only for contacts records that start with "S" and FALSE for every other contacts record. RAD function: exists A RAD function that checks for the existence of a field in a table. Function exists Format exists(<field name>, $file) Factors l l l l Returns true or false. Replaces the index(<field.name>, descriptor($file))>0 expression. The $file variable must be of data type 6. Any other data type returns false. The first parameter can be either a character type variable or a quoted string. Example $L.return=exists(“schedule.id”, $L.schedule) The value of $L.return is true if $L.schedule is a file variable containing a schedule record. RAD function: fduplicate A RAD function that copies an entire file variable from one record to another. Function Page 96 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference fduplicate Format fduplicate($target, $source) Factors l l l The system does not recognize fduplicate alone. Returns a Boolean value: true if it is successful, and false if it fails. Used primarily in RAD process panels and in Format Control. Example $L.void=fduplicate($file0, $file) Creates $file0, an independent copy of $file. RAD function: filename A RAD function that returns the name of the file for the specified file variable. Function filename Format filename($filename) Parameters The $filename variable has been bound to a database file with the rinit command panel. Factors This function is useful when executing a common subroutine that has been passed a file variable. This function allows you to determine the file name because the local variable contains data from an unknown file. Example filename($file) returns the dbdict name. RAD function: frestore A RAD function that restores all the fields in a file to their original values from the database. Function frestore Format frestore($file) Where: The $file variable is the file for which you want to restore the fields to their original values. Factors l l Use only with a Windows client. This function returns no value, it is not necessary to use it in an assignment statement. Example frestore($file) If the $file variable is initialized and a record is selected, changes are made to the contents of Page 97 of 396 HP Service Manager (9.30) form.base.name($form.Programming Guide Chapter 5: System Language reference the $filevariable in memory. All normal format processing occurs.name=get. After execution.form. including input and output routines. which is the state stored in the database. The output produced is either fixed or variable length.variable is a variable containing a record or records to process. Function genout Format genout($file.w (Web) file extension. RAD function: genout A RAD function that generates a string containing the contents of a record using a specified form.form.name=“operator. “Printer:sysprint Email:joes@hp. a date can be converted from 02/28/05 00:00:00to February 28. but the updates are not yet written to the database.form.name Format $base.form.name($form.name variable is the name of format to be used. $format. 2005.form.form.com”} RAD function: get.30) .base.name) Example 2: Page 98 of 396 HP Service Manager (9. without the .name is operator.name) Parameters The $file. the result is the same after execution: $base. Examples $output=genout($operator.base. Factors l l Spaces are substituted for NULL in fixed length output.variable. “operator. the $file variable is restored to the original value.name) Parameters $form.name A RAD function that returns the base name of a form. Example 1: $form.base. Function get.view”) $output={“Name:joes Full Name:Joe Smith”. The $format.name Examples In each of the following examples.name=get.g” $base. For example. Data can therefore be automatically reformatted or manipulated as part of the function.g (GUI) or . fmt=get.fmt is one (1).action() Page 99 of 396 HP Service Manager (9.base.form.name=get.name($form. Function get.dateformat A RAD function that returns the date format.action Description A RAD function that returns the activated action on a node in the graph diagram.name) RAD function: get.dateformat() After execution for a typical user in the United States. Function get.graph.graph.graphaction = get. by number: l l l l l l 1 = mm/dd/yy 2 = dd/mm/yy 3 = yy/mm/dd 4 = mm/dd/yyyy 5 = dd/mm/yyyy 6 = yyyy/mm/dd Example $date.name=get.dateformat Format $date.base.name) Example 4: $form.dateformat() Factors Date formats represented.form. represented by a number.name($form.30) .name=“operator” $base.name=“operator. RAD function: get.base.fmt=get.form.Programming Guide Chapter 5: System Language reference $form.graph.form.form.name) Example 3: $form. the value of $date.form.name=get.name=“operator.name($form.action() Example $L.a” $base. used by your operator ID.w” $base. Function get. Page 100 of 396 HP Service Manager (9. Function get. the value of $owner is "falcon".owner Format $owner= get.graph.lock.id() RAD function: get.Programming Guide Chapter 5: System Language reference RAD function: get.lock.IM1017".graphnodeid = get.graphtarget = get.id Description A RAD function that returns the value of the graph ID for the expand action on a node in the graph diagram. Function get. The function returns the name of the user who currently has the resource locked.graph.graphid = get.lock.target() Example $L.IM1017" $owner=get. Function get. By viewing the Lock Resource Status display one can determine that the name of the associated resource is "probsummary.graph.owner($lock) After execution.id() Example $L.id() RAD function: get.target() RAD function: get.id Description A RAD function that returns the value of the node ID for the expand action on a node in the graph diagram.30) .graph.id() Example $L.graph. To verify the owner from any other application: $lock="probsummary.owner("locked resource") Example Assume the user "falcon" is actively updating Incident IM1017.graphnode.target Description A RAD function that returns the target for an activated action on a node in the graph diagram.graphnode.owner A RAD function that returns the owner of a resource (lock).graph.graphnode.lock. timezoneoffset() Example $tzoffset=get. the value of $bool is true.uid Format $uid=get.uid() Example $uid=get. $uid contains a unique value such as 41ed9bf40032329a03039158. RAD function: get.uid() After execution.timezoneoffset() After execution for a Pacific Standard Time (PST) time zone user. Function get.30) . Function gui Format $bool=gui() Example $bool=gui() After execution in GUI mode. Page 101 of 396 HP Service Manager (9. NULL is the return.timezoneoffset A RAD function that returns the absolute time difference between Greenwich Mean Time (GMT) and the time zone of the operator. Function get. Each successive call returns a value greater than the previous value.timezoneoffset Format $tzoffset=get.Programming Guide Chapter 5: System Language reference Note: This function is primarily intended for internal use as it requires specific knowledge of the underlying resource names associated with a specific action. If the target value is not in the array or string. RAD function: get.uid A RAD function that returns a 24-character identifier that is unique to an installation of Service Manager. After execution in text mode. RAD function: index A RAD function that returns the index or position number for the value of a specific element in an array or a character in a string. the value of the $tzoffset variable is -08:00:00. value of $bool is false. RAD function: gui A RAD function that determines whether or not a process is running in GUI mode. str(field)). regardless of the data type in the array.description) > 0: n On a case insensitive database.{1. the target variable must exactly match the structure or array.number” in the 'field' field of the format table.{1. starting position #) Parameters The target value variable is the value you are searching for in the array or string. n l l On a case sensitive database. l When you use the index() function in a RAD or JavaScript expression and not within a query. returns 0. You can use the index function to search for any value by converting both the value and the search variable to the same type. Example index(1.Programming Guide Chapter 5: System Language reference Function index Format index(target value. the query returns all records where the brief.2. {“WINDOWS SERVER". if you use the Expert Search option on the Incident Management search screen.3}) returns two (2) index(1. If the array is composed of structures or of arrays. and search for index(“Windows Server”.2. {“WINDOWS SERVER”. if you want to search for the variable “$problem. For example.2) returns zero (0) index(2. brief.3}. the function does not allow selecting a field from a structure. For an example. Page 102 of 396 HP Service Manager (9. HP Service Manager evaluates it case sensitively (regardless of the database setting). “windows server”}).2. When you use the index() function in a query.description field contains “windows server” or “WINDOWS SERVER” or “Windows SERVER”. n The expression index(“Windows Server”. For example. HP Service Manager evaluates the function based on database case sensitivity. The index function searches for the variable “$problem.3}) returns one (1) index(2.{1. “windows Server”}).30) . and so on. the query only returns records where the brief.2. Factors l l The index() function operates identically for arrays. returns 2. consider the following RAD or JavaScript expressions: n The expression index(“Windows Server”.number” on all forms. The $variable variable is the name of the variable to be searched. “Windows Server”. $variable. The default value is one (1). The starting position # variable is the index in the array or position in the string where the search will begin. For example.3}.number”.{1. you could pass the following query to the select panel: index(“$problem.description field contains exactly “Windows Server”.2) returns two (2) RAD function: insert A RAD function that returns an array with one or more inserted elements. the element is inserted at the end of the array. "d". "b". . This is an optional parameter. set the value of the $denull parameter to false. "e". "c". $a={"a". . "a". 0. "f". "b". 1. $position[. Action desired Insert an element at the beginning of an array. 1. $denull]]]]) Parameters l l The $array parameter is the array into which an element is inserted.Programming Guide Chapter 5: System Language reference Function insert Format insert( $array[. The $position parameter is the position of the first inserted element. "b". This is an optional parameter. "c". "d"} $a=insert($a. The default value is zero (0). The $denull parameter is a logical value that determines whether or not the array should be denulled before inserting elements. If the value is zero (0). "d"} Insert an element in the middle of an array. 0. "b". "z") Where: The value of $a is {"a". $a=insert( $a. $value[. "e". The default value is one (1). "b". . "b". This is an optional parameter. "c". $number[. "d"} $a=insert($a. this function will return without changing the array. The $number parameter is the number of elements to insert. } Where: The value of $a is {"a". To insert an element in the middle of an array: $a={"a". The $value parameter is a value to insert into the new elements. "z") . "d"} $a=insert($a. To avoid this. "c". this function automatically denulls the array before inserting new elements in any position. "z"} The array is denulled. "d"} Insert an element at the end of an array. . "b". $a={"a". This is an optional parameter. Example and result $a={"a".30) . "c". The default value is NULL. 1. "z") Where: The value of $a is {"a". "c". . "z"} Page 103 of 396 HP Service Manager (9. . "z". "f". "z") Where: The value of $a is {"z". "b". 1. Examples The following examples show a desired result and the syntax used to achieve that result. If the value is zero (0). 1. l l l Factors If the source array has NULL elements at the end. The default value is true. 3. . .Programming Guide Chapter 5: System Language reference To avoid denulling the array.function" . "e". "e". "f". } Where: The value of $a is {"a". . $a={"a". "f". "b".30) .. "f"} RAD function: iscurrent A RAD function that determines if the record that you are working with is identical to the version in the database. . arg1 . Page 104 of 396 HP Service Manager (9. arg2. . . 0. 2."z"} The array is (again) denulled. . Function iscurrent Format $Boolean=iscurrent($file. } Where: The value of $a is {"a". $a={"a". . as shown in the following examples: "script. – . Arguments are not enclosed in quotes or double quotes and can be RAD expressions. . $a=insert( $a. "e". "b". The arguments passed to JavaScript.. argN Varies with each argument The required arguments depend upon the requirements of the script you call. . A value of true or false is returned. 1. . arg2. . . . "e". "f". "z". This parameter must be enclosed in double quotes. $a=insert( $a. "z". .function" String arg1. "b". Function jscall Format jscall( "script.variable) RAD function: jscall A RAD function that enables you to invoke JavaScript from within RAD. "z") . 0) . . 1. argN ) Parameters The following parameters are valid for the jscall function: Parameter Data type Required Yes Description Refers to a script in the ScriptLibrary and a particular function within the script. . . "b". You can pass an infinite number of arguments. NEW=0 RAD function: lioption This RAD function indicates whether a given input value is a licensed option on the current system. Function lioption Format lioption(input value) Parameters Parameters for this function are as follows: Input value Asset Contract Management Change Management Computer Telephony Configuration Management Contract Management Desktop Administration Incident Management IR Expert Knowledge Management Knowledge Management ESS Problem Management RAD Compiler Request Management SCAuto/SDK Unix SCAuto/SDK Windows Description Authority to use Asset Contract Management application Authority to use Change Management application Authority to use Computer Telephony Interface (CTI) Authority to use Configuration Management application Authority to use Contract Management application Authority to use Desktop Administration application Authority to use Incident Management application Authority to use IR Expert Authority to use Knowledge Management application Authority to use Employee Self-Service with the Knowledge Management application Authority to use Problem Management application Authority to use RAD Compiler Authority to use Request Management application Authority to use SC Automate Adapters Unix SDK Authority to use SC Automate Adapters Windows SDK Page 105 of 396 HP Service Manager (9.30) .OLD — OR — level in $L.Programming Guide Chapter 5: System Language reference city in $L. The function returns a false value if the input value is not part of the system license.30) .Programming Guide Chapter 5: System Language reference SCAuto/HP Network Node Manager SCAuto/Netview (AIX/NT) SCAuto/SunNet SCAuto/SPECTRUM SCAuto/HP Operations (ITO/VPO) SCAuto/UNIXmail SCAuto/MAPImail SCAuto/Lotus Notes SCAuto/Fax Unix SCAuto/Pager Unix SCAuto/Fax Windows SCAuto/Pager Windows SCAuto/Netview OS/390 SCAuto/TBSM SCAuto/Unicenter AMO SCAuto/Unicenter TNG SCAuto/Tivoli SCAuto/Tally NetCensus SCAuto/Remedy ARS SCAuto/ERP Connection Scheduled Maintenance Self-Service Ticketing Service Catalog Service Desk SLA SOAP API Authority to use SC Automate Adapters OpenView Authority to use SC Automate Adapters AIX Netview Authority to use SC Automate Adapters SunNet Authority to use SC Automate Adapters SPECTRUM Authority to use SC Automate Adapters IT Ops Authority to use SC Automate Adapters SMTP or UNIX mail Authority to use SC Automate Adapters MAPI mail Authority to use SC Automate Adapters Lotus Notes Authority to use SC Automate Adapters Unix Fax Authority to use SC Automate Adapters Unix Pager Authority to use SC Automate Adapters Windows Fax Authority to use SC Automate Adapters Windows Pager Authority to use SC Automate Adapters OS/390 Netview Authority to use SC Automate Adapters TBSM Authority to use SC Automate Adapters Unicenter Authority to use SC Automate Adapters CA TNG Authority to use SC Automate Adapters Tivoli Authority to use SC Automate Adapters Tally NetCensus Authority to use SC Automate Adapters Remedy ARS Authority to use SC Automate Adapters ERP Connection Authority to use Scheduled Maintenance application Authority to use Self-Service Ticketing Authority to use Service Catalog application Authority to use Service Desk application Authority to use Service Level Agreements application Authority to publish Service Manager data as Web services Factors The function returns a true value if the input value is part of the system license. Page 106 of 396 HP Service Manager (9. Function locks Format locks() Factors Page 107 of 396 HP Service Manager (9. Strings return the number of characters..30) . but be careful when denulling arrays of structures.3.}) returns 7 lng(denull({1. NULL or otherwise.. Remember to denull arrays to get the correct number of elements..})) returns 3 RAD function: locks A RAD function that returns an array of structures containing information about the locks used to lock a database for an update or the locks set by RAD applications using a locked command panel.3}) returns 3 lng({1. Examples lng("1234567890") returns 10 lng({1.. structure or a character string..2. Action desired Check for authorization to use Change Management Check for authorization to publish Web services Syntax $licensecheck=lioption("Change Management") $licensecheck=lioption("SOAP API") RAD function: lng A RAD function that returns the number of elements in an array or structure and the number of characters in a string. Function lng Format lng($variable) Where $variable is the array.Programming Guide Chapter 5: System Language reference Examples The following table describes a desired action and the syntax used to initiate the action. Factors l l l l The $variable must be an array.3. Structures return the number of fields.. or string. Arrays return the number of elements.2.2. structure. 30) . 0. 0.main”. true. “Windows 32”. Function logon Format logon() Factors This function does not return a value. 20212. true. “falcon”. false]}} RAD function: logoff A RAD function that logs off the current user and terminates the session. Function logoff Format logoff() Factors This function does not return a value.Programming Guide Chapter 5: System Language reference Each element of the array contains: l l l l l l l l l lock time process id terminal id operator name resource name (name of the lock) number exclusive locked breakable Example locks() Returns the following: {{[‘12/26/96 16:01:07’. true. Page 108 of 396 HP Service Manager (9. It executes a function. false. 22699. “agent:marquee”. “SYSTEM”. RAD function: logon A RAD function that logs a user on. It executes a function. “marquee”. false]} {[“01/02/97 11:26:08”. “AG/pm. 3 sets the security roles for the tables defined in the scFolderAccess file. element3. To establish the mandanten security for the user. if a new ticket is being opened and the client (customer) for the ticket is known. "Company B" and "Company C". . 1.{"cm3".) — OR — max($variable) Where: The $variable variable is an array or a list of values. l The value of the string variable is the mandanten value.string) Where: The n equals 0..30) . Example usage In Service Manager the out-of-box system has three scsecurity group records: "Company A". "device"}) Note: This fails if the string value does not match the values currently established.Programming Guide Chapter 5: System Language reference RAD function: mandant The Service Manager mandanten feature protects records of multiple clients by logically separating a shared database. the RAD could call the following: mandant(2. 2 links the current user to the set of records in the scsecuritygroup file that matches the array of security IDs. element2. RAD function: max A RAD function that returns the largest value in a list of values or arrays. or 3 Parameters l l l 0 represents a request for a subset of the current mandanten values. {"Company A"}) or mandant(2.{"Company A". Clients see only the data they are allowed to share. The mandant RAD function allows an application to create a subset of the current mandanten values. The RAD calls the mandant function with 3 to set the security roles for the given tables. 2. For example.. "ADMIN". "Company B"}) Security roles are implemented in the scFolderAccess table. then a subset of the mandanten values can be created to show only the assignments that are valid for that client. 1 represents a request to restore the original mandanten values. Function mandant Format mandant(n. mandant(3. Function max Format max(element1. The following example sets the security role of ADMIN for two tables. as defined in the scFolderAccess file. Factors Page 109 of 396 HP Service Manager (9. The log is implemented as a wraparound cache of the n most recent messages. excludes informational and action messages. Retrieve array of logged informational messages in last displayed order. $function_parameter) Parameters Parameters for this function are as follows: Function # Parameters Action 0 1 2 3 4 5 0 — 500 None None None None 0 Open message log with 0 to 500 entries.10) returns 73 max(1.24.Programming Guide Chapter 5: System Language reference l l The max function returns the maximum value of either times or numbers. Stop logging and clear the log. the system evaluates all of the elements in the array as if they were individual values. Close the log and recover memory. An attempt to use an array of strings as a parameter results in a segmentation fault. 5 1 5 2 5 3 Factors The following table outlines the proper order for each action related to this function and the corresponding function number. The log is not cleared. which causes the application to exit in error. Retrieve array of logged action messages in last displayed order. Retrieves array of error messages in last displayed order. If you include an array in the list of elements. Page 110 of 396 HP Service Manager (9.30) . excludes error and action messages. The log is not cleared.3) returns four (4) RAD function: messages A RAD function that provides logging functions for use in the memory message log. Start or resume logging. Stop logging. Function messages Format messages($function_number. l Example max(17.4}. The log is not cleared. excludes error and informational messages.35. Retrieve array of all log entries in most recently displayed order. The log is not cleared.73.{2.3. You cannot directly access message logs that are using other tasks. A maximum of 500 logged messages is supported..30) ... Clear log. Function Function zero (0) Function one (1) .1) Page 111 of 396 HP Service Manager (9.. Notes: l l l Function two (2) Function five (5) Function four (4) A user task (the sm process) can have only one private message log at a time. Close log. Retrieve log..run application N/A .run application N/A Stop logging. Retrieve log. Start logging. Syntax $throwaway=messages(0. Close log.200) $throwaway=messages(1) $throwaway=messages(2) $throwaway=messages(3) $throwaway=messages(4) $array=messages(5.run application N/A .. Start logging Stop logging...run application N/A Stop logging. $array=messages(5. start logging Function two (2) Function five (5) Function three (3) Function one (1) .Programming Guide Chapter 5: System Language reference Action Open log. Examples The following table describes a desired action and the syntax used to initiate the action. Clear log..run application N/A .. Action desired Open a log for 200 messages.0) Retrieve all logged informational messages. Retrieve all logged messages. Use modtime(currec()) to return the last modified date and time for any record. If you include an array in the list of elements. The modtime function is not updated on clients when the records are updated on the server until after the records are selected again. element2.) — OR — min($variable) Where: The $variable variable is an array or a list of values.3..2) $array=messages(5.2. Factors l l The min function returns the minimum value of either times or numbers.}.35.3) RAD function: min A RAD function that returns the smallest element in a list of values or arrays. element3..30) . l Examples modtime($file) Returns 1/10/96 12:15:17 Page 112 of 396 HP Service Manager (9. Retrieve all logged error messages. An attempt to use an array of strings as a parameter results in a segmentation fault. $array=messages(5.24.Programming Guide Chapter 5: System Language reference Retrieve all logged action messages. Function min Format min(element1.2) returns one (1) RAD function: modtime A RAD function that returns the last modified date and time of a record. You can also use this variation in queries to retrieve all records modified after a specified point in time. Function modtime Format modtime($file) Factors l l Use this function to determine if a record has been modified before or after a specified time. Service Manager evaluates all elements in the array as individual values. . which will cause the application to exit in error. l Example min(17.{1.73.10) returns 10 min(4. "IM10007". 3. the value of $x is set to the selected field contents.selection("fieldcontents") A RAD function that returns the contents of the field associated with the multiselection. For example. 5. Function month Format $ymonth=month($date) Parameters Where: The $date variable is the date and time value Example $ymonth=month(`2/15/96') After execution. Field contents are only returned if the associated column name is set using the Forms Designer property "Selection Field. Click OK to save your changes. The form opens. Click OK to see what the form will look like in the Windows client. regardless of the date format. type the name of the column on the table (for example. Click Design to open design mode. Page 113 of 396 HP Service Manager (9. type probsummary. "IM10006".Programming Guide Chapter 5: System Language reference modtime(currec)>tod( ). RAD function: month A RAD function that returns the month of year for a specified date.qbe. In the Form field. Function multiselect. "IM10012"}. RAD function: multiselect. For example {"IM10003". Click on the table object. In the Selection Field property.selection("fieldcontents") Example $x=multiselect. 8. Click Tailoring > Forms Designer. "IM10008".g and click Search. Log on as a System Administrator.selection("fieldcontents") Format $info=multiselect." To set the associated column name using the Forms Designer "Selection Field" property: 1. "IM10010". 7. type the form name. 6. type number). 2. the value of $ymonth is two (2).selection("fieldcontents") After execution. 4.30) .'08:00:00' Selects all records in a file that were added or updated in the last eight hours. 22. Click Tailoring > Forms Designer.g and click Search. In the Form field. type number). Click OK to see what the form will look like in the Windows client.selection("rows") Example $x=multiselect. For example {2. Click on the table object. 3. 4.selection("rows") A RAD function that returns an array of row numbers that were selected. Note: The field name is only returned if the associated column name is set using the Forms Designer property "Selection Field. Function multiselect. 2.selection("fieldname") Format $info=multiselect. type the form name. Page 114 of 396 HP Service Manager (9. 3. the value of $x is set to the column name (for example.Programming Guide Chapter 5: System Language reference Note: Field contents are only returned if the associated column name is set using the Forms Designer property "Selection Field. 7.selection("rows") Format $info=multiselect. For example. 30}. The form opens."number"). Click OK to save your changes. type the name of the column on the table (for example. the value of $x is set to the selected rows." RAD function: multiselect. In the Selection Field property. 8. 5.qbe.selection("rows") After execution." To set the associated column name using the Forms Designer "Selection Field" property: 1. Log on as a System Administrator. type probsummary.selection("fieldname") Example $x=multiselect. Function multiselect. The associated column name is set using the Forms Designer property "Selection Field." RAD function: multiselect. 23. 6. Click Design to open design mode.30) .selection("fieldname") After execution.selection("fieldname") A RAD function that returns the field name of the column associated with the multiselection. 7. RAD function: multiselect. Function multiselect.selection("tablename") After execution. Use the null function to determine whether or not the value of a field or variable is null.selection("tablename") A RAD function that returns the Table ID associated with the multiselection.Programming Guide Chapter 5: System Language reference RAD function: multiselect. RAD function: multiselect.selection("selected". Table0. For example 6.30) .variable) Example $x=multiselect.selection("selections") After execution.selection("selected". Function multiselect. RAD function: null A RAD function that returns a value of true if the parameter is NULL or is comprised of a compound data type consisting of all NULL values.selection("selected".selection("selections") A RAD function that returns the number of rows selected.$file. Note: The null function is different that the reserved word. the value of $x is set to the selected Table ID. NULL.selection("tablename") Example $x=multiselect. Function null Format null(value) Factors Page 115 of 396 HP Service Manager (9. the value of $x is set to the number of selected rows.file.file) After execution. Function multiselect.selection("tablename") Format $info=multiselect.selection("selections") Example $x=multiselect.selection("selections") Format $info=multiselect.variable) Format $info=multiselect. For example.selection("selected") A RAD function that returns true or false if the provided variable has multiple records selected.$L. the value of $x is set to true or false. 30) . Examples nullsub(1.value2) Where: The value2 variable is the value to return if value1 is null. Function operator Format operator() Factors The operator() value is set to the value of the login name in the operator record at the time of login."test") returns test. nullsub(NULL.}) returns false null({{}.2) returns two (2). The reserved word NULL only handles primitive data types. $a=NULL $a=nullsub($a. Function nullsub Format nullsub(value1. A zero (0) is not null.Programming Guide Chapter 5: System Language reference l l l The null function can handle compound data types.2) returns one (1). This function applies itself recursively to nested elements. l l l l Examples null(1) returns false null(NULL) returns true null({}) returns true null({1. The value 00:00 is not null. The operator function is also used to set the operator name.}) returns true RAD function: nullsub A RAD function that substitutes a null value with the second value specified. Examples $a = operator() operator() = $a Page 116 of 396 HP Service Manager (9. An empty string. An array or structure is null if it contains all null elements. such as (" ") is not null. RAD function: operator A RAD function that sets and returns the name of the current operator ID. A value of unknown in a Boolean field is not null. 1 = first option key. For example. RAD function: perf A RAD function that evaluates system performance and then logs this information in Service Manager's systemperform and systemtotals tables. Function parse Format parse(string. 0 = Enter. and a value of negative one (-1) indicates failure.type) Factors l l An operator can be an expression. Examples $x=parse("1+1". such as type<11. Function perf Page 117 of 396 HP Service Manager (9. the parse property automatically parses the data entered. such as type=11. A value of zero (0) indicates success. l l Example option() returns 10 RAD function: parse Parses a string into an operator. To avoid conflicts. Clicking a button returns the number defined in the Button ID property. Function option Format option() Factors l l The Enter key returns a value of zero (0).1) Evaluate($x) returns two (2) $x=parse("$x=1". Clicking an item in the More menu returns the GUI option number associated with this option in the displayoption table. or a statement. set a variable to option() when the first panel is accessed.11) Evaluate($x) causes the value of $x to be set to one (1).Programming Guide Chapter 5: System Language reference RAD function: option A RAD function that returns the number of the last interrupt key. Use caution when option() is a criteria for a decision or process panel that can be accessed from several paths. 2 = second option key.30) . When enabled on forms. file. regardless of capture status. Delete all records in the systemtotals and systemperform files. or the default printer specified in the operator record for the user.Programming Guide Chapter 5: System Language reference Format perf(n) Where: The value of n is the number that corresponds to the option you select. Function policyread Format $L.30) . the login application is executed. When an operator logs on. fieldsetting) Parameters Page 118 of 396 HP Service Manager (9. Nothing is removed before new records are written to the systemtotals and systemperform files. 2 3 4 Example perf(1) Returns zero (0) RAD function: printer A RAD function that sets and returns the value of the currently logged-on printer. fieldname. Parameters The following table shows the parameters used with the perf function: Option Result 1 Delete records in the systemtotals and systemperform files where capture=false before writing new information to disk. Add records and do not delete. Maintenance of these files is typically the responsibility of the RAD programmer. Delete records in the systemtotals and systemperform files where capture=false and do not write information to disk. assigning printer() to be either the printer specified by the user at login.returnvalue = policyread( $L. Example $a = printer() printer() = $a RAD function: policyread A RAD function that reads the data policy from a datadict table. Function printer Format printer() Factors This function is most often used to set the current printer. change). $L.file The file handle of the table for which the data policy information is to be read from the database. fieldname The name of the field in the specified table for which the data policy information is to be read from the database. a boolean. etc.30) . This is the value in the Name field in the datadict record. and "validations".) are not supported. "profile. "matchfiles". "readonly". "globallist". or null. "profile.change". Valid field settings are: "invisible". such as the operator table.functions. var operatorFile = new SCFile( "operator" ). "mandatory" ).change).returnvalue The policy value returned after it is read from the database. This one of the fields on Field Settings tab of the datadict record. merge files. rteReturn = system. Example 1 This example demonstrates how you could use a JavaScript to access the data policy on a simple file. this function returns a valid value or null. rteReturn = system. print( "DataPolicy on (file:operator. field:invisible) " + rteReturn ). as Page 119 of 396 HP Service Manager (9.Programming Guide Chapter 5: System Language reference The following parameters are valid for the policyread function: Parameter Description $L. Note: Other kinds of tables (adhoc sql. "profile. print( "DataPolicy on (file:operator. field:readonly) " + rteReturn ). fieldname:profile. "invisible" ). the server will throw an error message. as defined in (file:datadict.policyread( operatorFile . "defaults". // Access DataPolicy definition on operator file. It can be a join table or a normal table. "encrypt".change). as defined in (file:datadict. print( "DataPolicy on (file:operator. Factors If the fieldsetting is not in the list of Field Settings in the datadict table. fieldname:profile. This is the value in the Field Name field in the datadict record. "readonly" ).change". In any other case.functions.policyread( operatorFile . "matchfields".policyread( operatorFile . "mandatory". var rteReturn.functions. rteReturn = system. "avail". It can be a string.change". "captions". fieldname:profile. fieldsetting The field setting on the specified field for which the data policy information is to be read from the database. such as a join of the incidents and contacts tables. "captions" ). Page 120 of 396 HP Service Manager (9. fieldname:profile.change). print( "DataPolicy on (file:operator. "profile. "profile. as defined in (file:datadict. "profile. "matchfields" ). "globallist" ).functions.30) . "matchfiles" ).policyread( operatorFile . fieldname:profile. fieldname:profile. rteReturn = system.policyread( operatorFile . as defined in (file:datadict. print( "DataPolicy on (file:operator. rteReturn = system. "profile.policyread( operatorFile . rteReturn = system.policyread( operatorFile . as defined in (file:datadict. print( "DataPolicy on (file:operator. rteReturn = system. fieldname:profile. as defined in (file:datadict.functions. "profile.functions. as defined in (file:datadict. fieldname:profile. "profile.change).change". field:encrypt) " + rteReturn ). // Access DataPolicy definitions on join file inccontacts (incidents and contacts) var incident_contacts_file = new SCFile( "inccontacts" ).change". field:avail) " + rteReturn ). field:matchfiles) " + rteReturn ).change).change".Programming Guide Chapter 5: System Language reference defined in (file:datadict.policyread( operatorFile . field:validations) " + rteReturn ). field:globallist) " + rteReturn ).functions. fieldname:profile. rteReturn = system. print( "DataPolicy on (file:operator. "encrypt" ). "avail" ). field:defaults) " + rteReturn ).change". print( "DataPolicy on (file:operator. as defined in (file:datadict. rteReturn = system. as defined in (file:datadict.change". "profile.change). field:mandatory) " + rteReturn ).policyread( operatorFile .change).policyread( operatorFile .functions.change". "validations" ). as defined in (file:datadict. print( "DataPolicy on (file:operator.change". fieldname:profile.functions.change).functions. field:matchfields) " + rteReturn ). "profile. "defaults" ).policyread( operatorFile .change". rteReturn = system. rteReturn = system. print( "DataPolicy on (file:operator. Example 2 This example demonstrates how you could use a JavaScript to access the data policy on a complex file.change). print( "DataPolicy on (file:operator. field:captions) " + rteReturn ). fieldname:profile.change).functions. and datadata field readonly rteReturn = system. print( "DataPolicy on (joinfile:inccontacts.incidents. "readonly" ). // Access policy definition on file(incidents) and field(phone). field:phone). as defined in(file:datadict. field:defaults)" + rteReturn ). as defined in(file:datadict. print( "DataPolicy on (joinfile:inccontacts. " file.policyread( incident_contacts_file. print( "DataPolicy on (joinfile:inccontacts. field:phone). field:defaults)" + rteReturn ). field:readonly)" + rteReturn ).phone".30) . " file. subfile:incidents.incidents. // Access policy definition on file(contacts) and field(city) and datadict field defaults rteReturn = system. " file. as defined in(file:datadict.functions. Function processes Format processes(s) Factors Each element of the array contains the following information: l l l l l l l login time session id device name user name idle time process id thread id Page 121 of 396 HP Service Manager (9. subfile:incidents. field:city).policyread( incident_contacts_file. "defaults" ).city".contacts.functions. subfile:contacts.Programming Guide Chapter 5: System Language reference var rteReturn.phone". "defaults" ). // Access policy definition on file(incidents) and field(phone) and datadict field defaults rteReturn = system.policyread( incident_contacts_file. RAD function: processes A RAD function that returns an array describing all processes.functions. "15.173"]}} RAD function: prof A RAD function that returns system performance statistics while checking the system resources used by an application.Programming Guide Chapter 5: System Language reference l l host name ip address The argument of s determines the types of processes to be returned: S null ALL SYSTEM USER ACTIVE Type of process All All System (terminal="SYSTEM") User (not System) Active INACTIVE Inactive (not active) Example processes("ACTIVE") returns {{[‘04/06/09 11:02:22’. Returns the number of statements evaluated.163.80. 1692. This parameter is obsolete. "System. Page 122 of 396 HP Service Manager (9. "HPSD9667". Function prof Format prof(n) Where: The value of n is the value for the parameter corresponding to the option you want returned.30) . Returns the memory allocated. ‘00:00:00’. 5164. 11. This parameter is obsolete. Parameters The following parameters are valid for the prof function: Parameter Description 1 2 3 4 5 6 Returns the user CPU time. This parameter is obsolete. "Soap-Windows Vista".Admin". does not affect the outcome of the function. Returns the user executing priority.fields={"name". $source.voide=recordcopy($source.file $target.file. Ensure that you do not copy a number field to a string. $target. Factors The recordcopy function does not check the data type. $source. This parameter is obsolete. Function recordcopy Format $L.fields Array of field names in $source.file is an operator record. The source record from which fields are copied.file="858-481-5000" $source.fields.file="falcon" phone in $source. This parameter is obsolete. or a structure to a number. This parameter is obsolete.file.30) .file.Programming Guide Chapter 5: System Language reference 7 8 9 10 11 12 13 20 21 This parameter is obsolete. $target. $target. Array of field names in $target.void= $source. "phone"} Page 123 of 396 HP Service Manager (9.fields) Parameters The following parameters are valid for the recordcopy function: Parameter $L. Example prof(5) returns (7752). RAD function: recordcopy A RAD function that copies a set of fields from one record to another record. This parameter is obsolete.file. Returns the symbol table size. $target. This parameter is obsolete.fields The target record to which fields are copied. Example If $source.file is a contacts record.file Description Syntax requirement only. Returns the stack size. name in $source. The current file. RAD function: round A RAD function that rounds up.30) . Function recordtostring Format recordtostring($string.file is 858-481-5000.file. Factors Event Services uses the caret character (^) as a default separator. "^") Where: The value of $file is a location record in which location=Advantage HQ.n) Parameters Page 124 of 396 HP Service Manager (9.Programming Guide Chapter 5: System Language reference $target. the value of contact. $file.fields) After execution. and location. in the positive direction. Function round Format round(number. $sep) Parameters The following values are valid for the recordtostring function: Parameter $string $file Description The string to which the field value is appended.name=downtown.name in $target.fields={"contact. RAD function: recordtostring A RAD function that uses the value of a field from an array and appends that value to a string. $sep A separator character.void=recordcopy($source. to the nearest specified number of decimal places.file is falcon and contact.name".file. "location. You can use the recordtostring function to build an eventout string. $file. the value of $string will contain Advantage HQ^downtown. $target. $source. $arrayofnames The array from which the field is taken.fields.phone"} $L. "contact.name"}.phone in $target. After execution. $arrayofnames. $target. Example recordtostring("". {"location". Programming Guide Chapter 5: System Language reference The following parameters are valid for the round function: Parameter Description number n The number to round. The number of decimal digits to use when rounding. This number can be any input that equates to a numeric value, such as an expression, a variable, or a number. Example $a = round(3.47,1) $a = 3.5 $a = round(3.53,1) $a = 3.5 $a = round(3.45,1) $a = 3.5 $a = round(-3.45,1) $a = -3.4 $a = round(100/30,2) $a = 3.33 $a = round(‘1/19/96 06:19:34’,0) $a = ‘1/19/96 06:20’ RAD function: same A RAD function that compares two values. If the values are equal or both values are null, the result is true; otherwise, the result is false. Function same Format same(value1,value2) Factors l l Use this function to compare arrays and structures, nulls, or empty strings. When using the same function to compare arrays or structures, preface the variable names with denull, as shown in the following example. not same(denull($filea), denull($fileb)). Examples same(1,NULL) returns false same(NULL,NULL) returns true same({},{,}) returns true same({1},{1,}) returns true same("",NULL) returns false Page 125 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference RAD function: scmsg Returns a text string matching the format of the message ID number and message class specified. The function replaces any variables in the message with the text specified in an array of values. Function scmsg Format scmsg($id, $class, $arrayof values) Parameters The following parameters are valid for the scmsg function: Parameter $id Data type Description Number The ID number of the message (message.id) from the scmessage table. String The Message class from the scmessage table. An array of substitution text for the %S variables in the message text from the scmessage table. $class $arrayofvalues Array Factors l All substitution text must be %S, which indicates that a string is used to provide the data. Each entry in the array of substitution text is examined for the type. If it is not a string type, it is converted to a string. You must create a separate record in the scmessage table for the message in each language you want to display. The $arrayofvalues defined in the scmsg function are applied to the message in the scmessage table corresponding to the language defined for the client login. l l Example scmsg("21", "cib", {"mail", "middle,caller.id", "open"}) Resulting message from the scmessage table: Built macro to %S to %S on %S. When the %S array values from the scmsg function in the example are applied, the message is displayed as: Built macro to mail to middle,caller.id on open RAD function: set.timezone A RAD function that sets the time zone, the translation from local to internal characters, and the date format. Time zone is established at either user login or process startup time. Note that not all processes that are started are user processes. At login, Service Manager determines the time zone first by the company record and then the operator record. Function Page 126 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference set.timezone Format set.timezone(servertz) Parameters The following parameter is valid for the set.timezone function: Parameter Data type Description servertz String A record in a Service Manager tzfile table. RAD function: setsort A RAD function that sorts the fields in a table. The setsort function allows for a third parameter so that it could be an array of numbers, zero or one (0 or 1). The entries in this array correspond to the entries in the name array. A "0" indicates the field will be used to sort in ascending order and a "1" indicates the field will be used to sort in descending order. A "0" or "1" can also be used to sort on all fields in ascending or descending order. Function setsort Format setsort($L.file, $L.arrayofnames, 0): ascending sort setsort($L.file, $L.arrayofnames, 1): descending sort $L.void=setsort($L.file, $L.arrayofnames, $L.arraysortorder) Example If you wanted to sort a list of contacts by name (ascending), age (ascending), and state (descending). $L.arrayofnames={"name","age","state"} $L.arraysortorder={0,0,1} $L.void=setsort{$L.contacts, $L.arrayofnames, $L.arraysortorder} RAD function: shutdown A RAD function that shuts down Service Manager from within the system. No values are returned, this function only performs an operation. Function shutdown Format shutdown() Factors Place this function on the last panel to be executed in a shutdown application. Once the function is executed, the form from which Service Manager was started displays. Page 127 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference RAD function: simple.file.load A RAD function that loads an unload file containing only data records of one file into a target file. If the target file already exists it will either drop the target file first, or return an error based on a flag passed as a parameter. This function only works with binary unload files. Text unload files are not supported. WARNING: Due to the limited capabilities of this routine and the potential loss of data, this function should not be used except by system RAD routines such as the upgrade. Function simple.file.load() Format $L.rc=simple.file.load( <unload file name>, <target file name>, <drop if already exists flag> ) Function returns true - if successful false - if there was a failure Parameters The following parameters are valid for the simple.file.load function: Data Parameter type unload file name target file name Description character Specifies where the unload file is located character Specifies the target file for this function, for example, signatures. As a safety precaution, this file name has to match the dbdict record internally stored in the unload file, or the function returns an error. logical Controls the behavior of the function if the target file already exists. If set to FALSE, the function will fail and return an error if the target file already exists in the system. If set to TRUE, the function will drop the existing target file first, before recreating it based on the dbdict record stored in the unload file. drop if already exists Example $L.result=simple.file.load( "C:\\Temp\\my_signatures.unl", "signatures", false ) This example attempts to load the unload file C:\Temp\my_signatures.unl into the signatures file. It will fail if the signatures file already exists (third parameter is false). Note: The escape characters have to be escaped. RAD function: str A RAD function that converts a data type that is not a string into a string. Function Page 128 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference str Format str(any valid expression) Parameters Any valid expression passed to the str function can be converted to a string. Examples str(1+1) returns two (2) "report run at "+ str(tod()) returns "report run at 12/10/90 10:10:00" RAD function: stradj A RAD function that ensures a string is a specific length by removing or adding trailing blanks. Function stradj Format $L.void=stradj($string, $size) Parameters The following parameters are valid for the stradj function: Parameter Data type $L.void= Not applicable String Number Description A syntax requirement only, which does not affect the outcome of the function. The string being modified. The desired size of $string. $string $size Examples $string="Hewlett-Packard" $size=15 $L.void=stradj($string, $size) After execution, the value of $string is Hewlett-Packard. $string="Hewlett-Packard" $size=10 $L.void=stradj($string, $size) After execution, the value of $string is Hewlett-Pa. RAD function: strchrcp A RAD function that replaces part of a string with copies of another string. Function strchrcp Format $L.void=strchrcp($target, $index, $source, $copies) Parameters Page 129 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference The following values are valid for the strchrcp function: Parameter Data type $L.void= Not applicable. String Number String Number Description A syntax requirement only, does not affect the outcome of the function. The string being modified. The position in $target to begin copying $source. The string to be copied into $target. The number of copies of $source to replicate within $target. $target $index $source $copies Factors This function never extends the length of $target. Example $target="Hewlett-Packard" $index=4 $source="falcon" $copies=2 $L.void=strchrcp($target, $index, $source, $copies) After execution, the value of $target is Hewfalconfalcon. RAD function: strchrin A RAD function that inserts copies of a string into another string. Function strchrin Format $L.void=strchrin($target, $index, $source, $copies) Parameters The following parameters are valid for the strchrin function: Parameter Data type $L.void= Not applicable. String Number String Number Description A syntax requirement only, does not affect the outcome of the function. The string being modified. The position in $target to begin inserting copies of $source. The string to be inserted into $target. The number of copies of $source to insert into $target. $target $index $source $copies Example $target="Hewlett-Packard" $index=4 Page 130 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference $source="falcon" $copies=2 $L.void=strchrin($target, $index, $source, $copies) After execution, the value of $target is Hewfalconfalconlett-Packard. RAD function: strclpl A RAD function that removes a number of characters from the beginning of a string. Function strclpl Format $L.void=strclpl($string, $number) Parameters The following parameters are valid for the strclpl function: Parameter Data type $L.void= Not applicable. String Number Description A syntax requirement only, does not affect the outcome of the function. The string being modified. The number of characters to remove. $string $number Example $string="Hewlett-Packard" $number=6 $L.void=strclpl($string, $number) After execution, the value of $string is t-Packard. RAD function: strclpr A RAD function that removes a specified number of characters from the end of a string. Function strclpr Format $L.void=strclpr($string, $number) Parameters The following parameters are valid for the strclpr function: Parameter Data type $L.void= Not applicable. String Description A syntax requirement only. It does not affect the outcome of the function. The string being modified. $string Page 131 of 396 HP Service Manager (9.30) RAD function: strcpy A RAD function that replaces a part of a string with a substring. does not affect the outcome of the function. The number of characters to copy from $source.void= Not applicable. value of $target is Hewalct-Packard. The string being modified.void=strcpy($target. RAD function: strdel A RAD function that deletes a number of characters from a specific location in a string. $source.30) . The beginning position of the substring within $source. Function strdel Format Page 132 of 396 HP Service Manager (9. String Number Description A syntax requirement only. $tindex.void=strcpy($target.void=strclpr($string. $number) After execution. The position in $target to begin copying a substring from $source. $number) Parameters The following parameters are valid for the strcpy function: Parameter Data type $L. $number) After execution. the value of $string is Hewlett-P. $tindex. The string supplying a substring. Function strcpy Format $L. $sindex. $sindex.Programming Guide Chapter 5: System Language reference $number Example Number The number of characters to remove. $string="Hewlett-Packard" $number=6 $L. $target $tindex $source $sindex $number Example String String Number $target="Hewlett-Packard" $tindex=4 $source="falcon" $sindex=2 $number=3 $L. $source. String Number Number Description A syntax requirement only. The string being modified. the value of $string is Hewletd. does not affect the outcome of the function. $index. The beginning position of the substring within $source. $source. $number) Parameters The following parameters are valid for the strdel function: Parameter Data type $L.void= Not applicable. $target $tindex $source $sindex $number Example String String Number $target="Hewlett-Packard" $tindex=4 Page 133 of 396 HP Service Manager (9.30) . The location in $string from which characters are to be deleted. $index.void=strdel($string.Programming Guide Chapter 5: System Language reference $L. $sindex. does not affect the outcome of the function. The number of characters to delete from $string. The string being modified.void=strins($target. The number of characters to insert from $source.void= Not applicable. The position in $target to begin inserting a substring from $source. The string supplying a substring. Function strins Format $L. $tindex. $number) Parameters The following parameters are valid for the strins function: Parameter Data type $L. $number) After execution. String Number Description A syntax requirement only. $string $index $number Example $string="Hewlett-Packard" $index=6 $number=8 $L.void=strdel($string. RAD function: strins A RAD function that inserts a substring into another string. $size) After execution. RAD function: strpadl A RAD function that pads a string with leading blanks until the string is a specified size.void= Not applicable. value of $string is (space)(space)(space)(space)(space)Hewlett-Packard. does not affect the outcome of the function. RAD function: strpadr A RAD function that pads a string with trailing blanks until the string is a specified size. $tindex.void=strins($target.void=strpadr($string. It does not affect the outcome of the function.Programming Guide Chapter 5: System Language reference $source="falcon" $sindex=2 $number=3 $L. Description A syntax requirement only. Function strpadr Format $L. The desired size of $string. Function strpadl Format $L.void=strpadl($string. $string $size Example $string="Hewlett-Packard" $size=20 $L. $number) After execution.void=strpadl($string. The string being modified. $size) Parameters The following parameters are valid for the strpadl function: Parameter Data type $L. String Number Description A syntax requirement only. $size) Parameters The following parameters are valid for the strpadr function: Parameter Data type $L.30) . it is truncated. Page 134 of 396 HP Service Manager (9. If the string is longer than the size desired. $source.void= Not applicable. value of $target is Hewalclett-Packard. $sindex. void=strtrml($string) Parameters The following parameters are valid for the strtrml function: Page 135 of 396 HP Service Manager (9. the value of $string is Hewlett-Pa. The desired size of string.void=strpadr($string. After execution. The string replacing $string1. Function strrep Format strrep($target.Programming Guide Chapter 5: System Language reference $string $size Examples String Number The string being modified. the value of $string is Hewlett-Packard(space)(space)(space)(space)(space). Function strtrml Format $L. The string within $target to be replaced. $string="Hewlett-Packard" $size=20 $L. the value of $s is Performance. $size) After execution.void=strpadr($string. RAD function: strrep A RAD function that returns a string after replacing a specified character sequence with another string. RAD function: strtrml A RAD function that removes all leading blanks from a string.$string2) Parameters The following parameters are valid for the strrep function: Parameter Data type Description $target $string1 $string2 Example $s=strrep("Personnel"."sonnel".$string1.30) . $size) After execution."formance") String String String The string containing the characters specified to be replaced. $string="Hewlett-Packard" $size=10 $L. RAD function: strtrmr A RAD function that removes all trailing blanks from a string. length) Parameters The following parameters are valid for the substr function: Page 136 of 396 HP Service Manager (9. does not affect the outcome of the function. The string being modified. $string Note: This RAD function is not available as a JavaScript system.functions call. Example $string=" Hewlett-Packard" $L. RAD function: substr A RAD function that extracts a substring from a string. the value of $string is Hewlett-Packard.void=strtrmr($string) Parameters The following parameters are valid for the strtrmr function: Parameter Data type $L. Example $string="Hewlett-Packard $L.30) .Programming Guide Chapter 5: System Language reference Parameter Data type $L. the value of $string is Hewlett-Packard. beginning position. Function strtrmr Format $L. It does not affect the outcome of the function.void=strtrmr($string) " After execution. String Description A syntax requirement only.void= Not applicable. Function substr Format substr(string. The string being modified.functions call. $string Note: This RAD function is not available as a JavaScript system.void=strtrml($string) After execution.void= Not applicable. String Description A syntax requirement only. the value of $a is Manager and the value of $b is Service.Programming Guide Chapter 5: System Language reference Parameter $string Data type String Description The string being modified. If you choose too low a value the substituted string may contain corrupted data because the function did not have enough bytes to substitute a multibyte character. Function substrb Format substrb(string. RAD function: substrb A RAD function that extracts a substring from a multibyte character or binary string. beginning Number The position in the string where the substring is to begin. It is recommended that you only use this function on strings of a fixed byte length to avoid possible data corruption. Refer to a UTF-8 or UTF-16 character encoding map to see how many bytes a particular multibyte character requires. Page 137 of 396 HP Service Manager (9. beginning position. The default behavior is to include all remaining characters in the string from the starting position. You can use the length parameter to specify a shorter byte length. 8) $b=substr(" Service Manager". 7) After execution. 1. length) Parameters The following parameters are valid for the substr function: Parameter string Data type String Description The string being modified. beginning Number The position in the string where the substring is to begin. Example $a=substr(" Service Manager". If you want to replace a fixed number of characters use the substr function instead.30) . position length Number The total number of characters you want the substring to contain. position length Number The total number of bytes you want the substring to contain. The default behavior is to include all remaining bytes in the string from the starting position. Important: You should choose a length value that takes into account the number of bytes available in the source string. You can use the length parameter to specify a shorter substr length. Function sysinfo. Function sysinfo.get("ActiveNamedUsers") Format $info=sysinfo. 1.Programming Guide Chapter 5: System Language reference Example $a=substrb("abcÄÖÜdef". the value of $a is ÖÜdef and the value of $b is abcÄÖ.get("ActiveFloatUsers") Format $info=sysinfo. For the string $b.get("ActiveLicenses") Format $info=sysinfo.get("ClientNetAddress") Example $x. Function sysinfo. 5) $b=substrb("abcÄÖÜdef".30) .get("ActiveFloatUsers") A RAD function that returns the total number of floating users currently active.get("ActiveNamedUsers") A RAD function that returns the total number of named users currently active.get("ClientNetAddress") Format $info=sysinfo. Function sysinfo. 7) After execution.get("ActiveLicenses") RAD function: sysinfo.get("ActiveFloatUsers") RAD function: sysinfo.get("ClientNetAddress") A RAD function that returns the Service Manager client network IP address as a character string. RAD function: sysinfo.get("ActiveNamedUsers") RAD function: sysinfo.get("ActiveLicenses") A RAD function that returns the total number of licenses currently active.get("ClientNetAddress") Page 138 of 396 HP Service Manager (9. setting the length value to 4 or 6 would lead to data corruption because there are not enough bytes available to contain the multibyte characters Ä and Ö respectively.clientNetAddress=sysinfo. such as a background process. Function sysinfo. the $display variable is gui if the user is running a Windows session..get("ClientOSName") RAD function: sysinfo. The client PID is the same as the server PID.get("Display") Format $info=sysinfo.get("ClientVersion") A RAD function that returns the version number of the client software as a string in the form of release.get("Display") Example $display=sysinfo.get("ClientVersion") Format $info=sysinfo.get("Display")="gui" then (..get("Display") A RAD function that returns the following: l l Returns gui if the user is running a GUI client.1.get("ClientPID") Format $info=sysinfo. Returns text if the process is not running through a GUI client.get("ClientVersion") RAD function: sysinfo. Function sysinfo.30) .get("ClientOSName") Format $info=sysinfo.) Page 139 of 396 HP Service Manager (9.Programming Guide Chapter 5: System Language reference RAD function: sysinfo.get("ClientPID") RAD function: sysinfo.get("ClientPID") Example $x. Function sysinfo.level. Function sysinfo. such as Windows XP or Mac OS.get("ClientPID") A RAD function that returns the Process ID (PID) for RAD. for example.0.clientPid=sysinfo.version.get("display") After execution.get("ClientOSName") A RAD function that returns the name of the operating system (OS) that Service Manager is running on. 7. If sysinfo. .get("MaxLicenses") Page 140 of 396 HP Service Manager (9. Returns scguiwswt if your session is a Windows client connection.get("languagecode") Format $info=sysinfo. Function sysinfo. "en" is returned. Returns scguiwweb if your session is a Web client connection.get("Display").get("languagecode") Note: If no language has been set.get("MaxFloatUsers") RAD function: sysinfo.) If sysinfo..get("MaxLicenses") A RAD function that returns the maximum number of licenses used since startup.get("MaxFloatUsers") A RAD function that returns the total number of floating users logged on since startup.get("MaxFloatUsers") Format $info=sysinfo. Returns sm if your session is a background process such as a scheduler.30) ..Programming Guide Chapter 5: System Language reference If index(sysinfo.get("MaxLicenses") Format $info=sysinfo.get("Display")~="text" then (.get("Environment") Format $info=sysinfo. Function sysinfo. "gui")>0 then (. l l l Function sysinfo.) RAD function: sysinfo..get("Environment") RAD function: sysinfo.get("Environment") A RAD function that returns the following: l Returns scserver if your session is a client application connection such as ConnectIT or GetServices. Function sysinfo. RAD function: sysinfo.get("languagecode") A RAD function that returns the server session language code value used for localized forms and messages. get("Mode") Format $info=sysinfo.. If sysinfo.) If (index(sysinfo."server".get("PrintOption") Page 141 of 396 HP Service Manager (9. RAD function: sysinfo. A RAD program may also require the label of the last RAD panel that was executed.get("mode")="client" then (.get("mode") Returns SOAP if the user is running on a Windows or Web client..30) . the name is the calling panel name from the parent application. Function sysinfo..get("prevlabel") The panel name is the last panel executed in the RAD program called.get("PrintOption") A RAD function that returns printing option information.get("PrintOption") Format $info=sysinfo. Returns express if RAD is running in express mode. The return is either client or server.lastlabel = sysinfo.get("PrevLabel") A RAD function that returns the label name of the last RAD panel executed. thus helping determine where errors occur. "express"})>0 then (. depending on how the system is set.{"sm". Function sysinfo.) RAD function: sysinfo.get("mode").get("PrevLabel") Format $info=sysinfo..get("Mode") A RAD function that returns the following: l l l l Returns server if RAD is running in server mode.get("PrevLabel") Example $L.Programming Guide Chapter 5: System Language reference RAD function: sysinfo. Returns SOAP if RAD is running on a Windows or Web client. At the start panel for any application. Function sysinfo. Returns sm if RAD is running on a sm process.get("Mode") Examples $mode=sysinfo. get("RecList") RAD function: sysinfo.get("ServerNetPort") Format $info=sysinfo.get("ServerNetAddress") RAD function: sysinfo. Function sysinfo. Examples The system started with: sm –httpPort:12932 A connected client issuing this RAD function returns 12932 The system started with: sm –-httpPort:scport1 A connected client issuing this RAD function returns scport1.get("ServerNetAddress") A RAD function that returns the Service Manager server network IP address in the form of a character string. Function sysinfo.get("Quiesce") A RAD function that returns true if the system is quiesced and false if the system is not quiesced. Page 142 of 396 HP Service Manager (9.Programming Guide Chapter 5: System Language reference RAD function: sysinfo.get("Quiesce") RAD function: sysinfo.get("ServerNetPort") Factors Returns either the port number or the service name. it is readonly. Function sysinfo.get("RecList") A RAD function that returns true if record list is enabled and false if record list is disabled. Function sysinfo.30) .get("Quiesce") Format $info=sysinfo. When the system is quiesced. as specified .get("RecList") Format $info=sysinfo.get("ServerNetAddress") Format $info=sysinfo.get("ServerNetPort") A RAD function that returns the Service Manager server port used by the connected client or the system name when called by a background process. Function sysinfo. Function sysinfo.get("TotalLicenses") Page 143 of 396 HP Service Manager (9.get("ThreadID") Example $x=sysinfo. in the form of a number.get("ThreadID") After execution.get("Telephony") A RAD function that returns true if telephony is enabled and false if telephony is disabled.get("TotalFloatUsers") Format $info=sysinfo. Function sysinfo.Programming Guide Chapter 5: System Language reference RAD function: sysinfo.get("TotalFloatUsers") A RAD function that returns the total number of floating users allowed.get("Telephony") RAD function: sysinfo.get("ThreadID") Format $info=sysinfo.get("ThreadID") A RAD function that returns the number of the current RAD thread.get("TotalLicenses") Format $info=sysinfo.get("Telephony") Format $info=sysinfo.get("TotalLicenses") A RAD function that returns the total number of licenses allowed.get("TotalFloatUsers") RAD function: sysinfo. RAD function: sysinfo. Function sysinfo.get("ServerPID") A RAD function that returns the Process ID (PID) of the server.get("ServerPID") RAD function: sysinfo.get("ServerPID") Format $info=sysinfo. Function sysinfo. the value of $x is set to the number ID of the current RAD thread.30) . get("TotalSystemProcs") Format $info=sysinfo.30) .get("TotalProcs") Format $info=sysinfo. Function sysinfo.get("TotalUserProcs") A RAD function that returns the total user processes.get("TotalNamedUsers") Format $info=sysinfo.variable) Parameters The following parameter is valid for the time function: Parameter Data type Description Page 144 of 396 HP Service Manager (9.get("TotalUserProcs") RAD function: time A RAD function that returns the time portion of a date and time value.time.get("TotalProcs") RAD function: sysinfo.get("TotalUserProcs") Format $info=sysinfo.get("TotalNamedUsers") RAD function: sysinfo. Function time Format time($date. Function sysinfo.get("TotalProcs") A RAD function that returns the total number of executing processes.get("TotalSystemProcs") A RAD function that returns the total number of system processes.Programming Guide Chapter 5: System Language reference RAD function: sysinfo. Function sysinfo. Function sysinfo.get("TotalNamedUsers") A RAD function that returns the total number of named users allowed.get("TotalSystemProcs") RAD function: sysinfo. RAD function: tod A RAD function that returns the current system date and time in the logged on user's timezone and date format.30) . Function tolower Format tolower($string) Parameters The following parameter is valid for the tolower function: Parameter Data type Description $string String The string variable containing uppercase characters. Factors The time of a given date and time may be different in different time zones. Characters with no lowercase equivalent remain the same. Examples tod()=`4/20/96 12:15:16' $curr. Function tod Format tod() Factors The tod function returns mm/dd/yyhh:mm:ss.time) After execution.time=tod() RAD function: tolower A RAD function that converts all uppercase characters in a string variable to lowercase characters. Page 145 of 396 HP Service Manager (9. Example $s=tolower("Copyright 2011") After execution. the value of $s is copyright 2011.time is 12:10:15. Example time($date. Factors Character conversions are based on the value of the language parameter. the value of $date.Programming Guide Chapter 5: System Language reference $string String The string variable containing upper-case characters. Old and new character sets may be literals. new character set) Parameters The following parameters are valid for the translate function: Parameter source old character set Data type Description String String The string to translate. Example $s=toupper("Copyright 2004") After execution."ABC") After execution. The existing character set. Function toupper Format toupper($string) Parameters The following parameter is valid for the toupper function: Parameter Data type Description $string String The string variable containing lower-case characters. For example.30) . the value is 123ABCdef. Characters with no upper–case equivalent remain the same."abc". the value of $s is COPYRIGHT 2004. Page 146 of 396 HP Service Manager (9. Example translate("123abcdef". A one–for–one correlation must exist between the old and new character sets. new character set String Factors l l l Old and new character sets must be strings of the same length. or fields. RAD function: translate A RAD function that translates from one character set to another. Function translate Format translate(source. old character set. The character set to translate to. Factors Character conversions are based on the value of the language parameter.Programming Guide Chapter 5: System Language reference RAD function: toupper A RAD function that converts all lower–case characters in a string variable to upper–case characters. variables. such as from lower to uppercase or encoding data. the third character in the new set replaces the third character in the old set. the number passed is truncated to a whole number.Programming Guide Chapter 5: System Language reference RAD function: trunc A RAD function that truncates the decimal digits of a number to a specified number of digits. See "Data types" (on page 21) for a numeric representation of each data type. 3.n) Parameters Data Parameter type number n Number Number Description The number to truncate. Function type Format $ttype=type($any. $any.30) . l l Examples trunc(3.45.value) Parameters The following parameter is valid for the type function: Parameter Data type Description Any literal or variable.value String Example Page 147 of 396 HP Service Manager (9. By default.4 is returned. Factors l The second parameter is not required. trunc(3. trunc('13:19:34') After execution. Function trunc Format trunc(number. The number of decimal digits desired. 13:19:00 is returned. 3 is returned.44) After execution. The default value of n is zero (0).1) After execution. Negative and positive numbers are treated the same. Character conversions are based on the value of the language parameter. RAD function: type A RAD function returns the numeric type of a datum. or logical. For a list of the numbers that correspond to the data types. the value of $ttype is three (3).30) . date and time.Programming Guide Chapter 5: System Language reference $ttype=type('2/15/96') After execution. 4) $x=val(3. 3) $x=val(0. $new. A string can be converted to a number.type Number Data type to convert the data to. 2) $x=val(100. Function val Format $new. 4) $x=val(1.type) Parameters The following parameters are valid for the val function: Data Parameter type $data Any data type Description Datum to be converted. or logical. $new. The default value is one (1). see "Data types" (on page 21). Factors l l l l A number can be converted to date and time. a string. Logical can be converted to a number or a string. 4) Value of $x after execution 100 "100" ‘00:01:40’ false true unknown NULL Page 148 of 396 HP Service Manager (9. A date and time can be converted to a number or a string.data=val($data. 4) $x=val(2. Examples The following examples show the value after execution: Variable $x=val(100) $x=val(100. RAD function: val A RAD function that converts a datum to a different data type. 3) $x=val("2/15/96".7. 1) $x=val(‘02/16/96 08:00:00’) $x=val(‘01/01/96’. 1) $x=val(false. 1) $x=val("HP"."7. Example $a=version() After execution. 4) $x=val(‘12:34:56’. Function version Format version() Factors Character conversions are based on the value of the language parameter. 2) NULL 100. 2) b $x=val(unknown.30) . 4) $x=val(‘01:00:23’.3 "HP" NULL ‘02/15/96 00:00:00’ true NULL 3623 62992915200 “01/01/96 00:00:00” $x=val(‘02/09/96 08:00:00’.0.Programming Guide Chapter 5: System Language reference $x=val("HP". 4) NULL NULL 0 1 2 "false" NULL unknown RAD function: version A RAD function that returns an array containing the release number of the Service Manager executable. 1) $x=val("100. Page 149 of 396 HP Service Manager (9.0. 2) $x=val("HP". 4) $x=val("0".3".1"}. the value of $a is {"unix". 3) ‘02/09/96 08:00:00’ $x=val(‘01/01/96’. 1) $x=val(unknown. 3) $x=val("true". 4) $x=val(false) $x=val(true. in the proper form. RAD function: year A RAD function that returns the full year for a date. the value of $fyear is 2005. scripts. Copies all of the data in a collection to another file variable. or calculations. Turns counters on or off for the current session. rtecall("counter") rtecall("datemake") rtecall("escstr") rtecall("filldate") rtecall("filecopy") Page 150 of 396 HP Service Manager (9.30) . based upon a series of numbers passed to it. Other Service Manager users are unaffected.0. rtecalls can be used in Format Control calculations.Programming Guide Chapter 5: System Language reference l l l The first element is a string naming the platform: unix. Returns a date. Precedes special characters in a string with an escape character. Service Pack 1.0. Example $fyear=year('2/15/05') After execution. such as 7. For example. or only alphanumeric characters and the provided non-alphanumeric characters. New capabilities may appear in every release of Service Manager. List: rtecalls() The rtecalls are based on one RAD function. and displayoptions. Function rtecall("alalnum") Description Checks to make sure a string contains only alphanumeric characters. regardless of the date format. Places the current date and time in a field in the current record. the rtecall( ) function. the RAD release level. Function year Format $fyear=year($date) Parameters The following parameter is valid for the year function: Parameter Data type Description $date Date/time The date and time value. They are in-line statements that are useful in the Service Manager RAD Debugger. The rtecall() function is extensible. The third element is a string containing the Service Manager version number and the Service Pack number. The second element is 7. mswin. or winnt.1 indicates Service Manager version 7.0. statements. The rtecall function is available anywhere in Service Manager that supports expressions. 30) .log file. Checks to make sure a string contains only numeric characters.file). or only numeric characters and the provided non-numeric characters. Retrieves the most current value of a record from the database and returns it in the file variable. Imposes data policy as defined in the datadict table. Replaces the getnumb RAD application. or only alphabetic characters and the provided non-alphabetic characters. or only lowercase characters and the provided non-lowercase characters. Page 151 of 396 HP Service Manager (9. or only numeric characters and the provided non-numeric characters.Programming Guide Chapter 5: System Language reference rtecall("fileinit") rtecall("getnumber") rtecall("getrecord") rtecall("getunique") Initializes a new file (rinit) in $targetfile. or only uppercase characters and the provided non-uppercase characters. Places the pointer at the indicated record. Sends a message to the external sm.id in a record collection (a record list).file. Returns a record list form. Checks to make sure a string contains only numeric characters. Changes this user’s password. rtecall("transtart") Measures the amount of data transferred. Checks to make sure a string contains only lowercase characters. Specifies whether any records exist that match a particular query regardless of any Mandanten data restrictions. Retrieves the record identified by Unique key values in $L.array. elapsed time and CPU usage of any transaction. which can be passed into an rio or fdisp panel. Returns into $L. Checks to make sure a string contains only uppercase characters. rtecall("isalnum") rtecall("isalpha") rtecall("islower") rtecall("isnumeric") rtecall("isupper") rtecall("log") rtecall("passchange") rtecall("policycheck") rtecall("qbeform") rtecall("recdupl") rtecall("recordexists") rtecall("refresh") rtecall("rfirst") rtecall("rgoto") rtecall("rid") rtecall("scantable") rtecall("sort") rtecall("statusupdate") Publishes a message to a specific field on a form. Sorts a list or a list of lists in ascending or descending order. Places the pointer at the first record in a record collection (a record list). Scans the specified table for certain types of invalid records and fixes them.array the values for the Unique key from the current record in $L. Returns the record number of the current record (represented by $L. Copies the contents of the current record into the contents of another record. Checks to make sure a string contains only alphabetic characters. Programming Guide Chapter 5: System Language reference rtecall("transtop") Measures the amount of data transferred, elapsed time and CPU usage of any transaction. Transtop is commonly invoked from the debugger and is used in conjunction with transtart. It returns an array of 5 values. The 5 values are: Elapsed time in milliseconds for the transaction CPU milliseconds consumed by the transaction This value is reserved for future use Bytes of data sent to the client for the transaction Bytes of data received from the client for the transaction rtecall("trigger") Turns triggers on or off for the current session. rtecall("alalnum") function A RAD function that verifies that a string contains only alphanumeric characters. The first character must be alphabetic. The remaining characters must be alphabetic, numeric, or one of the nonalphabetic characters provided. Function rtecall("alalnum") Format $L.success.flag= rtecall ($L.fnc.name, $L.return.code, $L.str, $L.chars) Parameters The following parameters are valid for the rtecall("alalnum") function: Parameter $L.success.flg $L.fnc.name Data type Logical String Description Indicates if the function was successful Name of the sub-function to call, in this case "alalnum" Provides a more detailed return code The string to be checked An optional comma delimited string of non-alphanumeric characters to allow $L.return.code Number $L.str $L.chars String String Factors If the $L.success.flg is false, the function failed. If it is true, the function succeeded. Example $L.success.flag=true $L.return.code=0 $L.str=name in $L.file $L.chars="., _" Page 152 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference $L.success.flag=rtecall("alalnum", $L.return.code, $L.str, $L.chars) Results: l l l $L.success.flag is true when name in $L.file="my.name" $L.success.flag is true when name in $L.file="my_name" $L.success.flag is false when name in $L.file="my name" rtecall("counter") function A RAD function that turns counters on or off for the current session. Other users are not affected. Function rtecall("counter") Format $L.success.flag= rtecall($L.fnc.name, $L.return.code, $L.switch) Parameters The following parameters are valid for the rtecall("counter") function: Parameter $L.success.flg $L.fnc.name Data type Logical String Description Indicates whether or not the function was successful. The name of the sub-function to call, in this case "counter". $L.return.code Number Provides a more detailed return code. $L.switch Number The value is either one (1), indicating counters on, or zero (0), indicating counters off. Factors If the $L.success.flg is false, the function failed. If it is true, the function succeeded. Example $L.success.flg=rtecall("counter", $L.return.code, 1) to turn on counters $L.success.flg=rtecall("counter", $L.return.code, 0) to turn off counters rtecall("datemake") function A RAD function that returns a date, in the proper form, based upon a series of numbers passed to it. Function rtecall("datemake") Format $L.success.flg=rtecall($L.fnc.name, $L.return.code, $L.date, $L.yr, $L.mo, $L.da, $L.hr, $L.mn, $L.se) Parameters Page 153 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference The following parameters are valid for the rtecall("datemake") function: Parameter $L.success.flg $L.fnc.name Data type Logical String Description Indicates if the function was successful. The name of the sub-function to call, in this case "datemake". Provides a more detailed return code. $L.return.code Number $L.date $L.yr Date/Time The variable in which the date will be returned. Number The year. A 2-digit year uses the prefix 20 for years up to 50, and 19 for years after. For example, 48 returns 2048, 99 returns 1999. The month. The day. Valid values are from one (1) through 31. The hour. The minutes. The seconds. $L.mo $L.da $L.hr $L.mn $L.se Number Number Number Number Number Factors The $L.success.flag and $L.return.code always return true, even when the function is unsuccessful. Examples $L.cal.date=‘01/01/05 00:00:00’ $L.success.flg=rtecall("datemake",$L.return.code, $L.cal.date, 0, 5, 31, 17, 15, 22) Results: l l $L.success.flag=true $L.cal.date=‘05/31/2005 17:15:22’ $L.cal.date=‘01/01/05 00:00:00’ $L.success.flag= rtecall("datemake",$L.return.code, $L.cal.date, 0, 2, 31, 17, 15, 22) Note that 2/31/05 is an invalid date. Results: l $L.success.flag=true l $L.cal.date=‘01/01/2005 00:00:00’ The result is invalid; therefore the date variable is unchanged. Regardless of the success or failure, the $L.success.flag returns a value of true. rtecall("escstr") function A RAD function that precedes special characters in a string with an escape character. This function is rarely needed. The only situation in which a string needs the escape characters added is when Page 154 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference that string is to be fed back into Service Manager. Service Manager treats any data between quotes as a string. If the data contains a quote, then that quote must be escaped with a backslash escape character (\) to ensure that the quote is treated as data instead of the end of the string. Since the backslash is used as the escape character, any occurrence of a backslash in the data must also be escaped. An example of when this function might be needed is when a RAD program is constructing a query to retrieve a record based on data from another record. In this case, the contact name in an incident retrieves the contact information from the contacts table. The RAD program might construct a query as follows: $L.query = "name="+contact.name in $file This query will not function properly if the contact.name from $file contains a quote or a backslash character because these characters are not properly escaped and will cause the parse of the query to end prematurely. The correct example is as follows: $L.temp = contact.name in $file $L.ret = rtecall("escstr",$L.rc,$L.temp) $L.query="name="+$L.temp Function rtecall("escstr") Format rtecall($L.fnc.name, $L.rc, $L.str) Parameters The following parameters are valid for the rtecall("escstr") function: Parameter Data type Description Name of the sub-function to call, in this case "escstr". Provides a more detailed return code. The string to be modified. $L.fnc.name String $L.rc $L.str Number String Example Before the call to "escstr", $L.str contained c:\dir\sub $L.rc=0 $L.ret=rtecall("escstr", $L.rc, $L.str) After the rtecall, $L.str contains the following string: c:\\dir\\sub. The backslash escape character (\) is now inserted in front of the existing backslash. rtecall("filecopy") function A RAD function that copies all of the data in a collection to another file variable. The database dictionary record for both the source and target files must exist. Records are only added. Function rtecall("filecopy") Format $L.success.flg=rtecall($L.fnc.name, $L.return.code, $L.dbdict.source.name, $L.dbdict.target.name, $L.count, $L.bad) Page 155 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference Parameters The following parameters are valid for the rtecall("filecopy") function: Parameter $L.success.flg $L.fnc.name Data type Logical String Description Indicates if the function was successful. Name of the sub-function to call, in this case "filecopy". Provides a more detailed return code. The name of the source database dictionary record. The name of the target database dictionary record. A count of the number of records successfully moved. A count of the number of errors encountered. $L.return.code Number $L.dbdict.source.name String $L.dbdict.target.name $L.count $L.bad String Number Number Factors If the $L.success.flg is false, the function failed. If it is true, the function succeeded. Example $L.dbdict.source.name="location" $L.dbdict.target.name="locationbak" $L.success.flg=rtecall("filecopy", $L.return.code, $L.dbdict.source.name, $L.dbdict.target.name, $L.count, $L.bad) Returns the "locationbak" file as an exact copy of the "location" file. rtecall("fileinit") function A RAD function that initializes a file variable in $targetfile from $sourcefile. Function rtecall("fileinit") Format rtecall($L.fnc.name, $errcode, $targetfile, $sourcefile) Parameters The following parameters are valid for the rtecall("fileinit") function: Parameter $L.fnc.name $L.errcode $L.targetfile Data type Description String Number String Name of the sub-function to call, in this case "fileinit". The number of the error code encountered. The target file in which to initialize the variable. The source file that contains the variable. $L.sourcefile String Factors Page 156 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference l l l The file initialized is identified by the $sourcefile variable. The current record for $targetfile is the same as the current record in $sourcefile. Update and delete operations cannot be performed against $targetfile. Example $L.void=rtecall("fileinit", $L.errcode, $file.old, $file) rtecall("filldate") function A RAD function that places the current date and time in a field in the current record. Function rtecall("filldate") Format $L.success.flg= rtecall($L.fnc.name, $L.return.code, $L.file, $L.field.name) Parameters The following parameters are valid for the rtecall("filldate") function: Parameter $L.success.flg $L.fnc.name Data type Description Logical String Indicates if the function was successful. The name of the sub-function to call, in this case "filldate". Provides a more detailed return code. The file handle. The name of the field to be updated. $L.return.code Number $L.file $L.field File String Factors If the $L.success.flg is false, the function failed. If it is true, the function succeeded. Example $L.file={[, , {}, , , {}, , , {}, , , {}, , , {}, {}, {}, {{[, , , ]}}, , , ]} where the first field is named "date" $L.field.name="date" $L.success.flg= rtecall("filldate", $L.return.code, $L.file, $L.field.name) $L.file returns ={[‘04/14/2000 08:27:19’, , {}, , , {}, , , {}, , , {}, , , {}, {}, {}, {{[, , , ]}}, , , ]} rtecall("getnumber") function A RAD function that replaces the getnumb RAD application. Function rtecall("getnumber") Format Page 157 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference $L.flg=rtecall($L.fnc.name, $L.return.code, $L.number, $L.class, $L.field) Parameters The following parameters are valid for the rtecall("getnumber") function: Parameter $L.flg $L.fnc.name Data type Logical String Description The value is true for success and false if an error occurs. The name of the sub-function to call, in this case "getnumber". $L.return.code Number The value is zero (0) if everything is correct, negative one (-1) if an error occurs. This is related directly to $L.flg. $L.number $L.class String String The number or string returned The class of number for which you are searching (from the number file). Reserved for future use. $L.field String Factors A sequential overview: 1. The function establishes a lock called "getnumb"+$L.class+$L.field and waits until the lock is established. 2. If the number class is not found, or if there are duplicates, the following error displays: "($L.flg=false)" 3. The function reads the current number. 4. The function increments or decrements by the step value. The step defaults to one (1). 5. If incrementing and the number is greater than the reset value, it uses the start number. Start defaults to zero (0). 6. A new field called string.flg. n If string.flg is false, it remains a numeric type. n n If string.flg is true, the number is converted to a string. If string.flg is unknown, or the field isn’t in the database dictionary (not added during an upgrade), the function checks for a prefix, a suffix, or length. If any one of these exists, the function converts the value to a string. If none of these exist the function leaves the value as a number. 7. To convert the value to a string, the function uses the prefix, corrects the length of the number (padded with zeros on the left), and then adds the suffix. 8. The function eventually saves the new number to the file and returns it to the user, converted to a string if necessary. 9. Finally, it unlocks and returns. rtecall("getrecord") function A RAD function that retrieves the record identified by Unique key values in $L.array. Page 158 of 396 HP Service Manager (9.30) The keys can later be used to retrieve the record using the rtecall("getrecord") function.file does not represent a file variable. $L. $L. The $L.void=rtecall($L.errcode = 0 $L.name String $L. $L.array in the rtecall("getunique") function.file Number String String Factors $L.void=rtecall($L. {"IM1001"}.file represents a current database record. $L.file does not represent a current database record. $L.void=rtecall("getrecord".array. Example $L.file) Parameters The following parameters are valid for the rtecall("getunique") function: Variable/Value Description $L.worked = true $L. If no key values are returned.errcode.errcode. The number of the error code encountered.errcode $L. $L.fnc. The name of the record to retrieve. The name of the table to retrieve the record from.file) Where: The value of $L.file) Parameters The following parameters are valid for the rtecall("getrecord") function: Parameter Data type Description The name of the sub-function to call. in this case "getrecord".array $L. For example. Function rtecall("getunique") Format $L. if $L. $L. The function succeeded.30) .keyvalues. $L.errcode.name.array.name.errcode = 1 If key values are returned in $L.Programming Guide Chapter 5: System Language reference Function rtecall("getrecord") Format $L.fnc.file is initialized for the probsummary table. Page 159 of 396 HP Service Manager (9. if $L. $L.array is an input variable. For example. rtecall("getunique") function A RAD function that returns an array containing the Unique key values for a current record. typically the key values returned by $L.fnc.worked = false $L. code=0 $L.name Data type Logical String Description Indicates if the function was successful.fnc.flg is false.return. $L.chars String String Factors If the $L. Example $L.worked = rtecall( "getunique".Programming Guide Chapter 5: System Language reference $L. the function succeeded. Factors $L. an example of the key values returned in $L.success.success.flag=rtecall("isalnum".return.file. The string to be checked.chars) Parameters The following parameters are valid for the rtecall("isalnum") function: Parameter $L.keyvalues is {"IM1001". $L. The file variable initialized by the rinit command panel and containing a current record.file The file identified by $L. (. The output returns an array containing the unique key values for the record in $L.errcode. the function failed. numeric.file is for the problem table.30) . in this case "isalnum".chars=" .success.keyvalues.str=phone in $L.file $L. For example. $L.flag=true $L.str $L.success. Example $L. $L.file does not have a Unique key defined.errcode = 2 $L. Name of the sub-function to call. $L. $L.flg $L. ).code.name. $L.str. Function rtecall("isalnum") Format $L. If it is true. $L.1}.flag= rtecall ($L. if $L. $L.code Number $L. An optional comma-delimited string of non-numeric characters to allow.return.code. $L.chars) Results: Page 160 of 396 HP Service Manager (9.return.success.file ) rtecall("isalnum") function A RAD function that verifies that a string contains only alphabetic. Provides a more detailed return code.fnc. -" $L. or the non-alphabetic characters provided.str.keyvalues is an output variable. file="my 1st name" $L.success. Example $L.flg $L.Programming Guide Chapter 5: System Language reference l l When phone in $L.file="(508) 362. $L. Provides a more detailed return code.return. $L.flag= rtecall ($L.code.success.str $L. $L.success. or only lowercase characters and the provided non-lowercase characters.2701" $L.code=0 $L.flg is false.success.fnc. The string to be checked.chars=" " $L. $L. rtecall("isalpha") function A RAD function that verifies that a string contains only alphabetic characters or only alphabetic characters and the non-alphabetic characters provided.flag is false. When phone in $L.chars) Results: l l l When name in $L. When name in $L.str=name in $L.file="(508) 362-2701" $L. An optional comma-delimited string of non-alphabetic characters to allow.flag is false. $L. in this case "isalpha".flag=true $L. $L.return.str.success. If it is true.success.name. Function rtecall("isalpha") Format $L.return.fnc.success.30) . Page 161 of 396 HP Service Manager (9.return. rtecall("islower") function A RAD function that verifies that a string contains only lowercase characters.success.name Data type Logical String Description Indicates whether or not the function was successful.str.file $L.code. the function failed.chars) Parameters The following parameters are valid for the rtecall("isalpha") function: Parameter $L.flag is true.flag is true.flag is true.code Number $L.success. $L. The name of the sub-function to call. the function succeeded.chars String String Factors If the $L.file="my name" $L.success. When name in $L.file="my first name" $L.flag=rtecall("isalpha". fnc. in this case "islower". The string to be checked. $L.fnc.return.flag is true.code Number $L. $L.chars String String Factors If the $L.flag is false. Provides a more detailed return code. $L.code. Name of the sub-function to call.flag=rtecall("islower". the function succeeded.success. $L. If it is true. $L.Programming Guide Chapter 5: System Language reference Function rtecall("islower") Format $L. $L.success.code.success.file="bob" $L.return.return. or only numeric characters and the provided non-numeric characters.success.str.flg $L.success. the function failed.flag is false. rtecall("isnumeric") function A RAD function that verifies that a string contains only numeric characters. $L.file="Bob" $L.chars) Results: l l l When name in $L. $L. When name in $L. An optional comma-delimited string of non-lowercase characters to allow.return.chars) Parameters Page 162 of 396 HP Service Manager (9.success.name.flag=true $L. $L.success.code. Function rtecall("isnumeric") Format $L.file $L. $L.30) .str. Example $L.success.name.return.chars) Parameters The following parameters are valid for the rtecall("islower") function: Parameter $L.flag= rtecall ($L. When name in $L.flag= rtecall ($L.fnc.name Data type Logical String Description Indicates if the function was successful.flg is false.chars=" " $L.str=name in $L.code=0 $L.str $L.file="b1b" $L.str.success. file="B1B" $L. the function succeeded. $L.flag is false. in this case "isnumeric".str.name Data type Logical String Description Indicates if the function was successful. $L.flg $L. When name in $L.chars) Parameters The following parameters are valid for the rtecall("isupper") function: Parameter $L.code.success. Example $L.str. Provides a more detailed return code.success.return.return.flag=true $L.+.30) .chars) Results: l l l When name in $L. Provides a more detailed return code.flag is true.success. Function rtecall("isupper") Format $L. If it is true.str $L.chars String String Factors If the $L. the function failed.return./. When name in $L.flag= rtecall ($L.code Number $L.name Data type Logical String Description Indicates if the function was successful.name. An optional comma-delimited string of non-numeric characters to allow.return.file="Bob" $L. $L.file $L. in this case "isupper".flg $L.code.code Number Page 163 of 396 HP Service Manager (9. The string to be checked. Name of the sub-function to call.*.fnc.success. rtecall("isupper") function A RAD function that verifies that a string contains only uppercase characters.fnc.chars="-.success.Programming Guide Chapter 5: System Language reference The following parameters are valid for the rtecall("isnumeric") function: Parameter $L.flag is false. $L. or only uppercase characters and the provided non-uppercase characters. $L.%.return.success.str=name in $L. $L.flg is false.$" $L.code=0 $L. Name of the sub-function to call.file="36" $L.flag=rtecall("isnumeric". $L.fnc.success.success. $L.success. in this case "log". the function failed.success.name. the function failed.log file. When name in $L.message String Factors If the $L. rtecall("log") function A RAD function that sends a message to the external sm.return.flag is false.flag=rtecall("isupper".str $L. If it is true. $L.fnc. When name in $L.success.flg is false.code. the function succeeded.success.log: Page 164 of 396 HP Service Manager (9.chars=" " $L. $L.file="B1B" $L.success. $L.Programming Guide Chapter 5: System Language reference $L.return. An optional comma-delimited string of non-upper case characters to allow.success.success.code.file="BOB" $L.name Data type Description Logical String Indicates whether or not the function was successful.chars String String The string to be checked. $L.str=name in $L.success.success.return. Factors If the $L. Provides a more detailed return code.flag is false.return.file $L.success. $L. the function succeeded. The message to be sent.code. Function rtecall("log") Format $L.flag is true.code Number $L.flg=rtecall($L.message) Parameters The following parameters are valid for the rtecall("log") function: Parameter $L.str.chars) Results: l l l When name in $L.flg is false.flg $L. $L.return.success.file="Bob" $L. If it is true. Example $L.30) .flag=true $L. "This is a new message") Generates the following bold line in the sm. The name of the sub-function to call.flg=rtecall("log".code=0 $L. $L. Example $L.fnc. the function failed.pass $L.flg is false. Name of the sub-function to call. 24 records from location unloaded to: 306 04/12/2000 09:05:09 This is a new message rtecall("passchange") function A RAD function that changes a user password. String String The old password.name Data type Logical String Description Indicates if the function was successful.flg $L. 137 04/12/2000 07:03:45 at: 04/11/2000 23:02:51.confirm.code. $L.success. The new password. A confirmation of the new password. $L. 00:00:01 elapsed. Function rtecall("passchange") Format $L. 137 04/12/2000 07:03:45 started at: 04/11/2000 23:02:50.return.30) . In this case.pass Number Provides a more detailed return code. $L. the sub-function called is passchange.pass String Factors If the $L.code $L. If it is true.return.success.name.new.pass) Parameters The following parameters are valid for the rtecall("passchange") function: Parameter $L.Programming Guide Chapter 5: System Language reference 137 04/12/2000 07:03:44 started at: 04/11/2000 23:02:48. Example Page 165 of 396 HP Service Manager (9. $L.pass.fnc.new. 137 04/12/2000 07:03:45 started at: 04/11/2000 23:02:49. System background scheduler: event System background scheduler: availability System background scheduler: contract System background scheduler: ocm started System startup completed successfully. 137 04/12/2000 07:32:48 locations.flag=rtecall($L.old. the function succeeded.pass. $L.save. 137 04/12/2000 07:03:45 elapsed time: 00:00:18.confirm.success.old.fnc. $L. return.flg Data type Logical Description Indicates whether or not the function was successful. "newpassword") rtecall("policycheck") function A RAD function that imposes data policy as defined in the System Definition. the function succeeded.code. $L.code.$L.return. Provides a more detailed return code.errcode.30) . the function failed. $L.Programming Guide Chapter 5: System Language reference $L. You can insert this function into a format file handle using the contents() function.return. Page 166 of 396 HP Service Manager (9. The following example shows the syntax to use in the contents function: contents($L. "oldpassword". $L.flg= rtecall($L.name.rc=rtecall("policycheck". If it is true.code.fnc. "newpassword". $L.flg= rtecall("passchange".format) = $L.file) Parameters The following parameters are valid for the rtecall("policycheck") function: Parameter $L.file String Factors If the $L.fnc.filed) rtecall("qbeform") function A RAD function that returns a record list form. $L.form Function rtecall("qbeform") Format $L. The file handle.flag= rtecall($L.$L.flg is false.success. which can be passed into a rio (Record Display/Input) Command panel or fdisp panel.success.fnc.file.name.success.success.qbe.code Number $L. Example $L. in this case "policycheck".qbe.name Data type Description Logical String Indicates if the function was successful.return. Function rtecall("policycheck") Format $L. Name of the sub-function to call.form) Parameters The following parameters are valid for the rtecall("qbeform") function: Parameter $L.success.success.$L. $L.flg $L. Function rtecall("recdupl") Format rtecall($L.30) .code.$L. Factors If the $L. in this case "qbeform".fnc.name Data type Description String Name of the sub-function to call. the function succeeded.Programming Guide Chapter 5: System Language reference $L.flg= rtecall("qbeform".code Number $L.return. The file handle used to generate the record list. Page 167 of 396 HP Service Manager (9.form) rtecall("recdupl") function A RAD function that copies the contents of the current record into the contents of another record.fnc. This call does not return any records from the query. $L. obtain the contacts table by using the "rinit" panel. in this case "recdupl". Provides a more detailed return code. Example $L. The update and delete operations cannot be performed against $targetfile. $targetfile. $sourcefile) Parameters The following parameters are valid for the rtecall("recdupl") function: Parameter $L.temp. The target record to which fields are copied. not field name.qbe.name String The name of the subfunction to call.code. $return.flg=rtecall("recdupl". For example. $L.flg is false.success.form Structure The resulting record list form returned as a structure.return. $L.name.qbe.success. Data is copied by position. Provides a more detailed return code.$L. the function failed. $L. $L. l l Example $L. Both $targetfile and $sourcefile must be initialized file variables.code Number $targetfile $sourcefile Factors l String String Both $targetfile and $sourcefile must have identical descriptors.file File $L. If it is true.return.fnc.return. The source file from which fields are copied.file.file) rtecall("recordexists") function Specifies whether any records exist that match a particular query regardless of any Mandanten data restrictions.$L.code. "logical. "device". true ) Returns true if there are any records in the contacts table. String The query to be run. This query ignores all Mandanten restrictions.rc. $L. or a parsed expression. For example. The call returns false if there are no records that match the query. $L. Function rtecall("refresh") Format $L. a string.errcode. $L.rc String Provides a more detailed return code.Programming Guide Chapter 5: System Language reference Function rtecall("recordexists") Format $Lexists=rtecall("recordexists".filename.query Factors The call returns true if at least one record matches the query. $L. in this case "recordexists". $L. contacts or probsummary. $L. $L.success. This parameter is not currently used but is reserved for future use. $L.rc.flg=rtecall("refresh".name=\"pc001\"" ) Returns true if there is a record in the device table with a logical name of "pc001" regardless of whether the current user has access to the record or not. String The name of the Service Manager table to query. "contacts".query) Parameters The following parameters are valid for the rtecall("recordexists") function: Data type Parameter Description "recordexists" String Determines the name of the RTE call. rtecall("refresh") function This function retrieves the most current value of a record from the database and returns it in the file variable.file) Parameters The following parameters are valid for the rtecall("refresh") function: Variable/Value Description Page 168 of 396 HP Service Manager (9.30) .rc. rtecall( "recordexists". Example rtecall( "recordexists". The query can be true. $L. false.filename $L. $L.success. $L.errcode = 0 $L.success. Example $L.file does not represent a file variable. Provides a more detailed return code.errcode = 1 $L. $L.success.file) rtecall("rgoto") function A RAD function that places the pointer at the indicated record.name. Function rtecall("rfirst") Format $L.file.errcode.record. $L.code Number $L.30) . $L. in this case "rfirst".Programming Guide Chapter 5: System Language reference $L.fnc. It contains the current record. The name of the sub-function to call. $L. Example $L.flg = rtecall( "refresh".return. Function rtecall("rgoto") Format $L. $L. A file handle that represents the collection.code.code.code.fnc.success. the function failed.file ) rtecall("rfirst") function A RAD function that places the pointer at the first record in a record list. $L. It is true.return. If it is true. the function failed.file File Factors If the $L.flg is false..flg=rtecall($L.file The function succeeded.success.id in a record list.success. The $L.return.flg $L. the function succeeded.name. the function succeeded. $L.flg=rtecall("rfirst". Factors If the $L.return.flg is false.flg=rtecall($L.file) Parameters The following parameters are valid for the rtecall("rfirst") function: Parameter $L.$L.success.fnc.id) Parameters Page 169 of 396 HP Service Manager (9.name Data type Description Logical String Indicates if the function was successful. The file variable initialized by the rinit command panel. record. Provides a more detailed return code.success. The name of the sub-function to call.success.code Number $L. the function failed. A record number.$L.record.file $L.id File Number Factors If the $L. the function succeeded.code.fnc. the function failed. $L.fnc.name Data type Description Logical String Indicates whether or not the function was successful. in this case "rid".success.flg=rtecall($L.name Data type Description Logical String Indicates whether or not the function was successful. $L.flg is false.return.file. $L. If it is true. $L.name. Example $L.file.flg=rtecall("rid".code.flg is false.$L.code.record. as represented by $L. A file handle that represents the collection.file. $L. The name of the sub-function to call.flg=rtecall("rgoto".success.record.id File Number Factors If the $L.record.return. A record number.30) .success.file $L. Example $L. Provides a more detailed return code.code Number $L.Programming Guide Chapter 5: System Language reference The following parameters are valid for the rtecall("rgoto") function: Parameter $L. If it is true. in this case "rgoto".id) Page 170 of 396 HP Service Manager (9.return.success.flg $L.id) Parameters The following parameters are valid for the rtecall("rid") function: Parameter $L. $L. Function rtecall("rid") Format $L. A file handle that represents the collection. $L. $L. $L.return.fnc.return.success.flg $L. the function succeeded.id) rtecall("rid") function A RAD function that returns the record number of the current record.file. the function succeeded. $tablename.30) . $totalnum.name. $return.name Data type Logical String Description Indicates if the function was successful.flg $L.return.success. $totalnum. specifies the columns on which the function will scan for duplicate records. Only available when $scantype is 1. If it is true. $scantype.name.success. $deleted) Parameters The following parameters are valid for the rtecall("scantable") function: Parameter $L. This total number should include $fixed. "ioaction". $deleted. $L.flg=rtecall($L. $bfix.flg is false. Examples The following function call scans the ioaction table for duplicate records on the field1 and field2 fields and fixes the duplicate records. Number Indicates the number of the records that were removed.Programming Guide Chapter 5: System Language reference rtecall("scantable") function A RAD function that scans the specified table for certain types of invalid records and fixes the records.code. Number Indicates the number of the invalid records that were fixed. $bfix. $fixed. Specifies whether to automatically fix the invalid data. and $deleted are available when $scantype is 2 or 3. true. $scantype Number Specifies the type of scan the function will perform. Function rtecall("scantable") Format $L. $fixed.tablename $bfix $columns String Bool String array The name of the table to be scanned.code. such as fields with a "Unique" or "No Nulls" key applied 3–to scan for values whose data types do not match the data type defined on the field l $L. Factors If the $L.flg=rtecall("scantable". which can be one of the following: l l 1–to scan for duplicate records on specified columns 2–to scan for null values on non-nullable fields. the function failed.fnc. Page 171 of 396 HP Service Manager (9.success. $tablename.return. 1. Name of the sub-function to call.fnc. $scantype. and the number of invalid records that failed to be fixed.flg=rtecall($L. $totalnum $fixed $deleted Number Indicates the number of the invalid records that were found.success. in this case "scantable".code Number Provides a more detailed return code.code. $L.fnc. $columns) $L. $return. $L. index.code. Number The index of the array in the grid to use as the sort field.return. 4. in this case "sort".success.code Number Provides a more detailed return code..fnc. "ioaction".Programming Guide Chapter 5: System Language reference {"field1"."d". 2}} Page 172 of 396 HP Service Manager (9. 3.return. Name of the sub-function to call. 2. true. A zero (0) is the first element of the array. $L. $L. $L.success."field2"}) The following function call scans the ioaction table for null values that are disallowed by keys.flg=rtecall($L.index Array The list or list of lists to be sorted. $L.name.grid. $all. In a "type-2" scan.flg $L. 0) Parameters The following parameters are valid for the rtecall("sort") function: Parameter $L. the function: n converts the value into the correct data type if the value data makes sense in the target data type n replaces the value with a default value in the correct data type. Number The value for ascending is one (1) or descending zero (0).30) .flg=rtecall("scantable". "b" . rtecall("sort") function A RAD function that sorts a list or a list of lists in ascending or descending order.name Data type Logical String Description Indicates whether or not the function was successful.success. $fixed. the function failed. the function differentiates duplicate items by appending suffixes such as dup1. $L. If it is true. -dup2. the function succeeded.type Factors If the $L. $L. $L.-dupx. $deleted) Additional information If you choose to fix invalid data by setting $bfix to 1: l In a "type-1" scan. or n l replaces the first of the null values with a default value if null values violate a "No Nulls" key. Examples $L.return..code. Function rtecall("sort") Format $L. $L.{1.grid $L. l In a "type-3" scan.flg is false. the function: n removes the record if null values violate a "Unique" key.fnc.list={{"a". "c"}. success.Programming Guide Chapter 5: System Language reference $L. 2. 2.flag = rtecall($L. $L. 1. The widget must have a name property specified.name.widget. "b". "c". "c". 4}} $L.30) . 1) Returns: $L.code. 0) Returns: $L.success. $L. Example L.flg . 3. $list. "b". "d"}. 1. For example. 4}} $L.flg=rtecall("sort". 2.flg=rtecall("sort". 3.flg is false. Function rtecall("statusupdate") Format $L. 2}} $L. A string to be displayed in the widget.widget. $L. 1) Returns: $L. 4}} $L. $L. the function succeeded. $list.success. 3. the function failed."d". {1. This function is commonly used to update the format during a long-running transaction to inform the user of the status of the current operation.return. "c". 0. "b". $L.caption String Factors If the $L. "MyScrollingMarqueeWidget". 4.rtecall("statusupdate". converting a file to an RDBMS.list={{"a". 1}} rtecall("statusupdate") function A RAD function that dynamically changes the caption of a widget on the current format. "c". as specified in the name property of the widget. 0. {1. $L. 4. If it is true. 4. "a"}. {1.{1.func.caption Parameters The following parameters are valid for the rtecall("statusupdate") function: Parameter $L. 2.code.list={{"a". {4.success. "c"}.widget.success. "c"}. $list. 2}} $L. 0) Returns: $L. "d"}.code.code. "c"}."d". 3.list={{"d". 2}} $L.name.return. 3.{1.widget.flg=rtecall("sort".flg=rtecall("sort".list={{"a".name Data type String Description The name of the form widget. $L. "b" . "b". $list. 3.{1. "b" . 3.return.list={{"a". $L.success."d".success.return. "The end user will see this text in the marquee" ) Page 173 of 396 HP Service Manager (9.list={{"a". $L.code.return.list= {{"a". "b" .return. "d"}. $L. $L. Example $L. the function succeeded.flg is false.30) .code. Any name selected by the user for the transaction to measure.fnc.flg= rtecall("transtart". l l l The CPU time and data transmission number are retrieved from the server machine. and CPU usage of any transaction.return.code. Function rtecall("transtart") Format $L.return. Function rtecall("transtop") Format $L.flg $L. and CPU usage of any transaction.fnc.success.success. Name of the sub-function to call.flag= rtecall($L. elapsed time.flag= rtecall($L. $L.return. $L.name. You can have multiple transaction timings active at the same time.return. If it is true. String copies are a rough indication of the amount of RAD processing.transaction) Parameters The following parameters are valid for the rtecall("transtart") function: Parameter $L.fnc.Programming Guide Chapter 5: System Language reference rtecall("transtart") function A RAD function that measures the amount of data transferred.success. $L.name Data type Description Logical String Indicates whether or not the function was successful.success.transaction.code Number $L. $L. Provides a more detailed return code. elapsed time. The function is commonly invoked from the GUI debugger and used in conjunction with the rtecall("transtart") function. the function failed.success. $results) Parameters The following parameters are valid for the rtecall("transtop") function: Parameter Data type Description Page 174 of 396 HP Service Manager (9. This function is commonly invoked from the GUI debugger and used in conjunction with the rtecall ("transtop") function. in this case "transtart".name.transaction String Factors If the $L. "problemopen") rtecall("transtop") function A RAD function that measures the amount of data transferred. fnc.return.success. $L. Example $L. bytes sent to client.code Number $L. bytes received from client}.success. "problemopen".961 CPU seconds.return.code.961.code. in the form of an array: {elapsed seconds.name. 0.return. $L.success.flg $L. $L.flg is false. $L. Name of the sub-function to call. 0.success. in this case "transtop". The results gathered. the function failed. the function succeeded.Programming Guide Chapter 5: System Language reference $L.switch) Parameters The following parameters are valid for the rtecall("trigger") function: Parameter $L. $L. Factors If the $L.840 string copies. If it is true.name Logical String Indicates whether or not the function was successful. The value is either one (1) to turn triggers on. Example $L.code Number Provides a more detailed return code. Provides a more detailed return code.success. and performed 46. If it is true. Service Manager no longer keeps track of the third value in the array and it always reports as zero.fnc.return. or zero (0) to turn triggers off. 0. rtecall("trigger") function A RAD function that turns triggers on or off for the current session.30) . Function rtecall("trigger") Format $L.fnc.flg $L.flg is false.477 bytes to the server. The transaction sent 26. 26712. Other Service Manager users are not affected. 2477} This example shows that the "problemopen" transaction took 58.success.712 bytes to the client and the client returned 2.flg=rtecall("trigger". in this case "trigger".164. the function failed.code. the function succeeded.name Data type Logical String Description Indicates if the function was successful. $L.flag= rtecall($L.switch Number Factors If the $L.success. $L.$results String Array Any name selected by the user for the transaction to measure.164 seconds of real time and 0. $results) $results={58. Name of the sub-function to call.return. 1) to turn Page 175 of 396 HP Service Manager (9.transaction $L.flg=rtecall("transtop". cpu seconds. delete as. Copies an eventin record to the eventout file and changes the evtype.email axces.move. Routine as.intoout Page 176 of 396 HP Service Manager (9. Deletes an element from an array. Creates a schedule record that processes alerts for Change Management records.cts. Creates or updates an incident based on an Event Services eventin record.fax axces. Creates or updates a change request based on an Event Services eventin record.copy Description Copies an element from one position to another. updates or deletes records from Service Manager files using Event Services. leaving the original in place.return. a brief definition of each.receive axces.write axces.code. and a link to a detailed description of their use.name as.apm axces. 0) to turn triggers off List: RAD routines This section provides a list of RAD routines.insert as.email.database axces. Moves an element from one position in an array to another by creating a copy and then deleting the original Displays all available arrayed structure options on the rio (Record Display/Input) Command panel. Sorts an arrayed structure based on the contents of a particular field within the arrayed structure. Receives external e-mail and converts it to Service Manager mail using Event Services. $L.move as.flg=rtecall("trigger".get.cm3 axces. Creates an eventout record based on the Service Manager mail record that was passed in. Returns the structure name of the arrayed structure in which the cursor is located. Inserts a NULL element.30) .cm3. Adds. as.sort axces.Programming Guide Chapter 5: System Language reference triggers on $L.success. Builds an eventout record that can be processed by the SCAutomate / Fax application.options as. fc post. or deletes a software configuration item that an external agent (other than ServerView or StationView) discovers to the pcfiles file if the filter criteria are satisfied. date/time) in either ascending or descending order. It also processes the information from the scan into the Configuration Management application using the scauto. Sends a marquee message.page Creates an eventout record based on information passed in that can be processed by SCAutomate / Pager to send a numeric or alphanumeric page. Copies data from a target file to the current file.fields wmi. Establishes the numbering sequence in sequential numbering.inventory. Creates or updates Request Management quotes via Event Services eventin record. axces.sm axces.evin Breaks events into appropriate constituent parts.software Adds.publish routine.fc publish query.Programming Guide Chapter 5: System Language reference axces.30) . Executes the posting routine from the subroutines process (automatic posting) and from the additional options process (manual posting). Provides access to other tables from a particular record.checks Page 177 of 396 HP Service Manager (9.stored scauto. Provides access to configuration items. using predefined links under user control.approval fill. updates.inventory RAD routine. character. Validates fields in a form.write database es.send message. Sorts simple arrays (number.inventory sort.rm axces. axces.sap. Sends messages under user control.array validate.hybrid.publish marquee. Build the eventout record used by the SCAutomate interface. Accesses all queries for a specific file or to execute a specific stored query. Creates or updates Service Desk interactions based on an eventin record using Event Services. Processes approvals for Request Management and Change Management.fc marquee. Reads the schedule record and initiate the marquee. axces. Publishes a variable into SYSPUB. Checks the eventin record for status information from a type of scan.fc getnumb. and as.copy Parameters The following parameters are valid for the as.30) . This routine is used in conjunction with as. it is considered to be an arrayed structure name.move. This routine is used in conjunction with as. The default value is 1.name is executed against the data. leaving the original in place. as. name character No index number No The number of lines (height property) in the subform that displays the arrayed structure. The application as. Notes: This is not the window size that displays the arrayed structure.delete.get. 1) Where: The value of n = the number of lines in the subform. The value is always $file when called from Format Control.copy routine: Data Name type file record Required Description No The file variable that you are currently editing. If a comma is found.move routines.field.get.copy. the value must be passed as a number by using the following syntax: val("n".name then executes against this result. Page 178 of 396 HP Service Manager (9.name(1).insert. if the arrayed structure subform contains data on lines 1 and 2. Data is not normally passed to this parameter. If the data passed to this parameter does not contain commas. When calling the application from Format Control.copy A RAD routine that copies an element within an array or structure from one position to another. The default is the result of executing the function cursor. and 1 indicates a data type of number. then this parameter is 2.Programming Guide Chapter 5: System Language reference RAD routine: as. Routine as.delete A RAD routine that deletes an element from an array. the application as. Note: You can pass the name of a specific arrayed structure. as. and as.insert. For example. RAD routine: as. the application as. The default is the result of executing the function cursor. Notes: This is not the window size that displays the arrayed structure.get.name Parameters The following parameters are valid for the as. For example.field. The application as.get. name character No index number No RAD routine: as.Programming Guide Chapter 5: System Language reference Routine as.name executes against the data. the value must be passed as a number by using the following syntax: val("n".30) .get.name then executes against this result.name A RAD routine that returns the structure name of the arrayed structure where the cursor is located. The value is always $file when called from Format Control.delete routine: Data Name type file record Required Description No The file variable currently being edited. 1) Where: The value of n = the number of lines in the subform.name(1).name routine: Name Data type Required Description Page 179 of 396 HP Service Manager (9. If a comma is found. The number of lines (height property) in the subform that displays the arrayed structure. Data is not normally passed to this parameter. it is considered to be an arrayed structure name. Note: You can pass the name of a specific arrayed structure. then this parameter is 2.get. Routine as.delete Parameters The following parameters are valid for the as. and 1 indicates a data type of number. If the data passed to this parameter does not contain commas. When calling the application from Format Control. if the arrayed structure subform contains data on lines 1 and 2.get. The default value is 1. Programming Guide Chapter 5: System Language reference name character No The structure name of the arrayed structure. The default is the result of executing the function cursor.field.name(1). The returned structure name of the arrayed structure. This is a data return parameter, data should not be passed to it. prompt character No RAD routine: as.insert A RAD routine used to insert a NULL element. It is used in conjunction with as.copy, as.delete, and as.move. Routine as.insert Parameters The following parameters are valid for the as.insert routine: Data Name type file record Required Description No The file variable currently being edited. The value is always $file when called from Format Control. Data is not normally passed to this parameter. The default is the result of executing the function cursor.field.name(1). The application as.get.name then executes against this result. Note: You can pass the name of a specific arrayed structure. If the data passed to this parameter does not contain commas, it is considered an arrayed structure name. If a comma is found, the application as.get.name executes against the data. index number No The number of lines (height property) in the subform that displays the arrayed structure. For example, if the arrayed structure subform has data on lines 1 and 2, then this parameter is 2. The default value is 1. Notes: This is not the window size that displays the arrayed structure. When calling the application from Format Control, the value must be passed as a number by using the following syntax: val("n", 1) Where: The value of n = the number of lines in the subform, and 1 indicates a data type of number. name character No Page 180 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference RAD routine: as.move A RAD routine used to move an element from one position in an array to another by creating a copy and then deleting the original. This routine is used in conjunction with as.copy, as.insert, and as.delete. Routine as.move Parameters The following parameters are valid for the as.move routine: Data Name type file record Required Description No The file variable currently being edited. The value is always $file when called from Format Control. Data is not normally passed to this parameter. The default is the result of executing the function cursor.field.name(1). The application as.get.name then executes against this result. Note: You can pass the name of a specific arrayed structure. If the data passed to this parameter does not contain commas, it is considered an arrayed structure name. If a comma is found, the application as.get.name executes against the data. index number No The number of lines (height property) in the subform that displays the arrayed structure. For example, if he arrayed structure subform has data on lines 1 and 2, then this parameter is 2. The default value is 1. Notes: This is not the window size that displays the arrayed structure. When calling the application from Format Control, the value must be passed as a number by using the following syntax: val("n", 1) Where the value of n = the number of lines in the subform, and 1 indicates a data type of number. name character No RAD routine: as.options A RAD routine used to display all available arrayed structure options one rio (Record Display/Input) Command panel. Note: The as.options routine provides the control needed to copy, insert, delete, and move fields. It is not necessary to run as.copy, as.move, as.insert, and as.delete in conjunction with this routine. Routine as.options Page 181 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference Parameters The following parameters are valid for the as.options routine: Name file Data type record Required Description No The file variable currently being edited. The value is always $file when called from Format Control. Passes the name of the current form. If left blank, the default is the result of executing the function current.format(). Allows the user to edit the data record when the Arrayed structure maintenance options are displayed. The default value is true. Note: When calling the application from Format Control, the value must be passed as a data type of 4 (logical) by using the following syntax: val(“false”, 4) index number No The number of lines in the subform that displays the arrayed structure. For example, if the arrayed structure subform has data on lines 1 and 2, then the parameter is 2. The default value is 1. Notes: This is not the window size that displays the arrayed structure. When calling the application from Format Control, the value must be passed as a number by using the following syntax: val("n", 1) Where: The value of n = the number of lines in the subform, and one (1) indicates a data type of number. name character No cond.input Boolean No RAD routine: as.sort A RAD routine used to sort a structure that includes an array. It sorts based on the contents of a particular field within the array of the structure. This routine supports major, minor, and intermediate sorting by allowing you to sort multiple array fields in the structure with one pass of the routine. You can also specify an ascending or descending sort order. You must call this routine from Format Control or RAD on an as-needed basis. Routine Page 182 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference as.sort Parameters The following parameters are valid for the as.sort routine: Name file Data type Required Description record No The file variable currently being edited. The value is always $file when called from Format Control. The name of the structure you want to sort. This name corresponds to the input field of the subform object in the form to which the Format Control record is attached. Note: If the data passed to this parameter does not contain commas, it is considered an arrayed structure name. If a comma is found, the application as.get.name executes against the data. numbers array (numbers) Yes Specifies the field numbers on which to sort within the arrayed structure. In Format Control, you must first define a $variable in the Initializations form for the array of numbers. Next, pass that variable to the numbers input field in the Additional Options definition. Note: Field numbers correspond to the index numbers listed in the database dictionary and not to the sequence in which they appear on the form. condition array No (Boolean) Specifies either ascending or descending order for each field being sorted in the arrayed structure, as specified in the numbers parameter. To specify an ascending order, pass a value of true. To specify descending order, pass a value of false. The default value is true. Each element in this array has a direct correlation with the elements of the numbers parameter. In Format Control, you must first define a $variable in the Initializations screen that defines the Boolean array. Next, pass the variable to this input field in the Additional Options definition. name character No RAD routine: axces.apm A RAD routine that creates or updates an incident based on an Event Services eventin record. Routine axces.apm Parameters The following parameters are valid for the axces.apm routine: Page 183 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference Name record text prompt query Data type record Required Description Yes Identifies the eventin record to pass. Provides the specific action to take. Indicates the Map Name used in event registration. Indicates the query to use to find the pre-existing record updated by this Input event. Identifies the Service Manager file where the data is recorded. An error occurs if this is not set. If the value is set to NULL, change to close. If evstatus begins with error, the value is false. If evstatus does not begin with error, the value is true. character No character No character No string1 character No boolean1 Boolean No RAD routine: axces.cm3.cts.write A RAD routine that creates a schedule record that processes alerts for Change Management records. Routine axces.cm3.cts.write Parameters The following parameters are valid for the axces.cm3.cts.write routine: Name record name Data type record Required Description No Indicates what file variable passes to the application. Indicates the System ID of the system to send the message to and where to calculate the schedule time. Indicates the Client of the system to send the message to and where to calculate the schedule time. What is the target time for this event? Use the tod() function to indicate to the system that the message sends at the next acceptable time. Once you find the next acceptable time for this System ID and client combination, a new schedule record generates for a message of this type. When set to true, the rescheduling portion of the code is bypassed and all messages occur as soon as possible. character No prompt character No time1 time No query character No boolean1 Boolean No Page 184 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference RAD routine: axces.cm3 A RAD routine that creates or updates a change request based on an Event Services eventin record. Routine axces.cm3 Parameters The following parameters are valid for the axces.cm3 routine: Name string1 Data type Required Description Identifies the area of CM3 to work in and where to record data for branching or changing tasks (cm3r or cm3t). Indicates eventin record to process. What map interprets the incoming message? What map interprets the incoming message? Are Output events created? Identifies the area of CM3 to work in and where to record data for branching or changing tasks (cm3r or cm3t). The query for existing change record. character No record prompt text record No character No character No No boolean1 Boolean string1 character No query character No RAD routine: axces.database A RAD routine called by many Event Services events to add, update or delete records from Service Manager tables using Event Services. Routine axces.database Parameters The following parameters are valid for the axces.database routine: Parameter Name record Data type file record Required Description Yes Identifies the eventin record to pass. prompt character Yes Identifies the Map name used in Event Registration. The event map name must end with a for add events and must end with u for update events. Identifies the Service Manager table to populate with data. string1 character Yes Page 185 of 396 HP Service Manager (9.30) Programming Guide Chapter 5: System Language reference text character Yes Provides the specific action to take, such as the following: l l l add delete update query character No Indicates the query to use to find the existing record to update. When flagged, the value is true and Service Manager writes an eventout record. When not flagged, the value is false and no eventout record is written. Specifies the behavior to follow when more than one record matches the query. When flagged true, Service Manager processes more than one record. When not flagged (value is false), Service Manager processes only the first record found. Indicates the Format Control record to use. boolean1 Boolean No cond.input Boolean No name character No RAD routine: axces.email A RAD routine that creates an eventout record based on the Service Manager mail record that was passed in. Routine axces.email Parameters The following parameters are valid for the axces.email routine: Name Data type Required Description No Writes the unique record identifier to the eventin record. Set up the $axces variable using Format Control to create the intended result. Indicates the delimiter character. record record text character No RAD routine: axces.email.receive A RAD routine that receives external e-mail and converts it to Service Manager mail using Event Services. Routine axces.email.receive Parameters Page 186 of 396 HP Service Manager (9.30) If you pass a string in the text parameter. prompt character No string1 character No text character No names. ensure that it does not occur naturally in fields in the event. Use your login ID.phone from the contacts table.1 array (characters) name character No Passes the name of the recipient. For example. If you define your own character. Set up the $axces variable using Format Control to create the intended result. Defines the recipient’s fax telephone number. No Passes the record variable. use the pipe symbol (|) to separate line of text. names.receive routine: Name Data type Required Description This parameter writes the unique record identifier to the eventin record. Use the recipient’s login ID. Routine axces.email.fax Parameters The following parameters are valid for the axces. Names the form or text string. Page 187 of 396 HP Service Manager (9.3 array (characters) record record No No The destination of the FAX phone number. fax.30) . The default is ^.fax A RAD routine that builds an eventout record that can be processed by the SCAutomate / Fax application.fax routine: Name Data type Required Description No Passes the name of the sender. pass the form name in the text parameter. Defines the separation character. Use $file in Format Control.2 array (characters) names. Defines the FAX title. record record No RAD routine: axces. If a record variable passes in the record parameter.Programming Guide Chapter 5: System Language reference The following parameter is valid for the axces. move.intoout Parameters The following parameters are valid for the axces. record record name character RAD routine: axces. if the The numeric message. Yes.intoout A RAD routine that copies an eventin record to the eventout file and changes the evtype. Identifies the eventout type.page Parameters The following parameters are valid for the axces. text parameter is not used.page routine: Name name prompt Data type character character Required Yes Description Contains the Contact Name from the contacts table. such as pm9700123. Routine axces. If you define your own character. The default value is the caret character (^). if the The alphanumeric message. pass pm and the incident number.intoout routine: Name Data type Required Description Yes No Identifies the eventin record to pass. Yes. No Defines the separation character.page A RAD routine that creates an eventout record based on information passed in that can be processed by SCAutomate / Pager to send a numeric or alphanumeric page.30) . Routine axces. Defines the page response code used by the pageresp input event to identify the type of event processing to occur. The registration record then determines the application to call by examining the text character string1 character query character No Page 188 of 396 HP Service Manager (9. For example.Programming Guide Chapter 5: System Language reference RAD routine: axces. to update a particular incident with the response from a page. ensure that it does not occur naturally in fields in the event.move.move. prompt parameter is not used. rm A RAD routine that creates or updates Request Management quotes via Event Services eventin record. RAD routine: axces. ocmo. No Lists the pager telephone number from the contacts table. disapprove or unapprove. Identifies the operator (security profile) in Service Manager to use and which userID to stamp on records that are processed using this event. or ocml) where data is recorded. Provides the specific action to take. open.1 array (characters) names.rm routine: Name record text Data type record Required Description No This parameter identifies which eventin record to pass. update. close.rm Parameters The following parameters are valid for the axces. Routine axces. character No prompt query character No character No string1 character No boolean1 Boolean No name character No Page 189 of 396 HP Service Manager (9.30) .3 array (characters) No Passes the name of a group defined in the distgroup table.2 array (characters) names. such as add.Programming Guide Chapter 5: System Language reference data in the first position of the evfields field. true or false. The logical parameter flag. approve. The query string used to select a pre-existing record to update. values array (characters) names. No Identifies a list of addressees from the contacts table or operator table. No Lists the pager PIN number from the contacts table. that indicates whether to write the eventout record on transaction completion. Indicates the Map name in event registration. Identifies the Service Manager table (ocmq. This parameter expects one header and any number of properly-formed detail events.hybrid. Identifies the eventregister that interprets the detail portion of the event message.sap.sm routine: Name record prompt string1 query Data type record Required Description Yes Identifies the eventin record to pass. Routine axces.evin Parameters The following parameters are valid for the axces.sap.evin routine: Name record Data type record Required Description No A hybrid event that calls the appropriate routines for header and detail events.sm A RAD routine that creates or updates Service Desk interactions based on an eventin record using Event Services. prompt character No name character No RAD routine: axces. Identifies the eventregister that interprets the header portion of the event stream. Indicates the query to use to find the pre-existing record that this Input event updates.sm Parameters The following parameters are valid for the axces.evin A RAD routine that splits events out into the appropriate constituent parts.Programming Guide Chapter 5: System Language reference RAD routine: axces. Routine axces. Indicates the Map name used in event registration. character No character No character No boolean1 Boolean No text character No Page 190 of 396 HP Service Manager (9.hybrid.sap. true or false. that indicates whether the eventout record writes on transaction completion.30) .hybrid. Designates the output event type. A logical parameter flag. Identifies the Service Manager file where data is recorded. write routine: Name record Data type record Required Description Yes Names the record to be written. Defines the separation character.software Parameters The following parameters are valid for the axces.software routine: Name record Data type record Required Description No Writes the unique record identifier to the eventin record.write Parameters The following parameters are valid for the axces. Specifies the Format Control record to use.30) . to write an eventout record when an incident is opened. In Format Control the record is $file. A logical parameter flag. updates.fields and description=9 in $axces.Programming Guide Chapter 5: System Language reference RAD routine: axces.software A RAD routine that adds. Routine axces. or deletes a software configuration item (CI) that an external agent discovers to the pcfiles file once the filter criteria are satisfied. For example.fields. Names the registration type as it appears in the eventregister file.name=1 in $axces. If you define your own name character No string1 character No Page 191 of 396 HP Service Manager (9. true or false. logical. use the value pmo for this parameter. In this case. Indicates the Map name used in event registration. Routine axces. prompt string1 character No character No query character No boolean1 Boolean No name character No RAD routine: axces.write A RAD routine used to build an eventout record used by the SCAutomate (SCAuto) interface. Set up the $axces variable using Format Control to create the intended result. that indicates whether the eventout record writes on transaction completion. Identifies the software file in Service Manager where the configuration item (CI) data is recorded. Specifies the Format Control record to use.Programming Guide Chapter 5: System Language reference character. For example. The default is value is the caret character (^).30) . Note: This routine is only called from Additional Options in Format Control. Routine database Parameters The following parameter is valid for the database routine: Name name record Data type Required Description character record No No The name of the form you want to open. prompt character No query character No RAD routine: database A RAD routine used to access other tables from a particular record.approval A RAD routine that processes approvals for the Request Management and Change Management applications. ensure that it does not occur naturally in fields in the event.approval Parameters The following parameters are valid for the es. Defines a user sequence ID with a maximum length of 16 characters. Identifies the Service Manager table where data is recorded. text character No Defines a system sequence ID with a maximum length of 16 characters. Routine es. Defines the user name. RAD routine: es. The default value is operator(). allowing them to call the location table from the contacts table. character No Page 192 of 396 HP Service Manager (9. to enable an option button to appear on your users’ screens.approval routine: Name record text Data type record Required Description Yes Identifies the eventin record to pass. Service Manager generates the system sequence ID unless you supply one. The form name that determines which link record to use. The value of this parameter must be $file.fc Parameters The following parameters are valid for the getnumb.first $fill.fc through the Additional Options process. Routine fill. You can create simple identification numbers for database records.exact RAD routine: getnumb.input Boolean RAD routine: fill. the fill operation attempts to copy data back to that item in the selected array. Page 193 of 396 HP Service Manager (9. true or false.fc routine: Name record Data type Required Description record Yes The data record where the number will be placed.fc Parameters The following parameters are valid for the fill.fc routine: Data type record Name record Required Description Yes The value is $file when calling fill. The name of the field in the target file to fill. The default is the link record for the current form. or complex numbers composed of prefixes and suffixes.fc A RAD routine used to establish the numbering sequence in sequential numbering.fc A RAD routine that copies data from a target file to the current file using predefined links under user control. A logical parameter.replace $project. Routine getnumb. cond. text character No string1 character No Variables supported $fill.30) . If the field is an array. that specifies whether the eventout record writes on transaction completion. The default is the current field (the field where the cursor is located).Programming Guide Chapter 5: System Language reference name character No No Indicates the Map name used in event registration. 3 array No (numbers) numbers. For example.4 array No (numbers) RAD routine: marquee. 1). the sequential number resets to the starting value. Use this parameter to attach a specified number to your records without updating the number file. a four-digit number has a value of val("4". When the value passed to the application is reached.send. Routine marquee. displaying odd or even numbers only. if you want to increment by 2. Establishes a new starting value for the sequential number when the reset point is reached. Defines the length of the sequential number. The subroutine prefixes as many zeroes to the number as necessary to match the required number of digits.30) . This value appears in the Class field of the Sequential Numbering File. Pass the RAD function val() to the number1 parameter.publish A RAD routine used to send a marquee message. Determines the reset point for the sequential number.2 array No (numbers) numbers.Programming Guide Chapter 5: System Language reference name character Yes The sequential number Class (category) of the record that the Format Control record is attached. Where: The number 4 is the length of the number and the number 1 is the data type (a number representation).publish Parameters Page 194 of 396 HP Service Manager (9. Allows the user to increment or decrement the sequential number independent of the number file. numbers. This is the identifying character string that appears before the number.1 array No (numbers) numbers. Defines the data type of the sequential number (number or string). Names the field in the data record where the sequential number appears. For example. This routine is always called from within marquee. Sets the increment or decrement value. prompt character Yes text character No number1 number No string1 character No Defines the prefix. Note: The system automatically adds $MARQUEE to the beginning your variable name before publishing it. A logical field. the routine immediately publishes your message without adding it to the marquee table (recommended method).Programming Guide Chapter 5: System Language reference The following parameters are valid for the marquee. character Yes boolean1 Boolean No cond. The marquee agent then reads the record and publishes it.publish routine: Name name Data type Required Description The published variable used by the agent to search the database. If set to false. The default value is Red.send Parameters The following parameters are valid for the marquee. Set the flag to true to add the name to the database if that record does not exist.input Boolean No RAD routine: marquee. Routine message. text prompt character No character No A variable that contains the message to be published. A logical field.send routine: Name record Data type Required Description Schedule record for the marquee process Logical field.fc A RAD routine used to send messages under user control.fc Page 195 of 396 HP Service Manager (9.30) . Set the flag to true to add this message to the marquee table.send A RAD routine used to read the schedule record and initiate the marquee. Routine marquee. If the flag is set to false. the application publishes only the specific marquee message defined in the schedule record (recommended method). The display color for your marquee or the valid system number in the Color field.publish application. or the field is NULL. Set the flag to true to send all marquee messages defined in the schedule record. character Yes No boolean1 Boolean RAD routine: message. such as problemclose.main and a Mail Target must be defined. The default is operator(). an email address must be specified in the relevant table. the names must be operator ID’s defined in the operator table. The message number parameter identifies a message within the area specified by the string1 parameter. For internal Service Manager messages. prompt character No Enter a message class that matches one of the records in the msgclass table.name) defined in the contacts table. the names can either be operator ID’s or contact names (contact. It must contain the string pm. For example.Programming Guide Chapter 5: System Language reference Parameters The following parameters are valid for the message.fc routine: Name index Data type number Required Description No Select one of three message levels: l l 1 for information. The mail class parameter is used within Incident Management applications to identify the ticket number so that mail already sent can be selected and updated. generate an array of the screen contents using the genout() function and then insert lines of text at the top of the array. The message name parameter identifies the message. there must be a msgclass record with a type of email for the message class name specified. For email. 2 for action.30) . The default value is msg. Use the name of the Service Manager application or application area that generates the message. The text of the message can be a string or an array. this is the default. To send email messages. text character Yes name character No string1 character No number1 number No query character No Page 196 of 396 HP Service Manager (9. l 3 for error. message levels may appear in different colors. In Text mode. This value can contain either a list of operator names or a single name. RAD routine: post. The variable that identifies the message to be published. Defaults to the name of the input field that the cursor is in when the you select the option.1 array (characters) No The mail target parameter must contain the incident record number. name character No text character No Page 197 of 396 HP Service Manager (9.30) . name character No prompt character No RAD routine: publish A RAD routine used to publish a variable into SYSPUB. it could be $file1. In most cases. You can override this default by passing a string of the specific Link record you want to use.fc A RAD routine used to execute the posting routine from the subroutines process (automatic posting) and from the additional options process (manual posting).fc routine: Name file Data type record Required Description Yes The value is always $file when calling post.Programming Guide Chapter 5: System Language reference names.fc Parameters The following parameters are valid for the post. Routine publish Parameters The following parameters are valid for the publish routine: Data Name type Required Description The published variable used by the agent to search the database. Routine post.fc through the Additional Options process. however. or another file variable established by Format Control or custom RAD processing.fc through the Subroutine process. You can override this default by passing a string of a specific field name you want to use. Defaults to the name of the currently open form. the variable is $file when calling post. The name of the stored query you want to execute.inventory Parameters The following parameters are valid for the scauto. The logical parameter flag. for example. that indicates whether to write the eventout record on transaction completion. If you use a variable such as $axces. Identifies the Service Manager table name to write to. name=operator(). name character No text character No RAD routine: scauto.30) .inventory routine: Name record Data type record Required Description Yes Writes the unique record identifier to the eventin record.stored routine: Data Name type Required Description The name of the table you want to enable the user to query. Indicates the query to use to find the pre-existing record that this Input event updates. set it up using Format Control to create the intended result. Routine scauto. update. such as add. Note: This routine is called only from Additional Options in Format Control. true or false. prompt string1 text character No character No character No query character No boolean1 Boolean No name character No Page 198 of 396 HP Service Manager (9. for example. Provides the specific action to take. or delete.stored A RAD routine used to access all queries for a specific table or to execute a specific stored query. Indicates the Map name in event registration. device. Routine query.Programming Guide Chapter 5: System Language reference RAD routine: query.stored Parameters The following parameters are valid for the query.workstation.inventory A RAD routine that provides access to Configuration items (CIs). Specifies the event registration name. in either ascending or descending order. val("false".input Boolean No Page 199 of 396 HP Service Manager (9. the value can be looked up online.30) . 4). always pass $file to this parameter. and a value of falsesorts in descending order. When set to true.array from Format Control. Controls the sort order.array A RAD routine called from subroutines to sort simple arrays.fields A RAD routine used to validate fields in a form. For example. The line of the array to validate must be defined in the Initializations process. such as number.array routine: Name file Data type record Required Description Yes When calling sort.name. Name of the array in the current form containing the field names to validate.name(). use the value val("true".file record Yes cond.fields Parameters The following parameters are valid for the validate. To name the field in which the cursor was last located when an add or update was performed. This means a list of valid values is presented for selection.field.Programming Guide Chapter 5: System Language reference RAD routine: sort. to validate a Boolean field to true. Routine validate. such as logical. The value is expressed as val(). The data record in which the field is being validated. 4). names array (of No characters) second.array Parameters The following parameters are valid for the sort.fields routine: Name name Data type character Required Description No Names the field in the current form to validate. Routine sort. The name of the input field (array) in $file you want to sort. use the RAD function cursor. or date and time. for example. The value of this parameter must be $file. A value of true sorts in ascending order. The required value of the field defined by the parameter val(). name character Yes No boolean1 Boolean RAD routine: validate. character. or delete. Indicates the query to use to find the pre-existing record that this Input event updates.inventory RAD routine. Routine wmi. that specifies whether or not to process additional records if you select more than one record. A logical parameter flag.30) . Identifies the event registration name.inventory. This routine also processes the information from the scan into the Configuration Management application using the scauto.inventory.check routine: Name record prompt string1 Data type record Required Description Yes Identifies the eventin record to pass. that indicates whether the eventout record writes on transaction completion.inventory. Identifies the Service Manager table where data is recorded. A logical parameter. Indicates the Map name used in event registration.Programming Guide Chapter 5: System Language reference RAD routine: wmi. true or false. update. character No character No text character No query character No boolean1 Boolean No name character No No cond. such as add.check A RAD routine that checks the eventin record for status information from a type of scan. true or false.input Boolean Page 200 of 396 HP Service Manager (9. Provides the specific action to take.check Parameters The following parameters are valid for the wmi. forms" (on page 202) system.sysinfo . l l l l l l l l l l l system.oldrecord" (on page 206) system. The scripts that attempt to use these names as variables will not function as expected.vars .see "JavaScript object: system. For example.functions" (on page 203) system. It acts as a container for an entire hierarchy of objects. Page 201 of 396 HP Service Manager (9. Service Manager defined JavaScript objects.sysinfo" (on page 207) system.functions .see "JavaScript object: system.files The following JavaScript object is unique to HP Service Manager.user instead of user.files" (on page 201) system.vars" (on page 209) Note: All of the alias or shortcut global objects available in HP ServiceCenter 6. This is a complete list of global objects exposed as properties of the System object.see "JavaScript object: system. JavaScript functions available in the ScriptLibrary of Service Manager."JavaScript object: system.forms .record" (on page 206) system. The system.oldrecord .files .user .threads . JavaScript object: system."JavaScript object: system."JavaScript object: system. and some JavaScript examples. Note: None of the Service Manager global System objects have constructors. JavaScript global methods.library" (on page 205) system.see "JavaScript object: system.record . Objects have methods and/or subordinate properties that you refer to by using the dot operator.user" (on page 208) system.library ."JavaScript object: system. These other objects are properties of the System object. JavaScript global System objects Global objects are predefined objects that are always instantiated and cannot be created using the “new” operator.users .30.0 are deprecated in Service Manager 9. JavaScript functions available in Service Manager. Therefore.threads" (on page 207) system. They are deprecated because the alias or shortcut is likely to be used as a script variable.Chapter 6 JavaScript and Service Manager reference This chapter provide the reference details for the JavaScript global System objects. The primary global object is the System object. type system.see "JavaScript object: system."JavaScript object: system.files object allows you to call a particular Service Manager table into memory.users" (on page 208) system. you must type out the entire global system object name.30) ."JavaScript object: system. The system. Sets a variable equal to system. Usage system. Arguments There are no arguments for this object.forms. contacts) var f = system.Programming Guide Chapter 6: JavaScript and Service Manager reference Usage system. Arguments There are no arguments for this object.files. Properties The following properties are valid for this object: Property form name Methods None Example This example does the following: Required Description Yes This argument contains the form name you want to bring into memory.contacts Displays the contents of the contacts table This example requires the following sample data: l A valid Service Manager table name (for example.contacts is:\n" + f ).30) .contacts. print( "The value of system.form name Note: Service Manager global system objects do not have constructors. Page 202 of 396 HP Service Manager (9.files. JavaScript object: system.files.files. Properties The following properties are valid for this object: Property table name Methods None Example This example does the following: l l Required Description Yes This argument contains the table name you want to bring into memory.forms The following JavaScript object is unique to HP Service Manager.table name Note: Service Manager global system objects do not have constructors.forms object allows you to call a particular Service Manager form into memory. JavaScript object: system. ScriptLibrary) var fm = system.Programming Guide Chapter 6: JavaScript and Service Manager reference l l Sets a variable equal to system.forms.ScriptLibrary.functions.ScriptLibrary is:\n" + fm ).functions object allows you to call a particular Service Manager RAD function from JavaScript. Page 203 of 396 HP Service Manager (9. The system.ScriptLibrary Displays the contents of the ScriptLibrary form This example requires the following sample data: l A valid Service Manager form name (for example. print( "The value of system.functions.operator().operator() Displays the results of the RAD operator() function This example requires the following sample data: l A valid Service Manager RAD function name (for example.functions.forms. Properties The following properties are valid for this object: Property RAD function name Methods None Example This example does the following: l l Required Description Yes This argument contains the RAD function name you want to bring into memory. Sets a variable equal to system.RAD function name( RAD function arguments ) Note: There are two exceptions to syntax used for RAD functions: delete and null l l system. Arguments The following arguments are valid for this object: Argument RAD function arguments Data type String Required Description Yes This argument contains any arguments required to execute the RAD function._delete( RAD function arguments ) system. Usage system.functions.forms.functions This JavaScript object is unique to HP Service Manager. operator()) var operator = system.30) .functions._null( RAD function arguments ) Note: Service Manager global system objects do not have constructors. scmsg( message number. "km" class record 14 "Group %S and Profile %S are already in category %S") var msgrecord = "14". message elements ) Note: Service Manager global system objects do not have constructors. This argument contains the variable message elements indicated by %S in the message record. String Yes String Yes Array No Sets variables to define the message record Calls the RAD function scmsg() Displays the results of the RAD function scmsg() This example requires the following sample data: l A valid Service Manager message record (for example. Arguments The following arguments are valid for this object: Argument message number message class message elements Properties None Methods None Return values A string containing the complete message text indicated by the arguments. The system.operator() is:\n" + operator ).Programming Guide Chapter 6: JavaScript and Service Manager reference print( "The value of system.30) . Page 204 of 396 HP Service Manager (9.functions.functions. Example This example does the following: l l l Data type Required Description This argument contains the Service Manager message number you want to call into memory. var msgclass = "km". This argument contains the Service Manager message class you want to call into memory.scmsg object allows you to call a particular Service Manager message record from JavaScript. JavaScript object: system.functions. Usage system. message class.functions.scmsg The following JavaScript object is unique to HP Service Manager. push( "New Profile Name" ). Arguments The following arguments are valid for this function: Argument function arguments Data type String Required Description Yes This argument contains the function arguments you want to use. var result = system. This argument contains the function name you want to run. Page 205 of 396 HP Service Manager (9. arguments.30) .library. testArray. arguments ) ). The system.functions. Usage system. msgclass.function name( function arguments ) Note: Service Manager global system objects do not have constructors.contains(testArray. arguments.Programming Guide Chapter 6: JavaScript and Service Manager reference var arguments = new Array().ArrayUtil.library object allows you to call a particular Service Manager script library function.library. Properties The following properties are valid for this object: Property script name Required Description Yes This argument contains the script name you want to run. print( system. JavaScript object: system.scmsg( msgrecord.push("Blue"). arguments. "Blue"). function name No Methods None Example This example does the following: l l Creates an array Calls a script to check if a value is in the array var testArray = new Array().push("Pink").script name.library The following JavaScript object is unique to HP Service Manager.push( "Category Name" ). print("The value you specified is in the array: " + result). testArray.push( "New Group" ). record is:\n" + r ).record The following JavaScript object is unique to HP Service Manager. The system. Arguments There are no arguments for this object. Methods None Example This example does the following: l l Sets a variable equal to system.record. Arguments There are no arguments for this object.record Displays the results of system.record object allows you to call the current Service Manager record into memory. Usage system. JavaScript object: system. Page 206 of 396 HP Service Manager (9. The system. print( "The value of system.oldrecord var o = system.record is:\n" + o ).oldrecord Note: Service Manager global system objects do not have constructors.oldrecord. Properties There are no properties for this object.30) . Usage system.oldrecord Displays the results of system.oldrecord The following JavaScript object is unique to HP Service Manager.record r = system.oldrecord object allows you to call the last Service Manager record into memory.record Note: Service Manager global system objects do not have constructors. Methods None Example This example does the following: l l Sets a variable equal to system.Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript object: system. Properties There are no properties for this object. print( "The value of system. The system.threads Displays the results of system. Properties There are no properties for this object. Usage system.sysinfo The following JavaScript object is unique to HP Service Manager. Arguments There are no arguments for this object.sysinfo object allows you to call an XML list of properties about the Service Manager server.sysinfo Displays the results of system.sysinfo. The system. Arguments There are no arguments for this object. print( "The value of system. Properties There are no properties for this object.threads The following JavaScript object is unique to HP Service Manager. Methods None Example This example does the following: l l Sets a variable equal to system.sysinfo var s = system. JavaScript object: system.threads is:\n" + s ).30) . Usage system.sysinfo Note: Service Manager global system objects do not have constructors.threads Note: Service Manager global system objects do not have constructors.threads object allows you to call an XML list of the current Service Manager threads into memory. Methods None Example This example does the following: l l Sets a variable equal to system.threads Page 207 of 396 HP Service Manager (9.Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript object: system. users object allows you to call an XML list of the currently logged on Service Manager users into memory. The system. Methods None Example This example does the following: Page 208 of 396 HP Service Manager (9.user var u = system. Usage system.threads.user object allows you to call an XML list of properties of the currently logged on Service Manager user. Arguments There are no arguments for this object. Properties There are no properties for this object.user is:\n" + u ).Programming Guide Chapter 6: JavaScript and Service Manager reference var th = system. Properties There are no properties for this object. print( "The value of system.users Note: Service Manager global system objects do not have constructors.user Displays the results of system.user Note: Service Manager global system objects do not have constructors.users The following JavaScript object is unique to HP Service Manager. print( "The value of system. Methods None Example This example does the following: l l Sets a variable equal to system.user The following JavaScript object is unique to HP Service Manager. Arguments There are no arguments for this object.user. Usage system. The system. JavaScript object: system.threads is:\n" + th ). JavaScript object: system.30) . Properties The following properties are valid for this object: Property variable name Methods None Example This example does the following: l l Required Description Yes This argument contains the variable name you want to bring into memory. Usage system. $L_file) var v = system. You can invoke global methods directly just as you would do with any core JavaScript global functions such as parselnt() or eval().vars object is unique to HP Service Manager.vars.30) .users Displays the results of system. Sets a variable equal to system.vars.Programming Guide Chapter 6: JavaScript and Service Manager reference l l Sets a variable equal to system.vars. print( "The value of system.$L_file.$L_file Displays the contents of the $L_file variable This example requires the following sample data: l A valid Service Manager variable name (for example. JavaScript object: system.vars.vars The system. This is a complete list of all the global methods available in HP Service Manager. Global method Description Page 209 of 396 HP Service Manager (9. print( "The value of system.vars object allows you to call a particular Service Manager variable into memory. List: JavaScript global methods Global methods are functions that are available to any script as they are not methods of any specific object.users u = system. The system.variable name Note: Service Manager global system objects do not have constructors.$L_file is:\n" + v ).users is:\n" + u ). Arguments There are no arguments for this object.users. Takes HTML content and strips out the HTML tags and returns the content as text without the HTML tags. makeSCWebURL print Quit RCtoString readFile stripHtml writeAttachmentToFile Writes a requested attachment record to the local file system. Validates the syntax of the specified JavaScript. Converts a JavaScript string to an XML string. Return values A binary or string object containing the original data. Converts binary data to a base 64 string format. Issues an HTTP request to a specified URL. Reads data from the local file system. Description Page 210 of 396 HP Service Manager (9.30) . This method performs the specified process or program. Arguments The following arguments are valid for this function: Data Argument type data Binary Required Description Yes This argument contains the data you want the script to decode to its original format. Issues an SOAP request to a specified URL. Creates a URL query to the Service Manager Web tier. Allows JavaScript to abort processing and return a failure return code.Programming Guide Chapter 6: JavaScript and Service Manager reference base64Decode base64Encode compile doHTTPRequest doSOAPRequest execute help Converts base 64 string data to its original format. Displays a brief description of a Service Manager-defined JavaScript object. Displays a message in the client Messages view. Converts a Service Manager global return code value into a localized text string. Syntax base64Decode( data ). JavaScript global method: base64Decode Converts base 64 string data to its original format. writeFile xmlstring Writes data to the local file system. print( "Wrote " + decodedFile + " bytes to C:\\newImage. "t" ). Syntax base64Encode( data ).txt" ). "b". var encode = base64Encode( source ). var decode = base64Decode( source ). Return values A string object containing the data in base 64 format.gif".gif" ). var decodedFile = writeFile( "C:\\newImage. an image file) var source = readFile( "C:\\header_left. Example This example does the following: l l l l l l l l Reads the contents of a binary file Converts the file to a base 64 string format Writes the base 64 string data to a local file Prints the number of bytes written to the local file system Reads the contents of a base 64 string format file Converts the data into a binary file Writes the binary data to a local file Prints the number of bytes written to the local file system This example requires the following sample data: l A binary file on the local file system (for example. var encodedFile = writeFile( "C:\\base64EncodedImage. Page 211 of 396 HP Service Manager (9.gif".txt". Arguments The following arguments are valid for this function: Data Argument type data Binary Required Description Yes This argument contains the data you want the script to encode in base 64 format.Programming Guide Chapter 6: JavaScript and Service Manager reference This method converts data in base 64 string format to its original format. You can also use this method to encode plain text data in base 64 format. JavaScript global method: base64Encode Converts binary data to a base 64 string format. print( "Wrote " + encodedFile + " bytes to C:\\base64EncodedImage. Description This method converts binary data to a base 64 string format. encode ). source = readFile( "C:\\base64EncodedImage. "b". "b" ).30) . decode ).txt". description String No Return values A success or error message.gif". Example This example does the following: l l Creates a variable to store a JavaScript name Validates the contents of the script This example requires the following sample data: l A valid JavaScript Page 212 of 396 HP Service Manager (9. an image file) var source = readFile( "C:\\header_left. Use this argument to store any comments you want. Throws None Description This method validates the syntax of a JavaScript and displays a message as to the success or failure of the validation.30) . description ). print( "The value of encode is:\n" + encode ). JavaScript global method: compile Validates the syntax of the specified JavaScript. Syntax compile( script.Programming Guide Chapter 6: JavaScript and Service Manager reference Example This example does the following: l l l Reads the contents of a binary file Converts the file to a base 64 string format Prints the base 64 string This example requires the following sample data: l A binary file on the local file system (for example. var encode = base64Encode( source ). This method is an alias of the execute() method. Arguments The following arguments are valid for this function: Argument script Data type String Required Description Yes This argument contains the name of the script you want to validate. "b" ). This method displays the message "Successful compilation of JavaScript function or expression" if the JavaScript passes validation. POST. The WSDL2js function uses the doHTTPRequest method at line 114 as part of a try/catch statement. PUT. This argument specifies the URL to which the script should send an HTTP request. Page 213 of 396 HP Service Manager (9. We support GET. This argument contains the body of a POST command request. and DELETE. "Testing execute" ). URL. If the HTTP request requires SSL then the URL must start with https. This argument contains a JavaScript array of Service Manager-defined Header objects or an empty array. and POST body) Arguments The following arguments are valid for this function: Data Argument type HTTP command URL Required Description This argument specifies a command verb. See "JavaScript object: Header" (on page 232) for more information. This example requires the following sample data: l The URL to the Service Manager Web services API // Use the following url value to produce an HTTP 400 error. JavaScript global method: doHTTPRequest Issues an HTTP request to a specified URL.Programming Guide Chapter 6: JavaScript and Service Manager reference var s = "lib. Example This example does the following: l l l Sends an HTTP request to the Service Manager Web services API If successful.SCFILEgetTextTest" compile( s. Description This method sends an HTTP request to a remote server. displays the HTTP error message Note: To see a working example of the doHTTPRequest method that incorporates multiple error checking conditions. open the SOAP script in the script library. Headers. HEAD. String Yes String Yes Headers Array Yes POST body String No Return values A string containing an HTTP response or an error message. Syntax doHTTPRequest (HTTP command. writes the response to a local file If unsuccessful.30) . SOAP user ID. var WSDLrequest. XML. "text". Syntax doSOAPRequest( URL. This argument contains the password value to be SOAPAction XML String String Yes Yes SOAP user ID String No SOAP password String No Page 214 of 396 HP Service Manager (9.10 ). reply = writeFile( "C:\\IncidentManagement. SOAP password.).wsdl". print( "The result of the doHTTPRequest is \n" + WSDLrequest ).30) . null. } JavaScript global method: doSOAPRequest Issues a SOAP request to a specified URL.wsdl". Parameters The following arguments are valid for this function: Argument URL Data type String Required Description Yes This argument specifies the URL to which the script should send an HTTP request. Connect Timeout. Obsolete. url. // Use the following url value to produce valid WSDL. 10 . SOAPAction. var reply. headers. var headers = new Array(). This argument contains the user ID to be used for the Basic Authorization HTTP header.wsdl". try { WSDLrequest = doHTTPRequest( "GET". Refer to the Web Service's WSDL to determine the proper format of the SOAP request. This argument contains the XML for an entire SOAP request including the SOAP envelope. } catch ( e ) { print( "WSDL request failed with exception \n" + e ). var url = "http://localhost:13080/SM/7/IncidentManagement. This argument specifies the SOAPAction value. Attachment object.Programming Guide Chapter 6: JavaScript and Service Manager reference //var url = "http://localhost:13080/IncidentManagement. AcceptFastInfoset. WSDLrequest ). If the HTTP request requires SSL then the URL must start with https. 10. Read Timeout. cdyne. var xml = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/2001/XMLSchema\" xmlns:s0=\"http://ws.cdyne.cdyne. Description This method sends a SOAP request to a remote server and returns the SOAP response.w3. Examples Example 1 : l Sends a SOAP request to a delayed stock quote Web service and indicates SM accept the "fastinfoset" formatted SOAP message Prints the SOAP response to the screen l This example requires the following sample data: l l The URL to a delayed stock quote Web service Stock symbol for company var url = "http://ws.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www. var action = "http://ws. This argument specifies the number of seconds a SOAP request has to read data before it times out.w3.cdyne. This argument is obsolete. To set the SOAP Message flag "acceptfastinfoset".Programming Guide Chapter 6: JavaScript and Service Manager reference used for the Basic Authorization HTTP header. Connect Timeout Number No This argument specifies the number of seconds a SOAP request has to establish a connection before it times out. To turn "acceptfastinfoset" off: 0. See "JavaScript object: Attachment" (on page 228) for more information. Default value is 1.asmx".com/delayedstockquote/delayedstockquote.30) . This argument contains a JavaScript array of Service Manager-defined Attachment objects or an empty array.com/GetQuote". Read Timeout Number No Obsolete Attachment object Number No Array No AcceptFastInfoset Number No Return values A string containing a SOAP response or an error message.org/soap/envelope/\" xmlns:xsi=\"http://www.com/\"> <StockSymbol xsi:type=\"s:string\">GOOG</StockSymbol> <LicenseKey xsi:type=\"s:string\">0</LicenseKey> </GetQuote> Page 215 of 396 HP Service Manager (9.com/\"> <soap:Body> <GetQuote xmlns=\"http://ws. var pass = null.w3.asmx".xmlsoap. uid. uid. var quote = doSOAPRequest( url. JavaScript global method: execute Validates the syntax of the specified JavaScript. null.cdyne.org/2001/XMLSchema\" xmlns:s0=\"http://ws.w3. var action = "http://ws. Prints the SOAP response to the screen l This example requires the following sample data: l l The URL to a delayed stock quote Web service Stock symbol for company var url = "http://ws. 60. var attachments = new Array(). var uid = null. action. xml. description ). Page 216 of 396 HP Service Manager (9. Example 2: l Sends a SOAP request to a delayed stock quote Web service and indicates SM does not accept the "fastinfoset" formatted SOAP message. print( "The return value is: " + quote ). var pass = null. 60. var xml = "<soap:Envelope xmlns:soap=\"http://schemas.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www. and then runs it. var quote = doSOAPRequest( url. null. attachments ).com/\"> <StockSymbol xsi:type=\"s:string\">GOOG</StockSymbol> <LicenseKey xsi:type=\"s:string\">0</LicenseKey> </GetQuote> </soap:Body></soap:Envelope>". 60. var uid = null.org/soap/envelope/\" xmlns:xsi=\"http://www.com/GetQuote". pass.cdyne. Syntax execute( script.cdyne. print( "The return value is: " + quote ). 0 ). pass.cdyne.Programming Guide Chapter 6: JavaScript and Service Manager reference </soap:Body></soap:Envelope>". attachments. 60.30) . action.com/\"> <soap:Body> <GetQuote xmlns=\"http://ws.com/delayedstockquote/delayedstockquote. var attachments = new Array(). xml. Throws None Description This method validates the syntax of a JavaScript.30) . Return values A string or null. This method displays the message "Successful compilation of JavaScript function or expression" if the JavaScript passes validation. JavaScript global method: help Displays a brief description of a Service Manager-defined JavaScript object. Page 217 of 396 HP Service Manager (9. Use this argument to store any comments you want. description String No Return values A success or error message. The method also displays a message as to the success or failure of the validation. Example This example does the following: l l l Creates a variable to store a JavaScript name Validates the contents of the script Runs the script This example requires the following sample data: l A valid JavaScript var s = "lib.SCFILEgetTextTest" execute( s. "Testing execute" ). and then runs it. Syntax help( object ). Arguments The following arguments are valid for this function: Argument Data type object Service Managerdefined JavaScript object Required Description Yes This argument contains the Service Managerdefined JavaScript object for which you want a brief description.Programming Guide Chapter 6: JavaScript and Service Manager reference Arguments The following arguments are valid for this function: Argument script Data type String Required Description Yes This argument contains the name of the script you want to validate. table name. Example This example displays the help contents of several Service Manager-defined JavaScript objects. Syntax makeSCWebURL( Web tier URL. print( help( f ) ). docEngine. action). String Yes docEngine String Yes table name query String Yes String Yes hash key seed String No Page 218 of 396 HP Service Manager (9. query. This argument specifies an optional string you want to use to create a unique hash key. You must use the print() method to see the help text string. print( help( x ) ). You must URI encode the query string to prevent special characters from invalidating the URL. Throws None Description This method displays a brief description of a Service Manager-defined JavaScript object. This argument specifies the table where the Document Engine should query for records. var d = new XMLDate(). This argument does not accept any other string value. Arguments The following arguments are valid for this function: Data Argument type Web tier URL Required Description This argument specifies the fully qualified URL to the Service Manager Web tier. var f = new SCFile(). The hash key seed does not appear in the final URL produced. var x = new XML(). print( help( d ) ). This argument specifies the Service Manager query you want to use to search for records.Programming Guide Chapter 6: JavaScript and Service Manager reference This method returns a brief text string describing the Service Manager-defined JavaScript object or null if there is no help available. This URL must include the http:// protocol syntax as well as the server name or IP address and communications port number. JavaScript global method: makeSCWebURL Creates a URL query to the Service Manager Web tier. This argument specifies that the query should be handled by the Service Manager Document Engine. hash key seed.30) . It does not convert any special characters in the URL (such as spaces or quotation marks) to the character code equivalent in URI format. doceng. query) { var var var var var var url. doceng = "docEngine". action. webserver = "http://pdoref02/sc/index. print( "Converted: old query='" + query + "' new query='" + queryURI + "'" ). Example This example does the following: l l Creates a URL query to the Service Manager Web tier Converts any special characters in the URL to valid URI format This example requires the following sample data: l l l The URL to Service Manager Web tier A valid Service Manager table name (for example.30) . webtier. By default. print( "Parameters: table=" + table + "query='" + query + "'"). hashkey." ). incidents) A valid Service Manager query against the table (for example.. incident. You can use the encodeURIComponent method to convert any special characters in the URL. Description This method creates a URL query to the Service Manager Web tier. Return values A string containing a URL query to the Service Manager Web tier. queryURI = encodeURIComponent( query ). hashkey = "".id="SD1001") function createURLquery( table. print( "Converting special characters in query to valid URI format. webserver.do".. the URL query applicable always performs a search operation.Programming Guide Chapter 6: JavaScript and Service Manager reference action String Not This argument cannot be used. Page 219 of 396 HP Service Manager (9. You must enclose literal text strings in quotation marks. Example This example does the following: Page 220 of 396 HP Service Manager (9. url=encodeURIComponent(webtier). String Yes Return values None Throws None Description This method displays the contents of the method argument in the Messages view and also prints it in the Service Manager log file. table. JavaScript global method: print Displays a message in the client Messages view and prints it in the Service Manager log file. return url. Note: Messages only print to the Service Manager log file when JavaScript is running in the background. Syntax print( output ). Arguments The following arguments are valid for this function: Data Argument type output Required Description This argument contains the text string or variable value you want the script to print to the Message View and the sm." ). "abc"). print( "Creating URL from information provided. action.log file. print( "The value of url is:\n" + url ).30) . print( "The value of webtier is:\n" + webtier ). doceng. SCquery). } var tablename = "incidents" var SCquery = "incident. hashkey.id=\"SD1001\"" createURLquery( tablename.Programming Guide Chapter 6: JavaScript and Service Manager reference action = "". queryURI.. webtier = makeSCWebURL( webserver.. Quit( -1 ). Any JavaScript code after the Quit() method is ignored. Example This example does the following: l l Prints a message Quits and returns a failure return code print( "Testing the Quit() method. Syntax RCtoString( return code ). JavaScript global method: RCtoString Converts a Service Manager global return code value into a localized text string.30) .. Page 221 of 396 HP Service Manager (9. print( "You won't see this message because the JavaScript has already quit" )." ). Syntax Quit( return code ). print("The value of example is: " + example).Programming Guide Chapter 6: JavaScript and Service Manager reference l l Creates a variable with a string value Displays the contents of the variable This example requires the following sample data: l A text string var example = "abc123". JavaScript global method: Quit Allows JavaScript to abort processing and return a failure return code. Integer Yes Return values A failure return code Throws None Description This method stops the processing of JavaScript from the point it is called and returns the failure return code specified in the return code argument.. Arguments The following arguments are valid for this function: Data Argument type return code Required Description This argument contains the numeric return code you want the script to return upon ending. doSelect( "contact. CONTACT". "ADMINISTRATOR. SYSTEM") A invalid contact name (for example. CONTACT") var contactName. SYSTEM". var findContact = contactList. return null } } contactName = "ADMINISTRATOR. " + RCtoString( findContact ) ).name=\""+ name + "\"" ) if ( findContact == RC_SUCCESS ) { print( "Success.30) .getText() ). "NOT A. contactName = "NOT A. Integer Yes Return values A localized text string Throws None Description This method converts a Service Manager global return code value into a localized text string.Programming Guide Chapter 6: JavaScript and Service Manager reference Arguments The following arguments are valid for this function: Data Argument type return code Required Description This argument contains the Service Manager global return code value you want to convert to a localized string. return contactList } else { print( "Could not find contact. found " + name + " in contact record:\n" + contactList. findContactName( contactName )." ). function findContactName( name ) { print( "Searching for contact: " + name + ".. Page 222 of 396 HP Service Manager (9. Example This example does the following: l l Searches the contacts table for any contact name you define in the search variable Displays the contact record as a text string This example requires the following sample data: l l A valid contact name (for example. var contactList = new SCFile( "contacts" ).. String Yes binary String Yes Return values A string object containing the contents of the file. Syntax readFile( path.Programming Guide Chapter 6: JavaScript and Service Manager reference findContactName( contactName ). print( "The value of binFile is: " + binFile ). Arguments The following arguments are valid for this function: Data Argument type path Required Description This parameter contains the text string or variable value containing the fully qualified path of the file to be read. var binFile = readFile( "C:\\header_left. The file can be in binary format or text format as determined by the binary argument. JavaScript global method: stripHtml Takes HTML content and strips out the HTML tags and returns the content as text without the HTML tags. JavaScript global method: readFile Reads data from the file system on the Service Manager server host.30) . print( "The value of textFile is: " + textFile ). binary ). Syntax Page 223 of 396 HP Service Manager (9. Description This method reads the contents of a local file and returns a string object.gif". You must enclose literal text strings in quotation marks. Example This example does the following: l l Reads the contents of a text file Reads the contents of a binary file This example requires the following sample data: l l A text file on the local file system A binary file on the local file system var textFile = readFile( "C:\\test. "t" ).xml". Use any other value to read a text file. Use the string "b" or "B" to read a binary file. This parameter determines if the file format is binary or text. "b" ). You may also use this argument to specify the destination path of the attachment. This argument specifies the application name portion of the key that Service Manager uses to identify the attachment in the SYSATTACHMENTS table. Example var htmlstr = "<html><body>Hello</body></html>". Application. String Yes Returns JavaScript String without HTML tags. JavaScript global method: writeAttachmentToFile Writes a requested attachment record to the local file system. Arguments The following arguments are valid for this function: Data Argument type htmlstr Required Description This argument contains the JavaScript String with HTML tags that you want to strip out of the string. UID ).30) .Programming Guide Chapter 6: JavaScript and Service Manager reference stripHtml(htmlstr). If this argument does not specify a path. Topic. var text = stripHtml(htmlstr). This argument specifies the topic name portion of the key that Service Manager uses to identify the attachment in the SYSATTACHMENTS table. Syntax writeAttachmentToFile( File. print("after stripping HTML tags: " + text). Service Manager creates the attachment in the system working directory. print("before stripping HTML tags: " + htmlstr). String Yes Application String Yes Topic String Yes Page 224 of 396 HP Service Manager (9. Throws None Description Takes HTML content and strips out the HTML tags and returns the content as text without HTML tags. Arguments The following arguments are valid for this method: Data type Name File Required Description This argument specifies the file name of the attachment you want to write out to the file system. Return values RC_SUCCESS or one of the other global return code values. } else { print( "kmdocument.pdf".pdf Prints the return code to the screen This example requires the following sample data: l l The Knowledge Management record KM0018 An attachment in KM0018 var rc.pdf failed " . "KM0018". Arguments Page 225 of 396 HP Service Manager (9. Syntax writeFile( path.pdf successfully created" ). object ).30) .Programming Guide Chapter 6: JavaScript and Service Manager reference UID String Yes This argument specifies the unique identifier portion of the key that Service Manager uses to uniquely identify the attachment in the SYSATTACHMENTS table. "4462590a062ee0c2101d85c8" ). mode. Note: If you specify a path. The method writes the attachment record specified in the method arguments to the local file system and returns a global return code value of RC_SUCCESS or returns one of the failure global return code values if the method cannot return an attachment record. Example This example does the following: l l l Requests an attachment from the SYSATTACHMENTS table Writes the attachment to the file c:\kmdocument. Description This method extracts the specified attachment from the SYSATTACHMENTS table and writes it to the specified file and path on the local file system. RCtoString(rc) ). } JavaScript global method: writeFile Writes data to the local file system. rc = writeAttachmentToFile( "c:\\kmdocument. you must escape out any JavaScript reserved-characters in the path name such as slashes and backslashes. Consult a JavaScript reference for a full list of JavaScript reserved-characters and escape methods. if ( rc == RC_SUCCESS ) { print( "kmdocument. "kmdocument". Use the string "a" to append to a text file. isMode = null. Use the string "ba" to append to a binary file.users. return output } filePath = "C:\\users. binary. object ) { print( "Writing " + path + " to file. var var var var function writeToFile( path. isMode.xml".30) .. fileObject = userList. fileObject ). This is the default.users userList = system. isMode.Programming Guide Chapter 6: JavaScript and Service Manager reference The following arguments are valid for this function: Data Argument type path Required Description This argument contains the text string or variable value containing the fully qualified path of the file to be written." ). print( "The number of bytes written to file was: " + output ). Use any other string or omit the parameter to write to a text file. The file can be in binary format or text format as determined by the binary parameter. This parameter contains the text string or variable value containing the data you want to write to a file. mode. object ).. Use the string "b" to write a binary file. The values are case sensitive and only the values specified are valid. You must enclose literal text strings in quotation marks. Example This example does the following: l Writes the list of currently logged on users to a file This example requires the following sample data: l The list of currently logged on users stored in system. Page 226 of 396 HP Service Manager (9. Description This method writes the contents of the object parameter to the file specified in the path parameter. fileObject. writeToFile( filePath. String Yes mode String No object String Yes Return values A number representing the number of bytes written to a file. filePath. var output = writeFile( path. users ). When an object is initialized in RAD and then passed to JavaScript. the object becomes a Datum object and all the methods return true/false values. This object converts a Datum to a SCDatum so that you can test the results by using the return codes. Defined object Attachment Description This object allows you to create attachments for use with doSOAPRequest methods. update. Datum SCDatum SCFile Page 227 of 396 HP Service Manager (9.Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript global method: xmlstring This method converts a JavaScript string to an XML-formatted string. Service Manager defined JavaScript objects The defined objects are unique to the implementation of JavaScript within Service Manager. This object extracts aggregate types of data (structures or arrays) from a record in the file object.30) . In Service Manager. This object constructs a new file object. String No Return values None Throws None Example var xmldoc = new SCFile( system. a file record is a datum and so is each component of the record. print( xmldoc ). you can create a SCDatum object from the Datum object. Syntax xmlstring( string ). xmlstring( xmldoc ). You can use the SCFile object to access. and move between Service Manager files. If an error occurs and you want a more specific error message. Arguments The following arguments are valid for this function: Data Argument type string Required Description This argument contains the text string or variable value you want the script to convert to an XML string. This object exposes a small set of frequently used return code constants that make it easy to test values returned by methods without having to hard code return code values in the script. This is a complete list of the Service Manager defined objects. 30) . You may find that in certain instances the XML object in Service Manager is not compliant with the DOM binding for JavaScript. The Query object can not be used to write data back to Service Manager. SCRecordList has two available functions: getPosition() and getCount(). you can use the readFile global method to assign the value property. For binary data attachments. These include the following constructors: XMLDate( dateobject ). – it passes a JavaScript Date object to the constructor. datetime. JavaScript object: Attachment The following JavaScript object is unique to HP Service Manager. It is used in conjunction with the Query object to define the parameters for returning data from Service Manager. Query This object returns an array of records. or duration string to the constructor. time.Programming Guide Chapter 6: JavaScript and Service Manager reference SCRecordList This object is an array of Datums that qualify with the query. – it passes an XML schema date. the File and SCDoc objects are deprecated. HP strongly recommends that you do not use these objects since they may be removed in a future release. XMLDate( iso8601datetimeordurationstring ). The QueryCond object is similar to setConst method. you can use the push method to add each Attachment object to a JavaScript array. Constructor new Attachment(). XMLDate( datetimedatum ) – it passes a Service Manager datum object of type TIME to the constructor. Arguments None Properties The following properties are valid for this object: Property Data type Description Page 228 of 396 HP Service Manager (9. You have to manually define the value property of each attachment object. Underlying the XML object is the Document Object Model (DOM) object. QueryCond XML XMLDate Note: In ServiceCenter version 6. If you need to create multiple attachments for a doSOAPRequest request. This object allows you to create attachments for use with doSOAPRequest methods.1. This object makes it possible to do conversions between three kinds of datetime values. This object represents an XML document or a node in an XML document. This object defines the conditions of the query. This is a read only property. If present and the property has a value of "img.Programming Guide Chapter 6: JavaScript and Service Manager reference value Binary or String Use this property to store the binary or string data of the attachment.30) . len href Integer This property contains the file size of the attachment in bytes. etc.txt". The obtained string date then can be printed. The following options are available: l l l l action String add – adds the specified attachment remove – removes the specified attachment get – retrieves the specified attachment update – updates the specified attachment name type String String Use this property to store the file name of the attachment. into IM10005 This example requires the following sample data: l A binary file (for example. attachmentType String stringValue String Methods None Example l l l l l This example does the following: Assume there are two attachments in the incident IM10005 Get the existing attachments from the IM10005 Concatenate these two attachments to a string Create a new attachment which contains the concatenated string value Insert this new attachment. user can use this property to get the string data of the attachment. When the attachment object contains a text value (utf-8 or ascii characters). Use this property to store the name of action to take with the attachment in the Service Manager Web Services API. an image) var f = new SCFile( 'probsummary' ). var rc = f." then the attachment must also have a MIME type of "image/gif". Use this property to store the MIME type of the attachment. named "MyAttachment. Use this property to store the attachment type as defined in Service Manager. concatenated.getAttachments(). String Use this property to store the unique identifier for the attachment in the SOAP request message.doSelect( 'number = "IM10005"' ). var attachmentObj = f. Page 229 of 396 HP Service Manager (9. length ). or array you want to query or update. Constructor new Datum(). print("Attachment Value: "+ attachmentObj[ attachment ]. print("AttachmentID: "+attachmentID). Properties None Methods Page 230 of 396 HP Service Manager (9.txt". str+= attachmentObj[ attachment ].length). structure. or array. print("Attachment Type: "+ attachmentObj[ attachment ]. } //Create new attachment with a concatenated value print("String Length: "+str. You must enclose table names and arrays in quotation marks.type = "text/plain". attachObj. Arguments The following arguments are valid for this object: Data Argument type Object String Description The Service Manager table name. record.stringValue. var attachObj = new Attachment(). for ( var attachment in attachmentObj ) { print("Attachment Name: "+ attachmentObj[ attachment ]. This JavaScript object was deprecated as of HP ServiceCenter 6.href ).name ).name = "MyAttachment.insertAttachment( attachObj ).stringValue . attachObj. the Datum() constructor creates a Service Manager-formatted Datum object containing the provided record. var attachmentID = f.stringValue ).type). With no parameters. print("Attachment HREF: "+ attachmentObj[ attachment ]. the Datum() constructor creates an empty Datum object.value = str. new Datum(Object). attachObj. With an Object parameter. structure. JavaScript object: Datum The Datum JavaScript object is unique to HP Service Manager.30) .1 because this object's methods can only return true or false boolean values. You can use the Datum object as a parameter for RTECall routines that expect Service Manager-formatted parameters.Programming Guide Chapter 6: JavaScript and Service Manager reference var str = "". print("Attachment Value Length: "+ attachmentObj[ attachment ]. You can use the SCFile or SCDatum objects in place of this object to take advantage of the improved return code values. This method checks if an object represents a current table and has a record. This method inserts an object into the database. This method returns a string of all the entries in the array. This method executes a method defined on the object. This method converts an object to a JavaScript array. This method moves to the last record if the object represents a result set. This method is synonymous with the doRemove method. This method moves to the next record if the object represents a result set. This method returns the object type.30) . This method moves to the previous record if the object represents a result set. This method returns a string of all the entries in the array. This method updates the database. This method adds an item to an array. This method simply has a more intuitive name.doAction(). This method removes an object from the database. This method makes a query. This method returns the size of the object. This method returns a string of all the entries in the array. length() getNext() getPrev() This method returns the length of the object. This method moves to the first record if the object represents a result set. getFirst() getLast() doSelect() isRecord() getType() doUpdate() doInsert() doRemove() doDelete() doAction() toArray() push() pop() join() shift() unshift() setType() setValue() Page 231 of 396 HP Service Manager (9. This method sets the object to a given value. getMessages() This method returns an array of messages generated by the Document Engine from a previous SCFile. This method removes an item from an array. This method returns an XML representation of the object. This method sets the object type. It no longer requires that the first argument be the name of the table if the object is constructed with the name of the table.Programming Guide Chapter 6: JavaScript and Service Manager reference The following methods are valid for this object: Defined method getText() getXML() getSize() Description This method returns a text representation of the object. Arguments The following arguments are valid for this object: Argument Header type Description The HTTP header type such as "Accept-Encoding" or "Content-Type". JavaScript object: Header The following JavaScript object is unique to HP Service Manager.name # "B") var q = new Datum( "contacts" ). if ( ( q.30) . Header value The HTTP header value such as "gzip.soSelect( "contact. This method returns a JavaScript Date object. the Header() constructor creates an empty Header object. JSDate() Example This example does the following: l l l Creates a Datum object from the contacts table Selects records from this contacts table starting with the letter B Displays the contacts matching the select query This example requires the following sample data: l A valid query against the contacts table (for example. Properties None Methods None Example Page 232 of 396 HP Service Manager (9. With the HTTP header arguments. You must enclose header types and header values in quotation marks.deflate" or "text/html". Constructor new Header().name # \"B\"" ) ) == true ) { print( q.Programming Guide Chapter 6: JavaScript and Service Manager reference doSave() This method inserts a record if it is new and updates the record if it already exists. contact. } else print( "No contacts start with B" ). new Header(Header type. Header value). the Header() constructor creates a Header object containing the provided header types and values. With no arguments.getText() ). structure.push( hd ). new SCDatum(object).Programming Guide Chapter 6: JavaScript and Service Manager reference This example does the following: l l l l l Creates a Header object using the Header type and Header value arguments Creates a second empty Header object Defines the properties of the second Header object Creates an empty JavaScript array Adds the two Header objects to the JavaScript array This example requires the following sample data: l A valid header var h = new Header( "Accept-Encoding". With no arguments. Constructor new SCDatum().deflate" ). structure. Arguments The following arguments are valid for this object: Data Argument type object String Description The table name. You must enclose table names and arrays in quotation marks. var headers = new Array().push( h ).value = "text/html". headers. var hd = new Header(). JavaScript object: SCDatum The following JavaScript object is unique to HP Service Manager.name = "Content-Type". hd. This object's methods use the Service Manager-defined global return codes. headers.30) . the SCDatum() constructor creates an empty SCDatum object. Page 233 of 396 HP Service Manager (9. hd. the SCDatum() constructor creates an SCDatum object containing the provided record. record. This object is an alias of the SCFile object. "gzip. Properties None Methods The following methods are valid for this object: JSDate() This method returns a JavaScript Date object. or array. With an object argument. or array you want to query or update. This method returns the object type. This method removes an item from an array. It no longer requires that the first argument be the name of the table if the object is constructed with the name of the table. This method moves to the previous record if the object represents a result set. This method sets the object to a given value.30) .Programming Guide Chapter 6: JavaScript and Service Manager reference getText() getXML() getSize() This method returns a text representation of the object. This method moves to the next record if the object represents a result set. length() getNext() getPrev() This method returns the length of the object. This method moves to the last record if the object represents a result set.doAction(). This method returns the size of the object. This method sets the object type. This method removes an object from the database. This method returns an array of messages generated by the Document getMessages() Engine from a previous SCFile. This method updates the database. This method returns a string of all the entries in the array. This method returns an XML representation of the object. This method inserts a record if it is new and updates the record if it already exists. This method inserts an object into the database. This method converts an object to a JavaScript array. This method checks if an object represents a current table and has a record. This method makes a query. This method simply has a more intuitive name. This method moves to the first record if the object represents a result set. This method returns a string of all the entries in the array. This method returns a string of all the entries in the array. This method returns a JavaScript Date object. This method adds an item to an array. This method executes a method defined on the object. This method is synonymous with the doRemove method. getFirst() getLast() doSelect() isRecord() getType() doUpdate() doInsert() doRemove() doDelete() doAction() toArray() push() pop() join() shift() unshift() setType() setValue() doSave() JSDate() Page 234 of 396 HP Service Manager (9. Arguments The following arguments are valid for this object: Argument object Data type String Description The table name. } else print( "Return code is: " + q. You must enclose table names and arrays in quotation marks. or array. JavaScript object: SCFile The following JavaScript object is unique to Service Manager.RCtoString ). structure. SCFILE_ Number Causes the file object to become read-only.Programming Guide Chapter 6: JavaScript and Service Manager reference Example This example does the following: l l l Creates an SCDatum object from the contacts table Selects records from this contacts table starting with the letter B Displays the contacts matching the select query This example requires the following sample data: l A valid query against the contacts table (for example. with the file name specified as the first parameter. This object's methods use the Service Manager-defined global return codes. the SCFile() constructor creates an SCFile object containing the provided record. This READONLY constant is only supported as a second parameter. new SCFile( object. record. With no parameters. new SCFile(object).getText() ). contact.name # "B") var q = new SCDatum( "contacts" ).doSelect( "contact. SCFILE_READONLY ).name # \"B\"" ) ) == RC_SUCCESS ) { print( q. the SCFile() constructor creates an empty SCFile object. or array you want to query or update. Constructor new SCFile(). With an object parameter. structure.30) . if ( ( q. Properties Page 235 of 396 HP Service Manager (9. Programming Guide Chapter 6: JavaScript and Service Manager reference None Properties None Methods The following methods are valid for this object: Defined method deleteAttachment() Description This method deletes a specific attachment associated with the current file record. This method executes a method defined on the object. This method makes a query. deleteAttachments() doAction() doCount() doDelete() doInsert() doPurge() doRemove() doSave() doSelect() doUpdate() getAttachment() getAttachments() getFirst() getLast() getLastRC() getMessages() getNext() Page 236 of 396 HP Service Manager (9. It no longer requires that the first argument be the name of the table if the object is constructed with the name of the table. This method moves to the last record if the object represents a result set. This method inserts a record if it is new and updates the record if it already exists. This method moves to the first record if the object represents a result set. This method simply has a more intuitive name. This method purges a set of records directly in the back-end RDBMS. This method removes an object from the database. This method returns an array of messages generated by the Document Engine from a previous doAction(). This method gets all of the attachments associated with the current file record. This method deletes all of the attachments associated with the current file record. This method moves to the next record if the object represents a result set. This method returns the number of records for the provided query. This method gets a specific attachment associated with the current file record.30) . This method updates the database. This method returns the last return code generated by the SCFile and SCDatum objects. This method is synonymous with the doRemove() method. This method inserts an object into the database. This method returns a string of all the entries in the array. This method causes any subsequent doSelect() calls to fetch only the specified fields. This method returns a string of all the entries in the array. This method returns a string of all the entries in the array. getPurgedRowCount() This method retrieves the number of records deleted from a table by the doPurge(). This method returns the length of the object. getSize() getText() getType() getXML() insertAttachment() This method returns the size of the object. This method updates a specific attachment associated with the current file record.30) .Programming Guide Chapter 6: JavaScript and Service Manager reference getPrev() This method moves to the previous record if the object represents a result set. This method creates a new attachment associated with the current file record. This method sets the object type. This method converts an object to a JavaScript array. This method returns a text representation of the object. isRecord() join() JSDate() length() pop() push() setFields() setRecord() setOrderBy() setType() setValue() shift() toArray() unshift() updateAttachment() Example This example does the following: Page 237 of 396 HP Service Manager (9. This method checks if an object represents a current table and has a record. This method sets the field values from a given XML string. This method returns the object type. This method returns an XML representation of the object. This method causes any subsequent doSelect() call on a SCFile object to fetch only the specified fields by the specified sort sequences of the SCFileObject. This method returns a JavaScript Date object. This method adds an item to an array. This method sets the object to a given value. This method removes an item from an array. Values passed to deleteAttachment() will normally be ones obtained from a previous insertAttachment(). Return values If successful. JavaScript method: SCFile.doSelect( "contact. it returns an error return code.Programming Guide Chapter 6: JavaScript and Service Manager reference l l l Creates an SCFile object from the contacts table Selects records from this contacts table starting with the letter B Displays the contacts matching the select query This example requires the following sample data: l A valid query against the contacts table (for example. etc. Otherwise. deleteAttachment() returns RC_SUCCESS.deleteAttachment( attachID ).30) . contact.deleteAttachment( attachID ) This method deletes a specific attachment associated with the current file record. you must establish a current record using one of the positioning methods.name # \"B\"" ) ) == RC_SUCCESS ) { print(q. Before calling deleteAttachment. it returns RC_NO_MORE if the attachment was not found. getNext(). Arguments deleteAttachment() takes one argument. such as doSelect(). Page 238 of 396 HP Service Manager (9.RCtoString ).getText()). if ( ( q. } else print( "Return code is: " + q. which is a string containing an attachment ID of the form "cid:xxxxx". or getAttachments() operation. Example This example does the following: l l Selects one record from the probsummary file Deletes one attachment associated with the current record This example requires the following sample data: l Record number IM10001 in the probsummary table function createTestAttachment() { var attachmentObj = new Attachment(). Syntax SCFile.name # "B") var q = new SCFile("contacts"). For example. updateAttachment(). 30) .deleteAttachments() Arguments deleteAttachments() takes no arguments and returns no arguments.deleteAttachment( attachmentID ). Return values If successful.doSelect( 'number = "IM10001"' ). var rc = f. var attachmentID = f. } var attachmentID = createTestAttachment().doSelect( 'number = "IM10001"' ). var f = new SCFile( 'probsummary' ).name = "MyAttachment. etc. var f = new SCFile( 'probsummary' ). attachmentObj. var rc = f.type = "text/plain". var rc = f. attachmentObj.txt". deleteAttachments() deletes all of the attachments associated with the current record. Syntax SCFile.value = "My text attachment". Before calling deleteAttachment. return attachmentID.insertAttachment( attachmentObj ). Page 239 of 396 HP Service Manager (9. you must establish a current record using one of the positioning methods.deleteAttachments() Deletes all of the attachments associated with the current file record. such as doSelect().Programming Guide Chapter 6: JavaScript and Service Manager reference attachmentObj. getNext(). Example This example does the following: l l l Selects one record from the probsummary file Deletes all attachments associated with the current record Displays the number of attachments associated with the current record This example requires the following sample data: l Record number IM10001 in the probsummary file var f = new SCFile( 'probsummary' ). JavaScript method: SCFile. Arguments The following arguments are valid for this method: Argument Data type Description docEngineAction String This argument specifies the Document Engine action you want the script to execute on the object.length ).deleteAttachments().doSelect( 'number = "IM10001"' ). // will be zero JavaScript method: SCFile. Syntax SCFile.getAttachments(). This argument must contain a valid Service Manager Document Engine action appropriate for the Service Manager object. assignmentValue.doAction( docEngineAction ). var attachments = f. Example This example does the following: l l Creates a new incident record from variable values Resolves the incident record This example requires the following sample data: l l The "Use Resolved Status?" option enabled in the Incident Management Environment record A valid value for the number field (for example. print( attachments. callbackContact. The method returns RC_SUCCESS if the method successfully runs the Document Engine action or returns one of the error global return code values if the method cannot run the Document Engine action. descriptionValue. "IM11112") numberValue. Return values RC_SUCCESS or one of the other global return code values. f. You must define a Service Manager file object and new values for required fields.Programming Guide Chapter 6: JavaScript and Service Manager reference var rc = f. categoryValue.30) . var var var var var Page 240 of 396 HP Service Manager (9.doAction() This method executes a Document Engine action using any new field values defined in a Service Manager file object. findIncident.. newIncident. cat.resolution = res. var resolutionValue. function insertIncident( num.Programming Guide Chapter 6: JavaScript and Service Manager reference var actionType. print( "The incident record is " + findIncident. var findIncident = new SCFile ( "probsummary" ).doAction( action ). var resultionCodeValue. res ) { print( "Resolving incident " + id + ". newIncident.category = cat.. print( "The resolve Incident return value is " + RCtoString( a ) ).callback_contact = name." ). return null } } function resolveIncident( id. if ( f == RC_SUCCESS ) { print( "Success. var newIncident = new SCFile( "probsummary" ).." ).problem_status ). name. rescode. if ( rc == RC_SUCCESS ) { print( "Success.number = num.30) . return null } } Page 241 of 396 HP Service Manager (9. Found interaction record. var rc = newIncident. " + RCtoString( rc ) ).getText() ) print( "The value of the status field is: " + findIncident.getText() ). newIncident." ).number } else { print( "Could not create record. " + RCtoString( f ) ). var f = findIncident. desc ) { print( "Creating new incident record.. return newIncident. Created new record " + newIncident.resolution_code = rescode.. newIncident.. action. group. return findIncident } else { print( "Could not find record.doInsert().description = desc. findIncident. newIncident. var a = findIncident.assignment = group.doSelect( "number=\"" + id + "\"" ). Note: You should not use this method on an SCFile object for which you have performed a previous doSelect() if you intend to iterate over the results of the doSelect(). Displays the contact record as a text string. function countContacts( location ) { Page 242 of 396 HP Service Manager (9. descriptionValue ). categoryValue. actionType. This example requires the following sample data: l l A valid contact name (for example. actionType = "resolve". resolveIncident( interactionID. SYSTEM"). CONTACT").doCount() This method returns the number of records specified by the query. "ADMINISTRATOR.Programming Guide Chapter 6: JavaScript and Service Manager reference numberValue = "IM11121" callbackContact = "ADMINISTRATOR. Arguments The following arguments are valid for this method: Data Argument type query Description String This argument specifies the query you want to use to search for Service Manager records. var contactName. resolutionValue ). SYSTEM". "NOT A. callbackContact. JavaScript method: SCFile. You must use the slash character to escape out quotation marks and any special characters restricted from JavaScript. assignmentValue = "HELPDESK". An invalid contact name (for example. descriptionValue = null. interactionID = insertIncident( numberValue.30) . resultionCodeValue.doCount( "query" ). resolutionValue = null. resultionCodeValue = "Advice & Guidance". Return values A number representing the count of records. assignmentValue. Example This example does the following: l l Determines the number of contact records. categoryValue = "network". Syntax SCFile. doDelete(). " + RCtoString( rc ) ). This method is a synonym of the doRemove() method.. var interactionRecord = new SCFile( "probsummary" )." ). if ( rc == RC_SUCCESS ) { return nCount. return -1. var rc = getLastRC().doCount( "location=\""+ location + "\"" ).. var nCount = contactList. The method returns RC_SUCCESS if the method successfully removes a record or returns one of the error global return code values if the method cannot remove the record. function removeInteraction( num ) { print( "Removing interaction record... } else { print( "Could not count records. Example This example does the following: l l Searches the probsummary table for any interaction record you define in the search variable Removes the interaction record This example requires the following sample data: l A valid value for the number field (for example. You must define a Service Manager file object and new values for fields." ).Programming Guide Chapter 6: JavaScript and Service Manager reference print( "Counting contacts at location: " + location + ". Arguments There are no arguments for this method. } } JavaScript method: SCFile. "IM11111") var numberValue.doDelete() This method removes a HP Service Manager record with any new field values defined in a Service Manager file object. Syntax SCFile. Return values RC_SUCCESS or one of the other global return code values. var contactList = new SCFile( "contacts" ). Page 243 of 396 HP Service Manager (9. and related to the more extensive doPurge()method.30) . doInsert() This method creates a Service Manager record with any new field values defined in a file object. return interactionRecord } else { print( "Could not remove record. Syntax SCFile. SYSTEM") A valid value for the category field (for example. return null } } numberValue = "IM11111" removeInteraction( numberValue ). print( "The interaction record is " + interactionRecord ).doSelect( "number=\"" + num + "\""). "network") var numberValue. Example This example does the following: l l Searches the probsummary table for any incident record you define in the search variable Displays the new incident record as a text string This example requires the following sample data: l l l A valid value for the number field (for example. Return values RC_SUCCESS or one of the other global return code values. var rc = interactionRecord. "ADMINISTRATOR. " + RCtoString( rc ) ).doDelete().Programming Guide Chapter 6: JavaScript and Service Manager reference var findRecord = interactionRecord.doInsert(). You must define a Service Manager file object and new values for the fields. Arguments There are no arguments for this method. JavaScript method: SCFile.getText() ). var callbackContact. if ( rc == RC_SUCCESS ) { print( "Success. Page 244 of 396 HP Service Manager (9.contact field (for example. "IM11111") A valid value for the callback. The method returns RC_SUCCESS if the method successfully creates a record or returns one of the error global return code values if the method cannot create the record.30) . Removed record " + interactionRecord. var categoryValue. categoryValue = "network". Service Manager respects workflow actions as defined in record level triggers. function insertContact( num. descriptionValue ).. name. Created new record " + newInteraction.. The doPurge() method is an alternative to doDelete() or doRemove().category = cat. return null } } numberValue = "IM11112" callbackContact = "ADMINISTRATOR.Programming Guide Chapter 6: JavaScript and Service Manager reference var descriptionValue. SYSTEM". Service Manager does not have control to process record level triggers on the data being purged. var newInteraction = new SCFile( "probsummary" ). JavaScript method: SCFile. It enables the back-end RDBMS to do most of the processing. callbackContact. insertContact( numberValue.30) . newInteraction.callback_contact = name. iterate over each record in the list and perform a “delete” on a record by record basis. Standard Service Manager trigger processing will not occur on these records.doInsert(). The doDelete() method requires you to select a list of records from the database. categoryValue. and it does not matter whether Service Manager triggers are processed. Page 245 of 396 HP Service Manager (9. As a result of the RDBMS processing the record set purge in one transaction.doPurge() This method enables you to purge a set of HP Service Manager records directly in the back-end RDBMS while bypassing record level processing. return newInteraction } else { print( "Could not create record. newInteraction. cat ) { print( "Creating new interaction record. " + RCtoString( rc ) )." ).getText() ). When the delete is performed. if ( rc == RC_SUCCESS ) { print( "Success. newInteraction. var rc = newInteraction. You should use doPurge() only when you need to quickly delete a large record set from a single Service Manager table. The doPurge() method reduces the overhead of much of this by sending one SQL statement to the RDBMS to purge the data. thereby improving execution times when deleting a large amount of data from a single table.number = num. doPurge( "query" ). Some issues to understand and consider before using this method: l Data referential integrity could be an issue by purging data that is related to other types of Service Manager data. Boolean values (true or false) or a QueryCond object are also acceptable. If you encounter such an error. You must use the slash character to escape out quotation marks and any special characters restricted from JavaScript. you will bypass normal workflow processing in addition to record level triggers. Service Manger deletes a set of records. This method does not execute normal record level workflow processing in the applications layer. Return values Returns RC_SUCCESS if successful and RC_ERROR on failure. When you turn off triggers and run doPurge(). or QueryCond object This argument specifies the query you want to use to search for Service Manager records. No Service Manager audit or other tracking is available to indicate changes made by doPurge(). Some examples of the errors you could encounter are: Oracle:SQL code=30036 message=ORA-30036: unable to extend segment by % in undo tablespace SQL Server SQL State: 42000-9002 Message: [Microsoft][SQL Native Client][SQL Server]The transaction log for database '%' is full DB2 SQL State: 57011--964 Message: [IBM][CLI Driver][DB2/NT] SQL0964C The transaction log for the database is full.30) . Consider coding your own audit mechanism. Use doPurge() with caution. the database could run out of space for this activity and cause an error. This causes a delete to the back-end database. SQLSTATE=57011 Syntax SCFile. Boolean.Programming Guide Chapter 6: JavaScript and Service Manager reference Warning: Purging data has some risks. Each supported database platform provides some type of transaction or undo log to back up data changes and allow a rollback in case of errors. Arguments The following arguments are valid for this method: Argument Description query String. DELETE FROM "SM_TABLE_NAME" WHERE "COLOUMN_NAME" = 'value'. When Service Manager attempts to delete a large set of records. l l You can retrieve the number of records deleted from a table by doPurge() by using the JavaScript method: getPurgedRowCount() Note: When you use doPurge(). No Service Manager rollback or undo is available after you run doPurge(). It is the equivalent of issuing a SQL statement to the RDBMS such as. please contact your database administrator and ask them to increase the size available for this purpose. The following conditions will cause a doPurge() failure: Page 246 of 396 HP Service Manager (9. ) No LDAP mapped fields The table must not have “delete” triggers defined and enabled Example This example does the following: l l Searches the kmknowledgebaseupdates table for records where docid="docid1" Deletes whatever it finds. it has no effect. it will return RC_SUCCESS. Arguments Page 247 of 396 HP Service Manager (9. getFirst. This method is a synonym of the doDelete() method. It requires defining a Service Manager file object. getPrev. in this case.doRemove(). Calling doPurge() with an SCFile object which has “delete” triggers defined and enabled. Syntax SCFile. var deleteRC = recordList.….doPurge("docid = \"docid1\""). JavaScript method: SCFile.doRemove() This method removes a single HP Service Manager record matching the field values defined in the Service Manager file object. and related to the more extensive doPurge()method.a2. var recordList = new SCFile(fileName). l l When the method fails. See the limitations below for supported types. Limitations Only simple SCFile relations are supported: l l l l l Must not be a join file or a merge file Must have only 1 main table alias (m1) Must not have any alias tables (a1. To remove multiple records use the doSelect method to store a record list as a JavaScript object. or GetLast methods to bring a particular record into memory for removal. However. This example requires the following sample data: l Records in kmknowledgebaseupdates table where docid = "docid1" var fileName = "kmknowledgebaseupdates".30) . it will default to a “false” query and no records will be deleted.Programming Guide Chapter 6: JavaScript and Service Manager reference l l l l Calling doPurge() on an uninitialized SCFile or a read-only SCFile Calling doPurge() with an empty query argument Calling doPurge() with an invalid argument type (not a string) Calling doPurge() with one (or more) invalid (or unmapped) fields. Calling doPurge() with an unsupported complex type SCFile relation. A basic validation is performed on the field names to ensure they exist in the DBDICT. This validation will not cause a failure of the method. and then use the getNext. if ( rc == RC_SUCCESS ) { print( "Success. Page 248 of 396 HP Service Manager (9..doSave() This method adds to or updates the Service Manager database with any new field values defined in a Service Manager file object. var interactionRecord = new SCFile( "probsummary" ). Syntax SCFile.30) . return interactionRecord } else { print( "Could not remove record. It requires defining a Service Manager file object and defining new values for fields. return null } } numberValue = "IM11111" removeInteraction( numberValue ). "IM11111") var numberValue.doRemove(). Example This example does the following: l l Searches the probsummary table for any interaction record you define in the search variable Removes the interaction record This example requires the following sample data: l A valid value for the number field (for example." ). The method returns RC_SUCCESS if the method successfully removes a record or returns one of the error global return code values if the method cannot remove the record. Removed record " + interactionRecord.. function removeInteraction( num ) { print( "Removing interaction record. var rc = interactionRecord. Return values RC_SUCCESS or one of the other global return code values.getText() ).doSelect( "number=\"" + num + "\""). print( "The interaction record is " + interactionRecord ).Programming Guide Chapter 6: JavaScript and Service Manager reference There are no arguments for this method. " + RCtoString( rc ) ). Arguments There are no arguments for this method. JavaScript method: SCFile.doSave(). var findRecord = interactionRecord. var isContact = contactList..doSave().." )." ). print( "The contents of the user. set the "user.doSelect( "contact.30) . contactList. return contactList } else { print( "Could not find contact. SYSTEM") A valid field value update (for example. found " + name + " in contact record:\n" + contactList.type" field to "site") var contactName. Page 249 of 396 HP Service Manager (9. " + RCtoString( isContact ) ). The method returns RC_SUCCESS if the method successfully updates a record or returns one of the error global return code values if the method cannot update the record..user_type ).type field are now: " + contactList.Programming Guide Chapter 6: JavaScript and Service Manager reference Return values RC_SUCCESS or one of the other global return code values. print( "Saving record. SYSTEM".type field are: " + contactList. print( "Updating the user." ).user_type = "site". Example This example does the following: l l l l Searches the contacts table for any contact name you define in the search variable Displays the contact record as a text string Updates the value of the user. print( "The return code value for the doSave() method is: " + RCtoString( rc ) ).. print( "The current contents of the user.getText() ). if ( isContact == RC_SUCCESS ) { print( "Success.name=\""+ name + "\"" ).type field.. return null } } contactName = "ADMINISTRATOR. var rc = contactList.user_type ).. function updateContact( name ) { print( "Searching for contact: " + name + ". var contactList = new SCFile( "contacts" ). "ADMINISTRATOR.type field Saves the Service Manager record This example requires the following sample data: l l A valid contact name (for example. not for retrieving attachments.{"array value". If you need to retrieve attachments. you could corrupt the SYSATTACHMENTS table..Programming Guide Chapter 6: JavaScript and Service Manager reference updateContact( contactName ).getAtttachments() Syntax SCFile. you can use SCFile.doSelect( "query" ). JavaScript method: SCFile. Example This example does the following: l l Searches the contacts table for any contact name you define in the search variable Displays the contact record as a text string This example requires the following sample data: l l A valid contact name (for example. function findContactName( name ) { Page 250 of 396 HP Service Manager (9. method to limit the fields that doSelect returns from the database. "ADMINISTRATOR.doSelect() This method queries for records in an HP Service Manager object. CONTACT") var contactName. You must use the slash character to escape out quotation marks and any special characters restricted from JavaScript. If you use this method to retrieve attachments. SYSTEM") A invalid contact name (for example. "NOT A.30) . use one of the following functions to get the attachments associated with the current file record: SCFile.. Important Note: This method is used for retrieving normal data."array value"}.]} For performance improvement.getAttachment(attachID) or SCFile. The SCFile object has the following format: table={["field value". Arguments The following arguments are valid for this method: Data Argument type query Description String This argument specifies the query you want to use to search for Service Manager records.setFields. The method returns an SCFile object containing the records matching the query and a global return code value of RC_SUCCESS or returns one of the error global return code values if the method cannot return any records. Return values An SCFile object containing records and RC_SUCCESS or one of the other global return code values.. " ). CONTACT". var contactList = new SCFile( "contacts" )..getText() ).. return null } } contactName = "ADMINISTRATOR. " + RCtoString( findContact ) ). The method returns RC_SUCCESS if the method successfully updates a record or returns one of the error global return code values if the method cannot update the record. Syntax SCFile. SYSTEM".type" field to "site") Page 251 of 396 HP Service Manager (9.30) . findContactName( contactName ). return contactList } else { print( "Could not find contact. Arguments There are no arguments for this method.doSelect( "contact. It requires defining a Service Manager file object and defining new values for fields.Programming Guide Chapter 6: JavaScript and Service Manager reference print( "Searching for contact: " + name + ". var findContact = contactList. contactName = "NOT A. findContactName( contactName ). Example This example does the following: l l Searches the contacts table for any contact name you define in the search variable Displays the contact record as a text string This example requires the following sample data: l l A valid contact name (for example. Return values RC_SUCCESS or one of the other global return code values.doUpdate() This method updates a Service Manager record with any new field values defined in a Service Manager file object. set the "user.doUpdate(). "ADMINISTRATOR. found " + name + " in contact record:\n" + contactList.name=\""+ name + "\"" ) if ( findContact == RC_SUCCESS ) { print( "Success. JavaScript method: SCFile. SYSTEM") A valid field value update (for example. Example Page 252 of 396 HP Service Manager (9. updateContact( contactName ). which is a string containing an attachment ID of the form "cid:xxxxx". getNext().getAttachment( attachID ) Gets a specific attachment associated with the current file record.user_type ). getAttachment() returns an Attachment object. Syntax SCFile.. print( "Updating the user.. Arguments getAttachment() takes one argument. or getAttachments() operation. var isContact = contactList.type field.type field are " + contactList. etc.30) . function updateContact( name ) { print( "Searching for contact: " + name + ".doSelect( "contact. if ( isContact == RC_SUCCESS ) { print( "Success. such as doSelect(). SYSTEM". updateAttachment()." ). print( "The current contents of the user. Values passed to getAttachment() will normally be ones obtained from a previous insertAttachment(). Return values If successful.type field are now " + contactList.user_type ).name=\""+ name + "\"" ). JavaScript method: SCFile. " + RCtoString( isContact ) ). return contactList } else { print( "Could not find contact.doUpdate(). found " + name + " in contact record:\n" + contactList. Before calling getAttachment. it returns null. you must establish a current record using one of the positioning methods.user_type = "site". return null } } contactName = "ADMINISTRATOR. contactList.getAttachment( attachID ).Programming Guide Chapter 6: JavaScript and Service Manager reference var contactName. print( "The contents of the user. Otherwise. contactList..getText() )." ). var contactList = new SCFile( "contacts" ).. Page 253 of 396 HP Service Manager (9.doSelect( 'number = "IM10001"' ). you must establish a current record using one of the positioning methods. The array will be empty if there are no attachments for the record. Syntax SCFile.getAttachment( attachmentID ). var attachmentObj = f. The Attachment. JavaScript method: SCFile. Gets a specific attachment associated with the current record This example requires the following sample data: l Record number IM10001 in the probsummary table var f = new SCFile( 'probsummary' ).getAttachments() Arguments The getAttachments method takes no arguments.value will be NULL. var rc = f.getAttachments(). Before calling getAttachments. To get each attachment's binary data.30) .doSelect( 'number = "IM10001"' ). getNext().getAttachment(attachID) method where attachID contains the href property of the attachment object.Programming Guide Chapter 6: JavaScript and Service Manager reference This example does the following: l l Selects one record from the probsummary table. such as doSelect(). etc. The attachment objects retrieve here will only contain metadata. getAttachments() returns an array of attachment objects. var rc = f. Example This example does the following: l l Selects one record from the probsummary table Gets all of the attachments associated with the current record This example requires the following sample data: l Record number IM10001 in the probsummary table var f = new SCFile( 'probsummary' ). var attachments = f. Return values If successful. you will need to use SCFile.getAttachments() This method gets all of the attachments associated with the current file record. Found contacts starting with " + query + ". Syntax SCFile. function findFirstContact( query ) { print( "Searching for contacts starting with " + query + ". "F") var contactQuery..You must use one of the other SCFile methods to create a record list. "B") A contact query that produces a single record (for example. Example This example does the following: l l l l Queries the contacts table for any contact name you define in the search variable Displays the last record in the record list Displays the previous record in the record list Displays the first contact in the record list This example requires the following sample data: l l A contact query that produces a record list (for example.getFirst() This method returns the first record in a record list stored in an SCFile object.Programming Guide Chapter 6: JavaScript and Service Manager reference print( attachments.name ).name#\""+ query + "\"" ).length ). Page 254 of 396 HP Service Manager (9. var findContact = contactFile. Return values An SCFile object containing the first record and RC_SUCCESS or one of the other global return code values.doSelect( "contact. if ( findContact == RC_SUCCESS ) { print( "Success." ).30) .getFirst(). for ( var attachment in attachments ) { print( attachments[ attachment ]. var contactFile = new SCFile( "contacts" ). } JavaScript method: SCFile. Arguments There are no arguments for this method." ). The method returns an SCFile object containing the first record in a record list and a global return code value of RC_SUCCESS or returns one of the error global return code values if the method cannot find the first record.. } else { print( "Could not find contacts starting with " + query + ". " + RCtoString( findContact ) ).getLast(). Return values An SCFile object containing the last record and RC_SUCCESS or one of the other global return code values.Programming Guide Chapter 6: JavaScript and Service Manager reference var findLastRecord = contactFile.getPrev(). "B") A contact query that produces a single record (for example. findFirstContact( contactQuery ). function findLastContact( query ) Page 255 of 396 HP Service Manager (9. var findPrevRecord = contactFile. print( "The previous record is:\n" + contactFile ).getLast() This method returns the last record in a record list stored in an SCFile object. return null } } contactQuery = "H". var findFirstRecord = contactFile. The method returns an SCFile object containing the last record in a record list and a global return code value of RC_SUCCESS or returns one of the error global return code values if the method cannot find the last record. print( "The first record is:\n" + contactFile ). Example This example does the following: l l l Queries the contacts table for any contact name you define in the search variable Displays the first contact in the record list Displays the last record in the record list This example requires the following sample data: l l A contact query that produces a record list (for example. JavaScript method: SCFile.getLast(). print( "The last record is:\n" + contactFile ). Arguments There are no arguments for this method. You must use the other SCFile methods to create a record list.getFirst(). "F") var contactQuery.30) . Syntax SCFile. The first record is:\n" + contactFile ).30) . "$L. Example This example does the following: l l Inserts a new record into a local variable Displays the return code of the insert operation This example requires the following sample data: l A valid record in a local variable (for example. Return values One of the global return code values.Programming Guide Chapter 6: JavaScript and Service Manager reference { print( "Searching for contacts starting with " + query + ".vars.file") system. var findContact = contactFile. You can then use the RCtoString global method to convert the return code into a string. return null } } contactQuery = "H". " + RCtoString( findContact ) ). Found contacts starting with " + query + ". Syntax SCFile. Page 256 of 396 HP Service Manager (9. if ( findContact == RC_SUCCESS ) { print( "Success.getLastRC() This method returns the most recent global return code value generated by the SCFile object.name#\""+ query + "\"" ). var findLastRecord = contactFile.doSelect( "contact.. print( "The last record is:\n" + contactFile ).. The method returns the most recent global return code value generated by the SCFile object. JavaScript method: SCFile.getLast(). return contactFile } else { print( "Could not find contacts starting with " + query + ". contactQuery = "F"." ). var contactFile = new SCFile( "contacts" ). findLastContact( contactQuery ). findLastContact( contactQuery ).doInsert(). Arguments There are no arguments for this method.getLastRC().$L_file. Shows a validation failed due to invalid assignment group.doAction() returns 71..assignment = group.callback_contact = name. var newIncident = new SCFile( "probsummary" ). "validation failure".getMessages() Returns an array of messages generated by the Document Engine from a previous SCFile.description = desc. resolutionValue. SCFile. newIncident. name.getMessages(). descriptionValue. newIncident. actionType.category = cat. Arguments There are no arguments allowed for this method. resultionCodeValue. newIncident. Page 257 of 396 HP Service Manager (9.Programming Guide Chapter 6: JavaScript and Service Manager reference var rc = getLastRC(). } else if ( getLastRC() == false ) print( "Error " + RCtoString(rc) + " occurred trying to insert the record" ).doAction(). var var var var var var var var function insertIncident( num.getMessages() returns messages generated from the Document Engine. desc ) { print( "Creating new incident record. Return values Returns an array of messages from previous SCFile. JavaScript method: SCFile." ). assignmentValue.number = num. cat.doAction() call.30) . Syntax SCFile. categoryValue. group. Example This example does the following: l l l l Uses the Document Engine add to create a new incident record from variable values. callbackContact.. newIncident. newIncident. if ( rc == RC_SUCCESS ) { print( "Insert of document succeeded" ). numberValue. SCFile. The method returns an SCFile object containing the next record in a record list and a global return code value of RC_SUCCESS or returns one of the error global return code values if the method cannot find the next record. print( "Reason: "+ newIncident. Created new record " + newIncident.getNext() This method returns the next record in a record list stored in an SCFile object. assignmentValue = "HELPDESK".getNext().30) . assignmentValue. Could not create record. return null } } numberValue = "IM11121" callbackContact = "ADMINISTRATOR.number } else { print( "Could not create record.. interactionID = insertIncident( numberValue. " + RCtoString( rc ) ). if ( rc == RC_SUCCESS ) { print( "Success. callbackContact. return newIncident. Arguments There are no arguments for this method. SYSTEM".Programming Guide Chapter 6: JavaScript and Service Manager reference var rc = newIncident. Validation failed creating new incident record.getMessages() ).getText() ). descriptionValue = null. categoryValue = "network".. Syntax SCFile. Reason: Category specified is invalid. Example This example does the following: l l Queries the contacts table for any contact name you define in the search variable Displays the first contact in the record list Page 258 of 396 HP Service Manager (9. It requires the use of the other SCFile methods to create a record list. Return values An SCFile object containing the next record and RC_SUCCESS or one of the other global return code values. JavaScript method: SCFile.doAction('add'). Output Category specified is invalid. categoryValue. descriptionValue ). Found contacts starting with " + query + ". " + RCtoString( findContact ) ). JavaScript method: SCFile. print( "The next record is:\n" + contactFile.getPrev().getText() ).Programming Guide Chapter 6: JavaScript and Service Manager reference l Displays the next record in the record list This example requires the following sample data: l l A contact query that produces a record list (for example. Page 259 of 396 HP Service Manager (9." ). Arguments There are no arguments for this method. if ( findContact == RC_SUCCESS ) { print( "Success. return contactFile } else { print( "Could not find contact " + query + ". return null } } contactQuery = "B". You must use of the other SCFile methods to create a record list.getPrev() This method returns the previous record in a record list stored in an SCFile object. var findContact = contactFile.30) . findNextContact( contactQuery ). var findNextRecord = contactFile.getNext(). var contactFile = new SCFile( "contacts" ). findNextContact( contactQuery ).getText() ).doSelect( "contact. Syntax SCFile. contactQuery = "F".. function findNextContact( query ) { print( "Searching for contacts starting with " + query + ". "F") var contactQuery.. The first record is:\n" + contactFile. "B") A contact query that produces a single record (for example. Return values An SCFile object containing the previous record and RC_SUCCESS or one of the other global return code values.name#\""+ query + "\"" ). getLast().getPurgedRowCount(). " + RCtoString( findContact ) ).. return null } } contactQuery = "H". Found contacts starting with " + query + ". } else { print( "Could not find contacts starting with " + query + ".getPrev(). var findContact = contactFile. var findPrevRecord = contactFile.30) . print( "The previous record is:\n" + contactFile ). var contactFile = new SCFile( "contacts" ). var findLastRecord = contactFile." ).name#\""+ query + "\"" ). Syntax SCFile. findPrevContact( contactQuery ). if ( findContact == RC_SUCCESS ) { print( "Success. JavaScript method: SCFile.. function findPrevContact( query ) { print( "Searching for contacts starting with " + query + ". The first record is:\n" + contactFile ).getPurgedRowCount() This method enables you to retrieve the number of HP Service Manager records that were deleted from a table after invoking the doPurge() method. print( "The last record is:\n" + contactFile ). Example This example does the following: l l l l Queries the contacts table for any contact name you define in the search variable Displays the first contact in the record list Displays the last record in the record list Displays the previous record in the record list This example requires the following sample data: l A contact query that produces a record list (for example.doSelect( "contact.Programming Guide Chapter 6: JavaScript and Service Manager reference The method returns an SCFile object containing the previous record in a record list and a global return code value of RC_SUCCESS or returns one of the error global return code values if the method cannot find the previous record. "H") var contactQuery. Page 260 of 396 HP Service Manager (9. } JavaScript method: SCFile. You can use this method to return the length of Service Manager array fields. you can use the following format: SCFile_object. Return values l If successful. which are always stored as Datum objects. var purgedCount = recordList. if ( purgedCount >= 0 ) { print(purgedCount + " records have been purged").getSize() Page 261 of 396 HP Service Manager (9.getPurgedRowCount(). } } else { print ("doPurge failed"). If getPurgedRowCount() is not able to retrieve the record count it will return -1.array_field_name. } else { print("Could not retrieve purged record count").doPurge("docid = \"docid1\""). var recordList = new SCFile(fileName). var deleteRC = recordList. getPurgedRowCount() returns the number of records deleted by the last successful doPurge() call (which returned RC_SUCCESS).getSize() This method returns the number of array elements in an array stored in a Service Manager Datum object.Programming Guide Chapter 6: JavaScript and Service Manager reference Arguments There are no arguments for this method. if ( deleteRC == RC_SUCCESS ) { print ("doPurge succeeded"). It is also unaffected by a failed call to doPurge (returned RC_ERROR).30) . This example requires the following sample data: l Records in kmknowledgebaseupdates table where docid = "docid1" var fileName = "kmknowledgebaseupdates". To query a particular array field in an SCFile object. l The value returned by getPurgedRowCount is unaffected by any SCFile method call other than doPurge. Example This example does the following: l l Searches the kmknowledgebaseupdates table for records where docid="docid1" Deletes whatever it finds. This value can be 0 if no records were deleted. var actionSize = incidentFile.getSize(). print( "The contents of the action field is:\n" + actionText ). The first record is:\n" + incidentFile ). "IM1005") var incidentQuery.. print( "Running the getSize() method on the returned SCFile object produces the following result: " + objectSize ).action. var findIncident = incidentFile.doSelect( "number#\""+ query + "\"" ).30) . Example This example does the following: l l l Searches the probsummary table for any incident record you define in the search variable Attempts to get the size of the returned SCFile object (the result is always zero) Displays the contents of the action field (the action field contains Service Manager array data) Displays the size of the action field using the Service Manager getSize() method Converts the SCFile object into a JavaScript array using the Service Manager toArray() method Displays the size of the new JavaScript array using the core JavaScript length property l l l This example requires the following sample data: l A valid incident record number (for example. Found incident records starting with " + query + ". Arguments There are no arguments for this method. Page 262 of 396 HP Service Manager (9.Datum_object." ). var objectSize = incidentFile. if ( findIncident == RC_SUCCESS ) { print( "Success.Programming Guide Chapter 6: JavaScript and Service Manager reference Replace any periods in the name of array_field_name with underscores. you must convert the Service Manager array field update.action to update_action when querying it from JavaScript.getSize(). var actionText = incidentFile. For example.action.getSize(). Return values A number and RC_SUCCESS or one of the other global return code values. or returns one of the error global return code values if the method cannot return the number of array elements. function findIncidents( query ) { print( "Searching for incident records starting with " + query + ". The method returns the number of array elements in an array stored in a Service Manager Datum object and a global return code value of RC_SUCCESS. Syntax SCFile. var incidentFile = new SCFile( "probsummary" ).. SYSTEM") A invalid contact name (for example. "ADMINISTRATOR. " + RCtoString( findIncident ) ). return incidentFile. Example This example does the following: l l Searches the contacts table for any contact name you define in the search variable Displays the contact record as a text string This example requires the following sample data: l l A valid contact name (for example..{"array value". findIncidents( incidentQuery ). Return values A string and RC_SUCCESS or one of the other global return code values. The method returns a text string containing the current SCFile object and a global return code value of RC_SUCCESS.getText().30) . print( "The new JavaScript array is:\n" + incidentArray ).getText() This method returns a text string representation of the current SCFile object. CONTACT") var contactName. "NOT A. Arguments There are no arguments for this method. JavaScript method: SCFile.. var arraySize = incidentArray.Programming Guide Chapter 6: JavaScript and Service Manager reference print( "The size of the action field is: " + actionSize )..length.]} Syntax SCFile. print( "The size of the converted array is: " + arraySize ). return null } } incidentQuery = "IM1005". or returns one of the error global return code values if the method cannot return a string. Page 263 of 396 HP Service Manager (9."array value"}.. print( "Converting the SCFile object to a JavaScript array.toArray(). } else { print( "Could not find incident records starting with " + query + ". The text string has the following format: table={["field value"." ). var incidentArray = incidentFile.. findContactName( contactName ). Return values A data type and RC_SUCCESS or one of the other global return code values. This method fails on any scalar fields within file records. var findContact = contactList. To determine the type of scalar fields you can use. and boolean fields. Example This example does the following: l l l Searches the probsummary table for any incident record you define in the search variable Displays the contents of the incident record object Returns the data type of the incident record object using the getType() method Page 264 of 396 HP Service Manager (9. see the core JavaScript . Arguments There are no arguments for this method.Programming Guide Chapter 6: JavaScript and Service Manager reference function findContactName( name ) { print( "Searching for contact: " + name + ". " + RCtoString( findContact ) ). such as number fields. SYSTEM". date fields. The method returns a data type and a global return code value of RC_SUCCESS or returns one of the error global return code values..doSelect( "contact. if the method cannot determine the data type. return contactList } else { print( "Could not find contact. CONTACT"." ). Syntax SCFile. such as arrays and structured arrays. JavaScript method: SCFile. contactName = "NOT A.mozilla. var contactList = new SCFile( "contacts" ).org/).getText() ). found " + name + " in contact record:\n" + contactList.getType(). findContactName( contactName ). string fields..30) .name=\""+ name + "\"" ) if ( findContact == RC_SUCCESS ) { print( "Success. return null } } contactName = "ADMINISTRATOR.getType() This method returns the data type of HP Service Manager datum objects.type property in the JavaScript Guide (http://developer. getType(). } else { print( "Could not find incident records starting with " + query + ". function findTypes( query ) { print( "Searching for incident records starting with " + query + ". The XML object has the following format.. if ( findIncident == RC_SUCCESS ) { print( "Success.getType. "IM1001") var incidentQuery. " + RCtoString( findIncident ) ). print( "The contents of the category field are:\n" + textField ). print( "The object incidentFile is of type: " + objectType ).Programming Guide Chapter 6: JavaScript and Service Manager reference l l l l Displays the contents of the action field object Returns the data type of the action field object using the getType() method Displays the contents of the category field Returns the data type of the category field object using the core JavaScript type property This example requires the following sample data: l A valid incident record (for example. return null } } incidentQuery = "IM1001". var objectType = incidentFile. print( "The type of the action field is: " + fieldType ).getType(). findTypes( incidentQuery ). Found incident records starting with " + query + "." ). fieldType = arrayField.30) . print( "The type of the category field is: " + fieldType ).category. var findIncident = incidentFile. JavaScript method: SCFile.getXML() This method returns an XML object representation of the current SCFile object. var incidentFile = new SCFile( "probsummary" ). var arrayField = incidentFile.action.doSelect( "number#\""+ query + "\"" ). var textField = incidentFile.. The first record is:\n" + incidentFile ). print( "The contents of the action field are:\n" + arrayField ). which is compatible with the Service Manager Web services API: <model name="table" query="query"><keys><fieldname>key Page 265 of 396 HP Service Manager (9. fieldType = textField. . The method returns an XML object containing the current SCFile object and a global return code value of RC_SUCCESS or returns one of the failure global return code values if the method cannot return an XML object.doSelect( "contact. "NOT A. CONTACT") var contactName. found " + name + " in contact record:\n" + contactList. SYSTEM".</keys><instance><fieldname>instance value</fieldname>.. Return values An XML object and RC_SUCCESS or one of the other global return code values. Page 266 of 396 HP Service Manager (9.. findContact( contactName ). contactName = "NOT A..</instance></model> Syntax SCFile. SYSTEM") A invalid contact name (for example...Programming Guide Chapter 6: JavaScript and Service Manager reference value</fieldname>. "ADMINISTRATOR. return contactList } else { print( "Could not find contact. Example This example does the following: l l Searches the contacts table for any contact name you define in the search variable Displays the contact record as an XML object This example requires the following sample data: l l A valid contact name (for example. var isContact = contactList. CONTACT". " + RCtoString( isContact ) ).getXML(). Arguments There are no arguments for this method. function findContact( name ) { print( "Searching for contact: " + name + ". var contactList = new SCFile( "contacts" )." ).30) .name=\""+ name + "\"" ) if ( isContact == RC_SUCCESS ) { print( "Success.getXML() ). findContact( contactName ). return null } } contactName = "ADMINISTRATOR. attachmentObj.doSelect( 'number = "IM10001"' ). Arguments The insertAttachment method takes one argument. Page 267 of 396 HP Service Manager (9. such as doSelect().type — This is a string containing the MIME type of the attachment. attachmentObj. Attachment ID values are assigned by the server when attachments are inserted or updated. for example.type = "text/plain".Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript method: SCFile. Attachment objects can be obtained via Web Services calls or constructed by JavaScript code.value = "This is a test text attachment". The "href" property of the attachment object should not be set for an insert operation.insertAttachment( attachObj ). getNext(). Example This example does the following: l l l Creates a new attachment object Selects one record from the probsummary table Inserts the attachment object to the current record This example requires the following sample data: l Record number IM10001 in the probsummary table var attachmentObj = new Attachment(). etc. you must establish a current record using one of the positioning methods.txt". "foo. Required properties Attachment. Syntax SCFile.insertAttachment( attachObj ) This method creates a new attachment associated with the current file record.pdf" Attachment. var f = new SCFile( 'probsummary' ).insertAttachment( attachmentObj ).30) . Any value supplied will be ignored.name = "MyAttachment. such as "text/plain" or "application/pdf" Attachment. insertAttachment() returns a string of the form cid:xxxxxx containing the attachment ID for the inserted attachment.txt" or "foo. One way to obtain such data is by using the readFile() global method.name — This is a string containing the name of the attachment. Before calling insertAttachment. attachmentObj. var rc = f. The Attachment object must be properly populated prior to calling insertAttachment.value — This is a binary string containing the actual attachment data. which is an asttachment object. var attachmentID = f. Return values If successful. It requires using the deprecated File() object with a query or query condition. return null } Page 268 of 396 HP Service Manager (9. "IM1005") An invalid incident record (for example "incident") var incidentQuery.isRecord() This is a deprecated method as of version 6.Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript method: SCFile.isRecord(). Example This example does the following: l l Searches the probsummary table for any incident record you define in the search variable Displays the incident record object and the results of the isRecord() method This example requires the following sample data: l l A valid incident record (for example. "number#\""+ query + "\"" ).isRecord() ) { print( "Success. The isRecord() method verifies that the query or query condition returns a Service Manager record. Arguments There are no arguments for this method. var incidentFile = new File( "probsummary". Return values A Boolean value: 1 (true) or 0 (false).. function findTypes( query ) { print( "Searching for incident records starting with " + query + ". Found incident records starting with " + query + ".30) ." ). if ( incidentFile != null ) { print( "Successfully allocated a File object").. The first record is:\n" + incidentFile ).1 because it does not use the Service Manager-defined global return codes. The method returns a Boolean value of 1 if the File object contains a Service Manager record or returns 0 if the method does not find a Service Manager record. This method does not use the Service Manager-defined global return codes. return incidentFile } else { print( "Could not find incident records starting with " + query + ". if ( incidentFile. Syntax SCFile." ). "IM1010") An incident record with an action field value (for example.30) . JavaScript method: SCFile. var incidentFile = new SCFile( "probsummary" ). Arguments There are no arguments for this method." ). Syntax SCFile. incidentQuery = "incident". var rc = incidentFile. findTypes( incidentQuery ). This method does not use the Service Manager global return code values.join() This method returns the elements of either a Service Manager Datum array object or a JavaScript array.join(). return null } } incidentQuery = "IM1005". findTypes( incidentQuery ).. function findIncident( id ) { print( "Searching for Incident record: " + id + ". Example This example does the following: l l l Searches the probsummary table for any incident record you define in the search variable Displays the new incident record as a text string Displays the contents of action field using the join() method This example requires the following sample data: l l A valid value for the number field (for example. "IM1010") var incidentID. Return values A string.Programming Guide Chapter 6: JavaScript and Service Manager reference } else { print( "Could not allocate a File object." ).doSelect( "number=\"" + id + "\"" ) if ( rc == RC_SUCCESS ) { Page 269 of 396 HP Service Manager (9. The method returns the elements of an array.. JSDate( dataType ). JavaScript method: SCFile. Searches the probsummary table for any incident record you define in the search variable Displays the incident record and the value of the open.Programming Guide Chapter 6: JavaScript and Service Manager reference print( "Success.join() ). " + RCtoString( rc ) ).action ). return null } } incidentID = "IM1010". This method converted Service Manager date/time data into JavaScript date/time objects.getText() ). print( "Displaying the contents of the action field with join() method: " + incidentFile. Alternatively. The SCFile object now automatically converts Service Manager date/time data into JavaScript date/time objects.JSDate() This method is deprecated as of version 6. return incidentFile } else { print( "Could not find Incident record.time field Creates an SCDatum object containing the number of milliseconds you want to convert Converts the open. Arguments The following arguments are valid for this method: Argument Data type Description dataType Return values None Example This example does the following: l l l l String This argument specifies the data type of a field in an SCFile object.1 with the introduction of the SCFile object.time field data is in Service Manager's date/time data type) Converts the SCDatum object into a JavaScript date/time l This example requires the following sample data: Page 270 of 396 HP Service Manager (9.time field into an SCDatum object (by default the open. print( "Displaying the contents of the action field as an object: " + incidentFile. found Incident record:\n" + incidentFile.30) . you can now use the XMLDate object and its methods to convert between date/time formats. findIncident( incidentID ).action. Syntax SCFile. open_time ). print( "The new SCDatum object is: " + dat )..time to an SCDatum object.. var j = dat.Programming Guide Chapter 6: JavaScript and Service Manager reference l A valid incident record with a value in the open. print( "The value of the open. JavaScript method: SCFile. found " + id + " in incident record:\n" + incidentFile. For example.time field (for example." ). Return values Page 271 of 396 HP Service Manager (9." ).length() This method returns the number of array elements in an array stored in a Service Manager Datum object. if ( f == RC_SUCCESS ) { print( "Success.action to update_action when querying it from JavaScript.. You can use this method to return the length of Service Manager array fields. print( "Converting the SCDatum object to a JSDate. var dat = new SCDatum( incidentFile. var f = incidentFile.30) .time field is: " + incidentFile.length(). which are always stored as Datum objects. Arguments There are no arguments for this method.getText() ). To query a particular array field in an SCFile object.open_time ). Note: Replace any periods in the name of array_field_name with underscores. var incidentFile = new SCFile( "probsummary" ). function findIncident( id ) { print( "Searching for incident: " + id + ". print( "The converted SCDatum object is: " + j ). " + RCtoString( f ) )." ).. you must convert the Service Manager array field update. use the following format: SCFile_object. return null } } incidentID = "IM1010". findIncident( incidentID ).doSelect( "number=\""+ id + "\"" ). print( "Converting open. return incidentFile } else { print( "Could not find incident record.array_field_name. "IM1010") var incidentID.array_field_name..length(). Syntax SCFile.JSDate().. print( "The size of the action field is: " + actionSize ). var actionSize = incidentFile..getSize(). The method returns the number of array elements in an array stored in a Service Manager Datum object and a global return code value of RC_SUCCESS or returns one of the error global return code values if the method cannot return the number of array elements.. " + RCtoString( findIncident ) ).toArray()..doSelect( "number#\""+ query + "\"" ). var incidentArray = incidentFile. print( "The contents of the action field is:\n" + actionText ).action." ). var arraySize = incidentArray. The first record is:\n" + incidentFile ). function findIncidents( query ) { print( "Searching for incident records starting with " + query + ". } else { print( "Could not find incident records starting with " + query + ".30) .action.length.getSize(). return incidentFile. var findIncident = incidentFile. print( "Running the getSize() method on the returned SCFile object produces the following result: " + objectSize ). Found incident records starting with " + query + ". print( "The size of the converted array is: " + arraySize ). print( "The new JavaScript array is:\n" + incidentArray ). var incidentFile = new SCFile( "probsummary" ). var actionText = incidentFile. if ( findIncident == RC_SUCCESS ) { print( "Success.Programming Guide Chapter 6: JavaScript and Service Manager reference A number and RC_SUCCESS or one of the other global return code values. print( "Converting the SCFile object to a JavaScript array. var objectSize = incidentFile. return null Page 272 of 396 HP Service Manager (9." ). Example This example does the following: l l l Searches the probsummary table for any incident record you define in the search variable Attempts to get the size of the returned SCFile object (the result is always zero) Displays the contents of the action field (the action field contains Service Manager array data) Displays the size of the action field using the Service Manager length() method Converts the SCFile object into a JavaScript array using the Service Manager toArray() method Displays the size of the new JavaScript array using the core JavaScript length property l l l var incidentQuery.. Arguments There are no arguments for this method.." ).getText() ).pop() This method removes the last element from a JavaScript array and returns the element removed as a string. var rc = incidentFile.. print( "The action field array contains the following: " + a ). found Incident record:\n" + incidentFile..Programming Guide Chapter 6: JavaScript and Service Manager reference } } incidentQuery = "IM1005". var a = incidentFile." ). Syntax SCFile. findIncidents( incidentQuery ).doSelect( "number=\"" + id + "\"" ) if ( rc == RC_SUCCESS ) { print( "Success.pop(). Page 273 of 396 HP Service Manager (9. var incidentFile = new SCFile( "probsummary" ). Return values A string. This method does not use the Service Manager global return code values. function findIncident( id ) { print( "Searching for Incident record: " + id + ".toArray(). JavaScript method: SCFile. "IM1010") var incidentID. The method returns the element removed from the array.. Example This example does the following: l l l l l Searches the probsummary table for any incident record you define in the search variable Displays the new incident record as a text string Converts the action field into a JavaScript array Adds an item to the end of the array and displays the total number of elements in the array Removes an item from the end of the array and displays the array item removed This example requires the following sample data: l l A valid value for the number field (for example. "IM1010") An incident record with an action field value (for example. print( "Converting the action field to a JavaScript array.action.30) . Syntax SCFile. This method does not use the Service Manager global return code values.. Return values A number. Example This example does the following: l l l Searches the probsummary table for any incident record you define in the search variable Displays the new incident record as a text string Converts the contents of the action field into a JavaScript array Page 274 of 396 HP Service Manager (9. If you apply this method to a Service Manager array object.. The method returns the number of items in the array.pop(). print( "The number of items in the array are: " + addOne )." ). print( "The array item removed was: " + removeOne ). print( "Popping new array entry.. findIncident( incidentID ). " + RCtoString( rc ) ). return incidentFile.push( "First array item" ). then it adds the item but does not return the number of entries in the array.30) . } else { print( "Could not find Incident record." ). print( "The action field array contains the following: " + a ). var addOne = a.push( arrayItem ).Programming Guide Chapter 6: JavaScript and Service Manager reference print( "Pushing new array entry. var removeOne = a. print( "The action field array contains the following: " + a ). Arguments The following arguments are valid for this method: Data Argument type arrayItem String Description This argument specifies the array item you want to add to a JavaScript array..push() This method adds an entry to the end of a JavaScript array and returns the total number of entries in the array. return null } } incidentID = "IM1010". JavaScript method: SCFile. Page 275 of 396 HP Service Manager (9." ).getText() ). } else { print( "Could not find Incident record. var a = incidentFile. return null } } incidentID = "IM1010". print( "The action field array contains the following: " + a )... print( "The action field array contains the following: " + a )." ). print( "Pushing new array entry.. found Incident record:\n" + incidentFile. var addTwo = a. findIncident( incidentID ).doSelect( "number=\"" + id + "\"" ) if ( rc == RC_SUCCESS ) { print( "Success...30) . print( "The number of items in the array are: " + addOne ). If setFields has not been called on a table.. all fields are selected and a “SELECT *” is performed.push( "First array item" )." ). var addOne = a. function findIncident( id ) { print( "Searching for Incident record: " + id + ". " + RCtoString( rc ) )... "IM1010") An incident record with an action field value (for example.action. This method is supported for read-only objects. You can make an object read-only specifying the SCFILE_READONLY argument in the SCFile constructor." ). return incidentFile. JavaScript method: SCFile. "IM1010") var incidentID. print( "Converting the action field to a JavaScript array.Programming Guide Chapter 6: JavaScript and Service Manager reference l Adds an item to the end of the JavaScript array and prints the total number of items in the array This example requires the following sample data: l l A valid value for the number field (for example. print( "The action field array contains the following: " + a ). var incidentFile = new SCFile( "probsummary" ).setFields() This method causes any subsequent doSelect() calls to fetch only the specified fields.toArray(). print( "The number of items in the array are: " + addTwo ). print( "Pushing new array entry. var rc = incidentFile.push( "Second array item" ). setFields( ). for example.) When the method fails.setFields( field-string ). Syntax SCFile.id”)). it has no effect. for example.id”) field-string String Return values The method returns RC_SUCCESS if successful and RC_ERROR on failure. The following conditions cause a setFields failure: l l l Calling setFields on an uninitialized SCFile or a non read-only SCFile Calling setFields with an invalid argument type (not a string or an array of strings) Calling setFields with one (or more) invalid fields. l Page 276 of 396 HP Service Manager (9. A string of space-separated field names. setFields(“contact. there are certain situations when the call can be successful (returns RC_SUCCESS) but a “SELECT *” is still performed. If you reference field in the object that has not been specified in the setFields method. SCFile. from each underlying table) even if not explicitly specified in setFields. Any subsequent calls to doSelect() will fetch all fields (a SELECT * will be performed). “user.setFields( field-array ). Limitations l The main unique key fields of the dbdict are always selected from the table (and for join tables. a structure name or an unmapped field (which are unsupported).name”. SCFile. This would be the case if: n All specified fields exist in the DBDICT but at least one field is an alias field. the field appears as “null” whether the database has data in that column or not.Programming Guide Chapter 6: JavaScript and Service Manager reference Calling setFields with no parameters will reset any previously specified fields. Arguments The following arguments are valid for this method: Data Argument type field-array Array Description A javascript array of field name strings. (The method performs a basic validation on the field names to ensure they exist in the DBDICT. It issues a warning in the sm.30) . setFields(new Array(“contact.name user. Note: Do not reference fields in the object that have not been specified in the setFields method.log file. Since only basic field validation is performed in the setFields method. and the last successful call to setFields stays in effect. setFields( fields ). If setOrderBy() has not been called.doSelect( "contact.Programming Guide Chapter 6: JavaScript and Service Manager reference n LDAP is the primary data source for the table. " + RCtoString( findContact ) ). SCFILE_READONLY ). (LDAP mapped fields are supported as long as LDAP is not the primary data source." l This example requires the following sample data: l a contacts table with some records function findPrefix( prefix ) { var contactList = new SCFile( "contacts". // build array of fields to be returned from DB var rc = contactList. returns the message "Could not find contact. } else { print( "Could not find contact. On failure.name # \"" + prefix + "\"" ).30) . a Page 277 of 396 HP Service Manager (9.setOrderBy() This method causes any subsequent doSelect() call on a SCFile object to fetch only the specified fields by the specified sort sequences of the SCFileObject. return null. //added new parameter SCFILE_READONLY var fields = new Array("contact. } } JavaScript method: SCFile. // call new setFields method to identify fields to query from DB if ( rc != RC_SUCCESS ) { print( "setFields() failed. will revert to SELECT * (see log for more info)" ). return null. } var findContact = contactList.) Example usage This example does the following: l Takes the prefix of a contact name and returns a list of contacts that start with the specified prefix.id"). "user. if ( findContact == RC_SUCCESS ) { return contactList.name". This example does the following: Page 278 of 396 HP Service Manager (9.log file. A javascript array of sort sequenence specification. Calling setOrderBy() with two arrays of different length. Arguments The following arguments are valid for this method: Data Argument type sortFields Array Description A javascript array of field name string.30) . these samples show how to define a single sort sequence for descending sort order. var sortOrder = [SCFILE_DSC]. Return values Returns RC_SUCCESS if successful and RC_ERROR on failure. and SCFILE_ DSC for specifying sort by descending order. Syntax SCFile. (The method performs a basic validation on the field names to ensure they exist in the DBDICT. If the sort sequence specifications in the sortSeq array is of non-recognizable constant. SCFILE_ASC is assumed. • Fields from a join file should not be within a structure in the dbdict. Calling setOrderBy() with wrong number of arguments. Calling setOrderBy() with one (or more) invalid fields. var sortOrder = new Array(1). or SCFILE_DSC. SCFILE_ASC is a constant for specifying sort by ascending order."company"). sortSeqs Array Required properties This method requires two parameters of the data type of array.setOrderBy(sortFields. 1. newArray ("name". sortSeqs). It is either a SCFILE_ASC. 2. for example : new Array(SCFILE_ASC. SCFILE_DSC). A warning is written to SM. Calling setOrderBy() with parameters of uneven length of arrays or non-array data results in failure return status. The two arrays must be of the same length. Example Note: If you are running setOrderBy() on a single array. for example. Limitations: • Fields used in setOrderBy() should not be within an array in the dbdict. The following conditions cause a setOrderBy() failure: l l l l l Calling setOrderBy() on an uninitialized SCFile Calling setOrderBy() with an invalid argument type (not an array) for either argument.Programming Guide Chapter 6: JavaScript and Service Manager reference subsequent doSelect() will use the default sort sequence. sortOrder[0] = SCFILE_DSC. timeBefore) + " milliseconds" ). var fRec = new SCFile( table).doSelect( "true" ). and sorts the company field by descending order. RC=" + RCtoString( setOrderByRC ) ).Programming Guide Chapter 6: JavaScript and Service Manager reference l Takes two fields. sortOrder) { var timeBefore = new Date(). var setOrderByRC = fRec. } do { fCount++. print( "doSelect select column OrderBy test : Start time is: " + timeBefore ). from the operator table. RC=" + RCtoString( selectRC ) ). name and company. print( "doSelect select column Orderby test: + fields ). var timeAfter = new Date(). } var selectRC = fRec. if ( selectRC != RC_SUCCESS ) { print( "ERROR: doSelect OrderBy failed. sortOrder). table processed = " + fields processed = " sort order = " + count = " + fCount ). then the name field by ascending order.getNext() == RC_SUCCESS). print( "doSelect select column Orderby test: (timeAfter . return RC_SUCCESS. print( "doSelect select column Orderby test: print( "doSelect select column Orderby test: timeAfter ). On failure returns a RC_ERROR status code.setOrderBy( fields. return RC_ERROR. End time is " + Elapsed time is " + Page 279 of 396 HP Service Manager (9. print( "doSelect select column Orderby test: table ). fields. function runOrderByTest( table. if ( setOrderByRC != RC_SUCCESS ) { print( "ERROR: setOrderBy failed. return RC_ERROR. l This example requires the following sample data: l Records in the operator table that have various company and name fields. var fCount = 0. } while (fRec.30) . print( "doSelect select column Orderby test: sortOrder). fields = new Array("company". testRC = runOrderByTest( table. fields. sortOrder = new Array(SCFILE_DSC. You can also use the XMLDate object and its methods to convert between date/time formats.30) .setType() This method is deprecated as of ServiceCenter version 6. Page 280 of 396 HP Service Manager (9. See "Data types" (on page 21). JavaScript method: SCFile.Programming Guide Chapter 6: JavaScript and Service Manager reference } var var var var table = "operator". sortOrder). SCFILE_ASC).1 with the introduction of the SCFile object. Return values None Example This example does the following: l l l Creates an SCDatum object containing the number of milliseconds you want to convert Sets the data type of the SCDatum object to a Service Manager date/time type Converts the number of milliseconds into a JavaScript date/time This example requires the following sample data: l A number of milliseconds (for example.setType( 3 ).JSDate() ). "1234567890") var millisecs. function findDateTime( num ) { var t = new SCDatum( num ). } millisecs = 1234567890. print( num + " milliseconds is equal to the date: " + t. findDateTime( millisecs ). This method set the data type of Service Manager datum objects. t.setType( dataType ). "name"). The SCFile object now automatically converts Service Manager data types into corresponding JavaScript data types. Arguments The following arguments are valid for this method: Data Argument type dataType Description Number This argument specifies the Service Manager data type for the object. Syntax SCFile. doUpdate().phone></instance></model>". var xmlString = "<model name=\"contacts\" query=\"contact.setRecord(xmlstr). var contactRecord = new SCFile("contacts").name sctype=\"string\">ADMINISTRATOR.30) .name="ADMINISTRATOR.Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript method: scfile_setrecord Sets the SCFile field values from a given XML string.name="ADMINISTRATOR.. Notes l l The input XML string should follow the Service Manager File schema. " + RCtoString( rc ) ).toString()). SYSTEM</contact.name mandatory=\"true\" type=\"string\">ADMINISTRATOR. xmlString)."). You cannot use setRecord() to set dbdict records. SYSTEM\" uniquequery=\"contact. if ( rc == RC_SUCCESS) { print("found contact " + name + ". SYSTEM"\"><keys><contact. contactRecord. code. } else { print("Could not find contact. contactRecord. l Page 281 of 396 HP Service Manager (9. xmlstr ) { print("Searching for contact: "+ name + ". You cannot use setRecord() to set values for files that contain binary data.phone type=\"string\">(335) 123-4567</contact.name=\""+ name + "\"" ).contact_phone. Syntax SCFile.setRecord(). updateContactPhoneFromXML(contactName. SYSTEM"\"><contact. } } var contactName = "ADMINISTRATOR. SYSTEM".name><contact.doSelect( "contact. var rc = contactRecord.toString() ). Example function updateContactPhoneFromXML( name.you cannot use setRecord() for displaycache.. For example.contact_phone. SYSTEM</contact. Argument setRecord("xmlstring").name></keys><instance recordid=\"ADMINISTRATOR. SYSATTACHMENTS files. print("updated phone number in contact record:\n" + contactRecord. phone number:\n" + contactRecord. value ) { print( "Searching for Incident record: " + id + ". Arguments The following arguments are valid for this method: Data Argument type newValue Description String This argument specifies the new value you want the Service Manager object to have.30) .action ). This method does not use the Service Manager global return codes. You must use the slash character to escape out quotation marks and any special characters restricted from JavaScript..." ). print( "Displaying the Incident record: " + incidentFile ). incidentFile. print( "Displaying the contents of the action field as an object: " + incidentFile." ). function findIncident( id. Syntax SCFile. Page 282 of 396 HP Service Manager (9.. print( "Displaying the contents of the action field as an object: " + incidentFile. var rc = incidentFile. "IM1010") A valid action field value update (for example. var newValue.setValue() This method updates an HP Service Manager record with the new field value defined in the newValue argument.doSelect( "number=\"" + id + "\"" ) if ( rc == RC_SUCCESS ) { print( "Success.Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript method: SCFile.setValue( newValue ). found Incident record " + id ).. print( "Setting the value of the action field. var incidentFile = new SCFile( "probsummary" ).setValue( value ). Return values None Example This example does the following: l l l Searches the probsummary table for any incident record you define in the search variable Displays the current value of the action field Sets the value of the action field to any value you define in the input variable This example requires the following sample data: l l A valid incident record with a value in the action field (for example. set the action field to "New description") var incidentID.action.action ). This method does not use the Service Manager global return code values. findIncident( incidentID. The method returns the element removed from the array. Arguments There are no arguments for this method. var rc = incidentFile. "IM1010") An incident record with an action field value (for example. newValue = "New description". Return values A string.shift()..doSelect( "number=\"" + id + "\"" ) Page 283 of 396 HP Service Manager (9..30) . return null } } incidentID = "IM1010". var incidentFile = new SCFile( "probsummary" ). " + RCtoString( rc ) ). newValue ).shift() This method removes the first element from a JavaScript array and returns the element removed as a string. "IM1010") var incidentID.Programming Guide Chapter 6: JavaScript and Service Manager reference return incidentFile } else { print( "Could not find Incident record. Example This example does the following: l l l l l Searches the probsummary table for any incident record you define in the search variable Displays the new incident record as a text string Converts the action field into a JavaScript array Adds an item to the end of the array and displays the total number of elements in the array Removes an item from the beginning of the array and displays the array item removed This example requires the following sample data: l l A valid value for the number field (for example. JavaScript method: SCFile. Syntax SCFile." ). function findIncident( id ) { print( "Searching for Incident record: " + id + ". print( "The action field array contains the following: " + a ). print( "The array item removed was: " + removeOne ).toArray() This method converts an HP Service Manager Datum object into a JavaScript array.30) . found Incident record:\n" + incidentFile. print( "Converting the action field to a JavaScript array." ).." ).toArray(). var a = incidentFile. var addOne = a... var removeOne = a.getText() ).push( "First array item" ). Example This example does the following: l l l Searches the probsummary table for any incident record you define in the search variable Displays the incident record as a text string Converts the contents of the action field into a JavaScript array This example requires the following sample data: Page 284 of 396 HP Service Manager (9. print( "The action field array contains the following: " + a ). return null } } incidentID = "IM1010". findIncident( incidentID ).Programming Guide Chapter 6: JavaScript and Service Manager reference if ( rc == RC_SUCCESS ) { print( "Success. print( "The action field array contains the following: " + a )." ). return incidentFile.. JavaScript method: SCFile.toArray().shift(). Arguments There are no arguments for this method. Return values A JavaScript array and RC_SUCCESS or one of the other global return code values..action.. " + RCtoString( rc ) ). print( "Shifting array one entry. Syntax SCFile. } else { print( "Could not find Incident record. print( "The number of items in the array are: " + addOne ). print( "Pushing new array entry. doSelect( "number=\"" + id + "\"" ) if ( rc == RC_SUCCESS ) { print( "Success. found Incident record:\n" + incidentFile. return null } } incidentID = "IM1010". "IM1010") An incident record with an action field value (for example. findIncident( incidentID ).action. Syntax SCFile. Arguments The following arguments are valid for this method: Data Argument type arrayItem String Description This argument specifies the array item you want to add to a JavaScript array.. return incidentFile } else { print( "Could not find Incident record. print( "The action field contains the following " + a ). The method returns the number of items in the array. var rc = incidentFile. This method does not use the Service Manager global return code values.. then it adds the item but does not return the number of entries in the array. var incidentFile = new SCFile( "probsummary" ). Page 285 of 396 HP Service Manager (9.getText() ).Programming Guide Chapter 6: JavaScript and Service Manager reference l l A valid incident record number (for example. var a = incidentFile.unshift() This method adds an entry to the beginning of a JavaScript array and returns the total number of entries in the array. If you apply this method to a Service Manager array object. Return values A number. "IM1010") var incidentID. " + RCtoString( rc ) )." ).30) ..unshift( arrayItem ).toArray()." ). JavaScript method: SCFile.. function findIncident( id ) { print( "Searching for Incident record: " + id + ". print( "Converting the action field to a JavaScript array. . print( "The action field array contains the following: " + a ).." ). print( "Unshifting array one entry. function findIncident( id ) { print( "Searching for Incident record: " + id + ".." ). var rc = incidentFile. JavaScript method: SCFile. } else { print( "Could not find Incident record. " + RCtoString( rc ) )." ).unshift( "First array item" ). print( "The action field array contains the following: " + a ). found Incident record:\n" + incidentFile. return null } } incidentID = "IM1010". var incidentFile = new SCFile( "probsummary" ). return incidentFile. print( "The number of items in the array are: " + unshifting ). var a = incidentFile.action. findIncident( incidentID ).Programming Guide Chapter 6: JavaScript and Service Manager reference Example This example does the following: l l l l Searches the probsummary table for any incident record you define in the search variable Displays the new incident record as a text string Converts the contents of the action field into a JavaScript array Adds an item to the beginning of the JavaScript array and prints the total number of items in the array This example requires the following sample data: l l A valid value for the number field (for example. The attachment object must contain a valid attachment ID in the "href" property of the attachment object. var unshifting = a...doSelect( "number=\"" + id + "\"" ) if ( rc == RC_SUCCESS ) { print( "Success..getText() ). "IM1010") An incident record with an action field value (for example. "IM1010") var incidentID. print( "Converting the action field to a JavaScript array.30) . as well as Page 286 of 396 HP Service Manager (9.toArray().updateAttachment( attachObj ) This method updates a specific attachment associated with the current file record. var attachmentID = f.getAttachment( attachmentID ). Otherwise.Programming Guide Chapter 6: JavaScript and Service Manager reference valid values for the other required properties (name.name = "MyAttachment. which is an Attachment object. it returns NULL.doSelect( 'number = "IM10001"' ). var f = new SCFile( 'probsummary' ). etc. var f = new SCFile( 'probsummary' ). var attachmentObj = f. Arguments updateAttachment() takes one argument. var rc = f. Syntax SCFile.value = "My text attachment". such as doSelect(). return attachmentID.txt". getNext().doSelect( 'number = "IM10001"' ). and value).insertAttachment( attachmentObj ). } var attachmentID = createTestAttachment(). attachmentObj. Before calling updateAttachment.30) .updateAttachment( attachObj ). type. Return values If successful. // Now update the attachment object Page 287 of 396 HP Service Manager (9. Example This example does the following: l l l Selects one record from the probsummary table Gets a specific attachment associated with the current record Updates the attachment This example requires the following sample data: l l "IM10001" record in "probsummary" table An attachment associated with "IM10001" record function createTestAttachment() { var attachmentObj = new Attachment(). attachmentObj. updateAttachment() returns a string of the form cid:xxxxxx containing the new attachment ID for the attachment. you must establish a current record using one of the positioning methods. attachmentObj. var rc = f.type = "text/plain". <QueryCond object>). This method returns the last position in the record list that has been accessed.value = newValue.Programming Guide Chapter 6: JavaScript and Service Manager reference var newName = "NewName. JavaScript object: SCRecordList The following JavaScript object is unique to HP Service Manager.text".updateAttachment( attachmentObj ). attachmentObj.name = newName. // Do the update. QueryCond object Properties None Methods The following methods are valid for this object: Defined method getCount() getPosition() Description This method returns the total number of records in the SCRecordList. This should result in a new attachment ID var newID = f. SCRecordList is an array of Datums that qualify with the query. probsummary. Example This example does the following: l l lists the location's position in a record list counts the records in the list This example requires the following sample data: Page 288 of 396 HP Service Manager (9. attachmentObj. . Arguments The following arguments are valid for this object: Argument table name Data type String Description The name of the Service Manager table. Service Manager JavaScript object QueryCond which defines the SC query to be executed.30) . Constructor new SCRecordList( <table name>. var newValue = "Updated attachment text value". for example. " ). Syntax SCRecordList. 'a')).getPosition().getCount()). which is position 0. Return values This method returns the total number of records in a record list. Return values Page 289 of 396 HP Service Manager (9. print("Total record in the list: " + x. } JavaScript method: SCRecordList. it returns -1.getPosition() This method returns the position of the last accessed record in the record list. Syntax SCRecordList.30) . new QueryCond('location.Programming Guide Chapter 6: JavaScript and Service Manager reference l l valid location(s) valid record list with at least one record var x = new SCRecordList( 'location'. the position is set to the first element.getCount(). new QueryCond('location. JavaScript method: SCRecordList. 'a')). Arguments There are no arguments for this method. Arguments There are no arguments for this method.name'.getCount() This method counts the total number of records in the SCRecordList.location_name + " is the " + x. LIKE. If there are no records are in the SCRecordList. LIKE. If there is at least one record and it has not been accessed.name'.getCount()). print("Total record in the list: " + x. for (i in x ) { print(x[i].getPosition() + " record in the record list. Example This example does the following: l counts the records in the list This example requires the following sample data: l l valid location(s) valid record list with at least one record var x = new SCRecordList( 'location'. getPosition() + " record in the record list. Constructor new XML().getCount()).30) . 'a')). print("Total record in the list: " + x. Returns -1 if there are no records in the list.location_name + " is the " + x. Returns 0 if list is not yet or the first Datum is the last Datum accessed and the list contains at least one record. Example This example does the following: l l lists the location's position in a record list counts the records in the list This example requires the following sample data: l l valid location(s) valid record list with at least one record var x = new SCRecordList( 'location'. Page 290 of 396 HP Service Manager (9.Programming Guide Chapter 6: JavaScript and Service Manager reference Last position of Datum accessed in record list.name'. Returns an XML object representing the parent node of the current node. Arguments None Properties None Methods The following methods are valid for this object: Defined method setContent getParentNode Description Creates an XML document from a string or file. new QueryCond('location. } JavaScript object: XML The following JavaScript object is unique to HP Service Manager. LIKE. The XML() constructor creates an empty XML object where you can store and manipulate XML documents. for (i in x ) { print(x[i]." ). This object's methods do not use the Service Manager-defined global return codes. Adds or updates the value of the current element. Inserts an XML element as a child of the current element.30) . Creates an XML node from an XML object. Adds or updates an attribute value. Returns a string representing the name of the current element or attribute including any namespace value. Copies an XML node from one XML document to another. Creates an XML object containing the document element and all child elements from an XML object or XML string. Returns a string representing the name of the current element or attribute. Returns a string representing the name of the current element or attribute. Returns an XML object representing the next attribute of the current node. Returns the value of the target attribute. Returns true if the current element is the DOM document element. Inserts an XML node into an XML object. Returns an XML object containing an attribute node.Programming Guide Chapter 6: JavaScript and Service Manager reference getFirstChildElement Returns an XML object representing the first child node of the current node. Returns an XML object representing the next node at the same level in the Document Object Model (DOM) tree as the current node. Returns a string representing the namespace value of the current element or attribute. Returns an XML object representing the first attribute of the current node. Evaluates an XML object and returns an integer representing the XML DOM type of the current element or attribute. Adds or updates the value of the current element. Adds or updates the value of the current element. Inserts an XML attribute and attribute value into the current element. Returns a string representing the value of the current element. Returns a string representing the value of the current element. getNextSiblingElement getFirstAttribute getNextAttribute getNodeName getName getQualifiedName getPrefix getNodeValue getValue setNodeValue setValue getNodeType isDocumentElement getDocumentElement createNode appendNode importNode addAttribute getAttributeNode getAttributeValue setAttributeValue addElement setText Page 291 of 396 HP Service Manager (9. addAttribute() This method inserts an XML attribute and attribute value into the current element. Arguments The following arguments are valid for this method: Argument Data type Description AttributeName String This argument specifies the text string you want the script to use as the XML attribute name. } JavaScript method: XML. AttributeValue ). The string argument must contain characters valid for an XML element (for example. true ) ) { print( "setContent failed.30) . /* Instantiate a variable containing the path to an XML file */ var xmlFile = "C:\\myxmldoc. Converts an XML object into a valid XML string. print an error message */ if ( ! xmlObj. AttributeValue String This argument specifies the text string you want the script to use as the XML attribute value.addAttribute( AttributeName. the string cannot include the characters < or >).Programming Guide Chapter 6: JavaScript and Service Manager reference getText toXMLString Returns a string representing the value of the current element. Syntax XML.xml" containing "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2><child3 /><child4 /></parent2></document>") /* Instantiate an empty XML object */ var xmlObj = new XML(). /* Use setContent to make the XML object read and parse the XML file * If the setContent method fails.xml". This argument must contain characters valid for an XML element (for example. It requires you use the other XML get methods to navigate through an XML document. a file called "C:\test. Example This example does the following: l l Creates an XML object Sets the content of the XML object to a local XML file This example requires the following sample data: l A local XML file (for example. Page 292 of 396 HP Service Manager (9. the string cannot include the characters < or >).setContent( xmlFile. Unable to parse xml: " + xmlFile ). /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element.getFirstChildElement().getNodeName() != targetElem ) { var childNode = node. var AttributeName.setContent( "C:\\test02.getNextSiblingElement(). var TargetNode. If successful. * This function assumes that there is only one instance of the target * element in the source data. XMLFile = XMLFile. if (childNode == null) { childNode = node. var searchResults. Page 293 of 396 HP Service Manager (9. the method returns the updated XML element. var printResults. while (childNode == null) { node = node. if ( node == null || topNodeName == node. * Use XMLObject to store a valid XML object such as an XML file.getParentNode(). it returns null. a file called "C:\test02. true ). } childNode = node.30) . * Use sourceXMLString to store a valid XML string.xml". * The script sets the content of XMLString to sourceXMLString.getNodeName(). while (node != null && node. Example This example adds a new attribute and attribute value to any element you select from an XML document. var XMLSource.xml" containing "<document><parent1>value1</parent1><parent2></parent2></document>") /* Create variables to store XML objects and strings. * The script assigns values to the empty variables later on */ var XMLFile = new XML(). This example requires the following sample data: l A local XML file (for example. If it finds more than one element in the * data it only returns the first instance of the element. targetElem ) { var topNodeName = node. */ function findTargetElement( node.getNodeName() ) { return null.getNextSiblingElement().Programming Guide Chapter 6: JavaScript and Service Manager reference Return values An XML object or null. Otherwise. var AttributeValue. \n" ).getNodeName().addAttribute( attrName. TargetNode = "parent1" XMLSource = XMLFile searchResults = findTargetElement( XMLSource. AttributeValue ). attrName. targetNode. attrValue ) { print( "The target element we are looking for is: " + targetNode ). AttributeName = "id"... AttributeValue = "test". return null } } /* Set variable values for XMLFile and TargetNode. } else { node = childNode.30) .Programming Guide Chapter 6: JavaScript and Service Manager reference } node = childNode. } } return node. TargetNode ). } /* Create a function to print the target element and search results */ function createNewAttribute( searchResult. print( "The new object is:\n" + searchResult ). Page 294 of 396 HP Service Manager (9. searchResult. TargetNode. Run functions. print( "Adding new attribute " + attrName + " to element " + elementName ). return searchResult } else { print( "Cannot find " + target ). print( "Found element " + elementName + " in: \n" + searchResult + "\n" ). if ( searchResult != null ) { var elementName = searchResult. */ print( "Processing XML from XMLFile. AttributeName. attrValue ). createNewAttribute( searchResults. xml".addElement( String ). * The script assigns values to the empty variables later on */ var XMLFile = new XML(). * Use sourceXMLString to store a valid XML string. Return values An XML object or null. This example requires the following sample data: l A local XML file (for example.30) . a file called "C:\test02. Arguments The following arguments are valid for this method: Data Argument type String Description String This argument specifies the text string you want the script to use as the XML element name. * The script sets the content of XMLString to sourceXMLString.xml" containing "<document><parent1>value1</parent1><parent2></parent2></document>") /* Create variables to store XML objects and strings. true ).setContent( "C:\\test02. /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element. var XMLSource.addElement() This method inserts an XML element as a child of the current element. If it finds more than one element in the Page 295 of 396 HP Service Manager (9. Example This example adds a child element to any element you select in an XML document. var searchResults. var NewNodeName. * Use XMLObject to store a valid XML object such as an XML file. You must use the other XML get methods to navigate through an XML document. var printResults. var TargetNode. The method returns an XML object containing the new element or returns null if the method cannot add the element.Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript method: XML. The string argument must contain characters valid for an XML element (for example. Syntax XML. the string cannot include the characters < or >). * This function assumes that there is only one instance of the target * element in the source data. XMLFile = XMLFile. } node = childNode.addElement( nodeName ). targetNode. var newNode = searchResult. nodeName ) { print( "The target element we are looking for is: " + targetNode ).getParentNode().getNodeName() != targetElem ) { var childNode = node.getNextSiblingElement(). print( "Adding new node " + nodeName + " to element " + elementName ). if ( node == null || topNodeName == node.getNextSiblingElement(). if ( searchResult != null ) { var elementName = searchResult. } else { node = childNode. if (childNode == null) { childNode = node.getNodeName(). targetElem ) { var topNodeName = node.30) .getNodeName(). } childNode = node. } } return node. return null } Page 296 of 396 HP Service Manager (9.Programming Guide Chapter 6: JavaScript and Service Manager reference * data it only returns the first instance of the element. */ function findTargetElement( node. return searchResult } else { print( "Cannot find " + target ). while (childNode == null) { node = node. print( "Found element " + elementName + " in: \n" + searchResult + "\n" ). while (node != null && node.getFirstChildElement(). print( "The new object is:\n" + searchResult ).getNodeName() ) { return null. } /* Create a function to print the target element and search results */ function createNewNode( searchResult. NewNodeName = "child8". JavaScript method: XML. var NewNodeValue. createNewNode( searchResults. Syntax XML.appendNode() This method inserts an XML node into an XML object. */ print( "Processing XML from XMLFile.. TargetNode ). TargetNode = "parent1" XMLSource = XMLFile searchResults = findTargetElement( XMLSource.setContent( "<document> </document>" ). Arguments The following arguments are valid for this method: Data Argument type name Description String This argument specifies the XML node name you want to append to the target XML object.appendNode( name ). var NewNodeName. Example This example appends an XML node to an XML source object. XMLObject = XMLObject. NewNodeName ).. var TargetNode. targetElem ) { Page 297 of 396 HP Service Manager (9. Return values An XML object or null. TargetNode.Programming Guide Chapter 6: JavaScript and Service Manager reference } /* Set variable values for XMLFile and TargetNode. This method does not update the existing XML object. The method returns an XML object containing the new node or returns null if the method cannot append the node to the current target node. function findTargetElement( node.). and >. This example requires the following sample data: l An XML object (for example. the string cannot include the characters < or > except as XML entities such as <. There must be an existing XML object with a document element. Run functions. The string argument must contain characters valid for XML (for example. \n" ). an object containing "<document> </document>") var XMLObject = new XML.30) . var NewNodeType. var appendedNode = FoundNode. TargetNode = "document". } function appendNewNode( type. target ) { print( "The XML source object is: " + xmlSource). name. NewNodeName = "node". } childNode = node. var NewNode = xmlSource. while (childNode == null) { node = node. } else { node = childNode. NewNodeValue = "test". } NewNodeType = 1. } node = childNode. if ( node == null || topNodeName == node. value ).getNodeName() != targetElem ) { var childNode = node. name.getFirstChildElement().getNodeName().appendNode( NewNode ). NewNodeValue. while (node != null && node. xmlSource. Page 298 of 396 HP Service Manager (9. var FoundNode = findTargetElement( xmlSource.createNode( type. value. NewNodeName.getParentNode(). } } return node.Programming Guide Chapter 6: JavaScript and Service Manager reference var topNodeName = node. print( "Appending " + NewNode.toXMLString() + " to: " + target ).getNextSiblingElement(). target ). XMLObject. appendNewNode( NewNodeType.getNextSiblingElement().getNodeName() ) { return null. print( "The new XML object is: " + xmlSource ).30) . if (childNode == null) { childNode = node. TargetNode ). print( "Creating node of type: " + type + " named: " + name + " with value: " + value ). The string argument must contain characters valid for XML (for example. This argument specifies the text string you want the script to add as the XML node value.). 2. and >. the string cannot include the characters < or > except as XML entities such as <. It requires an existing XML object with a document element. name value String Return values An XML object or null. String This argument specifies the text string you want the script to add as the XML node name.).Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript method: XML. name. function createNewNode( type. var NewNodeName.createNode( type. XMLObject = XMLObject. an object containing "<document> </document>") var XMLObject = new XML("document"). The new method requires a rootname. the string cannot include the characters < or > except as XML entities such as <. name. The method returns an XML object containing the new node or returns null if the method cannot create the node. Arguments The following arguments are valid for this method: Data Argument type type Description Integer This argument specifies the XML DOM node type for the node you want the script to create. The string argument must contain characters valid for XML (for example.createNode() This method creates an XML node from an XML object. Example This example creates an XML node from an XML source object. This example requires the following sample data: l An XML object (for example. var NewNodeType. This method only accepts XML DOM types 1. Page 299 of 396 HP Service Manager (9. value ). and >. and 3.setContent( "<document> </document>" ). name.30) . value. but it does not update the existing XML object. var NewNodeValue. See the W3C Web site for a complete listing of XML DOM nodetypes by integer. Syntax XML. print( "Creating node of type: " + type + " named: " + name + " with value: " + value ). value ). xmlSource ) { print( "The XML source object is: " + xmlSource).createNode( type. var NewNode = xmlSource. Return values An XML object or null.getName() ). Syntax XML. NewNodeName. NewNodeValue = "test". Example This example searches for a particular attribute of any given element in an XML document. createNewNode( NewNodeType. NewNodeName = null. XMLObject ).getAttributeNode( Attribute ). NewNodeName. } NewNodeType = 1. NewNodeValue. NewNodeName = "node". NewNodeValue = "Text node". NewNodeValue. You must use the other XML get methods to navigate through an XML document.Programming Guide Chapter 6: JavaScript and Service Manager reference print( "The XML source object remains unchanged: " + XMLObject ).getAttributeNode() This method returns an XML object containing the target attribute. createNewNode( NewNodeType. or returns null if the method cannot find the target attribute in the current element. print( "The new node converted to an XML string is: " + NewNode. NewNodeName = "id". The method returns an XML object containing the target attribute. print( "Applying the getName method to the new node produces: " + NewNode. This example requires the following sample data: Page 300 of 396 HP Service Manager (9. NewNodeValue = "test". NewNodeType = 2.getValue() ).30) . or returns null if the method cannot find the target attribute in the current element.toXMLString() ). XMLObject ). JavaScript method: XML. XMLObject ). createNewNode( NewNodeType. Arguments The following arguments are valid for this method: Data Argument type Attribute String Description This argument specifies the XML attribute you want the script to return. NewNodeName. NewNodeValue. print( "Applying the getValue method on the new node produces: " + NewNode. NewNodeType = 3. if (childNode == null) { childNode = node.getNodeName().getNodeName() != targetElem ) { var childNode = node. } childNode = node. while (node != null && node. if ( node == null || topNodeName == node. } Page 301 of 396 HP Service Manager (9. } node = childNode. a file called "C:\test. var TargetNode. * This function assumes that there is only one instance of the target * element in the source data. * The script assigns values to the empty variables later on */ var XMLFile = new XML(). XMLFile = XMLFile.30) . targetElem ) { var topNodeName = node. /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element. } } return node.getNodeName() ) { return null.getNextSiblingElement(). var XMLSource.xml" containing "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2><child3 /><child4 /></parent2></document>") /* Create variables to store XML objects and strings.getFirstChildElement(). true ). while (childNode == null) { node = node.getNextSiblingElement().getParentNode().setContent( "C:\\test.Programming Guide Chapter 6: JavaScript and Service Manager reference l A local XML file (for example.xml". */ function findTargetElement( node. * Use XMLFile to store a valid XML file. If it finds more than one element in the * data it only returns the first instance of the element. var searchResults. } else { node = childNode. var TargetAttribute. Programming Guide Chapter 6: JavaScript and Service Manager reference /* Create a function to print the target element and search results */ function printFindResults( target. searchResult. var attributeFound = findAttributeNode( searchResult. Did not find attribute " + attribute ). Run functions print( "Processing XML from XMLFile.30) . \n" ). attribute ).. var attributeNode = sourceObject. Found attribute " + attributeNode ). return null } } /* Create a function to find the attribute node of the target element */ function findAttributeNode( sourceObject. if ( attributeNode != null ) { print( "Success..getNodeName(). attribute ) { print( "Looking for attribute node " + attribute ). attribute ) { print( "The target element we are looking for is: " + target ). TargetAttribute = "attribute1". TargetAttribute ). TargetNode ). TargetNode = "child1".getAttributeNode( attribute ). */ Page 302 of 396 HP Service Manager (9. searchResults. XMLSource = XMLFile. return null } } /* Set variable values for XMLFile and TargetNode. return attributeNode } else { print( "Fail. printFindResults( TargetNode. return attributeFound } else { print( "Cannot find " + target ). searchResults = findTargetElement( XMLSource. if ( searchResult != null ) { var elementName = searchResult. print( "Found element " + elementName + " in: \n" + searchResult + "\n" ). Page 303 of 396 HP Service Manager (9. This example requires the following sample data: l A local XML file (for example. a file called "C:\test. Example This example searches for the attribute value of any given element in an XML document. /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element.getNodeName().30) . Arguments The following arguments are valid for this method: Data Argument type Attribute String Description This argument specifies the XML attribute whose value you want the script to return.Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript method: XML. */ function findTargetElement( node.setContent( "C:\\test. Return values A string or null.getAttributeValue( Attribute ). * This function assumes that there is only one instance of the target * element in the source data. If it finds more than one element in the * data it only returns the first instance of the element. var searchResults. var TargetNode. targetElem ) { var topNodeName = node. * Use XMLFile to store a valid XML file.xml". true ). The method returns the string value of the target attribute or returns null if the method cannot find an attribute value. You must use the other XML get methods to navigate through an XML document. XMLFile = XMLFile. var XMLSource.getAttributeValue() This method returns the value of the target attribute.xml" containing "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2><child3 /><child4 /></parent2></document>") /* Create variables to store XML objects and strings. Syntax XML. * The script assigns values to the empty variables later on */ var XMLFile = new XML(). var TargetAttribute. getNextSiblingElement().getNodeName() != targetElem ) { var childNode = node. return attributeFound } else { print( "Cannot find " + target ).getNodeName() ) { return null.getNodeName().getParentNode(). searchResult. if (childNode == null) { childNode = node.getFirstChildElement(). } } return node. attribute ) { print( "The target element we are looking for is: " + target ). if ( node == null || topNodeName == node. var attributeFound = findAttributeValue( searchResult.getNextSiblingElement(). } childNode = node. } /* Create a function to print the target element and search results */ function printFindResults( target. return null } } /* Create a function to find the attribute node of the target element */ function findAttributeValue( sourceObject. attribute ).30) .Programming Guide Chapter 6: JavaScript and Service Manager reference while (node != null && node. while (childNode == null) { node = node. print( "Found element " + elementName + " in: \n" + searchResult + "\n" ). attribute ) { Page 304 of 396 HP Service Manager (9. } else { node = childNode. if ( searchResult != null ) { var elementName = searchResult. } node = childNode. Note: You cannot use this method on objects that you have converted using the toXMLString method. TargetAttribute ). TargetAttribute = "attribute1". It creates an XML object containing the document element and all child elements from an XML object or XML string.users) A valid XML string (for example.getDocumentElement() This method searches an XML object for the DOM document element (or "root" node). Arguments There are no arguments for this method. "<document><parent1><child1 attribute1=\"1\" /></parent1><parent2 /></document>") Page 305 of 396 HP Service Manager (9. Syntaz XML. searchResults = findTargetElement( XMLSource.. printFindResults( TargetNode. XMLSource = XMLFile. this method returns an XML object containing the document element and all of its child elements. This method returns null if applied to an empty or invalid XML object. Example This example displays the XML document element from four different input sources.getDocumentElement(). TargetNode = "child1". The value of " + attribute + " is " + attributeValue ). Run functions print( "Processing XML from XMLFile. the list of currently logged on users stored in system.Programming Guide Chapter 6: JavaScript and Service Manager reference print( "Looking for attribute value of " + attribute ). searchResults. \n" ). TargetNode ).getAttributeValue( attribute ). */ JavaScript method: XML. return null } } /* Set variable values for XMLFile and TargetNode. This example requires the following sample data: l l A valid XML object (for example. return attributeValue } else { print( "Fail. If successful. var attributeValue = sourceObject. if ( attributeValue != null ) { print( "Success..30) . Return values An XML object or null. Did not find attribute " + attribute ). return DocElem } else { print( "Error.setContent( badXML ). print( "Success.\n" ). */ function getDocElem( document ) { var DocElem = document.setContent( goodXML ).users var xmlString = new XML(). print( "The value of xmlBad is:\n" + xmlBad ).Programming Guide Chapter 6: JavaScript and Service Manager reference l A noncompliant XML string (for example. Page 306 of 396 HP Service Manager (9.. "<document1><parent1 /></document1><document2><parent2 /></document2>") An empty XML object l /* Create variables to store XML objects and strings. * The script sets the content of xmlEmpty to an XML object.30) . * Print the objects returned by each function. /* Create a function to execute the getDocumentElement method on the document argument.getDocumentElement(). xmlString = xmlString. var xmlEmpty = new XML(). Did not find document element in the following object: \n" + document ). xmlBad = xmlBad. in this case a second document element. if ( DocElem != null ) { var DocElemName = DocElem. Found the document element " + DocElemName + " in the following object: \n" + document ).. */ var goodXML = "<document><parent1><child1 attribute1=\"1\" /></parent1><parent2 /></document>" var badXML = "<document1><parent1 /></document1><document2><parent2 /></document2>" var xmlObject = system. return null } } /* Run the getDocElem and getDocElemName functions on four input sources. * Use xmlObject to store a valid XML object such as the system. var xmlBad = new XML(). * The script sets the content of xmlBad to badXML. * Use badXML to store any erroneous XML string.getNodeName(). */ print( "Now searching for a document element in a valid XML object.users list * The script sets the content of xmlString to goodXML. * Use goodXML to store a valid XML string. print( "Now searching for a document element in a valid XML string.xml" containing "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2><child3 /><child4 /></parent2></document>") A valid XML string (for example.. getFirstAttribute(Element) Arguments The following arguments are valid for this method: Data Argument type Element Description String This argument contains the name of the element you want the method to use as the starting position when searching for the first attribute. The example allows you to select an element from two different input sources. Page 307 of 396 HP Service Manager (9.\n" ). print( "Now searching for a document element in an empty XML object. getDocElem( xmlBad ). * Use sourceXMLString to store a valid XML string. getDocElem( xmlEmpty ).\n" ). getDocElem( xmlString ).. "<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1><parent2 /></document>") l /* Create variables to store XML objects and strings.getFirstAttribute()...getFirstAttribute() This method returns an XML object representing the first attribute of the current node. Example This example displays the first attribute of any element you select. Return values An XML object or null. JavaScript method: XML. The method returns an object representing the first attribute of the current node or returns null if the XML object has no attributes.Programming Guide Chapter 6: JavaScript and Service Manager reference getDocElem( xmlObject ).. * The script sets the content of XMLString to sourceXMLString. a file called "C:\test. * The script assigns values to the empty variables later on */ var XMLFile = new XML(). * Use XMLObject to store a valid XML object such as an XML file.. Syntax XML. print( "Now searching for a document element in a non-compliant XML string. This example requires the following sample data: l A local XML file (for example.\n" ).30) . searchResult ) Page 308 of 396 HP Service Manager (9.getNodeName() != targetElem ) { var childNode = node. if ( node == null || topNodeName == node. XMLString = XMLString.getNextSiblingElement(). var TargetNode. var searchResults. var XMLString = new XML().setContent( "C:\\test.30) .getFirstChildElement(). * This function assumes that there is only one instance of the target * element in the source data.xml".getParentNode(). while (childNode == null) { node = node. } } return node. If it finds more than one element in the * data it only returns the first instance of the element.Programming Guide Chapter 6: JavaScript and Service Manager reference XMLFile = XMLFile. } else { node = childNode. } node = childNode. if (childNode == null) { childNode = node. /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element. targetElem ) { var topNodeName = node. var attributeResults. while (node != null && node. true ). var sourceXMLString = "<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1><parent2 /></document>".getNodeName(). var XMLSource. */ function findTargetElement( node.setContent( sourceXMLString ).getNextSiblingElement(). } childNode = node. } /* Create a function to print the target element and search results */ function printFindResults( target.getNodeName() ) { return null. } } /* Set variable values for XMLFile and TargetNode. Run functions print( "Processing XML from XMLFile. return null } } /* Create a function to find the first attribute of the target element */ function findFirstAttribute( sourceObject. return searchResult } else { print( "Cannot find " + target ). TargetNode = "child1" */ Page 309 of 396 HP Service Manager (9.getFirstAttribute(). print( "Found element " + elementName + " in: \n" + searchResult + "\n" ).30) . print( "The first attribute of " + target + " is: " + attributeName ).getNodeName().Programming Guide Chapter 6: JavaScript and Service Manager reference { if ( searchResult != null ) { var elementName = searchResult. \n" ). targetNode ) var attribute = startingNode.getNodeName(). if ( attribute != null ) { return attribute } else { return null } } /* Create a function to print the first attribute of the target element */ function printAttributeResults( target... targetNode ) { var startingNode = findTargetElement( sourceObject. } else { print( "There are no attributes of " + target ). searchResult ) { if ( searchResult != null ) { var attributeName = searchResult. TargetNode ). printAttributeResults( TargetNode. The method returns an object representing the first child node of the current node or returns null if the XML object has no child node. Example This example displays the first child element of any element you select. \n" ).. attributeResults ). searchResults ). /* Set variable values for XMLFile and TargetNode.xml" containing "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2><child3 /><child4 /></parent2></document>") A valid XML string (for example.Programming Guide Chapter 6: JavaScript and Service Manager reference XMLSource = XMLFile print( "The target element we are looking for is: " + TargetNode ).getFirstChildElement() This method returns an XML object representing the first child node of the current node. printAttributeResults( TargetNode. "<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1><parent2 /></document>") l /* Create variables to store XML objects and strings. Run functions */ print( "Processing XML from XMLString. This example requires the following sample data: l A local XML file (for example. searchResults ). Syntax XML. attributeResults = findFirstAttribute( XMLSource. The example allows you to select an element from two different input sources. TargetNode ). Page 310 of 396 HP Service Manager (9..getFirstChildElement(). printFindResults( TargetNode. printFindResults( TargetNode.30) . TargetNode ). a file called "C:\test. JavaScript method: XML. searchResults = findTargetElement( XMLSource. Return values An XML object or null. TargetNode ). getFirstChildElement(Element) Arguments The following arguments are valid for this method: Data Argument type Element Description String This argument contains the name of the element you want the method to use as the starting position when searching for the first child element. attributeResults ). attributeResults = findFirstAttribute( XMLSource. TargetNode = "child2" XMLSource = XMLString print( "The target element we are looking for is: " + TargetNode ). searchResults = findTargetElement( XMLSource. } else { node = childNode. * This function assumes that there is only one instance of the target * element in the source data. var childResults.xml". * The script assigns values to the empty variables later on */ var XMLFile = new XML().getNodeName() ) { return null. var searchResults. var TargetNode. var XMLSource.setContent( "C:\\test.getParentNode(). * The script sets the content of XMLString to sourceXMLString. var XMLString = new XML().getNodeName() != targetElem ) { var childNode = node. XMLString = XMLString. while (childNode == null) { node = node. If it finds more than one element in the * data it only returns the first instance of the element. */ function findTargetElement( node. } childNode = node. targetElem ) { var topNodeName = node. if ( node == null || topNodeName == node.setContent( sourceXMLString ). true ). var sourceXMLString = "<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1><parent2 /></document>". XMLFile = XMLFile.Programming Guide Chapter 6: JavaScript and Service Manager reference * Use XMLObject to store a valid XML object such as an XML file. /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element. } node = childNode.30) . * Use sourceXMLString to store a valid XML string.getNextSiblingElement().getNodeName(). Page 311 of 396 HP Service Manager (9. while (node != null && node.getFirstChildElement().getNextSiblingElement(). } } return node. if (childNode == null) { childNode = node. getNodeName(). } else { print( "There are no child elements of " + target ).Programming Guide Chapter 6: JavaScript and Service Manager reference } /* Create a function to print the target element and search results */ function printFindResults( target. targetNode ) var firstChild = startingNode. searchResult ) { if ( searchResult != null ) { var childName = searchResult. return searchResult } else { print( "Cannot find " + target ). return null } } /* Create a function to find the first child element of the target element */ function findFirstChild( sourceObject. print( "The first child element of " + target + " is: " + childName ). searchResult ) { if ( searchResult != null ) { var elementName = searchResult.getNodeName(). targetNode ) { var startingNode = findTargetElement( sourceObject. print( "Found element " + elementName + " in: \n" + searchResult + "\n" ). } Page 312 of 396 HP Service Manager (9. if ( firstChild != null ) { return firstChild } else { return null } } /* Create a function to print the first child element of the target element */ function printChildResults( target.30) .getFirstChildElement(). printFindResults( TargetNode. This example requires the following sample data: l A local XML file (for example. TargetNode = "parent2" XMLSource = XMLString print( "The target element we are looking for is: " + TargetNode ).. \n" ). /* Set variable values for XMLFile and TargetNode. TargetNode ). Page 313 of 396 HP Service Manager (9. JavaScript method: XML. printFindResults( TargetNode.. searchResults )..Programming Guide Chapter 6: JavaScript and Service Manager reference } /* Set variable values for XMLFile and TargetNode. The method returns a string representing the name of the current element or attribute. TargetNode = "parent1" XMLSource = XMLFile print( "The target element we are looking for is: " + TargetNode ). searchResults = findTargetElement( XMLSource.xml" containing "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2><child3 /><child4 /></parent2></document>") A valid XML string (for example. Return values A string or null. Run functions */ print( "Processing XML from XMLString.getName(). "<document><parent1><child1>0123</child1></parent1></document>"") l /* Create variables to store XML objects and strings. It returns null if the current node has no name. childResults ). TargetNode ). a file called "C:\test. childResults ). searchResults = findTargetElement( XMLSource. This method is a synonym for getNodeName().30) .getName() This method returns a string representing the name of the current element or attribute. You must use the other XML get methods to navigate through an XML document... printChildResults( TargetNode. Syntax XML. \n" ). childResults = findFirstChild( XMLSource. childResults = findFirstChild( XMLSource. searchResults ). Example This example displays the names of the elements and attributes in an XML document. TargetNode ). Arguments There are no arguments for this method. Run functions */ print( "Processing XML from XMLFile. printChildResults( TargetNode. TargetNode ). setContent( sourceXMLString ). var attrValue = node. Page 314 of 396 HP Service Manager (9.getName() ). true ). XMLSource = XMLString walkXML( XMLSource ).getName(). var XMLString = new XML(). XMLFile = XMLFile.30) .getNodeValue().getNextSiblingElement(). print( "Attribute " + attrName + " = " + attrValue ). print( "Now printing the structure of an XML string. XMLString = XMLString.Programming Guide Chapter 6: JavaScript and Service Manager reference * Use XMLObject to store a valid XML object such as an XML file.getName(). function walkXML( elem ) { print( "Element " + elem. var XMLSource. } var child = elem.getName() + " is: " + nodeValue ). XMLSource = XMLFile walkXML( XMLSource ). * The script assigns values to the empty variables later on */ var XMLFile = new XML().getNodeValue().getNextAttribute()...xml". var sourceXMLString = "<document><parent1><child1>0123</child1></parent1></document>". walkXML( child ). node = elem.setContent( "C:\\test. child = child. var node = elem. while( node != null ) { var attrName = node..getNodeValue().\n" ).getFirstChildElement(). * The script sets the content of XMLString to sourceXMLString.\n" ).getFirstAttribute(). } var nodeValue = elem. if ( typeof nodeValue == "string" && nodeValue..length > 0 ) { print( "Element value of " + elem. while( child != null ) { var nodeName = child. * Use sourceXMLString to store a valid XML string. } } print( "Now printing the structure of an XML file. var nodeValue = child. true ). var XMLString = new XML(). XMLString = XMLString. var sourceXMLString = "<document><parent1><child1 /><child2 attribute2=\"b\" attribute3=\"c\" /></parent1><parent2 /></document>".xml".getNextAttribute(). The example allows you to select an element from two different input sources. * Use XMLObject to store a valid XML object such as an XML file. var TargetNode.30) . "<document><parent1><child1 /><child2 attribute2=\"b\" attribute3=\"c\" /></parent1><parent2 /></document>") l /* Create variables to store XML objects and strings.xml" containing "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2><child3 /><child4 /></parent2></document>") A valid XML string (for example. * Use sourceXMLString to store a valid XML string. Return values An XML object or null. * The script assigns values to the empty variables later on */ var XMLFile = new XML(). var attributeResults. var searchResults. This example requires the following sample data: l A local XML file (for example.setContent( "C:\\test. The method returns an object representing the first attribute of the current node or returns null if the XML object has no attributes.getNextAttribute() This method returns an XML object representing the next attribute of the current node. /* Create a function that searches an XML object (node) for a Page 315 of 396 HP Service Manager (9. var XMLSource. a file called "C:\test. * The script sets the content of XMLString to sourceXMLString. getNextAttribute(Element) Arguments The following arguments are valid for this method: Data Argument type Element Description String This argument contains the name of the element you want the method to use as the starting position when searching for the first attribute. Example This example displays the first attribute of any element you select. Syntax XML. XMLFile = XMLFile.Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript method: XML.setContent( sourceXMLString ). getNodeName() != targetElem ) { var childNode = node.getParentNode(). while (node != null && node. searchResult ) { if ( searchResult != null ) { var elementName = searchResult.getNextSiblingElement().getNodeName().getNextSiblingElement().getFirstChildElement(). if (childNode == null) { childNode = node. } /* Create a function to print the target element and search results */ function printFindResults( target. } } return node.getNodeName() ) { return null. } node = childNode. */ function findTargetElement( node. If it finds more than one element in the * data it only returns the first instance of the element. while (childNode == null) { node = node. if ( node == null || topNodeName == node. return searchResult } else { print( "Cannot find " + target ). } else { node = childNode. print( "Found element " + elementName + " in: \n" + searchResult + "\n" ).getNodeName().Programming Guide Chapter 6: JavaScript and Service Manager reference particular * element (targetElem) and returns an XML object containing the element. targetElem ) { var topNodeName = node. Page 316 of 396 HP Service Manager (9.30) . * This function assumes that there is only one instance of the target * element in the source data. } childNode = node. targetNode ) { var startingNode = findTargetElement( sourceObject.getNodeName(). if ( firstAttribute != null ) { var nextAttribute = startingNode. searchResult ) { if ( searchResult != null ) { var attributeName = searchResult. return searchResult } else { print( "There are no attributes of " + target ).Programming Guide Chapter 6: JavaScript and Service Manager reference return null } } /* Create a function to find the first attribute of the target element */ function findFirstAttribute( sourceObject. targetNode ) var firstAttribute = startingNode.30) . while ( nextAttribute != null ) { var attributeName = nextAttribute.getFirstAttribute(). targetNode ) var firstAttribute = startingNode. Page 317 of 396 HP Service Manager (9. if ( firstAttribute != null ) { return firstAttribute } else { return null } } /* Create a function to print the first attribute of the target element */ function printAttributeResults( target.getNextAttribute().getNodeName(). return null } } /* Create a function to find the next attribute of the target element */ function findNextAttribute( sourceObject.getFirstAttribute(). targetNode ) { var startingNode = findTargetElement( sourceObject. print( "The first attribute of " + target + " is: " + attributeName ). getNextAttribute(). TargetNode = "child1" XMLSource = XMLFile print( "The target element we are looking for is: " + TargetNode ). searchResults ). findNextAttribute( XMLSource. nextAttribute = nextAttribute. Run functions */ print( "Processing XML from XMLString. TargetNode ). TargetNode ).. printAttributeResults( TargetNode. TargetNode ). searchResults ). TargetNode ). Syntax XML. \n" ).. JavaScript method: XML. getNextSiblingElement(Element) Arguments The following arguments are valid for this method: Data Argument type Description Page 318 of 396 HP Service Manager (9. findNextAttribute( XMLSource. attributeResults ).getNextSiblingElement(). attributeResults = findFirstAttribute( XMLSource. /* Set variable values for XMLFile and TargetNode. printFindResults( TargetNode. } print( "There are no more attributes of " + targetNode )..Programming Guide Chapter 6: JavaScript and Service Manager reference print( "The next attribute of " + targetNode + " is: " + attributeName ). searchResults = findTargetElement( XMLSource. TargetNode ). TargetNode = "child2" XMLSource = XMLString print( "The target element we are looking for is: " + TargetNode ). TargetNode ).30) . return targetNode } else { return null } } /* Set variable values for XMLFile and TargetNode.getNextSiblingElement() This method returns an XML object representing the next node at the same level in the Document Object Model (DOM) tree as the current node. \n" ).. Run functions */ print( "Processing XML from XMLFile. attributeResults = findFirstAttribute( XMLSource. attributeResults ). searchResults = findTargetElement( XMLSource. printFindResults( TargetNode. printAttributeResults( TargetNode. Return values An XML object or null. while (node != null && node. Page 319 of 396 HP Service Manager (9. /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element. * This function assumes that there is only one instance of the target * element in the source data. Example This example displays the next sibling element of any element you select.getNodeName() != targetElem ) { var childNode = node. * Use XMLObject to store a valid XML object such as an XML file. */ function findTargetElement( node. a file called "C:\test. var XMLSource. * The script sets the content of XMLString to sourceXMLString. XMLFile = XMLFile.Programming Guide Chapter 6: JavaScript and Service Manager reference Element String This argument contains the name of the element you want the method to use as the starting position when searching for the next sibling element. true ). var TargetNode. This example requires the following sample data: l A local XML file (for example. XMLString = XMLString.xml".getNodeName(). "<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1><parent2 /></document>") l /* Create variables to store XML objects and strings.xml" containing "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2><child3 /><child4 /></parent2></document>") A valid XML string (for example. If it finds more than one element in the * data it only returns the first instance of the element. targetElem ) { var topNodeName = node.getFirstChildElement(). * The script assigns values to the empty variables later on */ var XMLFile = new XML(). var sourceXMLString = "<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1><parent2 /></document>".setContent( sourceXMLString ). var searchResults. * Use sourceXMLString to store a valid XML string.30) . var XMLString = new XML(). The method returns an object representing the next node at the same level in the DOM tree as the current node or returns null if the XML object has no sibling node.setContent( "C:\\test. The example allows you to select an element from two different input sources. var siblingResults. getParentNode().getNextSiblingElement(). searchResult ) { if ( searchResult != null ) { var elementName = searchResult. if ( node == null || topNodeName == node. } } return node.Programming Guide Chapter 6: JavaScript and Service Manager reference if (childNode == null) { childNode = node. return null } } /* Create a function to find the next sibling element of the target element */ function findNextSibling( sourceObject.getNextSiblingElement(). targetNode ) { var startingNode = findTargetElement( sourceObject. while (childNode == null) { node = node. } else { node = childNode.getNextSiblingElement().30) . } node = childNode. } /* Create a function to print the target element and search results */ function printFindResults( target. targetNode ) var nextSibling = startingNode.getNodeName().getNodeName() ) { return null. return searchResult } else { print( "Cannot find " + target ). } childNode = node. if ( nextSibling != null ) { return nextSibling } Page 320 of 396 HP Service Manager (9. print( "Found element " + elementName + " in: \n" + searchResult + "\n" ). \n" ). printFindResults. } else { print( "There are no sibling elements of " + target ). searchResults = findTargetElement( XMLSource. and * printAttributeResults on the XMLString and TargetNode */ print( "Processing XML from XMLString. siblingResults ). Page 321 of 396 HP Service Manager (9. printSiblingResults( TargetNode. \n" ). printFindResults. searchResults ). } } /* Set variables to search the XMLFile for the TargetNode. TargetNode ). searchResults ). TargetNode ). searchResults = findTargetElement( XMLSource. TargetNode = "child3" XMLSource = XMLFile print( "The target element we are looking for is: " + TargetNode ). printSiblingResults( TargetNode. findAttribute. printFindResults( TargetNode. TargetNode ). siblingResults = findNextSibling( XMLSource. * Run functions findTargetElement. printFindResults( TargetNode. TargetNode = "child1" XMLSource = XMLString print( "The target element we are looking for is: " + TargetNode ).30) .Programming Guide Chapter 6: JavaScript and Service Manager reference else { return null } } /* Create a function to print the first attribute of the target element */ function printSiblingResults( target..getNodeName(). siblingResults = findNextSibling( XMLSource. siblingResults ).. findAttribute.. TargetNode ).. * Run functions findTargetElement. /* Set variables to search the XMLString for the TargetNode. searchResult ) { if ( searchResult != null ) { var childName = searchResult. print( "The next sibling element of " + target + " is: " + childName ). and * printAttributeResults on the XMLFile and TargetNode */ print( "Processing XML from XMLFile. function walkXML( elem ) { print( "Element " + elem.setContent( sourceXMLString ). XMLString = XMLString.getNodeValue().getNextAttribute().setContent( "C:\\test.getNodeName() This method returns a string representing the name of the current element or attribute. var node = elem. Syntax XML.Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript method: XML. * The script sets the content of XMLString to sourceXMLString. var attrValue = node. if ( typeof nodeValue == "string" && nodeValue. * The script assigns values to the empty variables later on */ var XMLFile = new XML(). true ). The method returns a string representing the name of the current element or attribute or returns null if the current node has no name. "<document><parent1><child1>0123</child1></parent1></document>"") l /* Create variables to store XML objects and strings. This example requires the following sample data: l A local XML file (for example.length > 0 ) Page 322 of 396 HP Service Manager (9. a file called "C:\test. var sourceXMLString = "<document><parent1><child1>0123</child1></parent1></document>". var XMLSource. * Use sourceXMLString to store a valid XML string.getFirstAttribute(). var XMLString = new XML(). print( "Attribute " + attrName + " = " + attrValue ). XMLFile = XMLFile. You must use the other XML get methods to navigate through an XML document. } var nodeValue = elem. while( node != null ) { var attrName = node.getNodeName().getNodeName() ). * Use XMLObject to store a valid XML object such as an XML file.30) . node = elem.getNodeValue(). Example This example displays the names of the elements and attributes in an XML document.xml" containing "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2><child3 /><child4 /></parent2></document>") A valid XML string (for example.xml". Return values A string or null.getNodeName(). Arguments There are no arguments for this method. walkXML( child ). The method returns an integer representing the XML DOM type of the current element or attribute or returns null if the method cannot determine the XML DOM type. This limits this method to elements and attributes since the Service Manager XML object cannot represent element values as an XML object. while( child != null ) { var nodeName = child. } } print( "Now printing the structure of an XML file.getNodeType().getFirstChildElement().getNodeType() This method evaluates an XML object and returns an integer representing the XML DOM type of the current element or attribute. You must use the other XML get methods to navigate through an XML document.xml" containing "<document><parent1>value1<child1 attribute1="a" /><child2 Page 323 of 396 HP Service Manager (9. Example This example displays the XML DOM types of the elements and attributes in an XML document. Arguments There are no arguments for this method.getNodeName().30) . XMLSource = XMLString walkXML( XMLSource ).getNodeValue().org/)..\n" ). XMLSource = XMLFile walkXML( XMLSource ).getNodeName() + " is: " + nodeValue ). } var child = elem. This example requires the following sample data: l A local XML file (for example.. JavaScript method: XML. child = child..w3. Syntax XML. See the W3C Web site for a complete listing of XML DOM node types by integer (www.. a file called "C:\test. print( "Now printing the structure of an XML string.\n" ). var nodeValue = child. It returns a TypeError if applied to anything other than an XML object.Programming Guide Chapter 6: JavaScript and Service Manager reference { print( "Element value of " + elem. Return values A string or null.getNextSiblingElement(). true ).getNextSiblingElement().getNextAttribute().getFirstAttribute(). } } var xmlObj = new XML().getNodeName().getQualifiedName() + " is of type " + elem. node = elem. Arguments There are no arguments for this method.getNodeValue(). JavaScript method: XML. child = child.getNodeValue(). visitElement( xmlObj.getNodeType() ).Programming Guide Chapter 6: JavaScript and Service Manager reference /></parent1><parent2><child3 /><child4 /></parent2></document>") function visitElement( elem ) { print( "Element " + elem.setContent( "c:\\test. Return values A string or null.getNodeValue() This method returns a string representing the value of the current element.xml". /* Print attributes for this element */ var node = elem. It requires you use the other XML get methods to navigate through an XML document. if ( typeof nodeValue == "string" && nodeValue. } /* Print possible element value */ var nodeValue = elem.getDocumentElement() ). var attrValue = node. xmlObj.getNodeType() ). print( "Attribute " + attrName + "=" + attrValue + " and is of type " + node. while( child != null ) { var nodeName = child. visitElement( child ).getNodeValue().30) .getNodeValue(). while( node != null ) { var attrName = node. Syntax XML.getFirstChildElement(). Page 324 of 396 HP Service Manager (9.getQualifiedName(). } /* Now print child elements */ var child = elem. var nodeValue = child.length > 0 ) { print( "Element value is " + nodeValue + " and is of type " + elem.getNodeType() ). a file called "C:\test02.30) . * Use sourceXMLString to store a valid XML string.getFirstChildElement().getNodeName().getNodeName() ) { return null. XMLFile = XMLFile. if ( node == null || topNodeName == node. Example This example displays the value of the elements in an XML document. Page 325 of 396 HP Service Manager (9. while (node != null && node.Programming Guide Chapter 6: JavaScript and Service Manager reference The method returns a string representing the value of the current XML element or returns null if the current node has no value. * This function assumes that there is only one instance of the target * element in the source data.getNextSiblingElement(). This example requires the following sample data: l A local XML file (for example. */ function findTargetElement( node.xml" containing "<document><parent1>value1</parent1><parent2></parent2></document>") /* Create variables to store XML objects and strings. /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element.setContent( "C:\\test02. while (childNode == null) { node = node. * The script assigns values to the empty variables later on */ var XMLFile = new XML().getNodeName() != targetElem ) { var childNode = node. If it finds more than one element in the * data it only returns the first instance of the element. } else { node = childNode. if (childNode == null) { childNode = node.xml". var TargetNode. true ).getNextSiblingElement().getParentNode(). } node = childNode. targetElem ) { var topNodeName = node. } childNode = node. * Use XMLObject to store a valid XML object such as an XML file. * The script sets the content of XMLString to sourceXMLString. var XMLSource. getNodeName(). printFindResults( searchResults. return valueFound } else { print( "There is no value for " + targetNode ). if ( searchResult != null ) { var elementName = searchResult.30) . targetNode ) { var valueFound = sourceObject. Page 326 of 396 HP Service Manager (9.Programming Guide Chapter 6: JavaScript and Service Manager reference } } return node. valueFound = null return valueFound } } /* Set variable values for XMLFile and TargetNode. } /* Create a function to print the target element and search results */ function printFindResults( searchResult. TargetNode ).getNodeValue().length >= 1 ) { print( "The value of " + targetNode + " is: " + valueFound ). findValue( searchResult. Run functions. print( "Found element " + elementName + " in: \n" + searchResult + "\n" ). \n" ). TargetNode = "parent1" XMLSource = XMLFile searchResults = findTargetElement( XMLSource. TargetNode ). if ( valueFound. return null } } /* Create a function to find the parent node element of the target element */ function findValue( sourceObject... targetNode ) { print( "The target element we are looking for is: " + targetNode ). targetNode ). */ print( "Processing XML from XMLFile. return searchResult } else { print( "Cannot find " + target ). Syntax XML.. var sourceXMLString = "<document><parent1><child1 /><child2 Page 327 of 396 HP Service Manager (9. This example requires the following sample data: l A local XML file (for example. * The script sets the content of XMLString to sourceXMLString. a file called "C:\test. TargetNode = "parent2" XMLSource = XMLFile searchResults = findTargetElement( XMLSource.getParentNode() This method returns an XML object representing the parent node of the current node. * Use XMLObject to store a valid XML object such as an XML file.. * The script assigns values to the empty variables later on */ var XMLFile = new XML(). Return values An XML object or null. XMLFile = XMLFile. printFindResults( searchResults. getParentNode(Element) Arguments The following arguments are valid for this method: Data Argument type Node Description String This argument contains the name of the element you want the method to use as the starting position when searching for the parent node element.setContent( "C:\\test. true ).xml". TargetNode ). \n" ). "<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1><parent2 /></document>") l /* Create variables to store XML objects and strings.xml" containing "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2><child3 /><child4 /></parent2></document>") A valid XML string (for example. TargetNode ). The example allows you to select an element from two different input sources. * Use sourceXMLString to store a valid XML string. Run functions. The method returns an object representing the parent node of the current node or returns null if the XML object has no parent node.30) .Programming Guide Chapter 6: JavaScript and Service Manager reference /* Set variable values for XMLFile and TargetNode. */ print( "Processing XML from XMLFile. JavaScript method: XML.getParentNode(). Example This example displays the parent node element of any element you select. getParentNode(). } node = childNode. * This function assumes that there is only one instance of the target * element in the source data. XMLString = XMLString.getNextSiblingElement(). if ( node == null || topNodeName == node. /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element. var searchResults. var parentResults.getNextSiblingElement().getNodeName().setContent( sourceXMLString ). var TargetNode. if (childNode == null) { childNode = node. } } return node.Programming Guide Chapter 6: JavaScript and Service Manager reference attribute2=\"b\" /></parent1><parent2 /></document>". while (node != null && node. } /* Create a function to print the target element and search results */ function printFindResults( target.getNodeName() != targetElem ) { var childNode = node. If it finds more than one element in the * data it only returns the first instance of the element.30) . searchResult ) { if ( searchResult != null ) Page 328 of 396 HP Service Manager (9. } childNode = node. var XMLSource.getFirstChildElement(). while (childNode == null) { node = node. var XMLString = new XML(). */ function findTargetElement( node. } else { node = childNode.getNodeName() ) { return null. targetElem ) { var topNodeName = node. and * printAttributeResults on the XMLFile and TargetNode */ print( "Processing XML from XMLFile. targetNode ) var parentNode = startingNode. Page 329 of 396 HP Service Manager (9. print( "Found element " + elementName + " in: \n" + searchResult + "\n" ).Programming Guide Chapter 6: JavaScript and Service Manager reference { var elementName = searchResult.30) .getNodeName()... findAttribute. searchResult { if ( searchResult != null ) { var parentName = searchResult. return null } } /* Create a function to find the parent node of the target element */ function findParent( sourceObject. * Run functions findTargetElement. /* Set variables to search the XMLFile for the TargetNode. if ( parentNode != null ) { return parentNode } else { return null } } /* Create a function to print the first attribute element */ function printParentResults( target. targetNode ) { var startingNode = findTargetElement( sourceObject.getNodeName(). printFindResults. \n" ). return searchResult } else { print( "Cannot find " + target ).getParentNode(). print( "The parent node element of " + target + parentName ). } else { print( "There is no parent node elements of " + } } of the target ) " is: " + target ). printFindResults( TargetNode. The method returns a string representing the namespace value for the current node (element or attribute) or returns null if the current node has no namespace value. printParentResults( TargetNode. /* Set variables to search the XMLString for the TargetNode.hp. searchResults = findTargetElement( XMLSource. searchResults = findTargetElement( XMLSource. printFindResults( TargetNode. findAttribute. Arguments There are no arguments for this method.getPrefix(). TargetNode ). * Run functions findTargetElement. * Use XMLObject to store a valid XML object such as an XML file. This example requires the following sample data: l A local XML file (for example.0" encoding="UTF-8" standalone="yes" ?><document xmlns:http="http://schemas.getPrefix() This method returns a string representing the namespace value of the current element or attribute. searchResults ).. TargetNode ).Programming Guide Chapter 6: JavaScript and Service Manager reference TargetNode = "child3" XMLSource = XMLFile print( "The target element we are looking for is: " + TargetNode ). Example This example displays the namespace value of the elements and attributes in an XML document. printParentResults( TargetNode. a file called "C:\namespace. printFindResults. parentResults ). \n" ). parentResults = findParent( XMLSource.xml" containing <?xml version="1. Return values A string or null. TargetNode ). parentResults ).org/wsdl/http/" xmlns:ns="http://servicemanager.com/PWS"><http:element1 /><ns:element2 /></document> /* Create variables to store XML objects and strings. It requires you use the other XML get methods to navigate through an XML document. TargetNode = "child1" XMLSource = XMLString print( "The target element we are looking for is: " + TargetNode ). Syntax XML. parentResults = findParent( XMLSource. * Use sourceXMLString to store a valid XML string. JavaScript method: XML. searchResults ).xmlsoap. TargetNode ).. and * printAttributeResults on the XMLString and TargetNode */ print( "Processing XML from XMLString. Page 330 of 396 HP Service Manager (9.30) . * The script assigns values to the empty variables later on */ var XMLFile = new XML(). var prefixResults. var attributeResults.getNextSiblingElement(). /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element.30) . var searchResults. while (childNode == null) { node = node.getNextSiblingElement().setContent( "C:\\namespace. */ function findTargetElement( node.Programming Guide Chapter 6: JavaScript and Service Manager reference * The script sets the content of XMLString to sourceXMLString.getNodeName() != targetElem ) { var childNode = node. } /* Create a function to print the target element and search results */ Page 331 of 396 HP Service Manager (9. while (node != null && node. } else { node = childNode. if (childNode == null) { childNode = node. XMLFile = XMLFile.getNodeName().xml". targetElem ) { var topNodeName = node.getParentNode(). if ( node == null || topNodeName == node.getNodeName() ) { return null. } } return node. * This function assumes that there is only one instance of the target * element in the source data.getFirstChildElement(). var XMLSource. } node = childNode. var firstAttribute. } childNode = node. If it finds more than one element in the * data it only returns the first instance of the element. true ). var TargetNode. targetNode ) { var startingNode = findTargetElement( sourceObject. if ( firstAttribute != null ) { var attributeName = firstAttribute. targetNode ) { var prefixFound = sourceObject. targetNode ).getFirstAttribute().30) .getPrefix(). return prefixFound } else { print( "There is no namespace prefix of " + targetNode ).getNodeName(). print( "The first attribute of " + targetNode + " is: " + attributeName ). print( "Found element " + elementName + " in: \n" + searchResult + "\n" ). findPrefix( firstAttribute. return null } } /* Create a function to find the parent node element of the target element */ function findPrefix( sourceObject.Programming Guide Chapter 6: JavaScript and Service Manager reference function printFindResults( searchResult. targetNode ). return searchResult } else { print( "Cannot find " + target ). return firstAttribute Page 332 of 396 HP Service Manager (9. findPrefix( searchResult. targetNode ) { print( "The target element we are looking for is: " + targetNode ). targetNode ) var firstAttribute = startingNode. prefixFound = null return prefixFound } } /* Create a function to find the first attribute of the target element */ function findFirstAttribute( sourceObject.length >= 1 ) { print( "The namespace prefix of " + targetNode + " is: " + prefixFound ). if ( searchResult != null ) { var elementName = searchResult. if ( prefixFound.getNodeName(). /* Set variable values for XMLFile and TargetNode. nextAttribute = nextAttribute.getNodeName().. TargetNode ).30) . TargetNode = "document" XMLSource = XMLFile searchResults = findTargetElement( XMLSource. return targetNode } else { return null } } /* Set variable values for XMLFile and TargetNode. Page 333 of 396 HP Service Manager (9. printFindResults( searchResults. \n" ).. if ( firstAttribute != null ) { var nextAttribute = startingNode.. findFirstAttribute( XMLSource. return null } } /* Create a function to find the next attribute of the target element */ function findNextAttribute( sourceObject. printFindResults( searchResults. while ( nextAttribute != null ) { var attributeName = nextAttribute.getNextAttribute(). targetNode ). Run functions. */ print( "Processing XML from XMLFile. TargetNode ). print( "The next attribute of " + targetNode + " is: " + attributeName ). TargetNode ). TargetNode ). TargetNode = "element1" XMLSource = XMLFile searchResults = findTargetElement( XMLSource.getNextAttribute(). findPrefix( nextAttribute.Programming Guide Chapter 6: JavaScript and Service Manager reference } else { print( "There are no attributes of " + targetNode ). \n" ). */ print( "Processing XML from XMLFile. targetNode ) { var startingNode = findTargetElement( sourceObject. Run functions.getFirstAttribute(). targetNode ) var firstAttribute = startingNode.. } print( "There are no more attributes of " + targetNode ). TargetNode ). 30) . if ( typeof nodeValue == "string" && nodeValue.getQualifiedName() ).hp. a file called "C:\namespace.getNodeValue(). XMLFile = XMLFile.getQualifiedName(). including any namespace value.Programming Guide Chapter 6: JavaScript and Service Manager reference findNextAttribute( XMLSource.getQualifiedName() + " is: " + Page 334 of 396 HP Service Manager (9. print( "Attribute " + attrName + " = " + attrValue ). var attrValue = node. This example requires the following sample data: l A local XML file (for example.org/wsdl/http/" xmlns:ns="http://servicemanager. while( node != null ) { var attrName = node.com/PWS"><http:element1 /><ns:element2 /></document>") /* Create variables to store XML objects and strings.getNextAttribute(). The method returns a string representing the name of the current element or attribute. Syntax XML. node = elem. Arguments There are no arguments for this method. TargetNode ). You must use the other XML get methods to navigate through an XML document.getQualifiedName() This method returns a string representing the name of the current element or attribute. Example This example displays the qualified names of the elements and attributes in an XML document. var node = elem. * The script assigns values to the empty variables later on */ var XMLFile = new XML().setContent( "C:\\namespace. * Use XMLObject to store a valid XML object such as an XML file. Return values A string or null. } var nodeValue = elem.getQualifiedName(). var XMLSource. It returns null if the current node has no name.xmlsoap. JavaScript method: XML.getFirstAttribute().xml" containing "<?xml version="1.0" encoding="UTF-8" standalone="yes" ?><document xmlns:http="http://schemas.xml".getNodeValue(). true ). function nsXMLWalk( elem ) { print( "Element " + elem.length > 0 ) { print( "Element value of " + elem. .getNodeValue(). walkXML( child ).\n" ).getFirstAttribute(). } } print( "Now printing the structure of an XML file with qualified names. var attrValue = node. while( child != null ) { var nodeName = child.getQualifiedName(). } var child = elem. } var nodeValue = elem. var node = elem. child = child.getNextAttribute().getFirstChildElement().length > 0 ) { print( "Element value of " + elem.. print( "Now printing the structure of an XML file without qualified names. XMLSource = XMLFile nsXMLWalk( XMLSource ).getName() ). var nodeValue = child.getNodeValue().getNextSiblingElement().. print( "Attribute " + attrName + " = " + attrValue ).getNodeValue().30) . while( child != null ) { var nodeName = child.getName().getNextSiblingElement().Programming Guide Chapter 6: JavaScript and Service Manager reference nodeValue ). } } function walkXML( elem ) { print( "Element " + elem. while( node != null ) { var attrName = node. nsXMLWalk( child ).\n" ).. var nodeValue = child. XMLSource = XMLFile walkXML( XMLSource ).getName() + " is: " + nodeValue ).getName(). Page 335 of 396 HP Service Manager (9.getNodeValue(). if ( typeof nodeValue == "string" && nodeValue. child = child. } var child = elem.getFirstChildElement(). node = elem. a file called "C:\test02.xml" containing "<document><parent1>value1</parent1><parent2></parent2></document>") /* Create variables to store XML objects and strings.. * Use sourceXMLString to store a valid XML string. /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element.30) . var TargetNode. Arguments There are no arguments for this method.getFirstChildElement(). If it finds more than one element in the * data it only returns the first instance of the element.Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript method: XML. * The script sets the content of XMLString to sourceXMLString. */ function findTargetElement( node. Example This example displays the value of the elements in an XML document. targetElem ) { var topNodeName = node. while (node != null && node. var XMLSource. XMLFile = XMLFile. You must use the other XML get methods to navigate through an XML document.getText() This method returns a string representing the value of the current element. This example requires the following sample data: l A local XML file (for example.xml".getNodeName(). * Use XMLObject to store a valid XML object such as an XML file.getText(). true ). This method is a synonym for getNodeValue(). Return values A string or null. * The script assigns values to the empty variables later on */ var XMLFile = new XML(). * This function assumes that there is only one instance of the target * element in the source data.setContent( "C:\\test02. Syntax XML. The method returns a string representing the value of the current XML element or returns null if the current node has no value. if (childNode == null) { Page 336 of 396 HP Service Manager (9.getNodeName() != targetElem ) { var childNode = node. Programming Guide Chapter 6: JavaScript and Service Manager reference childNode = node.getParentNode().30) .getNextSiblingElement().getNextSiblingElement(). targetNode ). print( "Found element " + elementName + " in: \n" + searchResult + "\n" ). targetNode ) { print( "The target element we are looking for is: " + targetNode ). } node = childNode. findValue( searchResult. return searchResult } else { print( "Cannot find " + target ).length >= 1 ) { print( "The value of " + targetNode + " is: " + valueFound ). if ( valueFound. if ( node == null || topNodeName == node.getText().getNodeName(). } else { node = childNode. return valueFound } Page 337 of 396 HP Service Manager (9. } } return node. if ( searchResult != null ) { var elementName = searchResult. } childNode = node. return null } } /* Create a function to find the parent node element of the target element */ function findValue( sourceObject. while (childNode == null) { node = node.getNodeName() ) { return null. } /* Create a function to print the target element and search results */ function printFindResults( searchResult. targetNode ) { var valueFound = sourceObject. . Example This example displays the value of the elements in an XML document. TargetNode = "parent1" XMLSource = XMLFile searchResults = findTargetElement( XMLSource.Programming Guide Chapter 6: JavaScript and Service Manager reference else { print( "There is no value for " + targetNode ). /* Set variable values for XMLFile and TargetNode.xml" containing "<document><parent1>value1</parent1><parent2></parent2></document>") /* Create variables to store XML objects and strings. \n" ). printFindResults( searchResults. valueFound = null return valueFound } } /* Set variable values for XMLFile and TargetNode. * Use XMLObject to store a valid XML object such as an XML file... */ print( "Processing XML from XMLFile. This method is a synonym for getNodeValue().getValue() This method returns a string representing the value of the current element. Run functions. You must use the other XML get methods to navigate through an XML document.30) .getValue(). TargetNode ). */ print( "Processing XML from XMLFile. Run functions.. TargetNode ). TargetNode ). Return values A string or null. Syntax XML. printFindResults( searchResults. Page 338 of 396 HP Service Manager (9. \n" ). * Use sourceXMLString to store a valid XML string. a file called "C:\test02. JavaScript method: XML. TargetNode ).. TargetNode = "parent2" XMLSource = XMLFile searchResults = findTargetElement( XMLSource. Arguments There are no arguments for this method. The method returns a string representing the value of the current XML element or returns null if the current node has no value. This example requires the following sample data: l A local XML file (for example. if ( searchResult != null ) Page 339 of 396 HP Service Manager (9. while (childNode == null) { node = node.30) . } /* Create a function to print the target element and search results */ function printFindResults( searchResult. var TargetNode. targetElem ) { var topNodeName = node.getParentNode().getNodeName() != targetElem ) { var childNode = node.Programming Guide Chapter 6: JavaScript and Service Manager reference * The script sets the content of XMLString to sourceXMLString. } childNode = node. var XMLSource.getFirstChildElement(). if ( node == null || topNodeName == node. * This function assumes that there is only one instance of the target * element in the source data.getNextSiblingElement(). } node = childNode.setContent( "C:\\test02. } } return node. /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element.getNextSiblingElement(). * The script assigns values to the empty variables later on */ var XMLFile = new XML().getNodeName() ) { return null. while (node != null && node. */ function findTargetElement( node.getNodeName(). XMLFile = XMLFile. targetNode ) { print( "The target element we are looking for is: " + targetNode ). if (childNode == null) { childNode = node. If it finds more than one element in the * data it only returns the first instance of the element. } else { node = childNode. true ).xml". */ print( "Processing XML from XMLFile.. valueFound = null return valueFound } } /* Set variable values for XMLFile and TargetNode. Run functions. targetNode ) { var valueFound = sourceObject. if ( valueFound. TargetNode ).30) . /* Set variable values for XMLFile and TargetNode. TargetNode ).. return null } } /* Create a function to find the parent node element of the target element */ function findValue( sourceObject.getValue(). print( "Found element " + elementName + " in: \n" + searchResult + "\n" ).getNodeName(). findValue( searchResult.. return searchResult } else { print( "Cannot find " + target ). Run functions.length >= 1 ) { print( "The value of " + targetNode + " is: " + valueFound ). Page 340 of 396 HP Service Manager (9. TargetNode = "parent1" XMLSource = XMLFile searchResults = findTargetElement( XMLSource.. TargetNode = "parent2" XMLSource = XMLFile searchResults = findTargetElement( XMLSource. */ print( "Processing XML from XMLFile. return valueFound } else { print( "There is no value for " + targetNode ). printFindResults( searchResults. TargetNode ). \n" ).Programming Guide Chapter 6: JavaScript and Service Manager reference { var elementName = searchResult. \n" ). TargetNode ). printFindResults( searchResults. targetNode ). getNodeName() != targetElem ) { var childNode = node.getNextSiblingElement(). Instead. and >. It requires two existing XML objects with document elements: one is the source XML object and the other is the target XML document. Arguments The following arguments are valid for this method: Data Argument type name Description String This argument specifies the XML node name you want to copy from the source XML object. Return values An XML object or null.getFirstChildElement(). a file called "C:\test. var XMLObject = new XML().xml" containing "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2><child3 /><child4 /></parent2></document>") An XML object (for example. var TargetNode.Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript method: XML.30) . function findTargetElement( node. The method returns an XML object containing the copied node or returns null if the method cannot import a copy of the node. Syntax XML. Page 341 of 396 HP Service Manager (9. an object containing "<document> </document>") l var XMLFile = new XML(). The string argument must contain characters valid for XML (for example. This method does not update either the source or the target XML object. Example This example imports an XML node from one XML object to another. you must use the appendNode method to add the imported node into the target XML document.importNode() This method copies an XML node from one XML document to another.getParentNode().). while (node != null && node.importNode( name ). This example requires the following sample data: l A local XML file (for example. the string cannot include the characters < or > except as XML entities such as <. targetElem ) { var topNodeName = node. while (childNode == null) { node = node.getNodeName(). if (childNode == null) { childNode = node. setContent( "C:\\test.importNode( FoundNode ). } childNode = node. print( "Importing " + FoundNode + " into XML target object. } /* Create a function to print the target element and search results */ function printFindResults( target.getNodeName() ) { return null.getNextSiblingElement(). true ).getNodeName().. var NewNode = xmlTarget."). searchResult ) { if ( searchResult != null ) { var elementName = searchResult. node ) { print( "The XML source object is:\n" + xmlSource ). print( "Found element " + elementName + " in: \n" + searchResult + "\n" ). printFindResults( node. } XMLFile = XMLFile. } else { node = childNode.30) . print( "The target element we are looking for is: " + node ). } } return node. print( "The XML target object remains unchanged: " + xmlTarget ). FoundNode ).. Page 342 of 396 HP Service Manager (9. var FoundNode = findTargetElement( xmlSource.xml". node ). print( "The XML target object is:\n" + xmlTarget )." ).. return null } } function importNewNode( xmlSource. print( "Appending " + FoundNode + " into XML target object.Programming Guide Chapter 6: JavaScript and Service Manager reference if ( node == null || topNodeName == node. xmlTarget.appendNode( NewNode ).. return searchResult } else { print( "Cannot find " + target ). var appendedNode = xmlTarget. print( "The new XML target object is: " + xmlTarget ). } node = childNode. getNodeName() != targetElem ) Page 343 of 396 HP Service Manager (9.isDocumentElement() This method returns true if the current element is the Document Object Model (DOM) document element (the "root" node of the XML document). You must use the other XML get methods to navigate through an XML document. true ). * The script assigns values to the empty variables later on */ var XMLFile = new XML(). targetElem ) { var topNodeName = node. TargetNode ). The method returns true if the current XML element is the DOM document element or false if the current XML element is not the DOM document . This example requires the following sample data: l A local XML file (for example.getNodeName().setContent( "<document> </document>" ).30) . * Use XMLObject to store a valid XML object such as an XML file. */ function findTargetElement( node.isDocumentElement().setContent( "C:\\test02. XMLFile = XMLFile. a file called "C:\test02. If it finds more than one element in the * data it only returns the first instance of the element. importNewNode( XMLFile. Return values A Boolean value: true or false. * Use sourceXMLString to store a valid XML string.xml" containing "<document><parent1>value1</parent1><parent2></parent2></document>") /* Create variables to store XML objects and strings. Syntax XML. Example This example checks to see if the selected element is the DOM document element. TargetNode = "parent1". JavaScript method: XML. * The script sets the content of XMLString to sourceXMLString. var TargetNode. /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element. while (node != null && node.xml". XMLObject. Arguments There are no arguments for this method. var XMLSource.Programming Guide Chapter 6: JavaScript and Service Manager reference XMLObject = XMLObject. * This function assumes that there is only one instance of the target * element in the source data. while (childNode == null) { node = node.getFirstChildElement().getNodeName(). } } return node.Programming Guide Chapter 6: JavaScript and Service Manager reference { var childNode = node. if ( searchResult != null ) { var elementName = searchResult. } else { node = childNode. } /* Create a function to print the target element and search results */ function printFindResults( searchResult. targetNode ) { print( "The target element we are looking for is: " + targetNode ). return null } } /* Create a function to find the parent node element of the target element */ function testDocElem( sourceObject ) { var docElement = sourceObject. return searchResult } else { print( "Cannot find " + target ). if ( docElement == true ) Page 344 of 396 HP Service Manager (9. print( "Found element " + elementName + " in: \n" + searchResult + "\n" ).30) . if ( node == null || topNodeName == node.getNodeName() ) { return null. if (childNode == null) { childNode = node.getNextSiblingElement(). } node = childNode.getParentNode(). testDocElem( searchResult).getNextSiblingElement().isDocumentElement(). } childNode = node. . print( "Fail. Syntax XML. TargetNode ). printFindResults( searchResults. printFindResults( searchResults.. The element " + nodeName + " is not the DOM document element. TargetNode ). return valueFound } else { var nodeName = sourceObject.setAttributeValue( AttributeName. \n" ). TargetNode ). */ print( "Processing XML from XMLFile. */ print( "Processing XML from XMLFile.. You must use the other XML get methods to navigate through an XML document. TargetNode = "document" XMLSource = XMLFile searchResults = findTargetElement( XMLSource.30) ." ). TargetNode = "parent1" XMLSource = XMLFile searchResults = findTargetElement( XMLSource. Run functions. valueFound = null return valueFound } } /* Set variable values for XMLFile and TargetNode.getName().. Page 345 of 396 HP Service Manager (9.getName(). Arguments The following arguments are valid for this method: Argument Data type Description AttributeName String This argument specifies the XML attribute whose value you want the script to add or update.setAttributeValue() This method adds or updates the attribute value of the target attribute. AttributeValue ). Run functions. TargetNode ). /* Set variable values for XMLFile and TargetNode. The element " + nodeName + " is the DOM document element. JavaScript method: XML. print( "Success. \n" )." ).Programming Guide Chapter 6: JavaScript and Service Manager reference { var nodeName = sourceObject. while (node != null && node. if (childNode == null) { childNode = node. Example This example adds or updates the attribute value of any given element in an XML document. true ). * The script assigns values to the empty variables later on */ var XMLFile = new XML(). the string cannot include the characters < or >).getNodeName() ) { return null.Programming Guide Chapter 6: JavaScript and Service Manager reference AttributeValue String This argument specifies the text string you want the script to use as the XML attribute value. a file called "C:\test. while (childNode == null) { node = node. var TargetNode. if ( node == null || topNodeName == node. var TargetValue. This argument must contain characters valid for an XML element (for example. Page 346 of 396 HP Service Manager (9. Return values This method does not return any values. This example requires the following sample data: l A local XML file (for example. /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element. * This function assumes that there is only one instance of the target * element in the source data.30) . var XMLSource.getNodeName() != targetElem ) { var childNode = node. var searchResults.getFirstChildElement(). var TargetAttribute. targetElem ) { var topNodeName = node. If it finds more than one element in the * data it only returns the first instance of the element.getNextSiblingElement(). XMLFile = XMLFile.xml" containing "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2><child3 /><child4 /></parent2></document>") /* Create variables to store XML objects and strings.getParentNode().setContent( "C:\\test.xml". */ function findTargetElement( node. * Use XMLFile to store a valid XML file.getNodeName(). var setAttributeValue = sourceObject.getNodeName(). return null } } /* Create a function to set the attribute value of the target attribute */ function setAttributeValue( sourceObject. print( "The XML object is " + searchResult ). return newAttributeValue } Page 347 of 396 HP Service Manager (9.getNextSiblingElement(). attributeValue ) { print( "Setting attribute value of " + attributeName ). } } return node. attributeValue ). attributeName. attributeValue ) { print( "The target element we are looking for is: " + target ). attributeName. if ( searchResult != null ) { var elementName = searchResult. attributeValue ). var newAttributeValue = sourceObject. searchResult.Programming Guide Chapter 6: JavaScript and Service Manager reference } childNode = node. var attributeSet = setAttributeValue( searchResult. } else { node = childNode. } /* Create a function to print the target element and search results */ function printFindResults( target.30) . print( "The value of " + attributeName + " is now " + newAttributeValue ). attributeName. print( "Found element " + elementName + " in: \n" + searchResult + "\n" ).setAttributeValue( attributeName. return attributeSet } else { print( "Cannot find " + target ). } node = childNode.getAttributeValue( attributeName ). Run functions print( "Processing XML from XMLFile. TargetAttribute.setContent( String ). FilePath String IsFile Boolean This argument specifies whether the first argument is a string or a file path. TargetNode ). XMLSource = XMLFile.. TargetNode = "child1". TargetValue ).. TargetAttribute = "attribute1". setContent( "FilePath".. Syntax XML. TargetValue ). TargetValue = "z". It always creates a valid XML document with a document element. searchResults. searchResults = findTargetElement( XMLSource.. \n" ). The method removes any values outside the document element. searchResults.30) . Note: This method returns null if applied to an existing XML object because the header information ([C++ object XML] @nnnnnnnnnn . TargetValue = "z". TargetNode ). indicates that the first argument is a string.setContent() This method creates an XML object from a string or the contents of an external file. A true value indicates the first argument is a file path. IsFile ). including omitting the second argument. */ JavaScript method: XML.Programming Guide Chapter 6: JavaScript and Service Manager reference /* Set variable values for XMLFile and TargetNode. Page 348 of 396 HP Service Manager (9.) is not valid. XMLSource = XMLFile. printFindResults( TargetNode. searchResults = findTargetElement( XMLSource. You must enclose the FilePath argument in quotation marks and use the true argument to indicate that the first argument is a file path and not a string value. Any other value. \n" ). print( "Processing XML from XMLFile. printFindResults( TargetNode. TargetAttribute. TargetAttribute = "attribute1". This argument specifies the path to the XML document you want the script to parse an XML object. Arguments The following arguments are valid for this method: Data Argument type String String Description This argument specifies the text string you want the script to parse as on XML object. TargetNode = "child2". The string argument must contain a valid XML document with a document element. 30) . * The function creates a new XML object xmlObj.Programming Guide Chapter 6: JavaScript and Service Manager reference Return values An XML object or null. return null } Page 349 of 396 HP Service Manager (9. "<document><parent1><child1 attribute1=\"1\" /></parent1><parent2 /></document>") An XML string with more than one document element (for example. The method returns an XML object if it parses the XML input and returns null if it cannot parse the input.users) An XML object converted to a string (for example. the list of currently logged on users stored in system. "<document1><parent1 /></document1><document2><parent2 /></document2>") A local XML file (for example. * The isFile argument determines if the source is an XML string or file path.setContent( source. Arguments Use the toXMLString method to convert an XML object to an XML string. isFile ) { var xmlObj = new XML(). Example This example attempts to create an XML object from five different sources.xml" containing "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2><child3 /><child4 /></parent2></document>") An existing XML object (for example. This example requires the following sample data: l A valid XML string (for example. a file called "C:\test. it prints an XML string and returns the XML object. \n Could not parse the following input as XML: \n" + source ). the list of currently logged on users stored in system. * If setContent returns true. * If setContent returns false. it prints the source and returns null. * It sets the content of the XML object to the source argument. if ( xmlObj. print( "setContent succeeded! \n The XML document is: \n" + xmlDoc ). return xmlObj } else { print( "setContent failed. */ function setXML( source. isFile ) ) { var xmlDoc = xmlObj.users) l l l l /* Create a function to execute the setContent method.toXMLString(). . The string argument must contain characters valid for XML (for example. setXML( xmlObject. * See the xmlString example below. * Note: The toXMLstring method removes the object header information. Arguments The following arguments are valid for this method: String String This argument specifies the text string you want the script to add as the XML element value.Programming Guide Chapter 6: JavaScript and Service Manager reference } /* Create variables to store your XML source objects. Syntax XML. * Use xmlString to test setting content to an XML string. setXML( xmlFile. * Note: You must use the backslash character to escape out quotation marks in your XML string. print( "Testing setting content to an existing XML object..\n" )..\n" ). var xmlBad = "<document1><parent1 /></document1><document2><parent2 /></document2>" var xmlFile = "C:\\test. * xmlObjectConverted converts xmlObject to an XML string. false ). the string cannot include the characters < or > except as XML entities such as <. false ). setXML( xmlObjectConverted. print( "The non-compliant XML string before conversion is: \n" + xmlBad ).30) .\n" ).toXMLString(). print( "Testing setting content to an XML string with more than one document element. setXML( xmlBad ). Page 350 of 396 HP Service Manager (9.. * Use xmlObject to test setting content to an XML object.users var xmlObjectConverted = xmlObject. print( "Testing setting content to an existing XML object converted to an XML string..\n" ). /* Note: You can omit the isFile argument when the content source is an XML string.)..setNodeValue() This method adds or updates the value of the current element. print( "Testing setting content to an XML file.setNodeValue( String ).. * Use xmlFile to test setting content to an XML file. setXML( xmlString ).. true ). */ print( "Testing setting content to a valid XML string.xml".\n" ). var xmlObject = system. JavaScript method: XML. It requires you use the other XML get methods to navigate through an XML document.. and >.. */ var xmlString = "<document><parent1><child1 attribute1=\"1\" /></parent1><parent2 /></document>". getNextSiblingElement().Programming Guide Chapter 6: JavaScript and Service Manager reference String String This argument specifies the text string you want the script to add as the XML element value.). and >.xml". while (childNode == null) { node = node. Return values An XML object or null. a file called "C:\test03. true ). The string argument must contain characters valid for XML (for example.getFirstChildElement(). while (node != null && node. XMLFile = XMLFile. var findElement. The method returns an XML object containing the new value of the current XML element or returns null if the method cannot set a value for the element. Example This example sets the value of the elements in an XML document.setContent( "C:\\test03.getNodeName(). * Use XMLObject to store a valid XML object such as an XML file. the string cannot include the characters < or > except as XML entities such as <.30) . if ( node == null || topNodeName == node.getNodeName() ) Page 351 of 396 HP Service Manager (9. * This function assumes that there is only one instance of the target * element in the source data.getParentNode(). */ function findTargetElement( node.xml" containing "<document><parent1></parent1><parent2></parent2></document>") /* Create variables to store XML objects and strings. targetElem ) { var topNodeName = node. if (childNode == null) { childNode = node. var TargetValue.getNodeName() != targetElem ) { var childNode = node. * Use sourceXMLString to store a valid XML string. var TargetNode. /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element. * The script sets the content of XMLString to sourceXMLString. If it finds more than one element in the * data it only returns the first instance of the element. * The script assigns values to the empty variables later on */ var XMLFile = new XML(). This example requires the following sample data: l A local XML file (for example. TargetValue ). newValue ) { print( "The target element we are looking for is: " + targetNode ).setText() This method adds or updates the value of the current element. targetNode. } else { node = childNode. print( "The new value of " + targetNode + " is: " + searchResult ). Syntax XML. Page 352 of 396 HP Service Manager (9. } /* Create a function to print the target element and search results */ function setElementValue( searchResult. setElementValue( findElement. JavaScript method: XML. TargetValue = "1234". return null } } TargetNode = "parent1". You must use the other XML get methods to navigate through an XML document. if ( searchResult != null ) { var elementName = searchResult.setNodeValue( newValue ).getNodeName(). TargetNode ).Programming Guide Chapter 6: JavaScript and Service Manager reference { return null.setText( String ). } childNode = node.getNextSiblingElement(). return searchResult } else { print( "Cannot find " + targetNode ). } node = childNode. print( "Found element " + elementName + " in: \n" + searchResult + "\n" ). } } return node.. findElement = findTargetElement( XMLFile.30) . This method is a synonym for setNodeValue(). TargetNode. searchResult. var TargetValue. */ function findTargetElement( node. If it finds more than one element in the * data it only returns the first instance of the element. true ). /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element. Return values An XML object or null. * The script sets the content of XMLString to sourceXMLString. if (childNode == null) { Page 353 of 396 HP Service Manager (9. and >.30) .xml".getNodeName().xml" containing "<document><parent1></parent1><parent2></parent2></document>") /* Create variables to store XML objects and strings. This argument must contain characters valid for XML (for example.Programming Guide Chapter 6: JavaScript and Service Manager reference Arguments The following arguments are valid for this method: Data Argument type String Description String This argument specifies the text string you want the script to add as the XML element value. * Use XMLObject to store a valid XML object such as an XML file. The method returns an XML object containing the new value of the current XML element or returns null if the method cannot set a value for the element. * This function assumes that there is only one instance of the target * element in the source data. targetElem ) { var topNodeName = node.). Example This example sets the value of the elements in an XML document. while (node != null && node. var TargetNode.getNodeName() != targetElem ) { var childNode = node. var findElement. a file called "C:\test03. the string cannot include the characters < or > except as XML entities such as <. * The script assigns values to the empty variables later on */ var XMLFile = new XML(). * Use sourceXMLString to store a valid XML string. XMLFile = XMLFile. This example requires the following sample data: l A local XML file (for example.setContent( "C:\\test03.getFirstChildElement(). 30) . if ( node == null || topNodeName == node. } /* Create a function to print the target element and search results */ function setElementValue( searchResult. TargetNode. } childNode = node.setText( newValue ).getNextSiblingElement(). newValue ) { print( "The target element we are looking for is: " + targetNode ). if ( searchResult != null ) { var elementName = searchResult. print( "The new value of " + targetNode + " is: " + searchResult ).getNodeName() ) { return null. TargetNode ). TargetValue ). return searchResult } else { print( "Cannot find " + targetNode ).getParentNode(). Page 354 of 396 HP Service Manager (9. return null } } TargetNode = "parent1". } } return node. } else { node = childNode.getNodeName(). setElementValue( findElement. searchResult. findElement = findTargetElement( XMLFile.Programming Guide Chapter 6: JavaScript and Service Manager reference childNode = node. targetNode.getNextSiblingElement(). TargetValue = "1234". while (childNode == null) { node = node. } node = childNode. print( "Found element " + elementName + " in: \n" + searchResult + "\n" ). If it finds more than one element in the * data it only returns the first instance of the element. * The script assigns values to the empty variables later on */ var XMLFile = new XML(). */ Page 355 of 396 HP Service Manager (9. You must use the other XML get methods to navigate through an XML document. * Use XMLObject to store a valid XML object such as an XML file. This example requires the following sample data: l A local XML file (for example.xml" containing "<document><parent1></parent1><parent2></parent2></document>") /* Create variables to store XML objects and strings. The string argument must contain characters valid for XML (for example. /* Create a function that searches an XML object (node) for a particular * element (targetElem) and returns an XML object containing the element. the string cannot include the characters < or > except as XML entities such as <. var findElement. a file called "C:\test03. true ). The method returns an XML object containing the new value of the current XML element or returns null if the method cannot set a value for the element.30) . This method is a synonym for setNodeValue(). XMLFile = XMLFile.xml". Example This example sets the value of the elements in an XML document.setValue() This method adds or updates the value of the current element. var TargetValue..Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript method: XML. and >. var TargetNode.). Arguments The following arguments are valid for this method: Data Argument type String Description String This argument specifies the text string you want the script to add as the XML element value. * This function assumes that there is only one instance of the target * element in the source data. * The script sets the content of XMLString to sourceXMLString.setValue( String ). Return values An XML object or null.setContent( "C:\\test03. * Use sourceXMLString to store a valid XML string. Syntax XML. searchResult. } childNode = node. targetNode.getNodeName() ) { return null.getNodeName(). if ( searchResult != null ) { var elementName = searchResult.getFirstChildElement().getNodeName() != targetElem ) { var childNode = node. print( "The new value of " + targetNode + " is: " + searchResult ). targetElem ) { var topNodeName = node.30) . while (childNode == null) { node = node. print( "Found element " + elementName + " in: \n" + searchResult + "\n" ). return null } } Page 356 of 396 HP Service Manager (9. if ( node == null || topNodeName == node. } else { node = childNode.setValue( newValue ).getParentNode(). if (childNode == null) { childNode = node. newValue ) { print( "The target element we are looking for is: " + targetNode ).getNodeName(). } } return node. return searchResult } else { print( "Cannot find " + targetNode ). } /* Create a function to print the target element and search results */ function setElementValue( searchResult. while (node != null && node.Programming Guide Chapter 6: JavaScript and Service Manager reference function findTargetElement( node.getNextSiblingElement(). } node = childNode.getNextSiblingElement(). users) system. Syntax XML. xmlObject.insertBefore() Inserts the specified node before a reference element as a child of the current node. Page 357 of 396 HP Service Manager (9. You must use the other XML get methods to navigate through an XML document.Programming Guide Chapter 6: JavaScript and Service Manager reference TargetNode = "parent1". The parent of the newly inserted node.toXMLString() This method converts an XML object into a valid XML string. Return values A string or null. setElementValue( findElement. The method returns a string containing valid XML or returns null if the current node is not an XML object. TargetValue ). that is newElement.30) . referenceElement) Arguments The following arguments are valid for this function: Name insertedElement parentElement newElement Data type Required Description XML XML XML Yes Yes Yes The node being inserted. JavaScript method: XML.users the original XML object:\n" + xmlObject ). Example This example converts an XML object into a valid XML document. Arguments There are no arguments for this method.insertBefore(newElement.toXMLString(). the list of currently logged on users stored in system. findElement = findTargetElement( XMLFile. TargetNode ). JavaScript method: xmlDoc. TargetNode. TargetValue = "1234". This example requires the following sample data: l An existing XML object (for example. the XML object after conversion to a string:\n" + var xmlObject = print( "This is var xmlString = print( "This is xmlString ). The node to insert. Syntax var insertedElement = parentElement.toXMLString(). false ). we must // attach the new node somewhere. We can do that with appendNode or insertBefore // To get the new node in between two sibling nodes (as in this example) // we must use insertBefore. // Now insert a new element <three> in front of <four> // We do this in two steps: // a) create a new element node called <three> // b) insert the new element node before the <four> element // Note: Passing "1" as the first argument to createNode means create an element var nodeThree = xmlDoc. such as a newly created element for which appendNode has not been called. // Just as in the case of a node created with "importNode".30) . 2. // Now add create and add new element <four> in one step. "three" ).Programming Guide Chapter 6: JavaScript and Service Manager reference referenceElement XML Yes The parent of the newly inserted node.e. The result of invoking insertBefore using references to nodes already in the same DOM tree as newElement is undefined. Page 358 of 396 HP Service Manager (9.setContent( someXML. appendChild can only be used on a parent node.addElement( "four" ). Example var xmlDoc = new XML(). newElement the function will fail. i.createNode( 1. // The newly created node has not yet been given a position in the tree. If referenceElement is null. var someXML = "<doc> \ <one/> \ <two/> \ </doc>". Usage Notes 1. // Create an XML document from the literal XML string // we pass "false" as the second argument to setContent() to indicate // that the supplied string does NOT represent a path to an XML file xmlDoc. // It will be added at the end. The referenceElement may NOT be null. The newElement must be a newly created element within the same document (created using importNode or createNode) which has not yet been attached to the tree. after <two> var nodeFour = xmlDoc. the XMLDate() constructor converts an XML schema date object to an XMLDate object. With a DateObject argument. JavaScript object: XMLDate The following JavaScript object is unique to HP Service Manager. the XMLDate() constructor converts a Service Manager date object to an XMLDate object. Properties None Methods The following methods are valid for this object: getDate This method returns a JavaScript date object (same as the JSDate method). Page 359 of 396 HP Service Manager (9. ISO8601DateTimeOrDurationString XML schema Passes an XML schema date. it would end up following <four> xmlDoc. DateTimeDatum Service Manager Datum object Passes a Service Manager datum object formatted as a TIME type to the XMLDate constructor. Constructor new new new new XMLDate(). or duration string to the XMLDate constructor. the XMLDate() constructor converts a JavaScript date object to an XMLDate object. XMLDate( DateTimeDatum ). nodeFour ). the XMLDate() constructor creates an empty XMLDate object. XMLDate( DateObject ). XMLDate( ISO8601DateTimeOrDurationString ).Programming Guide Chapter 6: JavaScript and Service Manager reference // and if we were to append to the parent element <doc>.insertBefore( nodeThree.30) . With a DateTimeDatum argument. time. Arguments The following arguments are valid for this object: Argument DateObject Data type JavaScript date object Description Passes a JavaScript date object to the XMLDate constructor. With an ISO8601DateTimeOrDurationString argument. print( xmlDoc ). This object's methods use the Service Manager-defined global return codes. date datetime. With no arguments. This method adds the indicated duration to the contained value in the XMLDate object. This method returns a JavaScript date object. This method returns the indicated portions of the XMLDate value.Programming Guide Chapter 6: JavaScript and Service Manager reference getISODateTimeString This method passes a JavaScript Date object to the constructor.30) . * The dots in Service Manager field names must be converted to Page 360 of 396 HP Service Manager (9. This method returns the indicated portions of the XMLDate value. This method returns the indicated portions of the XMLDate value. This method returns the indicated portions of the XMLDate value. This method returns a JavaScript date object (same as the JSDate method). toSCDuration This method converts an ISO duration string to a Service Manager duration. This method returns an SCDatum object.start to today's date. /* Set the Service Manager fields date. This method returns a datetime string in Service Manager format. getISODate getISOTime getISOYear getISOMonth getISODay getDatum getSCDateTimeString getGMTSCDateTimeString This method returns the Greenwich Mean Time (GMT) datetime in Service Manager format.entered and planned. This method returns the indicated portions of the XMLDate value. addDuration( iso8601durationstring ) JSDate getDate Example This example does the following: l l l Creates an SCFile object from the cm3r table Creates an XMLDate object Sets the value of two fields to the XMLdate This example requires the following sample data: l A valid duration /* Instantiate a new SCFile object with records of the cm3r table */ var changeRequest = new SCFile("cm3r"). . var nextWeeksDate = theXMLDate.getDatum(). var todaysDate = theXMLDate.header. Arguments The following arguments are valid for this function: Argument Data type duration ISO 8601 duration string Required Description Yes This argument contains the ISO 8601 duration string or variable value you want the script to add to an XMLDate object. 3 days.planned_start = todaysDate." ). and 4 hours to date.planned_end = nextWeeksDate. months. Date() ).addDuration('P7D'). /* Increment the value of the planned.getDatum().date_entered = todaysDate.end field to be a week later. new XMLDate object is: " + dur ).. changeRequest. new XMLDate object is: " + d ).30) .addDuration( print( "The value of the Page 361 of 396 HP Service Manager (9. Example This example does the following: l l Creates a new XMLDate object containing today's date Adds 1 year.header. JavaScript method: XMLDate.header.addDuration( duration ). * P is the addDuration parameter for duration * 7D is the addDuration parameter for 7 days * See the addDuration method for additional information */ theXMLDate...addDuration() This method returns an XMLDate object containing the new date/time after adding the duration from the duration argument. "P1Y2M3DT4H" )." ). 2 months. Return values An XMLDate object or null. print( "Creating XMLDate var d = new XMLDate( new print( "The value of the print( "Adding 1 year. 3 days. The method returns an XMLDate object or null if conversion fails. changeRequest.Programming Guide Chapter 6: JavaScript and Service Manager reference underscores */ var theXMLDate = new XMLDate( new Date() ). 2 var dur = d. changeRequest. and 4 hours to the XMLDate object then displays the result object. Syntax XMLDate. changeRequest.doInsert(). var d = new XMLDate( new Date() ).getDate()." ).Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript method: XMLDate.. Arguments There are no arguments for this method. print( "The JavaScript date/time object is: " + js )...... Arguments There are no arguments for this method.getDate(). print( "Converting the XMLDate to a JavaScript object. print( "The value of the new XMLDate object is: " + d ). Example This example does the following: l l Creates a new XMLDate object containing today's date Converts the XMLDate object to JavaScript date/time object then displays the result print( "Creating XMLDate object.getDate() This method returns a JavaScript date/time object. print( "The value of the new XMLDate object is: " + d ). Page 362 of 396 HP Service Manager (9. The method returns a Service Manager-formatted date/time Datum object or null if the conversion fails. Return values A string or null." ).. Example This example does the following: l l Creates a new XMLDate object containing today's date Converts the XMLDate object to Service Manager-formatted date/time Datum object then displays the result print( "Creating XMLDate object." ).. Syntax XMLDate. Syntax XMLDate. print( "Converting the XMLDate to a Service Manager Datum. JavaScript method: XMLDate.getDatum() This method returns an HP Service Manager-formatted date/time Datum object. var js = d.30) ." ).getDatum(). The method returns a JavaScript date/time object or null if conversion fails. Return values A string or null. var d = new XMLDate( new Date() ). The method returns a Service Manager-formatted date/time string or null if the conversion fails..getISODate()..30) . The method returns a string containing the ISO date of a date/time object or null if conversion fails.getSCDateTimeString()." ). Example This example does the following: l l Creates a new XMLDate object containing today's date Converts the XMLDate object to Service Manager-formatted date/time string then displays the result print( "Creating XMLDate object. Syntax XMLDate.getISODate() This method returns a string containing the date portion of date/time object in ISO format..getGMTSCDateTimeString() This method returns HP Service Manager-formatted date/time string in Greenwich Mean Time (GMT). JavaScript method: XMLDate. Return values A string or null.. Syntax XMLDate.Programming Guide Chapter 6: JavaScript and Service Manager reference var sm = d. print( "Converting the XMLDate to a Service Manager date/time string.getDatum().getGMTSCDateTimeString(). Arguments There are no arguments for this method. print( "The Service Manager Datum object is: " + sm ). var sc = d. print( "The Service Manager GMT date/time string is: " + sc ). Example This example does the following: Page 363 of 396 HP Service Manager (9. var d = new XMLDate( new Date() )." ). Return values A string or null. Arguments There are no arguments for this method. JavaScript method: XMLDate. print( "The value of the new XMLDate object is: " + d ). getISODateTimeString().30) . print( "Converting the XMLDate to ISO format.. Return values A string or null.getISODateTimeString()... The method returns a string containing the ISO day of a date/time object or null if the conversion fails.Programming Guide Chapter 6: JavaScript and Service Manager reference l l Creates a new XMLDate object containing today's date Converts the XMLDate object to an ISO date then displays the result print( "Creating XMLDate object." ). Syntax XMLDate. Arguments There are no arguments for this method. Arguments There are no arguments for this method. print( "Converting the XMLDate to ISO format. var ISO = d. Example This example does the following: l l Creates a new XMLDate object containing today's date Converts the XMLDate object to an ISO date and time then displays the result print( "Creating XMLDate object. var d = new XMLDate( new Date() ). Syntax XMLDate. The method returns a string containing the ISO date and time of a date/time object or null if the conversion fails. var ISO = d. print( "The value of the new XMLDate object is: " + d ).getISODay().getISODay() This method returns a string containing the day portion of date/time object in ISO format." ).. print( "The value of the new XMLDate object is: " + d ).. JavaScript method: XMLDate.getISODate().. print( "The ISO date and time is: " + ISO ). Return values A string or null. var d = new XMLDate( new Date() ).getISODateTimeString() This method returns a string containing the date and time portion of date/time object in ISO format. Page 364 of 396 HP Service Manager (9.." ). JavaScript method: XMLDate.." ). print( "The ISO date is: " + ISO ). print( "The value of the new XMLDate object is: " + d )..getISODay().30) .. var d = new XMLDate( new Date() )." ). print( "Converting the XMLDate to ISO format. JavaScript method: XMLDate." ). Syntax XMLDate.getISOMonth() This method returns a string containing the month portion of date/time object in ISO format. var d = new XMLDate( new Date() ).. JavaScript method: XMLDate.getISOTime(). var ISO = d. The method returns a string containing the ISO month of a date/time object or null if the conversion fails.getISOMonth(). print( "Converting the XMLDate to ISO format. print( "The value of the new XMLDate object is: " + d ).getISOMonth(). print( "The ISO day is: " + ISO ).. var ISO = d..getISOTime() This method returns a string containing the time portion of date/time object in ISO format." ).Programming Guide Chapter 6: JavaScript and Service Manager reference Example This example does the following: l l Creates a new XMLDate object containing today's date Converts the XMLDate object to an ISO day then displays the result print( "Creating XMLDate object. Example This example does the following: l l Creates a new XMLDate object containing today's date Converts the XMLDate object to an ISO month then displays the result print( "Creating XMLDate object." ). Arguments There are no arguments for this method. Return values A string or null. print( "The ISO month is: " + ISO )... Arguments There are no arguments for this method. Syntax XMLDate. Return values Page 365 of 396 HP Service Manager (9.. Return values A string or null. print( "The value of the new XMLDate object is: " + d ).. var d = new XMLDate( new Date() )...." )..getISOYear(). JavaScript method: XMLDate.getSCDateTimeString() This method returns an HP Service Manager-formatted date/time string.Programming Guide Chapter 6: JavaScript and Service Manager reference A string or null. print( "Converting the XMLDate to ISO format. Syntax XMLDate.. print( "Converting the XMLDate to ISO format.30) .getISOTime().. var ISO = d. JavaScript method: XMLDate.getISOYear() This method returns a string containing the year portion of date/time object in ISO format." ). The method returns a string containing the ISO year of a date/time object or null if the conversion fails. Arguments There are no arguments for this method. Example This example does the following: l l Creates a new XMLDate object containing today's date Converts the XMLDate object to an ISO year then displays the result print( "Creating XMLDate object. Syntax XMLDate. Example This example does the following: l l Creates a new XMLDate object containing today's date Converts the XMLDate object to an ISO time then displays the result print( "Creating XMLDate object. var ISO = d. print( "The ISO time is: " + ISO ). var d = new XMLDate( new Date() ).getSCDateTimeString()." )." ). print( "The ISO year is: " + ISO ). Arguments Page 366 of 396 HP Service Manager (9.getISOYear(). print( "The value of the new XMLDate object is: " + d ).. The method returns a string containing the ISO time of a date/time object or null if the conversion fails. This method is an alias of the getDate() method." ). print( "The Service Manager date/time string is: " + sc ).. var d = new XMLDate( new Date() ). print( "Converting the XMLDate to a Service Manager date/time string. Example This example does the following: l l Creates a new XMLDate object containing today's date Converts the XMLDate object to Service Manager-formatted date/time string then displays the result print( "Creating XMLDate object.getSCDateTimeString(). JavaScript method: XMLDate. Syntax XMLDate. print( "The value of the new XMLDate object is: " + d )..Programming Guide Chapter 6: JavaScript and Service Manager reference There are no arguments for this method." ).JSDate(). Return values A string or null.toSCDuration() This method converts an ISO 8601 duration string to an HP Service Manager duration string. The method returns a Service Manager-formatted date/time string or null if the conversion fails. var d = new XMLDate( new Date() ). Example This example does the following: l l Creates a new XMLDate object containing today's date Converts the XMLDate object to a JavaScript date/time object then displays the result print( "Creating XMLDate object. print( "The JavaScript date/time object is: " + js ). var sc = d.. JavaScript method: XMLDate.. print( "Converting the XMLDate to a JavaScript object. The method returns a JavaScript date/time object or null if the conversion fails. Page 367 of 396 HP Service Manager (9.30) .JSDate(). Return values A string or null. var js = d..JSDate() This method returns a JavaScript date/time object. print( "The value of the new XMLDate object is: " + d )." ). Arguments There are no arguments for this method." ).... " ).. Returns the activated action on a node in the graph diagram. Example This example does the following: l l Creates a new XMLDate object containing a hard-coded ISO date Converts the ISO date/time to a Service Manager duration string print( "Creating XMLDate object. Return values A string or null. print( "The value of the new XMLDate object is: " + d ). print( "Converting " + d.30) ...toString() + " to a SC duration. JavaScript function add_ graphnodes get_graph_ action get_graph_id Description Returns XML to the Run-Time Environment (RTE) for the expand action on a node in the graph diagram. print( "The Service Manager duration is: " + smDur ). These functions provide a method of performing certain commands that will return a value when executed. Arguments The following arguments are valid for this function: Argument Data type Required Description duration ISO 8601 duration string Yes This argument contains the ISO 8601 duration string or variable value you want the script to convert to a Service Manager duration string. The method returns a Service Manager duration string or null if the conversion fails. var d = new XMLDate( "P01DT12H01M01S" ). var smDur = d. Returns the value of the node ID for the expand action on a node in the graph diagram. get_graph_ node_id get_graph_ target Page 368 of 396 HP Service Manager (9. Returns the value of the graph ID for the expand action on a node in the graph diagram." ).toSCDuration()..Programming Guide Chapter 6: JavaScript and Service Manager reference Syntax XMLDate.toSCDuration( duration ). Returns the target for an activated action on a node in the graph diagram. List: JavaScript functions The following table lists some of the JavaScript functions available in Service Manager. Refer to "List: RAD functions" (on page 81) for more information on using RAD functions to perform these commands instead of JavaScript. htm() JavaScript function: get_graph_node_id Description A JavaScript function that returns the value of the node ID for the expand action on a node in the graph diagram.functions.functions.functions. Function get_graph_action() Example system. Function add_graphnodes() Example system.get_graph_action() JavaScript function: get_graph_id Description A JavaScript function that returns the value of the graph ID for the expand action on a node in the graph diagram.get_graph_node_id() JavaScript function: get_graph_target Description Page 369 of 396 HP Service Manager (9.30) .add.graphnodes(String strXML) JavaScript function: get_graph_action Description A JavaScript function that returns the activated action on a node in the graph diagram.get_graph_id. Function get_graph_node_id() Example system.htm() Example system.evaluate() Returns the value of a given expression. Function get_graph_id.Programming Guide Chapter 6: JavaScript and Service Manager reference parse.functions. JavaScript function: add_graphnodes This function returns an XML file to the Run-Time Environment (RTE) for the expand action on a node in the graph diagram. Page 370 of 396 HP Service Manager (9.2 6. JavaScript function addToGroup checkAllowedOption isInGroup removeFromGroup returnGroupMembers returnMyGroups Implemented in version 6. These functions are part of system JavaScript files and should not be directly modified.30) . you can specify it as a string. Arguments The following arguments are valid for this function: Name ci Data type Required Description This argument contains the CI records you want to add.addToGroup( ci. Syntax lib. This argument contains the name of the configuration group to which you want to add CIs. the ci argument must be an SCFile or SCDatum object. Function get_graph_target Example system.Programming Guide Chapter 6: JavaScript and Service Manager reference A JavaScript function that returns the target for an activated action on a node in the graph diagram.ciGrouping. Datum Yes object or string Yes groupName String Return values A numerical value: 0 or 1.2 6.get_graph_target() List: JavaScript functions in the ScriptLibrary The following table lists some of the JavaScript functions available in the ScriptLibrary of Service Manager.2 6.2 JavaScript function: addToGroup This function adds one or more configuration items (CIs) to a Configuration Management list group and updates the list group record if successful. It is part of a system JavaScript and should not be directly modified.2 6. groupName ).2 6. To add an array of CIs.functions. To add a single CI. strings. */ var targetCIGroup. Example This example attempts to add CIs to a list group from the following sources: l l l l The logical. * Use startsWith to store a alphabetical value you want to query for.name value from a hard-coded string The logical. var startsWith. var recordTest.name you want to add.name values from an array of CI records The logical. */ function findCIGroup( ciGroup ) { Page 371 of 396 HP Service Manager (9. The function returns 1 if the function successfully adds the CIs to the list group. * Use targetCIGroup to store the name of CI group you want to add records to. var arrayTest. and datum objects. var deviceType. * Use oneLogicalName to store a string containing a logical. * Use deviceType to store a device type you want to query for. /* Create a function to store a particular CI group in memory.name value from a configuration group record The logical. var oneLogicalName.name values from a record list of one or more CIs This example requires the following sample data: l Create a list group containing a single configuration item (for example. * The variable recordTest stores the output of the findCIGroup function. a list group called "test03" containing the configuration items "HH-000001" and "HH-000002") l l /* Create variables to store CI group names.Programming Guide Chapter 6: JavaScript and Service Manager reference The function returns 0 if it is unable to add CIs to the list group or if the groupName argument specifies a query group. var sourceCIGroup. * The variable recordListTest stores the output of the findRecordList function. * The variable arrayTest stores the output of the createArray function. * Use sourceCIGroup to store the name of CI group you want to create an array from. a list group called "test01" containing the configuration item "DEFAULT Phone 0001") Create a list group containing one or more configuration items (for example. var recordListTest.30) . a list group called "test02" containing the configuration item "DEFAULT Phone 0003") Create a list group containing one or more configuration items (for example. var queryTest = ciGroupRecord. if ( query != null ) { print( "Looking for CIs matching type=\"" + deviceType + "\"\&" + "logical..$L_file = ciGroupRecord print( "Found CI group record for " + ciGroup + "\nThe record is:\n" + ciGroupRecord ).name#\"" + query + "\"" ) } else { print( "Looking for CIs matching type=\"" + deviceType + "\"" ).doSelect( "type=\"" + deviceType + "\"" ) } if ( queryTest == RC_SUCCESS ) { print( "Found the following CIs:\n" + ciRecordList ). query ) { var ciRecordList = new SCFile( "device" ).Programming Guide Chapter 6: JavaScript and Service Manager reference print( "Looking for CI Group " + ciGroup + ".vars." ).30) ..returnGroupMembers( ciGroup ) var ciGroupRecord = new SCFile( "cigroup" ).ciGrouping.name#\"" + query + "\"" ). print( "The current members of " + ciGroup + " are:\n" + members ). } else { if ( query != null ) { Page 372 of 396 HP Service Manager (9.$L_file = ciRecordList return ciRecordList. var queryTest = ciRecordList." ).vars.doSelect( "type=\"" + deviceType + "\"\&" + "logical.name=\"" + ciGroup + "\"" ) if ( queryTest == RC_SUCCESS ) { system. " + RCtoString( queryTest ) + ". return null. var queryTest = ciRecordList.doSelect( "logical. return ciGroupRecord } else { print( "Cannot find record for " + ciGroup + ". } } /* Create function to find a record list based on a device type and starting query */ function findRecordList( deviceType. var members = lib. system. } else Page 373 of 396 HP Service Manager (9. group ) { var groupMembers = lib. Group not in the cigroup table." ). print( "Now trying to add configuration item(s) to " + group + ". if ( AddCI == 1 ) { print( "Successfully added configuration item(s) to " + group )." ). */ function testAdd( ci.names of the record.ciGrouping.ciGrouping. if (arrayOfLogicalNames == null ) { print( "Cannot create array from " + record + ".Programming Guide Chapter 6: JavaScript and Service Manager reference print( "Cannot find records matching query: device=\""+ deviceType + "\"&logical.addToGroup( ci. print( "The members of " + group + " are now: \n" + afterAdd ). } else { print( "Cannot find records matching query: device=\""+ deviceType + "\"" + RCtoString( queryTest ) + ". group ). var afterAdd = lib. } } } /* Create a function to store the logical." )..returnGroupMembers( group ) var AddCI = lib.returnGroupMembers( group ). return arrayOfLogicalNames } } /* Create a function to call the addToGroup function and print results.group_members.ciGrouping.\nThe array is:\n" + arrayOfLogicalNames ).." ). */ function createArray( record ) { var arrayOfLogicalNames = record.30) . return null } else { print( "Created array from " + record + ". return null.name#\"" + query + "\"" + RCtoString( queryTest ) + ". return null. print( "The current members of " + group + " are:\n" + groupMembers ). 30) . targetCIGroup ).\n" ). if ( recordTest != null ) { testAdd( system. if ( recordTest != null ) { arrayTest = createArray( recordTest ).\n" ). targetCIGroup = "test01". targetCIGroup ).. targetCIGroup = "test01". targetCIGroup ). recordListTest = findRecordList( deviceType.vars. sourceCIGroup = "test03". testAdd( arrayTest.$L_file.. recordTest = findCIGroup( sourceCIGroup ).. } /* Test adding one or more CIs to a group from a CI record list */ print( "Now testing adding one or more CIs from a CI record list.Programming Guide Chapter 6: JavaScript and Service Manager reference { print( "Could not add configuration item(s) to " + group ).names */ print( "Now testing adding one or more CIs from an array of logical names. print( "The members of " + group + "are : \n" + groupMembers ).. } Page 374 of 396 HP Service Manager (9. targetCIGroup = "test01"..\n" ). recordTest = findCIGroup( sourceCIGroup ).returnGroupMembers( targetCIGroup ) testAdd( oneLogicalName. } } /* Test adding a CI to a group from a string */ print( "Now testing adding a single CI from a string. members = lib. startsWith ).$L_file. targetCIGroup ). /* Test adding a CI to a group from an existing CI record */ print( "Now testing adding a CI member from a CI group record.. if ( recordListTest != null ) { testAdd( system. } /* Test adding one or more CIs from an array of logical. sourceCIGroup = "test02"...vars. oneLogicalName = "DEFAULT Phone 0002". deviceType = "furnishings" startsWith = null.\n" ).ciGrouping. targetCIGroup = "test01". This argument contains an array of numbers representing the decimal value of the maximum number increments possible. String Yes Yes maxIncrement Array Return values A valid version number or the string "more".checkAllowedOption( versionOld.versionControl. maxIncrement ). */ var oldVersion. This example requires the following sample data: l l A variable storing the old version number A variable storing the maximum number of increments allowed /* Use oldVersion to store the old version number as a string. For example.0. Description This function is part of a system JavaScript and should not be directly modified. if maxIncrement equals [0. Example This example attempts to create the next valid version from two variables. if ( nextVersion == "more" ) Page 375 of 396 HP Service Manager (9. This function returns the next valid version number of a Configuration Management baseline group if there is one and only one valid version number available. Arguments The following arguments are valid for this function: Name oldVersion Data type Required Description This argument contains the previous version number. The function returns a valid version number if there is one and only one valid next version number.1. increment ) { var nextVersion = lib.1.0. var maxIncrement = new Array(). * Use maxIncrement to store the maximum number of increments as an array.0] then there are ten possible increments permissible from versions 0.versionControl. Syntax lib.1 to 0.Programming Guide Chapter 6: JavaScript and Service Manager reference JavaScript function: checkAllowedOption Returns the next valid version number of a Configuration Management baseline group if there is only one valid version number available.checkAllowedOption( oldVersion. If there is more than one valid next version number then the function returns the string "more". increment ). The function returns the string "more" if there is more than one valid next version number. /* Create a function to test the checkAllowedOption function */ function nextVersionTest( versionOld.30) . 0".Programming Guide Chapter 6: JavaScript and Service Manager reference { print( "Error.1]..0. newVersion. There is more than one valid next version number for " + versionOld + ". The next valid version number is " + nextVersion + ". print( "The current version number is " + oldVersion + ". print( "The maximum allowed increment is " + maxIncrement + ".\n" ).. For example. maxIncrement ). nextVersionTest( oldVersion. /* Test a valid version number update */ print( "Testing checkAllowedOption. maxIncrement ).30) Page 376 of 396 .0". return nextVersion } } /* Test a valid version number update */ print( "Testing checkAllowedOption. oldVersion = "1. print( "The maximum allowed increment is " + maxIncrement + ". maxIncrement ).")..\n" ). maxIncrement = [0.1.\n" ).\n" ).9.0.versionControl.0] then there are ten possible increments permissible from versions 0. JavaScript function: checkVersionString Validates a version string to ensure it adheres to Configuration Management baseline group version number requirements."). maxIncrement ). print( "The current version number is " + oldVersion + ".checkVersionString( oldVersion. /* Test an invalid version number update */ print( "Testing error condition. print( "The maximum allowed increment is " + maxIncrement + ". oldVersion = "0.1. nextVersionTest( oldVersion.. nextVersionTest( oldVersion." ). if maxIncrement equals [0. Syntax lib. Arguments The following arguments are valid for this function: maxIncrement Array Yes This argument contains an array of numbers representing the decimal value of the maximum number increments possible. return versionOld } else { print( "Success." ). maxIncrement = [0.9".\n").1]... HP Service Manager (9.0.1 to 0. maxIncrement = [0. print( "The current version number is " + oldVersion + ". oldVersion = "1.").2]." ). 1" since the oldVersion has two version levels and the newVersion has three.0" as this is a version with six version levels. The function returns -1 if the newVersion argument contains greater than five version levels.1. -1. This example requires the following sample data: Page 377 of 396 HP Service Manager (9. For example.1" and newVersion equals "1.1 to 0.1.0.0. For example.Programming Guide Chapter 6: JavaScript and Service Manager reference oldVersion newVersion String Yes String Yes Yes This argument contains the previous version number. maxIncrement Array Return values An integer value: 0. then the function returns a value of 0 if newVersion equals "1. and maxIncrement equals "2". This argument contains an array of numbers representing the decimal value of the maximum number increments possible.1.0. The function returns -2 if a version level value in the newVersion argument contains anything other than the digits 0 to 9. 1 -1 -2 -3 -4 Description This function is part of a system JavaScript and should not be directly modified.0.0. The function returns -3 if the number of version levels in the oldVersion argument do not match the number of version levels in the newVersion argument. Return value Condition 0 The function returns 0 if any version level value in the newVersion argument exceeds the value in the maxIncrement argument. or -4. if maxIncrement equals [0. For example. This argument contains the new version number. the function returns -1 if the newVersion argument equals "1. 1.0". the function returns -3 if oldVersion equals "1. -2.0. For example the function returns -2 if the newVersion argument equals "gold" or "1. Example This example attempts to validate any given version number update from three variables.1" and newVersion equals "1.0" because the newVersion value is prior to the oldVersion value.30) . The function returns -4 if the value of the newVersion argument is less than the value of the oldVersion argument. if oldVersion equals "1. The function returns 1 if it successfully validates the proposed change from the oldVersion to the newVersion. the function returns -4 if oldVersion equals "1. For example. This function validates a new Configuration Management baseline group version string against an old version string to ensure it adheres to version number requirements. -3.3" since going from a value of zero to three exceeds the maxIncrement value of 2. For example.0] then there are ten possible increments permissible from versions 0.0a" because the version number contains alphabetical characters. return versionOld } if ( validate == "-2" ) { print( "Error. * Use maxIncrement to store the maximum number of increments as an array. Could not update " + versionOld + " to " + versionNew + ".versionControl. /* Create a function to test the checkVersionString function */ function versionTest( versionOld."). var maxIncrement = new Array(). return versionNew } if ( validate == 0 ) { print( "Error. if ( validate == 1 ) { print( "Success. Updating " + versionOld + " to " + versionNew + " is a valid change. * Use newVersion to store the new version number as a string." ). versionNew. return versionOld } if ( validate == "-1" ) { print( "Error. return versionOld } Page 378 of 396 HP Service Manager (9. versionNew.").\n"). Could not update " + versionOld + " to " + versionNew + ". */ var oldVersion.30) . print( "The new version " + versionNew + " contains more than five version levels. increment ) { var validate = lib." ).Programming Guide Chapter 6: JavaScript and Service Manager reference l l l A variable storing the old version number A variable storing the desired new version number A variable storing the maximum number of increments allowed /* Use oldVersion to store the old version number as a string. Could not update " + versionOld + " to " + versionNew + ". var newVersion. increment ). print( "The new version " + versionNew + " exceeds the maximum version increment value of " + increment + ". print( "The checkVersionString return value is " + validate ).checkVersionString( versionOld." )." ). print( "The new version " + versionNew + " contains characters other than 0 to 9. oldVersion = "1.. return versionOld } if ( validate == "-4" ) { print( "Error.0.").0.")..0.0. maxIncrement = [0.0.\n" ). print( "The new version " + versionNew + " is an earlier version than the old version " + versionOld ).1". oldVersion = "1..1.1.2]. newVersion = "1.2].0.Programming Guide Chapter 6: JavaScript and Service Manager reference if ( validate == "-3" ) { print( "Error.\n" ).. Page 379 of 396 HP Service Manager (9. print( "The new version " + versionNew + " contains a different number of version levels than the old version " + versionOld ). maxIncrement ).0. /* Test an invalid version number update */ print( "Testing error condition 0. maxIncrement ). newVersion. versionTest( oldVersion.2]. newVersion. /* Test an invalid version number update */ print( "Testing error condition -2. oldVersion = "1. newVersion = "1.0.0".0". Could not update " + versionOld + " to " + versionNew + ". /* Test an invalid version number update */ print( "Testing error condition -1. newVersion = "1. newVersion. maxIncrement = [0.1. versionTest( oldVersion. oldVersion = "1.. return versionOld } else { return versionOld } } /* Test a valid version number update */ print( "Testing checkVersionString.0.. maxIncrement ).0". maxIncrement = [0. newVersion = "1.2].a.\n" ).0".0.9".30) .0".1".0. Could not update " + versionOld + " to " + versionNew + ".0.0.0..0. maxIncrement = [0.\n" ).. versionTest( oldVersion.1. . maxIncrement = [0. Example This example attempts to search for a CI in the following groups: l l A list group A query group This example requires the following sample data: Page 380 of 396 HP Service Manager (9. Arguments The following arguments are valid for this function: Name ci Data type Required Description This argument contains the CI record you want to search for in the group. /* Test an invalid version number update */ print( "Testing error condition -4.2]. JavaScript function: isInGroup Searches for one configuration item (CI) in a Configuration Management list or query group. newVersion = "1. This function searches for a CI in list or query groups and returns a Boolean value of true if successful.. The function returns false if it is unable to find the CI in the list or query group. newVersion.0.ciGrouping.\n" ). newVersion.isInGroup( ci. oldVersion = "1. oldVersion = "1.1". maxIncrement ).2]. maxIncrement = [0. groupName ). String Yes groupName String Yes Return values A Boolean value: true or false. The function returns true if the function successfully finds the CI in the list or query group.30) . versionTest( oldVersion.1".Programming Guide Chapter 6: JavaScript and Service Manager reference versionTest( oldVersion. newVersion.2". /* Test an invalid version number update */ print( "Testing error condition -3. maxIncrement ).\n" ).0".. versionTest( oldVersion. Description This function is part of a system JavaScript and should not be directly modified. maxIncrement ). newVersion = "1.. Syntax lib.2. This argument contains the name of the configuration group where you want to search for the CI. var members.30) . print( "The current members of " + targetCIGroup + " are:\n" + members ).. */ print( "Now testing isInGroup on query group. a list group called "test01" containing the configuration item "DEFAULT Phone 0001") Create a query group containing one or more configuration items (for example.ciGrouping.ciGrouping. Found " + ci + " in " + group ). targetCI = "DEFAULT Phone 0001". } else { print( "Error." ). group ) { inGroupTest = lib. } } /* Test returnGroupMembers on a list group. members = lib. group )." ).isInGroup( ci. findInGroup( targetCI. Syntax Page 381 of 396 HP Service Manager (9.returnGroupMembers( targetCIGroup ) print( "Looking for " + targetCI + " in " + targetCIGroup + ".returnGroupMembers( targetCIGroup ) print( "Looking for " + targetCI + " in " + targetCIGroup + "... var targetCI. Could not find " + ci + " in " + group ).. function findInGroup( ci.. /* Test returnGroupMembers on a query group. */ print( "Now testing isInGroup on list group. print( "The current members of " + targetCIGroup + " are:\n" + members ).. targetCIGroup = "test04". if ( inGroupTest == true ) { print( "Success. targetCIGroup ).\n" ).. findInGroup( targetCI. JavaScript function: removeFromGroup Removes one or more configuration items (CI) from a Configuration Management list group. a query group called "test04" containing the configuration items where type equals "telecom") l /* Create variables to store CI group name and the results of returnGroupMembers */ var targetCIGroup.Programming Guide Chapter 6: JavaScript and Service Manager reference l Create a list group containing one or more configuration items (for example. targetCI = "DEFAULT Phone 0006". members = lib.ciGrouping.\n" ).. targetCIGroup = "test01". targetCIGroup ). or -1 The function returns 0 if it is unable to remove CIs from the list group or if the groupName argument specifies a query group. * Use sourceCIGroup to store the name of CI group you want to create an array from.removeFromGroup( ci. Datum Yes object or string Yes groupName String Return values A numerical value: 0. The function returns -1 if it cannot remove CIs from the list group because the action would result in an empty configuration list group. and datum objects. Arguments The following arguments are valid for this function: Name ci Data type Required Description This argument contains the CI records you want to remove. This argument contains the name of the configuration group from which you want to remove CIs. * Use oneLogicalName to store a string containing a logical.ciGrouping. Description This function is part of a system JavaScript and should not be directly modified. a list group called "test03" containing the configuration items "HH-000001" and "HH-000002") l l /* Create variables to store CI group names. a list group called "test02" containing the configuration item "DEFAULT Phone 0003") Create a list group containing one or more configuration items (for example. a list group called "test01" containing the configuration item "DEFAULT Phone 0001") Create a list group containing one or more configuration items (for example. To remove a single CI. you can specify it as a string. groupName ). * Use targetCIGroup to store the name of CI group you want to remove records from.30) . The function returns 1 if the function successfully removes CIs from the list group. * Use deviceType to store a device type you want to query for. Page 382 of 396 HP Service Manager (9.name you want to remove. the ci argument must be an SCFile or SCDatum object. 1. This function removes one or more CIs from a configuration list group and updates the list group record if successful. strings. To remove an array of CIs.Programming Guide Chapter 6: JavaScript and Service Manager reference lib. Example This example attempts to remove the following CIs from a list group: l l l A string containing a single CI record A configuration group record containing one or more CIs A Datum object containing an array of CI records This example requires the following sample data: l Create a list group containing a single configuration item (for example. var startsWith." ). var recordListTest.name=\"" + ciGroup + "\"" ) if ( queryTest == RC_SUCCESS ) { system. */ function findCIGroup( ciGroup ) { print( "Looking for CI Group " + ciGroup + ".$L_file = ciGroupRecord print( "Found CI group record for " + ciGroup + "\nThe record is:\n" + ciGroupRecord ). */ var targetCIGroup. var sourceCIGroup. var oneLogicalName.30) . /* Create a function to store a particular CI group in memory.. if ( query != null ) { print( "Looking for CIs matching type=\"" + deviceType + "\"\&" + Page 383 of 396 HP Service Manager (9.. return null. var queryTest = ciGroupRecord. var recordTest.vars. var members = lib. " + RCtoString( queryTest ) + ". var deviceType. var arrayTest. return ciGroupRecord } else { print( "Cannot find record for " + ciGroup + "." ). * The variable recordListTest stores the output of the findRecordList function.ciGrouping.returnGroupMembers( ciGroup ) var ciGroupRecord = new SCFile( "cigroup" ). query ) { var ciRecordList = new SCFile( "device" ). * The variable recordTest stores the output of the findCIGroup function.doSelect( "logical. } } /* Create function to find a record list based on a device type and starting query */ function findRecordList( deviceType. * The variable arrayTest stores the output of the createArray function. print( "The current members of " + ciGroup + " are:\n" + members ).Programming Guide Chapter 6: JavaScript and Service Manager reference * Use startsWith to store a alphabetical value you want to query for. names of the record. } } } /* Create a function to store the logical. return null.doSelect( "type=\"" + deviceType + "\"\&" + "logical. return null } else { print( "Created array from " + record + ". var queryTest = ciRecordList. return arrayOfLogicalNames } Page 384 of 396 HP Service Manager (9. } else { if ( query != null ) { print( "Cannot find records matching query: device=\""+ deviceType + "\"&logical. Group not in the cigroup table." ).name#\"" + query + "\"" + RCtoString( queryTest ) + ".\nThe array is:\n" + arrayOfLogicalNames ). */ function createArray( record ) { var arrayOfLogicalNames = record.name#\"" + query + "\"" ) } else { print( "Looking for CIs matching type=\"" + deviceType + "\"" ). var queryTest = ciRecordList.$L_file = ciRecordList return ciRecordList." ).group_members.name#\"" + query + "\"" ).30) ." ). } else { print( "Cannot find records matching query: device=\""+ deviceType + "\"" + RCtoString( queryTest ) + ".Programming Guide Chapter 6: JavaScript and Service Manager reference "logical.doSelect( "type=\"" + deviceType + "\"" ) } if ( queryTest == RC_SUCCESS ) { print( "Found the following CIs:\n" + ciRecordList ). system.vars. if (arrayOfLogicalNames == null ) { print( "Cannot create array from " + record + ". return null. 30) .. /* Test removing a CI to a group from an existing CI record */ print( "Now testing removing a CI member from a CI group record.ciGrouping. */ function testRemove( ci.returnGroupMembers( group ). print( "The members of " + group + " are now: \n" + afterRemove ). group ). oneLogicalName = "DEFAULT Phone 0002". var afterRemove = lib.ciGrouping. group ) { var groupMembers = lib.\n" ). print( "The members of " + group + "are : \n" + groupMembers ). recordTest = findCIGroup( sourceCIGroup ). targetCIGroup = "test01".removeFromGroup( ci." ). sourceCIGroup = "test02".." ).ciGrouping.. } } } /* Test removing a CI to a group from a string */ print( "Now testing removing a single CI from a string. } else { print( "Could not remove configuration item from " + group + ".returnGroupMembers( group ) var removeCI = lib. targetCIGroup = "test01". print( "Now trying to remove configuration item(s) from " + group + ".").ciGrouping. if ( removeCI == 1 ) { print( "Successfully removed configuration item(s) to " + group ). print( "The current members of " + group + " are:\n" + groupMembers ).\n" + ci + " or " + group + " does not exist.returnGroupMembers( targetCIGroup ) testRemove( oneLogicalName.Programming Guide Chapter 6: JavaScript and Service Manager reference } /* Create a function to call the addToGroup function and print results. } else { if ( removeCI == "-1" ) { print( "Could not remove configuration item from " + group + " as " + ci + " is the last member of the group...\n" ). Page 385 of 396 HP Service Manager (9. targetCIGroup ). members = lib.. 30) . } JavaScript function: returnGroupMembers Returns an array containing the group members of a Configuration Management group. groupName String Yes Return values An array or null. recordTest = findCIGroup( sourceCIGroup ). if ( recordListTest != null ) { testRemove( system.vars. targetCIGroup ). deviceType = "furnishings" startsWith = null.\n" )..ciGrouping. targetCIGroup ). The function returns null if it cannot find a matching group name or if the group does not have any members. targetCIGroup )..\n" ). } /* Test removing one or more CIs from an array of logical. targetCIGroup = "test01".$L_file. Arguments The following arguments are valid for this function: Name Data type Required Description This argument contains the name of the configuration group whose members you want to return as an array. targetCIGroup = "test01". if ( recordTest != null ) { arrayTest = createArray( recordTest ).$L_file.returnGroupMembers( groupName ).. sourceCIGroup = "test03"..Programming Guide Chapter 6: JavaScript and Service Manager reference if ( recordTest != null ) { testRemove( system. testRemove( arrayTest. recordListTest = findRecordList( deviceType. Syntax lib.vars. startsWith ). } /* Test removing one or more CIs to a group from a CI record list */ print( "Now testing removing one or more CIs from a CI record list. The function returns an array containing the logical.name values of the group members if there are group members. Page 386 of 396 HP Service Manager (9.names */ print( "Now testing removing one or more CIs from an array of logical names. Syntax lib.. This function returns the logical. l If the group is a list type. JavaScript function: returnMyGroups Returns an array containing all the groups to which a configuration item (CI) belongs. targetCIGroup = "test04".returnMyGroups( ci. the function returns the array from the group configuration item record. a list group called "test04" containing the configuration items where type equals "telecom") l /* Create variables to store CI group name and the results of returnGroupMembers */ var targetCIGroup.ciGrouping..name values of the members of a Configuration Management group. /* Test returnGroupMembers on a query group */ print( "Now testing returnGroupMembers on a query group.returnGroupMembers( targetCIGroup ).ciGrouping. /* Test returnGroupMembers on a list group */ print( "Now testing returnGroupMembers on a list group.ciGrouping. print( "The current members of " + targetCIGroup + " are:\n" + members ). members = lib. This example requires the following sample data: l Create a list group containing one or more configuration items (for example.. targetCIGroup = "test01".returnGroupMembers( targetCIGroup ). a list group called "test01" containing the configuration item "DEFAULT Phone 0001") Create a query group containing one or more configuration items (for example.30) . listType ). members = lib.\n" ). If the group is a query type. print( "The current members of " + targetCIGroup + " are:\n" + members ). Arguments The following arguments are valid for this function: Name ci Data type Required Description This argument contains the CI record you want to search for in String Yes Page 387 of 396 HP Service Manager (9.Programming Guide Chapter 6: JavaScript and Service Manager reference Description This function is part of a system JavaScript and should not be directly modified.\n" ). l Example This example returns the members of the group listed in the variable.. the function returns an array of all the CIs it finds. var members. l Example This example returns the groups containing the CI listed in a variable. var groups. null – If there is a null entry for this argument. a list group called "test03" containing the configuration items "HH-000001" and "HH-000002") Create a query group containing one or more configuration items (for example.Programming Guide Chapter 6: JavaScript and Service Manager reference your list and query groups. the function searches both list and query groups. Description This function is part of a system JavaScript and should not be directly modified. If the group is a query type. listType String No This argument contains a string describing which types of configuration groups you want the function to query. The function queries all group records and does the following: l If the group is a list type. The function returns an array containing the logical. query – Add this argument to only search query groups. adds it to the groupArray.name values of the groups in which the CI is a member.30) . a list group called "test01" containing the configuration item "DEFAULT Phone 0001") Create a list group containing one or more configuration items (for example. /* Search for a CI in a list group only */ Page 388 of 396 HP Service Manager (9. a query group called "test04" containing the configuration items where type equals "telecom") l l l /* Create variables to store CI group name and the results of returnMyGroups */ var targetCIGroup.members and if the CI exists in the list group. The string can have one of four values: l l l list – Add this argument to only search list groups. This function returns an array containing the logical. var listTypes. The function returns an empty array if it cannot find the CI in any list or query group. the function uses the RTE function to determine whether the values in the CI record satisfy the search criteria defined by the query. This example requires the following sample data: l Create a list group containing a single configuration item (for example.name values of the list and query groups in which the CI is a member. a list group called "test02" containing the configuration item "DEFAULT Phone 0003") Create a list group containing one or more configuration items (for example. l Return values An array of group names. the function indexes the group. both – Add this argument to search both list and query groups. \n" ).returnMyGroups( targetCI. } else { print( "There are no query groups containing " + targetCI ). } /* Search for a CI in a query group only */ print( "Now testing search for configuration items in query groups only. if ( groups. groups = lib. targetCI = "DEFAULT Phone 0001".returnMyGroups( targetCI. listTypes )..returnMyGroups( targetCI. targetCI = "DEFAULT Phone 0001".\n" ).length >= 1 ) { print( "The groups containing " + targetCI + " are:\n" + groups ).\n" )... if ( groups. listTypes ). listTypes ). listTypes = "list".. } else { print( "There are no list groups containing " + targetCI ). } else { print( "There are no groups containing " + targetCI ). listTypes = "both". if ( groups. groups = lib.length >= 1 ) { print( "The list groups containing " + targetCI + " are:\n" + groups ).length >= 1 ) { print( "The query groups containing " + targetCI + " are:\n" + groups ).ciGrouping.30) . listTypes = "query". } /* Search for a CI in both list and query groups */ print( "Now testing search for configuration items in both list and query groups. } Page 389 of 396 HP Service Manager (9..ciGrouping.ciGrouping.. targetCI = "DEFAULT Phone 0001".Programming Guide Chapter 6: JavaScript and Service Manager reference print( "Now testing search for configuration items in list groups only. groups = lib. (method of the XML object) getDocumentElement(). or property demonstrated l l l system. (method of the XML object) getFirstAttribute().30) . (method of the XML object) getNextSiblingElement().users (global property) print(). These JavaScript are intended to work with an out-of-box Service Manager system and sample data. (method of the XML object) SCFile().Programming Guide Chapter 6: JavaScript and Service Manager reference List: JavaScript examples The following table lists the JavaScript examples available for review. (method of the SCFile object) getFirstChildElement(). (method of the XML object) getValue(). (global method) getName(). (SCFile object) doSelect(). as well as code samples that call the system JavaScript functions provided in the Script Library. (method of the XML object) getValue(). and properties. methods. (method of the SCFile object) RCtoString(). (XML object) setContent(). method. (method of the XML object) XML(). (method of the XML object) l Example: Iterating through a complex XML document l l None l l l l l Example: Query a record using the SCFile object l l None l l l l Page 390 of 396 HP Service Manager (9. System functions called None JavaScript example Example: Getting a list of logged on users Service Manager object. (method of the XML object) getQualifiedName(). (method of the XML object) getFirstChildElement(). These examples include sample JavaScript code for the Service Manager-defined JavaScript objects. (method of the XML object) getName(). for ( userIndex in usersXML ) { var userXML = usersXML[userIndex].Programming Guide Chapter 6: JavaScript and Service Manager reference Example: Testing a file name l l SCFile(). recompile. you can view the suppressed output. //print( usersXML ). var usersXML = system. Page 391 of 396 HP Service Manager (9. (global method) system. (method of the SCFile object) print(). //print( userXML ).users object to get an XML list of all the currently logged-on users on the system. (method of the SCFile object) print(). recompile. (SCDatum object) getType(). (method of the SCDatum object) doUpdate(). If you uncomment the line of code. you can view the suppressed output.functions (global property) Date(). (method of the SCDatum object) RCtoString(). It prints all logged-on users as a large XML document. (global method) SCFile(). (SCFile object) doSelect(). and then run the script again.30) . and then prints the name (XML tag) and value of each field. This part of the script loops through to process each XML element node within the <user> element.users. If you uncomment the line of code. (SCFile object) doSelect(). (Date object) SCDatum(). (method of the SCDatum object) None l Example: Updating a field with the current date and time l l None l l l l l l l Example: Getting a list of logged-on users This JavaScript example accesses the built in system. It then loops through to access each individual user. This part of the script loops through to process each <user> element within <users>. It prints an individual user as an XML document. and then run the script again. length > 0 ) { print( "Element value is " + nodeValue ). and prints the name of the node and its value. while( child != null ) { var nodeName = child. The script visits each node. while( node != null ) { var attrName = node.getValue() ).getNodeName(). xmlObj.getFirstChildElement(). } } Example: Iterating through a complex XML document This JavaScript example demonstrates how to iterate through a complex XML document that includes any number of levels of nesting and contains attributes.xml".Programming Guide Chapter 6: JavaScript and Service Manager reference for ( fldIndex in userXML ) { var node = userXML[fldIndex].getNextAttribute().getDocumentElement() ). child = child. print( node.getNodeValue(). var nodeValue = child. // Print attributes for this element var node = elem.30) . visitElement( child ).getName() + ": " + node. } // Print possible element value var nodeValue = elem. } } Page 392 of 396 HP Service Manager (9.getNextSiblingElement().getFirstAttribute(). returns the root node // getDocumentElement function visitElement( elem ) { print( "Element " + elem.setContent( "c:\\test. print( "Attribute " + attrName + "=" + attrValue ).getQualifiedName(). } // Now print child elements var child = elem.getQualifiedName() ). if ( typeof nodeValue == "string" && nodeValue. true ). visitElement( xmlObj. be it an attribute node or an element node. var xmlObj = new XML().getNodeValue(). var attrValue = node.getNodeValue(). node = elem. var fContacts = new SCFile( "contacts" ).getValue() ). var rc = fContacts.Programming Guide Chapter 6: JavaScript and Service Manager reference Example: Query a record using the SCFile object This JavaScript example demonstrates how to perform the following objectives. for ( fldIndex in xmlContactsRecord ) { var node = xmlContactsRecord[fldIndex]. if ( node. } else { var xmlContactsRecord = fContacts. var fldIndex.getValue() ). "=".30) .doSelect returned " + RCtoString(rc) ). } } else print( node. 2. see "Example: Iterating through a complex XML document" (on page 392).getName().getFirstChildElement() != null ) // this node has child elements { var i. NICHOLAS\" " ). "=".name = \"BROWN. 3. print( childNode.doSelect( "contact. Iterate through the resulting XML and print the field names and values. childNode.instance. Obtain the resulting record in XML format by using the getXML method that gives you field names in addition to values.getName(). if ( rc != RC_SUCCESS ) // doSelect can also return RC_BAD_QUERY or RC_NO_MORE { print( "Error . Query a record from a table using the SCFile object. } } Page 393 of 396 HP Service Manager (9. for ( i in node ) // print the child elements { var childNode = node[i].getXML(). For a more robust approach. node. 1. l l l l l l Page 394 of 396 HP Service Manager (9. if ( typeof f == "object" && f. Example: Updating a field with the current date and time This JavaScript example demonstrates how to update a field with the current date and time.30) . var f = new SCFile( fname ). How to assign JavaScript date objects to Service Manager datetime fields. How to use SCFile method return codes to test against global properties like RC_SUCCESS.$L_file or an SCFile object) and a string containing the name of a datetime field in that file. } testFile( "nonexistentfile" ). How to pass traditional query strings that are in Service Manager syntax directly to the doSelect method. function testFile( fname ) { var undefined. testFile( "contacts" ). l l How to call the RAD filename function from JavaScript. The script takes a file object (such as system. This script illustrates several key concepts of using JavaScript in HP Service Manager. How to test the field’s data type.doSelect != undefined ) { print( fname + " is a real file!" ). The script uses a string containing the file name to create a new SCFile object. and updates the indicated field with the current date and time. How to access a field in a record using an expression of the form file[fieldName] where fieldName is a string. it contains the expected properties and methods (such as "doSelect"). How to obtain a localized error message from a return code value using the RCtoString method. If the file name is valid. } else print( fname + " is NOT a real file!" ). and then tests the resulting object to see if it is valid.Programming Guide Chapter 6: JavaScript and Service Manager reference Example: Testing a file name This JavaScript example demonstrates how to test whether or not a HP Service Manager file name in a string is valid.vars. How to return JavaScript date objects when you reference Service Manager datetime fields. return false.30) . var today. datetimestamp( f. NICHOLAS\"" ). if ( rc != RC_SUCCESS ) { // Timestamp the field Page 395 of 396 HP Service Manager (9.sysmodtime ). It selects a record from the contacts table and updates the sysmodtime field. var f = new SCFile( "contacts" ).functions. var fieldType.doSelect( "contact. print( "sysmodtime is now: " + f. function datetimestamp( file. "contact_name" ). if ( fieldType != "TIME" ) { print( "Error! Field " + fieldName + " is a " + fieldType + " field! This function can only be called with date/time fields!" ).Programming Guide Chapter 6: JavaScript and Service Manager reference l How to use underscores in JavaScript to reference Service Manager field names containing dots (such as contact. var d = new SCDatum( file[fieldName] ).name = \"BROWN. This script demonstrates how passing the wrong kind of field to the datetimestamp function generates an error message. fileName = system.filename( file ). var rc.doUpdate(). print( "sysmodtime was: " + f. rc = file. } file[fieldName] = today. "sysmodtime" ). f.name).sysmodtime ). fieldType = d. today = new Date(). print( "datetimestamp called for file " + fileName + " and field " + fieldName ). This script demonstrates calling the datetimestamp function. fieldName ) { var fileName.getType(). datetimestamp( f. } Page 396 of 396 HP Service Manager (9. } return true.Programming Guide Chapter 6: JavaScript and Service Manager reference print( "Error " + RCtoString(rc) + " trying to update " + fileName + " record" ).30) . return false.
Copyright © 2024 DOKUMEN.SITE Inc.