SM Programming Guide
SM Programming Guide
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.
Copyright Notice
© 1994-2014 Hewlett-Packard Development Company, L.P.
Trademark Notices
Adobe® is a trademark of Adobe Systems Incorporated.
Microsoft® and Windows® are U.S. registered trademarks of Microsoft Corporation.
Oracle and Java are registered trademarks of Oracle and/or its affiliates.
UNIX® is a registered trademark of The Open Group.
Linux® is the registered trademark of Linus Torvalds in the U.S. and other countries.
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.
Documentation Updates
The title page of this document contains the following identifying information:
l Software Version number, which indicates the software version.
l Document Release Date, which changes each time the document is updated.
l 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: https://softwaresupport.hp.com
This site requires that you register for an HP Passport and sign in. 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 login 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.
Support
Visit the HP Software Support Online website at: https://softwaresupport.hp.com
This website 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 website to:
l Search for knowledge documents of interest
l Submit and track support cases and enhancement requests
l Download software patches
l Manage support contracts
l Look up HP support contacts
l Review information about available services
l Enter into discussions with other software customers
l 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
HP Software Solutions Now accesses the HPSW Solution and Integration Portal website. This site enables you to explore HP Product Solutions to meet your business needs,
includes a full list of Integrations between HP Products, as well as a listing of ITIL Processes. The URL for this website is http://h20230.www2.hp.com/sc/solutions/index.jsp
Contents
Introduction to the Programming guide 16
System language 17
Data types 17
List: Data types 17
Data type: Primitive 18
Data type: Number 18
Data type: Character 19
Data type: Time 20
Data type: Boolean 21
Data type: Label 22
Data type: Compound 22
Data type: File/Record 22
File variables 22
Data type: Offset 23
Data type: Array 23
Data type: Structure 24
Data type: Operator 25
Arithmetic operators 29
Logical operators 29
Relational operators 30
Data Type: Expression 30
Data type: Pseudo field 30
Data type: Global variable 31
Data type: Local variable 31
Reserved words 31
Literals 32
Variables 32
Creating variables 33
Global variables 34
List: Default variables 34
Variable pools 36
Statements 37
Assignment statements 39
Format Control 76
Links 77
Trigger scripts 79
Triggers example 80
Using RAD functions in JavaScript 81
JavaScript function: parse_evaluate() 82
RAD functions: parse() and evaluate() 82
JavaScript global properties 83
Query operators 83
JavaScript return code properties 84
Order of execution of JavaScript versus RAD language 85
Corresponding JavaScript syntax for RAD language tasks 87
System administrators and implementers can use the standard JavaScript scripting language and RAD
to customize their Service Manager applications. RAD is the Service Manager system language that
enables administrators and implementers to manipulate Service Manager processes and workflows.
JavaScript is a widely supported, industry-standard programming language that eliminates the need for
a separate programming skill set, and reduces user reliance on proprietary tools. JavaScript in Service
Manager does not invalidate the current Service Manager RAD tool set; instead, the JavaScript interface
is an alternative to the RAD language for tailoring.The main components of this document are:
l System language reference that describes the RAD functions, rtecalls, and RAD routines
l JavaScript and Service Manager reference that describes the JavaScript global system objects,
JavaScript global methods, Service Manager defined JavaScript objects, JavaScript functions,
JavaScript functions in the ScriptLibrary, and JavaScript examples
The System language creates RAD applications that contain application panels (records) linked together
in a logical flow. Each panel performs a specific function. When the function is complete, the application
exits to another panel. The field value within the exit is a label name of another panel.
The parameter panel defines local variables passed to it by a calling application. In general, two kinds of
local variables exist: those used within an application, and those used as exits. Normally, the exit
variables are $normal (in the normal exit) and $error (in the error exit).
The first command panel, where execution begins, is always labeled start. Execution continues at a
panel’s normal exit (or another exit depending on conditions). When that exit is defined as $normal,
execution of the panel is complete. If an error is encountered, then the $error exit is taken.
Note: You must have a RAD license to view and modify the RAD applications with the RAD editor.
Data types
The HP Service Manager data type specifies the expected format of a field's data. The data type
determines the possible range of values of the set, the operations that can be performed on the values,
and the way values are stored in memory. Defining a data type enables the system to manipulate the
data appropriately. The values are denoted either by literals or variables. They also can be obtained as a
result of operations. Data types can be either primitive or compound.
Note: System Administrators and implementers should only use types 1 through 4 or 8 to 10.
time 3 Primitive Used for absolute dates and times as well as relative
(date/time) time intervals.
Local 14 Compound Used for variables only visible to the RAD application
variable
optionally followed by a decimal point, then more digits which are optionally followed by the letter E and
an exponent.
Integer 1
Negative Integer -1
l It can contain a double quotation mark, 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. For example,"Vendor=\"473\"" denotes the string:
Vendor="473".
l It can treat any special or reserved character as a literal character by preceding it with a backslash.
l An empty (for example, length of zero) character string is not the same as a character string with a
NULL value.
Alphabetic "abcde"
Numeric "12379"
Alphanumeric "a1276b45"
Special "$%=+*#@/"
Mixed "$vendor"
Mixed "$12379@6:54"
Mixed "A1276%#B"
Hexadecimal "\01\ff\c2"
l Time is recorded on a 24-hour clock. '00:00:00' is midnight, '12:00:00' is noon, '18:00:00' is 6 p.m.
l Enter absolute time in the following format: 'MM/DD/YY HH:MM:SS'. The format's sequence is
affected by the set.timezone() function. It determines the order of date (MM/DD/YY). Note that
absolute time is stored as GMT notation.
l The use of seconds is optional. If you do not use seconds, the default is :00.
l The use of time is optional in absolute time. If you omit time, it defaults to 00:00:00. For example,
'MM/DD/YY' is 'MM/DD/YY 00:00:00'.
l The use of days is optional in relative time. If you omit days, the default is 0. For example '12:00' is
zero days and 12 hours, '345 03:00' is 345 days and 3 hours.
Relative time Indicates an amount of time '197 05:00' (means 197 days and 5 hours)
l Enter the Boolean directly as true, false, NULL, unknown (t, f or u).
l $exit
l $normal
l <panel name>
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 (HP ServiceCenter / HP Service
Manager).
Every table must have a table name and other descriptive data in the database dictionary. For example,
the name of the contacts table is contacts. The contacts table has keys, fields with index numbers, and
a descriptor. Table variables are the mechanism you use to make changes to tables. Always create table
variables on the rinit command panel. The table variable stores one record at any given point in time.
The record resides in memory for display or modification. For additional information, see the Database
Management section in the Service Manager Help Center documentation.
File variables
A file variable is an instance of a single record in a file. It is not an array, but it is conceptually similar. A
file variable contains the dbdict name, the data, and the structure of an entire record as it would be
stored in the database according to the dbdict. 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. The rinit command panel binds the file variable to a file. The file name of
a file variable can be accessed either by using the pseudo field or using the filename() RAD function.
l List: records selected from the file When executed, a select command panel retrieves the file’s
records from the database and sets up the list. When executed, a fdisp (File Display) command panel
displays summary information from records in the list.
l Current record A file variable can only contain one record from a file at a time. You can move to the
next record in the list of records by using the next command panel (Read Next Record). You can
move to the previous record in the list by using the previous command panel (Read Previous Record).
The select command panel always sets the current record to the first record that satisfies the
selection query. The fdisp (File Display) command panel sets the current record to the record
selected by the cursor when the user presses Enter.
l Descriptor The descriptor enables fields to be extracted by name. Each record is a structure and has
the structure delimiter {[ ]}. The field names in the structure are listed in the database dictionary.
For example:
l lastname is a field name listed in the database dictionary for the file that $file has been bound to
using the rinit command panel.
l lastname in $file is a valid expression whose value is the lastname field in the current record in $file,
or the nth field, based on the index of the lastname field in the descriptor.
Note: Service Manager is case sensitive. The case for field names, file names, and other elements
must match. For example, STATUS.CUST is not the same as status.cust.
array is synonymous with the terms list, vector, and sequence. Elements in arrays can be of any data
types (including arrays or structures). A fully qualified array name (array field in $file) can be used in
place of an array variable. The number of items in an array can vary and does not have to be allocated in
advance. Arrays are delimited by curly braces ({ }). The following table shows some examples.
Numeric {1,2,3}
Character {"a","b","c","f","e","h"}
Nested {{1,2},{3,4}}
Structures {{[1,"a"]},{[2,"b"]}}
{{[1,"a",true]},{[2,"b",false]},{[3,"c",unknown]}}
Empty {}
You can use either of the following equivalent syntaxes to access an element in an array:
l $array[element_number]
l element_number in $array
For example, to extract the value of the first customer number (2753) in the array $customer with value
{2753, 2842, 2963}, use any of the following equivalent syntaxes:
l 1 in $customer
l $customer[1]
If the accessed array element does not exist, the element is created and set to NULL. This effectively
extends the array. To insert a value into an array use the insert RAD function. To delete an element
from an array, use the delete RAD function.
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.
index (element) number. Structures are delimited with both curly braces and square brackets ({[ ]}).
Note the following examples:
l {[1,"a",true]}
l {[true,‘10/16/90 00:00’,false]}
l {[1,1,"b",0]}
You can use either of the following syntaxes to extract an element from a structure:
l $structure[index of field]
For example, to extract the value of the part number (672) in the part.no field within the structure
$order.line1 with the value of {[672,10,"ball.bearings"]} with the field names part.no, quantity and
description, use either of the following syntaxes:
l $order.line1[1]
l 1 in $order.line1
In addition, elements of structures may be extracted using their numeric order in the structure . For
example, the 1 in $order.line1 is the same as part.no in $order.line1.
Field names are contained in the database dictionary and can only be used when associated with a file
variable.
Assuming that the table contains a structure called part and within the structure and there is field
called part.no, this command works because it is associated with a file variable.
$x=part,part.no in $file
These commands do not work because the second command is not associated with a file variable.
$y=part in $file
$x=part.no in $y
l arithmetic operators
l logical operators
l relational operators
l special operators
l string operators
Charact
Type Name er Description
49 + 51 = 100
Example:
40 - 20 = 20
Example:
5 * 5 = 25
300 / 10 = 30
Example:
2 **5 = 32
Arithmet Modulus mod or The modulus is the remainder of a division operation. You may
ic % specifically want the remainder for a division operation, or you
may want to generate a circular number sequence within a
given range.
Example:
5 mod 2 = 1 or 5 % 2 = 1
String Concatenate + Indicates that two strings or two arrays are to be combined
(concatenated) into a single string.
Example:
Logical not ! Inverts the Boolean value of the Boolean expression. If the
expression is true, the system returns FALSE. If the expression
is false, the system returns TRUE.
Example:
Logical and AND and 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:
Example:
Relation Less Than < Indicates that the value of one item is less than the value of
al another item.
Example:
Relation Less Than or <= or =< Indicates that the value of one item is less than or equal to the
al Equal To value of another item.
Example:
Relation Equal To = Indicates that the value of one item is equal to the value of
al another item.
Example:
1 = 1 is TRUE
Relation Greater than > Indicates that the value of one item is greater than the value
al of another item.
Example:
Relation Greater Than >= or => Indicates that the value of one item is greater than or equal to
al or Equal To the value of another item.
Example:
Relation Not Equal To (¬ =) or Indicates that the value of one item is not equal to the value of
al (~=) or another item.
(<>) or Example:
(><) 1 ~=2 is TRUE (UNIX only)
Relation Starts With # Indicates that the value of the first string starts with the value
al (Truncated of the second string. The order of the operands affects this
Equals) operation.
Example:
"abc"#"ab" is TRUE
Relation Does Not ¬# or ~# Indicates that the value of the first string does not start with
al Start With the value of the second string. The order of the operands
(Truncated affects this operation.
Not Equal To)
Example:
Special Statement ; This operator separates two or more statements on the same
Separation line.
Example:
$A=$B+$C;$B=$C+$D
Example:
3*($x + $y)
IF ($x=1) THEN ($y="z") ELSE ($y=3)
IF ($x=1) THEN ($x=2;$z=1) ELSE ($y=3)
Arithmetic operators
An arithmetic operator indicates actions to be performed under the terms of an arithmetic expression.
Arithmetic operators have the following precedence: exponentiation, followed by multiplication, division
and modulus (all equal); then addition and subtraction (both equal). Operators with higher precedence
are evaluated first. When the operators have equal precedence, they execute from left to right.
Logical operators
A logical operator evaluates one or two Boolean expressions. It determines whether the expression is
true, false, or unknown.
l not
l and
l or
The unknown truth value is treated according to the Substitution Principle, which dictates:
l If UNKNOWN occurs as a logical operand, then the result of the operation is TRUE if substituting TRUE
or FALSE for UNKNOWN always yields TRUE.
l The result is FALSE if substituting TRUE or FALSE for UNKNOWN always yields FALSE.
l The result is UNKNOWN if substituting TRUE or FALSE for UNKNOWN sometimes yields TRUE and
sometimes yields FALSE.
Relational operators
A relational operator makes a comparison, then generates logical results on whether the comparison is
true or false. An operand can be checked for null using the special value NULL. $x=NULL is true if $x is
null. Relational operators treat null operands according to the NULL substitution principle:
l If the relation is true regardless of the value of the null operand, the result is true.
l $X * 25
l $Y > 32
Month
Explanation Accesses the number of months from the beginning of the time base in a date. Use it
to increment a date by a period of months.
Factors The month pseudo field is useful for scheduling monthly reports, since it calculates the
number of days to add to each month.
Name
Reserved words
Reserved words have special meaning in HP Service Manager. This meaning is defined in RAD. They can
only be used for that purpose. Do not use them for any other purpose such as field names. Here is a
alphabetical list of reserved words:
l AND
l BEGIN
l DO
l ELSE
l END
l FALSE
l FOR
l IF
l IN
l ISIN
l NOT
l NULL
l OR
l STEP
l WHILE
l THEN
l TRUE
l UNKNOWN
Literals
A literal is an explicit value. It is expressed as itself rather than as a variable's value or as the result of
an expression. Some simple examples are “23”, “2.5”, and “John.” You can use a literal wherever you can
use a variable, with one exception. 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. It is a named entity that refers to data
to which you can assign values. 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. HP Service Manager contains three types
of variables:
l Local
l Global
l Thread
Local variables begin with $L. and persist only within the currently executing RAD application. The
server automatically cleans up local variables when it exits a RAD application.
Global variables begin with $G. or $lo. and persist throughout a user session ($lo. is an abbreviation
for logged on. These variables are set when the operator logs on). The server automatically cleans up
global variables when a user logs off the system.
Thread variables do not have a consistent naming scheme other than beginning with a dollar sign ($).
Thread variables are only valid for the current RAD thread. If the RAD thread terminates, then the
server automatically cleans up all thread variables.
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, but may not include blanks.
l Data assigned to a variable has a data type. This data type becomes the variable's data type.
l Any variable can be set to a null value by assigning the value NULL to it. For example,
$variable=NULL.
l Global variables are treated as global among all applications executed within the process or task
with two exceptions:
n When the variable is designated local (or something other than global) by an initial identifier. For
example, when the variable is created within a function.
Global variables
The following global variables are available when defining registration events.
$axces.debug If true, the evlist array in the eventin record is not Use this
removed before attempting to update the record. If feature
the size of the record exceeds 32KB, Event Services with
generates an error, the eventin record is not discretion.
updated, and the event reprocesses because the
evtime field is not removed.
Variable Definition
$G.problem.inboxes List of Incident Management views available to all the users as well as
the views available to the logged on operator.
$G.prompt.for.save Global flag (Boolean) that determines whether or not to prompt you to
save when you press OK or Cancel after you update a record.
$G.incident.inboxes List of Service Desk views available to all the users as well as the views
available to the logged on operator.
$L.new The current file being updated when evaluating macro conditions.
$lo.appl.name The name of the application responsible for managing the user’s menu
(menu.manager)
$lo.date.order The number representing date order (mdy, dmy, ymd) in the operator
record.
$lo.msglog.lvl 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. Message levels affect on-screen messages only.
$lo.uallow.syslog Determines whether syslog table is updated when processes start and
end in the system.
$lo.user.name operator()
Variable pools
Variable pools are functional groupings of variables within HP Service Manager. There are currently four
variable pools:
l Global
A global variable is visible to the entire system. It begins with $G. or $lo..
l Local
A local variable is only visible to the RAD application in which it was defined. It begins with $L..
l Parameter
A parameter variable is defined on a parameter command panel. It may contain a value passed in
from another application. By convention, parameter variables are written in uppercase letters, such
as $PHASE or $GROUP.LIST. Parameter variables are invisible to the debugger.
l Thread
A thread variable is only visible to the thread in which it was defined. The same variable in different
threads has different values, even when the threads are spawned by the same parent.
Variable
pool Variable Comments
Global $G.
Global $lo.
Global $MARQUEE.
Global $SYSPUB.
Local $L. There is only one local variable. It can contain many pieces of data,
similar to the way a structure contains many pieces of information. For
example, $L.env and $L.file are two pieces of data that $L. can
contain.
Parameter $PHASE These are just a few examples, there are many parameter variables.
$GROUP.LIST
Thread $file These are just a few examples, there are many thread variables.
$array
$post
Statements
Statements are the smallest executable entities within HP Service Manager. A statement is governed by
the following rules.
l The following BASIC language statements perform processing and looping: IF, WHILE and FOR. They
can be nested. For example, for...to...if...then...else...if...then.
l The following assignment statements are used: assign, increment, and decrement.
l RAD functions can be used in statements to further define selection criteria and/or execute
commands, initialize values, and perform calculations. Service Manager syntax rules must be
followed. The result of a RAD function can be assigned to a variable using the assign (=) assignment
statement. For example, $string.length=lng($string).
The following table lists all of the statements available in Service Manager.
Charac
Type Name ter Description and Examples
Assignment Assign = Assigns the value of the right hand operand to the left hand
operand.
Example:
$x=1 assigns 1 to $x
Assignment Increm += Increment the left hand operand by the right hand operand.
ent
Example:
Assignment Decrem -= Decrement the left hand operand by the right hand operand.
ent
Example:
Processing and l FOR Allows you to perform a loop. You can set a variable, perform
ooping a statement, and increment the variable until the variable is
greater than a maximum value. Format this statement as
follows:
for $I = 1 to 10 do ($J=$I*$I+$J)
Example:
Example:
if (nullsub($location,"Chicago")="Seattle") then
($x=$x+1) else ($x=$x - 1)
Example:
Assignment statements
An assignment statement assigns a value to a variable. The order for the assignment statements when
read left to right is the destination variable first, then the assignment operator, then the expression. It
usually consists of three elements:
l An expression to be assigned.
l A destination variable.
On execution, HP Service Manager evaluates the expression and stores the resulting value in the
variable.
about bulletin.key Displays the system bulletin and any active “hot”
incidents.
cm3ropen cmc.open.from.menu Initiates the script for opening a new change request
record.
cm3topen cmt.open.from.menu Initiates the script for opening a new change task.
cmdlist report.exerciser Executes the Menu Command List report via Report
Exerciser.
configure sla sla.edit.config Displays the Service Level Agreement Control form.
delmail database Displays the form for sending internal Service Manager
broadcast mail.
doc menu.manager Displays the menu with options for maintaining the
document engine.
edit gkn database Displays the form for editing core knowledge.
gen core ke.gencore.verify Displays the prompt for generating the core Knowledge
Base.
inact kill.inactive.setup Displays the Kill Inactive Users Setup Parameters form.
irq ir.query.window Displays the form for issuing an IR Query File form.
linklist report.exerciser Executes the Link File Listing report via Report
Exerciser.
load transfer apm.upgrade.load.transfer Initiates the Service Manager Upgrade Utility Load
Transfer form.
model database Displays the Configuration Item (CI) Model search form.
modelicm database Displays the Configuration Item (CI) Model search form.
new incident apm.first Displays a blank incident form for record entry.
ocmbldlvl ocm.co.bld.lvls Displays the prompt for updating all of the level
numbers for all components in the model file.
ocmco database Displays the Configuration Item (CI) Model search form.
ocmdeliv report.exerciser Executes the Delivery Forecast for Next 7 Days report
via Report Exerciser.
ocmdreqj report.exerciser Executes the Daily Quote Log report via Report
Exerciser.
ocmdrj report.exerciser Executes the Daily Receipt Journal report via Report
Exerciser.
ocml ocml.access Displays the search form for Request Management line
items
ocmpo report.exerciser Executes the Print Purchase Orders report via Report
Exerciser.
password password.change Displays the prompt for changing the login password.
rmail read mail Displays the prompt for selecting which type of internal
Service Manager mail to read.
scr report.exerciser Executes the "shift change report" report via Report
Exerciser.
search cal cc.search.incidents Displays the search form for Service Desk interactions.
search calls cc.search.incidents Displays the search form for Service Desk interactions.
search sla sla.search.objects Displays the search form for Service Level Agreements.
shutdown system.shutdown Initiates the process for shutting down the Service
Manager server.
userlevel us.userlevel Displays the current user access level and the options
for changing this access.
userstats report.userstats Displays the prompt for executing the Usage Statistics
report.
usrcmr cm3r.main Initiates the script for opening a new change request
record.
l Display Options
l Format Control
l Scripts
l Processes
l Triggers
When you call a RAD application, you may need to pass the required parameters. These parameters
consist of a parameter name and a value.
Note: Service Manager does not currently support calls from JavaScript on any RAD application that
uses the rio/fdisp panels. Avoid calls from JavaScript on RAD applications that use the rio or fdisp
panels. If you cannot avoid doing so, always set the RunInNewThread parameter to true. This does
not work for all cases.
1. Locate the RAD you want to use. See "Locate a RAD function" on the next page.
2. Click View when you have the RAD application panel displayed. This displays a list of parameter to
pass.
3. Position the cursor on each parameter and then click Help to view the name of the field used as
the parameter.
Note: To display the field help, make sure either of the following conditions is fulfilled:
l In the Windows client, click Preferences > HP Service Manager > Appearance and then select
the Show context-sensitive help debug information option.
l In the Web client, viewcontexthelp=true is appended to the URL before you log in.
4. Click More or the More Actions icon and then select Expert Search. A query window is displayed.
Example:
index("jscall", str(contents(currec
())))>0
index("rtecall(\"rinit\"", str
(contents(currec())))>0
Use this syntax to search for all instances of all index("rtecall(\"<first letter>",
rtecall functions beginning with a particular
str(contents(currec())))>0
letter (for example, the letter r). For this query
to run properly, a backslash must precede the Example:
first set of double quotation marks. The closed
parenthesis is not necessary in this syntax. index("rtecall(\"s", str(contents
(currec())))>0
6. Click Search. A record list of RAD panels matching the search criteria is displayed.
RAD Debugger
The RAD Debugger enables you to view and isolate RAD processes for the purpose of troubleshooting.
Information about the RAD flow opens in a separate window containing a scrollable text field. The RAD
Debugger uses its own command line language to trace, display values, and set break points.
1. Click Window > Show View > Other > HP Service Manager Administrator > RAD Debugger.
3. Press Enter.
Command Description
d (display) Displays the contents of a variable. A common use of this command is to display the
name of the Display application Screen ID attached to the current form.
d $L.screen
t (trace) Turns tracing on or off. Tracing allows you to see every panel that the RAD flow
encounters. Use the command by itself to display the status of the trace function.
t on
t off
t
ta Turns panel tracing on or off for a specific RAD application. To turn application tracing
on, include the name of a RAD application. To turn application tracing off, repeat the
same command combination a second time. You may have multiple traces engaged at
one time. Use the command by itself to display a list of the RAD applications being
traced.
ta script.execute
ta
tar Removes all RAD specific panel traces. If you are tracing multiple applications, you can
save time by using tar rather than using ta to turn off each trace individually.
b Sets a panel breakpoint. When the RAD flow encounters a panel with this label, it halts
(breakpoint) before executing the named panel and gives you an opportunity to perform debugging
procedures such as displaying variables or executing statements. Repeat the
command combination a second time to turn off the breakpoint. Execute the
command by itself to display a list of all current breakpoints.
b init.operator
b
ba Sets a breakpoint on a specific RAD application. A breakpoint is applied each time the
RAD flow enters the named application, either when it runs for the first time or when
the flow returns to it from a subroutine.
ba menu.manager
bt Sets a breakpoint on a specific type of RAD panel. When the RAD flow encounters a
RAD command panel with this name, the application stops running and returns you to
the RAD Debugger. Enter the command combined with the name of a RAD panel to set
the breakpoint. Re-enter the same command combination to turn off the breakpoint.
bt rinit
c (continue) Resumes the execution of the RAD flow after a breakpoint occurs.
gl (globals) Displays all the global variables: those beginning with $G., $lo., $CHART., $SYSPUB.,
$MARQUEE.
v Displays all the thread variables: those not beginning with a special code.
(variables)
l (locals) Displays all the local RAD variables: those beginning with $L.
re Displays only the variables which are table relations (file handles initialized by the rinit
(relations) command panel).
m (memory) Displays all the variables in memory. This is equivalent to issuing the globals (g),
variables (v), and locals (l) commands.
x Execute a statement.
For detailed information about the syntax of Mozilla SpiderMonkey JavaScript, refer to:
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide
http://www.mozilla.org/js/spidermonkey/
Language overview
JavaScript is a scripting language which is different from programming languages like Java™, C++, or
Visual Basic®. It is a smaller, dynamically typed, scripting language that offers programming tools with
easy syntax and built-in functionality.
Unlike programming languages, scripting languages do not use compilers to create executable program
code. Because JavaScript is an interpreted language, each time the script is executed, it is loaded into
an interpreter that runs the code. The Compile button in the Script Library does not create an
executable load module; it runs a syntax check to verify that the script is executable.
JavaScript can be either client-side, server-side, or core language. Core JavaScript is the base JavaScript
language with client-side and server-side JavaScript as extensions. Server-side JavaScript is used for
accessing and manipulating data and is the only one available within HP Service Manager.
Learning JavaScript
HP does not endorse these references but provides them as a courtesy to our customers and partners.
These are helpful resources that contain information about JavaScript.
l JavaScript: The Definitive Guide, 5th Edition by David Flanagan (ISBN: 0596101996).
For best results, fully understand the programming language prior to attempting to use it with HP
Service Manager.
Note: There is a difference between server-side and client-side JavaScript. Service Manager only
supports server-side JavaScript. Therefore, any JavaScript that addresses output is not available in
the Service Manager environment.
l JavaScript is case-sensitive.
l Variables:
n Must be defined before being used. The variable name can contain A – Z, a – z, underscore or
digits and must start with a letter or an underscore (“_”).
n Assume the type of the data that is put into the variable. The data type does not have to be
explicitly defined
n Are global variables when defined outside of a function, and are available anywhere in the
current script context. Variables created within a function are local variables, and can be used
only within that function.
l Strings have to be enclosed in quotation marks, either a single or double. For example: print
(”Hello ” + ‘world ‘+ Country.name) produces the following: Hello world US.
l Special characters that are displayed literally must be preceded by a backslash character (\). Quotes
within a string can be entered preceded by a backslash as well. See the Core Language Features -
Literals - "String literals" section for more information in
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide.
l To increment a variable, such as a = a + 1, you can use a++. You can decrement a variable in the
same way, as in a--.
l To enter comments in the script, use "//" to start a single line comment or the combination of "/*"
and "*/" to enclose a multi-line comment.
l Values that are not defined as a data type (string, number, Boolean) may be defined as an object,
such as Date, Array, Boolean, String, and Number. As an example you could define: var
ArrayList=new Array(”test”, ” this”, ” list”);.
l Dots in HP Service Manager field names must be replaced by an underscore (_) in JavaScript. For
example contact.name becomes contact_name.
l Service Manager field names that are reserved words in JavaScript have to be preceded by an
underscore, such as “_class” for the “class” field.
<Statements;>
<function calls;>
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide
The list of operators includes assignment operators, comparison operators, arithmetic operators,
bitwise operators, logical operators, string operators, and special operators.
may contain a set of properties that more closely define the object. The syntax you use to call methods
and properties is: Object.method or Object.property.
For more information about JavaScript objects and properties refer to the Details of the Object Model
section in :
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide
Each of these is described in detail in the Working With Objects – Predefined Core Objects section of:
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide
Conditional statements
The following example returns true if the date entered is within the number of days in a month (here, 30
days); otherwise, it returns false.
Note: Note the use of the conditional statement to shorten the "if" expressions. The var return
= (parm.Date.getDate <= 30) ? true : false; statement works in the same way as its
much longer equivalent:
var result=false;
if (parm.getDate()<= 30)
{
result = true;
}
else
{
result=false;
}
For detailed information about the for and while loop statements, refer to the Statements – Loop
Statements section in:
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide
The following example shows how to check how many times a given number can be divided by 2, first
using a for loop, and then using a while loop:
function DivisableByTwoFOR(ParmNumber)
{
for (var i=0; ParmNumber > 1; i++)
{
ParmNumber = ParmNumber / 2;
}
return i;
}
function DivisableByTwoWHILE(ParmNumber)
{
var i = 0;
while( ParmNumber > 1 )
{
ParmNumber = ParmNumber / 2;
i++;
}
return i;
}
Note: A Do..While loop is available for those instances when you want to execute a statement (or
block of statements) at least once. In a Do..While loop, the exit condition is checked after the
statements are executed.
Caution: The for…in loop over an array may return unexpected results. For details, see "Avoiding
the use of the for…in loop over an array" on page 61.
Note: Both these statements violate the rules of structured programming but are nonetheless
widely used in special cases.
function break4error(parmArray, x)
{
var i = 0;
var n = 0;
while (i < 10)
{
if (isNaN(parmArray[x]))
{
print(parmArray[i].toString + “ is not numeric. Please repair
and run again”);
break;
}
n = n + parmArray[i];
i++;
}
return n;
}
Modifying the above example, the continue statement would work as follows:
function break4error(parmArray, x)
{
var i = 0;
var n = 0;
while (i < 10)
{
if (isNaN(parmArray[x]))
{
print(parmArray[i].toString + “ is not numeric. Continuing with
next number”);
i++;
continue;
}
n = n + parmArray[i];
i++;
}
return n;
}
function SetFullName(FirstName,LastName)
{
if (FirstName != null || LastName != null)
{
FullName=FirstName + “ “ + LastName
return FullName
}
else
{
throw "InvalidName"
}
}
try
{
// statements to try
var MyName=SetFullName(First, Last) // function could throw exception
}
catch (e)
{
MyName="unknown"
logMyErrors(e) // pass exception object to error handler
}
For detailed information about exception handling, refer to the Statements – Exception Handling
Statements section in:
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide
Service Manager currently uses a JavaScript Engine that complies with JavaScript 1.5, in which some
Array.prototype functions are implemented as built-in functions. When enhancing an array object
with a custom method, the for...in loop iterates on all items in the array including the custom
method. Similar issue also occurs to customized Array.prototype functions, as demonstrated in the
following example code and its output. This behavior might lead to errors that are difficult to debug.
Array.prototype._prototypeFunction = function() {
// prototype function will be iterated as non built-in property
print('prototype element');
}
print(‘built-in property: ‘ + array.length);
// length is built-in property of array object, it will not be iterated within
for…in statement
for(var item in [1]) {
print(‘ non built-in properties of Array type:’ + item);
//iterate the non built-in properties
}
Output:
In this situation, you can use a guarding if statement to help debug the code. For example:
or
if (typeof(<array>[<item index>]!="function")
The for…in loop iterates objects in an order according to the ASCII values of the property names. Do not
use the for…in loop to iterate over an array when the index order is important. See the following
example code and its output.
Output:
For more information about using the for...in statement, refer to https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Statements/for...in.
If a variable is declared inside a loop, JavaScript will allocate fresh memory for it in each iteration, even
if older allocations will still consume memory. While this might be acceptable for variables of scalar data
types, it may allocate a lot of memory for SCFile variables, or huge arrays or objects.
Unrecommended implementation
The following implementation, in which a variable is declared inside a loop, is not recommended.
for(i=0;i<arr.length;i++)
file.doSelect('name="'+arr[i]+'"');
Recommended implementation
for(i=0;i<arr.length;i++)
file.doSelect('name="'+arr[i]+'"');
Counting records
Counting the record set returned by a query is a frequent task in tailoring. Instead of fetching each
record in a loop, you can use the HP Service Manager rtecall("count") more efficiently.
var rc = getLastRC();
if (RC_SUCCESS == rc)
return nCount;
else
return -1;
function countFile(file)
var returnCode = 1;
return iTotal.getText();
Unrecommended implementation
file.doSelect('true');
file.getLast();
Alternatively, you can set the result order by the setOrderBy() method at the time of the select. You
can change the sort order that the record you are looking for is no more the last in the list, but the first.
Recommended implementation
file.setOrderBy(["number"],[SCFILE_DSC]);
file.doSelect('true');
In JavaScript implementations, you can use read-only file variables and restrict them to a set of fields
only. Using this option will significantly reduce memory consumption, as well as select against tables not
containing any of these fields.
Recommended implementation
file.setFields( fields );
var rc = file.doSelect(query);
rc = file.getNext();
When using the setFields() function on a file variable that is not read-only, the query is executed
against all fields and this message is written to the log file:
while ( rc = RC_SUCCESS)
rc = file.getNext();
A good practice to avoid this issue proactively, is to position the unchangeable value at the left side.
Recommended implementation
rc = file.getNext();
While Service Manager allows array[<index>] access to system language arrays from JavaScript, it
does not allow to access sub items in an array of array like this: array[<index1>][<index2>].
However, it is possible to access the sub items in an array of array using this syntax: array
["<index1>.<index2>"] instead.
Example
array1.setType(8);
array1.push("1_1");
array1.push("1_2");
array1.push("1_3");
array2.setType(8);
array2.push("2_1");
array2.push("2_2");
array2.push("2_3");
nestedArray.setType(8);
nestedArray.push(array1);
nestedArray.push(array2);
l Function calls in JavaScript use call-by-reference. That is, when calling a function with a variable as
parameter, the value of the variable is NOT copied, but only referenced.
l Calling doAction() function from JavaScript will call the Document Engine, and by this MAY CHANGE
non-local variables such as $file. That is, when calling a JavaScript function from Format Control,
and calling doAction() inside this function might corrupt the $file variable when control is returned
to Format Control.
function test()
var rc = file.doSelect('number="IM10001"');
if (rc == RC_SUCCESS)
file.job_name="test";
file.doAction("save");
else
print("1. Filename:"+system.functions.filename(vars.$file));
system.library.testFC.test();
print("2. Filename:"+system.functions.filename(vars.$file));
1. In the System Navigator, navigate to Configuration Management > Resources > Search CIs.
2. Filename:probsummary
1. Filename:device
Recommended implementation
Back up the $file variable before the function call, and restore afterwards. Change the Format Control
"device" implementation in the example above like this:
print("1. Filename:"+system.functions.filename(vars.$file));
var rc = system.functions.fduplicate(backup,vars.$file);
system.library.testFC.test();
vars.$file=backup;
print("2. Filename:"+system.functions.filename(vars.$file));
Note: HP advises that you store JavaScript in the ScriptLibrary and refer to it from other places.
l Cascade updates
l Display Screens
l Display Options
l Format Control
l Links
l ScriptLibrary
l Scripts
l Triggers
l Wizards
Some of these stored JavaScript programs can be used to interface with third party Web Services
providers, such as real-time currency conversions. All of these JavaScripts are identified as SOAP
packages within the ScriptLibrary. Integrations are typically performed through JavaScript stored in the
Script Library as well.
Note: Do not use Administrative Mode when entering the ScriptLibrary because functions such as
compile and execute are not available in that mode.
You can access any script or function in the ScriptLibrary from any of the locations in HP Service
Manager that support JavaScript. To call one of these functions, use one of the following statements:
system.library.<scriptname>.<functionname>( parameters )
or
library.<scriptname>.<functionname>( parameters )
l The size value is controlled by the recordsizelimit parameter in the sm.ini file. This is general record
size in database. The defaulting is 256K, but changing this value will affect all records in the
database.
l It is a best practice to set the recordsizelimit parameter to its default value of 256K since SOAP
scripts generated by HP‘s WSDL2JS utility can exceed 64K. Setting recordsizelimit to a smaller value
can result in failure when using the WSDL2JS utility with complex files.
l Red: Keywords.
l Teal: Comments.
First, you must establish a record in the ScriptLibrary that contains the function to be called. Within the
record you must know the name of the script as well as create a properly-constructed function.
function square(value)
{
var ret_val = value * value;
return ret_val;
}
function cube(value)
{
var ret_val = value * value * value;
return ret_val;
}
var x = 3;
var y = system.library.functionTest.square(x);
print(x, " squared = ", y);
x = -2;
y = system.library.functionTest.square(x);
print(x, " squared = ", y);
x = 2;
y = system.library.functionTest.cube(x);
print(x, " cubed = ", y);
/*
The function calls produce the following output:
3 squared = 9
-2 squared = 4
2 cubed = 8
*/
When working with the ScriptLibrary, you can compile the JavaScript code to check for syntax errors.
Executing the script will compile the code and then run it. Before executing the code, ensure that all
inputs are available.
You can access any script or function in the ScriptLibrary from any tool within HP Service Manager that
supports JavaScript, by using the following syntax:
system.library.<scriptname>.<functionname>( parameters )
Within a ScriptLibrary record, 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, you can use the jscall RAD function. The syntax for this
function is:
The following statements illustrate a JavaScript call to the system library and a call to the script library
by using jscall(), respectively:
system.library.tzfunctions.getTZforOperator(“falcon”);
jscall("tzfunctions.getTZforOperator", “falcon”);
To call a JavaScript function from the operating system's command prompt, you can use the us.js.call
RAD routine. The syntax for the command is:
sm us.js.call UpdateAllInteractions.updateInteractionFields
{\\\"abc\\\",\\\"def\\\"} NULL
process a special case, Unplanned Changes, in the out-of-box system. This code can serve as an
example for Administrators who need to customize the Close button label for other special cases.
l filename: name of the table we are currently on, cm3r for Change record, cm3t for Task
Example:
$L.close.label=jscall("changeManagement.getCloseLabel", filename($L.filed),
current.phase in $L.file, $L.filed)
The log4js script allows developers to set the following logging levels.
API Details
Constructor syntax:
You can also use the following method to create an instance of the logger:
myLogger.info("an info");
myLogger.warn("a warning");
myLogger.error("an error");
You can change the log level or turn off logging with:
myLogger.setLevel(lib.log4js.Log.WARN);
myLogger.setLevel(lib.log4js.Log.OFF);
You can also change the log level or turn off logging with this format:
myLogger.setLevel("WARN");
myLogger.setLevel("OFF");
The log4js script supports appending a prefix to each message. For example:
Type of Logger:
Logger Description
alertLogger Output information to Service Manager Message view or the server log file (default:
<SM server installation directory>\logs\sm.log), depending on whether a background or
foreground process calls the log4j functions.
API methods:
Method Description
Method Description
Performance impact
The log4js uses the standard Service Manager print method to write the Service Manager server log file
or the Messages view, which is useful for debugging your JavaScript, but keep in mind that when logging
is turned on there is a performance impact so log4js should be used carefully.
Format Control
The following example can be used to verify whether or not the operator who was just entered in the
assignee.name field in an incident record is currently logged in. Otherwise, validation will fail.
1. In the Calculations section of Format Control, enter a condition of true in the initial column. Then
add the following codes in the calculation column.
2. Click the JavaScript tab, enter true for Add and Update, and then enter the following statements.
3. In the Validation section, enter the following codes in the Add and Update column respectively.
assignee.name in $file~=$assignee.old;
$IsUser > 0
The new assignee is not logged in at this time. Please try another assignee.
This example uses the standard indexOf method for the String Object, and the toXMLString() function,
to search for the user who was entered as the new assignee in the XML object containing all logged-in
users.
Any RAD variable can be set and used by preceding it with system.vars. This lets variable values be
exchanged between JavaScript and RAD expressions.
Links
This example shows how to query a record from within HP Service Manager, and how to update fields in
that record. Additionally, it shows how to transfer an array from Service Manager to JavaScript. An array
from Service Manager cannot be directly copied into a JavaScript array, because the syntax of Service
Manager {“IM1001”, “IM1002”} does not work in JavaScript. Properties such as the length property
assume that the value is a function if it is enclosed in curly braces {}. To successfully convert a Service
Manager array into a JavaScript array, you can either use the SCFile.toArray method, or create a while
loop or a for loop to move through the elements and do an element-by-element transfer, as shown
above.
Note: In JavaScript, it is very important that you handle null values. Functions such as length may
not work on null values.
l Queries the configuration item that was previously selected from a fill.
l Increases a counter in that configuration item called num.issues.on.CI (this new field has to be added
in the device file).
l Adds the new record number to an array of issues in the device file called array.incidents.
l Sends an alert to the person who is opening the record if the item is currently down.
Trigger scripts
The triggers.g form contains a field for entering JavaScript (Script). HP recommends that the Script
field contain single statements that invoke functions in the ScriptLibrary. For example,
system.library.myTriggers.triggerXYZ( );.
Click the Compile icon in the ScriptLibrary to verify the syntax of your trigger script function. A trigger
script only needs to return a value if the trigger fails. The user can indicate the failure of a trigger by
returning the value of –1. Trigger scripts can access the value of the current record in memory using
the global object called system.record, and they can access the value of the same record on disk using
the global object called system.oldrecord. For example, system.library.myTriggers.triggerXYZ(
system.record, system.oldrecord );.
Triggers example
In this example, 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. It then adds an activity note that the message
has been sent.
RCtoString( findAssignment ) );
return null;
}
}
/* 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" );
var today=new Date();
newActivity.number= incNumber;
newActivity.datestamp= today;
newActivity.type= "Update";
newActivity.description[0]= "Notification email on the update has been
sent to all members of the assignment group.";
var result = newActivity.doAction("add");
if (result == RC_CANT_HAVE || result == 51 )
{
system.library.activityUpdates.scheduleActivityUpdate
( newActivity, newActivity.type, newActivity.description );
}
}
/* Selects the operators to send the message to */
Addressees = selectAddressees( NewRecord.assignment );
if (Addressees != null)
{
/* adds the message to the schedule file for sending */
insertSchedule( incNumber, incAssignee, Addressees);
/* adds an activity to inform the user of the email being sent*/
addActivity(incNumber);
}
The example also shows (among other things) how to call a Document Engine Action, how to call a
function from the Script Library, and how to insert a new record. In addition, it shows how to use several
functions within a single JavaScript and how to call them.
Note: Because the class field name in the schedule file is in conflict with the class keyword used in
JavaScript, it must be preceded by an underscore (_).
Refer to "List: RAD functions" on page 90 for a list of other RAD functions.
Syntax
system.functions.parse_evaluate( exp , 10 );
Note: The data is the character string to parse and the parse type is the numeric value normally
passed into the parse function.
Example
if (system.functions.parse_evaluate(expression in $l.file, 10 ))
userIsSysAdmin = true;
Note: The expression works when the statement being evaluated and parsed contains thread or
global variables. It does not work for local variables. However, you can transfer local variables to
thread variables before calling the parse_evaluate expressions.
Syntax
evaluate(parse(exp, 10 )
Note: The data is the character string to parse and the parse type is the numeric value normally
passed into the parse function.
Example
Note: The expression works when the statement being evaluated and parsed contains thread or
global variables. It does not work for local variables. However, you can transfer local variables to
thread variables before calling the parse and evaluate expressions.
Query operators
These operators are used solely for constructing query expressions using the Query object.
Note: The Query object has been deprecated, but older JavaScript code within the ScriptLibrary still
uses the object.
EQ Equals to
GT Greater than
GE Greater or equal to
LT Lower than
LE Lower or equal to
Example:
RC_ERROR Some other error occurred. Examine the contents of the Messages view or the
sm.log file for more information.
RC_CANT_HAVE The operation failed because the resource is unavailable because some other user
or process has the resource locked.
RC_DUPLICATE_ The insert operation failed because the file already contains a record with this
KEY unique key value.
RC_MODIFIED The update operation failed because the record was modified by another user or
process since you read it.
RC_DELETED The operation failed because the record was deleted by another user or process.
RC_NOT_ The request operation was not performed due to an authorization failure. Check
AUTHORIZED the permissions associated with the user who submitted the request.
RC_VALIDATION_ The operation failed because the data supplied in a field or the record did not pass
FAILED validity checks performed by the application.
RC_UNABLE_TO_ The operation failed. Check to make sure the file name is correct, that the file
WRITE_TO_FILE exists, and that it is not read-only.
RC_UNABLE_TO_ The operation failed. Check to make sure the file name is correct, that the file
CLOSE_FILE exists, and that it is not read-only.
RC_UNABLE_TO_ The operation failed. Check to make sure the file name is correct, that the file
DELETE_FILE exists, and that it is not read-only.
RC_INVALID_ The operation failed because the file name is not valid.
FILENAME
Example:
var rc = mySCFile.doInsert();
if ( rc == RC_SUCCESS )
{
print( "Insert succeeded" );
}
else
throw( "Error " + RCtoString(rc) + " occurred trying to insert a
record" );
l Format Control: The JavaScript is executed after calculations and before validations. JavaScript code
in Format Control is executed via the format.cjavascript RAD.
l Links: JavaScript in links is executed after the (initial) expressions, but before the fill or find is
executed. This is done in us.link on evaluate.expressions.
l The post JavaScript is executed after the fill or find was performed, immediately after the post
expressions. This happens in us.fill or us.find, respectively, on the eval.post.expressions panel.
l Triggers: The JavaScript in the triggers file is executed after the RAD application. This is controlled
by the server binaries and not by RAD code.
l Cascade updates: The JavaScript in cascade updates is executed from the RAD application
process.update.config.record. The evaluate expressions panel is executed before the
evaluate.javascript panel, so that expressions take precedence over JavaScript.
l Wizards: Wizards use JavaScript in three different areas: During File Selection, Actions, and Cancel
Expressions.
n File Selection: The Select $L.file by information is processed first, followed by the Initial
Expressions and then the JavaScript.
n Actions: In the Actions tab, the Expressions are run first, then the JavaScript, followed by the
information on the Format Control / Process Name tab.
n Cancel Expressions: First the Expressions Executed on Cancel are processed, followed by
Javascript Executed on Cancel.
l Interoperability (ioaction file) : The ioaction file executes only JavaScript and not RAD expressions.
The JavaScript code is executed in the ioevents.process.action application on the process.action
panel .
l Display screens: In the display application on the panel prep.screen, the JavaScript expressions are
executed after the RAD expressions.
l Display options: Display options have pre- and post-JavaScript and RAD expressions that are
executed in the following order:
a. Pre-RAD expression
b. Pre-JavaScript
c. RAD application
d. Post-RAD expression
e. Post-JavaScript
f. Display Action
l Processes: Process records have initial and final JavaScript and RAD expressions executed in the
following order:
b. Initial JavaScript
c. Pre-RAD expressions
d. RAD application(s)
e. Post-RAD expressions
g. Final JavaScript
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.
apm.get.assignments cc.user.to.group
RAD functions can be used in statements to further define selection criteria and/or execute commands,
initialize values, and perform calculations. Service Manager syntax rules must be followed. For example,
the result of a RAD function can be assigned to a variable using the assign (=) assignment statement:
$string.length=lng($string)
In most cases, there is a JavaScript function that can do the same operation as a RAD function. If you
prefer to work with JavaScript rather than RAD, see "Using RAD functions in JavaScript" on page 81 for
more information.
Function Description
add.graphnodes(xml) Returns XML to the Run-Time Environment (RTE) for the expand action on a
node in the graph diagram.
current.device Returns a string with the type of system the user is using to log in to Service
Manager, such as "SOAP-Windows Vista."
cursor.field.contents Returns a string containing the contents of the input field in which the cursor
was positioned when the last interrupt key was pressed.
cursor.field.name Returns a string containing the name of the field in which the cursor was
positioned when the last interrupt key was pressed.
cursor.field.readonly Returns true if the selected field is read-only. Returns false if the selected
field is not read only.
cursor.line Returns the number of the line, relative to the screen, in which the cursor
was positioned when the last interrupt key was pressed.
date Returns the date portion of a date/time variable and defaults time portion to
’00:00:00‘.
datecmp Translates the date/time fields to the correct SQL statement dialect.
day Returns the day of the month for a date regardless of the date format.
dayofweek Returns a number from 1 to 7 representing the day of the week for a specific
date.
dayofyear Returns the day of the year for a date regardless of the date format.
descriptor Returns the database dictionary descriptor record for a file variable.
filename Returns a string containing the name of the file for a specified file variable.
frestore Restores all fields in a file variable to their original database values.
genout Generates a formatted string based on a record and format name passed as
parameters.
get.base.form.name Returns the base name of a form, stripping off the form extension for GUI or
Web forms.
get.graph.id Returns the value of the graph ID for the expand action on a node in the
graph diagram.
get.graphnode.id Returns the value of the node ID for the expand action on a node in the graph
diagram.
get.graph.target Returns the target for an activated action on a node in the graph diagram.
get.timezoneoffset Returns the absolute time difference between GMT and the time zone of the
operator.
index Returns the element number of an array or the position in a string that
matches a specified string.
insert Returns a modified array with a specified number of new elements inserted
at a specified location.
iscurrent Determines if the record with which you are working is identical to the
version stored in the database.
lioption Indicates whether a given input value is a licensed option on the current
system.
messages Provides logging functions for use in the memory message log. The log is
implemented as a wrap-around cache of the x most recent messages (error,
informational, and action).
month Returns the month of year for a date regardless of the date format.
multiselect.selection Returns the contents of the fields associated with the multiselection.
("fieldcontents")
multiselect.selection Returns the field name of the column associated with the multiselection. The
("fieldname") associated column name is set using the Forms Designer property "Selection
Field."
multiselect.selection Returns true or false if the provided file variable has multiple records
("selected") selected.
null Returns true if the value of a variable is NULL. Returns false if the value of a
variable or field is not NULL.
operator Returns the string of the name of the currently logged on operator.
recordtostring Takes the value of a field from an array and appends the value to a string.
same Compares two compound or null values. Returns true if two values are
identical, otherwise returns false.
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.
shutdown Shuts down Service Manager from inside the system. This function does not
return any values.
simple file load loads an unload file containing only data records of one file into a target file.
stradj Makes a string a specific length by either clipping or adding trailing blanks.
strpadl Pads a string with leading blanks until the string is a certain size.
strpadr Pads a string with trailing blanks until the string is a certain size.
sysinfo.get Returns the Service Manager client network IP address as a character string.
(“ClientNetAddress”)
sysinfo.get Returns the name of the operating system that Service Manager is running
(“ClientOSName”) on.
sysinfo.get(“Display”) Returns “GUI” or “text”, depending on the type of client that is running.
sysinfo.get Returns the name of the environment in which the client is operating.
(“Environment”)
sysinfo.get Returns the server session language code value that is used for localized
(“languagecode”) forms and messages.
sysinfo.get Returns the total number of floating users logged on since the server
(“MaxFloatUsers”) started.
sysinfo.get Returns the maximum number of licenses used since the server started.
(“MaxLicenses”)
sysinfo.get(“Mode”) Returns a value that states the type of client being used.
sysinfo.get Returns the label name of the last RAD panel that was executed.
(“PrevLabel”)
sysinfo.get(“Quiesce”) Returns “true” if system is quiesced and “false” if system is not quiesced.
sysinfo.get(“RecList”) Returns “true” if record list is enabled and “false” if record list is disabled.
sysinfo.get Returns the Service Manager server port used by the connected client or the
(“ServerNetPort”) system name when called by a background process.
sysinfo.get Returns the total number of executing system and user tasks.
(“TotalProcs”)
updatestatus Returns the result of the last update operation on a Service Manager file.
year Returns the full year for a date regardless of the date format.
A RAD function that returns XML to the Run-Time Environment (RTE) for the expand action on a node in
the graph diagram.
Function
add.graphnodes()
Example
add.graphnodes(xml)
Function
cache.flush
Format
Parameters
nType is a number from 1 to 4 representing the type of flush operation. Flush types 1, 2, and 4 remove
the item from the global shared memory cache. Flush type 3 removes the item from the local format
cache.
l 2 flushes dbdicts
l 3 flushes formats
pItem is the name of the item to flush enclosed in quotation marks. Note that pItem is not used if flush
type is 3.
Factors
Example
cache.flush( 2, "probsummary" )
$L.type = 3
cache.flush( $L.type )
Function
cleanup
Format
cleanup(file variable)
Factors
This function does not return a value. It cleans up (empties) the variable or field specified by setting the
value to NULL.
You can use this function on any variable type (local, thread, or global), but it is generally used on local
and thread variables to clean up values before a user logs out.
This is the preferred way to clean up both variables and fields in records as opposed to $x=NULL or field
in $file=NULL.
Unless you run this function, variables remain in memory until their defining environment ends. For local
variables, this is the parent RAD program. For thread variables, this is the parent RAD thread. For global
variables, this is the user session.
Note: This RAD function is not available as the system.functions call JavaScript.
Example
cleanup($system)
Function
contents
Format
contents(file variable)
Factors
If you use the contents() function to compare two records, always use the denull function on both
records first to remove null values. If one record is displayed and the other is not, the arrays in one
record may contain extra null values.
Using the denull function on an empty array of structures converts the array of structures to a simple
array.
Note: Always test for null values first, as shown in the following example:
denull(contents($save.rec))=denull(contents($rec))
Example
contents($file.variable)
Function
copyright
Format
copyright()
Example
Function
currec
Format
currec()
Example
modtime(currec())>'1/1/05'
Function
current.device
Format
current.device()
Factors
Example
Function
current.format
Format
current.format()
Example
Function
cursor.field.contents
Format
cursor.field.contents()
Factors
Example
Function
cursor.field.name.set
Format
cursor.field.name.set($field.name, $row.number)
Factors
l 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 field on the next form displayed.
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
Function
cursor.field.readonly
Format
cursor.field.readonly()
Function
cursor.line
Format
cursor.line(n)
Factors
l $l=cursor.line() = the numeric value of the line where the cursor was positioned.
l $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.
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, 00:00:00. The
function uses the local time zone to determine the date.
l The argument can be any absolute date and time value, or an absolute time, including tod.
Example
$date.opened=date($date.time.variable)
Where $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'
.
Function
datecmp
Format
datecmp("DateTimeField1","LogicOperator","DateTimeField2","+/-", "TimeInterval")
Parameters
Example
Argument Description Value (s)
DateTimeField2 Another date time field in the same Service Manager table. open.time
l All arguments must be enclosed in a pair of double quotes; otherwise, the query parsing will fail.
l This function supports AND, OR, and NOT to concatenate multiple datecmp() calls in one query.
l You can combine the result of this function with other query conditions to construct a complete
query. For example, you can execute one of the following queries when performing an expert search
of incidents:
Note: The first two queries should return the same results, which are incidents whose closed
time is between 2 hours and 4 hours from their open time; the third query should return
incidents that were closed more than 31 days after their open time.
Example
Function
day
Format
day=day($date)
Factors
Although the set.timezone function affects the way a date is presented, the day function always
extracts the proper day value.
Example
$mday=day(‘2/15/08’)
Function
dayofweek
Format
day=dayofweek($date)
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
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.
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.
Function
dayofyear
Format
$yday=dayofyear($date)
Example
$yday=dayofyear('2/15/08')
Function
delete
Format
Where the array variable is the array, the element number is the index number of the first element to
delete, and [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}
Function
denull
Format
denull(array)
Factors
l If the array contains a NULL entry in the middle of the array, that entry is not removed.
l Using denull on an empty array of structures converts the array of structures to a simple array.
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}.
denull({1,,2,,})
Returns {1,,2}.
Function
descriptor
Format
descriptor($filename)
Parameters
The $filename variable is used for the table whose descriptor structure you are requesting.
Function
evaluate
Format
$e = evaluate($x)
Factors
l The evaluate function is also valuable when the statement to be evaluated is contained in a HP
Service Manager field that is not qualified once the application is compiled.
l The parse flag is used to parse data in a form, which in turn converts the data to an operator (data
type 10).
l Although an lvalue is always required, a value is not always assigned to the lvalue.
Example
$x=evaluate($x)
Function
evaluate.query()
Format
Function returns
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.
Parameters
Examples
This example returns TRUE only for contacts records that start with "S" and FALSE for every other
contacts record.
Function
exists
Format
Factors
l The $file variable must be of data type 6. Any other data type returns false.
l 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.
Function
fduplicate
Format
fduplicate($target, $source)
Factors
Example
$L.void=fduplicate($file0, $file)
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
Function
filequeryex
Format
filequeryex(file)
Parameters
file is an HP Service Manager file variable, which can be either $L.file in RAD or SCFile in JavaScript.
Factors
l No.0 is the query string, which supports both HP Service Manager queries and ADHOC SQL queries.
l No.1 is the sort-by fields, separated by a comma. Note that the group-by fields will be merged with a
higher priority.
l No.2 is the sort-by order: 0 is ascending, 1 is descending, and an empty value is NULL.
l No.4 is the group order: 0 is ascending, 1 is descending, and an empty value is NULL.
Note: To set the sort-by and group-by arrays, use "var sortOrder=[SCFILE_ASC];" instead of
"var sortOrder=new Array(SCFILE_ASC);".
Examples
var sql = 'select affected.item, number from probsummary where affected.item isin
(select logical.name from device where owner=\""Administration\"")';
var sortOrder=[SCFILE_ASC];
var rc = system.functions.setsort(file,fields,sortOrder);
var q = system.functions.filequeryex(file);
print("rc: " + success + ", q[0]: " + q[0] + ", q[1]:" + q[1] + ", q[2]:" + q[2]+",
q[3]:" + q[3] + ", q[4]:" + q[4]);
var sql='number#"IM1"';
var rc =f1.doSelect(sql);
var sortOrder=[SCFILE_ASC];
var rc = system.functions.setsort(f1,fields,sortOrder);
var q = system.functions.filequeryex(f1);
print("rc: " + success + ", q[0]: " + q[0] + ", q[1]:" + q[1] + ", q[2]:" + q[2]+",
q[3]:" + q[3] + ", q[4]:" + q[4]);
Function
frestore
Format
frestore($file)
The $file variable is the file for which you want to restore the fields to their original values.
Factors
Example
frestore($file)
If the $file variable is initialized and a record is selected, changes are made to the contents of the
$file variable in memory, but the updates are not yet written to the database. After execution, the
$file variable is restored to the original value, which is the state stored in the database.
Function
genout
Format
genout($file.variable, $format.name)
Parameters
Factors
l All normal format processing occurs, including input and output routines. Data can therefore be
automatically reformatted or manipulated as part of the function. For example, a date can be
converted from 02/28/05 00:00:00to February 28, 2005.
Examples
$output=genout($operator, “operator.view”)
“Printer:sysprint Email:[email protected]”}
Function
get.base.form.name
Format
$base.form.name=get.base.form.name($form.name)
Parameters
$form.name
Examples
In each of the following examples, the result is the same after execution: $base.form.name is
operator.
Example 1:
$form.name=“operator.g”
$base.form.name=get.base.form.name($form.name)
Example 2:
$form.name=“operator.w”
$base.form.name=get.base.form.name($form.name)
Example 3:
$form.name=“operator”
$base.form.name=get.base.form.name($form.name)
Example 4:
$form.name=“operator.a”
$base.form.name=get.base.form.name($form.name)
Function
get.dateformat
Format
$date.fmt=get.dateformat()
Factors
l 1 = mm/dd/yy
l 2 = dd/mm/yy
l 3 = yy/mm/dd
l 4 = mm/dd/yyyy
l 5 = dd/mm/yyyy
l 6 = yyyy/mm/dd
Example
$date.fmt=get.dateformat()
After execution for a typical user in the United States, the value of $date.fmt is one (1).
A RAD function that returns the activated action on a node in the graph diagram.
Function
get.graph.action()
Example
$L.graphaction = get.graph.action()
A RAD function that returns the value of the graph ID for the expand action on a node in the graph
diagram.
Function
get.graph.id()
Example
$L.graphid = get.graph.id()
A RAD function that returns the target for an activated action on a node in the graph diagram.
Function
get.graph.target()
Example
$L.graphtarget = get.graph.target()
A RAD function that returns the value of the node ID for the expand action on a node in the graph
diagram.
Function
get.graphnode.id()
Example
$L.graphnodeid = get.graphnode.id()
Function
get.lock.owner
Format
Example
Assume the user "falcon" is actively updating Incident IM1017. By viewing the Lock Resource Status
display, one can determine that the name of the associated resource is probsummary;IM1017. To verify
the owner from any other application:
$lock="probsummary;IM1017"
$owner=get.lock.owner($lock)
Note: This function is primarily intended for internal use as it requires specific knowledge of the
underlying resource names associated with a specific action.
Function
get.timezoneoffset
Format
$tzoffset=get.timezoneoffset()
Example
$tzoffset=get.timezoneoffset()
After execution for a Pacific Standard Time (PST) time zone user, the value of the $tzoffset variable is
-08:00:00.
Function
get.uid
Format
$uid=get.uid()
Example
$uid=get.uid()
Function
gui
Format
$bool=gui()
Example
$bool=gui()
After execution in GUI mode, the value of $bool is true. After execution in text mode, value of $bool is
false.
Function
index
Format
Parameters
The target value variable is the value you are searching for in the array or string.
The starting position # variable is the index in the array or position in the string where the search
will begin. The default value is 1).
Factors
l The index() function operates identically for arrays, regardless of the data type in the array.
l If the array is composed of structures or of arrays, the target variable must exactly match the
structure or array.
For example, the function does not allow selecting a field from a structure.
l You can use the index function to search for any value by converting both the value and the search
variable to the same type.
For example, if you want to search for the $problem.number variable on all forms, you could pass
the following query to the select panel:
index(“$problem.number”, str(field))
The index function searches for the $problem.number variable in the field field of the format
table.
l When you use the index() function in a query, HP Service Manager evaluates the function based on
database case sensitivity.
For example, if you use the Expert Search option on the Incident Management search screen, and
search for index(“Windows Server”, brief.description) > 0:
n On a case insensitive database, the query returns all records where the brief.description
field contains windows server or WINDOWS SERVER or Windows SERVER, and so on.
n On a case sensitive database, the query only returns records where the brief.description
field contains exactly Windows Server.
l When you use the index() function in a RAD or JavaScript expression and not within a query, HP
Service Manager evaluates it case sensitively (regardless of the database setting).
Example
index(1,{1,2,3}) returns 1
index(2,{1,2,3}) returns 2
index(1,{1,2,3},2) returns 0
index(2,{1,2,3},2) returns 2
Function
insert
Format
Parameters
l The $position parameter is the position of the first inserted element. If the value is zero (0),
the element is inserted at the end of the array. This is an optional parameter. The default value
is zero (0).
l The $number parameter is the number of elements to insert. This is an optional parameter. The
default value is one (1). If the value is zero (0), this function will return without changing the
array.
l The $value parameter is a value to insert into the new elements. This is an optional parameter.
The default value is NULL.
l The $denull parameter is a logical value that determines whether or not the array should be
denulled before inserting elements. This is an optional parameter. The default value is true.
Factors
If the source array has NULL elements at the end, this function automatically denulls the array before
inserting new elements in any position. To avoid this, set the value of the $denull parameter to false.
Examples
The following examples show a desired result and the syntax used to achieve that result.
Where:
Insert an element in the middle of an array. To insert an element in the middle of an array:
Where:
Where:
Where:
Where:
Where:
Function
iscurrent
Format
$Boolean=iscurrent($file.variable)
Factors
This function only determines if another user has changed the current record since you open it.
Examples
Example 1:
A value of true is returned. This is because the record user1 gets in step 1 is identical to the
version in the database.
Example 2:
2. User2 logins and opens record IM10005. (User2 gets the same version of record IM10005 as user1.)
3. User1 modifies IM10005 and saves it. (IM10005 in the database is changed.)
Function
isExpressionValid
Format
$e = isExpressionValid(expr_string, type)
Parameters
expr_string is a RAD expression, and type is a basic data type of HP Service Manager.
Factors
l It works the same way as the parse.evaluate() function, except that it does not send error
messages to the client when the input string is invalid.
Examples
Function
isfileexist
Format
isfileexist(“filepath”)
Parameters
Example
$L.filepath="c:\\note.txt"
L.ret=isfileexist($L.filepath)
if ($L.ret=false) then ($L.void=rtecall("msg", $L.code, "File doesn't exist"))
else ($L.void=rtecall("msg", $L.code, "File exists"))
Function
jscall
Format
Parameters
Data
Parameter type Required Description
arg1, arg2, – Varies The required The arguments passed to JavaScript. You can
, argN with each arguments pass an infinite number of arguments.
argument depend upon the Arguments are not enclosed in quotes or double
requirements of quotes and can be RAD expressions, as shown in
the script you the following examples:
call.
city in $L.OLD
Or:
level in $L.NEW=0
Function
lioption
Format
lioption(input value)
Parameters
Factors
The function returns a true value if the input value is part of the system license.
The function returns a false value if the input value is not part of the system license.
Examples
The following table describes a desired action and the syntax used to initiate the action.
Function
lng
Format
lng($variable)
Factors
Examples
lng({1,2,3}) returns 3.
lng({1,2,3,,,,}) returns 7.
lng(denull({1,2,3,,,,})) returns 3.
Function
locks
Format
locks()
Factors
l lock time
l process id
l terminal id
l operator name
l number
l exclusive
l locked
l breakable
Example
locks()
Function
logoff
Format
logoff()
Factors
Function
logon
Format
logon()
Factors
Function
mandant
Format
mandant(n,string)
Where n equals 0, 1, 2, or 3.
Parameters
l 2 links the current user to the set of records in the scsecuritygroup file that matches the array of
security IDs.
l 3 sets the security roles for the tables defined in the scFolderAccess file.
Example usage
In Service Manager the out-of-box system has three scsecurity group records: "Company A", "Company
B" and "Company C". To establish the mandanten security for the user, the RAD could call the following:
Security roles are implemented in the scFolderAccess table. The RAD calls the mandant function with 3
to set the security roles for the given tables. The following example sets the security role of ADMIN for
two tables, as defined in the scFolderAccess file.
Note: This fails if the string value does not match the values currently established.
Function
max
Format
Or:
max($variable)
Factors
l The max function returns the maximum value of either times or numbers.
l If you include an array in the list of elements, the system evaluates all of the elements in the array
as if they were individual values.
l An attempt to use an array of strings as a parameter results in a segmentation fault, which causes
the application to exit in error.
Example
max(1,{2,3,4},3) returns 4.
Function
messages
Format
messages($function_number, $function_parameter)
Parameters
5 0 Retrieve array of all log entries in most recently displayed order. The log is
not cleared.
Factors
The following table outlines the proper order for each action related to this function and the
corresponding function number.
Action Function
Note:
l A user task (the sm process) can have only one private message log at a time.
l You cannot directly access message logs that are using other tasks.
Examples
The following table describes a desired action and the syntax used to initiate the action.
Function
min
Format
Or:
min($variable)
Factors
l The min function returns the minimum value of either times or numbers.
l If you include an array in the list of elements, HP Service Manager evaluates all elements in the array
as individual values.
l An attempt to use an array of strings as a parameter results in a segmentation fault, which will
cause the application to exit in error.
Example
min(4,{1,2,3,},2) returns 1.
Function
modtime
Format
modtime($file)
Factors
l Use this function to determine if a record has been modified before or after a specified time.
l Use modtime(currec()) to return the last modified date and time for any record. You can also use
this variation in queries to retrieve all records modified after a specified point in time.
l The modtime function is not updated on clients when the records are updated on the server until
after the records are selected again.
Examples
modtime(currec)>tod( )- '08:00:00' selects all records in a file that were added or updated in the
last eight hours.
Function
month
Format
$ymonth=month($date)
Parameters
Example
$ymonth=month(`2/15/96')
To set the associated column name using the Selection Field property in Forms Designer, follow these
steps:
3. In the Form field, type the form name. For example, type probsummary.qbe.g and click Search.
The form opens.
6. In the Selection Field property, type the name of the column on the table (for example, type
number).
7. Click OK to see what the form will look like in the Windows client.
Function
multiselect.selection("fieldcontents")
Format
$info=multiselect.selection("fieldcontents")
Example
$x=multiselect.selection("fieldcontents")
After execution, the value of $x is set to the selected field contents. For example, {"IM10003",
"IM10006", "IM10007", "IM10008", "IM10010", "IM10012"}.
Note: Field contents are only returned if the associated column name is set using the Selection
Field property in Forms Designer.
To set the associated column name using the Selection Field property in Forms Designer, follow these
steps:
3. In the Form field, type the form name. For example, type probsummary.qbe.g and click Search.
The form opens.
6. In the Selection Field property, type the name of the column on the table (for example, type
number).
7. Click OK to see what the form will look like in the Windows client.
Function
multiselect.selection("fieldname")
Format
$info=multiselect.selection("fieldname")
Example
$x=multiselect.selection("fieldname")
After execution, the value of $x is set to the column name (for example,"number").
Note: Field contents are only returned if the associated column name is set using the Selection
Function
multiselect.selection("rows")
Format
$info=multiselect.selection("rows")
Example
$x=multiselect.selection("rows")
After execution, the value of $x is set to the selected rows. For example {2, 3, 7, 22, 23, 30}.
Function
multiselect.selection("selected",$file.variable)
Format
$info=multiselect.selection("selected",file.variable)
Example
$x=multiselect.selection("selected",$L.file)
Function
multiselect.selection("selections")
Format
$info=multiselect.selection("selections")
Example
$x=multiselect.selection("selections")
After execution, the value of $x is set to the number of selected rows. For example, 6.
Function
multiselect.selection("tablename")
Format
$info=multiselect.selection("tablename")
Example
$x=multiselect.selection("tablename")
After execution, the value of $x is set to the selected Table ID. For example, Table0.
Note: The null function is different that the reserved word, NULL.
Function
null
Format
null(value)
Factors
l An array or structure is null if it contains all null elements. This function applies itself recursively to
nested elements.
Examples
null(1) returns false.
null(NULL) returns true.
null({}) returns true.
null({1,}) returns false.
null({{},}) returns true.
Function
nullsub
Format
nullsub(value1,value2)
Examples
nullsub(1,2) returns 1.
nullsub(NULL,2) returns 2.
$a=NULL
$a=nullsub($a,"test") returns test.
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.
Examples
$a = operator()
operator() = $a
Function
option
Format
option()
Factors
l Use caution when option() is a criteria for a decision or process panel that can be accessed from
several paths. To avoid conflicts, set a variable to option() when the first panel is accessed.
l Clicking an item in the More menu returns the GUI option number associated with this option in the
displayoption table.
Example
option() returns 10.
Function
parse
Format
parse(string,type)
Factors
l When enabled on forms, the parse property automatically parses the data entered.
Examples
$x=parse("1+1",1)
Evaluate($x) returns 2.
$x=parse("$x=1",11)
Function
perf
Format
perf(n)
Where the value of n is the number that corresponds to the option you select.
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.
2 Add records and do not delete. Nothing is removed before new records are written to the
systemtotals and systemperform files. Maintenance of these files is typically the
responsibility of the RAD programmer.
3 Delete records in the systemtotals and systemperform files where capture=false and do not
write information to disk.
4 Delete all records in the systemtotals and systemperform files, regardless of capture
status.
Example
Function
printer
Format
printer()
Factors
This function is most often used to set the current printer. When an operator logs on, the login
application is executed, assigning printer() to be either the printer specified by the user at login, or the
default printer specified in the operator record for the user.
Example
$a = printer()
printer() = $a
Function
policyread
Format
Parameters
Parameter Description
$L.returnvalue The policy value returned after it is read from the database. It can be a string, a
boolean, or null.
$L.file The file handle of the table for which the data policy information is to be read from
the database. It can be a join table or a normal table.
Note: Other kinds of tables (adhoc sql, merge files, etc.) are not supported.
fieldname The name of the field in the specified table for which the data policy information is
to be read from the database.
This is the value in the Field Name field in the datadict record.
fieldsetting The field setting on the specified field for which the data policy information is to be
read from the database.
This one of the fields on Field Settings tab of the datadict record.
Factors
If the fieldsetting is not in the list of Field Settings in the datadict table, the server will throw an error
message. In any other case, this function returns a valid value or null.
Example 1
This example demonstrates how you could use a JavaScript to access the data policy on a simple file,
such as the operator table.
Example 2
This example demonstrates how you could use a JavaScript to access the data policy on a complex file,
such as a join of the incidents and contacts tables.
Function
processes
Format
processes(s)
Factors
l login time
l session id
l device name
l user name
l idle time
l process id
l thread id
l host name
l IP address
S Type of process
null All
ALL All
ACTIVE Active
Example
Function
prof
Format
prof(n)
Where:
The value of n is the value for the parameter corresponding to the option you want returned.
Parameters
Parameter Description
Example
Function
recordcopy
Format
Parameters
Parameter Description
$L.void= Syntax requirement only, does not affect the outcome of the function.
Factors
The recordcopy function does not check the data type. Ensure that you do not copy a number field to a
string, or a structure to a number.
Example
name in $source.file="falcon"
phone in $source.file="858-481-5000"
$source.fields={"name", "phone"}
$target.fields={"contact.name", "contact.phone"}
$L.void=recordcopy($source.file, $source.fields, $target.file, $target.fields)
Function
recordtostring
Format
recordtostring($string, $file, $arrayofnames, $sep)
Parameters
The following values are valid for the recordtostring function:
Parameter Description
Factors
Event Services uses the caret character (^) as a default separator. You can use the recordtostring
function to build an eventout string.
Example
Where:
Function
round
Format
round(number,n)
Parameters
The following parameters are valid for the round function:
Parameter Description
n 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’
Function
same
Format
same(value1,value2)
Factors
l Use this function to compare arrays and structures, nulls, or empty strings.
l When using the same function to compare arrays or structures, preface the variable names with
denull, as shown in the following example.
Examples
same(1,NULL) returns false.
same(NULL,NULL) returns true.
same({},{,}) returns true.
same({1},{1,}) returns true.
same("",NULL) returns false.
Function
scmsg
Format
Parameters
Data
Parameter type Description
$id Number The ID number of the message (message.id) from the scmessage table.
$arrayofvalues Array An array of substitution text for the %S variables in the message text
from the scmessage table.
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.
l You must create a separate record in the scmessage table for the message in each language you
want to display.
l 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.
Example
When the %S array values from the scmsg function in the example are applied, the message is
displayed as:
Function
set.timezone
Format
set.timezone(servertz)
Parameters
Function
setsort
Format
p
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}
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 is displayed.
This function only works with binary unload files. Text unload files are not supported.
Caution: 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
Function returns
true - if successful.
Parameters
Data
Parameter type Description
target file character Specifies the target file for this function, for example, signatures. As a
name safety precaution, this file name has to match the dbdict record internally
stored in the unload file, or the function returns an error.
drop if logical Controls the behavior of the function if the target file already exists. If set
already to FALSE, the function will fail and return an error if the target file already
exists 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.
Example
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).
Function
str
Format
Parameters
Any valid expression passed to the str function can be converted to a string.
Examples
str(1+1) returns 2.
Function
stradj
Format
$L.void=stradj($string, $size)
Parameters
$L.void= Not A syntax requirement only, which does not affect the outcome of the
applicable function.
Examples
$string="Hewlett-Packard"
$size=15
$L.void=stradj($string, $size)
$string="Hewlett-Packard"
$size=10
$L.void=stradj($string, $size)
Function
strchrcp
Format
Parameters
$L.void= Not applicable. A syntax requirement only, does not affect the outcome of the
function.
Factors
Example
$target="Hewlett-Packard"
$index=4
$source="falcon"
$copies=2
$L.void=strchrcp($target, $index, $source, $copies)
Function
strchrin
Format
Parameters
$L.void= Not applicable. A syntax requirement only, does not affect the outcome of the
function.
Example
$target="Hewlett-Packard"
$index=4
$source="falcon"
$copies=2
$L.void=strchrin($target, $index, $source, $copies)
Function
strclpl
Format
$L.void=strclpl($string, $number)
Parameters
$L.void= Not applicable. A syntax requirement only, does not affect the outcome of the
function.
Example
$string="Hewlett-Packard"
$number=6
$L.void=strclpl($string, $number)
Function
strclpr
Format
$L.void=strclpr($string, $number)
Parameters
$L.void= Not A syntax requirement only. It does not affect the outcome of the
applicable. function.
Example
$string="Hewlett-Packard"
$number=6
$L.void=strclpr($string, $number)
Function
strcpy
Format
Parameters
$L.void= Not applicable. A syntax requirement only, does not affect the outcome of the
function.
$tindex Number The position in $target to begin copying a substring from $source.
Example
$target="Hewlett-Packard"
$tindex=4
$source="falcon"
$sindex=2
$number=3
$L.void=strcpy($target, $tindex, $source, $sindex, $number)
Function
strdel
Format
Parameters
$L.void= Not A syntax requirement only, does not affect the outcome of the
applicable. function.
$index Number The location in $string from which characters are to be deleted.
Example
$string="Hewlett-Packard"
$index=6
$number=8
$L.void=strdel($string, $index, $number)
Function
strins
Format
Parameters
$L.void= Not applicable. A syntax requirement only, does not affect the outcome of the
function.
$tindex Number The position in $target to begin inserting a substring from $source.
Example
$target="Hewlett-Packard"
$tindex=4
$source="falcon"
$sindex=2
$number=3
$L.void=strins($target, $tindex, $source, $sindex, $number)
Function
strpadl
Format
$L.void=strpadl($string, $size)
Parameters
$L.void= Not applicable. A syntax requirement only, does not affect the outcome of the
function.
Example
$string="Hewlett-Packard"
$size=20
$L.void=strpadl($string, $size)
Function
strpadr
Format
$L.void=strpadr($string, $size)
Parameters
$L.void= Not A syntax requirement only. It does not affect the outcome of the
applicable. function.
Examples
$string="Hewlett-Packard"
$size=20
$L.void=strpadr($string, $size)
$string="Hewlett-Packard"
$size=10
$L.void=strpadr($string, $size)
Function
strraw
Format
Parameters
Data
Parameter type Description
$delim Character The delimiter that separates the elements of the array in the result
string. The default is space.
Example
$result=strraw({“a”,2,,true},”;”)
Function
strrep
Format
strrep($target,$string1,$string2)
Parameters
Example
$s=strrep("Personnel","sonnel","formance")
Function
strtrml
Format
$L.void=strtrml($string)
Parameters
$L.void= Not A syntax requirement only. It does not affect the outcome of the
applicable. function.
Example
$string="Hewlett-Packard"
$L.void=strtrml($string)
Function
strtrmr
Format
$L.void=strtrmr($string)
Parameters
$L.void= Not applicable. A syntax requirement only, does not affect the outcome of the
function.
Example
$string="Hewlett-Packard "
$L.void=strtrmr($string)
Function
substr
Format
Parameters
Data
Parameter type Description
beginning Number The position in the string where the substring is to begin.
position
length Number The total number of characters you want the substring to contain. 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 substr length.
Example
Function
substrb
Format
Parameters
Data
Parameter type Description
beginning Number The position in the string where the substring is to begin.
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. You can use the length parameter to specify a shorter byte length.
Caution: You should choose a length value that takes into account the
number of bytes available in the source string. 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.
Refer to a UTF-8 or UTF-16 character encoding map to see how many
bytes a particular multibyte character requires. It is recommended that
you only use this function on strings of a fixed byte length to avoid
possible data corruption. If you want to replace a fixed number of
characters use the substr function instead.
Example
$a=substrb("abcÄÖÜdef", 5)
$b=substrb("abcÄÖÜdef", 1, 7)
For the string $b, setting the length value to 4 or 6 would lead to data corruption because there are not
enough bytes available to contain the multi-byte characters Ä and Ö respectively.
Function
sysinfo.get("ActiveFloatUsers")
Format
$info=sysinfo.get("ActiveFloatUsers")
Function
sysinfo.get("ActiveLicenses")
Format
$info=sysinfo.get("ActiveLicenses")
Function
sysinfo.get("ActiveNamedUsers")
Format
$info=sysinfo.get("ActiveNamedUsers")
l Returns ldap if using password authentication and the password exits in LDAP.
Function
sysinfo.get("AuthMode")
Format
$info=sysinfo.get("AuthMode")
Example
$info=sysinfo.get("AuthMode")
After execution, the value of $info is set to the authentication mode of the current user.
Function
sysinfo.get("ClientNetAddress")
Format
$info=sysinfo.get("ClientNetAddress")
Example
$x.clientNetAddress=sysinfo.get("ClientNetAddress")
Function
sysinfo.get("ClientOSName")
Format
$info=sysinfo.get("ClientOSName")
Function
sysinfo.get("ClientPID")
Format
$info=sysinfo.get("ClientPID")
Example
$x.clientPid=sysinfo.get("ClientPID")
Function
sysinfo.get("ClientVersion")
Format
$info=sysinfo.get("ClientVersion")
l Returns text if the process is not running through a GUI client, such as a background process.
Function
sysinfo.get("Display")
Format
$info=sysinfo.get("Display")
Example
$display=sysinfo.get("display")
After execution, the $display variable is gui if the user is running a Windows session.
l Returns scserver if your session is a client application connection such as ConnectIT or GetServices.
Function
sysinfo.get("Environment")
Format
$info=sysinfo.get("Environment")
Function
sysinfo.get("languagecode")
Format
$info=sysinfo.get("languagecode")
Function
sysinfo.get("MaxFloatUsers")
Format
$info=sysinfo.get("MaxFloatUsers")
Function
sysinfo.get("MaxLicenses")
Format
$info=sysinfo.get("MaxLicenses")
Function
sysinfo.get("Mode")
Format
$info=sysinfo.get("Mode")
Examples
$mode=sysinfo.get("mode")
If (index(sysinfo.get("mode"),{"sm","server",
"express"})>0 then (...)
Function
sysinfo.get("PrevLabel")
Format
$info=sysinfo.get("PrevLabel")
Example
$L.lastlabel = sysinfo.get("prevlabel")
The panel name is the last panel executed in the RAD program called. At the start panel for any
application, the name is the calling panel name from the parent application.
RAD function: sysinfo.get("PKMode")
A RAD function that returns the primary key mode for the system. Returned values are of the following
types:
l true: indicates that the system is running in primary keys mode (primary_key_mode=1 in sm.ini).
l false: indicates that the system is not running in primary keys mode (primary_key_mode=0 in
sm.ini).
Function
sysinfo.get("PKMode")
Format
$info=sysinfo.get("PKMode")
Example
<variable> = sysinfo.get("pkmode")
Function
sysinfo.get("PrintOption")
Format
$info=sysinfo.get("PrintOption")
Function
sysinfo.get("Quiesce")
Format
$info=sysinfo.get("Quiesce")
Function
sysinfo.get("RecList")
Format
$info=sysinfo.get("RecList")
Function
sysinfo.get("ServerNetAddress")
Format
$info=sysinfo.get("ServerNetAddress")
Function
sysinfo.get("ServerNetPort")
Format
$info=sysinfo.get("ServerNetPort")
Factors
Examples
sm –httpPort:12932
sm –-httpPort:scport1
Function
sysinfo.get("ServerPID")
Format
$info=sysinfo.get("ServerPID")
Function
sysinfo.get("Telephony")
Format
$info=sysinfo.get("Telephony")
Function
sysinfo.get("ThreadID")
Format
$info=sysinfo.get("ThreadID")
Example
$x=sysinfo.get("ThreadID")
After execution, the value of $x is set to the number ID of the current RAD thread.
Function
sysinfo.get("TotalFloatUsers")
Format
$info=sysinfo.get("TotalFloatUsers")
Function
sysinfo.get("TotalLicenses")
Format
$info=sysinfo.get("TotalLicenses")
Function
sysinfo.get("TotalNamedUsers")
Format
$info=sysinfo.get("TotalNamedUsers")
Function
sysinfo.get("TotalProcs")
Format
$info=sysinfo.get("TotalProcs")
Function
sysinfo.get("TotalSystemProcs")
Format
$info=sysinfo.get("TotalSystemProcs")
Function
sysinfo.get("TotalUserProcs")
Format
$info=sysinfo.get("TotalUserProcs")
Function
time
Format
time($date.time.variable)
Parameters
Factors
The time of a given date and time may be different in different time zones.
Example
time($date.time)
Function
tod
Format
tod()
Factors
Examples
tod()=`4/20/96 12:15:16'
$curr.time=tod()
Function
tolower
Format
tolower($string)
Parameters
Factors
Example
$s=tolower("Copyright 2011")
Function
toupper
Format
toupper($string)
Parameters
Factors
Example
$s=toupper("Copyright 2004")
Programming considerations: This function has been deprecated and is maintained for backward
compatibility only. This function can only be used on simple single byte character strings and is not UTF-
8 safe. Case conversion on strings should be done with the toupper() and tolower() functions, which are
UTF-8 safe.
Function
translate
Format
Parameters
Factors
l Old and new character sets must be strings of the same length.
l A one–for–one correlation must exist between the old and new character sets. For example, the
third character in the new set replaces the third character in the old set.
Example
translate("123abcdef","abc","ABC")
Function
trunc
Format
trunc(number,n)
Parameters
n Number The number of decimal digits desired. The default value of n is zero (0).
Factors
l The second parameter is not required. By default, the number passed is truncated to a whole
number.
Examples
trunc(3.45,1)
trunc(3.44)
trunc('13:19:34')
Function
type
Format
$ttype=type($any.value)
Parameters
Example
$ttype=type('2/15/96')
Function
updatestatus
Format
updatestatus(file_variable)
Parameters
Factors
l If the last update operation succeeded, this function returns 0 (zero), otherwise it returns one of the
following values:
n 51: The update failed because the record had already been modified.
n 52: The update failed because the record had already been deleted.
l Every time the file variable is moved or changed (for example, a new record is inserted), the return
value of this function is reset to 0.
Example
$L.updateresult=updatestatus($L.file)
Function
val
Format
$new.data=val($data, $new.type)
Parameters
Data
Parameter type Description
$new.type Number Data type to convert the data to. The default value is one (1). For a list of the
numbers that correspond to the data types, see "Data types" on page 17.
Factors
Examples
$x=val(100) 100
$x=val(100, 2) "100"
$x=val(100, 3) ‘00:01:40’
$x=val(0, 4) false
$x=val(1, 4) true
$x=val(2, 4) unknown
$x=val(3, 4) NULL
$x=val("HP", 1) NULL
$x=val("100.3", 1) 100.3
$x=val("HP", 2) "HP"
$x=val("HP", 3) NULL
$x=val("true", 4) true
$x=val("0", 4) NULL
$x=val(‘01:00:23’, 1) 3623
$x=val(‘01/01/96’, 4) NULL
$x=val(‘12:34:56’, 4) NULL
$x=val(false) 0
$x=val(true, 1) 1
$x=val(unknown, 1) 2
$x=val(false, 2) "false"
b NULL
$x=val(unknown, 4) unknown
Function
version
Format
version()
Factors
Example
$a=version()
l The first element is a string naming the platform: unix, mswin, or winnt.
l The third element is a string containing the Service Manager version number and the Service Pack
number, such as 7.0.1 indicates Service Manager version 7.0, Service Pack 1.
Function
year
Format
$fyear=year($date)
Parameters
Example
$fyear=year('2/15/05')
List: rtecalls()
The rtecalls are based on one RAD function, the rtecall( ) function. They are in-line statements that are
useful in the HP Service Manager RAD Debugger. The rtecall function is available anywhere in Service
Manager that supports expressions, statements, or calculations. For example, rtecalls can be used in
Format Control calculations, scripts, and displayoptions. The rtecall() function is extensible. New
capabilities may appear in every release of Service Manager.
Function Description
rtecall("alalnum") Checks to make sure a string contains only alphanumeric characters, or only
alphanumeric characters and the provided non-alphanumeric characters.
rtecall("counter") Turns counters on or off for the current session. Other Service Manager users
are unaffected.
rtecall Returns a date, in the proper form, based upon a series of numbers passed to it.
("datemake")
rtecall("filldate") Places the current date and time in a field in the current record.
rtecall Returns into $L.array the values for the Unique key from the current record in
("getunique") $L.file.
rtecall("isalnum") Checks to make sure a string contains only numeric characters, or only numeric
characters and the provided non-numeric characters.
rtecall("isalpha") Checks to make sure a string contains only alphabetic characters, or only
alphabetic characters and the provided non-alphabetic characters.
rtecall("islower") Checks to make sure a string contains only lowercase characters, or only
lowercase characters and the provided non-lowercase characters.
rtecall Checks to make sure a string contains only numeric characters, or only numeric
("isnumeric") characters and the provided non-numeric characters.
rtecall("isupper") Checks to make sure a string contains only uppercase characters, or only
uppercase characters and the provided non-uppercase characters.
rtecall Returns a record list form, which can be passed into an rio or fdisp panel.
("qbeform")
rtecall("recdupl") Copies the contents of the current record into the contents of another record.
rtecall Specifies whether any records exist that match a particular query regardless of
("recordexists") any Mandanten data restrictions.
rtecall("refresh") Retrieves the most current value of a record from the database and returns it in
the file variable.
rtecall("rfirst") Places the pointer at the first record in a record collection (a record list).
rtecall("rgoto") Places the pointer at the indicated record.id in a record collection (a record list).
rtecall("rid") Returns the record number of the current record (represented by $L.file).
rtecall Scans the specified table for certain types of invalid records and fixes them.
("scantable")
rtecall Measures the amount of data transferred, elapsed time and CPU usage of any
("transtart") transaction.
rtecall Measures the amount of data transferred, elapsed time and CPU usage of any
("transtop") transaction.
Transtop is commonly invoked from the RAD debugger and is used in conjunction
with transtart.
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 non-
alphabetic characters provided.
Function
rtecall("alalnum")
Format
Parameters
Data
Parameter type Description
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="., _"
$L.success.flag=rtecall("alalnum", $L.return.code, $L.str, $L.chars)
Results:
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
Parameters
Data
Parameter type Description
$L.fnc.name String The name of the sub-function to call, in this case "counter".
$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
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
Parameters
$L.fnc.name String The name of the sub-function to call, in this case "datemake".
$L.yr 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.
$L.da Number The day. Valid values are from one (1) through 31.
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.success.flag=true
l $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)
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 that
string is to be fed back into HP 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:
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:
Function
rtecall("escstr")
Format
Parameters
Example
$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
Parameters
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)
rtecall("fileinit") function
A RAD function that initializes a file variable in $targetfile from $sourcefile.
Function
rtecall("fileinit")
Format
Parameters
Factors
l The current record for $targetfile is the same as the current record in $sourcefile.
Example
rtecall("filldate") function
A RAD function that places the current date and time in a field in the current record.
Function
rtecall("filldate")
Format
Parameters
$L.fnc.name String The name of the sub-function to call, in this case "filldate".
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
Parameters
Data
Parameter type Description
$L.flg Logical The value is true for success and false if an error occurs.
$L.fnc.name String 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.class String The class of number for which you are searching (from the number file).
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)
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).
n 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.
Function
rtecall("getprimary")
Format
Parameters
Variable/Value Description
$L.void = true If key values are returned in $L.keyvalues. For example, if $L.file represents a
current database record.
$L.void= false If no key values are returned. For example, if $L.file does not represent a current
database record.
$L.errcode = 2 The file identified by $L.file does not have a primary key defined.
$L.file The file variable initialized by the rinit command panel and containing a current
record.
Factors
$L.keyvalues is an output variable. The output returns an array containing the primary key values for
the record in $L.file. For example, if $L.file is for the problem table, an example of the key values
returned in $L.keyvalues is {"IM1001",1}.
Example
rtecall("getrecord") function
A RAD function that retrieves the record identified by Unique key values in $L.array.
Function
rtecall("getrecord")
Format
Parameters
$L.fnc.name String The name of the sub-function to call, in this case "getrecord".
$L.file String The name of the table to retrieve the record from.
Factors
$L.array is an input variable, typically the key values returned by $L.array in the rtecall("getunique")
function.
Example
Where:
rtecall("getunique") function
A RAD function that returns an array containing the Unique key values for a current record. The keys
can later be used to retrieve the record using the rtecall("getrecord") function.
Function
rtecall("getunique")
Format
Parameters
Variable/Value Description
$L.void = true If key values are returned in $L.keyvalues. For example, if $L.file represents a
current database record.
$L.void = false If no key values are returned. For example, if $L.file does not represent a current
database record.
$L.errcode = 2 The file identified by $L.file does not have a Unique key defined.
$L.file The file variable initialized by the rinit command panel and containing a current
record.
Factors
$L.keyvalues is an output variable. The output returns an array containing the unique key values for the
record in $L.file. For example, if $L.file is for the problem table, an example of the key values returned in
$L.keyvalues is {"IM1001",1}.
Example
rtecall("isalnum") function
A RAD function that verifies that a string contains only alphabetic, numeric, or the non-alphabetic
characters provided.
Function
rtecall("isalnum")
Format
Parameters
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=phone in $L.file
$L.chars=" , (, ), -"
$L.success.flag=rtecall("isalnum", $L.return.code, $L.str, $L.chars)
Results:
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.
Function
rtecall("isalpha")
Format
Parameters
Data
Parameter type Description
$L.fnc.name String The name of the sub-function to call, in this case "isalpha".
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=" "
$L.success.flag=rtecall("isalpha", $L.return.code, $L.str, $L.chars)
Results:
rtecall("islower") function
A RAD function that verifies that a string contains only lowercase characters, or only lowercase
characters and the provided non-lowercase characters.
Function
rtecall("islower")
Format
Parameters
Data
Parameter type Description
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=" "
$L.success.flag=rtecall("islower", $L.return.code, $L.str, $L.chars)
Results:
rtecall("isnumeric") function
A RAD function that verifies that a string contains only numeric characters, or only numeric characters
and the provided non-numeric characters.
Function
rtecall("isnumeric")
Format
Parameters
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="-,+,*,/,%,$"
$L.success.flag=rtecall("isnumeric", $L.return.code, $L.str, $L.chars)
Results:
rtecall("isupper") function
A RAD function that verifies that a string contains only uppercase characters, or only uppercase
characters and the provided non-uppercase characters.
Function
tecall("isupper")
Format
Parameters
Data
Parameter type Description
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=" "
$L.success.flag=rtecall("isupper", $L.return.code, $L.str, $L.chars)
Results:
rtecall("log") function
A RAD function that sends a message to the external sm.log file.
Function
rtecall("log")
Format
Parameters
$L.fnc.name String The name of the sub-function to call, in this case "log".
Factors
If the $L.success.flg is false, the function failed. If it is true, the function succeeded.
Example
rtecall("passchange") function
A RAD function that changes a user password.
Function
rtecall("passchange")
Format
Parameters
Data
Parameter type Description
$L.fnc.name String Name of the sub-function to call. In this case, the sub-function called is
passchange.
Factors
If the $L.success.flg is false, the function failed. If it is true, the function succeeded.
Example
rtecall("policycheck") function
A RAD function that imposes data policy as defined in the System Definition.
Function
rtecall("policycheck")
Format
Parameters
Factors
If the $L.success.flg is false, the function failed. If it is true, the function succeeded.
Example
rtecall("qbeform") function
A RAD function that returns a record list form, which can be passed into a rio (Record Display/Input)
Command panel or fdisp panel. You can insert this function into a format file handle using the contents
() function. The following example shows the syntax to use in the contents function: contents
($L.format) = $L.qbe.form.
Function
rtecall("qbeform")
Format
$L.success.flg= rtecall($L.fnc.name,$L.return.code,$L.file,$L.qbe.form)
Parameters
Data
Parameter type Description
$L.fnc.name String The name of the subfunction to call; in this case "qbeform".
$L.file File The file handle used to generate the record list. For example, obtain the
contacts table by using the "rinit" panel.
Factors
If the $L.success.flg is false, the function failed. If it is true, the function succeeded.
Example
$L.success.flg= rtecall("qbeform",$L.return.code,$L.file,$L.qbe.form)
rtecall("recdupl") function
A RAD function that copies the contents of the current record into the contents of another record.
Function
rtecall("recdupl")
Format
Parameters
$sourcefile String The source file from which fields are copied.
Factors
l Both $targetfile and $sourcefile must have identical descriptors. Data is copied by position, not
field name.
Example
rtecall("recordexists") function
Specifies whether any records exist that match a particular query regardless of any Mandanten data
restrictions. This call does not return any records from the query.
Function
rtecall("recordexists")
Format
Parameters
Data
Parameter type Description
"recordexists" String Determines the name of the RTE call, in this case "recordexists".
$L.rc String Provides a more detailed return code. This parameter is not currently
used but is reserved for future use.
$L.filename String The name of the Service Manager table to query. For example, contacts
or probsummary.
$L.query String The query to be run. The query can be true, false, a string, or a parsed
expression. This query ignores all Mandanten restrictions.
Factors
The call returns true if at least one record matches the query.
The call returns false if there are no records that match the query.
Example
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.
rtecall("refresh") function
This function retrieves the most current value of a record from the database and returns it in the file
variable.
Function
rtecall("refresh")
Format
Parameters
The following parameters are valid for the rtecall("refresh") function:
Variable/Value Description
$L.file The file variable initialized by the rinit command panel. It contains the current
record.
Factors
If the $L.success.flg is false, the function failed. It is true, the function succeeded.
Example
rtecall("resetnotebook") function
A RAD function that adds an XML attribute "resetnotebook=true" to the "execute" response of the
current RAD thread. The Service Manager client will set the active page of a notebook to its first page
when this XML attribute is present.
Function
rtecall("resetnotebook");
Format
Parameters
Factors
Example
rtecall("rfirst") function
A RAD function that places the pointer at the first record in a record list.
Function
rtecall("rfirst")
Format
Parameters
$L.fnc.name String The name of the sub-function to call, in this case "rfirst".
Factors
If the $L.success.flg is false, the function failed. If it is true, the function succeeded.
Example
$L.success.flg=rtecall("rfirst",$L.return.code, $L.file)
rtecall("rgoto") function
A RAD function that places the pointer at the indicated record.id in a record list.
Function
rtecall("rgoto")
Format
Parameters
$L.fnc.name String The name of the sub-function to call, in this case "rgoto".
Factors
If the $L.success.flg is false, the function failed. If it is true, the function succeeded.
Example
rtecall("rid") function
A RAD function that returns the record number of the current record, as represented by $L.file.
Function
rtecall("rid")
Format
Parameters
$L.fnc.name String The name of the sub-function to call, in this case "rid".
Factors
If the $L.success.flg is false, the function failed. If it is true, the function succeeded.
Example
rtecall("scantable") function
A RAD function that scans the specified table for certain types of invalid records and fixes the records.
Function
rtecall("scantable")
Format
Parameters
Data
Parameter type Description
$scantype Number Specifies the type of scan the function will perform, which can be one of
the following:
l 2–to scan for null values on non-nullable fields, such as fields with a
"Unique" or "No Nulls" key applied
l 3–to scan for values whose data types do not match the data type
defined on the field
$columns String Only available when $scantype is 1, specifies the columns on which the
array function will scan for duplicate records.
$totalnum Number Indicates the number of the invalid records that were found.
$fixed Number Indicates the number of the invalid records that were fixed.
$deleted Number Indicates the number of the records that were removed.
Factors
If the $L.success.flg is false, the function failed. If it is true, the function succeeded.
$totalnum, $fixed, and $deleted are available when $scantype is 2 or 3. This total number should include
$fixed, $deleted, and the number of invalid records that failed to be fixed.
Examples
The following function call scans the ioaction table for duplicate records on the field1 and field2 fields
and fixes the duplicate records.
The following function call scans the ioaction table for null values that are disallowed by keys.
Additional information
l In a "type-1" scan, the function differentiates duplicate items by appending suffixes such as -dup1, -
dup2...-dupx.
n The function removes the record if null values violate a "Unique" key.
n Or the function replaces the first of the null values with a default value if null values violate a "No
Nulls" key.
n The function converts the value into the correct data type if the value data makes sense in the
target data type.
n The function replaces the value with a default value in the correct data type.
rtecall("sort") function
A RAD function that sorts a list or a list of lists in ascending or descending order.
Function
rtecall("sort")
Format
Parameters
Data
Parameter type Description
$L.index Number The index of the array in the grid to use as the sort field. A zero (0) is the
first element of the array.
$L.type Number The type of sort to perform. Use zero (0) for an ascending sort or one (1)
for a descending sort.
$L.nulls Number Specifies how the function should sort null values. Use one (1) to sort null
values at the end of the list or zero (0) to sort values at the start of the
list.
Factors
If the $L.success.flg is false, the function failed. If it is true, the function succeeded.
Examples
rtecall("statusupdate") function
A RAD function that dynamically changes the caption of a widget on the current format. The widget
must have a name property specified. 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. For example,
converting a file to an RDBMS.
Function
rtecall("statusupdate")
Format
Parameters
Data
Parameter type Description
$L.widget.name String The name of the form widget, as specified in the name property of
the widget.
Factors
If the $L.success.flg is false, the function failed. If it is true, the function succeeded.
Example
rtecall("transtart") function
A RAD function that measures the amount of data transferred, elapsed time, and CPU usage of any
transaction. This function is commonly invoked from the RAD debugger and used in conjunction with the
rtecall ("transtop") function.
Function
rtecall("transtart")
Format
$L.success.flag= rtecall($L.fnc.name, $L.return.code, $L.transaction)
Parameters
$L.transaction String Any name selected by the user for the transaction to measure.
Factors
If the $L.success.flg is false, the function failed. If it is true, the function succeeded.
Example
rtecall("transtop") function
A RAD function that measures the amount of data transferred, elapsed time, and CPU usage of any
transaction. The function is commonly invoked from the RAD debugger and used in conjunction with the
rtecall("transtart") function.
l You can have multiple transaction timings active at the same time.
Function
rtecall("transtop")
Format
Parameters
Data
Parameter type Description
$L.transaction String Any name selected by the user for the transaction to measure.
$L.$results Array The results gathered, in the form of an array: {elapsed seconds, cpu
seconds, 0, 0, 0}. HP Service Manager no longer keeps track of the
third, fourth, and fifth value in the array and it always reports as zero.
Factors
If the $L.success.flg is false, the function failed. If it is true, the function succeeded.
Example
This example shows that the problemopen transaction took 58.164 seconds of real time and 0.961 CPU
seconds.
rtecall("trigger") function
A RAD function that turns triggers on or off for the current session. Other HP Service Manager users are
not affected.
Function
rtecall("trigger")
Format
Parameters
Data
Parameter type Description
$L.switch Number The value is either one (1) to turn triggers on. or zero (0) to turn triggers
off.
Factors
If the $L.success.flg is false, the function failed. If it is true, the function succeeded.
Example
Routine Description
as.copy Copies an element from one position to another, leaving the original in place.
as.get.name Returns the structure name of the arrayed structure in which the cursor is
located.
as.move Moves an element from one position in an array to another by creating a copy
and then deleting the original
as.options Displays all available arrayed structure options on the rio (Record
Display/Input) Command panel.
as.sort Sorts an arrayed structure based on the contents of a particular field within
the arrayed structure.
axces.cm3.cts.write Creates a schedule record that processes alerts for Change Management
records.
axces.database Adds, updates or deletes records from Service Manager files using Event
Services.
axces.email Creates an eventout record based on the Service Manager mail record that
was passed in.
axces.email.receive Receives external e-mail and converts it to Service Manager mail using Event
Services.
axces.fax Builds an eventout record that can be processed by the SCAutomate / Fax
application.
axces.move.intoout Copies an eventin record to the eventout file and changes the evtype.
axces.rm Creates or updates Request Management quotes via Event Services eventin
record.
fill.fc Copies data from a target file to the current file, using predefined links under
user control.
marquee.send Reads the schedule record and initiate the marquee.publish routine.
post.fc Executes the posting routine from the subroutines process (automatic
posting) and from the additional options process (manual posting).
query.stored Accesses all queries for a specific file or to execute a specific stored query.
us.js.call A RAD routine that can invoke any JavaScript function in the ScriptLibrary.
This routine enables you to run a JavaScript function without connecting to
the Service Manager server via a client.
wmi.inventory.checks Checks the eventin record for status information from a type of scan. It also
processes the information from the scan into the Configuration Management
application using the scauto.inventory RAD routine.
Routine
as.copy
Parameters
file record No The file variable that you are currently editing. The value is always
$file when called from Format Control.
name character No Data is not normally passed to this parameter. The default is the
result of executing the cursor.field.name(1) function. The application
as.get.name then executes against this result.
index number No The number of lines (height property) in the subform that displays
the arrayed structure. For example, if the arrayed structure subform
contains data on lines 1 and 2, then this parameter is 2. The default
value is 1.
Note: 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:
Routine
as.delete
Parameters
file record No The file variable currently being edited. The value is always $file
when called from Format Control.
name character No Data is not normally passed to this parameter. The default is the
result of executing the cursor.field.name(1) function . The
application as.get.name then executes against this result.
index number No The number of lines (height property) in the subform that displays
the arrayed structure. For example, if the arrayed structure subform
contains data on lines 1 and 2, then this parameter is 2. The default
value is 1.
Note: 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:
Routine
as.get.name
Parameters
name character No The structure name of the arrayed structure. The default is the
result of executing the cursor.field.name(1) function .
prompt character No The returned structure name of the arrayed structure. This is a
data return parameter, data should not be passed to it.
Routine
as.insert
Parameters
file record No The file variable currently being edited. The value is always $file
when called from Format Control.
name character No Data is not normally passed to this parameter. The default is the
result of executing the cursor.field.name(1) function. The application
as.get.name then executes against this result.
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.
Note: 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:
Routine
as.move
Parameters
file record No The file variable currently being edited. The value is always $file
when called from Format Control.
name character No Data is not normally passed to this parameter. The default is the
result of executing the cursor.field.name(1) function. The application
as.get.name then executes against this result.
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.
Note: 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)
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
Parameters
file record No The file variable currently being edited. The value is always
$file when called from Format Control.
name character No Passes the name of the current form. If left blank, the default is
the result of executing the current.format() function.
cond.input Boolean No Allows the user to edit the data record when the Arrayed
structure maintenance options are displayed. The default value
is true.
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.
Note: This is not the window size that displays the arrayed
structure.
val("n", 1)
Where:
The value of n is the number of lines in the subform, and one (1)
indicates a data type of number.
Routine
as.sort
Parameters
file record No The file variable currently being edited. The value is always $file
when called from Format Control.
name character No 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.
numbers array Yes Specifies the field numbers on which to sort within the arrayed
structure. In Format Control, you must first define a $variable
(numbers)
in the Initializations form for the array of numbers. Next, pass
that variable to the numbers input field in the Additional Options
definition.
condition array No Specifies either ascending or descending order for each field
being sorted in the arrayed structure, as specified in the
(Boolean)
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.
Routine
axces.apm
Parameters
query character No Indicates the query to use to find the pre-existing record updated
by this Input event.
string1 character No Identifies the HP Service Manager file where the data is recorded.
boolean1 Boolean No 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.
Routine
axces.cm3.cts.write
Parameters
name character No Indicates the System ID of the system to send the message to
and where to calculate the schedule time.
prompt character No Indicates the Client of the system to send the message to and
where to calculate the schedule time.
time1 time No 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.
query character No 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.
boolean1 Boolean No When set to true, the rescheduling portion of the code is
bypassed and all messages occur as soon as possible.
Routine
axces.cm3
Parameters
string1 character No Identifies the area of CM3 to work in and where to record data for
branching or changing tasks (cm3r or cm3t).
string1 character No Identifies the area of CM3 to work in and where to record data for
branching or changing tasks (cm3r or cm3t).
Routine
axces.database
Parameters
Parameter
Name Data type Required Description
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.
string1 character Yes Identifies the Service Manager table to populate with data.
text character Yes Provides the specific action to take, such as the following:
l add
l delete
l update
query character No Indicates the query to use to find the existing record to update.
boolean1 Boolean No 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.
cond.input Boolean No 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.
Routine
axces.email
Parameters
record record No Writes the unique record identifier to the eventin record. Set up the
$axces variable using Format Control to create the intended result.
Routine
axces.email.receive
Parameters
record record No This parameter writes the unique record identifier to the eventin
record. Set up the $axces variable using Format Control to create
the intended result.
Routine
axces.fax
Parameters
names,1 array No Passes the name of the sender. Use your login ID.
(characters)
name character No Passes the name of the recipient. Use the recipient’s login ID.
prompt character No Defines the recipient’s fax telephone number. For example,
fax.phone from the contacts table.
string1 character No Defines the separation character. If you define your own
character, ensure that it does not occur naturally in fields in the
event. The default is ^.
text character No Names the form or text string. If a record variable passes in the
record parameter, pass the form name in the text parameter. If
you pass a string in the text parameter, use the pipe symbol (|)
to separate line of text.
(characters)
(characters)
record record No Passes the record variable. Use $file in Format Control.
Routine
axces.move.intoout
Parameters
Routine
axces.page
Parameters
name character Yes Contains the Contact Name from the contacts table.
string1 character No Defines the separation character. If you define your own
character, ensure that it does not occur naturally in fields in
the event. The default value is the caret character (^).
query character No Defines the page response code used by the pageresp input
event to identify the type of event processing to occur. For
example, to update a particular incident with the response
from a page, pass pm and the incident number, such as
pm9700123. The registration record then determines the
application to call by examining the data in the first position of
the evfields field.
names,1 array No Lists the pager telephone number from the contacts table.
(characters)
names,2 array No Lists the pager PIN number from the contacts table.
(characters)
names,3 array No Passes the name of a group defined in the distgroup table.
(characters)
Routine
axces.rm
Parameters
text character No Provides the specific action to take, such as add, open, update,
close, approve, disapprove or unapprove.
query character No The query string used to select a pre-existing record to update.
string1 character No Identifies the HP Service Manager table (ocmq, ocmo, or ocml)
where data is recorded.
boolean1 Boolean No The logical parameter flag, true or false, that indicates whether
to write the eventout record on transaction completion.
Routine
axces.sap.hybrid.evin
Parameters
record record No A hybrid event that calls the appropriate routines for header and
detail events. This parameter expects one header and any number
of properly-formed detail events.
prompt character No Identifies the eventregister that interprets the detail portion of the
event message.
name character No Identifies the eventregister that interprets the header portion of
the event stream.
Routine
axces.sm
Parameters
string1 character No Identifies the HP Service Manager file where data is recorded.
query character No Indicates the query to use to find the pre-existing record that this
Input event updates.
boolean1 Boolean No A logical parameter flag, true or false, that indicates whether
the eventout record writes on transaction completion.
Routine
axces.software
Parameters
record record No Writes the unique record identifier to the eventin record. Set up
the $axces variable using Format Control to create the intended
result.
string1 character No Identifies the software file in HP Service Manager where the
configuration item (CI) data is recorded.
boolean1 Boolean No A logical parameter flag, true or false, that indicates whether
the eventout record writes on transaction completion.
Routine
axces.write
Parameters
record record Yes Names the record to be written. In Format Control the record is
$file.
name character No Names the registration type as it appears in the eventregister file.
For example, to write an eventout record when an incident is
opened, use the value pmo for this parameter.
string1 character No Defines the separation character. If you define your own character,
ensure that it does not occur naturally in fields in the event. The
default is value is the caret character (^).
query character No Defines the user name. The default value is operator().
Note: This routine is only called from Additional Options in Format Control.
Routine
database
Parameters
Routine
es.approval
Parameters
text character No Identifies the HP Service Manager table where data is recorded.
cond.input Boolean No A logical parameter, true or false, that specifies whether the
eventout record writes on transaction completion.
Routine
fill.fc
Parameters
record record Yes The value is $file when calling fill.fc through the Additional Options
process.
text character No The name of the field in the target file to fill. The default is the
current field (the field where the cursor is located). If the field is an
array, the fill operation attempts to copy data back to that item in
the selected array.
string1 character No The form name that determines which link record to use. The
default is the link record for the current form.
Variables supported
$fill.replace
$project.first
$fill.exact
Routine
getnumb.fc
Parameters
record record Yes The data record where the number will be placed. The value of
this parameter must be $file.
name character Yes The sequential number Class (category) of the record that the
Format Control record is attached. This value appears in the
Class field of the Sequential Numbering File.
prompt character Yes Names the field in the data record where the sequential number
appears.
text character No Defines the data type of the sequential number (number or
string).
number1 number No 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. Pass the val() RAD function to the
number1 parameter. For example, a four-digit number has a
value of val("4", 1).
Where:
string1 character No Defines the prefix. This is the identifying character string that
appears before the number.
numbers,1 array No Determines the reset point for the sequential number. When
(numbers) the value passed to the application is reached, the sequential
number resets to the starting value.
numbers,2 array No Establishes a new starting value for the sequential number
when the reset point is reached.
(numbers)
numbers,3 array No Sets the increment or decrement value. For example, if you
want to increment by 2, displaying odd or even numbers only.
(numbers)
Routine
marquee.publish
Parameters
name character Yes The published variable used by the agent to search the
database.
prompt character No The display color for your marquee or the valid system number
in the Color field. The default value is Red.
boolean1 Boolean No A logical field. Set the flag to true to add this message to the
marquee table. The marquee agent then reads the record and
publishes it. If the flag is set to false, the routine immediately
publishes your message without adding it to the marquee table
(recommended method).
cond.input Boolean No A logical field. Set the flag to true to add the name to the
database if that record does not exist.
Routine
marquee.send
Parameters
boolean1 Boolean No Logical field. Set the flag to true to send all marquee messages
defined in the schedule record. If set to false, or the field is
NULL, the application publishes only the specific marquee
message defined in the schedule record (recommended method).
Routine
message.fc
Parameters
l 2 for action.
l 3 for error.
prompt character No Enter a message class that matches one of the records in the
msgclass table, such as problemclose. To send email messages,
there must be a msgclass record with a type of email for the
message class name specified. The default value is msg.
text character Yes The text of the message can be a string or an array. For
example, generate an array of the screen contents using the
genout() function and then insert lines of text at the top of the
array.
name character No This value can contain either a list of operator names or a single
name. For internal HP Service Manager messages, the names
must be operator ID’s defined in the operator table. For email,
the names can either be operator ID’s or contact names
(contact.name) defined in the contacts table; an email address
must be specified in the relevant table. The default is operator
().
string1 character No The message name parameter identifies the message. Use the
name of the Service Manager application or application area
that generates the message.
query character No The mail class parameter is used within Incident Management
applications to identify the record number so that mail already
sent can be selected and updated. It must contain the string
pm.main and a Mail Target must be defined.
names,1 array No The mail target parameter must contain the incident record
number.
(characters)
Routine
post.fc
Parameters
file record Yes The value is always $file when calling post.fc through the
Additional Options process. In most cases, the variable is $file
when calling post.fc through the Subroutine process; however, it
could be $file1, or another file variable established by Format
Control or custom RAD processing.
name character No Defaults to the name of the currently open form. You can override
this default by passing a string of the specific Link record you want
to use.
prompt character No Defaults to the name of the input field that the cursor is in when
the you select the option. You can override this default by passing a
string of a specific field name you want to use.
Routine
publish
Parameters
name character No The published variable used by the agent to search the database.
Routine
query.stored
Parameters
name character No The name of the table you want to enable the user to query, for
example, device.workstation.
text character No The name of the stored query you want to execute, for example,
name=operator().
Routine
scauto.inventory
Parameters
record record Yes Writes the unique record identifier to the eventin record. If you
use a variable such as $axces, set it up using Format Control to
create the intended result.
string1 character No Identifies the Service Manager table name to write to.
text character No Provides the specific action to take, such as add, update, or
delete.
query character No Indicates the query to use to find the pre-existing record that this
Input event updates.
boolean1 Boolean No The logical parameter flag, true or false, that indicates whether
to write the eventout record on transaction completion.
Routine
sort.array
Parameters
file record Yes When calling sort.array from Format Control, always pass $file
to this parameter.
name character Yes The name of the input field (array) in $file you want to sort.
boolean1 Boolean No Controls the sort order. A value of true sorts in ascending order,
and a value of falsesorts in descending order. The value is
expressed as val(), for example, val("false", 4).
Routine
us.js.call
Parameters
Routine
validate.fields
Parameters
name character No Names the field in the current form to validate, such as
logical.name. To name the field in which the cursor was
last located when an add or update was performed, use
the cursor.field.name() RAD function .
names array No Name of the array in the current form containing the field
(of characters) names to validate. The line of the array to validate must be
defined in the Initializations process.
second.file record Yes The data record in which the field is being validated. The
value of this parameter must be $file.
cond.input Boolean No The required value of the field defined by the val()
parameter . For example, to validate a Boolean field to
true, use the value val("true", 4). When set to true,
the value can be looked up online. This means a list of valid
values is presented for selection.
Routine
wmi.inventory.check
Parameters
string1 character No Identifies the Service Manager table where data is recorded.
text character No Provides the specific action to take, such as add, update, or
delete.
query character No Indicates the query to use to find the pre-existing record that
this Input event updates.
boolean1 Boolean No A logical parameter flag, true or false, that indicates whether
the eventout record writes on transaction completion.
The primary global object is the System object. It acts as a container for an entire hierarchy of objects.
These other objects are properties of the System object.
Note: None of the Service Manager global System objects have constructors.
This is a complete list of global objects exposed as properties of the System object.
Global System
objects Description
system.sysinfo Calls an XML list of properties about the Service Manager server.
system.threads Calls an XML list of the current Service Manager threads into memory.
system.user Calls an XML list of properties of the currently logged on Service Manager
user.
Global System
objects Description
system.users Calls an XML list of the currently logged on Service Manager users into
memory.
Note: All of the alias or shortcut global objects available in HP ServiceCenter 6.0 are deprecated in
Service Manager. They are deprecated because the alias or shortcut is likely to be used as a script
variable. The scripts that attempt to use these names as variables will not function as expected.
Therefore, you must type out the entire global system object name. For example, type
system.user instead of user.
The system.files object allows you to call a particular Service Manager table into memory.
Usage
system.files.table name
Arguments
Properties
table name Yes This argument contains the table name you want to bring into memory.
Methods
None
Example
var f = system.files.contacts;
print( "The value of system.files.contacts is:\n" + f );
The system.forms object allows you to call a particular Service Manager form into memory.
Usage
system.forms.form name
Arguments
Properties
form name Yes This argument contains the form name you want to bring into memory.
Methods
None
Example
var fm = system.forms.ScriptLibrary;
print( "The value of system.forms.ScriptLibrary is:\n" + fm );
Usage
Note: There are two exceptions to syntax used for RAD functions: delete and null.
Arguments
RAD function String Yes This argument contains any arguments required to
arguments execute the RAD function.
Properties
RAD function Yes This argument contains the RAD function name you want to bring
name into memory.
Methods
None
Example
The system.functions.scmsg object allows you to call a particular Service Manager message record
from JavaScript.
Usage
Arguments
message String Yes This argument contains the Service Manager message
number number you want to call into memory.
message String Yes This argument contains the Service Manager message class
class you want to call into memory.
Properties
None
Methods
None
Return values
Example
l A valid Service Manager message record (for example, "km" class record 14 "Group %S and Profile
%S are already in category %S")
The system.library object allows you to call a particular Service Manager script library function.
Usage
Arguments
function String Yes This argument contains the function arguments you
arguments want to use.
Properties
script name Yes This argument contains the script name you want to run.
function name No This argument contains the function name you want to run.
Methods
None
Example
l Creates an array.
The system.oldrecord object allows you to call the last Service Manager record into memory.
Usage
system.oldrecord
Arguments
Properties
Methods
None
Example
var o = system.oldrecord;
print( "The value of system.record is:\n" + o );
The system.record object allows you to call the current Service Manager record into memory.
Usage
system.record
Arguments
Properties
Methods
None
Example
r = system.record;
print( "The value of system.record is:\n" + r );
The system.sysinfo object allows you to call an XML list of properties about the Service Manager server.
Usage
system.sysinfo
Arguments
Properties
Methods
None
Example
var s = system.sysinfo;
print( "The value of system.threads is:\n" + s );
The system.threads object allows you to call an XML list of the current Service Manager threads into
memory.
Usage
system.threads
Arguments
Properties
Methods
None
Example
var th = system.threads;
print( "The value of system.threads is:\n" + th );
The system.user object allows you to call an XML list of properties of the currently logged on Service
Manager user.
Usage
system.user
Arguments
Properties
Methods
None
Example
var u = system.user;
print( "The value of system.user is:\n" + u );
The system.users object allows you to call an XML list of the currently logged on Service Manager users
into memory.
Usage
system.users
Arguments
Properties
Methods
None
Example
u = system.users;
print( "The value of system.users is:\n" + u );
The system.vars object allows you to call a particular Service Manager variable into memory.
Usage
system.vars.variable name
Arguments
Properties
variable Yes This argument contains the variable name you want to bring into
name memory.
Methods
None
Example
var v = system.vars.$L_file;
print( "The value of system.vars.$L_file is:\n" + v );
This is a complete list of all the global methods available in HP Service Manager.
getLog This method retrieves a logger named according to the value of the name
parameter.
Quit Allows JavaScript to abort processing and return a failure return code.
RCtoString Converts a Service Manager global return code value into a localized text
string.
setAppMessage Defines the message returned in the "message" attribute in the soap
response.
stripHtml Takes HTML content and strips out the HTML tags and returns the content
as text without the HTML tags.
Syntax
base64Decode( data );
Arguments
data Binary Yes This argument contains the data you want the script to decode
to its original format.
Return values
Description
This method converts data in base 64 string format to its original format.
Example
l A binary file on the local file system (for example, an image file)
Syntax
base64Encode( data );
Arguments
data Binary Yes This argument contains the data you want the script to encode in
base 64 format.
Return values
Description
This method converts binary data to a base 64 string format. You can also use this method to encode
plain text data in base 64 format.
Example
l A binary file on the local file system (for example, an image file)
Syntax
Arguments
script String Yes This argument contains the name of the script you want to
validate.
description String No Use this argument to store any comments you want.
Return values
This method displays the message "Successful compilation of JavaScript function or expression" if the
JavaScript passes validation.
Throws
None
Description
This method validates the syntax of a JavaScript and displays a message as to the success or failure of
the validation. This method is an alias of the execute() method.
Example
l A valid JavaScript
var s = "lib.SCFILEgetTextTest"
compile( s, "Testing execute" );
Syntax
doHTTPRequest( HTTP command, URL, Headers, POST body, Connect Timeout, Read
Timeout, Obsolete, Response headers, Binary request data, Binary response data,
Follow redirects);
Arguments
HTTP String Yes This argument specifies a command verb. We support GET,
command POST, PUT, HEAD, and DELETE.
URL String Yes This argument specifies the URL to which the script should
send an HTTP request. If the HTTP request requires SSL then
the URL must start with https.
POST body String No This argument contains the body of a POST command
request.
Binary Boolean No This argument specifies if the content of a post body is binary
request data.
data
Return values
Description
Note: If the charset is not defined in the “Content-Type” header in the parameter “Headers”, the
charset for the message body will be UTF-8 by default.
Example
Note: To see a working example of the doHTTPRequest method that incorporates multiple error
checking conditions, open the SOAP script in the script library. The WSDL2js function uses the
doHTTPRequest method at line 114 as part of a try/catch statement.
try
{
WSDLrequest = doHTTPRequest( "GET", url, headers, null, 10, 10, null,
respHeaders );
print( "The response headers of the doHTTPRequest is:" );
for( var name in respHeaders )
{
print( name + "=" + respHeaders[name] );
}
print( "The result of the doHTTPRequest is \n" + WSDLrequest );
reply = writeFile( "C:\\IncidentManagement.wsdl", "text", WSDLrequest );
}
catch ( e )
{
print( "WSDL request failed with exception \n" + e );
}
Syntax
doSOAPRequest( URL, SOAPAction, XML, SOAP user ID, SOAP password, Connect Timeout,
Read Timeout, Obsolete, Attachment object, AcceptFastInfoset );
Parameters
URL String Yes This argument specifies the URL to which the script
should send an HTTP request. If the HTTP request
requires SSL then the URL must start with https.
XML String Yes This argument contains the XML for an entire SOAP
request including the SOAP envelope. Refer to the
Web Service's WSDL to determine the proper format
of the SOAP request.
SOAP user ID String No This argument contains the user ID to be used for the
Basic Authorization HTTP header.
Return values
Description
This method sends a SOAP request to a remote server and returns the SOAP response.
Examples
Example 1 :
l Sends a SOAP request to a delayed stock quote Web service and indicates SM accept the
"fastinfoset" formatted SOAP message
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"
xmlns:s0=\"http://ws.cdyne.com/\">
<soap:Body>
<GetQuote xmlns=\"http://ws.cdyne.com/\">
<StockSymbol xsi:type=\"s:string\">GOOG</StockSymbol>
<LicenseKey xsi:type=\"s:string\">0</LicenseKey>
</GetQuote>
</soap:Body></soap:Envelope>";
var uid = null;
var pass = null;
var attachments = new Array();
var quote = doSOAPRequest( url, action, xml, uid, pass, 60, 60, null, attachments
);
print( "The return value is: " + quote );
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.
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"
xmlns:s0=\"http://ws.cdyne.com/\">
<soap:Body>
<GetQuote xmlns=\"http://ws.cdyne.com/\">
<StockSymbol xsi:type=\"s:string\">GOOG</StockSymbol>
<LicenseKey xsi:type=\"s:string\">0</LicenseKey>
</GetQuote>
</soap:Body></soap:Envelope>";
var uid = null;
var pass = null;
var attachments = new Array();
var quote = doSOAPRequest( url, action, xml, uid, pass, 60, 60, null, attachments,
0 );
print( "The return value is: " + quote );
Syntax
Arguments
script String Yes This argument contains the name of the script you want to
validate.
description String No Use this argument to store any comments you want.
Return values
Throws
None
Description
This method validates the syntax of a JavaScript, and then runs it. The method also displays a message
as to the success or failure of the validation.
Example
l A valid JavaScript
var s = "lib.SCFILEgetTextTest"
execute( s, "Testing execute" );
Syntax
getLog (name)
Arguments
Return values
Description
This method retrieves a logger named according to the value of the name parameter. Loggers are
normally named entities, using dot-separated names such as "lib.test01.func01." The logger object in
JavaScript is an adapter of log4j in the Service Manager server. Logger names and levels follow the rules
of log4j.
Example
log.setLevel('trace');
if (log.isTraceEnabled()){
log.trace('trace message');
if (log.isDebugEnabled()){
log.debug('debug message');
if (log.isInfoEnabled()){
log.info('informatin message');
if (log.isWarnEnabled()){
log.warn('warning message');
if (log.isErrorEnabled()){
log.error('error message');
if (log.isFatalEnabled()){
log.fatal('fatal message');
log.setLevel("trace");
log.setLevel("debug");
log.setLevel("info");
log.setLevel("warn");
log.setLevel("error");
log.setLevel("fatal");
log.setLevel(0); //trace
log.setLevel(1); //debug
log.setLevel(2); // info
log.setLevel(3); // warn
log.setLevel(4); // error
log.setLevel(5); // fatal
4. In the Level field, select a value from the following values: Trace, Debug, Info, Warn, Error, and
Fatal.
5. Click Save.
Note: The logger level will be cleared after the HP Service Manager server is restarted.
Syntax
help( object );
Arguments
object Service Manager- Yes This argument contains the Service Manager-defined
defined JavaScript JavaScript object for which you want a brief
object description.
p
Return values
A string or null.
This method returns a brief text string describing the Service Manager-defined JavaScript object or null
if there is no help available.
Throws
None
Description
This method displays a brief description of a Service Manager-defined JavaScript object. You must use
the print() method to see the help text string.
Example
This example displays the help contents of several Service Manager-defined JavaScript objects.
Syntax
makeSCWebURL( Web tier URL, docEngine, table name, query, hash key seed, action);
Arguments
Web tier String Yes This argument specifies the fully qualified URL to the Service
URL Manager Web tier. This URL must include the http:// protocol
syntax as well as the server name or IP address and
communications port number.
docEngine String Yes This argument specifies that the query should be handled by
the Service Manager Document Engine. This argument does not
accept any other string value.
table String Yes This argument specifies the table where the Document Engine
name should query for records.
query String Yes This argument specifies the Service Manager query you want to
use to search for records. You must URI encode the query string
to prevent special characters from invalidating the URL.
hash key String No This argument specifies an optional string you want to use to
seed create a unique hash key. The hash key seed does not appear in
the final URL produced.
action String Not This argument cannot be used. By default, the URL query always
applicable performs a search operation.
Return values
Description
This method creates a URL query to the Service Manager web tier. It does not convert any special
characters in the URL (such as spaces or quotation marks) to the character code equivalent in URI
format. You can use the encodeURIComponent method to convert any special characters in the URL.
Example
l A valid Service Manager query against the table (for example, incident.id="SD1001")
var url;
var webtier;
var webserver;
var doceng;
var hashkey;
var action;
webserver = "http://pdoref02/sc/index.do";
doceng = "docEngine";
hashkey = "";
action = "";
webtier = makeSCWebURL( webserver,
doceng,
table,
queryURI,
hashkey,
action, "abc");
url=encodeURIComponent(webtier);
print( "Creating URL from information provided..." );
print( "The value of webtier is:\n" + webtier );
print( "The value of url is:\n" + url );
return url;
}
Note: Messages only print to the Service Manager log file when JavaScript is running in the
background.
Syntax
print( output );
Arguments
output String Yes This argument contains the text string or variable value you want
the script to print to the Message View and the sm.log file. You
must enclose literal text strings in quotation marks.
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.
Example
l A text string
Syntax
Arguments
return Integer Yes This argument contains the numeric return code you want the
code script to return upon ending.
Return values
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. Any JavaScript code after the Quit() method is
ignored.
Example
l Prints a message
Syntax
Arguments
return Integer Yes This argument contains the Service Manager global return code
code value you want to convert to a localized string.
Return values
Throws
None
Description
This method converts a Service Manager global return code value into a localized text string.
Example
l Searches the contacts table for any contact name you define in the search variable
var contactName;
Syntax
Arguments
path String Yes This parameter contains the text string or variable value
containing the fully qualified path of the file to be read. You must
enclose literal text strings in quotation marks.
binary String Yes This parameter determines if the file format is binary or text.
Use the string "b" or "B" to read a binary file. Use any other value
to read a text file.
Return values
Description
This method reads the contents of a local file and returns a string object. The file can be in binary
format or text format as determined by the binary argument.
Example
Syntax
setAppMessage(message);
Arguments
message String Yes This argument contains the text string you want to show in the
"message" attribute in the soap response. You must enclose
literal text strings in quotation marks.
Return values
None
Throws
None
Description
This method defines the message returned in the "message" attribute in the soap response.
Example
inputValue = "CompanyA";
setAppMessage("The input value "+inputValue+" is invalid");
Syntax
stripHtml(htmlstr);
Arguments
htmlstr String Yes This argument contains the JavaScript String with HTML tags
that you want to strip out of the string.
Returns
Throws
None
Description
Takes HTML content and strips out the HTML tags and returns the content as text without HTML tags.
Example
Syntax
Arguments
Data
Argument type Required Description
file name String Yes This argument specifies the path and file name of the .zip file to
uncompress.
target String No This argument specifies the target directory. If not specified, the
directory location of the .zip file is used.
Return values
True indicates that the file uncompressed successfully, and any other return value indicates failure.
Throws
None
Description
Example
var rc = uncompressFile("c:/test/upgtest.zip");
if( rc == true )
{
print("uncompress file with one file successfully");
// this will unzip the file to C:/test/test
rc = uncompressFile("c:/test/upgtest.zip", "c:/test/test");
}
else
{
print("Failed to uncompress file.");
}
if(rc == true)
{
print("All tasks are finished.");
}
Syntax
Arguments
File String Yes This argument specifies the file name of the attachment you
want to write out to the file system. You may also use this
argument to specify the destination path of the attachment.
If this argument does not specify a path, Service Manager
creates the attachment in the system working directory.
Application String Yes This argument specifies the application name portion of the
key that Service Manager uses to identify the attachment in
the SYSATTACHMENTS table.
Topic String Yes This argument specifies the topic name portion of the key
that Service Manager uses to identify the attachment in the
SYSATTACHMENTS table.
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.
Return values
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.
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.
Note: If you specify a path, 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.
Example
l An attachment in KM0018
var rc;
rc = writeAttachmentToFile( "c:\\kmdocument.pdf", "kmdocument", "KM0018",
"4462590a062ee0c2101d85c8" );
if ( rc == RC_SUCCESS )
{
print( "kmdocument.pdf successfully created" );
}
else
{
print( "kmdocument.pdf failed " , RCtoString(rc) );
}
Syntax
Arguments
path String Yes This argument contains the text string or variable value
containing the fully qualified path of the file to be written. You
must enclose literal text strings in quotation marks.
mode String No Use the string "b" to write a binary file. Use the string "ba" to
append to a binary file. Use the string "a" to append to a text file.
Use any other string or omit the parameter to write to a text file.
This is the default. The values are case sensitive and only the
values specified are valid.
object String Yes This parameter contains the text string or variable value
containing the data you want to write to a file.
Return values
Description
This method writes the contents of the object parameter to the file specified in the path parameter.
The file can be in binary format or text format as determined by the binary parameter.
Example
filePath = "C:\\users.xml";
isMode = null;
fileObject = userList;
writeToFile( filePath, isMode, fileObject );
Syntax
xmlstring( string );
Arguments
string String No This argument contains the text string or variable value you want
the script to convert to an XML string.
Return values
None
Throws
None
Example
Attachment This object allows you to create attachments for use with doSOAPRequest methods.
Datum This object extracts aggregate types of data (structures or arrays) from a record in
the file object. In Service Manager, a file record is a datum and so is each
component of the record.
SCDatum This object converts a Datum to a SCDatum so that you can test the results by using
the return codes. 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. If
an error occurs and you want a more specific error message, you can create a
SCDatum object from the Datum object.
SCFile This object constructs a new file object. You can use the SCFile object to access,
update, and move between Service Manager files. 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.
SCRecordList This object is an array of Datums that qualify with the query. SCRecordList has two
available functions: getPosition() and getCount().
Query This object returns an array of records. The Query object cannot be used to write
data back to Service Manager.
QueryCond This object defines the conditions of the query. It is used in conjunction with the
Query object to define the parameters for returning data from Service Manager.
XML This object represents an XML document or a node in an XML document. Underlying
the XML object is the Document Object Model (DOM) object. You may find that in
certain instances the XML object in Service Manager is not compliant with the DOM
binding for JavaScript.
XMLDate This object makes it possible to do conversions between three kinds of datetime
values. These include the following constructors:
Note: In ServiceCenter version 6.1, 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.
Constructor
new Attachment();
Arguments
None
Properties
value Binary or Use this property to store the binary or string data of the
String attachment.
len Integer This property contains the file size of the attachment in bytes.
href String Use this property to store the unique identifier for the attachment in
the SOAP request message.
action String Use this property to store the name of action to take with the
attachment in the Service Manager Web Services API. The following
options are available:
name String Use this property to store the file name of the attachment.
type String Use this property to store the MIME type of the attachment.
attachmentType String Use this property to store the attachment type as defined in Service
Manager. If present and the property has a value of "img," then the
attachment must also have a MIME type of "image/gif".
Methods
None
Example
With an Object parameter, the Datum() constructor creates a Service Manager-formatted Datum object
containing the provided record, structure, or array. You must enclose table names and arrays in
quotation marks. You can use the Datum object as a parameter for RTECall routines that expect Service
Manager-formatted parameters.
Constructor
new Datum();
new Datum(Object);
Arguments
Object String The Service Manager table name, record, structure, or array you want to
query or update.
Properties
None
Methods
getMessages() This method returns an array of messages generated by the Document Engine
from a previous SCFile.doAction().
getNext() This method moves to the next record if the object represents a result set.
getPrev() This method moves to the previous record if the object represents a result set.
getFirst() This method moves to the first record if the object represents a result set.
getLast() This method moves to the last record if the object represents a result set.
doSelect() This method makes a query. 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.
isRecord() This method checks if an object represents a current table and has a record.
doDelete() This method is synonymous with the doRemove method. This method simply has a
more intuitive name.
join() This method returns a string of all the entries in the array.
shift() This method returns a string of all the entries in the array.
unshift() This method returns a string of all the entries in the array.
doSave() This method inserts a record if it is new and updates the record if it already exists.
Example
l Selects records from this contacts table starting with the letter B
l A valid query against the contacts table (for example, contact.name # "B")
}
else
print( "No contacts start with B" );
With the HTTP header arguments, the Header() constructor creates a Header object containing the
provided header types and values. You must enclose header types and header values in quotation
marks.
Constructor
new Header();
new Header(Header type, Header value);
Arguments
Argument Description
Properties
None
Methods
None
Example
l Creates a Header object using the Header type and Header value arguments
l A valid header
With an object argument, the SCDatum() constructor creates an SCDatum object containing the
provided record, structure, or array. You must enclose table names and arrays in quotation marks.
This object's methods use the Service Manager-defined global return codes.
Constructor
new SCDatum();
new SCDatum(object);
Arguments
object String The table name, record, structure, or array you want to query or update.
Properties
None
Methods
getMessages() This method returns an array of messages generated by the Document Engine
from a previous SCFile.doAction().
getNext() This method moves to the next record if the object represents a result set.
getPrev() This method moves to the previous record if the object represents a result set.
getFirst() This method moves to the first record if the object represents a result set.
getLast() This method moves to the last record if the object represents a result set.
doSelect() This method makes a query. 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.
isRecord() This method checks if an object represents a current table and has a record.
doDelete() This method is synonymous with the doRemove method. This method simply has a
more intuitive name.
join() This method returns a string of all the entries in the array.
shift() This method returns a string of all the entries in the array.
unshift() This method returns a string of all the entries in the array.
doSave() This method inserts a record if it is new and updates the record if it already exists.
Example
l Selects records from this contacts table starting with the letter B
l A valid query against the contacts table (for example, contact.name # "B")
With an object parameter, the SCFile() constructor creates an SCFile object containing the provided
record, structure, or array. You must enclose table names and arrays in quotation marks.
This object's methods use the Service Manager-defined global return codes.
Constructor
new SCFile();
new SCFile(object);
new SCFile( object, SCFILE_READONLY );
Arguments
object String The table name, record, structure, or array you want to query or update.
SCFILE_ Number Causes the file object to become read-only. This constant is only supported
READONLY as a second parameter, with the file name specified as the first parameter.
Properties
None
Properties
None
Methods
deleteAttachment() This method deletes a specific attachment associated with the current file
record.
deleteAttachments This method deletes all of the attachments associated with the current file
() record.
doCount() This method returns the number of records for the provided query.
doDelete() This method is synonymous with the doRemove() method. This method simply
has a more intuitive name.
doPurge() This method purges a set of records directly in the back-end RDBMS.
doSave() This method inserts a record if it is new and updates the record if it already
exists.
doSelect() This method makes a query. 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.
getAttachment() This method gets a specific attachment associated with the current file
record.
getAttachments() This method gets all of the attachments associated with the current file
record.
getBinary() This method returns the binary representation of a field in a Service Manager
file object.
getFirst() This method moves to the first record if the object represents a result set.
getLast() This method moves to the last record if the object represents a result set.
getLastRC() This method returns the last return code generated by the SCFile and
SCDatum objects.
getMessages() This method returns an array of messages generated by the Document Engine
from a previous doAction().
getNext() This method moves to the next record if the object represents a result set.
getPrev() This method moves to the previous record if the object represents a result
set.
getPurgedRowCount This method retrieves the number of records deleted from a table by the
() doPurge().
insertAttachment() This method creates a new attachment associated with the current file
record.
isRecord() This method checks if an object represents a current table and has a record.
join() This method returns a string of all the entries in the array.
setBinary() This method saves binary data to a field in a Service Manager file object.
setFields() This method causes any subsequent doSelect() calls to fetch only the specified
fields.
setRecord() This method sets the field values from a given XML string.
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.
shift() This method returns a string of all the entries in the array.
unshift() This method returns a string of all the entries in the array.
updateAttachment() This method updates a specific attachment associated with the current file
record.
Example
l Selects records from this contacts table starting with the letter B
l A valid query against the contacts table (for example, contact.name # "B")
Values passed to deleteAttachment() will normally be ones obtained from a previous insertAttachment
(), updateAttachment(), or getAttachments() operation.
Before calling deleteAttachment, you must establish a current record using one of the positioning
methods, such as doSelect(), getNext(), etc.
Syntax
SCFile.deleteAttachment( attachID );
Arguments
deleteAttachment() takes one argument, which is a string containing an attachment ID of the cid:xxxxx
form.
Return values
If successful, deleteAttachment() returns RC_SUCCESS. Otherwise. it returns an error return code. For
example, it returns RC_NO_MORE if the attachment was not found.
Example
function createTestAttachment()
{
var attachmentObj = new Attachment();
attachmentObj.type = "text/plain";
attachmentObj.name = "MyAttachment.txt";
attachmentObj.value = "My text attachment";
return attachmentID;
}
Before calling deleteAttachments, you must establish a current record using one of the positioning
methods, such as doSelect(), getNext(), etc.
Syntax
SCFile.deleteAttachments()
Arguments
Return values
If successful, deleteAttachments() deletes all of the attachments associated with the current record.
Example
f.deleteAttachments();
Syntax
SCFile.doAction( docEngineAction );
Arguments
docEngineAction String This argument specifies the Document Engine action you want the
script to execute on the object. This argument must contain a valid
Service Manager Document Engine action appropriate for the
Service Manager object.
Return values
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.
Example
l The "Use Resolved Status?" option enabled in the Incident Management Environment record
var numberValue;
var callbackContact;
var categoryValue;
var assignmentValue;
var descriptionValue;
var actionType;
var resultionCodeValue;
var resolutionValue;
numberValue = "IM11121"
callbackContact = "ADMINISTRATOR, SYSTEM";
categoryValue = "network";
assignmentValue = "HELPDESK";
descriptionValue = null;
interactionID = insertIncident( numberValue, callbackContact, categoryValue,
assignmentValue, descriptionValue );
actionType = "resolve";
resultionCodeValue = "Advice & Guidance";
resolutionValue = null;
resolveIncident( interactionID, actionType, resultionCodeValue, resolutionValue );
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().
Syntax
SCFile.doCount( "query" );
Arguments
query String This argument specifies the query you want to use to search for Service
Manager records. You must use the slash character to escape out quotation
marks and any special characters restricted from JavaScript.
Return values
Example
var contactName;
{
print( "Could not count records. " + RCtoString( rc ) );
return -1;
}
}
Syntax
SCFile.doDelete();
Arguments
Return values
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.
Example
l Searches the probsummary table for any interaction record you define in the search variable
var numberValue;
var rc = interactionRecord.doDelete();
if ( rc == RC_SUCCESS )
{
print( "Success. Removed record " + interactionRecord.getText() );
return interactionRecord
}
else
{
print( "Could not remove record. " + RCtoString( rc ) );
return null
}
}
numberValue = "IM11111"
removeInteraction( numberValue );
Syntax
SCFile.doInsert();
Arguments
Return values
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.
Example
l Searches the probsummary table for any incident record you define in the search variable
l A valid value for the callback.contact field (for example, "ADMINISTRATOR, SYSTEM")
var numberValue;
var callbackContact;
var categoryValue;
var descriptionValue;
numberValue = "IM11112"
callbackContact = "ADMINISTRATOR, SYSTEM";
categoryValue = "network";
insertContact( numberValue, callbackContact, categoryValue, descriptionValue );
The doDelete() method requires you to select a list of records from the database, iterate over each
record in the list and perform a “delete” on a record by record basis. When the delete is performed,
Service Manager respects workflow actions as defined in record level triggers. The doPurge() method
reduces the overhead of much of this by sending one SQL statement to the RDBMS to purge the data. As
a result of the RDBMS processing the record set purge in one transaction, Service Manager does not
have control to process record level triggers on the data being purged. Standard Service Manager
trigger processing will not occur on these records.
You should use doPurge() only when you need to quickly delete a large record set from a single Service
Manager table, and it does not matter whether Service Manager triggers are processed.
Caution: Purging data has some risks. Use doPurge() with caution. It is the equivalent of issuing a
SQL statement to the RDBMS such as, DELETE FROM "SM_TABLE_NAME" WHERE "COLOUMN_
NAME" = 'value'.
l Data referential integrity could be an issue by purging data that is related to other types of Service
Manager data. This method does not execute normal record level workflow processing in the
applications layer. When you turn off triggers and run doPurge(), you will bypass normal workflow
processing in addition to record level triggers.
l No Service Manager audit or other tracking is available to indicate changes made by doPurge().
Consider coding your own audit mechanism.
You can retrieve the number of records deleted from a table by doPurge() by using the JavaScript
method: getPurgedRowCount()
Note: When you use doPurge(), Service Manager deletes a set of records. This causes a delete to
the back-end database. When Service Manager attempts to delete a large set of records, the
database could run out of space for this activity and cause an error. 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. If you encounter such an error, please contact your database
administrator and ask them to increase the size available for this purpose.
SQL Server SQL State: 42000-9002 Message: [Microsoft][SQL Native Client][SQL Server]The
transaction log for database '%' is full
Syntax
SCFile.doPurge( query );
Arguments
Argument Description
This argument specifies the query you want to use to search for Service Manager
records. You must use the slash character to escape out quotation marks and any
special characters restricted from JavaScript. Boolean values (true or false) or a
QueryCond object are also acceptable.
Return values
l Calling doPurge() with one (or more) invalid (or unmapped) fields.
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; it will return RC_SUCCESS. However, in this case, it will default
to a “false” query and no records will be deleted.
l Calling doPurge() with an SCFile object which has “delete” triggers defined and enabled.
Limitations
l The table must not have “delete” triggers defined and enabled
Example
Syntax
SCFile.doRemove();
Arguments
Return values
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.
Example
l Searches the probsummary table for any interaction record you define in the search variable
var numberValue;
numberValue = "IM11111"
removeInteraction( numberValue );
Syntax
SCFile.doSave();
Arguments
Return values
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.
Example
l Searches the contacts table for any contact name you define in the search variable
l A valid field value update (for example, set the "user.type" field to "site")
var contactName;
For performance improvement, you can use SCFile.setFields method to limit the fields that doSelect
returns from the database.
Note: This method is used for retrieving normal data, not for retrieving attachments. If you use this
method to retrieve attachments, you could corrupt the SYSATTACHMENTS table. If you need to
retrieve attachments, use one of the following functions to get the attachments associated with
the current file record: SCFile.getAttachment(attachID) or SCFile.getAtttachments().
Syntax
SCFile.doSelect( query );
Arguments
query String This argument specifies the query you want to use to search for Service
Manager records. You must use the slash character to escape out quotation
marks and any special characters restricted from JavaScript.
Return values
An SCFile object containing records and RC_SUCCESS or one of the other global return code values.
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.
Example
l Searches the contacts table for any contact name you define in the search variable
var contactName;
Syntax
SCFile.doUpdate();
Arguments
Return values
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.
Example
l Searches the contacts table for any contact name you define in the search variable
l A valid field value update (for example, set the "user.type" field to "site")
var contactName;
Values passed to getAttachment() will normally be ones obtained from a previous insertAttachment(),
updateAttachment(), or getAttachments() operation.
Before calling getAttachment, you must establish a current record using one of the positioning
methods, such as doSelect(), getNext(), etc.
Syntax
SCFile.getAttachment( attachID );
Arguments
getAttachment() takes one argument, which is a string containing an attachment ID of the cid:xxxxx
form.
Return values
Example
Before calling getAttachments, you must establish a current record using one of the positioning
methods, such as doSelect(), getNext(), etc.
Syntax
SCFile.getAttachments()
Arguments
Return values
If successful, getAttachments() returns an array of attachment objects. The array will be empty if there
are no attachments for the record. The attachment objects retrieve here will only contain metadata.
The Attachment.value will be NULL. To get each attachment's binary data, you will need to use
SCFile.getAttachment(attachID) method where attachID contains the href property of the attachment
object.
Example
print( attachments.length );
for ( var attachment in attachments )
{
print( attachments[ attachment ].name );
}
Syntax
SCFile.getBinary (fieldName);
Arguments
fieldName String This argument specifies the name of a field from which you want to extract
the binary data.
Return values
The method returns a JS object that contains the binary data of the field.
Example
var rc = bb.doSelect("true");
attachmentObj.value = bb.getBinary("att_attachment")
attachmentObj.name = bb.att_filename;
attachmentObj.type = "excel";
Syntax
SCFile.getFirst();
Arguments
Return values
An SCFile object containing the first record and RC_SUCCESS or one of the other global return code
values.
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.
Example
l Queries the contacts table for any contact name you define in the search variable
var contactQuery;
Syntax
SCFile.getLast();
Arguments
Return values
An SCFile object containing the last record and RC_SUCCESS or one of the other global return code
values.
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.
Example
l Queries the contacts table for any contact name you define in the search variable
var contactQuery;
print( "Could not find contacts starting with " + query + ". " + RCtoString(
findContact ) );
return null
}
}
contactQuery = "H";
findLastContact( contactQuery );
contactQuery = "F";
findLastContact( contactQuery );
Syntax
SCFile.getLastRC();
Arguments
Return values
The method returns the most recent global return code value generated by the SCFile object.
Example
system.vars.$L_file.doInsert();
var rc = getLastRC();
if ( rc == RC_SUCCESS )
{
print( "Insert of document succeeded" );
}
Syntax
SCFile.getMessages();
Arguments
Return values
Example
l Uses the Document Engine add to create a new incident record from variable values.
var numberValue;
var callbackContact;
var categoryValue;
var assignmentValue;
var descriptionValue;
var actionType;
var resultionCodeValue;
var resolutionValue;
var rc = newIncident.doAction('add');
if ( rc == RC_SUCCESS )
{
print( "Success. Created new record " + newIncident.getText() );
return newIncident.number
}
else
{
print( "Could not create record. " + RCtoString( rc ) );
print( "Reason: "+ newIncident.getMessages() );
return null
}
}
numberValue = "IM11121"
callbackContact = "ADMINISTRATOR, SYSTEM";
categoryValue = "network";
assignmentValue = "HELPDESK";
descriptionValue = null;
interactionID = insertIncident( numberValue, callbackContact, categoryValue,
assignmentValue, descriptionValue );
Output
Category specified is invalid. Reason: Category specified is invalid. Could not
create record. Validation failed creating new incident record...
Syntax
SCFile.getNext();
Arguments
Return values
An SCFile object containing the next record and RC_SUCCESS or one of the other global return code
values.
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.
Example
l Queries the contacts table for any contact name you define in the search variable
var contactQuery;
contactQuery = "F";
findNextContact( contactQuery );
Syntax
SCFile.getPrev();
Arguments
Return values
An SCFile object containing the previous record and RC_SUCCESS or one of the other global return code
values.
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.
Example
l Queries the contacts table for any contact name you define in the search variable
var contactQuery;
return null
}
}
contactQuery = "H";
findPrevContact( contactQuery );
Syntax
SCFile.getPurgedRowCount();
Arguments
Return values
l If successful, getPurgedRowCount() returns the number of records deleted by the last successful
doPurge() call (which returned RC_SUCCESS). This value can be 0 if no records were deleted.
l If getPurgedRowCount() is not able to retrieve the record count it will return -1.
The value returned by getPurgedRowCount is unaffected by any SCFile method call other than doPurge.
It is also unaffected by a failed call to doPurge (returned RC_ERROR).
Example
if ( purgedCount >= 0 )
{
print(purgedCount + " records have been purged");
}
else
{
print("Could not retrieve purged record count");
}
}
else
{
print ("doPurge failed");
}
Replace any periods in the name of array_field_name with underscores. For example, you must
convert the Service Manager array field update.action to update_action when querying it from
JavaScript.
Syntax
SCFile.Datum_object.getSize();
Arguments
Return values
A number and RC_SUCCESS or one of the other global return code values.
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.
Example
l Searches the probsummary table for any incident record you define in the search variable
l Attempts to get the size of the returned SCFile object (the result is always zero)
l Displays the contents of the action field (the action field contains Service Manager array data)
l Displays the size of the action field using the Service Manager getSize() method
l Converts the SCFile object into a JavaScript array using the Service Manager toArray() method
l Displays the size of the new JavaScript array using the core JavaScript length property
var incidentQuery;
incidentQuery = "IM1005";
findIncidents( incidentQuery );
Syntax
SCFile.getText();
Arguments
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, or returns one of the error global return code values if the method cannot return a string.
Example
l Searches the contacts table for any contact name you define in the search variable
var contactName;
else
{
print( "Could not find contact. " + RCtoString( findContact ) );
return null
}
}
Syntax
SCFile.getType();
Arguments
Return values
A data type and RC_SUCCESS or one of the other global return code values.
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, if the method cannot determine the data type.
Example
l Searches the probsummary table for any incident record you define in the search variable
l Returns the data type of the incident record object using the getType() method
l Returns the data type of the action field object using the getType() method
l Returns the data type of the category field object using the core JavaScript type property
var incidentQuery;
incidentQuery = "IM1001";
findTypes( incidentQuery );
Syntax
SCFile.getXML();
Arguments
Return values
An XML object and RC_SUCCESS or one of the other global return code values.
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.
Example
l Searches the contacts table for any contact name you define in the search variable
var contactName;
return null
}
}
Syntax
SCFile.insertAttachment( attachObj );
Arguments
Attachment objects can be obtained via Web Services calls or constructed by JavaScript code.
Required properties
Attachment.name: This is a string containing the name of the attachment, for example, foo.txt or
foo.pdf.
Attachment.type: This is a string containing the MIME type of the attachment, such as text/plain or
application/pdf.
Attachment.value: This is a binary string containing the actual attachment data. One way to obtain such
data is by using the readFile() global method.
The "href" property of the attachment object should not be set for an insert operation. Any value
supplied will be ignored. Attachment ID values are assigned by the server when attachments are
inserted or updated.
Return values
If successful, insertAttachment() returns a string of the form cid:xxxxxx containing the attachment ID
for the inserted attachment.
Example
attachmentObj.type = "text/plain";
attachmentObj.name = "MyAttachment.txt";
attachmentObj.value = "This is a test text attachment";
Syntax
SCFile.isRecord();
Arguments
Return values
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.
Example
l Searches the probsummary table for any incident record you define in the search variable
l Displays the incident record object and the results of the isRecord() method
var incidentQuery;
incidentQuery = "IM1005";
findTypes( incidentQuery );
incidentQuery = "incident";
findTypes( incidentQuery );
Syntax
SCFile.join();
Arguments
Return values
A string.
Example
l Searches the probsummary table for any incident record you define in the search variable
var incidentID;
function findIncident( id )
{
print( "Searching for Incident record: " + id + "..." );
var incidentFile = new SCFile( "probsummary" );
var rc = incidentFile.doSelect( "number=\"" + id + "\"" )
if ( rc == RC_SUCCESS )
{
print( "Success. found Incident record:\n" + incidentFile.getText() );
print( "Displaying the contents of the action field as an object: " +
incidentFile.action );
print( "Displaying the contents of the action field with join() method: " +
incidentFile.action.join() );
return incidentFile
}
else
{
print( "Could not find Incident record. " + RCtoString( rc ) );
return null
}
}
incidentID = "IM1010";
findIncident( incidentID );
Syntax
SCFile.JSDate( dataType );
Arguments
dataType String This argument specifies the data type of a field in an SCFile object.
Return values
None
Example
l Searches the probsummary table for any incident record you define in the search variable
l Displays the incident record and the value of the open.time field
l Creates an SCDatum object containing the number of milliseconds you want to convert
l Converts the open.time field into an SCDatum object (by default the open.time field data is in
Service Manager's date/time data type)
l A valid incident record with a value in the open.time field (for example, "IM1010")
var incidentID;
function findIncident( id )
{
print( "Searching for incident: " + id + "..." );
var incidentFile = new SCFile( "probsummary" );
var f = incidentFile.doSelect( "number=\""+ id + "\"" );
if ( f == RC_SUCCESS )
{
print( "Success. found " + id + " in incident record:\n" + incidentFile.getText()
);
print( "The value of the open.time field is: " + incidentFile.open_time );
print( "Converting open.time to an SCDatum object..." );
var dat = new SCDatum( incidentFile.open_time );
print( "The new SCDatum object is: " + dat );
print( "Converting the SCDatum object to a JSDate..." );
var j = dat.JSDate();
print( "The converted SCDatum object is: " + j );
return incidentFile
}
else
{
print( "Could not find incident record. " + RCtoString( f ) );
return null
}
}
incidentID = "IM1010";
findIncident( incidentID );
Note: Replace any periods in the name of array_field_name with underscores. For example, you
must convert the Service Manager array field update.action to update_action when querying it
from JavaScript.
Syntax
SCFile.array_field_name.length();
Arguments
Return values
A number and RC_SUCCESS or one of the other global return code values.
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.
Example
l Searches the probsummary table for any incident record you define in the search variable
l Attempts to get the size of the returned SCFile object (the result is always zero)
l Displays the contents of the action field (the action field contains Service Manager array data)
l Displays the size of the action field using the Service Manager length() method
l Converts the SCFile object into a JavaScript array using the Service Manager toArray() method
l Displays the size of the new JavaScript array using the core JavaScript length property
var incidentQuery;
print( "Running the getSize() method on the returned SCFile object produces the
following result: " + objectSize );
var actionText = incidentFile.action;
print( "The contents of the action field is:\n" + actionText );
var actionSize = incidentFile.action.getSize();
print( "The size of the action field is: " + actionSize );
print( "Converting the SCFile object to a JavaScript array..." );
var incidentArray = incidentFile.toArray();
print( "The new JavaScript array is:\n" + incidentArray );
var arraySize = incidentArray.length;
print( "The size of the converted array is: " + arraySize );
return incidentFile;
}
else
{
print( "Could not find incident records starting with " + query + ". " +
RCtoString( findIncident ) );
return null
}
}
incidentQuery = "IM1005";
findIncidents( incidentQuery );
Syntax
SCFile.pop();
Arguments
Return values
A string.
Example
l Searches the probsummary table for any incident record you define in the search variable
l Adds an item to the end of the array and displays the total number of elements in the array
l Removes an item from the end of the array and displays the array item removed
var incidentID;
function findIncident( id )
{
print( "Searching for Incident record: " + id + "..." );
var incidentFile = new SCFile( "probsummary" );
var rc = incidentFile.doSelect( "number=\"" + id + "\"" )
if ( rc == RC_SUCCESS )
{
print( "Success. found Incident record:\n" + incidentFile.getText() );
print( "Converting the action field to a JavaScript array..." );
var a = incidentFile.action.toArray();
print( "The action field array contains the following: " + a );
print( "Pushing new array entry..." );
var addOne = a.push( "First array item" );
print( "The number of items in the array are: " + addOne );
print( "The action field array contains the following: " + a );
print( "Popping new array entry..." );
var removeOne = a.pop();
print( "The array item removed was: " + removeOne );
print( "The action field array contains the following: " + a );
return incidentFile;
}
else
{
print( "Could not find Incident record. " + RCtoString( rc ) );
return null
}
}
incidentID = "IM1010";
findIncident( incidentID );
Syntax
SCFile.push( arrayItem );
Arguments
arrayItem String This argument specifies the array item you want to add to a JavaScript
array.
Return values
A number.
Example
l Searches the probsummary table for any incident record you define in the search variable
l Adds an item to the end of the JavaScript array and prints the total number of items in the array
var incidentID;
function findIncident( id )
{
print( "Searching for Incident record: " + id + "..." );
var incidentFile = new SCFile( "probsummary" );
var rc = incidentFile.doSelect( "number=\"" + id + "\"" )
if ( rc == RC_SUCCESS )
{
print( "Success. found Incident record:\n" + incidentFile.getText() );
print( "Converting the action field to a JavaScript array..." );
var a = incidentFile.action.toArray();
print( "The action field array contains the following: " + a );
print( "Pushing new array entry..." );
var addOne = a.push( "First array item" );
print( "The number of items in the array are: " + addOne );
print( "The action field array contains the following: " + a );
print( "Pushing new array entry..." );
var addTwo = a.push( "Second array item" );
print( "The number of items in the array are: " + addTwo );
print( "The action field array contains the following: " + a );
return incidentFile;
}
else
{
print( "Could not find Incident record. " + RCtoString( rc ) );
return null
}
}
incidentID = "IM1010";
findIncident( incidentID );
Syntax
Arguments
fieldName String The name of a field in which you want to save the binary data.
binaryObj String The name of a JS object that contains the binary data.
Return values
RC_SUCCESS or one of the other global return code values. The method returns RC_SUCCESS if the
method successfully saves binary data to a Service Manager file object or returns one of the error
global return code values if the method cannot save binary data to a Service Manager file object.
Example
rc = f.doSelect('contact.name#"AARON"');
b.name = attachmentObj[0].name;
b.setBinary ("data",attachmentObj[0].value );
rc = b.doSave();
This method is supported for read-only objects. You can make an object read-only specifying the
SCFILE_READONLY argument in the SCFile constructor.
Calling setFields with no parameters will reset any previously specified fields. Any subsequent calls to
doSelect() will fetch all fields (a SELECT * will be performed).
Note: Do not reference fields in the object that have not been specified in the setFields method. If
you reference field in the object that has not been specified in the setFields method, the field
appears as “null” whether the database has data in that column or not.
Syntax
SCFile.setFields( field-array );
SCFile.setFields( field-string );
SCFile.setFields( );
Arguments
Data
Argument type Description
field- Array A javascript array of field name strings; for example, setFields(new Array
array (“contact.name”, “user.id”)).
Return values
l Calling setFields with an invalid argument type (not a string or an array of strings)
l Calling setFields with one (or more) invalid fields. (The method performs a basic validation on the
field names to ensure they exist in the DBDICT.)
When the method fails, it has no effect, and the last successful call to setFields stays in effect. It issues
a warning in the sm.log file.
Limitations
l The main unique key fields of the dbdict are always selected from the table (and for join tables,
from each underlying table) even if not explicitly specified in setFields.
l Since only basic field validation is performed in the setFields method, there are certain situations
when the call can be successful (returns RC_SUCCESS) but a “SELECT *” is still performed.
n All specified fields exist in the DBDICT but at least one field is an alias field, a structure name or
an unmapped field (which are unsupported).
n LDAP is the primary data source for the table. (LDAP mapped fields are supported as long as LDAP
is not the primary data source.)
Example usage
l Takes the prefix of a contact name and returns a list of contacts that start with the specified prefix.
if ( rc != RC_SUCCESS )
{
print( "setFields() failed, will revert to SELECT * (see log for more info)"
);
return null;
}
Syntax
SCFile.setOrderBy(sortFields, sortSeqs);
Arguments
sortFields Array A javascript array of field name string, for example, newArray
("name","company").
Required properties
This method requires two parameters of the data type of array. The two arrays must be of the same
length. Calling setOrderBy() with parameters of uneven length of arrays or non-array data results in
failure return status.
Return values
l Calling setOrderBy() with an invalid argument type (not an array) for either argument.
l Calling setOrderBy() with one (or more) invalid fields. (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.
Limitations:
l Fields from a join file should not be within a structure in the dbdict.
Example
Note: If you are running setOrderBy() on a single array, these samples show how to define a single
sort sequence for descending sort order.
l Takes two fields, name and company, from the operator table, and sorts the company field by
descending order, then the name field by ascending order.
l Records in the operator table that have various company and name fields.
if ( setOrderByRC != RC_SUCCESS )
{
print( "ERROR: setOrderBy failed, RC=" + RCtoString( setOrderByRC ) );
return RC_ERROR;
}
var selectRC = fRec.doSelect( "true" );
if ( selectRC != RC_SUCCESS )
{
print( "ERROR: doSelect OrderBy failed, RC=" + RCtoString( selectRC ) );
return RC_ERROR;
}
do
{
fCount++;
}
while (fRec.getNext() == RC_SUCCESS);
print( "doSelect select column Orderby test: table processed = " + table );
print( "doSelect select column Orderby test: fields processed = " + fields );
print( "doSelect select column Orderby test: sort order = " + sortOrder);
print( "doSelect select column Orderby test: count = " + fCount );
print( "doSelect select column Orderby test: End time is " + timeAfter );
print( "doSelect select column Orderby test: Elapsed time is " + (timeAfter -
timeBefore) + " milliseconds" );
return RC_SUCCESS;
}
Syntax
SCFile.setType( dataType );
Arguments
dataType Number This argument specifies the Service Manager data type for the object. See
"Data types" on page 17.
Return values
None
Example
l Creates an SCDatum object containing the number of milliseconds you want to convert
l Sets the data type of the SCDatum object to a Service Manager date/time type
var millisecs;
millisecs = 1234567890;
findDateTime( millisecs );
Syntax
SCFile.setRecord();
Argument
setRecord("xmlstring");
Example
}
}
updateContactPhoneFromXML(contactName, xmlString);
Note:
l The input XML string should follow the Service Manager File schema.
l You cannot use setRecord() to set values for files that contain binary data. For example,you
cannot use setRecord() for displaycache, code, SYSATTACHMENTS files.
Syntax
SCFile.setValue( newValue );
Arguments
newValue String This argument specifies the new value you want the Service Manager object
to have. You must use the slash character to escape out quotation marks
and any special characters restricted from JavaScript.
Return values
None
Example
l Searches the probsummary table for any incident record you define in the search variable
l Sets the value of the action field to any value you define in the input variable
l A valid incident record with a value in the action field (for example, "IM1010")
l A valid action field value update (for example, set the action field to "New description")
var incidentID;
var newValue;
incidentID = "IM1010";
newValue = "New description";
findIncident( incidentID, newValue );
Syntax
SCFile.shift();
Arguments
Return values
A string.
Example
l Searches the probsummary table for any incident record you define in the search variable
l Adds an item to the end of the array and displays the total number of elements in the array
l Removes an item from the beginning of the array and displays the array item removed
var incidentID;
function findIncident( id )
{
print( "Searching for Incident record: " + id + "..." );
var incidentFile = new SCFile( "probsummary" );
var rc = incidentFile.doSelect( "number=\"" + id + "\"" )
if ( rc == RC_SUCCESS )
{
incidentID = "IM1010";
findIncident( incidentID );
Syntax
SCFile.toArray();
Arguments
Return values
A JavaScript array and RC_SUCCESS or one of the other global return code values.
Example
l Searches the probsummary table for any incident record you define in the search variable
var incidentID;
function findIncident( id )
{
print( "Searching for Incident record: " + id + "..." );
var incidentFile = new SCFile( "probsummary" );
var rc = incidentFile.doSelect( "number=\"" + id + "\"" )
if ( rc == RC_SUCCESS )
{
print( "Success. found Incident record:\n" + incidentFile.getText() );
print( "Converting the action field to a JavaScript array..." );
var a = incidentFile.action.toArray();
print( "The action field contains the following " + a );
return incidentFile
}
else
{
print( "Could not find Incident record. " + RCtoString( rc ) );
return null
}
}
incidentID = "IM1010";
findIncident( incidentID );
Syntax
SCFile.unshift( arrayItem );
Arguments
arrayItem String This argument specifies the array item you want to add to a JavaScript
array.
Return values
A number.
Example
l Searches the probsummary table for any incident record you define in the search variable
l Adds an item to the beginning of the JavaScript array and prints the total number of items in the
array
var incidentID;
function findIncident( id )
{
print( "Searching for Incident record: " + id + "..." );
var incidentFile = new SCFile( "probsummary" );
var rc = incidentFile.doSelect( "number=\"" + id + "\"" )
if ( rc == RC_SUCCESS )
{
print( "Success. found Incident record:\n" + incidentFile.getText() );
print( "Converting the action field to a JavaScript array..." );
var a = incidentFile.action.toArray();
print( "The action field array contains the following: " + a );
print( "Unshifting array one entry..." );
var unshifting = a.unshift( "First array item" );
print( "The number of items in the array are: " + unshifting );
print( "The action field array contains the following: " + a );
return incidentFile;
}
else
{
print( "Could not find Incident record. " + RCtoString( rc ) );
return null
}
}
incidentID = "IM1010";
findIncident( incidentID );
Syntax
SCFile.updateAttachment( attachObj );
Arguments
Return values
If successful, updateAttachment() returns a string of the form cid:xxxxxx containing the new
attachment ID for the attachment. Otherwise, it returns NULL.
Example
function createTestAttachment()
{
var attachmentObj = new Attachment();
attachmentObj.type = "text/plain";
attachmentObj.name = "MyAttachment.txt";
attachmentObj.value = "My text attachment";
return attachmentID;
}
attachmentObj.name = newName;
attachmentObj.value = newValue;
Constructor
Arguments
table String The name of the Service Manager table. For example, probsummary.
name
QueryCond object Service Manager JavaScript object QueryCond which defines the SC query to
be executed.
Properties
None.
Methods
getCount() This method returns the total number of records in the SCRecordList.
getPosition() This method returns the last position in the record list that has been accessed. .
Example
l valid location(s)
for (i in x ) {
print(x[i].location_name + " is the " + x.getPosition() + " record in the record
list." );
}
Syntax
SCRecordList.getCount();
Arguments
Return values
Example
l valid location(s)
Syntax
SCRecordList.getPosition();
Arguments
Return values
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
l valid location(s)
for (i in x ) {
print(x[i].location_name + " is the " + x.getPosition() + " record in the record
list." );
}
The XML() constructor creates an empty XML object where you can store and manipulate XML
documents.
This object's methods do not use the Service Manager-defined global return codes.
Constructor
new XML();
Arguments
None
Properties
None
Methods
getParentNode Returns an XML object representing the parent node of the current node.
getFirstChildElement Returns an XML object representing the first child node of the current node.
getNextSiblingElement Returns an XML object representing the next node at the same level in the
Document Object Model (DOM) tree as the current node.
getFirstAttribute Returns an XML object representing the first attribute of the current node.
getNextAttribute Returns an XML object representing the next attribute of the current node.
getNodeName Returns a string representing the name of the current element or attribute.
getName Returns a string representing the name of the current element or attribute.
getQualifiedName Returns a string representing the name of the current element or attribute
including any namespace value.
getPrefix Returns a string representing the namespace value of the current element
or attribute.
getNodeType Evaluates an XML object and returns an integer representing the XML DOM
type of the current element or attribute.
isDocumentElement Returns true if the current element is the DOM document element.
getDocumentElement Creates an XML object containing the document element and all child
elements from an XML object or XML string.
addAttribute Inserts an XML attribute and attribute value into the current element.
Example
/* Use setContent to make the XML object read and parse the XML file
* If the setContent method fails, print an error message */
if ( ! xmlObj.setContent( xmlFile, true ) )
{
print( "setContent failed. Unable to parse xml: " + xmlFile );
}
Syntax
Arguments
AttributeName String This argument specifies the text string you want the script to use as
the XML attribute name. The string argument must contain
characters valid for an XML element (for example, the string cannot
include the characters < or >).
AttributeValue String This argument specifies the text string you want the script to use as
the XML attribute value. This argument must contain characters valid
for an XML element (for example, the string cannot include the
characters < or >).
Return values
If successful, the method returns the updated XML element. Otherwise, it returns null.
Example
This example adds a new attribute and attribute value to any element you select from an XML
document.
Syntax
XML.addElement( String );
Arguments
String String This argument specifies the text string you want the script to use as the XML
element name. The string argument must contain characters valid for an
XML element (for example, the string cannot include the characters < or >).
Return values
The method returns an XML object containing the new element or returns null if the method cannot add
the element.
Example
This example adds a child element to any element you select in an XML document.
var searchResults;
var printResults;
var NewNodeName;
}
else
{
print( "Cannot find " + target );
return null
}
}
Syntax
XML.appendNode( name );
Arguments
name String This argument specifies the XML node name you want to append to the
target XML object. The string argument must contain characters valid for
XML (for example, the string cannot include the characters < or > except as
XML entities such as < and >).
Return values
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.
Example
NewNodeType = 1;
NewNodeName = "node";
NewNodeValue = "test";
TargetNode = "document";
appendNewNode( NewNodeType, NewNodeName, NewNodeValue, XMLObject, TargetNode );
Syntax
Arguments
type Integer This argument specifies the XML DOM node type for the node you want the
script to create. This method only accepts XML DOM types 1, 2, and 3. See
the W3C Web site for a complete listing of XML DOM node-types by integer.
name String This argument specifies the text string you want the script to add as the
XML node name. The string argument must contain characters valid for XML
(for example, the string cannot include the characters < or > except as XML
entities such as < and >).
value String This argument specifies the text string you want the script to add as the
XML node value. The string argument must contain characters valid for XML
(for example, the string cannot include the characters < or > except as XML
entities such as < and >).
Return values
The method returns an XML object containing the new node or returns null if the method cannot
create the node.
Example
NewNodeType = 1;
NewNodeName = "node";
NewNodeValue = "test";
createNewNode( NewNodeType, NewNodeName, NewNodeValue, XMLObject );
NewNodeType = 2;
NewNodeName = "id";
NewNodeValue = "test";
createNewNode( NewNodeType, NewNodeName, NewNodeValue, XMLObject );
NewNodeType = 3;
NewNodeName = null;
NewNodeValue = "Text node";
createNewNode( NewNodeType, NewNodeName, NewNodeValue, XMLObject );
Syntax
XML.getAttributeNode( Attribute );
Arguments
Attribute String This argument specifies the XML attribute you want the script to return.
Return values
The method returns an XML object containing the target attribute, or returns null if the method
cannot find the target attribute in the current element.
Example
This example searches for a particular attribute of any given element in an XML document.
node = node.getParentNode();
if ( node == null || topNodeName == node.getNodeName() )
{
return null;
}
childNode = node.getNextSiblingElement();
}
node = childNode;
}
else
{
node = childNode;
}
}
return node;
}
}
}
Syntax
XML.getAttributeValue( Attribute );
Arguments
Attribute String This argument specifies the XML attribute whose value you want the script
to return.
Return values
A string or null.
The method returns the string value of the target attribute or returns null if the method cannot find
an attribute value.
Example
This example searches for the attribute value of any given element in an XML document.
return attributeFound
}
else
{
print( "Cannot find " + target );
return null
}
}
Note: You cannot use this method on objects that you have converted using the toXMLString
method.
Syntax
XML.getDocumentElement();
Arguments
Return values
If successful, 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.
l A valid XML object (for example, the list of currently logged on users stored in system.users)
if ( DocElem != null )
{
var DocElemName = DocElem.getNodeName();
print( "Success. Found the document element " + DocElemName + " in the following
object: \n" + document );
return DocElem
}
else
{
print( "Error. Did not find document element in the following object: \n" +
document );
return null
}
}
Syntax
XML.getFirstAttribute();
getFirstAttribute(Element)
Arguments
Element 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.
Return values
The method returns an object representing the first attribute of the current node or returns null if the
XML object has no attributes.
Example
This example displays the first attribute of any element you select. The example allows you to select an
element from two different input sources.
{
node = node.getParentNode();
if ( node == null || topNodeName == node.getNodeName() )
{
return null;
}
childNode = node.getNextSiblingElement();
}
node = childNode;
}
else
{
node = childNode;
}
}
return node;
}
Syntax
XML.getFirstChildElement();
getFirstChildElement(Element)
Arguments
Element 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.
Return values
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. The example allows you to
select an element from two different input sources.
/* Create a function to find the first child element of the target element */
function findFirstChild( sourceObject, targetNode )
{
var startingNode = findTargetElement( sourceObject, targetNode )
var firstChild = startingNode.getFirstChildElement();
if ( firstChild != null )
{
return firstChild
}
else
{
return null
}
}
/* Create a function to print the first child element of the target element */
function printChildResults( target, searchResult )
{
if ( searchResult != null )
{
var childName = searchResult.getNodeName();
print( "The first child element of " + target + " is: " + childName );
}
else
{
print( "There are no child elements of " + target );
}
}
Syntax
XML.getName();
Arguments
Return values
A string or null.
The method returns a string representing the name of the current element or attribute. It returns null
if the current node has no name.
Example
This example displays the names of the elements and attributes in an XML document.
}
var nodeValue = elem.getNodeValue();
if ( typeof nodeValue == "string" && nodeValue.length > 0 )
{
print( "Element value of " + elem.getName() + " is: " + nodeValue );
}
Syntax
XML.getNextAttribute();
getNextAttribute(Element)
Arguments
Element 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.
Return values
The method returns an object representing the first attribute of the current node or returns null if the
XML object has no attributes.
Example
This example displays the first attribute of any element you select. The example allows you to select an
element from two different input sources.
{
return null;
}
childNode = node.getNextSiblingElement();
}
node = childNode;
}
else
{
node = childNode;
}
}
return node;
}
if ( searchResult != null )
{
var attributeName = searchResult.getNodeName();
print( "The first attribute of " + target + " is: " + attributeName );
return searchResult
}
else
{
print( "There are no attributes of " + target );
return null
}
}
TargetNode = "child2"
XMLSource = XMLString
print( "The target element we are looking for is: " + TargetNode );
searchResults = findTargetElement( XMLSource, TargetNode );
printFindResults( TargetNode, searchResults );
attributeResults = findFirstAttribute( XMLSource, TargetNode );
printAttributeResults( TargetNode, attributeResults );
findNextAttribute( XMLSource, TargetNode );
Syntax
XML.getNextSiblingElement();
getNextSiblingElement(Element)
Arguments
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.
Return values
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.
Example
This example displays the next sibling element of any element you select. The example allows you to
select an element from two different input sources.
/* Create a function to find the next sibling element of the target element */
function findNextSibling( sourceObject, targetNode )
{
var startingNode = findTargetElement( sourceObject, targetNode )
var nextSibling = startingNode.getNextSiblingElement();
if ( nextSibling != null )
{
return nextSibling
}
else
{
return null
}
}
TargetNode = "child3"
XMLSource = XMLFile
print( "The target element we are looking for is: " + TargetNode );
searchResults = findTargetElement( XMLSource, TargetNode );
printFindResults( TargetNode, searchResults );
siblingResults = findNextSibling( XMLSource, TargetNode );
printSiblingResults( TargetNode, siblingResults );
Syntax
XML.getNodeName();
Arguments
Return values
A string or null.
The method returns a string representing the name of the current element or attribute or returns null
if the current node has no name.
Example
This example displays the names of the elements and attributes in an XML document.
/></parent2></document>)
Syntax
XML.getNodeType();
Arguments
Return values
A string or null.
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. See the W3C Web site for a complete
listing of XML DOM node types by integer. It returns a TypeError if applied to anything other than an XML
object. This limits this method to elements and attributes since the Service Manager XML object cannot
represent element values as an XML object.
Example
This example displays the XML DOM types of the elements and attributes in an XML document.
Syntax
XML.getNodeValue();
Arguments
Return values
A string or null.
The method returns a string representing the value of the current XML element or returns null if the
current node has no value.
Example
/* Create a function to find the parent node element of the target element */
function findValue( sourceObject, targetNode )
{
var valueFound = sourceObject.getNodeValue();
if ( valueFound.length >= 1 )
{
print( "The value of " + targetNode + " is: " + valueFound );
return valueFound
}
else
{
print( "There is no value for " + targetNode );
valueFound = null
return valueFound
}
}
Syntax
XML.getParentNode();
getParentNode(Element)
Arguments
Node 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.
Return values
The method returns an object representing the parent node of the current node or returns null if the
XML object has no parent node.
Example
This example displays the parent node element of any element you select. The example allows you to
select an element from two different input sources.
else
{
print( "Cannot find " + target );
return null
}
}
Syntax
XML.getPrefix();
Arguments
Return values
A string or null.
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.
Example
This example displays the namespace value of the elements and attributes in an XML document.
l A local XML file (for example, a file called "C:\namespace.xml" containing <?xml version="1.0"
encoding="UTF-8" standalone="yes" ?><document
xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
xmlns:ns="http://servicemanager.hp.com/PWS"><http:element1 /><ns:element2 /></document>
var XMLSource;
var TargetNode;
var searchResults;
var prefixResults;
var firstAttribute;
var attributeResults;
return searchResult
}
else
{
print( "Cannot find " + target );
return null
}
}
/* Create a function to find the parent node element of the target element */
function findPrefix( sourceObject, targetNode )
{
var prefixFound = sourceObject.getPrefix();
if ( prefixFound.length >= 1 )
{
print( "The namespace prefix of " + targetNode + " is: " + prefixFound );
return prefixFound
}
else
{
print( "There is no namespace prefix of " + targetNode );
prefixFound = null
return prefixFound
}
}
Syntax
XML.getQualifiedName();
Arguments
Return values
A string or null.
The method returns a string representing the name of the current element or attribute. It returns null
if the current node has no name.
Example
This example displays the qualified names of the elements and attributes in an XML document.
l A local XML file (for example, C:\namespace.xml which contains <?xml version="1.0"
encoding="UTF-8" standalone="yes" ?><document
xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
xmlns:ns="http://servicemanager.hp.com/PWS"><http:element1 /><ns:element2
/></document>)
child = child.getNextSiblingElement();
}
}
print( "Now printing the structure of an XML file with qualified names...\n" );
XMLSource = XMLFile
nsXMLWalk( XMLSource );
print( "Now printing the structure of an XML file without qualified names...\n" );
XMLSource = XMLFile
walkXML( XMLSource );
Syntax
XML.getText();
Arguments
Return values
A string or null.
The method returns a string representing the value of the current XML element or returns null if the
current node has no value.
Example
}
node = childNode;
}
else
{
node = childNode;
}
}
return node;
}
/* Create a function to find the parent node element of the target element */
function findValue( sourceObject, targetNode )
{
var valueFound = sourceObject.getText();
if ( valueFound.length >= 1 )
{
print( "The value of " + targetNode + " is: " + valueFound );
return valueFound
}
else
{
print( "There is no value for " + targetNode );
valueFound = null
return valueFound
}
}
XMLSource = XMLFile
searchResults = findTargetElement( XMLSource, TargetNode );
printFindResults( searchResults, TargetNode );
Syntax
XML.getValue();
Arguments
Return values
A string or null.
The method returns a string representing the value of the current XML element or returns null if the
current node has no value.
Example
}
}
/* Create a function to find the parent node element of the target element */
function findValue( sourceObject, targetNode )
{
var valueFound = sourceObject.getValue();
if ( valueFound.length >= 1 )
{
print( "The value of " + targetNode + " is: " + valueFound );
return valueFound
}
else
{
print( "There is no value for " + targetNode );
valueFound = null
return valueFound
}
}
Syntax
XML.importNode( name );
Arguments
name String This argument specifies the XML node name you want to copy from the
source XML object. The string argument must contain characters valid for
XML (for example, the string cannot include the characters < or > except as
XML entities such as < and >).
Return values
The method returns an XML object containing the copied node or returns null if the method cannot
import a copy of the node.
Example
This example imports an XML node from one XML object to another.
}
else
{
node = childNode;
}
}
return node;
}
Syntax
XML.isDocumentElement();
Arguments
Return values
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.
Example
This example checks to see if the selected element is the DOM document element.
/* Create a function to find the parent node element of the target element */
function testDocElem( sourceObject )
{
var docElement = sourceObject.isDocumentElement();
if ( docElement == true )
{
Syntax
Arguments
AttributeName String This argument specifies the XML attribute whose value you want the
script to add or update.
AttributeValue String This argument specifies the text string you want the script to use as
the XML attribute value. This argument must contain characters valid
for an XML element (for example, the string cannot include the
characters < or >).
Return values
Example
This example adds or updates the attribute value of any given element in an XML document.
}
else
{
node = childNode;
}
}
return node;
}
Note: This method returns null if applied to an existing XML object because the header information
([C++ object XML] @nnnnnnnnnn - ) is not valid.
Syntax
Arguments
String String This argument specifies the text string you want the script to parse as on
XML object. The string argument must contain a valid XML document with a
document element.
FilePath String This argument specifies the path to the XML document you want the script
to parse an XML object. 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.
IsFile Boolean This argument specifies whether the first argument is a string or a file path.
A true value indicates the first argument is a file path. Any other value,
including omitting the second argument, indicates that the first argument is
a string.
Return values
The method returns an XML object if it parses the XML input and returns null if it cannot parse the
input.
Arguments
Example
This example attempts to create an XML object from five different sources.
l An XML string with more than one document element (for example, <document1><parent1
/></document1><document2><parent2 /></document2>)
l An existing XML object (for example, the list of currently logged on users stored in system.users)
l An XML object converted to a string (for example, the list of currently logged on users stored in
system.users)
/* Note: You can omit the isFile argument when the content source is an XML string.
* See the xmlString example below. */
print( "Testing setting content to a valid XML string...\n" );
setXML( xmlString );
print( "Testing setting content to an XML string with more than one document
element...\n" );
print( "The non-compliant XML string before conversion is: \n" + xmlBad );
setXML( xmlBad );
print( "Testing setting content to an XML file...\n" );
setXML( xmlFile, true );
print( "Testing setting content to an existing XML object...\n" );
setXML( xmlObject, false );
print( "Testing setting content to an existing XML object converted to an XML
string...\n" );
setXML( xmlObjectConverted, false );
Syntax
XML.setNodeValue( String );
Arguments
String String This argument specifies the text string you want the script to add as the
XML element value. The string argument must contain characters valid for
XML (for example, the string cannot include the characters < or > except as
XML entities such as < and >).
Return values
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
node = node.getParentNode();
if ( node == null || topNodeName == node.getNodeName() )
{
return null;
}
childNode = node.getNextSiblingElement();
}
node = childNode;
}
else
{
node = childNode;
}
}
return node;
}
TargetNode = "parent1";
TargetValue = "1234";
findElement = findTargetElement( XMLFile, TargetNode );
setElementValue( findElement, TargetNode, TargetValue );
Syntax
XML.setText( String );
Arguments
String String This argument specifies the text string you want the script to add as the
XML element value. This argument must contain characters valid for XML
(for example, the string cannot include the characters < or > except as XML
entities such as < and >).
Return values
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
if (childNode == null)
{
childNode = node.getNextSiblingElement();
while (childNode == null)
{
node = node.getParentNode();
if ( node == null || topNodeName == node.getNodeName() )
{
return null;
}
childNode = node.getNextSiblingElement();
}
node = childNode;
}
else
{
node = childNode;
}
}
return node;
}
TargetNode = "parent1";
TargetValue = "1234";
findElement = findTargetElement( XMLFile, TargetNode );
setElementValue( findElement, TargetNode, TargetValue );
Syntax
XML.setValue( String );
Arguments
String String This argument specifies the text string you want the script to add as the
XML element value. The string argument must contain characters valid for
XML (for example, the string cannot include the characters < or > except as
XML entities such as < and >).
Return values
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
}
}
TargetNode = "parent1";
TargetValue = "1234";
findElement = findTargetElement( XMLFile, TargetNode );
setElementValue( findElement, TargetNode, TargetValue );
Syntax
XML.toXMLString();
Arguments
Return values
A string or null.
The method returns a string containing valid XML or returns null if the current node is not an XML
object.
Example
l An existing XML object (for example, the list of currently logged on users stored in system.users)
Syntax
Arguments
Usage Notes
1. The referenceElement may NOT be null. If referenceElement is null, newElement the function
will fail.
2. 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, such as a newly created
element for which appendNode has not been called. The result of invoking insertBefore using
references to nodes already in the same DOM tree as newElement is undefined.
Example
// Now add create and add new element <four> in one step.
// It will be added at the end, i.e. after <two>
// The newly created node has not yet been given a position in the tree.
print( xmlDoc );
With a DateObject argument, the XMLDate() constructor converts a JavaScript date object to an
XMLDate object.
With a DateTimeDatum argument, the XMLDate() constructor converts a Service Manager date object to
an XMLDate object.
This object's methods use the Service Manager-defined global return codes.
Constructor
new XMLDate();
new XMLDate( DateObject );
new XMLDate( ISO8601DateTimeOrDurationString );
new XMLDate( DateTimeDatum );
Arguments
Properties
None
Methods
getISODate This method returns the indicated portions of the XMLDate value.
getISOTime This method returns the indicated portions of the XMLDate value.
getISOYear This method returns the indicated portions of the XMLDate value.
getISOMonth This method returns the indicated portions of the XMLDate value.
getISODay This method returns the indicated portions of the XMLDate value.
getGMTSCDateTimeString This method returns the Greenwich Mean Time (GMT) datetime in
Service Manager format.
addDuration This method adds the indicated duration to the contained value in the
( iso8601durationstring ) XMLDate object.
getDate This method returns a JavaScript date object (same as the JSDate
method).
Example
l A valid duration
/* Set the Service Manager fields date.entered and planned.start to today's date.
* The dots in Service Manager field names must be converted to underscores */
var theXMLDate = new XMLDate( new Date() );
var todaysDate = theXMLDate.getDatum();
changeRequest.header.date_entered = todaysDate;
changeRequest.header.planned_start = todaysDate;
changeRequest.doInsert();
Syntax
XMLDate.addDuration( duration );
Arguments
duration ISO 8601 Yes This argument contains the ISO 8601 duration string or
duration variable value you want the script to add to an XMLDate
string object.
Return values
Example
l Adds 1 year, 2 months, 3 days, and 4 hours to the XMLDate object then displays the result
Syntax
XMLDate.getDate();
Arguments
Return values
A string or null.
Example
l Converts the XMLDate object to JavaScript date/time object then displays the result
Syntax
XMLDate.getDatum();
Arguments
Return values
A string or null.
The method returns a Service Manager-formatted date/time Datum object or null if the conversion
fails.
Example
l Converts the XMLDate object to Service Manager-formatted date/time Datum object then displays
the result
Syntax
XMLDate.getSCDateTimeString();
Arguments
Return values
A string or null.
The method returns a Service Manager-formatted date/time string or null if the conversion fails.
Example
l Converts the XMLDate object to Service Manager-formatted date/time string then displays the
result
Syntax
XMLDate.getISODate();
Arguments
Return values
A string or null.
The method returns a string containing the ISO date of a date/time object or null if conversion fails.
Example
l Converts the XMLDate object to an ISO date then displays the result
Syntax
XMLDate.getISODateTimeString();
Arguments
Return values
A string or null.
The method returns a string containing the ISO date and time of a date/time object or null if the
conversion fails.
Example
l Converts the XMLDate object to an ISO date and time then displays the result
Syntax
XMLDate.getISODay();
Arguments
Return values
A string or null.
The method returns a string containing the ISO day of a date/time object or null if the conversion fails.
Example
l Converts the XMLDate object to an ISO day then displays the result
Syntax
XMLDate.getISOMonth();
Arguments
Return values
A string or null.
The method returns a string containing the ISO month of a date/time object or null if the conversion
fails.
Example
l Converts the XMLDate object to an ISO month then displays the result
Syntax
XMLDate.getISOTime();
Arguments
Return values
A string or null.
The method returns a string containing the ISO time of a date/time object or null if the conversion
fails.
Example
l Converts the XMLDate object to an ISO time then displays the result
Syntax
XMLDate.getISOYear();
Arguments
Return values
A string or null.
The method returns a string containing the ISO year of a date/time object or null if the conversion
fails.
Example
l Converts the XMLDate object to an ISO year then displays the result
Syntax
XMLDate.getSCDateTimeString();
Arguments
Return values
A string or null.
The method returns a Service Manager-formatted date/time string or null if the conversion fails.
Example
l Converts the XMLDate object to Service Manager-formatted date/time string then displays the
result
Syntax
XMLDate.JSDate();
Arguments
Return values
A string or null.
The method returns a JavaScript date/time object or null if the conversion fails.
Example
l Converts the XMLDate object to a JavaScript date/time object then displays the result
Syntax
XMLDate.toSCDuration( duration );
Arguments
duration ISO 8601 Yes This argument contains the ISO 8601 duration string or variable
duration value you want the script to convert to a Service Manager
string duration string.
Return values
A string or null.
The method returns a Service Manager duration string or null if the conversion fails.
Example
Refer to "List: RAD functions" on page 90 for more information on using RAD functions to perform these
commands instead of JavaScript.
JavaScript
function Description
add_ Returns XML to the Run-Time Environment (RTE) for the expand action on a node in
graphnodes the graph diagram.
get_graph_id Returns the value of the graph ID for the expand action on a node in the graph
diagram.
get_graph_ Returns the value of the node ID for the expand action on a node in the graph
node_id diagram.
get_graph_ Returns the target for an activated action on a node in the graph diagram.
target
Function
add_graphnodes()
Example
system.functions.add.graphnodes(String strXML)
A JavaScript function that returns the activated action on a node in the graph diagram.
Function
get_graph_action()
Example
system.functions.get_graph_action()
A JavaScript function that returns the value of the graph ID for the expand action on a node in the graph
diagram.
Function
get_graph_id.htm()
Example
system.functions.get_graph_id.htm()
A JavaScript function that returns the value of the node ID for the expand action on a node in the graph
diagram.
Function
get_graph_node_id()
Example
system.functions.get_graph_node_id()
A JavaScript function that returns the target for an activated action on a node in the graph diagram.
Function
get_graph_target
Example
system.functions.get_graph_target()
JavaScript functions
in the ScriptLibrary Description
JavaScript functions
in the ScriptLibrary Description
returnMyGroups Returns an array containing all the groups to which a configuration item
(CI) belongs.
Syntax
Arguments
ci Datum Yes This argument contains the CI records you want to add. To add
object or an array of CIs, the ci argument must be an SCFile or SCDatum
string object. To add a single CI, you can specify it as a string.
groupName String Yes This argument contains the name of the configuration group to
which you want to add CIs.
Return values
A numerical value: 0 or 1.
The function returns 0 if it is unable to add CIs to the list group or if the groupName argument specifies
a query group. The function returns 1 if the function successfully adds the CIs to the list group.
Example
This example attempts to add CIs to a list group from the following sources:
l Create a list group containing a single configuration item (for example, a list group called "test01"
containing the configuration item "DEFAULT Phone 0001")
l Create a list group containing one or more configuration items (for example, a list group called
"test02" containing the configuration item "DEFAULT Phone 0003")
l Create a list group containing one or more configuration items (for example, a list group called
"test03" containing the configuration items "HH-000001" and "HH-000002")
/* Create function to find a record list based on a device type and starting query
*/
function findRecordList( deviceType, query )
{
var ciRecordList = new SCFile( "device" );
if ( query != null )
{
print( "Looking for CIs matching type=\"" + deviceType + "\"\&" +
"logical.name#\"" + query + "\"" );
var queryTest = ciRecordList.doSelect( "type=\"" + deviceType + "\"\&" +
"logical.name#\"" + query + "\"" )
}
else
{
print( "Looking for CIs matching type=\"" + deviceType + "\"" );
var queryTest = ciRecordList.doSelect( "type=\"" + deviceType + "\"" )
}
if ( queryTest == RC_SUCCESS )
{
print( "Found the following CIs:\n" + ciRecordList );
system.vars.$L_file = ciRecordList
return ciRecordList;
}
else
{
if ( query != null )
{
print( "Cannot find records matching query: device=\""+ deviceType +
"\"&logical.name#\"" + query + "\""
if ( AddCI == 1 )
{
print( "Successfully added configuration item(s) to " + group );
print( "The members of " + group + " are now: \n" + afterAdd );
}
else
{
print( "Could not add configuration item(s) to " + group );
print( "The members of " + group + "are : \n" + groupMembers );
}
Syntax
Arguments
oldVersion String Yes This argument contains the previous version number.
Return values
The function returns a valid version number if there is one and only one valid next version number. The
function returns the string more if there is more than one valid next version number.
Description
This function is part of a system JavaScript and should not be directly modified.
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. If there is more than one valid next version
number then the function returns the string more.
Example
This example attempts to create the next valid version from two variables.
if ( nextVersion == "more" )
{
print( "Error. There is more than one valid next version number for " +
versionOld
+ ".\n");
return versionOld
}
else
{
print( "Success. The next valid version number is " + nextVersion + ".\n" );
return nextVersion
}
}
Syntax
Arguments
oldVersion String Yes This argument contains the previous version number.
newVersion String Yes This argument contains the new version number.
Return values
Return
value Condition
0 The function returns 0 if any version level value in the newVersion argument exceeds the
value in the maxIncrement argument. For example, if oldVersion equals "1.0". and
maxIncrement equals "2", then the function returns a value of 0 if newVersion equals "1.3"
since going from a value of zero to three exceeds the maxIncrement value of 2.
1 The function returns 1 if it successfully validates the proposed change from the
oldVersion to the newVersion.
-1 The function returns -1 if the newVersion argument contains greater than five version
levels. For example, the function returns -1 if the newVersion argument equals "1.0.0.0.0.0"
as this is a version with six version levels.
-2 The function returns -2 if a version level value in the newVersion argument contains
anything other than the digits 0 to 9. For example the function returns -2 if the newVersion
argument equals "gold" or "1.0a" because the version number contains alphabetical
characters.
-3 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. For example, the function
returns -3 if oldVersion equals "1.1" and newVersion equals "1.1.1" since the oldVersion
has two version levels and the newVersion has three.
-4 The function returns -4 if the value of the newVersion argument is less than the value of
the oldVersion argument. For example, the function returns -4 if oldVersion equals "1.1"
and newVersion equals "1.0" because the newVersion value is prior to the oldVersion
value.
Description
This function is part of a system JavaScript and should not be directly modified.
This function validates a new Configuration Management baseline group version string against an old
version string to ensure it adheres to version number requirements.
Example
This example attempts to validate any given version number update from three variables.
if ( validate == "-2" )
{
print( "Error. Could not update " + versionOld + " to " + versionNew + ".");
print( "The new version " + versionNew + " contains characters other than 0 to
9." );
return versionOld
}
if ( validate == "-3" )
{
print( "Error. Could not update " + versionOld + " to " + versionNew + ".");
print( "The new version " + versionNew
+ " contains a different number of version levels than the old version " +
versionOld );
return versionOld
}
if ( validate == "-4" )
{
print( "Error. Could not update " + versionOld + " to " + versionNew + ".");
print( "The new version " + versionNew + " is an earlier version than the old
version "
+ versionOld );
return versionOld
}
else
{
return versionOld
}
}
Syntax
isfileexist(“filepath”)
Arguments
Return values
The function returns true if the file exists. Otherwise, this function returns false.
Description
This function determines whether a file exists or not and returns a Boolean value of true if the file
exists.
Example
This example attempts to determine whether the note.txt file exists or not in c:\\.
if ( system.functions.isfileexist(“c:\\note.txt”))
print ("file exist")
else
print ("file doesn't exist");
Syntax
Arguments
ci String Yes This argument contains the CI record you want to search for in
the group.
groupName String Yes This argument contains the name of the configuration group
where you want to search for the CI.
Return values
The function returns true if the function successfully finds the CI in the list or query group. The function
returns false if it is unable to find the CI in the list or query group.
Description
This function is part of a system JavaScript and should not be directly modified.
This function searches for a CI in list or query groups and returns a Boolean value of true if successful.
Example
l A list group
l A query group
l Create a list group containing one or more configuration items (for example, a list group called
"test01" containing the configuration item "DEFAULT Phone 0001")
l Create a query group containing one or more configuration items (for example, a query group called
"test04" containing the configuration items where type equals "telecom")
Syntax
Arguments
ci Datum Yes This argument contains the CI records you want to remove. To
object or remove an array of CIs, the ci argument must be an SCFile or
string SCDatum object. To remove a single CI, you can specify it as a
string.
groupName String Yes This argument contains the name of the configuration group
from which you want to remove CIs.
Return values
The function returns 0 if it is unable to remove CIs from the list group or if the groupName argument
specifies a query group. The function returns 1 if the function successfully removes CIs from the list
group. The function returns -1 if it cannot remove CIs from the list group because the action would
result in an empty configuration list group.
Description
This function is part of a system JavaScript and should not be directly modified.
This function removes one or more CIs from a configuration list group and updates the list group record
if successful.
Example
This example attempts to remove the following CIs from a list group:
l Create a list group containing a single configuration item (for example, a list group called "test01"
containing the configuration item "DEFAULT Phone 0001")
l Create a list group containing one or more configuration items (for example, a list group called
"test02" containing the configuration item "DEFAULT Phone 0003")
l Create a list group containing one or more configuration items (for example, a list group called
"test03" containing the configuration items "HH-000001" and "HH-000002")
/* Create function to find a record list based on a device type and starting query
*/
function findRecordList( deviceType, query )
{
var ciRecordList = new SCFile( "device" );
if ( query != null )
{
print( "Looking for CIs matching type=\"" + deviceType + "\"\&" +
"logical.name#\"" + query + "\"" );
var queryTest = ciRecordList.doSelect( "type=\"" + deviceType + "\"\&" +
"logical.name#\"" + query + "\"" )
}
else
{
print( "Looking for CIs matching type=\"" + deviceType + "\"" );
var queryTest = ciRecordList.doSelect( "type=\"" + deviceType + "\"" )
}
if ( queryTest == RC_SUCCESS )
{
print( "Found the following CIs:\n" + ciRecordList );
system.vars.$L_file = ciRecordList
return ciRecordList;
}
else
{
if ( query != null )
{
print( "Cannot find records matching query: device=\""+ deviceType +
"\"&logical.name#\"" + query + "\""
+ RCtoString( queryTest ) + "." );
return null;
}
else
{
print( "Cannot find records matching query: device=\""+ deviceType + "\"" +
RCtoString( queryTest ) + "." );
return null;
}
}
}
);
return null
}
else
{
print( "Created array from " + record + ".\nThe array is:\n" +
arrayOfLogicalNames );
return arrayOfLogicalNames
}
}
if ( removeCI == 1 )
{
print( "Successfully removed configuration item(s) to " + group );
print( "The members of " + group + " are now: \n" + afterRemove );
}
else
{
if ( removeCI == "-1" )
{
print( "Could not remove configuration item from " + group + " as "
+ ci + " is the last member of the group." );
print( "The members of " + group + "are : \n" + groupMembers );
}
else
{
print( "Could not remove configuration item from " + group + ".\n"
+ ci + " or " + group + " does not exist.");
}
}
}
Syntax
lib.ciGrouping.returnGroupMembers( groupName );
Arguments
groupName String Yes This argument contains the name of the configuration group
whose members you want to return as an array.
Return values
An array or null.
The function returns an array containing the logical.name values of the group members if there are
group members. The function returns null if it cannot find a matching group name or if the group does
not have any members.
Description
This function is part of a system JavaScript and should not be directly modified.
This function returns the logical.name values of the members of a Configuration Management group.
l If the group is a list type, the function returns the array from the group configuration item record.
l If the group is a query type, the function returns an array of all the CIs it finds.
Example
This example returns the members of the group listed in the variable.
l Create a list group containing one or more configuration items (for example, a list group called
"test01" containing the configuration item "DEFAULT Phone 0001")
l Create a query group containing one or more configuration items (for example, a list group called
"test04" containing the configuration items where type equals "telecom")
Syntax
Arguments
ci String Yes This argument contains the CI record you want to search for in
your list and query groups.
l both: Add this argument to search both list and query groups.
Return values
The function returns an array containing the logical.name values of the list and query groups in which
the CI is a member. The function returns an empty array if it cannot find the CI in any list or query group.
Description
This function is part of a system JavaScript and should not be directly modified.
This function returns an array containing the logical.name values of the groups in which the CI is a
member. The function queries all group records and does the following:
l If the group is a list type, the function indexes the group.members and if the CI exists in the list
group, adds it to the groupArray.
l If the group is a query type, the function uses the RTE function to determine whether the values in
the CI record satisfy the search criteria defined by the query.
Example
l Create a list group containing a single configuration item (for example, a list group called "test01"
containing the configuration item "DEFAULT Phone 0001")
l Create a list group containing one or more configuration items (for example, a list group called
"test02" containing the configuration item "DEFAULT Phone 0003")
l Create a list group containing one or more configuration items (for example, a list group called
"test03" containing the configuration items "HH-000001" and "HH-000002")
l Create a query group containing one or more configuration items (for example, a query group called
"test04" containing the configuration items where type equals "telecom")
print( "The query groups containing " + targetCI + " are:\n" + groups );
}
else
{
print( "There are no query groups containing " + targetCI );
}
JavaScript function: skipApproval
Prevents an item's approval status from being reset to "pending."
Syntax
Arguments
isChanged Boolean Yes This argument indicates whether the cart Item is
changed.
finalstatus String Yes This argument contains the latest cart item’s approval
status
Return values
If the function returns true, the item approval status is not reset to "pending."
Description
You can modify the implementation of this function base on your organization's own business logic.
Example
In OOB, if the item is not changed, and the approval status is not denied, you can skip resetting the
approval status to pending.
return true;
}else {
return false;
}
}
l getDocumentElement(); (method of
the XML object)
l getFirstChildElement(); (method of
the XML object)
l getNextSiblingElement(); (method of
the XML object)
l getFirstChildElement(); (method of
the XML object)
If you uncomment the line of code, recompile, and then run the script again, you can view the
suppressed output. It prints all logged-on users as a large XML document.
//print( usersXML );
This part of the script loops through to process each <user> element within <users>.
If you uncomment the line of code, recompile, and then run the script again, you can view the
suppressed output. It prints an individual user as an XML document.
//print( userXML );
This part of the script loops through to process each XML element node within the <user> element.
2. Obtain the resulting record in XML format by using the getXML method that gives you field names
in addition to values.
3. Iterate through the resulting XML and print the field names and values. For a more robust
approach, see "Example: Iterating through a complex XML document" on the previous page.
var fldIndex;
}
}
testFile( "nonexistentfile" );
testFile( "contacts" );
This script illustrates several key concepts of using JavaScript in HP Service Manager.
l How to access a field in a record using an expression of the form file[fieldName] where fieldName
is a string.
l How to return JavaScript date objects when you reference Service Manager datetime fields.
l How to use SCFile method return codes to test against global properties like RC_SUCCESS.
l How to obtain a localized error message from a return code value using the RCtoString method.
l How to pass traditional query strings that are in Service Manager syntax directly to the doSelect
method.
l How to use underscores in JavaScript to reference Service Manager field names containing dots
(such as contact.name).
This script demonstrates calling the datetimestamp function. It selects a record from the contacts
table and updates the sysmodtime field.
datetimestamp( f, "sysmodtime" );
This script demonstrates how passing the wrong kind of field to the datetimestamp function generates
an error message.
datetimestamp( f, "contact_name" );
print( "datetimestamp called for file " + fileName + " and field " + fieldName );
fieldType = d.getType();
if ( fieldType != "TIME" )
{
print( "Error! Field " + fieldName + " is a " + fieldType + " field!
This function can only be called with date/time fields!" );
return false;
}
rc = file.doUpdate();
if ( rc != RC_SUCCESS )
{
print( "Error " + RCtoString(rc) + " trying to update " + fileName + " record"
);
return false;
}
return true;
}
Note: The sample "teststructarray" has the following Database Dictionary format fields:
l id character
l arr array
l arr structure
l a number
l b character
Note: : To populate the elements of the field, the elements have to be populated in order.
fvar.id="abc";
print(fvar);
If no email client is available, copy the information above to a new message in a web mail client, and
send your feedback to [email protected].