You are on page 1of 712

BMC FootPrints AssetCore

Chilli Reference
Version 12.0
Introduction to Chilli

Chilli is a procedural programming language, combining the features of BASIC and C as well as some C++
concepts into a flexible computer language. This powerful script language is a self-contained stand-alone
language with its own compiler.
Chilli is used in and comes with BMC Software products to facilitate repetitive tasks and execute specific actions.
But it is not limited to BMC Software products. It can also be used to create scripts in general systems and
network management environments to automate repetitive and otherwise time consuming tasks.

How to Use this Reference


This Chilli reference was written to lead you through the Chilli programming language and to provide you with
the necessary detailed information you need to develop Chilli scripts for the BMC Software products as well as
Chilli scripts for other non-product related situations in everyday network and system administration.
This reference assumes that you have some programming experience and understand the main concepts of
programming. If you are an experienced programmer wanting to learn another new language which is very
helpful for automating tasks in the networks and system administration in general or through BMC Client
Management, this book guides you through the language. It points out comparisons to and differences from other
languages such as C, BASIC or Java. Because Chilli is largely based on C you should have no issues getting up to
speed quickly and moving through the basic Chilli programming chapters in Section I to get into Section II and the
specifics of the Chilli functions.
If you already know Chilli and have written your own scripts, this book provides a reference for you to look up
specific function names which you just cannot remember and introduces you to the changes since the last version
of Chilli.

Organization
The Chilli Reference is a comprehensive guide to the Chilli language and is divided into the following sections:

Section I - The Chilli Language


The first section, immediately following this introduction documents the core Chilli language. It begins with
some bland but necessary reading which covers topics necessary when learning any new programming language.
• Chilli Basics
• Data Types
• Variables
• Constants
• Expressions
• Language Statements
• Functions and Procedures
• Configuration, Error Handling and Debugging

Numara Software, Inc. and BMC Software, Inc. Confidential.


4 - BMC FootPrints Asset Core - Chilli Reference

Section II - Internal Chilli Functions Reference


The second part of the book is a complete reference to all function modules of the Chilli language. The Chilli
functions are grouped into modules which is each explained in a separate chapter. Every function is detailed with
its syntax and all possible signatures, its return type and any special characteristics. Most of the function
descriptions also contain an example showing typical uses of the function. You will find it helpful to study these
examples carefully. The functions groups also explain all module specific data types in the respective chapters.

Appendix
The last part of the book is the Appendix. It contains a number of appendices providing references to Chilli that
you might find useful.
• Alphabetical Function Listing
• Alphabetical Data Type Listing
• Reserved Words
• Chilli Error Codes
• Language Operators
• Predefined Variables and Constants
• Chilli Function Group Modules

Numara Software, Inc. and BMC Software, Inc. Confidential.


Introduction to Chilli - 5

Numara Software, Inc. and BMC Software, Inc. Confidential.


Section I

The Chilli Language


As a building is made of bricks, a Chilli program is made of basic elements, such as
expressions, statements, statement blocks, and function blocks. These and other elements are
discussed in the following section.
• Chilli Basics
• Data Types
• Variables
• Constants
• Expressions
• Language Statements
• Functions and Procedures
• Configuration, Error Handling and Debugging
This part of the book documents the core Chilli language as it is used for the Windows, UNIX
and Mac agents and as it can be used as a standalone scripting language in the Windows or
UNIX environment. This part is a Chilli language reference, and you might find yourself
referring to it while creating your own scripts.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chilli Basics

Chilli is a procedural language, combining the features of BASIC and C as well as some concepts of C++ into a
flexible and easy-to-use computer language. It is a self-contained stand-alone language and has its own compiler.
Being procedural, the language does not have any goto or gosub statements, all control mechanisms are achieved
through procedure calls.
The fundamental elements of Chilli - as for any computer programming language - are its data types, statements
and operators, as well as its functions and user definable procedures, which are all explained in detail in the
following chapters. This introductory chapter to Chilli provides some more general information about the
language and its concepts and features.

1.1 Case-Sensitivity
Chilli is not a case-sensitive language. This means that it is not necessary to type language keywords, procedure
names, and any other identifiers with a consistent capitalization of letters. The string keyword, for example, can
be typed string, String or STRING.

1.2 Naming Rules


Similar to other programming languages such as C or BASIC, there are some rules as to how to name the elements
of the Chilli language, such as variables, constants, structures, arrays, functions or procedures. When giving a
name to an element be aware that:
• Chilli does not define a maximum length for names. The number of characters for names are limited according
to the memory limits of the supporting hardware platform, that is, 260 characters for Windows and 1024 on
UNIX and Linux systems.
• It can be any combination of alphanumeric characters, that is, letters, digits, and underscores.
• The name can be in lower-case or upper-case or a mixture of both.
• It can start with an underscore (_) or a letter, but not with a digit.
• The name must not contain any spaces.
• The name must not be a reserved statement, a function name or a keyword.
• The name must not be an already declared variable or constant.

1.3 Semicolons and Braces


Contrary to other programming languages such as BASIC or C, Chilli does not allow any statements, array,
structure or procedure declarations to be enclosed by braces ({}). If the Chilli parser encounters a brace in a script
it terminates the execution with an error.
Chilli does not demand a semicolon (;) at the end of each condition or statement, in a function or procedure
declaration. If you put a semicolon, the Chilli parser just ignores it or, if it is followed by other characters, regards
it as the beginning of a comment.

Numara Software, Inc. and BMC Software, Inc. Confidential.


10 - BMC FootPrints Asset Core - Chilli Reference

1.4 Comments
Chilli supports several different styles of comments. Any text following a semicolon (;), a hash (#) or a double
slash (//) is considered a comment and is ignored by the Chilli parser. Comments can be placed at the beginning of
a line to explain the following statements, for example:
;*************************************************************
;This script provides the basis of a Dynamic Group
;Membership script. For this script to work, the BMC Client Management
;agent must be running already.
;*************************************************************
Comments can also be placed after the statement in the middle of the line. In this case the comment also needs to
be preceded by a semicolon (;), a hash (#) or a double slash (//) to be identified as such.
while (cont < 10) //start of loop
To comment out a whole block of code rather than several individual lines, Chilli also supports C-style /* ... */
comments. The /* and */ symbols should appear on a line by themselves before and after the block of code to
be commented out.
Thus the above mentioned code example can also be commented out this way:
/*
This script provides the basis of a Dynamic Group
Membership script. For this script to work, the BMC Client Management
agent must be running already.
*/

1.5 Data Types


The Chilli language supports most C data types as well as some other, more advanced data types, such as strings,
numerals, arrays, structures, and so on.
• Chilli integers are signed 32-bit integer values that can also be used as object handles depending on the
function they are used with. Variables of type integer are declared with the Int or Integer statements.
• The long data type is a signed 32-bit number, similar to the integer, which, however requires 4 bytes of storage
instead of 2, giving the long a storage range of -2,147,483,648 to 2,147,483,647. Variables of type long are
declared with the Long statement.
• A character is an 8-bit signed numeric data type that can represent a number from -128 to +127. Variables of
type integer are declared with the Char statement.
• Floating points are a numeric data type that contains a number with a decimal point and a fraction. Their
maximum range is between 1.2-38 and 3.438. Variables of type floating point are declared with the Float
statement.
• Double precision floating points are very similar to floating points in that they are a numeric data type that
contains a number with a decimal point and a fraction, but their maximum range is between 2.2-308 and 1.8308.
They are declared with the Double statement.
• The Boolean data type represents a truth value and has only two possible values, true and false. It is
declared with the Bool or Boolean statement.
• Strings can contain any sequence of characters up to a maximum of 8000 characters. String values can be
assigned values and passed as function parameters. String variables are declared with the String statement.
• Encryption strings are strings which are encrypted by Chilli when the script they are defined in is executed.
Encryption variables are declare with the Estring statement.
• Arrays are lists of variables of the same data type. Chilli only supports single dimension arrays.
• Structures are lists of one or more variables, which can be of different data types. Structures are declared with
the Struct - Endstruct language statement.
• A number of function groups or modules in Chilli create additional data types which are specific to their
module.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 1 - Chilli Basics - 11

The Chilli language does not contain any explicit pointer types although the integer type is often used as a handle
to an object used by related functions.

1.6 Literals
In Chilli a literal is data that appears directly in a script. These data values can be numbers, strings (in hard (‘) or
soft (“) quotes) and the Boolean values true and false. Literals are closely connected with data types, which
are explained in detail in chapter Data Types on page 15.

1.6.1 String Literals


String literals are a sequence of numbers and characters enclosed by a matching pair of soft (“) or hard (‘) quotes.
Soft quotes can be contained in strings enclosed in hard quotes and vice versa. Hard and soft quotes are used in
Chilli to define the interpretation of a backslash (\) character within a sequence of characters. This is explained in
more detail later on in this section under Strings in chapter Data Types on page 15.

1.6.2 Integer Literals


The integer literal is the most common literal, and can be divided into three “subliterals”: the decimal,
hexadecimal and octal literal. The integer literal is a signed 32-bit value.
• decimal literal
The decimal - base 10 - integer is a ‘simple’ number such as 5 or 20. It does not have a leading zero (0).
• hexadecimal literal
The hexadecimal - base 16 - integer is typically used as a binary shorthand, each digit grouping four binary
ones and zeros. They are represented by the digits 0-9 and the upper- or lower-case letters a-f, which represent
the numbers 10-15. These integers are preceded by 0x or 0X.
• octal literal
The octal - base 8 - integer is represented by the presence of a zero (0) in front of the digits.

1.6.3 Character Literals


The character literal generally represents an ASCII character, more commonly known as text, or a small whole
number. It is stored in one byte of memory thus can only represent a number from -128 to +127.

1.6.4 Floating Point and Double Precision Floating Point Literals


Floating point literals of any size are used to represent decimal numbers with fractional parts. They can be either
in standard notation, for example, 3.1415, .5, 4., or in scientific notation, for example, 8.45-12, 8.45e-12, 32.52520,
32.525E20.

1.6.5 Boolean Literals


The Boolean literal has only two values: its two states true and false. They are represented by the keywords true
and false. If a certain action is to take place, these values are typically used as flags to determine. Similar to
other programming languages, the Boolean value is the representation of a zero or non-zero integer value.

1.7 Variables
Together with data types, variables are among the most important concepts of a programming language. Variables
are named storage locations which can be used to represent different values.
Variables in Chilli can be declared to be of local or global scope. The Chilli language creates and defines a number
of predefined variables upon starting the Chilli compiler which are always of global scope. In Chilli variables can
be defined on the command line. Any parameter declared on the command line is effectively a global variable,
too.

Numara Software, Inc. and BMC Software, Inc. Confidential.


12 - BMC FootPrints Asset Core - Chilli Reference

1.8 Language Statements


The Chilli language defines a number of statements that form the core of the language. The following statements
are available in Chilli:
• Include
The Include statement can be used in a script to include other scripts as part of the main script being executed.
The effect of an included file is the same as having the entire contents of that file within the original script.
• Call
The Call statement can be used within a procedure to call another script. Contrary to a included scripts, a
called script is always runnable by itself and is used by another script to perform a fixed function.
• Struct / Endstruct
The Struct - Endstruct statements are used in scripts to define structures. Structures are a collection of
variables of the same or different data types grouped together under a single name for easy manipulation.
• Proc / Endproc
The Proc - Endproc statements are the mechanism through which procedures are defined in the script.
Procedures are like the built-in statements in that they can but need not return a value.
• Return
The Return statement provides a mechanism of returning from a user defined procedure before the end of the
procedure has been reached.
• If / Else / Elif / Endif
The If and its related conditional statements provide the main mechanism of conditional execution within the
Chilli language.
• While / Endwhile
The While - Endwhile construct is the main looping mechanism in Chilli and is similar in operation to the If -
Endif, but for the statement block that is controlled by the While statement. This statement block is executed
repeatedly until the value of the condition expression becomes false.
• For / Endfor
The For - Endfor statement is a second looping construct, similar to the While -Endwhile statement except for
the behavior of continue and an additional initialization of the loop.
Although this reference and related documentation denote the statements using a capital letter as the first letter,
the case of the letters is not significant, so for example, return, Return and RETURN are equivalent.

1.9 Expression Operators


Operators are fundamental to most programming languages. In general there are three different types of operators:
unary operators, binary operators, and tertiary operators. Chilli, however, only handles unary and binary
operators, which means that they take one or two parameters and perform an operation using those one or two
parameters.
The following unary and binary operators are supported by Chilli:
Arithmetic Operators
Arithmetic operators are used in mathematical operations that do not change the values of the operands. They
return a value that is usually assigned to a variable.
• Negation (- )
• Addition (+)
• Subtraction (-)
• Multiplication (*)
• Division (/)
• Modulo (%)
Comparison Operators

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 1 - Chilli Basics - 13

Comparison operators compare values of various types and return a Boolean value (true or false) depending on
the result of the comparison. They are most commonly used in if or while statements to control the flow of
program execution.
• Equality (==)
• Inequality (!=)
• Less Than (<)
• Greater Than (>)
• Less Than or Equal (<=)
• Greater Than or Equal (>=)
Logical Operators
The logical operators perform Boolean algebra on their operands. Generally they are used with the comparison
operators to express complex comparisons that involve more than one variable.
• Logical Negation (! )
• Logical And (&&)
• Logical Or (||)
Bitwise Operators
All three bitwise operators supported in Chilli perform Boolean algebra on the individual bits of the operand. All
operators are used for low-level manipulation of binary numbers.
• Bitwise And (&)
• Bitwise Or (|)
• Bitwise Xor (^)
• Shift Left (<<)
• Shift Right (>>)
Assignment Operators
The assignment operator (=) is used to assign a value to a variable, a constant or an array element. In Chilli the
assignment operator can also be combined with arithmetic and bitwise operators to provide a short-cut. Chilli
supports the following assignment operators:
• Assignment (=)
• Addition (+=)
• Subtraction (-=)
• Division (/=)
• Multiplication (*=)
• Modulo (%=)
• Shift Left (<<=)
• Shift Right (>>=)
• Bitwise AND (&=)
• Bitwise OR (|=)
• Bitwise Xor (^=)

1.10 Reserved Words


There are a number of reserved words in Chilli. These are words that you cannot (or should not) use as identifiers
(such as variable names) in your Chilli script programs. These keywords have special meaning to Chilli - they are
part of the language syntax itself. This means that they should not be used in any other way. The list of reserved
words is composed of all function names, predefined constant and variable names and values as well as all
language statements. You find a complete list of all Chilli keywords in the appendix Reserved Words on page 675
of this manual.

Numara Software, Inc. and BMC Software, Inc. Confidential.


14 - BMC FootPrints Asset Core - Chilli Reference

1.11 Internal and External Chilli Function Modules


The function modules of the Chilli programming language are divided up into two groups:
• internal function modules, which have been integrated into the core and thus are always available, and
• external function modules, which are stored in .chx files and can be loaded according to the scripts’
requirements.
External modules can be loaded through either one of the following two ways:
a Include Statement
The include statement can either load individual function modules or a script which defines the function
modules to be loaded for this script. For more information refer to chapter Language Statements - Include on
page 49 later on in this section.
b General Configuration Settings in the Chilli.ini File
The chilli.ini file contains two optional entries, Preload and ModulePath, in its [ChilliConfig]
section, through which the external function modules to be loaded can be defined. If you use this option the
modules to load specifications are applicable to all Chilli scripts. For more information refer to chapters
Language Statements - Include on page 49 and Configuration, Error Handling and Debugging - The Chilli
Configuration File on page 65 later on in this section.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Data Types

This chapter introduces a very important concept of programming languages: data types. Data types are, as the
name suggests, the types of data that the Chilli language can manipulate. The following table lists all Chilli data
types:

Data Type Description Keyword


Integer Numeric data type of type integer Int / Integer
Long Numeric data type of type long Long
Character Numeric data type of type character Char
Floating point Numeric data type of type floating point Float
Double precision Numeric data type of type double precision floating point Double
floating point
String A string of characters to represent text String
Encryption string A string of characters converted to encrypted format when run. Estring
boolean boolean value (true / false) Bool / boolean
Array Collection of data values of the same type -
Structure Collection of data values of same or different types Struct - Endstruct
Module specific types Data types specifically created by function modules in addition to normal -
types

If any data type, be it a numeric data type, a string, a boolean, an array or a structure, is declared outside of any
procedure body, it has Global Scope, meaning that it is usable within any procedure. If the declaration falls
within a procedure definition, the variable has Local Scope, meaning it is only accessible within the procedure
where it is declared. The same variable name can be declared and used in two different procedures.
If within a procedure, a local variable is declared using the name of a global variable, any references to the
variable in that procedure uses the local copy. The global variable is not used and in effect is masked by the local
variable.

2.1 Numeric Data Types


Numbers are the most basic data type there is. As already mentioned in the preceding chapter, in Chilli numbers
can be divided up into character, integer, floating point and double precision floating point data types.

2.1.1 Integers
Integer variables hold signed 32-bit values that have no fractional part. Therefore the result of an integer division
is truncated, simply because any fractional part is ignored. All integers are signed by default in Chilli, that is the
integer variables can hold positive or negative values. The Chilli integer data type is the equivalent to the long
integer type in C and therefore has a maximum value range from -2,147,486,648 to 2,147,438,647.
Integer variables are declared with the Int or Integer statement. All integer variables must be declared before they
are referenced, otherwise a fatal script error occurs. Multiple variables can be declared on the same line as long as
they are separated by commas.

Numara Software, Inc. and BMC Software, Inc. Confidential.


16 - BMC FootPrints Asset Core - Chilli Reference

Syntax
Int Variable1 [, Variable2 ...]
Integer Variable1 [, Variable2 ...]

2.1.2 Longs
The Long data type is very similar to the integer data type, it is stored as a signed 32-bit number, which requires 4
bytes of storage, giving the Long integer a storage range of -2,147,483,648 to 2,147,483,647. Within Chilli the
integer and long data types are the same and are interchangeable in all functions.
Long variables are declared with the Long statement. All long variables must be declared before they are
referenced, otherwise a fatal script error occurs. Multiple variables can be declared on the same line as long as
they are separated by commas.
Syntax
Long Variable1 [, Variable2 ...]

2.1.3 Characters
The character type of data is very similar to the integer data type except that it can only be assigned numerical
values between -128 to 127, because it is stored in only one byte of memory. The char type of data is usually used
for ASCII data, more commonly known as text. A char is an integer variable type that can represent either one
character of text or a small whole number. The Chilli language can only manipulate signed chars, not unsigned
chars.
Characters are declared with the Char statement. All character variables must be declared before they are
referenced, otherwise a fatal script error occurs. Multiple variables can be declared on the same line as long as
they are separated by commas.
Syntax
Char Variable1 [, Variable2 ...]
Example
The following example demonstrates the use of the Chilli character data type in combination with the MakeStr
and Print functions.
proc main ()

string szTmp
char ptrChar[]
int i, j

szTmp = "Hello"

// Assigning a string to an array of characters sets the size of


// the array to the number of characters in the string and assigns
// each character of the string to an element of the array

ptrChar = szTmp

for (i=1; i<=StrLen (szTmp); i+=1)

// Printing a character prints its string equivalent


print ("Element number "+i+" is " +ptrChar[i]+"\n")

// Assigning a character to an int puts the ASCII code of the


// character into the int
j=ptrChar[i]
print ("ASCII code for "+ptrChar[i]+" is "+j+"\n")

// Using MakeStr does the same


print ("Using MakeStr, ASCII code for "+ptrChar[i]+" is "+MakeStr (ptrChar[i],

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 2 - Data Types - 17

"%d")+"\n")

endfor

endproc
OUTPUT
Element number 1 is H
ASCII code for H is 72
Using MakeStr, ASCII code for H is 72

Element number 2 is e
ASCII code for e is 101
Using MakeStr, ASCII code for e is 101

Element number 3 is l
ASCII code for l is 108
Using MakeStr, ASCII code for l is 108

Element number 4 is l
ASCII code for l is 108
Using MakeStr, ASCII code for l is 108

Element number 5 is o
ASCII code for o is 111
Using MakeStr, ASCII code for o is 111

2.1.4 Floating Points


Unlike the integer numbers a floating point number contains a decimal point and a fractional part. Similar to the
integer, a floating point has a limited range, the maximum value range being between approximately 1.2 and -38

3.4 . This means a maximum precision of 7 digits.


38

Floating points are declared with the Float statement. All floating point variables must be declared before they are
referenced, otherwise a fatal script error occurs. Multiple variables can be declared on the same line as long as
they are separated by commas.
Syntax
Float Variable1 [, Variable2 ...]
Comments
Unlike an integer division, from which the result is truncated and the fraction part is discarded, a floating point
division produces another floating point number. If both the divisor and the dividend or at least one of them are
floating point numbers, a floating point division is carried out.

2.1.5 Double Precision Floating Points


In Chilli long floating point numbers are represented by another data type, the double precision floating point.
The difference between a double data type and a float data type is that the former normally uses twice as many
bits as the latter. Therefore, a double floating point number is of at least 10 digits of precision and of a maximum
precision of 19 digits, although the ANSI standard does not specify it for the double data type. Its value range is a
number including a fractional part with a maximum of approximately 2.2 and 1.8 . -308 308

Double precision floating points are declared with the Double statement. All double precision floating point
variables must be declared before they are referenced, otherwise a fatal script error occurs. Multiple variables can
be declared on the same line as long as they are separated by commas.
Syntax
Double Variable1 [, Variable2 ...]

Numara Software, Inc. and BMC Software, Inc. Confidential.


18 - BMC FootPrints Asset Core - Chilli Reference

2.2 Strings
A string is a sequence of letters, digits, punctuation characters, and so on. - it is the Chilli data type for
representing text. Strings can be included in scripts by enclosing them in a matching pair of hard (‘) or soft quotes
(“). A string must be delimited by a pair of soft or hard quotes, not a combination of both. A string variable can
hold string values with a maximum of 8000 characters.
String variables are declared with the String statement. All string variables must be declared before they are
referenced, otherwise a fatal script error occurs. Multiple variables can be declared on the same line as long as
they are separated by commas.
Syntax
String Variable1 [, Variable2 ...]
Comments
As already mentioned above, strings should be enclosed in soft (“) or hard quotes (‘). The only difference between
hard and soft quotes is that Chilli interprets a backslash (\) character within a soft quote pair as an Escape
Sequence which can change the meaning of the string. Any backslash characters within a hard quoted string are
used verbatim, making hard quotes suitable for specifying file paths which contain backslashes. Soft quotes can
be contained in strings enclosed in hard quotes and vice versa.
Example 1
The following string
“http:\\www.example.com\news.html”
is written to the output as follows:
http:\www.example.com
ews.html
To print correctly the string needs to have the following syntax:
‘http:\\www.example.com\news.html’
Example 2
“Oh, she exclaimed, there is no tea left.\nThen you better make some more, he answered.”
has the following screen output:
Oh, she exclaimed, there is no tea left.
Then you better make some more, he answered.
The same string in hard quotes prints as follows:
Oh, she exclaimed, there is no tea left.\nThen you better make some more, he answered.
Example 3
The following string examples appears correctly and as intended in the output.
string Path
Path=‘c:\Programm Files\Metrix Systems\rollout\ro_files\ro_boot.chl’
Print (“The file path for the rollout script is” + Path)
Output
The file path for the rollout script is c:\Programm Files\Metrix
Systems\rollout\ro_files\ro_boot.chl

2.2.1 Escape Sequences


An escape sequence is one or more characters preceded by a backslash (\). If used within a string delimited by soft
quotes (“), the backslash changes the meaning of the character following it in a very similar manner to the C
language. The most commonly used escape sequence is \r\n, which creates a Carriage Return - LineFeed pair,
typically used to terminate Windows text files. The following table lists the escape sequences you can use in a
Chilli Script.

Escape Sequence Description


\b Inserts a backspace character which means that the following character overwrites the character
before the \b.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 2 - Data Types - 19

Escape Sequence Description


\n Inserts a LineFeed character.
\r Inserts a CarriageReturn character which can be used together with a LineFeed to terminate lines
in a text file.
\t Inserts a horizontal TAB character.
\\ Inserts a single backslash character (\).
\’ Inserts a single quote character.
\’’ Inserts one double quote character.
\xNN If both characters following the x are valid hexadecimal digits (0-9,A-F) the escape sequence is
converted to the code specified by the digits. If either one of the digits is not valid, the \ character
is dropped altogether and no translation occurs. Note that exactly 2 digits and no more are
required to be present.

Remember that escape sequences are not interpreted in a string delimited by hard quotes (‘). This is useful when
specifying file paths which use the backslash (\) character which must not be interpreted as an escape sequence.

2.3 Encryption Strings


A encryption string is a sequence of letters, digits, punctuation characters, and so on, representing a string in
encrypted format. A constant string assigned to an estring with the format e:Secret has the secret encrypted and
saved in place to the Chilli file. The string becomes encrypted when the script is executed.
Encryption string variables are declared with the Estring statement. All estring variables must be declared before
they are referenced, otherwise a fatal script error occurs. Multiple variables can be declared on the same line as
long as they are separated by commas.
Syntax
Estring Variable1 [, Variable2 ...]
Example 1
The following script
proc main ()
estring strEncrypted
strEncrypted = "e:This is a newline:\nHello World!\nThis is on the third line\n"
print (strEncrypted)
endproc
Becomes encrypted when run, and becomes this:
proc main ()
estring strEncrypted
strEncrypted = "x:dtZD1+A16AEgpYZIX+7orYfv7dOEFqdTHiWhFwSkPNUxoxAnFBMurj77QeJtud
1ohcHO7mc4DYtc2wS/mQ=="
print (strEncrypted)
endproc

2.4 booleans
The numeric and string data types have an infinite number of possible values. The boolean data type on the other
hand has only two: its two states true and false. The two legal values are represented by the keywords true and
false. A boolean value represents a truth value - it declares if something is true or not. It is the expression of a
zero (0) or non-zero integer value, whereby 0 is false and non-zero true.
boolean values are declared with the Bool or boolean statement. All boolean variables must be declared before
they are referenced, otherwise a fatal script error occurs. Multiple variables can be declared on the same line as
long as they are separated by commas.

Numara Software, Inc. and BMC Software, Inc. Confidential.


20 - BMC FootPrints Asset Core - Chilli Reference

Syntax
Bool Variable1 [, Variable2 ...]
boolean Variable1 [, Variable2 ...]
Comments
boolean values are generally the result of a comparison in a script. Therefore they are usually used in control
structures. For example, the if - else statement which performs one action if a boolean value is true and
another action if the value is false. In general a comparison that creates a boolean value is combined with a
statement that uses it.

2.5 Arrays
An array is a collection of data values of the same data type. Each value has a number or index, and they are
referenced by the name of the array and stored in a set of consecutive memory slots. In Chilli only single-
dimensional arrays, that is, arrays with one index, can be handled.
Arrays are declared through their respective data type. All arrays must be declared before they are referenced,
otherwise a fatal script error occurs.
Syntax
data_type array_name [array_size]
data_type is the type specifier that indicates what data type the declared array is.
array_name is the name of the declared array.
array_size defines how many elements the array can contain. If no array size is defined, the compiler
creates an array just large enough to hold the initialization values.
In Chilli arrays are indexed (that is, individual, numbered values are retrieved from the array) by enclosing the
index within square brackets after the array name. This index is also called the array subscript. For example, if an
array is named x and i is an integer, x[i] is an element of the array. Contrary to C all arrays in Chilli are
indexed starting at 1 not zero (0), which means that the first element in an array is at index 1. Thus x[5] really
refers to the fifth element of the array x.
Arrays can contain any of the following basic data types whereby all values must be of the same data type:
• integer
• long
• character
• float
• double
• string
• boolean
• structure
Examples
int inittime[30]

inittime[2] = 75# the second element of the initialization


# time array stores the value ‘75’.
inittime[1] = inittime[6]# the value stored in element 6 is
# assigned to element 1.
When you refer to an array element, the array subscript can be a literal constant, as in the above listed examples.
However, a Chilli script might often use a subscript that is a Chilli integer variable or an expression, or even
another array element or a structure member.
Examples
float inittime[100]
int x[10]

x[4] = 10

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 2 - Data Types - 21

inittime[i] = 100# i is an integer variable


inittime[3 + 6] = 100# equivalent to inittime[9]
inittime[x[4]] = 100# x[] is an integer array
This last example needs some more explanation: The array x[] has the value 10 stored in array element x[4].
If this array element is used in another array inittime[], the following two ways of writing the array are equal:
inittime[x[4]]
inittime[10]
Comments
General array naming rules are the same as for any other element in the Chilli language. In addition to those the
array name must be unique and it can not be used for another array or any other identifiers, such as a variable, a
constant, and so on.
When using arrays keep the subscript numbering scheme in mind. In an array with n elements, the subscripts
range from 1 to n in Chilli. If you use a subscript value n+x, you get a program error. The Chilli compiler does not
check if the array subscript used is within the permitted range or not. Your script compiles but fails at run time.
Example
The following example demonstrates the use of the Chilli character data type with arrays.
proc main ()

int i,j
string szTmp
char ptrChar[]

szTmp = "Hello"

// Assigning a string to an array of characters sets the size of


// the array to the number of characters in the string and assigns
// each character of the string to an element of the array

ptrChar = szTmp
for (i=1; i<=StrLen (szTmp); i+=1)

// Assigning a character to an int puts the ASCII code of the


// character into the int

j=ptrChar[i]
print ("ASCII code for "+ptrChar[i]+" is "+j+"\n")

endfor

endproc
OUTPUT
ASCII code for H is 72
ASCII code for e is 101
ASCII code for l is 108
ASCII code for l is 108
ASCII code for o is 111

2.6 Structures
A structure is a collection of one or more variables grouped together under a single name for easy manipulation.
The variables in a structure, unlike those in an array, can be of different variable types, and each data item has its
own name instead of a subscript value. A structure can contain any of Chilli’s data types, including arrays, other
structures and arrays of structures. Structures therefore help to organise complicated data, notably in large
scripts, because they permit a group of related variables to be treated as a unit instead of as separate entities.

Numara Software, Inc. and BMC Software, Inc. Confidential.


22 - BMC FootPrints Asset Core - Chilli Reference

A structure can be regarded as a data type same as an integer or a string, however, before its variables can be
declared in a script its type must be defined in a type definition, otherwise a fatal script error occurs.

2.6.1 Simple Structures


A structure type is defined through the Struct - Endstruct language statement.
Syntax
Struct struct_name
member_variable1
[member_variable2
..... ]
Endstruct
Struct is the keyword to start a structure declaration.
struct_name is the name of the structure.
member_variable defines the members or fields of the structure.
Endstruct is the keyword that marks the end of the structure definition.
The Struct - Endstruct language statement must be followed immediately by the structure name (which follows
the same rules as any other Chilli name). To define the members of the structure in Chilli the following rules must
be observed:
• The list of the structure’s members must not follow on the same line as the struct keyword and the name of
the structure, but start on the next line.
• The syntax of a member declaration is the following:
data_type var_name [, var_name2, ...]
• Generally structure members must each be defined on a separate line starting with the data type which is
followed by a space and the variable name. However, variables of the same type can be listed on the same line
as long as they are separated by commas.
Example
struct a_struct
int x, y
float a
string stringvar1, stringvar2
endstruct
The Struct - Endstruct language statement defines a structure without an instance: It is therefore just a template
that can be used later on in a script to declare a structure.
Example
Following you find an example for a structure definition which declares a date of birth.
struct BirthInfo
int Day, Year
string Month, Location
endstruct
The structure contains four member variables, two integers and two strings. All member variables have their own
names: Day, Month, Year and Location.
Comments
General structure naming rules are the same as for any other element in the Chilli language. In addition to those
the structure name must be unique and it can not be used for another structure or any other identifiers, such as a
variable, a constant, and so on.
The only legal operations on a structure are copying it or assigning to it as a unit, both of which include passing
arguments to functions and returning values from functions as well, taking its address with the reference
parameter and accessing its members. Structures can not be compared.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 2 - Data Types - 23

2.6.2 Declaring Structure Variables


After defining a structure the structure variables need to be declared. Structure variables are declared in the
following way:
Syntax
struct_name variable1 [, variable2, ...]
Example
Three structure variables are defined for the structure BirthInfo for the above mentioned example:
BirthInfo Elinor, Marianne, Margaret
The three structure variables Elinor, Marianne and Margaret are defined as structures of type BirthInfo.

2.6.3 Referencing Structure Members


The individual members of a structure can be used just like any other variable of the same type. Structure
members are accessed or referenced using the structure member operator dot (.) between the structure name and
the member name.
Example
In the structure data type of BirthInfo example from above, the member Year of the structure Elinor can
be accessed in the following way and have an integer assigned to it:
Elinor.Year = 1802
The structure name and its member’s name are separated by the dot (.) operator. This is to make sure that the
compiler knows that the integer value of 1802 is assigned to the variable called Year which is a member of the
structure Elinor.

2.6.4 Initialising Structures


Contrary to other programming languages such as C, structures in Chilli cannot be initialized at the same time as
they are declared. The initialization of a structure must be effected through a procedure, in which the structure is
used. Each structure member must be initialized separately on a new line.
Example
1 struct BirthInfo
2 int Day, Year
3 string Month, Location
4 endstruct
5 struct BirthInfo Elinor
6 proc ExampleProc
7 .....
8 Elinor.Day = 25
9 Elinor.Year = 1802
10 Elinor.Month = “May”
11 Elinor.Location = “Canterbury, Kent”
12 .....
13 endproc
When these statements are executed, they perform the following actions:
Lines 1-4 Define a structure type named BirthInfo.
Line 5 Declare an instance of structure type BirthInfo named Elinor.
Line 8 Initialise structure member Elinor.Day to the integer 25.
Line 9 Initialise structure member Elinor.Year to the integer 1802.
Line 10 Initialise structure member Elinor.Month to the string “May”.
Line 11 Initialise structure member Elinor.Location to the string “Canterbury, Kent”.

Numara Software, Inc. and BMC Software, Inc. Confidential.


24 - BMC FootPrints Asset Core - Chilli Reference

2.6.5 Structures Containing Structures


As already mentioned in the introduction to structures, structures can also contain structures as members. If you
need to manipulate more complex information about a subject, this might be useful.
Following you find an example for a structure declaration called EmployeeInfo, which contains three
structures detailing the data about an employee.
Example
struct EmployeeInfo
struct DeptInfo
struct Address
struct BirthInfo
endstruct
To reference the members of the structure you must use the member operator dot (.) twice. Do not forget that an
instance of the structure has to be declared before referencing the individual members.
Example
EmployeeInfo e128
e128.DeptInfo.Dept = “Finance”
e128.Address.Name = “Dashwood, John Adam”
e128.Address.County = “Kent”
e128.Address.Village = “Canterbury”
In the same way as simple structures, the initialization of a structure containing structures must be effected
through a procedure, in which the structures are used. Each structure member must be initialized separately on a
new line.To initialise a structure containing structures as members, the initialization values must be listed in the
proper order.
Example
The following procedure initializes the above mentioned structure:
1 proc ExampleProc
2 .....
3 e128.DeptInfo.Dept = “Finance”
4 e128.DeptInfo.Salary = 12458.56
5 e128.Address.Name = “Dashwood, John Adam”
6 e128.Address.County = “Kent”
7 e128.Address.Village = “Canterbury”
8 e128.Address.Street = “2, Old Church Lane”
9 e128.Address.Phone = “01248/121212”
10 e128.BirthInfo.Day = 15
11 e128.BirthInfo.Year = 1948
12 e128.BirthInfo.Month = “April”
12 e128.BirthInfo.Location = “Bath, Somerset”
14 .....
15 endproc
Lines 3-4 initialise the 2 members of structure DeptInfo, lines 5-9 initialise the 5 members of structure Address
and lines 10-12 the four members of structure BirthInfo.

2.6.6 Structures Containing Arrays


Structures can contain one or several arrays as structure members. The arrays can be of any Chilli data type such
as integer, string or even references to other structures. Remember however, that all members of the array must be
of the same data type.
Example
struct Employees

string Name[50], County[50]


float Salary[50]

endstruct

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 2 - Data Types - 25

This structure defines a structure of type Employees. The individual elements of arrays which are members of a
structure can be accessed by using the member operator dot (.) and the array subscript.
Example
Employees FinDept
FinDept.Name[3] = “Dashwood John”
FinDept.County[3] = “Cornwall, Devonshire”
In the same way as simple structures, the initialization of a structure containing arrays must be effected through a
procedure, in which the structure and array are used. Each member must be initialized separately on a new line.
To initialise a structure containing arrays as members, the initialization values must be listed in the proper order.
They are placed in the array elements in the order in which the elements are listed in the array definition.
Example
The following procedure initializes the above mentioned array:
1 proc ExampleProc
2 .....
3 FinDept.Name[3] = “Dashwood John”
4 FinDept.County[3] = “Cornwall, Devonshire”
5 FinDept.Salary = 12458.56
6 .....
7 endproc
The first two values in the procedure are the values for the two string array elements Name and County, the third
value is the float value for member Salary.

2.6.7 Structures Containing Arrays of Structures


as it is possible for structures to contain arrays and other structures it is also possible for structures to contain
arrays of structures. In fact, arrays of structures are very powerful programming tools, because they allow a
program to work with more than one instance of data.
Example
Imagine a program that needs to maintain the payroll list of a company. You can define a structure to hold each
employee’s name, some other respective company data, such as department and the salary.
struct Employee

string Name, Branch, Dept


float salary

endstruct
This structure however can only contain one single instance. Therefore an array of this structure is needed to hold
all entries for the structure of type Employee.
Employee SalaryList[500]
The above declares an array of structure of type Employee named SalaryList that contains 500 elements.
Each element is a structure of type Employee which is identified by subscript just like any other array element
types. Each of these structures has four elements, three of type string and one of type float.
The individual elements of arrays of structures can be accessed by using a combination of the member operator
dot (.) and the array subscript.
Example
SalaryList[15].Branch = SalaryList[234].Branch
To initialise structures containing arrays of structures as members, the initialization values must be listed in
order. They are placed in the structure members in the order in which the members are listed in the structure
definition.
Example
The following procedure initializes the above mentioned structure:
proc ExampleProc
.....
1 SalaryList[25].Name = “Dashwood, John Adam”

Numara Software, Inc. and BMC Software, Inc. Confidential.


26 - BMC FootPrints Asset Core - Chilli Reference

2 SalaryList[25].Branch = “Canterbury, Kent”


3 SalaryList[25].Dept = “Finance”
4 SalaryList[25].Salary = 12458.56
5 SalaryList[156].Name = “Ferrars, Edward Robin”
6 SalaryList[156].Branch = “Plymouth, Cornwall”
7 SalaryList[156].Dept = “Finance”
8 SalaryList[156].Salary = 4256.80
9 SalaryList[238].Name = “Middleton, John Charles”
10 SalaryList[238].Branch = “Exeter, Devonshire”
11 SalaryList[238].Dept = “Admin”
12 SalaryList[238].Salary = 9845.52
.....
endproc
This procedure initializes three instances of the array of the structure which contains the three string elements
Name, Branch and Dept as well as the individual structure member, the float value Salary. The members of the
individual structures/arrays are grouped together through consecutive lines.

2.7 Module Specific Data Types


A number of Chilli modules create their own additional module specific data types. These data types are either a
structure or a handle type called opaque handle. These opaque handles contain the necessary information for
accessing various data. They are returned by functions and passed on to other functions or procedures without
changes.
The individual data types is explained in detail in the chapter of the respective function module.

2.8 Automatic Data Type Conversions


All of Chilli’s data objects have a specific type. Chilli scripts often require that different types be combined in
expressions and statements. Many operators cause conversions and yield result types in a similar way. The effect
is to bring operands into a common type, which is also the type of the result. Casting or data type conversion is
this act of changing a value of one type into a similar value of another type. The resultant value might actually be
different to the starting one because it could have had its size changed (the number of bytes of memory used to
store the value) or it has been written into a type whose bits mean different things to the original.
In Chilli data type conversions happen automatically (Chilli does not support explicit casting), being used by the
compiler transparently to the coder. As the name implies, automatic casting is performed automatically by the
Chilli compiler.

2.8.1 Mathematical Operations


When a Chilli mathematical expression is evaluated the resulting value has a particular data type. If all operands
in the expression have the same data type, the resulting type is that data type as well. For example, if the variables
a and b are both integers, the data type of the result of the expression a + b also is an integer.
If the operands of an expression have different types, the result of the expression has the same data type as the
expression’s most comprehensive operand. From least-comprehensive to most-comprehensive the numerical data
types in Chilli are: int - float - double.
There are some rather easy rules that govern how the Chilli compiler applies this automatic casting.
• If either operand is a double, convert the other one to a double.
• Else, if either operand is a float, promote the other one to a float.
For example, if a is an integer and b is a float, evaluating the expression a*b causes a to be converted to a
float before the expression is evaluated. This does not mean that the type of the variable a is changed. It means
that a float copy of a is created and used in the expression evaluation. The value of the expression is of type
float.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 2 - Data Types - 27

Example
Following you find a rather extreme and farfetched but explicit example of this concept of data type conversion.
This mathematical code presents all three numerical data conversions handled by Chilli:
int iValue
float fValue
double dValue
iValue = 295
fValue = 4.8e31
dValue = iValue * fValue
Here, because an integer value is being multiplied by a floating point value and the result is to be stored in a
double precision floating point value, much casting is employed by the compiler. When the compiler sees that the
* operator has operands of different types it has to convert them to the same type. It does so by taking the lowest
type and casting it into the higher one. In this example the integer is cast into a float before the * is performed. For
the result, the float is then cast into a double before being stored in dValue.

2.8.2 Assignment
Data conversion also occurs with the assignment operator. The expression on the right hand side of the operator is
always cast to the data type of the left hand side. Depending on the data type of the left hand side this might imply
a ‘downgrade’ for the right hand side.
Example
If f is a float and i is an integer, the integer value is ‘upgraded’ to a float.
f = i
If the assignment is the other way round,
i = f
the float f is downgraded to an integer. The decimal value is truncated, that is, the decimal part is lost on
conversion to integer. Be aware, that decimals are always rounded down. For example, 3.14 is rounded down to 3
as usual, but 3.98 also becomes 3! Remember also, that the variable f in itself is not changed, because the
downgrade only affects a copy of the value. Therefore, after the following statement is executed:
float f = 3.98
int i
i = f
the variable i has the value 3 but f still has the value 3.98.

2.8.3 Function Arguments


as an argument of a function call is an expression, automatic data type conversion is also used when arguments
are passed to functions and when function return values are assigned. The rules followed are the same as for the
mathematical conversion.

Numara Software, Inc. and BMC Software, Inc. Confidential.


28 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Variables

This chapter introduces another very important concept of programming languages: variables. Variables are
named data storage locations in your computer’s memory that have values assigned to them. They provide a way
to manipulate values by name. The variable's name is a label on one of these data storage locations, which enables
you to find it easily without knowing its actual memory address.
The value associated with a name can vary, therefore these data storage locations are called variables. For
example, the following line of a Chilli script assigns the value 5 to a variable named x.
x = 5
The following line adds 10 to the value of x and assigns the result to a new variable called sum.
sum = x + 10
Similar to C you need to declare all variables in a Chilli script before using them. Variables are declared the same
way as in C - by first defining the data type of the variable and then declaring the name of the variable. It is also
possible to declare multiple variables at the same time, as long as they are separated by commas.
Int Variable1 [, Variable2, ...]
string Variable1 [, Variable2, ...]
Variables in Chilli can be of the following data types:
• Integer
• Long integer
• Character
• Floating point
• Double precision floating point
• Boolean
• String
• Array
• Structure

3.1 Variable Scope - Global and Local Variables


Before a variable can be used in a Chilli script it must be declared. Variables can be declared with global or local
scope. The scope of a variable refers to the extent to which different parts of a program have access to the variable.
When talking about scope in Chilli, the term variable refers to all Chilli data types: simple variables, arrays,
structures, and so forth. A variable’s scope also determines the lifetime of a variable, because it decides for how
long a variable persists in memory, or when a variable’s storage is allocated and de-allocated.

3.1.1 Global or External Scope


A global or external variable is a variable defined outside of any procedure. This includes outside of main() as
well. The scope of a global variable is the entire program. This means that a global variable is visible throughout
every function and procedure within your entire program.
However, be careful when declaring global variables. Only use them when all or most of your scripts’ functions
and procedures need to access the variable.

Numara Software, Inc. and BMC Software, Inc. Confidential.


30 - BMC FootPrints Asset Core - Chilli Reference

When functions or procedures use external variables those should be declared with the extern keyword to mark
them as external variables.
Syntax
extern data_type variable

3.1.2 Local Scope


A local variable is a variable defined within a procedure. The scope of the local variable is limited to the
procedure in which it is defined. Local variables are not automatically initialized to 0 by the compiler, they must
explicitly be assigned a value before they are used for the first time.
Local variables are automatic by default. That means that they are newly created each time the procedure is
called, and they are destroyed when the procedure terminates. This implies that a local variable does not retain its
value between calls to the procedure in which it is defined.

3.2 Predefined Variables


Upon starting the Chilli compiler declares and defines a number of variables with global scope which are used by
various functions to determine their default operation. These variables can be read and written to like any other
variable, although special care must be taken when changing their values because this can change the operation
of functions which depend on them. The table below lists the predefined variables along with their type and
meaning.

Name Type Description


ErrCode Integer The error code from the last function executed. This is set by each function.
The default value is ERR_SUCCESS.
ErrHandler String The name of the default error handler in case of run-time errors.
ErrLine Integer The line number in the script where the latest run-time error has occurred.
IntBase Integer The integer conversion base used by the Integer to String conversion function
MakeStr.
LogFile String The name of the default log file. This is set to the name of the script file except
it has a .log extension. If required, it can be changed.
ScriptFile String The name of the script file currently being executed. This value should not be
changed.
StrCase Boolean Case sensitivity flag for string comparisons.

3.2.1 ErrCode
The error code from the last executed function. This variable is cleared before each new function execution and is
set, if the function has an error. If an error occurs and the ErrCode variable is set, it must be copied to a new
variable before calling a function, otherwise it is lost. The default value is ERR_SUCCESS. For a complete list of
possible error codes see Chilli Error Codes on page 677.

3.2.2 ErrHandler
The ErrHandler variable defines the default error handler in case of run-time errors. This can be one of the
following 2 predefined constants:

Value Type Meaning


DEFAULT_HANDLER String The default handler prints the error code with a message to the file as configured in
the Chilli.ini file and terminates the program.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 3 - Variables - 31

Value Type Meaning


INLINE_HANDLER String The error is handled by a procedure that is specified by the INLINE_HANDLER’s
settings. These define the name of the procedure to be called and executed in Chilli.
If the procedure to be called is not found the script terminates with a fatal error.
Otherwise the called script is responsible for checking the result of each function
and taking appropriate action.
The Syntax of the INLINE_HANDLER is the following:
proc <proc_name> (Int ErrCode)

The default value is DEFAULT_HANDLER.

3.2.3 IntBase
The integer conversion base used by the Integer to String conversion function. This can be set to any of the
following 3 predefined constants:

Value Type Meaning


INTBASE_DEC Integer The integer value is converted into a string using base 10.
INTBASE_HEXU Integer The integer value is converted into a hexadecimal string using upper-case letters for
A-C.
INTBASE_HEXL Integer The integer value is converted into a hexadecimal string using lowercase letters for
a-c.

The default value is INTBASE_DEC.

3.2.4 LogFile
This variable defines the name of the default log file. This is set to the name of the script file except it has a .log
extension. If required, it can be changed.
If a preload script is specified through the Preload entry in the [ChilliConfig] section of the chilli.ini
file, the LogFile variable is set according to the name of the preload file as found in the chilli.ini file. When
the preload file has been executed and the main script starts, the variable is set to a new value based on the name
of the main script file. This means that if the variable is set in the preload script, the changes is lost as soon as the
main script starts.

3.2.5 ScriptFile
This variable defines the name of the script file currently being executed. This value should not be changed.
If a preload script is specified through the Preload entry in the [ChilliConfig] section of the chilli.ini
file, the ScriptFile variable is set according to the name of the preload file as found in the chilli.ini file. When
the preload file has been executed and the main script starts, the variable is set to a new value based on the name
of the main script file. This means that if the variable is set in the preload script, the changes is lost as soon as the
main script starts.

3.2.6 StrCase
Determines case sensitivity in string comparisons, such as <=, == and !=. This can be one of the following 2
predefined constants:

Value Type Meaning


TRUE Boolean All comparison functions are using case sensitive compare for string parameters.
FALSE Boolean All comparison functions are using non-case sensitive compare for string parameters.

The default value is FALSE.

Numara Software, Inc. and BMC Software, Inc. Confidential.


32 - BMC FootPrints Asset Core - Chilli Reference

3.3 Variables on the Command Line


One of the most powerful features of the Chilli compiler is its ability to accept parameters on the command line
for use within the script being executed. The command line parameter mechanism is very simple in principle but
also very flexible. Formally, the syntax for passing parameters on the command line is:
Syntax
chilli.exe ScriptFile [, Param = Value, ...] [Option ...]
Chilli_Executable_Filepath (chilli.exe) defines the path to the Chilli executable file chilli.exe, relative to
the location of the script to execute, for example, ../bin/chilli.exe.
ScriptFile is the name of the script to be executed.
Param is the variable name of the parameter.
Value is the initial value of the variable.
Option are additional command line options.

3.3.1 chilli.exe ScriptFile


Typically the compiler is started with just the script file as its only parameter. This is what happens if you drag
and drop a script file on top of the chilli executable in the File Manager or Explorer. The Explorer calls the Chilli
executable with the script file as its only command line parameter.
The ScriptFile can also be a URL pointing to a file on another system. In this case the file is downloaded into a
local copy. Be aware, that the local copy is not deleted after the script has been executed. The supported protocols
are HTTP, FTP and SMB (Microsoft Lan Manager). For the correct syntax of the URLs refer to chapter File
Manipulation Functions on page 170 in the Chilli Function section which explains in detail the usage of URLs in
Chilli.

3.3.2 Param = Value


The above syntax can be used to supply additional parameters to the script. Each parameter name must be
followed by an equal sign (=) and then its initial value which can be a constant or an expression. Pairs of
parameter name and value are separated by a single comma (,). Note that in this way, the script file name is the
only parameter which appears without a following equal sign.
Each parameter supplied on the command line becomes a globally declared variable which can be used like any
other variable in the script. The type of the variable is determined by the type of the value after the equal sign. To
declare a string parameter which contains spaces, the value must be enclosed in hard (’) or soft (“) quotes. The
escape rules which normally apply to hard/soft quotes are not applicable in this situation. If the value is not
quoted, the compiler attempts to evaluate the supplied text as a numeric value resulting as an integer, a float or a
double. If this fails, then the initialization of the script fails and it is terminated.
As all command line parameters are effectively globally declared variables, they must be explicitly declared
within the script as global variables with the extern keyword. When Chilli completes the initialization, the
command line parameters need to be included in the list of global variables and, if they are not declared again
within the script, a fatal parse error occurs. As with normal global variables, the names can be used for local
variables without error, in which case the local scope names take precedence over the global names.
You can use the functions Defined and Export within your scripts to determine whether a particular command
line parameter has been supplied, and if not, to declare and initialise it with a default value.
Command Line Options
The Chilli language provides a number of options which can be used on the command line. These are optional
and have both a ’short’ and a ’long’ version. The following table lists and explains these commands:

Long Command
cmd Description
Format
-v --version Show Chilli executable version string.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 3 - Variables - 33

Long Command
cmd Description
Format
-i --inifile <path> Define the Chilli initialization file which is to be used when executing this
<path> Chilli script. The option must be followed by the absolute or relative path of
the initialization file. For more information about user defined initialization
files refer to chapter The Chilli Configuration File on page 65 later on in this
section.
-co --compileonly Use this option to check whether a script compiles correctly. Chilli tries to
compile the script and displays a message to indicate failure or success.
The script is NOT executed.
Examples:
Typically to start a Chilli script, say example.chl, a command line similar to the following would be used:
c:\Programm Files\BMC Software\Client Management\bin\chilli.exe example.chl
To check first if the script compiles correctly the command line looks as follows:
c:\Programm Files\BMC Software\Client Management\bin\chilli.exe example.chl -co
or
c:\Programm Files\BMC Software\Client Management\bin\chilli.exe example.chl --compileonly
If, for example, the script did not compile correctly, we might check to see if the Chilli executable we used is that
of the newest version:
c:\Programm Files\BMC Software\Client Management\bin\chilli.exe --version
orbin\
c:\Programm Files\BMC Software\Client Management\bin\chilli.exe example.chl -v
If the file is to be executed with specific settings defined in a user defined initialization file, you can specify this
through the following command line.
c:\Programm Files\BMC Software\Client Management\bin\chilli.exe example.chl -i ’c:\Programm
Files\BMC Software\Client Management\config\mychilli.ini’
Now, to start the same script with an additional string parameter called User with the value “John Smith”, we
could use either of the following command lines:
c:\Programm Files\BMC Software\Client Management\bin\chilli.exe example.chl, User=“John
Smith”
or
c:\Programm Files\BMC Software\Client Management\bin\chilli.exe example.chl, User=“John” +
“Smith”
If we now want to add an additional integer parameter, the command line becomes:
c:\Programm Files\BMC Software\Client Management\bin\chilli.exe example.chl, User=“John
Smith”, Age=32
To call the script with an initialization file as well as a user parameter the command line looks as follows:
c:\Programm Files\BMC Software\Client Management\bin\chilli.exe example.chl -i ’c:\Programm
Files\BMC Software\Client Management\config\mychilli.ini’ User=“John Smith”

3.4 Environment Variables


The Chilli executable can configure itself through the use of environment variables. Following you find a table
that lists all supported environment variables and their description:

Name Description
CHILLI_INI_FILE If this variable is set it determines the path of the Chilli initialization file used by the program.
If the environment variable is not set or does not exist and no command line option
specifying an initialization file is set, the default behavior is to use a file called
chilli.ini which is in the same directory as the executable.

Numara Software, Inc. and BMC Software, Inc. Confidential.


34 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Constants

Constants are effectively read only variables. They are defined once and their value cannot be changed. The Const
(or Constant) statement declares and defines a constant value. All constants have global scope. Constants can be
declared anywhere in a script BUT in a procedure. The naming rules for constants are the same as those for any
other variable, data type or procedure in Chilli. Make sure you do not use keywords as constant names.
Syntax
Constant Name Value
Const Name Value
Name is the name given to the constant.
Value is the expression to be assigned to the constant.
Comments
The type of the constant is determined by the type of the Value expression which can be any Chilli data type. The
Value expression can be an actual value, such as 123 or “Hello, World”, or a complex expression using function
calls and operators. On execution of the statement, the Value expression is evaluated and depending on its type
the constant is declared and set to the value.
Declaring a constant more than once, even if the same value and type are used, causes a fatal script error.
Therefore, the most suitable place for the declarations is at the beginning of a script.
When using a simple value (not an expression using functions or operators) in the declaration, the compiler
selects the type of the constant, based on whether the value is a quoted (single or double) string or not. If the value
is not a string, it is evaluated as if it is a numeric data type. If the evaluation fails, a fatal script error terminates the
script. The following declarations, for example, are valid:
Constant Homepath ‘C:\home’ # String
Constant Folder ‘16’ # String
Constant ETA ‘20.56’ # String
Constant RunLevel 12 # Integer
Constant Pi 3.14 # Float
Constant pi_2 3.141592653589794 # Double
and the following causes a fatal error:
Constant Noquote ‘C:\home
Constant BadQuote ‘C:\home”
Constant BadInt 16abc
Constant Define 5 #define is a keyword

4.1 Constant Types


Like variables, constants are data storage locations used by the program and as the name already implies,
constants are values that never change. Chilli handles the following different types of constants:
• integer constants
• long constants
• character constants
• floating point constants

Numara Software, Inc. and BMC Software, Inc. Confidential.


36 - BMC FootPrints Asset Core - Chilli Reference

• double precision floating point constants


• boolean constants and
• string constants

4.1.1 Integer Constants


An integer constant consists of a sequence of digits only. A decimal integer is a sequences of the digits 0-9 that
does not begin with a 0. If the sequence has a leading 0, the integer is a octal integer. If a sequence of digits is
preceded by 0x or 0X it is taken to be a hexadecimal integer. Those also include the letters A or a through F or f
representing the values 10 through 15.
Examples
ConstantDecimalInt12
ConstantD_OInt05421
ConstantHexaInt0x1000008

4.1.2 Floating Point and Double Precision Floating Point Constants


A floating point constant or double precision floating point constant consists of an integer part, a decimal point,
and a fraction part. The integer as well as the fraction part consist of a sequence of digits. Either the integer part or
the fraction part (but not both) can be missing. Floating point constants can be either in standard notation, for
example, 3.1415, .5, 4., or in scientific notation, for example, 8.45 , 8.45e-12, 32.525 , 32.525E20.
-12 20

Examples
Constantpi3.14159
ConstantLitPerGal.26425
Constantcount12

4.1.3 Boolean Constants


A Boolean constant has only two possible values: its two legal states which are represented by the keywords true
and false. A Boolean value represents a truth value - it declares if something is true or not.
Examples
Constanttest1true
Constanttest2false

4.1.4 String Constants


A string constant is a sequence of characters surrounded by quotation marks, either soft (“) or hard (‘). The only
difference between hard and soft quotes is that Chilli interprets backslash (\) characters within a soft quote pair as
an Escape Sequence which can change the meaning of the string. Any backslash characters within a hard quoted
string are used verbatim, making hard quotes suitable for specifying file paths which contain backslashes. A
string must be delimited by a pair of soft or hard quotes, not a combination of both.
Examples
ConstantNewPath‘c:\Programm Files\BMC Software\Client Management’
ConstantIntroText“Welcome to the Chilli Language”

4.2 Constant Scope


Before a constant can be used in a Chilli script it must be declared. Constants can only be declared with global
scope. When talking about scope in Chilli, the term global refers to the extent to which different parts of a
program have access to the constant. The scope of a global constant is the entire program. This means that a
constant is visible throughout every procedure within your entire program.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 4 - Constants - 37

4.3 Predefined Constants


Upon starting the Chilli compiler declares and defines a number of constants with global scope which are used by
various functions to determine their default operation. You find a complete list of predefined constants along with
their data types and meanings in Predefined Variables and Constants on page 683 of this manual.

Numara Software, Inc. and BMC Software, Inc. Confidential.


38 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Expressions

An expression is a phrase of Chilli, that the compiler can evaluate to produce a value. It is a combination of
constants, variables and operators. Simple expressions are constants or variable names such as these:
1.7 # a numeric literal
“Oh no! There is no tea left!”# a string literal
true # a boolean literal
x # the variable x
sum # the variable sum
exit(0) # a function call
The value of a constant expression is simply the constant itself. The value of a variable expression is the value the
variable refers to.
More complex expressions than these can be created by connecting simple expressions through operators. For
example the above mentioned expressions 1.7 and x:
x + 1.7
The value of this ‘combined’ expression is determined by adding the values of the two simpler expressions. The
plus sign (+) in this example is an operator that is used to combine two expressions into one more complex
expression. Another operator is - which is used to combine expressions by subtraction:
(s + 1.7) - sum

5.1 Expression Operators


Operators are fundamental to most programming languages. This chapter explains how they work in Chilli. If you
are familiar with C or Java you will notice that Chilli expressions and operators are very similar to those you
already know. Contrary to some other programming languages which mostly have three different types of
operators Chilli only handles unary and binary operators.
• Unary operators take only one parameter at a time and act on it, that is, a unary operator converts a single
expression into a more complex expression.
• Binary operators take two parameters and perform an operation using those parameters, that is the operator
combines the two expressions into a single, more complex expression.
Apart from the distinction of unary and binary operator, the expression operators can also be divided into broader
categories by their functions:
• Arithmetic Operators
• Comparison Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
All operators have the following syntax:
Syntax
[Parameter1] Operator Parameter2

Numara Software, Inc. and BMC Software, Inc. Confidential.


40 - BMC FootPrints Asset Core - Chilli Reference

The following table shows the available operators in the Chilli Language. The column called Symbol in the table
refers to the operator, the column P shows the operator precedence and the column Data Type specifies the
type(s) of operand(s) that can be used with the respective operator. In the description column LHS (Left Hand
Side) refers to Parameter1 and RHS (Right Hand Side) refers to Parameter2.
In cases where the unary and binary operator take the same form the unary operator always takes precedence over
the binary operator.

Symbol P Data Types Description


() 12 String, Int, Float, Double Used to change the evaluation precedence in a compound
statement.
- 11 Int, Float, Double Unary operator - used to reverse the sign of the argument.
! 11 boolean, Int, Float, Double Unary operator - used to perform a logical negation, that is,
a ‘not’.
* 10 Int, Float, Double Multiply the LHS by the RHS.
/ 10 Int, Float, Double Divide the LHS by the RHS.
% 10 Int, Float, Double Calculate the remainder when the LHS is divided by the
RHS.
+ 9 String, Int, Float, Double Add the LHS to the RHS. If used with two string values, this
operator concatenates the two strings together.
- 9 Int, Float, Double Subtract the RHS from the LHS.
<< 8 Int, Float, Double Shift all bits in the LHS to the left by the number of places
specified by the RHS.
>> 8 Int, Float, Double Shift all bits in the LHS to the right by the number of places
specified by the RHS.
< 7 String, Int, Float, Double If the LHS is smaller than the RHS, the result is non-zero.
When used with strings, the value is true if the first
mismatched character in the LHS is alphabetically lower
than that in the RHS.
> 7 String, Int, Float, Double If the LHS is larger than the RHS, the result is non-zero.
<= 7 String, Int, Float, Double If the LHS is smaller than or equal to the RHS, the result is
non-zero.
>= 7 String, Int, Float, Double If the LHS is larger than or equal to the RHS, the result is
non-zero.
== 6 String, Int, Float, Double If the LHS is equal to the RHS, the result is non-zero.
!= 6 String, Int, Float, Double If the LHS is not equal to the RHS, the result is non-zero.
& 5 Int, Float, Double If a bit is set in the LHS AND in the RHS, a corresponding
bit is set in the result.
| 4 Int, Float, Double If a bit is set in the LHS AND in the RHS, or in the LHS OR
the RHS, a corresponding bit is set in the result.
^ 3 Int, Float, Double If a bit is set in the LHS OR in the RHS, a corresponding bit
is set in the result.
&& 2 Int, Float, Double If both the LHS and the RHS are non-zero, the result is
non-zero.
|| 1 Int, Float, Double If either the LHS or the RHS is non-zero, the result is non-
zero.

5.2 Operator Precedence


In the above shown table the column labelled P specifies the precedence of each operator. The operator
precedence controls the order in which operations are performed. Operators with a higher number in this column
are executed before those with a lower number.
For example, the expression
3*5+5

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 5 - Expressions - 41

is equal to 20 and NOT 30 as the multiplication operator has a higher precedence than the addition operator. To
change the order, use parenthesis as follows:
3*(5+5)
In this case the expression in the parentheses is evaluated first and the final result is 30.
Chilli has no predefined limit to the level of parenthesis nesting or the number of operators used within an
expression.

5.3 Operands
When constructing Chilli expressions you must pay attention to the data types that are being passed to operators,
and to the data types that are returned. Different operators expect their operands’ expression to evaluate to values
of a certain type. It is for example not possible to multiply strings. Furthermore, some operators behave differently
depending on the type of the operands. Most notably the + operator adds numeric operands but concatenates
string operands.
Operators do not always return the same data type as their operands. The comparison operators for example takes
operands of various types, but when comparison expressions are evaluated, they always return a boolean result
that indicates whether the comparison is true or not.

5.4 Arithmetic Operators


This paragraph explains in more detail the arithmetic operators shown in the table above. These arithmetic
operations do not change the values of the operands. They return a value that is normally assigned to a variable.
Chilli handles the following unary and binary arithmetic operators:

5.4.1 Unary Operators


The Chilli language supports the following unary arithmetic operator:

5.4.1.1 Negation
The unary - operator reverses the sign of the argument and works for integers, floating values and double
precision floating values. The result is always numeric, so unary plus is sometimes used for type conversion.
Examples
- 1,248 evaluates to -1,248
- (-12.458) evaluates to 12.458

5.4.2 Binary Operators


The Chilli language supports the following five binary arithmetic operators:

5.4.2.1 Addition
The + operator adds two numeric operands. If both operands are strings, a string is returned that is the
concatenation of the second operand onto the first. If one operand is a string and the other a numeric data type,
the number is converted into a string and concatenated with the other string.
Example 1
3 + 5 = 8
“Today is “ + “Tuesday“ = “Today is Tuesday”
“3” + 5 = “35”
5 + “3” = “53”
Example 2
...
char a
a = “y”

Numara Software, Inc. and BMC Software, Inc. Confidential.


42 - BMC FootPrints Asset Core - Chilli Reference

“Toda” + a = “Today”
...

5.4.2.2 Subtraction
The - operator subtracts its second operand from its first. Both operands must be numeric data types otherwise
the operation terminates with an error. The more complex operand determines the return type.
Examples
8 - 3 = 5
8 - 3.5 = 4.5
8.5 - 3 = 5.5

5.4.2.3 Multiplication
The * operator multiplies its two operands, which must be both numeric data types, otherwise the operation
terminates with an error. The more complex operand determines the return type.
Examples
3 * 5 = 15
5.5 * 3.5 = 19.25
5.5 * 3 = 16.5
3 * 5.5 = 16.5

5.4.2.4 Division
The / operator divides its first operand by its second. Both operands must be numeric data types, otherwise the
operation terminates with an error. The more complex operand determines the return type.
Examples
16 / 3 = 5
25.5 / 5.2 = 4.9
62.45129845 / 5 = 12.49025969

5.4.2.5 Modulo
The % operator returns the remainder when the first operand is divided by the second operand, with both
operands being integers. Any floating point or string value is not acceptable.
Examples
16 % 3 = 1

5.5 Comparison Operators


This section describes the comparison operators used in Chilli. These are operators that compare values of
various types and return a boolean value (true or false) depending on the result of the comparison. They are
most commonly used in if or while statements to control the flow of the program execution. The two
operands on comparisons must either always be two strings or two numeric values.
In Chilli numbers and strings are compared by value. This means that if two variables contain the same value,
they are equal. Strings can not be compared to any type of numeric value. Two strings for example are only equal
if they contain exactly the same characters in the same order. When comparing two strings the comparison
operator first checks for equality. It compares the whole string letter for letter up to the end of the string or the first
inequality. If it finds an inequality it checks the ASCII code for the two letters in question and thus determines
which letter is larger. Having established the relationship between the unequal letters it checks if the comparison
operator used evaluates to true or false.
Example 1
The strings Filepath and Filepaths are compared. Chilli compares F to F, i to i, and so on. When it arrives
at the end the first string does have no more letters which is equal to 0, while the second still has the letter s. The
ASCII code for s is larger than 0, therefore the string Filepaths is larger that the string Filepath.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 5 - Expressions - 43

Example 2
The strings Filepath and FilePath are compared. Again Chilli compares F to F, i to i, and so on. When it
arrives at the letter p it finds that the ASCII code for the small letter p (112) is larger than the ASCII code for the
capital letter P (80). Therefore the string Filepaths is larger than the string FilePath.

5.5.1 Equality
If the two operands are equal, the == operator returns true and if they are not, it returns false. The operands
can be any numeric data type or a string and the definition of “equal” depends on the type.
Examples
(8 - 4) == (10 - 6) evaluates to true
“HomePath” == “HomePaths” evaluates to false

5.5.2 Inequality
The != operator tests for the exact opposite of the == operator. If two variables are equal to each other, then
comparing them with the inequality operator returns false. On the other hand, comparing two variables which
are not equal to each other with != returns true. The operands can be any numeric data type or strings, however,
strings can not be compared to any type of numeric value.
Examples
10 != 20 evaluates to true
“HomePath” != “HomePaths” evaluates to true

5.5.3 Less Than


If its first operand is less than its second operand, the < operator evaluates to true, otherwise it evaluates to
false. The operands can be any numeric data type or string, however, strings can not be compared to any type of
numeric value. Strings is ordered alphabetically, by character encoding.
Examples
12 < (9 - 6) evaluates to false
“HomePath” < “HomePaths” evaluates to true

5.5.4 Greater Than


If its first operand is greater than its second operand, the > operator evaluates to true, otherwise it evaluates to
false. The operands can be any numeric data type or a string, however, strings can not be compared to any type
of numeric value. Strings is ordered alphabetically, by character encoding.
Examples
10 > 12 evaluates to false
“HomePath” > “HomePaths” evaluates to false

5.5.5 Less Than or Equal


If its first operand is less than or equal to its second operand, the <= operator evaluates to true, otherwise it
evaluates to false. The operands can be any numeric data type or a string, however, strings can not be compared
to any type of numeric value.
Examples
12 <= (9 - 6) evaluates to false
“HomePath” <= “HomePaths” evaluates to true

5.5.6 Greater Than or Equal


If its first operand is greater than or equal to its second operand, the >= operator evaluates to true, otherwise it
evaluates to false. The operands can be any numeric data type or a string, however, strings can not be compared
to any type of numeric value.
Examples
10 >= 12 evaluates to false
“HomePath” >= “HomePaths” evaluates to false

Numara Software, Inc. and BMC Software, Inc. Confidential.


44 - BMC FootPrints Asset Core - Chilli Reference

5.6 Logical Operators


The logical operators expect their operands to be numeric data types, and they perform boolean algebra on them.
In programming they are used with the comparison operators to express complex comparisons that involve more
than one variable.

5.6.1 Unary Operators


The Chilli Script language supports the following logical unary operator:

5.6.1.1 Logical Not


The unary ! operator performs a logical negation, that is, a “not”. The operand can be any boolean value or a
numeric value (integer, float or double). The result of the operation always is a boolean TRUE or FALSE.
Examples
! TRUE evaluates to FALSE
! 25,452897451 evaluates to FALSE
! -15.457 evaluates to FALSE
! 0 evaluates to TRUE
! (5*9 - 45) evaluates to TRUE

5.6.2 Binary Operators


The Chilli Script language supports the following two logical binary operators:

5.6.2.1 Logical And


If and only if its first operand and its second operand are both true, the && operator evaluates to true.
Examples
( 5 == 5 ) && ( 6 != 2 ) evaluates to true because both operands are true
( 2 == 1 ) && ( 5 == 5 ) evaluates to false because operand 1 is false

5.6.2.2 Logical Or
If its first operand or its second operand (or both) are true, the || operator evaluates to true.
Examples
( 5 > 1 ) || ( 6 < 2 ) evaluates to true because one operand (operand 1) is true
( 2 == 1 ) || ( 4 + 5 >= 20 - 5 ) evaluates to false because both operands are false

5.7 Bitwise Operators


The bitwise operators require numeric operands which have integral values. They operate on these integer
operands using a 32-bit integer representation instead of the equivalent floating point representation. Float and
double values could be used, however, because they is converted to integers for execution of the operation. All
three bitwise operators used in Chilli perform boolean algebra on the individual bits of the operands, behaving as
if each bit in each operand was a boolean value. All three of these operators are used for low-level manipulation of
binary numbers.

5.7.1 Bitwise And


The & operator performs a boolean AND operation on each bit of its integer arguments. Only if a bit is set in both
operands, the corresponding bit is set in the result.
Examples
00011010 & 00001000 evaluates to 00001000
00011010 & 00000001 evaluates to 00000000

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 5 - Expressions - 45

5.7.2 Bitwise Or
The | operator performs a boolean OR operation on each bit of its integer argument. If a bit is set in one or both
operands, the corresponding bit is set in the result.
Examples
00011010 | 00001000 evaluates to 00011010
00011010 | 00001001 evaluates to 00011011

5.7.3 Bitwise Xor


The ^ operator performs a boolean exclusive OR operation on each bit of its integer argument. If a bit is set on
one (but not both) of the two operands, the corresponding bit is set in the result of this operation.
Examples
00011010 ^ 00001000 evaluates to 00010010
00011010 ^ 00001001 evaluates to 00010011

5.7.4 Shift Left


The << operator shifts a bit pattern specified in its first operand to the left (without sign extension) by the
number of places specified in the second operand, which should be an integer between 1 and 31. 1s or 0s that are
shifted to the end of a word simply disappear whilst 0s are generated and inserted at the other end.
Examples
00011010 << 2 evaluates to 01101000
00011010 << 6 evaluates to 10000000
a = 5 >> 1 evaluates to a=2
A zero is used for the new first bit, and the value of the 32nd bit is lost. Shifting a value left by one position is
equivalent to multiplying by 2. Shifting two positions is equivalent to multiplying by 4, and so on.

5.7.5 Shift Right


The >> operator shifts a bit pattern specified in its first operand to the right (without sign extension) by the
number of places specified in the second operand (an integer between 1 and 31). 1s or 0s that are shifted to the
end of a word simply disappear whilst 0s are generated and inserted at the other end.
Examples
00011010 >> 2 evaluates to 00000110
00011010 >> 6 evaluates to 00000010
a = 3 << 2 evaluates to a=12
Shifting a value right one place is equivalent to dividing by two (discarding the remainder), shifting right tow
places is equivalent to integer division by four, and so on.

5.8 Assignment Operators


The assignment operator is the equal sign (=).
Syntax
variable = expression
Its use in Chilli is somewhat different from its use in normal mathematics.
x = y
in a Chilli script does not mean “x is equal to y”. Instead it means “assign the value of y to x”. The = operator
expects its left-hand operand to be a variable, or an element of an array, and its right-hand operand to be an
arbitrary value of any data type. The = operator assigns the value on the right to the variable, element, or
property on the left so that future uses of the variable, element or property refer to the value.

5.8.1 Assignment with Operation


Besides the normal = assignment operator Chilli also supports a number of other assignment operators that
provide a short-cut by combining assignment with some other operation.

Numara Software, Inc. and BMC Software, Inc. Confidential.


46 - BMC FootPrints Asset Core - Chilli Reference

For example the += operator performs addition and assignment at the same time. The following expression:
total += sales_tax
is equivalent to this regular assignment:
total = total + sales_tax
The += operator works for numeric data types as well as strings. For numeric operands it performs addition and
assignment, for string operands it performs concatenation and assignment.
The following table lists all assignment with operation operators that are supported in Chilli:

Operator Data Type Description Example Equivalent


+= String, Int, Add the LHS to the RHS and assign result to LHS. a += b a=a+b
Float, Double If used with two string values, this operator
concatenates the two strings together.
+= Array Increase the number of elements of an array. array += #Elements
-= Int, Float, Subtract the RHS from the LHS and assign result a -= b a=a-b
Double to LHS.
-= Array Reduce the number of elements of an array. array -= #Elements
*= Int, Float, Multiply the LHS by the RHS and assign result to a *= b a=a*b
Double LHS.
/= Int, Float, Divide the LHS by the RHS and assign result to a /= b a=a/b
Double LHS.
%= Int Calculate the remainder when the LHS is divided a %= b a=a%b
by the RHS and assign result to LHS.
<<= Int, Float, Shift all bits in the LHS to the left by the number of a <<= b a = a << b
Double places specified by the RHS.
<<= Array Append a specific element to the end of an array. Array <<=
“array_element”
>>= Int, Float, Shift all bits in the LHS to the right by the number a >>= b a = a >> b
Double of places specified by the RHS.
&= Int, Float, If a bit is set in the LHS AND in the RHS, the a &= b a=a&b
Double corresponding bit is set in the result. The result is
assigned to the LHS.
|= Int, Float, If a bit is set in the LHS AND in the RHS, or in the a |= b a=a|b
Double LHS OR the RHS, the corresponding bit is set in
the result. The result is assigned to the LHS.
^= Int, Float, If a bit is set in the LHS OR in the RHS, the a ^= b a=a^b
Double corresponding bit is set in the result. The result is
assigned to the LHS.

5.8.2 Assignment Operators and Arrays


Three of the above mentioned assignment operators behave differently when applied to arrays:
Append a specific element at the end of an array (<<=)
In the Chilli language you can automatically add an array element to an existing array through the append
assignment operator.
Syntax
Array <<= "ArrayElement"
The append allocates the necessary space automatically, therefore it is not necessary to change the size of the
array before the append. The new element is appended to the end of the array. If the appended value is a
structure or any other variable, a copy of it is appended and not the structure itself.
Resize an array (+= / -=)
Chilli offers the following two assignment operators to resize an existing array:
§ Increase the number of elements of an array (+=).
Syntax:
array += int

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 5 - Expressions - 47

§ Reduce the number of elements of an array (-=).


Syntax:
array -= int
In both cases int can be a positive or a negative integer to represent the adjustment required. The changes in
the array to adapt to the new size always takes place at the end of the array. That is, if the size of the array is
reduced, the last elements of the array is cut, and if the array is extended, new empty elements is added at the
end of the original array.

Numara Software, Inc. and BMC Software, Inc. Confidential.


48 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Language Statements

The Chilli language defines a number of statements that form the core of the language. Although similar in syntax
to functions, statements differ from functions in the following ways:
• Statements do not have any return values. Therefore, statements can not be used in expressions.
• As a rule, statements must appear on a line by themselves together with any arguments that they might need.
For example, the If statement must appear on a line by itself with its condition expression. It must not be
followed on the same line with a function call or an EndIf statement.
Following you find a table listing all currently available statements of the Chilli language:

Statement Description
Include Include additional scripts into the main script
Call Call another script
Struct / Endstruct Define a collection of variables of different types
Proc / Endproc User defined procedure definition
Return Return from a user defined procedure
If / Else / Elif / Endif If-then-Else conditional execution construct
While / Endwhile While-Wend conditional looping construct
For / Endfor For-Endfor conditional looping construct

Although this reference and related documentation denote the statements using a capital letter as the first letter,
the case of the letters is not significant, so for example, include, Include and INCLUDE are equivalent.

6.1 Include
Include additional chilli scripts or chilli extension modules into the main script.
The Include statement can be used in a script to include other scripts or external modules as part of the main
script being executed. Include statements can only be used in Global Scope, that is, outside of any procedure
definitions. If the compiler encounters an include statement inside a procedure, it raises a fatal parse error.
The include statement behaves differently when including another Chilli script or Chilli function modules.

6.1.1 Including Chilli Scripts


Including a script is the same as having the entire contents of that file within the original script.
Syntax:
Include ScriptFile
ScriptFile is any string expression which when evaluated points to a script file.
Comments:
Include statements can be nested, which means that an included file can itself include other files. A file can be
included more than once, but it is only loaded the first time, all subsequent include calls to it are ignored.

Numara Software, Inc. and BMC Software, Inc. Confidential.


50 - BMC FootPrints Asset Core - Chilli Reference

The include statement searches for the supplied script names in the following order in these directories, which
can be relative or absolute:
1 The current working directory.
2 The directory in which the including script is located.
If the included script cannot be found in any of these directories an error occurs.
When the compiler encounters an included file, it reads the second file and parses it. The defined constants,
variables and procedures are added to a global list of variables and procedures. This means that the included file
must not redefine any variables or procedures already defined in the first file. In addition, only one of the two
files can contain a ‘main’ procedure which is called when the execution of the script starts.

6.1.2 Including External Function Modules


The Chilli function modules have been divided into internal and external modules; the internal modules have
been integrated into the Chilli core language and are always available, while the external function modules must
be loaded when needed. To be able to execute functions contained in these external modules they must be loaded
before the script is executed.
Syntax:
Include ExtensionModule
ExtensionModule is the external chilli function module to be included into the main script.
Comments:
By default external Chilli function modules have a .chx file extension although they can also be .dll on
Windows and .so on UNIX/Linux. If you create your own modules and compile them as .dll/.so be aware that
this makes the scripts in which they are included non-portable.
Any .chx module can be included more than once, although it is only loaded up the first time and any
subsequent include calls to it is ignored.
The include statement searches for the supplied module names in the following order in these directories, which
can be relative or absolute:
1 The current working directory.
2 The directory in which the including script is located.
3 The directory which contains the chilli.exe file.
4 The Modules subdirectory which can be found on the same level as the bin directory containing the
chilli.exe file.
5 Any other directories in the ModulePath setting in the Chilli initialization file (for more information see
chapter The Chilli Configuration File on page 65 later on in this section).
If the module is not found in any of the above listed directories, a fatal error occurs and the script is terminated.

6.1.3 Example
You can preload by default a number of common function modules, such as the Archive, Ini File or Time module,
through creating and including a file which defines the modules to be preloaded every time any Chilli script is
called. In this case a preload script might look like the following example:
include "archive.chx"
include "csv.chx"
include "html.chx"
include "time.chx"
include "window.chx"
When this file has been created and either been stored in one of the above mentioned directories, for example,
under C:\Programm Files\BMC Software\Client Management\scripts, or in a special directory, such as
D:\SecretScripts it must be defined in the chilli.ini file under the [ChilliConfig] section.
a The Preload Entry:
[ChilliConfig]
...
Preload = D:\SecretScripts\preload.chl

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 6 - Language Statements - 51

...
For more information about these settings refer to chapter The Chilli Configuration File on page 65 later on in this
section.
Now, all above listed modules is included by default when any script is executed and this initialization file is
used.

6.2 Call
Call the main function in another script.
Syntax
Call ScriptFile
ScriptFile is any string expression which when evaluated points to a script file.
Comments
The Call statement can be used within a procedure to call another script. This is different from an included script
in that the called script must contain a main procedure to be called. An included file can be viewed as a list of
library definitions which can be used by any other script, but the script itself is not runnable. A called script is
always runnable by itself and is used by another script to perform a fixed function. A called script can also use the
same procedure names as the script that is calling it, because the two scripts are executed in separate name spaces
from each other.
When a script is called from another script, the compiler copies the global variables and constants in the calling
script into the name space of the called script. This means that when the called script starts, in addition to all of
its own defined global variables, it also has all of those defined in the script calling it. Any changes made to these
variables are NOT passed back to the calling script.
When the called script reaches the end of its main procedure, or executes the exit statement, the original calling
script is continued at the line after the one with the call statement. If the called script encounters a fatal parse
error, then both scripts are terminated.
Calls can be nested, so that a called script can itself call another script. In this way the global variables and
constants passed to the script from the first script are handed down to the next called script.

6.3 Struct / Endstruct


Define a collection of variables of different types.
Syntax
Struct struct_name
struct_member1
[struct_member2
..... ]
Endstruct
struct_name is the name (= the label) of the structure.
struct_member defines the members of the structure.
Comments
A structure is a collection of one or more variables grouped together under a single name for easy manipulation.
The variables in a structure, unlike those in an array, can be of different types, and each data item has its own
name instead of a subscript value. A structure can contain any of Chilli’s data types, including arrays and other
structures.
A structure can be regarded as a data type same as an integer or a string, however, before its variables can be
declared in a script its type must be defined in a type definition, otherwise a fatal script error occurs.
Structures are defined through the Struct - Endstruct language statement, which must be followed immediately
by the structure name (which follows the same rules as other Chilli variable names). To defined the members of
the structure in Chilli a few rules must be observed:

Numara Software, Inc. and BMC Software, Inc. Confidential.


52 - BMC FootPrints Asset Core - Chilli Reference

• The list of the structure’s members must NOT follow on the same line as the struct keyword.
• Each structure member must be defined on a separate line starting with the data type of the member which is
followed by a space and the variable name of the member:
data_type variable_name
• Generally structure members must each be defined on a separate line starting with the data type which is
followed by a space and the variable name. However, variables of the same type can be listed on the same line
as long as they are separated by commas.
data_type var1, var2, ...
The only legal operations on a structure are copying it or assigning to it as a unit and accessing its members. Copy
and assignment operations include passing arguments to functions and returning values from functions as well.
Structures can not be compared.
If a structure is declared outside of any procedure body, it has Global Scope, meaning that it is usable within any
procedure, including main. If the declaration falls within a procedure definition, the structure has Local Scope,
meaning it is only accessible within the procedure where it is declared. The same structure name can be declared
and used in two different procedures.
If within a procedure, a local structure is defined using the name of a global structure, any references to the
structure in that procedure uses the local copy. The global structure is not used and is in effect masked by the
local structure.

6.4 Proc / Endproc


Define a user-defined procedure.
Syntax
Proc ProcName (Data_Type Parameter [, Data_Type Parameter] )
Procedure Body
Endproc
Comments
The Chilli language is a procedural language meaning that the scripts consist of a number of procedures which
call each other in order to perform a certain task. There must always be a procedure called main which marks the
start of execution. The Proc - Endproc statements are the mechanism through which procedures are defined in
the script. Procedures are like the built-in statements in that they can but do not need to return a value.
The syntax of the Proc statement is very simple. After the Proc keyword itself the name to be given to the
procedure must be supplied. This name can be of any length but must not be a reserved statement or function
name, nor an already declared variable or constant and must consist of alphanumeric characters and underscores.
The name of the procedure is always followed by a list of parameters in parentheses. If the procedure is to take no
parameters, a pair of empty parentheses must be supplied. Within the parentheses, the individual parameters
must be listed along with their types. Each parameter declaration must appear on its own and be separated from
the next by a comma, for example:
Proc TestProc (Int Param1, String Param2, Int Param3)
The declared parameters have local scope within the procedure, meaning that they can only be referenced inside
that procedure. The same parameter name can be used in more than one procedure without any ambiguity. The
parameter name can not be a reserved word or a constant, but it can be the same as a global variable, in which
case it masks the global variable within the procedure. Within the script, user defined procedures are called by
simply using their name as per normal function calls, for example:
TestProc (23, “string1”, 99)
The procedure body can not contain any procedure declarations within it, meaning that local procedures (as in
PASCAL) are not supported. The declaration is terminated by an Endproc statement which, similar to other
statements, must appear on a line by itself.
You will find more detailed information about procedures in chapter Functions and Procedures.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 6 - Language Statements - 53

6.5 Return
Return from a user defined procedure or return a value from a procedure. This statement can have either of the
following syntax.
Syntax
Return
Return expression
Comments
The Return statement provides a mechanism of returning from a user defined procedure before the end of the
procedure has been reached. Normally, all procedures return automatically when the Endproc statement at the
end of the procedure is reached. Using the Return statement, the procedure can be terminated earlier, which
might be necessary in error conditions.
If the Return statement contains an expression, the result of this expression must match the return type which is
declared in the procedure definition.
Example 1:
This example procedure might return from the procedure before the end of the procedure is reached.
Proc TestProc (Int Param1, String Param2, Int Param3)

Int DiskSpace

//Get The amount of free space in MBs


DiskSpace = DiskGetFree (‘C’) / (1024 * 1024)

If (DiskSpace < 100)


Return

EndIf
//Continue normal processing here

EndProc
Example 2
The following example procedure returns an integer value.
int TripleValue (int value)
return 3*value
EndProc

proc main ()
int v
v = 3
print (““+TripleValue(v))
endproc
Printed output:
9

6.6 If / Else / Elif / Endif


Conditional execution constructs.
Syntax 1
If (Condition Expression)
Statement Block
Endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


54 - BMC FootPrints Asset Core - Chilli Reference

Syntax 2
If (Condition Expression)
Statement Block
Else
Statement Block
Endif
Syntax 3
If (Condition Expression)
Statement Block
Elif (Condition Expression)
Statement Block
[Elif (Condition Expression)
Statement Block]
Endif
Syntax 4
If (Condition Expression)
Statement Block
Elif (Condition Expression)
Statement Block
[Elif (Condition Expression)
Statement Block]
Else
Statement Block
Endif
Condition Expression is any expression which returns a boolean value.
Statement Block is a sequence of statements and functions executed according to the value of the Condition
Expression.
Comments
The If and its related conditional statements provide the main mechanism of conditional execution within the
Chilli language. As the most complicated statement set, there are a number of rules which govern their use.
Violation of any of the rules listed below typically results in a fatal error which terminates the script.
• Each statement must appear on a line by itself as shown in the syntax above. The If and Elif statements must
be followed only by an expression enclosed in parenthesis. The Else and Endif statements must appear on a
line by themselves and not be followed by anything.
• The Condition Expression determines the action of the If and Elif statements. If the result of the expression is
true (not equal to 0) then the If and Elif statements executes the block immediately following. Execution
continues until the first Elif, Else or Endif statement at the same nesting level, where the compiler jumps to the
first line after the entire If - Endif construct. If the expression is false (equal to 0), the compiler jumps to the
first Elif, Else or Endif statement and continues execution from there.
• The Elif statement can be used as many times as required to create a selection block where one of a number of
possible blocks can be executed depending on the expression being tested.
• There can be a maximum of one Else statement within the If - Endif construct. If used, the Else part must be
the last block within the construct and is executed if all the other tests (If and Elif statements) are false. The
Else construct must be terminated by an Endif statement which signals the end of the entire construct.
• If - Endif constructs can be nested as deep as required. This means that within any of the Statement Blocks
there can be other If - Endif constructs. The compiler matches the correct parts of a construct.

6.7 While / Endwhile


Conditional looping construct.
Syntax
While (Condition Expression)
Statement Block
Endwhile

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 6 - Language Statements - 55

Condition Expression is any expression which returns a boolean value.


Statement Block is a sequence of statements and functions executed according to the value of the Condition
Expression.
Comments
The While - Endwhile construct is the main looping mechanism in Chilli and is similar in operation to the If -
Endif. The only difference is that unlike the If construct, the Statement Block being controlled by the While
statement is executed repeatedly until the value of the Condition Expression becomes false. That is, while the
expression is true, the Statement Block is executed. The expression is tested on entry to the loop and then once
each time the Statement Block has been executed. If the value is FALSE, the compiler jumps to the first statement
after the Endwhile statement.
The While - Endwhile construct also supports Break and Continue statements which can be used anywhere
within the While - Endwhile pairs:
• Break: The Break statement causes the while loop to be broken and execution to continue at the first line after
the Endwhile statement. The break only exits its While construct. If the while is nested inside another while
loop, the break only exits the nested while loop.
• Continue: The Continue statement causes the While loop to repeat at the While statement. After executing the
line with the Continue statement on it, the compiler moves to the line with the While statement on it and re-
evaluates the condition to see if another loop is to be started.
As with the If - Endif construct, the While and Endwhile statements must appear on a line by themselves. The
same nesting rules also apply in that there can be other While - Endwhile constructs within the Statement Block.

6.8 For / Endfor


Conditional looping construct.
Syntax
For (Initialization Expression; Condition Expression; Increment
Expression)
Statement Block
Endfor
Initialization Expression is usually an assignment statement which is evaluated and returns an integer
value.
Condition Expression is usually a relational expression which is evaluated and returns either TRUE
(nonzero) or FALSE (zero). If the Condition Expression evaluates to FALSE the For statement terminates.
Increment Expression is evaluated and execution returns to the Condition Expression.
Statement Block is a sequence of statements and functions executed if the return value of the Condition
Expression evaluates to TRUE.
Comments
The For - Endfor statement is a construct, which can have an initialization condition, a test condition and an
increment or decrement expression. In the For statement the initialization expression is evaluated once, and thus
specifies the initialization of the loop. It can be of any type. The condition expression must have an arithmetic
type, because it is evaluated before each iteration. If it evaluates to FALSE (0), the For loop is terminated. The
increment expression is evaluated after each iteration and thus specifies re-initialization of the loop. It can be of
any type.
The For - Endfor statement is almost equivalent to the While -Endwhile statement except for the behavior of
Continue. Therefore the statement
for (init, condition, expression)
statement block
endfor
is equivalent to:
init
while (condition)
statement block

Numara Software, Inc. and BMC Software, Inc. Confidential.


56 - BMC FootPrints Asset Core - Chilli Reference

expression
endwhile
Any of the three parts can be omitted. If the initialization expression or the increment expression is omitted, it is
simply dropped from the expansion. If the test condition expression is not present, it is taken as permanently true,
so the statement:
for ()
endfor
is an infinite loop, presumably to be broken by other means such as a Break or Return.
Whether to use While or For is largely a matter of personal preference. The For statement is generally preferable
when there is a simple initialization and increment, because it keeps the loop control statements close together
and visible at the top of the loop.
The For - Endfor construct also supports Break and Continue statements which can be used anywhere within the
For - Endfor pairs:
• Break: The Break statement causes the For loop to be broken and execution to continue at the first line after
the Endfor statement. The break only exits its For construct. If the For is nested inside another For loop, the
break only exits the nested For loop.
• Continue: The Continue statement causes the next iteration of the enclosing For loop to begin, which means
that control passes to the increment step.
• As with the If - Endif and While -Endwhile constructs, the For and Endfor statements must appear on a line by
themselves. The same nesting rules also apply in that there can be other For - Endfor constructs within the
Statement Block.

6.9 Example
The following example illustrates the use of some of the language statements in Chilli.
/*********************************************************************
Type Definitions
*********************************************************************/

Struct Employee
int ID
string Name
float Salary
Endstruct

/*********************************************************************
Main
*********************************************************************/

Proc Main ()

string DateStamp, XMLFile, TmpString


int i, ListLength, ArraySize, ArrayPointer
XMLFileHandle hXMLFile

// Declare a data structure to hold all employee information


// In this case an array of type Employee
// We won't bother to predict any size of this because we'll know
// only at runtime when we start loading data into the array

Employee EmployeeList []

// Make a nicely formatted datestamp for use when printing output

DateStamp = TimeFormat (TimeGetAbsSeconds(), "%Y-%m-%d %H:%M:%S")

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 6 - Language Statements - 57

// Set our current working directory to the same as the ScriptFile


// and assign a good name to our LogFile (the root name of the ScriptFile
// with the suffix exchanged to be ".log"
// Note that both "ScriptFile" and "LogFile" are predefined (or build-in)
// Chilli variables

DirSetCurrent (PathGetDrive(ScriptFile) + ':' + PathGetDir(ScriptFile))


LogFile = PathGetFileRoot(ScriptFile) + '.log'

// Open the xml file and obtain a handle to the (now) open file

XMLFile = "EmpList.xml"
hXMLFile = XMLOpen (XMLFile)

// We'll loop through an XML file and read all the employee information

TmpString = XMLGetValue (hXMLFile, "count (/EMPLIST/EMP)")


ListLength = MakeInt (TmpString)

// Remember the compact For loop statement:


// For (initialization ; Condition to continue with loop ; incrementation ; )

For (i = 1; i <= ListLength; i += 1)

EmployeeList += 1 // This extends the arraysize by one

TmpString = XMLGetValue (hXMLFile, "/EMPLIST/EMP[" + MakeStr(i) + "]/ID")


EmployeeList[i].ID = MakeInt (TmpString)

EmployeeList[i].NAME = XMLGetValue (hXMLFile, "/EMPLIST/EMP[" + MakeStr(i) + "]


/NAME")

TmpString = XMLGetValue (hXMLFile, "/EMPLIST/EMP[" + MakeStr(i) + "]/SALARY")


EmployeeList[i].Salary = StrEvalAsFloat (TmpString)

Endfor

// Next, for illustration purposes we'll use a while loop

ArraySize = ArrayGetSize (EmployeeList) // Initialization


ArrayPointer = 1 // Initialization

While (ArrayPointer <= ArraySize) // Condition to loop

Print ("ID: " + MakeStr(EmployeeList[ArrayPointer].ID) + "\n")


Print (" Name: " + EmployeeList[ArrayPointer].Name + "\n")
Print (" Salary: " + MakeStr(EmployeeList[ArrayPointer].Salary) + "\n")

ArrayPointer = ArrayPointer + 1 // Incrementation

Endwhile

XMLClose (hXMLFile)

Endproc
The xml file to be read has the following contents:
<?xml version="1.0" encoding="ISO-8859-1"?>
<EMPLIST>

Numara Software, Inc. and BMC Software, Inc. Confidential.


58 - BMC FootPrints Asset Core - Chilli Reference

<EMP>
<ID>1000</ID>
<NAME>Peter</NAME>
<SALARY>1111.00</SALARY>
</EMP>
<EMP>
<ID>1001</ID>
<NAME>Laura</NAME>
<SALARY>2222.00</SALARY>
</EMP>
<EMP>
<ID>1003</ID>
<NAME>Paul</NAME>
<SALARY>3333.00</SALARY>
</EMP>
<EMP>
<ID>1004</ID>
<NAME>Rita</NAME>
<SALARY>4444.00</SALARY>
</EMP>
<EMP>
<ID>1005</ID>
<NAME>Albert</NAME>
<SALARY>5555.00</SALARY>
</EMP>
</EMPLIST>
The output file has the following contents.
ID: 1000
Name: Peter
Salary: 1111.000000
ID: 1001
Name: Laura
Salary: 2222.000000
ID: 1003
Name: Paul
Salary: 3333.000000
ID: 1004
Name: Rita
Salary: 4444.000000
ID: 1005
Name: Albert
Salary: 5555.000000

Numara Software, Inc. and BMC Software, Inc. Confidential.


Functions and Procedures

Functions and procedures are the building blocks of Chilli scripts. Apart from the standard Chilli built-in
functions you can create and use your own procedures in Chilli. To easily distinguish between the built-in and
your own, custom made functions we apply the following terminology:
Functions:
Chilli comes with a large number of built-in functions which are organized in topic-specific function modules,
for example, all functions dealing with the manipulation of files are grouped together in the File Function
Module. These functions are predefined in Chilli and can only be applied and executed as explained in the
second part of the manual.
Procedures:
In some situations the predefined functions might not provide you with just the function you need, thus the
Chilli language allows you to create and call your own routines. These are referred to as procedures and need
to be defined according to a certain standard, which is explained under the heading Procedures on page 60
further on in this chapter.

7.1 Functions
A function is a built-in, named, independent section of Chilli code that performs a specific task and optionally
returns a value to the calling program. The Chilli functions are organized in modules through DLLs or Shared
Object Libraries (UNIX), and can be loaded on demand.
You will find a comprehensive guide to all Chilli functions in the next section, which explains each function in
detail.

7.1.1 Function signatures


The function signature is a model for a function that appears later in a program. It provides the compiler with a
description of the function that is defined outside the current script, containing the name of the function, a list of
the variable types of the arguments that must be passed to it and the return type indicating the type of variable
that the function returns, if any. Contrary to other programming language Chilli does not require a line end
character such as a semicolon after a function signature.
Syntax
return_type function_name ([arg_type arg1][, arg_type arg2][, ... ])
If the return type of the function is a structure the syntax of the function signature is slightly changed, because it
must include the name of the returned structure:
Syntax
struct struct_name function_name ([arg_type arg1][, arg_type arg2][, ... ])

7.1.2 Overloaded Functions


Chilli handles functions that have more than one signature. This means that a function can have multiple
signatures. In Chilli this is also known as the principle of overloaded functions.

Numara Software, Inc. and BMC Software, Inc. Confidential.


60 - BMC FootPrints Asset Core - Chilli Reference

Normally a function has a fixed number of specifically defined arguments. Multiple prototypes or signatures
means that, contrary to the before mentioned principle, a function is not limited to one signature. That is, a
function can be defined more than once and the number of its arguments in those definitions as well as their data
type(s) can be different.
Example 1
The print function, for example, has two signatures:
string print (string, string)
string print (string)
When one of these print functions is called Chilli checks the type(s) and number of the arguments and
automatically knows which of the two print functions to use.
Example 2
The file function FileDeleteEntry, which deletes an entry in an INI format file has the following four different
signatures:
FileDeleteEntry (string, string, string)
FileDeleteEntry (string, string, int)
FileDeleteEntry (string, int, string)
FileDeleteEntry (string, int, int)
When one of these file delete functions is called Chilli checks the types of the arguments and automatically
knows which of the four signatures the called function refers to.

7.2 Procedures
A procedure is a piece of Chilli code that is defined once in a program by the user and can be executed many
times by other parts of the program. User procedures in Chilli can be passed parameters that specify the value(s)
that the procedure is to operate upon. Procedures are like functions and thus can but need not return a value.

7.2.1 Procedure Definition


The actual procedure is called a procedure definition and it contains the code that is executed. There are two
different types of syntax for the procedure definition, depending on whether the procedure returns a value or not:
1 Procedure without Return Value
A procedure definition consists of several parts. It begins with the procedure header, which is at the start of a
procedure, that is, the first line in the definition. The header starts with the Proc keyword, contains the
procedure’s name and lists the procedure’s arguments. The body of a procedure follows the header and
contains statements which are executed whenever the procedure is called. The end of the procedure is marked
by the Endproc keyword.
Syntax:
Proc procedure_name ([arg_type ‘arg_1’][, arg_type ‘arg_2’][, ...])
procedure_body
Endproc
Proc is the keyword indicating the beginning of a procedure definition.
procedure_name determines the name of the procedure.
arg_type determines the data type of the variable.
arg_x are the variables passed to the procedure enclosed into parenthesis. If there is more than one
argument they need to be separated by a comma.
procedure_body contains the variable declaration(s) and procedure statement(s).
Endproc is the keyword indicating the end of a procedure definition. It must appear on a line by itself.
2 Procedure with Return Value
Apart from the first element of the procedure’s header, the definition for a procedure which returns a value is
the same as for one which does not. It starts with the type of the returned value (NO Proc keyword), and then
continues with the procedure’s name and describes the procedure’s arguments as usual. The body of a

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 7 - Functions and Procedures - 61

procedure contains statements which are executed whenever the procedure is called. It also marks the end of
the procedure with the Endproc keyword.
Syntax:
return_type procedure_name ([arg_type ‘arg_1’][, arg_type ‘arg_2’][,...])
procedure_body
Endproc
return_type determines the data type of the returned value. This can be any of the data types recognized in
Chilli, such as integer, long or structure.
procedure_name determines the name of the procedure.
arg_type determines the data type of the variable.
arg_x are the variables passed to the procedure enclosed into parenthesis. If there is more than one
argument they need to be separated by a comma.
procedure_body contains the variable declaration(s) and procedure statement(s).
Endproc is the keyword indicating the end of a procedure definition. It must appear on a line by itself.
Examples:
The first example returns an integer value.
int Triplevalue (int value)
return 3*Value
endproc
This example returns a structure.
struct mystruct myproc (myparameters)
mystruct ThisValue
return ThisValue
endproc
Comments:
Contrary to other languages such as BASIC or C, Chilli does not demand a semicolon (;) at the end of each
condition or statement in a procedure declaration nor does it expect one after a procedure signature. If you put a
semicolon the Chilli parser just ignores it or regard it as the beginning of a comment. In addition Chilli does not
allow the procedure body to be enclosed by brackets ({}). Contrary to the semicolon you need to make sure not to
use them because Chilli terminates executing a script if it encounters a brace.
The syntax of the Proc statement is very simple. A procedure name should be given in such a way as to reflect
what the procedure can do. For example the name of the procedure CheckLoginID checks the login authorization.
However, there are certain rules you need to follow on naming procedures:
• The name can be of any length, the number of characters being only limited according to the memory limits of
the supporting hardware platform, that is, 260 characters for Windows and 1024 on UNIX and Linux systems.
• It can be any combination of alphanumeric characters and, that is, letters and digits, and underscores.
• The name can be in lowercase or uppercase or a mixture of both.
• It can start with an underscore (_) or a letter, but not with a digit.
• The name must not contain any spaces.
• The name must NOT be a reserved statement, a function name or an already declared variable or constant.
The name of the procedure is always followed by a list of parameters in parentheses. Very often a procedure needs
to be passed information before execution. Those pieces of information are called arguments. If no arguments
need to be passed to a procedure a pair of empty parentheses must be supplied. The number of arguments to a
procedure is determined by the task of the procedure. If a procedure needs more than one argument, the
individual parameters must be listed along with their types within the parentheses. Each parameter declaration
must appear on its own and be separated from the next by a comma and a space.
Int TestProc (Int Param1, String Param2, Int Param3)
The declared parameters have local scope within the procedure, meaning that they can only be referenced inside
that procedure. The same parameter name can be used in more than one procedure without any ambiguity.
The parameter name:
• can not be a reserved word

Numara Software, Inc. and BMC Software, Inc. Confidential.


62 - BMC FootPrints Asset Core - Chilli Reference

• can not be a constant


• can be the same as a global variable, in which case it masks the global variable within the procedure.
Within the script, user defined procedures are called by simply using their name as per normal function calls.
The body in a procedure contains the variable declaration(s) and the Chilli statement(s). The task of a procedure
is accomplished by executing the statements inside the procedure body one at a time. The procedure body can
also contain function or other procedure calls.
The elements contained in the procedure body are variable declarations, which only have local scope because
they are declared within a procedure or in a language statement which is executed, such as a while, a for or an if-
else construct. Local procedures are not supported in Chilli, therefore the procedure body can not contain any
other procedure declarations.
The declaration is terminated by an Endproc statement which, similar to other language statements in Chilli,
must appear on a line by itself.

7.2.2 Procedure Calls


Contrary to other programming languages such as C, it is not necessary in Chilli to declare procedures called later
on in the script at the beginning of the script in form of procedure signatures, because Chilli does not have
procedure signatures.
However, procedures being called in a script must have been defined before they are called. The definition can
either be in the current script before the procedure call or the procedure definition can be in a called or included
script.
Syntax
procedure_name (procedure_arguments)

7.2.3 Reference Parameters


In Chilli procedures can have their parameters passed to them as references rather than values, so that any
changes to the values in the procedure are reflected to the passed variable outside the procedure. A parameter
passed as a reference is identified by it being preceded by the ampersand sign (&).
Example
....
int x
x=4
proc TripleValue (int &y)
y = y*3
endproc
....
TripleValue (x)
print (x)
....
Printed Output
12
In the second example the procedure definition also has the ampersand sign (&) in front of its only parameter,
namely OutputName, so it can modify it, and return the modified value to the main program. In the course of the
procedure execution, the value of the variable Name is changed from Dog to Cat.
proc GetName (string & OutputName)
OutputName=”Cat”
endproc

proc main ()

string Name
Name=Dog

GetName (Name)
print (Name)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 7 - Functions and Procedures - 63

endproc
Printed Output
Cat

7.2.4 How Procedures Work


Each procedure has a unique name. By calling that name in another part of the program you can execute the
statements contained in the procedure. A Chilli script does not execute the statements in a procedure until the
procedure is called by another part of the script. When a procedure is called, the script can send the procedure
information in the form of one or more arguments. An argument is data needed by the procedure to perform its
task. It can perform its task without interference from or interfering with other parts of the script. A task is a
discrete job that a script must perform as part of its overall operation. When a program calls a procedure, the
statements contained in the procedure body are executed. After the procedure’s statements have finished,
execution passes back to the same location in the program that called the procedure. If demanded these
statements pass information back to the calling program.

7.2.5 Procedure Examples


The following paragraphs shows you some easy examples on how to create procedures. The functions used in
these example procedures are explained in great detail in the following sections.
Example 1
This procedure prints the current date and time into the log file to identify when it was executed.
proc PrintCurrentDate ()

string LogFile

LogFile = “C:\\temp\\logfile.txt”

Print (LogFile, “\r\nScript started on ”)


Print (LogFile, MakeStr (TimeGetYear()) + “/”)
Print (LogFile, MakeStr (TimeGetMonth()) + “/”)
Print (LogFile, MakeStr (TimeGetDay()))

Print (LogFile, “ at “)
Print (LogFile, MakeStr (TimeGetHour()) + “:”)
Print (LogFile, MakeStr (TimeGetMinute()) + “:”)
Print (LogFile, MakeStr (TimeGetSecond()))
Print (LogFile, “\r\n”)

endproc
Example 2
This example procedure extracts files out of an archive.
proc ExtractFiles (string PackageFile, string LogFile)

string path, PackageFile


int handle, limit, count
archivehandle handle
PackageFile = 'C:\package.pkg'

handle = ArchiveOpen (PackageFile)

if (ErrCode != 0)
Print (LogFile, “The archive ” + PackageFile + “ is not valid\r\n”)
exit
endif
limit = ArchiveGetCount (handle)
Print (LogFile, “There are a total of ” + MakeStr (limit-1)

Numara Software, Inc. and BMC Software, Inc. Confidential.


64 - BMC FootPrints Asset Core - Chilli Reference

+ “ files in the archive\r\n”)

count = 1
while (count <= limit)
path = ArchiveGetPath (handle, count)
ArchiveExtract (handle, count, path)
count = count+1
endwhile

ArchiveClose (handle)

endproc

proc main ()
string PackageFile, LogFile
ExtractFiles (PackageFile, LogFile)
endproc
Example 3
The following example procedure returns a value and can be used for instance in expressions.
int TripleValue (int value)
return 3*value
int TripleValue (int value)
return 3*value
EndProc

proc main ()
int v
v = 3
print ("" + TripleValue(v))
endproc
Printed Output
9

Numara Software, Inc. and BMC Software, Inc. Confidential.


Configuration, Error Handling and Debugging

The Error Handling and Debugging in Chilli is done through the special Chilli debug sections defined in the Chilli
configuration file. The default file is called chilli.ini. Due to the use of the command line and the fact that
Chilli supports environment variables it is possible to create and use custom defined configuration files.
The order in which Chilli checks for the configuration file to use is the following:
1 Command line
If the -i option is used on the command line to specify a configuration file the value takes precedence over any
other initialization file definition. This custom defined configuration file can have any name and path with a
.ini extension. For more information about the command line refer to chapter Variables on the Command
Line on page 32 earlier in this section.
2 Environment variable (CHILLI_INI_FILE)
If no configuration file is specified on the command line Chilli checks if the environment variable
CHILLI_INI_FILE is set. This custom defined configuration file can have any name and path with a .ini
extension. For more information about these variables refer to chapter Environment Variables on page 33 earlier
in this section.
3 chilli.ini
If neither the command line nor the environment variable specify a configuration file Chilli uses the default
configuration file which must be called chilli.ini and be located in the same directory as the Chilli
executable file, chilli.exe.
4 If none of the above listed options is set or no initialization file can be found in the specified or default
directory, Chilli operates with default values. You will find a list with the default values at the end of this
chapter under heading Chilli Default Operating values.

8.1 The Chilli Configuration File


The Chilli configuration file, chilli.ini, defines the general behavior of the Chilli environment. It contains
predefined debugging sections and allows the user to define additional user specific debugging configurations.
The chilli.ini file can contain each the following predefined sections and any number of user defined sections
concerning the error handling and debugging of the Chilli language.
• [ChilliConfig] - General Chilli Configuration Settings
• [ChilliDebug] - Chilli Debug Section
• [ChilliParseErrors] - Chilli Parse Errors Section
• [ChilliRunErrors] - Chilli Runtime Errors Section
• [UserDefinedSectionName] - User Defined Error Section

8.1.1 The Chilli General Configuration Settings


The [ChilliConfig] section is used for the general configuration of Chilli and contains the following optional
entries:
[ChilliConfig]
Preload=C:\Programm Files\BMC Software\Client Management\modules\preload.chl
ModulePath=C:\ChilliScripts;D:\SecretScripts;E\SuperSecretScripts

Numara Software, Inc. and BMC Software, Inc. Confidential.


66 - BMC FootPrints Asset Core - Chilli Reference

These entries have the following meaning:


• ModulePath
The optional ModulePath entry can be specified to add to the default list of directories, which are to be
searched for external Chilli function modules. The format of this list is a standard path format with the
directories being separated with a semi-colon (;) or a colon (:). To make the chilli.ini file compatible for
both Windows and UNIX/Linux platforms use the semi-colon (;) separator.
• Preload
The optional Preload entry can be used to name a single file that is executed on startup before running the
main script. Only one single file can be named with an absolute or relative path. If the path is relative, it is
searched for in the following locations in the given order:
1 The current working directory.
2 The directory in which the script is located.
3 The directory which contains the chilli.ini file.
4 The directory which contains the chilli.exe file.
If the file is not found in any of these an initialization error is flagged and the script execution is terminated.
Contrary to ’normal’ scripts which are included into other Chilli scripts, the preloaded script can contain a
main procedure that is called before the execution of the actual script.
The preloaded file can include general external Chilli function modules, check the environment, the operating
system type or the current user, it can execute a generic testing of the environment, the PC, and so on, it can set
up the environment under which all Chilli scripts are to be executed, such as the current working directory,
and so on.
This version of Chilli includes by default a preload.chl file that loads up all Chilli function modules, which
existed up to version 2.5.1 to make all existing scripts backwards compatible. The script default location is
\InstallDirectory\Modules.

8.1.2 Chilli Debug Section


The [ChilliDebug] section is only used internally to control the operation of the compiler at compile and run
time. Any of the values explained in the following paragraphs should only be set at debug time, because enabling
them has a severe impact on the performance of the script at run time.
This section consist of the following entries:
[ChilliDebug]
OutputType=file
OutputName=chilli.cod
CompileOnly=0
DumpStatements=0
ProcedureTrace=0
These entries have the following meaning:
• OutputType
The output type defines of which type the output should be. There are the following four options:
§ none
There is no debugger output regardless of the other settings.
§ stdout
The debugging output is sent to the standard output.
§ file
The debugger output is written to a file whose name is to be specified through the entry OutputName
which follows.
§ var
The debugger output is written to a file whose name is to be specified through a variable which is defined
in the entry OutputName which follows.
• OutputName
Depending on the value specified under the preceding entry there are the following three options for this
parameter:

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 8 - Configuration, Error Handling and Debugging - 67

§ none
If none or stdout are specified for the output type parameter this is not used.
§ file name and path
If the OutputType is file this entry defines the name and path of the output file.
§ variable name
If the OutputType is var this entry defines the name of the variable which in turn defines the name and
path of the output file.
• CompileOnly
If set to an integer value other than 0, this switches the compile only operation on. If set the compiler does not
execute anything, just compile and update the cache if needed. The default value is 0, which means compile
and execute.
• DumpStatements
If DumpStatements is set to any integer value other than 0, the compiler dumps the output of a procedure
compilation into a location (stdout/file) dictated by the OutputType and OutputName entries of the
[ChilliDebug] section settings. The default value is 0.
• ProcedureTrace
If set to a value other than 0, this enables a procedure trace which prints a trace of the procedures executed
and the number of statements executed in each one. The trace is indented appropriately to show nested
procedure calls. The default value is 0. The dump also shows cumulative times per procedure.

8.1.3 Chilli Parse Errors Section


The [ChilliParseErrors] section controls the user defined output in case of a parse error of a chilli script
when executed. It is used to control if the files compile correctly. For a detailed explanation of all entries refer to
heading User Defined Debug Section.

8.1.4 Chilli Runtime Errors Section


The [ChilliRunErrors]section controls the user defined output in case of a runtime error of a chilli script when
executed. This section controls if Chilli executes correctly. For a detailed explanation of all entries refer to
heading User Defined Debug Section.

8.1.5 User Defined Debug Section


In addition to these predefined default sections you can add personalized debug sections
[UserDefinedSectionName].
The entries of Chilli Parse Errors and Chilli Runtime Errors as well as the user defined sections are the
same and have the following entries and meaning:
[ChilliParseErrors] / [ChilliRunErrors] / [{UserDefinedSectionName}]
OutputPrefix=****************************
OutputSuffix=****************************
OutputType=stdout
OutputName=
DumpSource=
DumpLocals=*
DumpGlobals=*
DumpConstants=*
DumpTypes=*
DumpFunctions=*
DumpProcedures=*
These entries have the following meaning:
• OutputPrefix
This line appears at the beginning of an output to mark the beginning. Including a specific marker and HTML
tags at the beginning of a debug dump makes the dump more easily recognizable within an HTML file.
• OutputSuffix
This line appears at the end of an output to mark the end. Including a specific marker and HTML tags at the
end of a debug dump makes the dump more easily recognizable within an HTML file.

Numara Software, Inc. and BMC Software, Inc. Confidential.


68 - BMC FootPrints Asset Core - Chilli Reference

• OutputType
The output type defines of which type the output should be. There are the following four options:
§ none
There is no output.
§ stdout
The output is sent to the standard output.
§ file
The output is written to a file whose name is to be specified through the entry OutputName which follows.
§ var
The output is written to a file whose name is to be specified through a variable which is defined in the
entry OutputName which follows.
• OutputName
Depending on the value specified under the preceding parameter there are the following three options for this
parameter:
§ none
If none or stdout are specified under the preceding entry this entry is not used.
§ file name and path
If the OutputType is file this entry needs to define the name and path of the output file.
§ variable name
If the OutputType is var this entry defines the name of the variable which in turn defines the name and
path of the output file.
• DumpSource
This entry defines the number of lines around the line containing the error which are to be printed in the
output.
Example: if the number of lines is 5, the output shows the two lines before the error, the line containing the
error and the two lines immediately following the line with the error. The line containing the error is marked
with ‘>>>’ at the beginning of the line.
• DumpLocals
This entry defines the local variables which are to be included in the debug output. In the case of the local
variables these are restricted to those used by the procedure which caused the error. There are the following
three possibilities:
§ none
No local variables is included into the output.
§ name name name ....
The local variables whose names were specified separated by a space, a comma (,), a semi-colon (;) or a
colon (:), is included into the debug output. If you select this option the output file contains an extra line
informing you that the number of local variables was limited by the .ini file settings.
§ asterix (*)
All local variables is included into the output.
• DumpGlobals
This entry defines the global variables which are to be included in the debug output. There are the following
three possibilities:
§ none
No global variables is included into the output.
§ name name name ....
The global variables whose names were specified separated by a space, a comma (,), a semi-colon (;) or a
colon (:), is included into the debug output. If you select this option the output file contains an extra line
informing you that the number of global variables was limited by the .ini file settings.
§ asterix (*)
All global variables is included into the output.
• DumpConstants
This entry define the constants which are to be included in the debug output. In the case of the local variables

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 8 - Configuration, Error Handling and Debugging - 69

these are restricted to those used by the procedure which caused the error. There are the following three
possibilities:
§ none
No constants is included into the output.
§ name name name ....
The constants whose names were specified separated by a space, a comma (,), a semi-colon (;) or a colon (:),
is included into the debug output. If you select this option the output file contains an extra line informing
you that the number of constants was limited by the .ini file settings.
§ asterix (*)
All constants is included into the output.
• DumpTypes
This entry defines the data types, predefined and user specified, to be included in the debug output. The data
types shown are the simple data types, such as integers and strings, but also the user defined arrays and
structures. There are the following three possibilities:
§ none
No data types is included into the output.
§ name name name ....
The data types whose names were specified separated by a space, a comma (,), a semi-colon (;) or a colon (:),
is included into the debug output. If you select this option the output file contains an extra line informing
you that the number of data types was limited by the .ini file settings.
§ asterix (*)
All data types is included into the output.
• DumpFunctions
This entry defines the functions in Chilli to be included in the debug output. There are the following three
possibilities:
§ none
No functions is included into the output.
§ name name name ....
The functions whose names were specified separated by a space, a comma (,), a semi-colon (;) or a colon (:),
is included into the output. If you select this option the output file contains an extra line informing you that
the number of functions was limited by the .ini file settings.
§ asterix (*)
All functions is included into the output.
• DumpProcedures
This entry defines the procedures in Chilli to be included in the debug output. There are the following three
possibilities:
§ none
No procedures is included into the output.
§ name name name ....
The procedures whose names were specified separated by a space, a comma (,), a semi-colon (;) or a colon
(:), is included into the output. If you select this option the output file contains an extra line informing you
that the number of procedures was limited by the .ini file settings.
§ asterix (*)
All procedures is included into the output.

8.2 Debugging
Chilli offers a function called DebugDump. This function can be included in any Chilli script at any point in the
script. The function needs to be declared in the following way:
Syntax
DebugDump (SectionName)

Numara Software, Inc. and BMC Software, Inc. Confidential.


70 - BMC FootPrints Asset Core - Chilli Reference

SectionName is the name of the section in the ini file which defines how the debugging output is to be
executed.
The Chilli debugging system offers you two choices:
• You can either set up your own debug section in the chilli.ini file, defining which way you want the debug
output to be. If the DebugDump function is called with a section name other than ChilliDebug, Chilli searches
the chilli.ini file for a section with the name of the string parameter. The debugging is then executed
exactly as defined in this section.
• Or you can use one of the predefined sections in the chilli.ini file for your debug output. In this case you
need to specify either ChilliRunErrors or ChilliParseErrors as your section name. If no section of this
name is found, the Chilli Debugger takes the values to be empty and therefore does not generate any output.
Example 1
This example displays an error message for a parameter type mismatch occurred in a Chilli script printed on
stdout in an html page:
****************************
Fatal parse or run time error ERR_EXPRPARMMATCH in file /usr/local/WebConsole_v2_test/Files/
Panels/SpectrumCompactAlarm/SpectrumCompactAlarm.html, line 26 Parameter type mismatch
Script source dump:
SpecAlarmList AlarmRegister[]
SpecAttrValue AttrValue
string szTmp
SpecAttrValueList RespAttrList
>>>GetURLVariableInt ("_plattype", "PlatType", 0, szPlatType)
GetURLVariableInt ("_platport", "PlatPort", 0, PlatPort)
GetURLVariableString ("_platip", "PlatIP", "", szPlatIp)
****************************
This error message prints 7 lines around the error and does not include any variables, constants, data types,
functions or procedures.
Example 2
This example displays an error message for an unrecognized statement or variable name error occurred in a Chilli
script printed on stdout in an html page:
****************************
Fatal parse or run time error ERR_BADSTATEMENT in file /usr/local/WebConsole_v2_raphael/
Files/Panels/AttributeBrowser/attributebrowser.html, line 122 HTMLTable: Unrecognized
statement or variable name
Script source dump:
endif
endfor
print("</TABLE>")
>>>HTMLTable modelTypeTable
HTMLTableColumn modelTypeTableColumn[2]
modelTypeTableColumn[1].Name = "Type"
modelTypeTableColumn[2].Name = "Handle"
****************************
This error message prints 7 lines around the error and does not include any variables, constants, data types,
functions or procedures.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 8 - Configuration, Error Handling and Debugging - 71

Numara Software, Inc. and BMC Software, Inc. Confidential.


Section II

Chilli Function Reference


The second part of the book is a complete reference to all internal function modules of the
Chilli language. The Chilli functions are grouped into modules which are each explained in a
separate chapter. Every function is detailed with its syntax and all possible prototypes, its
return type and any special characteristics. Most of the function descriptions also contain an
example showing typical uses of the function. You will find it helpful to study these examples
carefully. The functions groups also explain all module specific data types in the respective
chapters.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Archive Functions

The Archive functions add the necessary Chilli script functions to allow the scripts to manipulate file archives.
All functions of this module are included in the archive.chx file for Windows or archive.so file for UNIX and
Linux.

9.1 Introduction
Archives provide a storage medium for files, into which they can be added in compressed form.
The archives created by Chilli are compatible with those created by the BCM Deployment Manager. Their formats
(.pkg/.cst) are proprietary and not compatible with the TAR or ZIP formats. The archive stores each of the files
as a compressed image, together with information about the file, such as its original path, size and modification
date.
The Chilli archive functions allow you to create archives, to extract information from existing archives and to
manipulate any type of archive, which has been created by the BCM Deployment Manager.
However, the Chilli archive functions also deal and manipulate Winzip (.zip) archives.

9.2 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli Archive function group has Predefined Handle Data Types.

9.2.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


ArchiveHandle Object type: reference to the handle of an archive

ArchiveHandle
The ArchiveHandle data type is a reference to the handle of an archive.
The function ArchiveOpen returns a value of this object type that all other functions expect as their first
argument. Any open archive and thus the value of this object type should always be closed by the
ArchiveClose function.

9.3 Functions
Following you find the list of all functions of the Archive function module:

Numara Software, Inc. and BMC Software, Inc. Confidential.


76 - BMC FootPrints Asset Core - Chilli Reference

Function OS Description
ArchiveAdd Add a file to an archive

ArchiveClose Close an already opened archive

ArchiveDelete Delete an entry in an archive

ArchiveExtract Extract a file from an archive

ArchiveFindName Find a file with a matching name in an archive

ArchiveFindPath Find a file with a matching name and path in an archive

ArchiveGetCount Get the number of files in an archive

ArchiveGetPath Get the path of a file in an archive

ArchiveGetSize Get the size of a file in an archive

ArchiveGetStoredSize Return the stored size of an entry identified by its index in the archive

ArchiveGetWriteTime Return the write date and time of the file as stored in the archive

ArchiveOpen Open an archive

ArchiveSetPath Set the full path of an entry identified by its index in the archive

ArchiveAdd
Add a file to an archive which has already been opened by ArchiveOpen.
Syntax:
Int ArchiveAdd (ArchiveHandle Handle, String FileName)
Handle is a handle to a file archive returned by ArchiveOpen.
FileName is the relative or absolute path of the file to add to the archive.
Returns:
If the file is added successfully, the function returns the index of the new entry in the archive. If the function fails,
0 is returned.
Comments:
If the handle is not valid, the function validates the handle value passed to it and sets ErrCode to
ERR_BADHANDLE. To add files to an archive, you must first obtain a valid handle by using ArchiveOpen. All
files added to the archive are automatically compressed and stored with their full path as supplied in the
FileName parameter. The archive only stores unique paths, therefore if an entry with a matching path is found, it
is replaced by the supplied file. In all cases, the original copy of the file being added is left unaltered.
Example:
The following example checks if a file exists and if yes, adds it to the archive.
proc main ()

ArchiveHandle handle;
string szFile;

szFile = "./archive.zip"
handle = ArchiveOpen (szFile);

szFile = "../../spectrum/tests/spectrum.xml"
if (FileFind (szFile))
ArchiveAdd (handle, szFile);
else
print (szFile + " not found\r\n")
endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 9 - Archive Functions - 77

ArchiveClose (handle);

endproc

ArchiveClose
Close an archive file opened by ArchiveOpen.
Syntax:
Bool ArchiveClose (ArchiveHandle Handle)
Handle is a handle to a file archive returned by ArchiveOpen.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
If the handle is not valid, the function validates the handle value passed to it and sets ErrCode to
ERR_BADHANDLE. Closing the archive frees up the resources associated with the handle and invalidates the
handle. After closing the archive the handle value can no longer be used.
Example:
The following example checks if an archive is valid and counts the lines it contains before closing it.
proc main ()

string path, file


int limit, count
archivehandle handle

file = 'install.chl'
handle = ArchiveOpen ('C:\package.pkg')

if (ErrCode != 0)
Print (LogFile, 'The archive ' + file + ' is not valid.\r\n')
exit
endif

limit = ArchiveGetCount (handle)


Print (LogFile, 'There are a total of ' + MakeStr (limit-1) + ' files in
the archive.\r\n')
ArchiveClose (handle)

endproc

ArchiveDelete
Delete a file from an archive which has already been opened by ArchiveOpen.
Syntax:
Bool ArchiveDelete (ArchiveHandle Handle, Int FileIndex)
Handle is a handle to a file archive returned by ArchiveOpen.
FileIndex is the index (starting from 1) of the entry to delete.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


78 - BMC FootPrints Asset Core - Chilli Reference

Comments:
If the handle is not valid, the function validates the handle value passed to it and sets ErrCode to
ERR_BADHANDLE. If the supplied index is 0 or larger than the number of files in the archive, it also fails.
Example:
The following example checks if a file exists by looking for the name then deletes it.
proc main ()

string filename
int fileindex
archivehandle handle

filename = ’install.chl’
handle = ArchiveOpen (’C:\package.pkg’)

fileindex = ArchiveFindName (handle, filename)

if (ErrCode != 0)
Print (Logfile, ’ The file ’ + filename + ’ has not been found.\r\n’)
endif

ArchiveDelete (handle, fileindex)


ArchiveClose (handle)

endproc

ArchiveExtract
Extract a file from an archive which has already been opened by ArchiveOpen.
Syntax:
Bool ArchiveExtract (ArchiveHandle Handle, Int FileIndex, String FileName)
Handle is a handle to a file archive returned by ArchiveOpen.
FileIndex is the index (starting from 1) of the entry to extract.
FileName is the relative or absolute path of the file to extract the entry into. This name does not have to
match that of the file in the archive.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
If the handle is not valid, the function validates the handle value passed to it and sets ErrCode to
ERR_BADHANDLE. The function also fails if the supplied index is 0 or larger than the number of files in the
archive. If the indexed file is compressed, it is automatically decompressed before being extracted. The FileName
parameter can be used to extract the file to any location and does not have to match the path stored with the entry.
The extracted entry is left in the archive.
Example:
The following example extracts all files from the archive.
proc main ()

string path
int limit, count
archivehandle handle

handle = ArchiveOpen (“C:\\package.pkg”)


limit = ArchiveGetCount (handle)
Print (LogFile, ’There are a total of ’ + MakeStr (limit-1) + ’ files in
the archive\r\n’)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 9 - Archive Functions - 79

count = 1
while (count <= limit)
path = ArchiveGetPath (handle, count)
ArchiveExtract (handle, count, path)
count = count+1
wend

endproc

ArchiveFindName
Search for a file by name in an archive which has already been opened by ArchiveOpen.
Syntax:
Int ArchiveFindName (ArchiveHandle Handle, String FileName)
Handle is a handle to a file archive returned by ArchiveOpen.
FileName is the name plus extension to search for. It should not contain any directory or drive
specifications.
Returns:
If the file is found, the function returns the index of the matching entry in the archive. If the file cannot be found
or the function fails, 0 is returned.
Comments:
If the handle is not valid, the function validates the handle value passed to it and sets ErrCode to
ERR_BADHANDLE. The search is done by name only, therefore, if the archive contains files with matching names
but different paths, this function returns the first one file matching the name.
Example:
The following example checks if a file exists by looking for the name then deletes it.
proc main ()

string filename
int fileindex
archivehandle handle

filename = 'test.txt'
handle = ArchiveOpen ('C:\package.pkg')
fileindex = ArchiveFindName (handle, filename)

if (ErrCode != 0)
Print (Logfile, ' The file ' + filename + ' has not been found.\r\n')
endif

ArchiveDelete (handle, fileindex)


ArchiveClose (handle)

endproc

ArchiveFindPath
Search for a file by its path in an archive which has already been opened by ArchiveOpen.
Syntax:
Int ArchiveFindPath (ArchiveHandle Handle, String FilePath)
Handle is a handle to a file archive returned by ArchiveOpen.
FilePath is the path to search for and has to match an entry exactly, but is not case sensitive.
Returns:
If the file is found, the function returns the index of the matching entry in the archive. If the file cannot be found
or the function fails, 0 is returned.

Numara Software, Inc. and BMC Software, Inc. Confidential.


80 - BMC FootPrints Asset Core - Chilli Reference

Comments:
If the handle is not valid, the function validates the handle value passed to it and sets ErrCode to
ERR_BADHANDLE. The search is done by path, therefore an entry must match the supplied path exactly. Because
the ArchiveAdd only adds unique paths to the archive, at most one single match can be found.
Example:
The following example extracts a file after having searched for it by its path.
proc main ()

int limit, avoid


string file
archivehandle handle

limit = 0
file = 'C:\package.pkg'
handle = ArchiveOpen (file)

if (ErrCode != 0)
Print (LogFile, "The archive " + file + " is not valid.\r\n")
Exit (ERR_ARCHIVE)
endif

limit = ArchiveGetCount (handle)


avoid = ArchiveFindPath (handle, "ro_wwnt.chl")
Print (LogFile, "\r\nExtracting files from the archive\r\n")
Print (LogFile, "There are a total of " + MakeStr (limit-1) + " files in
the archive.\r\n")
ArchiveClose (handle)

endproc

ArchiveGetCount
Get the number of files in an archive which has already been opened by ArchiveOpen.
Syntax:
Int ArchiveGetCount (ArchiveHandle Handle)
Handle is a handle to a file archive returned by ArchiveOpen.
Returns:
If the function is successful, the return value is the number of files in the archive. 0 is returned if there are no files
in the archive or if the function fails. If the function fails ErrCode is set to ERR_BADHANDLE.
Comments:
If the handle is not valid, the function validates the handle value passed to it and sets ErrCode to
ERR_BADHANDLE.
Example:
The following example extracts all files from the archive.
proc main ()

string path
int limit, count
archivehandle handle

handle = ArchiveOpen (’C:\package.pkg’)


limit = ArchiveGetCount (handle)
Print (LogFile, ’There are a total of ’ + MakeStr (limit-1) + ’ files in
the archive.\r\n’)

count = 1
while (count <= limit)
path = ArchiveGetPath (handle, count)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 9 - Archive Functions - 81

ArchiveExtract (handle, count, path)


count = count+1
wend

endproc

ArchiveGetPath
Get the stored path of a file in an archive which has already been opened by ArchiveOpen.
Syntax:
String ArchiveGetPath (ArchiveHandle Handle, Int FileIndex)
Handle is a handle to a file archive returned by ArchiveOpen.
FileIndex is the index (starting from 1) of the entry to examine.
Returns:
If the function is successful, it returns the path of the indexed entry. If the function fails, an empty string is
returned.
Comments:
If the handle is not valid, the function validates the handle value passed to it and sets ErrCode to
ERR_BADHANDLE.
Example:
The following example extracts all files from the archive.
proc main ()

string path
int limit, count
archivehandle handle

handle = ArchiveOpen (’C:\package.pkg’)


limit = ArchiveGetCount (handle)
Print (LogFile, ’There are a total of ’ + MakeStr (limit-1) + ’ files in
the archive.\r\n’)

count = 1
while (count <= limit)
path = ArchiveGetPath (handle, count)
ArchiveExtract (handle, count, path)
count = count+1
wend

endproc

ArchiveGetSize
Get the size of a file in an archive which has already been opened by ArchiveOpen.
Syntax:
Int ArchiveGetSize (ArchiveHandle Handle, Int FileIndex)
Handle is a handle to a file archive returned by ArchiveOpen.
FileIndex is the index (starting from 1) of the entry to examine.
Returns:
If the function is successful, it returns the actual size (before compression) of the indexed file. If the function fails,
0 is returned.
Comments:
If the handle is not valid, the function validates the handle value passed to it and sets ErrCode to
ERR_BADHANDLE.

Numara Software, Inc. and BMC Software, Inc. Confidential.


82 - BMC FootPrints Asset Core - Chilli Reference

Example:
The following example gets the size of the first file contained in the archive.
proc main ()

archivehandle handle
int size

handle = ArchiveOpen ('C:\package.pkg')


Size = ArchiveGetSize (handle, 1)

ArchiveClose (handle)

endproc

ArchiveGetStoredSize
Return the stored size of an entry identified by its index in the archive.
Syntax:
Int ArchiveGetStoredSize (ArchiveHandle Handle, Int Index)
Handle is a handle to a file archive returned by ArchiveOpen.
Index is the identifier to the entry in the archive.
Returns:
The stored size of an entry identified or 0 if the archive or index is not valid or the operation failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
Archive member numbers start at 1 for the first one. The stored size does not include any header overhead.
Example:
The following example gets the stored size of the first file contained in the archive.
proc main ()

archivehandle handle
int size

handle = ArchiveOpen ('C:\package.pkg')


Size = ArchiveGetStoredSize (handle, 1)

ArchiveClose (handle)

endproc

ArchiveGetWriteTime
Return the write date and time of the file as stored in the archive.
Syntax:
Int ArchiveGetWriteTime (ArchiveHandle Handle, Int Index)
Handle is a handle to a file archive returned by ArchiveOpen.
Index is the identifier to the entry in the archive.
Returns:
The write time as the number of seconds since 00:00:00 UTC, January 1, 1970 or 0 if the archive or index is not
valid or the operation failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
Archive member numbers start at 1 for the first one.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 9 - Archive Functions - 83

ArchiveOpen
Open or create an archive for manipulation by the Archive functions.
Syntax:
ArchiveHandle ArchiveOpen (String FileName)
FileName is the relative or absolute path of the archive file to be opened or created.
Returns:
If the archive file is opened or created successfully, the function returns a handle to the archive for use with other
Archive functions. If the function fails, 0 is returned.
Comments:
If the supplied FileName exists and is a valid archive file, it is opened. If the file does not exist, a new file is
created and initialized as an empty archive. Changing the value invalidates the ArchiveHandle and it is rejected
by other Archive functions.
The archives created by Chilli are compatible with those created by the BCM Deployment Manager. The archive
stores each of the files as a compressed image, together with information about the file, such as its original path,
size and modification date. The archive format is proprietary and not compatible with the TAR or ZIP formats.
Example:
The following example checks if an archive is valid.
proc main ()

archivehandle handle
string PackageFile

PackageFile = 'C:\package.pkg'
handle = ArchiveOpen (PackageFile)

if (ErrCode != 0)
Print (LogFile, 'The archive ' + PackageFile + ' is not valid.\r\n')
exit
endif

endproc

ArchiveSetPath
Set the full path of an entry identified by its index in the archive.
Syntax:
Bool ArchiveSetPath (ArchiveHandle Handle, Int Index, String NewPath)
Handle is a handle to a file archive returned by ArchiveOpen.
Index is the identifier to the entry in the archive.
NewPath is the full path the entry in the archive is to be set to.
Returns:
TRUE if the entry is correctly set or FALSE if the archive or index is not valid or the operation failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
Archive member numbers start at 1 for the first one.

9.4 Example
This example counts the number of files in the archive and extracts all files from the archive.
proc ExtractFiles (string PackageFile, string LogFile)

Numara Software, Inc. and BMC Software, Inc. Confidential.


84 - BMC FootPrints Asset Core - Chilli Reference

string path, PackageFile


int limit, count
archivehandle handle

PackageFile = 'C:\package.pkg'
handle = ArchiveOpen (PackageFile)
if (ErrCode != 0)
Print (LogFile, 'The archive ' + PackageFile + ' is not valid.\r\n')
exit
endif

limit = ArchiveGetCount (handle)


Print (LogFile, 'There are a total of ' + MakeStr (limit-1) + ' files in the
archive.\r\n')

count = 1
while (count <= limit)
path = ArchiveGetPath (handle, count)
ArchiveExtract (handle, count, path)
count = count+1
wend

ArchiveClose (handle)

endproc

proc main ()

string PackageFile, LogFile


ExtractFiles (PackageFile, LogFile)

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


BMC Client Management Agent Functions

This chapter explains all functions concerning the BCM agent. These functions are only applicable if the BCM
agent is installed. All functions of this module are included in the mtxagent.chx file for Windows or
mtxagent.so file for UNIX and Linux.

10.1 Introduction
A container is an object whose main purpose is to hold other objects. Container objects simplify information tree
structures and avoid name collisions by grouping various objects under different containers. The objects or
components in a container are tracked in a first-in-first-out list, which also defines the order of the components
within the container.

10.2 Predefined Constants


Following you find the complete list of all predefined constants of the BCM agent functions group of the Chilli
language:

Name Type Description


CONTAINER_ENTRY_NONE Integer The entry type of the container can not be defined
CONTAINER_ENTRY_BOOLEAN Integer The entry type of the container is boolean
CONTAINER_ENTRY_DOUBLE Integer The entry type of the container is double
CONTAINER_ENTRY_INTEGER Integer The entry type of the container is integer
CONTAINER_ENTRY_STRING Integer The entry type of the container is string
CONTAINER_ENTRY_CONTAINER Integer The entry type of the container is container

10.3 Error Codes


Following you find a list of all error codes of the functions contained in the BCM agent function group. These
errors are run-time errors that causes the handler specified in ErrorHandler to be invoked:

Name Description
ERR_ACTINPARAM Unable to resolve action input parameters
ERR_ACTOUTPARAM Unable to set action output parameters
ERR_ACTFAILED Failed to execute agent action

Numara Software, Inc. and BMC Software, Inc. Confidential.


86 - BMC FootPrints Asset Core - Chilli Reference

10.4 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli BCM agent function group has predefined data types of type
handle and structure.

10.4.1 Predefined Handle Data Types


Predefined data types of type handle are opaque handles which contain the necessary information for accessing
various data. They have a name and are returned by functions andpassed on to other functions or procedures
without changes.
Following you find a list of all predefined data types of type handle:

Data Type Description


ContainerHandle Object type: reference to the container handle.

ContainerHandle
The ContainerHandle data type is a reference to the handle of container.
The function ContainerCreate returns a value of this object type and most of the other functions expect it as
their first argument. Any open container and thus the value of this object type should be destroyed by the
ContainerDestroy function.

10.4.2 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated.
Following you find a list of all predefined data types of type structure:

Data Type Description


InvObjInstAttr This structure provides information about the inventory object.
InvObjInst This structure provides information about the inventory object instance.
InvObjTypeAttr This structure provides information about the inventory object type attributes.
InvObjType This structure contains the information about the inventory object type and is required by the
InventoryAddObjType function.

InvObjInstAttr
The InvObjInstAttr structure provides information about the inventory object.
Elements:

Elements Element Type Description


Name String The name of the inventory object.
Value String The value of the inventory object.

InvObjInst
The InvObjInst structure contains information about the inventory object instance.
Elements:

Elements Element Type Description


Name String The name of the object type instance.
Attrs[] InvObjInstAttr The structure containing the inventory object information.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 10 - BMC Client Management Agent Functions - 87

InvObjTypeAttr
The InvObjTypeAttr structure contains the information about the inventory object type attributes.
Elements:

Elements Element Type Description


Name String The name of the attribute.
Desc String A description of the attribute.
Type String The type of the attribute.
Unit String The unit of the attribute.
NeedTranslation String Specifies if a translation exists for this attribute and is required for
displaying on the console.

InvObjType
The InvObjType structure contains the information about the inventory object type and is required by the
InventoryAddObjType function.

Elements:

Elements Element Type Description


Name String The name of the object type.
Attrs[] InvObjTypeAttr The structure containing the inventory object information.
Insts[] InvObjInst The structure contains the information about the inventory object
instances.

10.5 Functions
Following you find the list of all functions of the BCM agent function module:

Function OS Description
ContainerCountNames Return the number of entries in the container

ContainerCountValues Return the number of values for the named entry in the container

ContainerCreate Create a new empty container

ContainerDestroy Destroy a container identified by the supplied handle

ContainerGetBoolean Return the boolean value of the entry

ContainerGetContainer Return the container value of the entry

ContainerGetDividedInt64 Convert a divided 64 bit integer into an integer

ContainerGetDouble Return the double value of the entry

ContainerGetInteger Return the integer value of the entry

ContainerGetNextName Return the next name in the container

ContainerGetString Return the string value of the entry

ContainerGetType Return the type of the named entry in the container

ContainerLoadPList Load the supplied container from an XML formatted string value

ContainerLoadXml Load the supplied container from an XML formatted string value

ContainerLoadXmlFile Load the supplied container from an XML formatted file given its path

Numara Software, Inc. and BMC Software, Inc. Confidential.


88 - BMC FootPrints Asset Core - Chilli Reference

Function OS Description
ContainerLoadXmlFileAtSe Load the supplied container from an XML formatted file given its path
ek
ContainerSaveXml Create the string XML string equivalent of the supplied container

ContainerSaveXmlFile Save the supplied container to an XML formatted file given its path

ContainerSaveXmlFileApp Save the supplied container to an XML formatted file given its path
end
ContainerSetBoolean Set the indexed boolean value of a named entry in the container

ContainerSetContainer Set the indexed container value of a named entry in the container

ContainerSetDouble Set the indexed double value of a named entry in the container

ContainerSetInteger Set the indexed integer value of a named entry in the container

ContainerSetString Set the indexed string value of a named entry in the container

InventoryAddObjType Add an object type to an existing inventory

InventoryCreate Create a new empty inventory and return its handle

InventoryDestroy Destroy an existing inventory

InventorySave Save the inventory to a specific location

MtxAgentInvokeAction Invoke an action on a BCM agent

ContainerCountNames
Return the number of entries in the container.
Syntax:
Int ContainerCountNames (ContainerHandle Handle)
Handle is the handle to the container to be counted.
Returns:
The number of named entries in the container if the operation was successful or 0 if the container is empty, the
supplied handle is not valid or the operation failed.
Comments:
If one of the entries is itself a container, it counts as 1, that is, the count is not recursive.
Example:
proc main ()

int i, iCount
ContainerHandle contParams
contParams = ContainerCreate ()

// Load up a container from the parameter string

ContainerLoadXml (contParams, PerfEntry.szParameters)

iCount = ContainerCountNames (contParams)

string szName
for (i=1; i<=iCount; i+=1)
szName = ContainerGetNextName (contParams, szName)
print (szName + ":\n")

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 10 - BMC Client Management Agent Functions - 89

int iType;
iType = ContainerGetType (contParams, szName)
endfor

ContainerDestroy (contParams)

endproc

ContainerCountValues
Return the number of values for the named entry in the container.
Syntax:
Int ContainerCountValues (ContainerHandle Handle, String Name)
Handle is the handle to the container.
Name is the name of the entry to be counted.
Returns:
The number of values for the named entry in the container if the operation was successful or 0 if the entry is not
found, the handle was not valid or the operation failed.
Comments:
A container can not have any 0-value entries in it.
If the named entry is itself a container, the count is the number of instances of that container and not the count of
values in it.
Example:
The following example is taken from the hardware inventory and returns the list of hardware inventory objects
from the agent.
proc main ()

string[] GetHwObjectInstances (string szObjName)

// Create a container for the direct request

ContainerHandle contRequest, contResult


contRequest = ContainerCreate ()

ContainerSetString (contRequest, "ObjectName", 1, szObjName)


contResult = MtxAgentInvokeAction ("", "HardwareGetInstances", contRequest)
ContainerDestroy (contRequest)

int i, iCount
iCount = ContainerCountValues (contResult, "InstanceName")

string szInstances[]

for (i=1; i<=iCount; i+=1)


string szName
szName = ContainerGetString (contResult, "InstanceName", i)
szInstances <<= szName
endfor

ContainerDestroy (contResult)
return szInstances

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


90 - BMC FootPrints Asset Core - Chilli Reference

ContainerCreate
Create a new empty container.
Syntax:
ContainerHandle ContainerCreate ()
Returns:
A handle of type ContainerHandle referencing the newly created container if the function was successful, 0 if
the operation failed.
Example:
The following example returns the list of queued objects from the agent.
proc main ()

OpRuleEntry[] GetOpRuleList ()

// Create a container for the direct request

ContainerHandle contRequest, contResult


contRequest = ContainerCreate ()

contResult = MtxAgentInvokeAction ("", "OpRuleList", contRequest)


ContainerDestroy (contRequest)

int i, iCount
iCount = ContainerCountValues (contResult, "Values")

OpRuleEntry ruleList[]

for (i=1; i<=iCount; i+=1)


OpRuleEntry ruleEntry
ruleEntry.szID = ContainerGetString (contResult, "Values", i)
GetOpRuleInfo (ruleEntry)
ruleList <<= ruleEntry
endfor

ContainerDestroy (contResult)
return ruleList

endproc

ContainerDestroy
Destroy a container identified by the supplied handle.
Syntax:
Bool ContainerDestroy (ContainerHandle Handle)
Handle is the handle to the container to be destroyed.
Returns:
TRUE if the function was successful, FALSE if the operation failed or the handle was invalid.
Comments:
After this function has been called the handle becomes invalid and thus can not be used any longer with any
other function, regardless if the operation executed with success or failed.
Example:
The following example returns the list of queued objects from the agent.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 10 - BMC Client Management Agent Functions - 91

proc main ()

OpRuleEntry[] GetOpRuleList ()

// Create a container for the direct request

ContainerHandle contRequest, contResult


contRequest = ContainerCreate ()

contResult = MtxAgentInvokeAction ("", "OpRuleList", contRequest)


ContainerDestroy (contRequest)

int i, iCount
iCount = ContainerCountValues (contResult, "Values")

OpRuleEntry ruleList[]

for (i=1; i<=iCount; i+=1)


OpRuleEntry ruleEntry
ruleEntry.szID = ContainerGetString (contResult, "Values", i)
GetOpRuleInfo (ruleEntry)
ruleList <<= ruleEntry
endfor

ContainerDestroy (contResult)
return ruleList

endproc

ContainerGetBoolean
Return the boolean value of the entry.
Syntax:
Bool ContainerGetBoolean (ContainerHandle Handle, String Name, Int Index)
Handle is the handle to the container.
Name is the name of the container entry.
Index is the value index of the container entry.
Returns:
The value the entry if found, FALSE if there is no entry with the given name and of type boolean.
Comments:
Given the name of an entry and a value index, return the value of the entry if found in the container. Each entry
can have multiple 'instances' or values and the required instance is identified by the supplied index. The index
starts at 1 for the first value and is also needed for single value entries. If the named value does not exist or is of
the wrong type, a runtime error is generated.
Example:
proc main ()

int i, iCount
ContainerHandle contParams
string szName

contParams = ContainerCreate ()

for (i=1; i<=iCount; i+=1)


szName = ContainerGetNextName (contParams, szName)
print (szName + ":\n")

Numara Software, Inc. and BMC Software, Inc. Confidential.


92 - BMC FootPrints Asset Core - Chilli Reference

int iType;
iType = ContainerGetType (contParams, szName)

if (iType == CONTAINER_ENTRY_BOOLEAN)
bool fValue
fValue = ContainerGetBoolean (contParams, szName, 1)
if (fValue)
print ("True")
else
print ("False")
endif
elseif (iType == CONTAINER_ENTRY_DOUBLE)
print (MakeStr (ContainerGetDouble (contParams, szName, 1)))
else
print ("<Array>")
endif
endfor

ContainerDestroy (contParams)

endproc

ContainerGetContainer
Return the container value of the entry.
Syntax:
ContainerHandle ContainerGetContainer (ContainerHandle Handle, String Name, Int Index)
Handle is the handle to the container.
Name is the name of the entry.
Index is the value index of the entry.
Returns:
A handle to the container entry if found, 0 if there is no entry with the given name and of type 'Container'.
Comments:
Given the name of an entry and a value index, return the value of the entry if found in the container. Each entry
can have multiple 'instances' or values and the required instance is identified by the supplied index. The index
starts at 1 for the first value and is also needed for single value entries. If the named value does not exist or is of
the wrong type, a runtime error is generated.
Example:
This example returns an OpStepEntry structure filled with information about a single operational rule step entry.
struct OpStepEntry
string szRuleName
string szScript
int iNumber, iStopOnError
endstruct

proc GetOpStepInfo (OpStepEntry & stepEntry)

// Create a container for the direct request

ContainerHandle contRequest, contResult


contRequest = ContainerCreate ()
ContainerSetString (contRequest, "RuleID", 1, stepEntry.szRuleName)
ContainerSetInteger (contRequest, "StepNumber", 1, stepEntry.iNumber)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 10 - BMC Client Management Agent Functions - 93

contResult = MtxAgentInvokeAction ("", "OpRuleGetStep", contRequest)


ContainerDestroy (contRequest)

ContainerHandle contValues
contValues = ContainerGetContainer (contResult, "Values", 1)
ContainerDestroy (contResult)

stepEntry.szScript = ContainerGetString (contValues, "StepScriptName", 1)


stepEntry.iStopOnError = ContainerGetInteger (contValues, "StepStopOnError", 1)

ContainerDestroy (contValues)

endproc

ContainerGetDividedInt64
Convert a divided 64 bit integer into an integer.
Syntax:
Int ContainerGetDividedInt64 (ContainerHandle Handle, String Name, Int Divisor)
Handle is the handle to the container.
Name is the name of the container entry.
Divisor is the value by which to divide the 64 bit integer.
Returns:
The converted integer if the operation was successful, 0 if the operation failed.
Comments:
By default Chilli does not support the 64 bit integer.

ContainerGetDouble
Return the double value of the entry.
Syntax:
Double ContainerGetDouble (ContainerHandle Handle, String Name, Int Index)
Handle is the handle to the container.
Name is the name of the container entry.
Index is the value index of the container entry.
Returns:
The value the entry if found, FALSE if there is no entry with the given name and of type double.
Comments:
Given the name of an entry and a value index, return the value of the entry if found in the container. Each entry
can have multiple 'instances' or values and the required instance is identified by the supplied index. The index
starts at 1 for the first value and is also needed for single value entries. If the named value does not exist or is of
the wrong type, a runtime error is generated.
Example:
proc main ()

int i, iCount
ContainerHandle contParams
string szName

contParams = ContainerCreate ()

for (i=1; i<=iCount; i+=1)

Numara Software, Inc. and BMC Software, Inc. Confidential.


94 - BMC FootPrints Asset Core - Chilli Reference

szName = ContainerGetNextName (contParams, szName)


print (szName + ":\n")

int iType;
iType = ContainerGetType (contParams, szName)

if (iType == CONTAINER_ENTRY_BOOLEAN)
bool fValue
fValue = ContainerGetBoolean (contParams, szName, 1)
if (fValue)
print ("True")
else
print ("False")
endif
elseif (iType == CONTAINER_ENTRY_DOUBLE)
print (MakeStr (ContainerGetDouble (contParams, szName, 1)))
else
print ("<Array>")
endif
endfor

ContainerDestroy (contParams)

endproc

ContainerGetInteger
Return the integer value of the entry.
Syntax:
Int ContainerGetInteger (ContainerHandle Handle, String Name, Int Index)
Handle is the handle to the container.
Name is the name of the container entry.
Index is the value index of the container entry.
Returns:
The value the entry if found, FALSE if there is no entry with the given name and of type integer.
Comments:
Given the name of an entry and a value index, return the value of the entry if found in the container. Each entry
can have multiple 'instances' or values and the required instance is identified by the supplied index. The index
starts at 1 for the first value and is also needed for single value entries. If the named value does not exist or is of
the wrong type, a runtime error is generated.
Example:
This example returns an OpStepEntry structure filled with information about a single operational rule step entry.
struct OpStepEntry
string szRuleName
string szScript
int iNumber, iStopOnError
endstruct

proc GetOpStepInfo (OpStepEntry & stepEntry)

// Create a container for the direct request

ContainerHandle contRequest, contResult


contRequest = ContainerCreate ()
ContainerSetString (contRequest, "RuleID", 1, stepEntry.szRuleName)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 10 - BMC Client Management Agent Functions - 95

ContainerSetInteger (contRequest, "StepNumber", 1, stepEntry.iNumber)

contResult = MtxAgentInvokeAction ("", "OpRuleGetStep", contRequest)


ContainerDestroy (contRequest)

ContainerHandle contValues
contValues = ContainerGetContainer (contResult, "Values", 1)
ContainerDestroy (contResult)

stepEntry.szScript = ContainerGetString (contValues, "StepScriptName", 1)


stepEntry.iStopOnError = ContainerGetInteger (contValues, "StepStopOnError", 1)

ContainerDestroy (contValues)

endproc

ContainerGetNextName
Return the next name in the container.
Syntax:
String ContainerGetNextName (ContainerHandle Handle, String Name)
Handle is the handle to the container.
Name is the name of the entry in the container.
Returns:
The name of the entry if a next entry was found, an empty string if there are no more entries in the container.
Comments:
Given the name of an entry this returns the next name in the container and can be used to iterate through the
entries. To start, the first passed name should be a blank string.
The components in the container are sorted in the same order as they were added to it.
Example:
proc main ()

int i, iCount
ContainerHandle contParams
contParams = ContainerCreate ()

// Load up a container from the parameter string

ContainerLoadXml (contParams, PerfEntry.szParameters)

iCount = ContainerCountNames (contParams)

string szName
for (i=1; i<=iCount; i+=1)
szName = ContainerGetNextName (contParams, szName)
print (szName + ":\n")
endfor

ContainerDestroy (contParams)

endproc

ContainerGetString
Return the string value of the entry.

Numara Software, Inc. and BMC Software, Inc. Confidential.


96 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
String ContainerGetString (ContainerHandle Handle, String Name, Int Index)
Handle is the handle to the container.
Name is the name of the container entry.
Index is the value index of the container entry.
Returns:
The value the entry if found, FALSE if there is no entry with the given name and of type string.
Comments:
Given the name of an entry and a value index, return the value of the entry if found in the container. Each entry
can have multiple 'instances' or values and the required instance is identified by the supplied index. The index
starts at 1 for the first value and is also needed for single value entries. If the named value does not exist or is of
the wrong type, a runtime error is generated.
Example:
The following example is taken from the hardware inventory and returns the list of hardware inventory objects
from the agent.
proc main ()

string[] GetHwObjectInstances (string szObjName)

// Create a container for the direct request

ContainerHandle contRequest, contResult


contRequest = ContainerCreate ()

ContainerSetString (contRequest, "ObjectName", 1, szObjName)


contResult = MtxAgentInvokeAction ("", "HardwareGetInstances", contRequest)
ContainerDestroy (contRequest)

int i, iCount
iCount = ContainerCountValues (contResult, "InstanceName")

string szInstances[]

for (i=1; i<=iCount; i+=1)


string szName
szName = ContainerGetString (contResult, "InstanceName", i)
szInstances <<= szName
endfor

ContainerDestroy (contResult)
return szInstances

endproc

ContainerGetType
Return the type of the named entry in the container.
Syntax:
Int ContainerGetType (ContainerHandle Handle, String Name)
Handle is the handle to the container.
Name is the name of the container entry.
Returns:
The type of the named entry in the container if the operation was successful or CONTAINER_ENTRY_NONE if the
entry is not found, the handle is invalid or the operation failed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 10 - BMC Client Management Agent Functions - 97

Comments:
The returned type can be any one of the values listed and explained under the heading Predefined Constants
earlier in this chapter.
If the named entry does not exist the return value is CONTAINER_ENTRY_NONE but no runtime error is generated.
Example:
proc main ()

int i, iCount
ContainerHandle contParams
string szName

contParams = ContainerCreate ()

for (i=1; i<=iCount; i+=1)


szName = ContainerGetNextName (contParams, szName)
print (szName + ":\n")

int iType;
iType = ContainerGetType (contParams, szName)

if (iType == CONTAINER_ENTRY_BOOLEAN)
bool fValue
fValue = ContainerGetBoolean (contParams, szName, 1)
if (fValue)
print ("True")
else
print ("False")
endif
elseif (iType == CONTAINER_ENTRY_STRING)
if (szName == 'Password')
print ("******")
else
print (ContainerGetString (contParams, szName, 1))
endif
else
print ("<Array>")
endif
endfor

ContainerDestroy (contParams)

endproc

ContainerLoadPList
Load the supplied container from an XML formatted string value.
Syntax:
Bool ContainerLoadPList (ContainerHandle Handle, String XmlValue)
Handle is the handle to the container.
XmlValue is the name of the entry in the container.
Returns:
True if the supplied XML string was successfully parsed, false if an error occurred such as invalid handle or XML
format.
Comments:
Any previous data in the container is lost. The format of the XML string follows the Mac OS standard.

Numara Software, Inc. and BMC Software, Inc. Confidential.


98 - BMC FootPrints Asset Core - Chilli Reference

ContainerLoadXml
Load the supplied container from an XML formatted string value.
Syntax:
Bool ContainerLoadXml (ContainerHandle Handle, String XmlValue)
Handle is the handle to the container.
XMLValue is the XML formatted string value of the container to load.
Returns:
TRUE if the supplied XML string was successfully parsed, FALSE if an error occurred such as invalid handle or
XML format.
Comments:
Any previous data in the container is lost. The format of the XML string follows the XML-RPC standard and is
compatible with the output of ContainerSaveXml.
Example:
proc main ()

int i, iCount
ContainerHandle contParams
contParams = ContainerCreate ()

// Load up a container from the parameter string

ContainerLoadXml (contParams, PerfEntry.szParameters)

iCount = ContainerCountNames (contParams)

string szName
for (i=1; i<=iCount; i+=1)
szName = ContainerGetNextName (contParams, szName)
print (szName + ":\n")
endfor

ContainerDestroy (contParams)

endproc

ContainerLoadXmlFile
Load the supplied container from an XML formatted file given its path.
Syntax:
Bool ContainerLoadXmlFile (ContainerHandle Handle, String FilePath)
Handle is the handle to the container.
FilePath is the name of the entry.
Returns:
TRUE if the supplied file was successfully opened and parsed, FALSE if an error occurred such as invalid handle
or XML format.
An integer indicating the first unread location, 0 if the function failed.
Comments:
Any previous data in the container is lost. The format of the XML file contents follows the XML-RPC standard and
is compatible with the output of ContainerSaveXml.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 10 - BMC Client Management Agent Functions - 99

ContainerLoadXmlFileAtSeek
Load the supplied container from an XML formatted file given its path.
Syntax:
Int ContainerLoadXmlFile (ContainerHandle Handle, String FilePath, Int SeekInFile)
Handle is the handle to the container.
FilePath is the name of the entry.
SeekInFile is the location at which to load.
Returns:
TRUE if the supplied file was successfully opened and parsed, FALSE if an error occurred such as invalid handle
or XML format.
An integer indicating the first unread location, 0 if the function failed.
Comments:
Any previous data in the container is lost. The format of the XML file contents follows the XML-RPC standard and
is compatible with the output of ContainerSaveXml.

ContainerSaveXml
Save the supplied container to an XML formatted file given its path.
Syntax:
String ContainerSaveXml (ContainerHandle Handle, string FilePath)
Handle is the handle to the container.
FilePath is the name and path of the file to save.
Returns:
True if the supplied file was successfully opened and filled, false if an error occurred such as invalid file
attributes or container handle.
Comments:
The format of the XML string follows the XML-RPC standard and is compatible with the input to
ContainerLoadXml.
Example:
The following example creates the container of parameters to pass to a client performance process action.
proc main ()

ContainerHandle contParams

contParams = ContainerCreate ()

ContainerSetString (contParams, "Name", 1, szEntryName)


ContainerSetString (contValues, "ActionParams", 1, ContainerSaveXml (contParams))

ContainerDestroy (contParams)

endproc

ContainerSaveXmlFile
Save the supplied container to an XML formatted file given its path.
Syntax:
Bool ContainerSaveXmlFile (ContainerHandle Handle, String FilePath)
Handle is the handle to the container.
FilePath is the name and path of the file to save.

Numara Software, Inc. and BMC Software, Inc. Confidential.


100 - BMC FootPrints Asset Core - Chilli Reference

Returns:
True if the supplied file was successfully opened and appended, false if an error occurred such as invalid file
attributes or an invalid container handle.
Comments:
The format of the XML string follows the XML-RPC standard and is compatible with the input to
ContainerLoadXml.

ContainerSaveXmlFileAppend
Save the supplied container to an XML formatted file given its path.
Syntax:
Bool ContainerSaveXmlFile (ContainerHandle Handle, String FilePath, Bool AppendToFile)
Handle is the handle to the container.
FilePath is the name and path of the file to save.
AppendToFile indicates if the saved XML data are to be saved at the end of the file.
Returns:
True if the supplied file was successfully opened and appended, false if an error occurred such as invalid file
attributes or an invalid container handle.
Comments:
The format of the XML string follows the XML-RPC standard and is compatible with the input to
ContainerLoadXml.

ContainerSetBoolean
Set the indexed boolean value of a named entry in the container.
Syntax:
Bool ContainerSetBoolean (ContainerHandle Handle, String Name, Int Index, Bool Value)
Handle is the handle to the container.
Name is the name of the container entry.
Index is the value index of the container entry.
Value is the new value the container entry is to be set to.
Returns:
TRUE if the value was updated or added, FALSE if an error occurred such as invalid handle or the index is too
large (more than 1 plus the largest value index).
Comments:
If the named entry does not exist, it is created and added to the container. The index starts at 1 for the first value.
Additional values can be added to the entry by supplying an index 1 higher than the number of values for the
entry.
Example:
The following example writes the contents of a RelayInfo structure containing the relevant relay information to
the relay module
struct RelayInfo
string szParent
int uParentPort
bool fAutoSelect, fEnabled
string szChildRange
int uSelectInterval
endstruct

proc main ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 10 - BMC Client Management Agent Functions - 101

bool SetRelayInfo (RelayInfo & relay)

// Create a container for the direct request

ContainerHandle contRequest, contValues, contResult


contRequest = ContainerCreate ()

contValues = ContainerCreate ()
ContainerSetString (contValues, "ParentName", 1, relay.szParent)
ContainerSetInteger (contValues, "ParentPort", 1, relay.uParentPort)
ContainerSetString (contValues, "ChildRange", 1, relay.szChildRange)
ContainerSetBoolean (contValues, "IsEnabled", 1, relay.fEnabled)
ContainerSetBoolean (contValues, "AutoSelect", 1, relay.fAutoSelect)
ContainerSetInteger (contValues, "SelectInterval", 1, relay.uSelectInterval)

ContainerSetContainer (contRequest, "Values", 1, contValues)

contResult = MtxAgentInvokeAction ("", "RelaySetValues", contRequest)


ContainerDestroy (contRequest)

return true

endproc

ContainerSetContainer
Set the indexed container value of a named entry in the container.
Syntax:
ContainerHandle ContainerSetContainer (ContainerHandle Handle, String Name, Int Index,
ContainerHandle Value)
Handle is the handle to the container.
Name is the name of the container entry.
Index is the value index of the container entry.
Value is the new value the container entry is to be set to.
Returns:
TRUE if the value was updated or added, FALSE if an error occurred such as invalid handle or the index is too
large (more than 1 plus the largest value index).
Comments:
If the named entry does not exist, it is created and added to the container. The index starts at 1 for the first value.
Additional values can be added to the entry by supplying an index 1 higher than the number of values for the
entry. If the addition of the container is successful the supplied value handle is consumed and is no longer valid.
Example:
The following example adds a new entry to the timer module and returns true/false to indicate if the addition was
successful or not.
proc main ()

bool AddTimer (string szTimer)

// Create a container for the request

ContainerHandle contRequest, contValues, contResult


contRequest = ContainerCreate ()
ContainerSetString (contRequest, "Name", 1, szTimer)

Numara Software, Inc. and BMC Software, Inc. Confidential.


102 - BMC FootPrints Asset Core - Chilli Reference

contValues = ContainerCreate ()
ContainerSetContainer (contRequest, "Values", 1, contValues)

contResult = MtxAgentInvokeAction ("", "TimerCreate", contRequest)


ContainerDestroy (contRequest)

ContainerDestroy (contResult)

return true

endproc

ContainerSetDouble
Set the indexed double value of a named entry in the container.
Syntax:
Bool ContainerSetDouble (ContainerHandle Handle, String Name, Int Index, Double Value)
Handle is the handle to the container.
Name is the name of the container entry.
Index is the value index of the container entry.
Value is the new value the container entry is to be set to.
Returns:
TRUE if the value was updated or added, FALSE if an error occurred such as invalid handle or the index is too
large (more than 1 plus the largest value index).
Comments:
If the named entry does not exist, it is created and added to the container. The index starts at 1 for the first value.
Additional values can be added to the entry by supplying an index 1 higher than the number of values for the
entry.

ContainerSetInteger
Set the indexed integer value of a named entry in the container.
Syntax:
Bool ContainerSetInteger (ContainerHandle Handle, String Name, Int Index, Int Value)
Handle is the handle to the container.
Name is the name of the container entry.
Index is the value index of the container entry.
Value is the new value the container entry is to be set to.
Returns:
TRUE if the value was updated or added, FALSE if an error occurred such as invalid handle or the index is too
large (more than 1 plus the largest value index).
Comments:
If the named entry does not exist, it is created and added to the container. The index starts at 1 for the first value.
Additional values can be added to the entry by supplying an index 1 higher than the number of values for the
entry.
Example:
This example returns an OpStepEntry structure filled with information about a single operational rule step entry.
struct OpStepEntry
string szRuleName
string szScript
int iNumber, iStopOnError

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 10 - BMC Client Management Agent Functions - 103

endstruct

proc GetOpStepInfo (OpStepEntry & stepEntry)

// Create a container for the direct request

ContainerHandle contRequest, contResult


contRequest = ContainerCreate ()
ContainerSetString (contRequest, "RuleID", 1, stepEntry.szRuleName)
ContainerSetInteger (contRequest, "StepNumber", 1, stepEntry.iNumber)

contResult = MtxAgentInvokeAction ("", "OpRuleGetStep", contRequest)


ContainerDestroy (contRequest)

ContainerHandle contValues
contValues = ContainerGetContainer (contResult, "Values", 1)
ContainerDestroy (contResult)

stepEntry.szScript = ContainerGetString (contValues, "StepScriptName", 1)


stepEntry.iStopOnError = ContainerGetInteger (contValues, "StepStopOnError", 1)

ContainerDestroy (contValues)

endproc

ContainerSetString
Set the indexed string value of a named entry in the container.
Syntax:
Bool ContainerSetString (ContainerHandle Handle, String Name, Int Index, String Value)
Handle is the handle to the container.
Name is the name of the container entry.
Index is the value index of the container entry.
Value is the new value the container entry is to be set to.
Returns:
TRUE if the value was updated or added, FALSE if an error occurred such as invalid handle or the index is too
large (more than 1 plus the largest value index).
Comments:
If the named entry does not exist, it is created and added to the container. The index starts at 1 for the first value.
Additional values can be added to the entry by supplying an index 1 higher than the number of values for the
entry.
Example:
This example returns an OpStepEntry structure filled with information about a single operational rule step entry.
struct OpStepEntry
string szRuleName
string szScript
int iNumber, iStopOnError
endstruct

proc GetOpStepInfo (OpStepEntry & stepEntry)

// Create a container for the direct request

ContainerHandle contRequest, contResult


contRequest = ContainerCreate ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


104 - BMC FootPrints Asset Core - Chilli Reference

ContainerSetString (contRequest, "RuleID", 1, stepEntry.szRuleName)


ContainerSetInteger (contRequest, "StepNumber", 1, stepEntry.iNumber)

contResult = MtxAgentInvokeAction ("", "OpRuleGetStep", contRequest)


ContainerDestroy (contRequest)

ContainerHandle contValues
contValues = ContainerGetContainer (contResult, "Values", 1)
ContainerDestroy (contResult)

stepEntry.szScript = ContainerGetString (contValues, "StepScriptName", 1)


stepEntry.iStopOnError = ContainerGetInteger (contValues, "StepStopOnError", 1)

ContainerDestroy (contValues)

endproc

InventoryAddObjType
Add an object type to an existing inventory.
Syntax:
Bool InventoryAddObjType (InventoryHandle Inventory, InvObjType objType)
Inventory is the handle to the inventory to which the new object type is to be added.
objType is the structure containing all information of the object type to be added.
Returns:
TRUE if the operation was successful, FALSE otherwise.

InventoryCreate
Create a new empty inventory and return its handle.
Syntax:
InventoryHandle InventoryCreate ()
Returns:
The handle to the inventory if successful, or an error code if the function failed.

InventoryDestroy
Destroy an existing inventory.
Syntax:
Bool InventoryDestroy (InventoryHandle Inventory)
Inventory is the handle to the inventory to be destroyed.
Returns:
TRUE if the operation was successful, FALSE otherwise.
Comments:
The handle to this inventory cannot be used anymore after executing this function.

InventorySave
Save the inventory to a specific location.
Syntax:
Bool InventorySave (InventoryHandle Inventory, String FilePath)
Inventory is the handle to the inventory to be saved.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 10 - BMC Client Management Agent Functions - 105

FilePath is the full file path to the target storage location of the inventory.
Returns:
TRUE if the operation was successful, FALSE otherwise.

MtxAgentInvokeAction
Invoke an action on a BCM agent.
Syntax:
ContainerHandle MtxAgentInvokeAction (String HostUrl, String ActionName, ContainerHandle
Params)
HostUrl is the complete URL address indentifying the host on which to execute the action.
ActionName is the action to be executed on the host.
Params is the handle to a container which lists the parameters necessary for the action to execute.
Returns:
A handle of type ContainerHandle if the function was successful, 0 if the operation failed.
Example:
The following example adds a new entry to the timer module and returns true/false to indicate if the addition was
successful or not.
proc main ()

bool AddTimer (string szTimer)

// Create a container for the request

ContainerHandle contRequest, contValues, contResult


contRequest = ContainerCreate ()
ContainerSetString (contRequest, "Name", 1, szTimer)

contValues = ContainerCreate ()
ContainerSetContainer (contRequest, "Values", 1, contValues)

contResult = MtxAgentInvokeAction ("", "TimerCreate", contRequest)


ContainerDestroy (contRequest)

ContainerDestroy (contResult)
return true

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


106 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


CSV File Functions

This chapter details all elements and functions which handle the CSV file functions in the Chilli script language.
All functions of this module are included in the csv.chx file for Windows or csv.so file for UNIX and Linux.

11.1 Introduction
CSV files are Comma Separated Values and are typically used to store information similar to spreadsheets.

11.2 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli CSV File function group has predefined data types of type
structure.

11.2.1 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated. For each predefined structure an array type of this structure also exists for usage
in the scripts.
Following you find a list of all predefined data types of type structure:

Data Type Description


CsvRow Represent all cells in a CSV file.
CsvRowList Represent all rows in a CSV file.

CsvRow
The CsvRow structure represents all cells in a CSV file.
Elements:

Elements Element Type Description


CellCount integer Number of all cells in the row.
Cells string array List of cells’ values.

A cell is the value between two separators, for example, the following ‘file’ has eight cells:
1,2,3,4
5,6,7,8

CsvRowList
The CsvRowList structure represents all rows in a CSV file.

Numara Software, Inc. and BMC Software, Inc. Confidential.


108 - BMC FootPrints Asset Core - Chilli Reference

Elements:

Elements Element Type Description


RowCount integer Number of rows in CSV file.
Rows CsvRow array List of all rows in CSV file.

A row is a line in a CSV file. The above mentioned example therefore has two rows which contain the eight cells.

11.3 Functions
Following you find a list of all available CSV File functions:

Function OS Description
CsvReadFile Parse a CSV file and build the list of rows including the value of each cell.

CsvReadFile
Parse a CSV file and build the list of rows including the value of each cell.
The CsvReadFile function has the following two signatures:
Syntax:
Struct CsvRowList CsvReadFile (String Filename)
Struct CsvRowList CsvReadFile (String Filename, String Separator)
Filename is the name of the CSV file to be read.
Separator is the type of separator to use in the file.
Returns:
A CsvRowList structure if the read operation was successful, or a structure with 0 elements if the function failed
or the file could not be found. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
A separator can be provided optionally if the CSV file is using anything other than a comma “,” as the separator
value. If the separator string is empty the function looks for a ‘\0’ character in the file.

Numara Software, Inc. and BMC Software, Inc. Confidential.


cURL Functions

This chapter explains the high level network functions of the Chilli language. All functions of this module are
included in the curl.chx file. These functions are not applicable to Solaris.

12.1 Introduction
curl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS, SCP,
SFTP, TFTP, TELNET, DICT, FILE and LDAP. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP
uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM,
Negotiate, kerberos...), file transfer resume, proxy tunneling, and so on.
The Curl related functions are a wrapper to cURL library. The procedure to use CURL is as follows:
1 Create a cURL object using the CurlCreate function.
2 Set the various parameters using the various CurlAdd, CurlSet, CurlRedirect functions (optional).
3 Set the target using the CurlSetTarget function.
4 Execute the request using the CurlSendAndRcv function.
5 Collect information about the request execution using the various CurlGetInfo functions (optional).
6 Destroy the cURL object using the CurlDestroy function.
Paramaters are persistent after they are set, which allows to run step 2, 3, 4, and 5 over and over again, re-using
the same cURL object, using the various CurlReset or setting the different elements independently to modify the
cURL parameters.

12.2 Error Codes


Following you find a list of all cURL error codes which are returned by the cURL functions. For the list of Chilli
runtime errors refer to Appendix E - Chilli Error Codes on page 677 at the end of the manual.

Error Description
ABORTED_BY_CALLBACK Aborted by callback. A callback returned "abort" to cURL.
BAD_CALLING_ORDER This is never returned by current cURL.
BAD_CONTENT_ENCODING Unrecognized transfer encoding.
BAD_FUNCTION_ARGUMENT Internal error. A function was called with a bad parameter.
BAD_PASSWORD_ENTERED This is never returned by current cURL.
CONV_FAILED Character conversion failed.
CONV_REQD Caller must register conversion callbacks.
COULDNT_CONNECT Failed to connect() to host or proxy.
COULDNT_RESOLVE_HOST Couldn't resolve host. The given remote host was not resolved.
COULDNT_RESOLVE_PROXY Couldn't resolve proxy. The given proxy host could not be resolved.
FAILED_INIT Very early initialization code failed. This is likely to be an internal error or issue.

Numara Software, Inc. and BMC Software, Inc. Confidential.


110 - BMC FootPrints Asset Core - Chilli Reference

Error Description
FILE_COULDNT_READ_FILE A file given with FILE:// couldn't be opened. Most likely because the file path doesn't identify
an existing file. Did you check file permissions?
FILESIZE_EXCEEDED Maximum file size exceeded.
FTP_ACCESS_DENIED We were denied access when trying to login to an FTP server or when trying to change
working directory to the one given in the URL.
FTP_BAD_DOWNLOAD_RESUME Attempting FTP resume beyond file size.
FTP_CANT_GET_HOST An internal failure to lookup the host used for the new connection.
FTP_CANT_RECONNECT A bad return code on either PASV or EPSV was sent by the FTP server, preventing cURL
from being able to continue.
FTP_COULDNT_GET_SIZE The FTP SIZE command returned error. SIZE is not a kosher FTP command, it is an
extension and not all servers support it. This is not a surprising error.
FTP_COULDNT_RETR_FILE This was either a weird reply to a 'RETR' command or a zero byte transfer complete.
FTP_COULDNT_SET_ASCII cURL failed to set ASCII transfer type (TYPE A).
FTP_COULDNT_SET_BINARY Received an error when trying to set the transfer mode to binary.
FTP_COULDNT_STOR_FILE FTP couldn't STOR file. The server denied the STOR operation. The error buffer usually
contains the server's explanation to this.
FTP_COULDNT_USE_REST The FTP REST command returned error. This should never happen if the server is sane.
FTP_PORT_FAILED The FTP PORT command returned error. This mostly happen when you haven't specified a
good enough address for cURL to use. See FTPPORT.
FTP_QUOTE_ERROR When sending custom "QUOTE" commands to the remote server, one of the commands
returned an error code that was 400 or higher.
FTP_SSL_FAILED Requested FTP SSL level failed
FTP_USER_PASSWORD_INCORRECT This is never returned by current cURL.
FTP_WEIRD_227_FORMAT FTP servers return a 227-line as a response to a PASV command. If cURL fails to parse
that line, this return code is passed back.
FTP_WEIRD_PASS_REPLY After having sent the FTP password to the server, cURL expects a proper reply. This error
code indicates that an unexpected code was returned.
FTP_WEIRD_PASV_REPLY cURL failed to get a sensible result back from the server as a response to either a PASV or
a EPSV command. The server is flawed.
FTP_WEIRD_SERVER_REPLY After connecting to an FTP server, cURL expects to get a certain reply back. This error
code implies that it got a strange or bad reply. The given remote server is probably not an
OK FTP server.
FTP_WEIRD_USER_REPLY After having sent user name to the FTP server, cURL expects a proper reply. This error
code indicates that an unexpected code was returned.
FTP_WRITE_ERROR After a completed file transfer, the FTP server did not respond a proper "transfer
successful" code.
FUNCTION_NOT_FOUND Function not found. A required LDAP function was not found.
GOT_NOTHING Nothing was returned from the server, and under the circumstances, getting nothing is
considered an error.
HTTP_PORT_FAILED Interface error. A specified outgoing interface could not be used. Set which interface to use
for outgoing connections' source IP address with INTERFACE.
HTTP_POST_ERROR This is an odd error that mainly occurs due to internal confusion.
HTTP_RANGE_ERROR The HTTP server does not support or accept range requests.
HTTP_RETURNED_ERROR This is returned if FAILONERROR is set TRUE and the HTTP server returns an error code
that is >= 400.
LDAP_CANNOT_BIND LDAP cannot bind. LDAP bind operation failed.
LDAP_INVALID_URL Invalid LDAP URL.
LDAP_SEARCH_FAILED LDAP search failed.
LIBRARY_NOT_FOUND Library not found. The LDAP library was not found.
LOGIN_DENIED The remote server denied curl to login (Added in 7.13.1).

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 12 - cURL Functions - 111

Error Description
OBSOLETE This is not an error. This used to be another error code in an old cURL version and is
currently unused.
OK All fine. Proceed as usual.
OPERATION_TIMEOUTED Operation timeout. The specified time-out period was reached according to the conditions.
OUT_OF_MEMORY Out of memory. A memory allocation request failed. This is serious badness and things are
severely screed up if this ever occur.
PARTIAL_FILE A file transfer was shorter or larger than expected. This happens when the server first
reports an expected transfer size, and then delivers data that doesn't match the previously
given size.
READ_ERROR There was an issue reading a local file or an error returned by the read callback.
RECV_ERROR Failure with receiving network data.
SEND_FAIL_REWIND When doing a send operation curl had to rewind the data to retransmit, but the rewinding
operation failed.
SHARE_IN_USE Share is in use.
SSL_CACERT Peer certificate cannot be authenticated with known CA certificates.
SSL_CACERT_BADFILE Issue with reading the SSL CA cert (path? access rights?).
SSL_CERTPROBLEM Issue with the local client certificate.
SSL_CIPHER Couldn't use specified cipher.
SSL_CONNECT_ERROR An issue occurred somewhere in the SSL/TLS handshake. You really want the error buffer
and read the message there because it pinpoints the issue slightly more. Could be
certificates (file formats, paths, permissions), passwords, and others.
SSL_ENGINE_INITFAILED Initiating the SSL Engine failed.
SSL_ENGINE_NOTFOUND The specified crypto engine wasn't found.
SSL_ENGINE_SETFAILED Failed setting the selected SSL crypto engine as default!
SSL_PEER_CERTIFICATE The remote server's SSL certificate was deemed not OK.
TELNET_OPTION_SYNTAX A telnet option string was Illegally formatted.
TFTP_DISKFULL Out of disk space on TFTP server.
TFTP_EXISTS TFTP File already exists.
TFTP_ILLEGAL Illegal TFTP operation.
TFTP_NOSUCHUSER No such TFTP user.
TFTP_NOTFOUND File not found on TFTP server.
TFTP_PERM Permission issue on TFTP server.
TFTP_UNKNOWNID Unknown TFTP transfer ID.
TOO_MANY_REDIRECTS Too many redirects. When following redirects, cURL hit the maximum amount. Set your limit
with MAXREDIRS.
UNKNOWN_TELNET_OPTION An option set with TELNETOPTIONS was not recognized/known. Refer to the appropriate
documentation.
URL_MALFORMAT The URL was not properly formatted.
URL_MALFORMAT_USER This is never returned by current cURL.
WRITE_ERROR An error occurred when writing received data to a local file, or an error was returned to
cURL from a write callback.
BAD_PARAM Provided paramaters are of the wrong type for this function.
MALFORMAT_USER This is never returned by current cURL.
SEND_ERROR Failed sending network data.
UNSUPPORTED_PROTOCOL The URL you passed to cURL used a protocol that this cURL does not support. The support
might be a compile-time option that you didn't use, it can be a misspelled protocol string or
just a protocol cURL has no code for.

Numara Software, Inc. and BMC Software, Inc. Confidential.


112 - BMC FootPrints Asset Core - Chilli Reference

12.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli User function group has Predefined Handle Data Types.

12.3.1 Predefined Curl Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


CurlHandle Object type: reference to the Handle of a curl client object

CurlHandle
The CurlHandle data type is a reference to the Handle of a curl client object.
The function CurlCreate returns a value of this object type that other functions expect as their first argument.
Any open curl client object and thus the value of this object type should always be closed by the CurlDestroy
function.

12.4 Functions
Following you find the list of all functions of the user function module:

Function OS Description
CurlAddCookie Add/update a specific cookie to be sent

CurlAddFormField Add/update a specific form field to be sent in a POST operation

CurlAddFtpCommand Add a complete FTP command line to be executed after connection

CurlAddHeaderField Add/update a specific field in the header to be sent

CurlAddTelnetOption Add/update a specific TELNET option.

CurlCancelBodyRedirect Cancel the previous body redirection set by CurlRedirectBodyTo

CurlCancelHeaderRedirect Cancel the previous body redirection set by CurlRedirectHeaderTo

CurlClearAll Clear all parameters

CurlClearOutputBuffers Clear both header and body internal buffers

CurlCreate Create the CURL client object

CurlDestroy Destroy a CURL client object

CurlGetBodyFromBuffer Get the body content from the internal buffer

CurlGetHeaderFromBuffer Get the header content from the internal buffer

CurlGetInfo Get string type information about the previously performed transfer

CurlRedirectBodyTo Set a file to redirect the output body to

CurlRedirectHeaderTo Set a file to redirect the output header to

CurlResetCookies Clear the list of cookies

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 12 - cURL Functions - 113

Function OS Description
CurlResetFormFields Clear the list of form fields

CurlResetFtpCommands Clear the list of FTP commands

CurlResetHeaderFields Clear the list of header fields

CurlResetTelnetOptions Clear the list of TELNET options

CurlSendAndRecv Send the request to the server

CurlSendBufferAndRecv Send the buffer content to the server and store the response in the internal buffer

CurlSetAuthentication Set the login/password pair

CurlSetDefaultTimeOut Set the timeout for the transactions

CurlSetOption Set the specified option

CurlSetProxy Set a proxy using a URL

CurlSetProxyCredentials Set the proxy login/password pair

CurlSetSSLVersion Set the SSL version

CurlSetTarget Set the target URL to xxx

CurlTelnetConnect Establish a connection with a TELNET server

CurlTelnetExecCmd Execute a shell or bash command

CurlTranslateErrorCode Translate a cURL error code to its description string

HttpSimpleGet A simple all-in-one GET request to the provided URL and saving the header and
the body to the provided file paths with no specific options

CurlAddCookie
Add/update a specific cookie to be sent.
Syntax:
Bool CurlAddCookie (CurlHandle Curl, String CookieName, String CookieValue)
Curl is the handle on a previously created cURL object.
CookieName is the cookie name to be added/updated.
CookieValue is the cookie value to be added/updated to.
Returns:
It returns TRUE if successful, FALSE otherwise.
Comments:
Subsequent calls to this method appends the cookie using a ; (semi-colon) as separator. If the CookieName was
already present in the list its CookieValue is overwritten.
An alternate use is to call this method only once with CookieName empty and set CookieValue to the entire cookie
list to be sent, this is the raw data behavior.
No space character is allowed in CookieName or CookieValue.
Examples:
Example1:
CookieName1 = "user"
CookieValue1 = "toto"
CookieName2 = "lang"
CookieValue2 = "english"
result: "user=toto;lang=english" in the packet capture.

Numara Software, Inc. and BMC Software, Inc. Confidential.


114 - BMC FootPrints Asset Core - Chilli Reference

Example2:
CookieName = ""
CookieValue = "user=toto;lang=english"
result: "user=toto;lang=english" in the packet capture.

CurlAddFormField
Add/update a specific form field to be sent in a POST operation.
Syntax:
Bool CurlAddFormField (CurlHandle Curl, String FieldName, String FieldValue)
Curl is the handle on a previously created cURL object.
FieldName is the form field name to be added/updated.
FieldValue is the form field value to be added/updated to.
Returns:
It returns TRUE if successful, FALSE otherwise.
Comments:
Subsequent calls to this method appends the fields using a & (ampersand) as separator. If the FieldName was
already present in the list its FieldValue is overwritten.
An alternate use is to call this method only once with FieldName empty and set FieldValue to the entire parameter
list to be sent, this is the raw data behavior.
No space character is allowed in FieldName or FieldValue.
After those form fields are defined (at least one call) the operation is automatically a POST to the specified URL
(defined using CurlSetTarget), pointing to the form file like: “http://server/form.php”
Examples:
Example1:
FieldName1 = "user"
FieldValue1 = "toto"
FieldName2 = "submit"
FieldValue2 = "send"
result: "user=toto&submit=send" in the packet capture.
Example2:
FieldName = ""
FieldValue = "user=toto&submit=send"
result: "user=toto&submit=send" in the packet capture.

CurlAddFtpCommand
Add a complete FTP command line to be executed after the connection is established.
Syntax:
Bool CurlAddFtpCommand (CurlHandle Curl, String FtpCmdLine)
Handle is the handle on a previously created cURL object.
FtpCmdLine is the FTP command line to be executed.
Returns:
It returns TRUE if successful, FALSE otherwise.
Comments:
Subsequent calls to this method creates a list of operation to be performed in the order of addition.
Example:
"DELE file-to-delete"

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 12 - cURL Functions - 115

CurlAddHeaderField
Add/update a specific field in the header to be sent.
Syntax:
Bool CurlAddHeaderField (CurlHandle Curl, String FieldName, String FieldValue)
Curl is the handle on a previously created cURL object.
FieldName is the header field name to be added/updated.
FieldValue is the header field value to be added/updated to.
Returns:
It returns TRUE if successful, FALSE otherwise.
Comments:
Subsequent calls to this method creates a list of header fields to be added/replaced. If the FieldName was already
present in the list its FieldValue is overwritten.
No space is allowed in FieldName or FieldValue.
Example:
FieldName = "User-Agent"
FieldValue = "BCM"
result: "User-Agent: BCM\r\n" in the packet capture.

CurlAddTelnetOption
Add/update a specific TELNET option.
Syntax:
Bool CurlAddTelnetOption (CurlHandle Curl, String OptionName, String OptionValue)
Curl is the handle on a previously created cURL object.
OptionName is the TELNET field name to be added/updated.
OptionValue is the TELNET field value to be added/updated to.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
OptionName = "TTYPE"
OptionValue = "Linux"
result: "TTYPE=Linux" in the telnet option list.

CurlCancelBodyRedirect
Cancel the previous body redirection set by CurlRedirectBodyTo.
Syntax:
int CurlCancelBodyRedirect (CurlHandle Curl)
Curl is the handle on a previously created cURL object.
Returns:
It returns TRUE if successful, FALSE otherwise.
Comments:
This has no effect if CurlRedirectBodyTo has not been called. The purpose of this method is to not save the
body at all, neither to a file, nor to the internal buffer, which is the default behavior.
Example:
include "curl.chx"

Numara Software, Inc. and BMC Software, Inc. Confidential.


116 - BMC FootPrints Asset Core - Chilli Reference

CurlHandle hHttp
hHttp = CurlCreate ()

if (fOnlyHeader && fKeepHeader)

# Redirects the HTTP header to a file.

lResult = CurlRedirectHeaderTo (hHttp, strTempFile)

# Cancel any kind of redirection for the HTTP body (discard the content)

CurlCancelBodyRedirect (hHttp)
else
lResult = CurlRedirectHeaderTo (hHttp, strTempFile + ".head")

if (lResult != 0)
LogPrint (Logger, "GetServerUrl", "Failed, to set the output to ["+ strTempFile +".head], with code
["+ lResult +"].")
endif

FileSetAttr (strTempFile + ".head", 32)


lResult = CurlRedirectBodyTo (hHttp, strTempFile)
endif

CurlDestroy (hHttp)

CurlCancelHeaderRedirect
Cancel the previous header redirection set by CurlRedirectHeaderTo.
Syntax:
int CurlCancelHeaderRedirect (CurlHandle Curl)
Curl is the handle on a previously created cURL object.
Returns:
It returns TRUE if successful, FALSE otherwise.
Comments:
This has no effect if CurlRedirectHeaderTo has not been called. The purpose of this method is to not save the
header at all, neither to a file, nor to the internal buffer, which is the default behavior.

CurlClearAll
Clear all parameters.
Syntax:
Bool CurlClearAll (CurlHandle Curl)
Curl is the handle on a previously created cURL object.
Returns:
It returns TRUE if successful, FALSE otherwise.
Comments:
This function clears all parameters, such as internal buffers, header fields, form fields, options, everything; it
returns the cURL to its initial state.

CurlClearOutputBuffers
Clear both header and body internal buffers.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 12 - cURL Functions - 117

Syntax:
Bool CurlClearOutputBuffers (CurlHandle Curl)
Curl is the handle on a previously created cURL object.
Returns:
It returns TRUE if successful, FALSE otherwise.
Comments:
This function can be used independend if the buffers are cues or not.

CurlCreate
Create the CURL client object.
Syntax:
CurlHandle CurlCreate ()
Returns:
It returns a handle to the object of type CurlHandle if successful, 0 otherwise.
Comments:
Options for this object can be set throught the various accessors before the actual connection to the server is done
using CurlSendAndRcv.

CurlDestroy
Destroy a CURL client object.
Bool CurlDestroy (CurlHandle Curl)
Curl is the handle on the cURL object to be destroyed.
Returns:
It returns TRUE if the destroy is successful, FALSE otherwise.
Comments:
This is used to destroy a previously created connection.

CurlGetBodyFromBuffer
Get the body content from the internal buffer.
Syntax:
String CurlGetBodyFromBuffer (CurlHandle Curl)
Curl is the handle on a previously created cURL object.
Returns:
It returns a string containing the body(ies) of the previous transaction with the remote server.
Comments:
This function can only be applied if CurlRedirectBodyTo has been used with no file name or not used at all
since the cURL object creation (CurlCreate).
This method is NOT recommended to be used.

CurlGetHeaderFromBuffer
Get the header content from the internal buffer.
Syntax:
String CurlGetHeaderFromBuffer (CurlHandle Curl)
Curl is the handle on a previously created cURL object.

Numara Software, Inc. and BMC Software, Inc. Confidential.


118 - BMC FootPrints Asset Core - Chilli Reference

Returns:
It returns a string containing the header(s) of the previous transaction with the remote server.
Comments:
This function can only be applied if CurlRedirectHeaderTo has been used with no file name or not used at all
since the cURL object creation (CurlCreate).

CurlGetInfo
Get string type information about the previously performed transfer.
Syntax:
Int CurlGetInfo (CurlHandle Curl, String InfoName, String InfoValue)
Int CurlGetInfo (CurlHandle Curl, String InfoName, Long InfoValue)
Int CurlGetInfo (CurlHandle Curl, String InfoName, Double InfoValue)
Curl is the handle on a previously created cURL object.
InfoName is the name of the information to get.
InfoValue is the string information asked for.
Returns:
It returns the cURL return code of the operation, 0 means success. This code can be translated to text using
CurlTranslateErrorCode. Error codes and their translations are listed further in this document.
Comments:
InfoValue is an output parameter containing the string type result of the element specified by InfoName.

Notes about the use of the InfoName parameter:


You will find additional information for this parameter on the cURL website: http://curl.haxx.se/libcurl/c/
curl_easy_getinfo.html.
• The InfoName to be used is the cURL name without the CURLINFO_ prefix.
For example, in cURL the information CURLINFO_REDIRECT_COUNT should be used in CurlGetInfo as
REDIRECT_COUNT.
• Information which need to pass a struct curl_slist is not supported.
• What is described as Pass a pointer to a 'char *' should be used as InfoName type being a string, so the
function to use should be:
Int CurlGetInfo (CurlHandle Curl, String InfoName, String InfoValue)
• What is described as Pass a pointer to a double should be used as InfoName type being a double, so the
function to use should be:
Int CurlGetInfo (CurlHandle Curl, String InfoName, Double InfoValue)
• What is described as Pass a pointer to a long should be used as InfoName type being a long, so the
function to use should be:
Int CurlGetInfo (CurlHandle Curl, String InfoName, Long InfoValue)
The InfoName parameter can be one of the following values:

Name Description
EFFECTIVE_URL Pass a String type InfoValue to receive the last used effective URL.
RESPONSE_CODE Pass a Long type InfoValue to receive the last received HTTP or FTP code. This is zero if no server
response code has been received. Note that a proxy's CONNECT response should be read with
HTTP_CONNECTCODE and not this.
HTTP_CONNECTCODE Pass a Long type InfoValue to receive the last received proxy response code to a CONNECT request.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 12 - cURL Functions - 119

Name Description
FILETIME Pass a Long type InfoValue to receive the remote time of the retrieved document (in number of
seconds since 1 jan 1970 in the GMT/UTC time zone). If you get -1, it can be because of many
reasons (unknown, the server hides it or the server doesn't support the command that tells
document time etc.) and the time of the document is unknown. Note that you must tell the server to
collect this information before the transfer is made, by using the FILETIME option with
CurlSetOption or you will unconditionally get a -1 back.
TOTAL_TIME Pass a Double type InfoValue to receive the total time in seconds for the previous transfer, including
name resolving, TCP connect etc.
NAMELOOKUP_TIME Pass a Double type InfoValue to receive the time, in seconds, it took from the start until the name
resolving was completed.
CONNECT_TIME Pass a Double type InfoValue to receive the time, in seconds, it took from the start until the connect
to the remote host (or proxy) was completed.
PRETRANSFER_TIME Pass a Double type InfoValue to receive the time, in seconds, it took from the start until the file
transfer is just about to begin. This includes all pre-transfer commands and negotiations that are
specific to the particular protocol(s) involved.
STARTTRANSFER_TIME Pass a Double type InfoValue to receive the time, in seconds, it took from the start until the first byte
is just about to be transferred. This includes PRETRANSFER_TIME and also the time the server
needs to calculate the result.
REDIRECT_TIME Pass a Double type InfoValue to receive the total time, in seconds, it took for all redirection steps
include name lookup, connect, pretransfer and transfer before final transaction was started.
REDIRECT_TIME contains the complete execution time for multiple redirections.
REDIRECT_COUNT Pass a Long type InfoValue to receive the total number of redirections that were actually followed.
SIZE_UPLOAD Pass a Double type InfoValue to receive the total amount of bytes that were uploaded.
SIZE_DOWNLOAD Pass a Double type InfoValue to receive the total amount of bytes that were downloaded. The
amount is only for the latest transfer and will be reset again for each new transfer.
SPEED_DOWNLOAD Pass a Double type InfoValue to receive the average download speed that curl measured for the
complete download.
SPEED_UPLOAD Pass a Double type InfoValue to receive the average upload speed that curl measured for the
complete upload.
HEADER_SIZE Pass a Long type InfoValue to receive the total size of all the headers received.
REQUEST_SIZE Pass a Long type InfoValue to receive the total size of the issued requests. This is so far only for
HTTP requests. Note that this may be more than one request if FOLLOWLOCATION is true.
SSL_VERIFYRESULT Pass a Long type InfoValue to receive the result of the certification verification that was requested
(using the SSL_VERIFYPEER option with CurlSetOption).
SSL_ENGINES Not implemented.
CONTENT_LENGTH_DOWNLO Pass a Double type InfoValue to receive the content-length of the download. This is the value read
AD from the Content-Length: field.
CONTENT_LENGTH_UPLOAD Pass a Double type InfoValue to receive the specified size of the upload.
CONTENT_TYPE Pass a String type InfoValue to receive the content-type of the downloaded object. This is the value
read from the Content-Type: field. If you get NULL, it means that the server didn't send a valid
Content-Type header or that the protocol used doesn't support this.
PRIVATE Pass a String type InfoValue to receive the pointer to the private data associated with the curl handle
(set with the PRIVATE option with CurlSetOption).
HTTPAUTH_AVAIL Pass a Long type InfoValue to receive a bitmask indicating the authentication method(s) available.
The meaning of the bits is explained in the HTTPAUTH option for CurlSetOption.
PROXYAUTH_AVAIL Pass a Long type InfoValue to receive a bitmask indicating the authentication method(s) available for
your proxy authentication.
OS_ERRNO Pass a Long type InfoValue to receive the errno variable from a connect failure.
NUM_CONNECTS Pass a Long type InfoValue to receive how many new connections cURL had to create to achieve the
previous transfer (only the successful connects are counted). Combined with REDIRECT_COUNT
you are able to know how many times cURL successfully reused existing connection(s) or not. See
the Connection Options of CurlSetOption to see how cURL tries to make persistent connections to
save time.
COOKIELIST Not implemented.

Numara Software, Inc. and BMC Software, Inc. Confidential.


120 - BMC FootPrints Asset Core - Chilli Reference

Name Description
LASTSOCKET Pass a Long type InfoValue to receive the last socket used by this curl session. If the socket is no
longer valid, -1 is returned. When you finish working with the socket, you must call
curl_easy_cleanup() as usual and let cURL close the socket and cleanup other resources
associated with the handle. This is typically used in combination with CONNECT_ONLY.
FTP_ENTRY_PATH Pass a String type InfoValue to receive a pointer to a string holding the path of the entry path. That is
the initial path cURL ended up in when logging on to the remote FTP server. This stores a NULL as
pointer if something is wrong.

CurlRedirectBodyTo
Set a file to redirect the output body to.
Syntax:
Int CurlRedirectBodyTo (CurlHandle Curl, String FilePath)
Curl is the handle on a previously created cURL object.
FilePath is the absolute path of the file to save the body to.
Returns:
It returns the cURL return code of the operation, 0 means success. This code may be translated to text using
CurlTranslateErrorCode. Error codes and their translations are listed further in this document.
Comments:
If the FilePath parameter is empty the output will be redirected to the internal buffer dedidated to the body of the
server response. It is NOT recommended to leave it empty as the body may be large and may crash the
application.
If the file path does not already exist it will be created, if it does, it will be opened. The server response body will
be written at the end of the file.

CurlRedirectHeaderTo
Set a file to redirect the output header to.
Syntax:
Int CurlRedirectHeaderTo (CurlHandle Curl, String FilePath)
Curl is the handle on a previously created cURL object.
FilePath is the absolute path of the file to save the header to.
Returns:
It returns the cURL return code of the operation, 0 means success. This code may be translated to text using
CurlTranslateErrorCode. Error codes and their translations are listed further in this document.
Comments:
If the FilePath parameter is empty the output will be redirected to the internal buffer dedidated to the header of
the server response.
If the file path does not already exist it will be created, if it does, it will be opened. The server response header
will be written at the end of the file.

CurlResetCookies
Clear the list of cookies added through CurlAddCookie.
Syntax:
Bool CurlResetCookies (CurlHandle Curl)
Curl is the handle on a previously created cURL object.
Returns:
It returns TRUE if successful, FALSE otherwise.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 12 - cURL Functions - 121

CurlResetFormFields
Clear the list of form fields added through CurlAddFormField thus setting the operation back from a POST to the
default GET.
Syntax:
Bool CurlResetFormFields (CurlHandle Curl)
Curl is the handle on a previously created cURL object.
Returns:
It returns TRUE if successful, FALSE otherwise.

CurlResetFtpCommands
Clear the list of FTP commands added through CurlAddFtpCommand.
Syntax:
Bool CurlResetFtpCommands (CurlHandle Curl)
Curl is the handle on a previously created cURL object.
Returns:
It returns TRUE if successful, FALSE otherwise.

CurlResetHeaderFields
Clear the list of header fields added through CurlAddHeaderField.
Syntax:
Bool CurlResetHeaderFields (CurlHandle Curl)
Curl is the handle on a previously created cURL object.
Returns:
It returns TRUE if successful, FALSE otherwise.

CurlResetTelnetOptions
Clear the list of TELNET options.
Syntax:
Bool CurlResetTelnetOptions (CurlHandle Curl)
Curl is the handle on a previously created cURL object.
Returns:
TRUE to indicate success, FALSE in case of failure.

CurlSendAndRecv
Send the request to the server using all the parameters previously set via the various CurlSet, CurlAdd, and
CurlRedirect functions.

Syntax:
Int CurlSendAndRecv (CurlHandle Curl)
Curl is the handle on a previously created cURL object.
Returns:
It returns the cURL return code of the operation, 0 means success. This code may be translated to text using
CurlTranslateErrorCode. Error codes and their translations are listed further in this document.

Numara Software, Inc. and BMC Software, Inc. Confidential.


122 - BMC FootPrints Asset Core - Chilli Reference

Comments:
Once this function has been called the various CurlInfo may be called upon needs and purposes. The
parameters set before this call remain valid and can be modified/updated to run this function again.

CurlSendBufferAndRecv
Send the buffer content to the server and store the response in the internal buffer.
Syntax:
Int CurlSendBufferAndRecv (CurlHandle Curl, String Buffer)
Curl is the handle on a previously created cURL object.
Buffer is the buffer to send.
Returns:
The return code of the operation, 0 indicating success, any other return code describing the error.
Comments:
CurlSendAndRecv should be performed on time before using CurlSendBufferAndRecv.
The response is always stored in the internal buffer bufOutputBody, even if CURLOPT_NOBODY is set to false or
CurlRedirectBodyTo is set to a file. It can be read with CurlGetBodyFromBuffer.

CurlSetAuthentication
Set the login/password pair.
Syntax:
Int CurlSetAuthentication (CurlHandle Curl, String UserName, String Password)
Curl is the handle on a previously created cURL object.
UserName is the username to be used for authentication.
Password is the password to be used for authentication.
Returns:
It returns the cURL return code of the operation, 0 means success. This code may be translated to text using
CurlTranslateErrorCode. Error codes and their translations are listed further in this document.
Comments:
This function is to be used for websites that have restricted areas. If set, it will be used in subsequent calls to the
server.

CurlSetDefaultTimeOut
Set the timeout for the transactions.
Syntax:
Bool CurlSetDefaultTimeOut (CurlHandle Curl, Int TimeOut)
Curl is the handle on a previously created cURL object.
TimeOut is the number of seconds before aborting the transaction.
Returns:
It returns TRUE if successful, FALSE otherwise.

CurlSetOption
Set the specified option.
Syntax:
Int CurlSetOption (CurlHandle Curl, String OptionName, String OptionValue)
Int CurlSetOption (CurlHandle Curl, String OptionName, Long OptionValue)
Int CurlSetOption (CurlHandle Curl, String OptionName, Double OptionValue)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 12 - cURL Functions - 123

Curl is the handle on a previously created cURL object.


OptionName is the name of the option to be set.
OptionValue is the long value to set.
Returns:
It returns the cURL return code of the operation, 0 means success. This code may be translated to text using
CurlTranslateErrorCode. Error codes and their translations are listed further in this document.
Comments:
Sets the specified option, the value being either a string, a long integer or a double floating point value.

Notes about the use of CurlSetOption for the OptionName parameter:


You will find additional information for this parameter on the cURL website: http://curl.haxx.se/libcurl/c/
curl_easy_setopt.html.
• Options which need to pass a function pointer, data pointer, pointer, curl_off_t, curl_slist and
pointer to a linked list are not supported.
• The OptionName to be used is the cURL name without the CURLOPT_ prefix.
For example, in cURL the option CURLOPT_FOLLOWLOCATION should be used in CurlSetOption as
FOLLOWLOCATION.
• What is described as Pass a pointer to a zero terminated string and Pass a char * should be used
as OptionValue type being a string, so the function signature to use should be:
Int CurlSetOption (CurlHandle Curl, String OptionName, String OptionValue)
• Chilli strings are natively zero terminated.
• What is described as Pass a long should be used as OptionValue type being a long, so the function to use
should be:
Int CurlSetOption (CurlHandle Curl, String OptionName, Long OptionValue)

CurlSetProxy
Set a proxy using a URL.
Syntax:
Bool CurlSetProxy (CurlHandle Curl, String ProxyUrl)
Curl is the handle on a previously created cURL object.
ProxyUrl is the address of the proxy.
Returns:
It returns TRUE if successful, FALSE otherwise.
Comments:
Sets a proxy using a URL, similar to the CurlSetTarget, the URL may contain the port number: http://
<proxy>:<port> or there could be a separate call to CurlSetOption with the OptionName set to PROXYPORT.

CurlSetProxyCredentials
Set the proxy login/password pair
Syntax:
Bool CurlSetProxyCredentials (CurlHandle Curl, String UserName, String Password)
Curl is the handle on a previously created cURL object.
UserName is the username to be used for proxy authentication.
Password is the password to be used for proxy authentication.
Returns:
It returns TRUE if successful, FALSE otherwise.

Numara Software, Inc. and BMC Software, Inc. Confidential.


124 - BMC FootPrints Asset Core - Chilli Reference

Comments:
If set, it will be used in subsequent calls to the server.

CurlSetSSLVersion
Set the SSL version.
Syntax:
Bool CurlSetSSLVersion (CurlHandle Curl, Int SSLVersion)
Curl is the handle on a previously created cURL object.
SSLVersion defines the SSL version to be used.
Returns:
It returns TRUE if successful, FALSE otherwise.
Comments:
It will be used in subsequent calls to the server once set.
SSLVersion valid inputs are:
0 = DEFAULT (no SSL).
1 = TLS v1.
2 = SSL v2.
3 = SSL v3.

CurlSetTarget
Set the target URL to
Syntax:
Int CurlSetTarget (CurlHandle Curl, String Url)
Curl is the handle on a previously created cURL object.
Url is the URL to perform operations on.
Returns:
It returns the cURL return code of the operation, 0 means success. This code may be translated to text using
CurlTranslateErrorCode. Error codes and their translations are listed further in this document
Comments:
The format of the URL supports various elements such as: login, password, server address (IP or Name), port
number, subfolders, filename where only the server address is mandatory.
If the given URL lacks the protocol part ("http://" or "ftp://" etc.), it will attempt to guess which protocol to use
based on the given host name. If the given protocol of the set URL is not supported, cURL will return on error
(UNSUPPORTED_PROTOCOL).
HTTP, HTTPS, FTP, FTPS, and TELNET are supported.
Example:
Here are a few example of URL format:
http://<login>:<password>@<server>:<port>/<subfolder1>/<subfolder2>/<file>
http://<login>:<password>@<server>:<port>/
http://<login>@<server>:<port>/
http://<server>/

CurlTelnetConnect
Establish a connection with a TELNET server.Execute a shell or bash command
Syntax:
Int CurlTelnetConnect (CurlHandle Curl)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 12 - cURL Functions - 125

Curl is the handle on a previously created cURL object.


Returns:
The return code of the operation, 0 indicating success, any other code representing an error.
Comments:
This function requires its options being set beforehand via the CurlSetOption function.

CurlTelnetExecCmd
Execute a shell or bash command.
Syntax:
Int CurlTelnetExecCmd (CurlHandle Curl, String Command)
Curl is the handle on a previously created cURL object.
Command is the shell or bash commande to execute.
Returns:
The return code of the operation, 0 indicating success, any other code representing an error.
Example:
This example executes the inputed command on the remote hosts and returns the output
long lResult

lResult = CurlTelnetExecCmd (hTelnet, “ls“)

if (lResult != 0)
LogPrint (Logger, "ExecuteCmd", "An error occurred. CODE ["+ lResult +"], DESCRIPTION ["+
CurlTranslateErrorCode (hTelnet, lResult) +"] for [telnet://"+ szIpAddress +"].")
endif

szReceived = CurlGetBodyFromBuffer (hTelnet)


Print (Logger, "ExecuteCmd", "["+ szReceived +"]")

CurlTranslateErrorCode
Translate a cURL error code to its description string.
Syntax:
String CurlTranslateErrorCode (CurlHandle Curl, Int ErrorCode)
Curl is the handle on a previously created cURL object.
ErrorCode is the cURL error code to be translated for better understanding.
Returns:
It returns a string describing the cURL error.

HttpSimpleGet
This function is a simple all-in-one GET request to the provided URL and saving the header and the body to the
provided file paths with no specific options.
Syntax:
Int HttpSimpleGet (String Url, String BodyPath, String HeaderPath)
Url is the URL to get.
BodyPath is the absolute file path where the body will be saved.
HeaderPath is the absolute file path where the header will be saved.

Numara Software, Inc. and BMC Software, Inc. Confidential.


126 - BMC FootPrints Asset Core - Chilli Reference

Returns:
It returns the cURL return code of the operation, 0 means success. This code may be translated to text using
CurlTranslateErrorCode. Error codes and their translations are listed further in this document.
Comments:
The Url may include optional element such as username, password, and server port, mandatory elements are
protocol and server address or name.
Full options Url looks like: http://<user>:<password>@<server>:<port>/<subdir>/<file>
Minimum options Url looks like: http://<server>/
If the BodyPath is empty the body will not be downloaded, a HEAD will be performed instead of a GET.
If the HeaderPath is empty the header will not be saved.
HeaderPath and BodyPath may NOT be the same file.
It will create a cURL object use it for a GET and destroy it.

12.5 Example
The following example performs an HTTP GET operation on www.yahoo.com and saves the page content to a file
using the above explained functions.

include "curl.chx"

int main ()

CurlHandle hHttp
double dblMaxSize
long lResult, lTimeout, lHttpReturnCode
int iPort
string strUrl, strWholeFile, strFileName, strUserAgent

hHttp = CurlCreate ()

lTimeout = 90
CurlSetOption (hHttp, "TIMEOUT", lTimeout)

dblMaxSize = 102400
CurlSetOption (hHttp, "MAXFILESIZE_LARGE", dblMaxSize)

iPort = 80
CurlSetOption (hHttp, "PORT", iPort)

strUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705)"
CurlAddHeaderField (hHttp, "User-Agent", strUserAgent)

strUrl = "http://www.yahoo.com"
lResult = CurlSetTarget (hHttp, strUrl)

if (lResult != 0)
// ...
endif

strFileName = "./Yahoo.html"
FileDelete (strFileName)
lResult = CurlRedirectBodyTo (hHttp, strFileName)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 12 - cURL Functions - 127

FileSetAttr (strFileName, 32)

if (lResult != 0)
// ...
endif

lResult = CurlSendAndRecv (hHttp)

if (lResult != 0)
// ...
endif

CurlResetHeaderFields (hHttp)

CurlGetInfo (hHttp, "RESPONSE_CODE", lHttpReturnCode)

if (lHttpReturnCode == 200)
strWholeFile = FileToString (strFileName, true)
// ...
else
// ...
endif

CurlDestroy (hHttp)

return 0
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


128 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


DBM Database Functions

This chapter in the Chilli Reference explains in detail all functions concerning the DBM database manipulation.
All functions of this module are included in the dbm.chx file for Windows or dbm.so file for UNIX and Linux.

13.1 Introduction
DBM files are simple key/value lookup files used as simple databases. The Chilli DBM functions group enables
you to store, modify and extract information from such files.

13.2 Error Codes


Following you find a list of all DBM error codes. These errors are run-time errors that causes the handler specified
in ErrorHandler to be invoked. Functions can return these in addition to the standard runtime errors such as
FUNCFAILED. You will find a list with all runtime errors in Appendix E - Chilli Error Codes on page 677 at the end
of the manual.

Name Description
ERR_DBMBADFILE Unable to open/create DBM file
ERR_DBMBADHANDLE Invalid DBM handle

13.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli DBM Database function group has Predefined Handle Data
Types.

13.3.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


Dbm Object type: reference to the dbm file handle

DBM
The DBM data type is a reference to the handle of an DBM file.

Numara Software, Inc. and BMC Software, Inc. Confidential.


130 - BMC FootPrints Asset Core - Chilli Reference

The function DbmCreateFile returns a value of this object type that other functions expect as their first
argument. Any open DBM file and thus the value of this object type should always be closed by the
DbmCLoseFile function.

13.4 Functions
Following you find a complete list of all DBM Database functions:

Function OS Description
DbmCloseFile Close an already open DBM file

DbmCreateFile Create a DBM file if it does not exist already

DbmDeleteValue Delete the supplied key and its associated value from an open DBM file

DbmFetchValue Read the value of the supplied key from an already open DBM file

DbmFirstKey Read the value of the first key from an already open DBM file

DbmInsertValue Insert a key/value pair into an already open DBM file

DbmNextKey Reads the value of the ‘next’ key from an already open DBM file

DbmOpenFile Open a DBM file if it exists already

DbmReplaceValue Replace a key/value pair into an already open DBM file

DbmCloseFile
Close an open DBM file.
Syntax:
Bool DbmCloseFile (Dbm FileName)
FileName is the name of the DBM file to be closed.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Example:
The following example prints all keys and values from a dbm file.
proc main ()

dbm ptrDbm
string szKey

// Open the database file


ptrDbm = DbmOpenFile ("my_dbm")

// Get first key


szKey = DbmFirstKey (ptrDbm)
while (szKey != "")
// Print key and value
print ("key :" + szKey + " value:" + DbmFetchValue (ptrDbm, szKey) + "\n")
// Get next key
szKey = DbmNextKey (ptrDbm)
endwhile

// Close the database file


DbmCloseFile (ptrDbm)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 13 - DBM Database Functions - 131

endproc

DbmCreateFile
Create a new DBM file.
Syntax:
Dbm DbmCreateFile (String FileName)
FileName is the name of the DBM file to be created.
Returns:
Returns a reference to the DBM file if the create operation was successful. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
If the file already exists the function opens the file.
Example:
The following example inserts new keys, deletes a key and replaces another in a dbm file.
proc main ()
dbm ptrDbm
ptrDbm = DbmCreateFile ("my_dbm")
DbmInsertValue (ptrDbm, "my_first_key", "my_first_value")
DbmInsertValue (ptrDbm, "my_second_key", "my_second_value")
DbmDeleteValue (ptrDbm, "my_first_key")
DbmReplaceValue (ptrDbm, "my_second_key", "my_second_new_value")
DbmCloseFile (ptrDbm)
endproc

DbmDeleteValue
Delete the supplied key and its associated value from an open DBM file.
Syntax:
Bool DbmDeleteValue (Dbm FileName, String KeyName)
FileName is the name of the DBM file containing the value.
KeyName is the name of the key of the key/value pair to be deleted.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The operation fails if the key or the file do not exist.
Example:
The following example inserts new keys, deletes a key and replaces another in a dbm file.
proc main ()
dbm ptrDbm
ptrDbm = DbmCreateFile ("my_dbm")
DbmInsertValue (ptrDbm, "my_first_key", "my_first_value")
DbmInsertValue (ptrDbm, "my_second_key", "my_second_value")
DbmDeleteValue (ptrDbm, "my_first_key")
DbmReplaceValue (ptrDbm, "my_second_key", "my_second_new_value")
DbmCloseFile (ptrDbm)
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


132 - BMC FootPrints Asset Core - Chilli Reference

DbmFetchValue
Read the value of the supplied key from an already open DBM file.
Syntax:
String DbmFetchValue (Dbm FileName, String Key)
FileName is the name of the DBM file.
Key is the name of the key to be fetched.
Returns:
A string containing the value of the key if successful, or an empty string if the operation fails or the key cannot be
found. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Example:
The following example prints all keys and values from a dbm file.
proc main ()

dbm ptrDbm
string szKey

// Open the database file


ptrDbm = DbmOpenFile ("my_dbm")

// Get first key


szKey = DbmFirstKey (ptrDbm)
while (szKey != "")
// Print key and value
print ("key :" + szKey + " value:" + DbmFetchValue (ptrDbm, szKey) + "\n")
// Get next key
szKey = DbmNextKey (ptrDbm)
endwhile

// Close the database file


DbmCloseFile (ptrDbm)

endproc

DbmFirstKey
Read the first key from an already open DBM file.
Syntax:
String DbmFirstKey (Dbm FileName)
FileName is the name of the DBM file.
Returns:
A string containing the first key if successful, or an empty string if the operation fails. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.
Comments:
This is used with DbmNextKey to start stepping through all the keys in the file.
Example:
The following example prints all keys and values from a dbm file.
proc main ()

dbm ptrDbm
string szKey

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 13 - DBM Database Functions - 133

// Open the database file


ptrDbm = DbmOpenFile ("my_dbm")

// Get first key


szKey = DbmFirstKey (ptrDbm)
while (szKey != "")
// Print key and value
print ("key :" + szKey + " value:" + DbmFetchValue (ptrDbm, szKey) + "\n")
// Get next key
szKey = DbmNextKey (ptrDbm)
endwhile

// Close the database file


DbmCloseFile (ptrDbm)

endproc

DbmInsertValue
Insert a key/value pair into an open DBM file.
Syntax:
Bool DbmInsertValue (Dbm FileName, String Key, String KeyValue)
FileName is the name of the DBM file.
Key is the name of the key to be created.
KeyValue is the value to be attributed to the new key.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
This operation fails if the key exists already.
Example:
The following example inserts new keys, deletes a key and replaces another in a dbm file.
proc main ()
dbm ptrDbm
ptrDbm = DbmCreateFile ("my_dbm")
DbmInsertValue (ptrDbm, "my_first_key", "my_first_value")
DbmInsertValue (ptrDbm, "my_second_key", "my_second_value")
DbmDeleteValue (ptrDbm, "my_first_key")
DbmReplaceValue (ptrDbm, "my_second_key", "my_second_new_value")
DbmCloseFile (ptrDbm)
endproc

DbmNextKey
Read the 'next' key from an already open DBM file.
Syntax:
String DbmNextKey (Dbm FileName)
FileName is the name of the DBM file.
Returns:
A string containing the next key if successful, or an empty string if the operation fails or there are no more keys. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


134 - BMC FootPrints Asset Core - Chilli Reference

Comments:
The first key is provided by a call to the DbmFirstKey function.
Example:
The following example prints all keys and values from a dbm file.
proc main ()

dbm ptrDbm
string szKey

// Open the database file


ptrDbm = DbmOpenFile ("my_dbm")

// Get first key


szKey = DbmFirstKey (ptrDbm)
while (szKey != "")
// Print key and value
print ("key :" + szKey + " value:" + DbmFetchValue (ptrDbm, szKey) + "\n")
// Get next key
szKey = DbmNextKey (ptrDbm)
endwhile

// Close the database file


DbmCloseFile (ptrDbm)

endproc

DbmOpenFile
Open a DBM file.
Syntax:
Dbm DbmOpenFile (String FileName)
FileName is the name of the DBM file to be opened.
Returns:
Returns a reference to the opened DBM file if the operation was successful, 0 if the function failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Example:
The following example prints all keys and values from a dbm file.
proc main ()

dbm ptrDbm
string szKey

// Open the database file


ptrDbm = DbmOpenFile ("my_dbm")

// Get first key


szKey = DbmFirstKey (ptrDbm)
while (szKey != "")
// Print key and value
print ("key :" + szKey + " value:" + DbmFetchValue (ptrDbm, szKey) + "\n")
// Get next key
szKey = DbmNextKey (ptrDbm)
endwhile

// Close the database file

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 13 - DBM Database Functions - 135

DbmCloseFile (ptrDbm)

endproc

DbmReplaceValue
Replace a key/value pair in an open DBM file.
Syntax:
Bool DbmInsertValue (Dbm FileName, String KeyName, String Value)
FileName is the name of the DBM file.
KeyName is the name of the key to be replaced.
Value is the value to be attributed to the new key.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
If the key does not yet exist it is created and attributed the specified value.
Example:
The following example inserts new keys, deletes a key and replaces another in a dbm file.
proc main ()
dbm ptrDbm
ptrDbm = DbmCreateFile ("my_dbm")
DbmInsertValue (ptrDbm, "my_first_key", "my_first_value")
DbmInsertValue (ptrDbm, "my_second_key", "my_second_value")
DbmDeleteValue (ptrDbm, "my_first_key")
DbmReplaceValue (ptrDbm, "my_second_key", "my_second_new_value")
DbmCloseFile (ptrDbm)
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


136 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Directory Functions

This chapter explains all directory functions of the Chilli language. The directory module is included in the Chilli
core and thus always accessible.

14.1 Introduction
Directories are special kinds of files which are used to organize other files into a hierarchical structure. Directories
contain bookkeeping information about files that are, figuratively speaking, beneath them. You can think of a
directory as a folder or cabinet that contains files and perhaps other folders. The directory function group in Chilli
allows you to create, modify, delete, search and manipulate directories within your system.

14.2 Functions
Following you find the list of all functions of the Directory function module:

Function OS Description
DirCreate Create a new empty directory

DirDelete Delete an empty directory

DirExists Check for existence of a directory

DirFind Check for existence of a directory

DirGetCurrent Get the full path of the current working directory

DirMove Move an existing directory

DirRename Rename an existing directory

DirSetCurrent Set the current working directory

DirCreate
Create a new empty directory.
Syntax:
Bool DirCreate (String DirectoryName)
DirectoryName is the relative or absolute path of the directory to be created.
Returns:
TRUE if the create operation was successful, FALSE if part of the path does not exist or the operation failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


138 - BMC FootPrints Asset Core - Chilli Reference

Comments:
If the named directory exists already, the function returns TRUE, indicating a successful operation.
Example:
This following example creates a directory, moves it to another location and then renames it.
proc main ()

string stringDir
stringDir = "C:\\temp\\testdir"

if (DirFind (stringDir) == FALSE)


DirCreate (stringDir)
DirMove (stringDir, "C:\\temp\\newtestdir")
else
DirRename (stringDir, "C:\\temp\\newtestdir")
endif

DirDelete ("C:\\temp\\newtestdir")

endproc

DirDelete
Delete an empty directory. It has the following two signatures:
Syntax:
Bool DirDelete (String DirectoryName)
Bool DirDelete (String DirectoryName, Bool ForceDelete)
DirectoryName is the relative or absolute path of the directory to be deleted.
ForceDelete indicates if the directory is to be deleted if the ReadOnly flag is set. By default this option is set
to false.
Returns:
TRUE if the delete operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The named directory must be empty for the operation to succeed. If the directory does not exist, the function
returns TRUE to indicate success.
Example:
This following example creates a directory, moves it to another location, renames and then deletes it.
proc main ()

string stringDir
stringDir = "C:\\temp\\testdir"

if (DirFind (stringDir) == FALSE)


DirCreate (stringDir)
DirMove (stringDir, "C:\\temp\\newtestdir")
endif

DirDelete ("C:\\temp\\newtestdir")

endproc

DirExists
Check to see if a directory exists.
Syntax:
Bool DirFind (String DirectoryName)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 14 - Directory Functions - 139

DirectoryName is the relative or absolute path of the directory to be checked.


Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
If the path exists but is a file the return value is FALSE. The function DirExists is an alias for DirFind and is
identical in operation.
Example:
This following example checks if a directory exists already and then creates it, moves it to another location,
renames and then deletes it.
proc main ()

string stringDir
stringDir = "C:\\temp\\testdir"

if (DirExists (stringDir) == FALSE)


DirCreate (stringDir)
DirMove (stringDir, "C:\\temp\\newtestdir")
endif

DirDelete ("C:\\temp\\newtestdir")

endproc

DirFind
Check to see if a directory exists.
Syntax:
Bool DirFind (String DirectoryName)
DirectoryName is the relative or absolute path of the directory to be found.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
If the path exists but is a file the return value is FALSE. The function DirExists is an alias for DirFind and is
identical in operation.
Example:
This following example checks if a directory exists already and then creates it, moves it to another location,
renames and then deletes it.
proc main ()

string stringDir
stringDir = "C:\\temp\\testdir"

if (DirExists (stringDir) == FALSE)


DirCreate (stringDir)
DirMove (stringDir, "C:\\temp\\newtestdir")
endif

DirDelete ("C:\\temp\\newtestdir")

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


140 - BMC FootPrints Asset Core - Chilli Reference

DirGetCurrent
Get the path of the current working directory.
Syntax:
String DirGetCurrent ()
Returns:
The full path including the drive letter of the current working directory.
Comments:
The current working directory has a direct impact on all relative file names which are referenced relative to the
current working directory. To refer to files using a relative path, or just their names, set the current working
directory first.
Example:
The following code example is taken from the main rollout installation procedure for the BCM agent on Windows
NT. It tries to find where BMC Client Management is installed.
proc FindFPAC ()

string WWDir
int iWWFind

iWWFind = FileFind (DirGetCurrent () + '\mtxagent.exe')


if (iWWFind == 1)
WWDir = DirGetCurrent () + '\'
else
iWWFind = FileFind ('C:\Program Files\BMC Software\Client Management\mtxagent.exe')
endif

endproc

proc main ()
FindFPAC ()
endproc

DirMove
Move an existing directory.
Syntax:
Bool DirMove (String SrcDirName, String DstDirName)
SrcDirName is the relative or absolute path of the directory to be renamed.
DstDirName is the new relative or absolute path to give to the directory.
Returns:
TRUE if the rename operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
This function can only rename directories, but cannot move them in the same way as FileRename does with files.
The function DirMove is an alias for DirRename and is identical in operation.
Example:
This following example checks if a directory exists already and then creates it, moves it to another location,
renames and then deletes it.
proc main ()
string stringDir
stringDir = "C:\\temp\\testdir"
if (DirFind (stringDir) == FALSE)
DirCreate (stringDir)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 14 - Directory Functions - 141

DirMove (stringDir, "C:\\temp\\newtestdir")


else
DirRename (stringDir, "C:\\temp\\newtestdir")
endif
DirDelete ("C:\\temp\\newtestdir")
endproc

DirRename
Rename an existing directory.
Syntax:
Bool DirRename (String SrcDirName, String DstDirName)
SrcDirName is the relative or absolute path of the directory to be renamed.
DstDirName is the new relative or absolute path to give to the directory.
Returns:
TRUE if the rename operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The function DirRename is an alias for DirMove and is identical in operation.
Example:
This following example checks if a directory exists already and then creates it, moves it to another location,
renames and then deletes it.
proc main ()
string stringDir
stringDir = "C:\\temp\\testdir"
if (DirFind (stringDir) == FALSE)
DirCreate (stringDir)
DirMove (stringDir, "C:\\temp\\newtestdir")
else
DirRename (stringDir, "C:\\temp\\newtestdir")
endif
DirDelete ("C:\\temp\\newtestdir")
endproc

DirSetCurrent
Set the current working directory.
Syntax:
Bool DirSetCurrent (String DirName)
DirName is the absolute path of the directory which is to become the current working directory.
Returns:
TRUE if the operation was successful, FALSE if the operation failed or the specified path does not exist.
Comments:
The current working directory has a direct impact on all relative file names which are referenced relative to the
current working directory. To refer to files using a relative path, or just their names, set the current working
directory first.
Example:
This following example is taken from the main rollout installation procedure for the BCM agent on Windows NT.
proc main ()

string RC, CPDir


CPDir = "C:\\Program Files\BMC Software\Client Management"

Numara Software, Inc. and BMC Software, Inc. Confidential.


142 - BMC FootPrints Asset Core - Chilli Reference

if (RC == "Yes")
RunProgram (CPDir + '\mtxagent.exe', 0)
Wait (45)
DirSetCurrent (CPDir + '\rp\')
RunProgram (CPDir + '\rp\rp32nt.exe', 0)
Wait (6)
Exit (ERR_NOERR)
endif

endproc

14.3 Example
The following script sets the current directory and creates a new one.
proc DirFunctions ()
string stringDir, stringCurDir, stringWinDir
stringCurDir = DirGetCurrent ()
stringWinDir = GetWinDir ()
if (stringCurDir != stringWinDir)
DirSetCurrent (stringWinDir)
endif
stringDir = "C:\\temp\\testdir"
if (DirFind (stringDir) == FALSE)
DirCreate (stringDir)
DirMove (stringDir, "C:\\temp\\newtestdir")
else
DirRename (stringDir, "C:\\temp\\newtestdir")
endif
DirDelete ("C:\\temp\\newtestdir")
endproc

proc main ()
DirFunctions ()
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Disk Functions

This chapter explains all disk functions of the Chilli script language. All functions of this module are included in
the disk.chx file for Windows or disk.so file for UNIX and Linux.
Some of these functions are not applicable to the UNIX environment.

15.1 Introduction
Disks are large data storage mediums on the machines in your system. The disk functions module of the Chilli
language enables you to query disks for information as well as add, redirect or unmount them.

15.2 Functions
Following you find the list of all functions of the Disk function module:

Function OS Description
DiskExists Check for existence of a disk drive

DiskFind Check for existence of a disk drive

DiskGetFree Get the amount of free space on a disk

DiskGetFreeKb Get the amount of free space on a disk in KB

DiskGetLabel Return the volume label of a drive on the system

DiskGetMask Retrieve a bitmask representing the currently available disk drives

DiskGetSerialNumber Return the volume serial number of a drive on the system

DiskGetTotal Get the total capacity of a disk drive

DiskGetTotalKb Get the total capacity of a disk drive in KB

DiskGetType Determine whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network
drive
DiskNetAdd Mount a redirected network drive

DiskNetAddEx Redirect a drive letter to a network drive

DiskNetAddEx2 Mount a network drive for a specific user

DiskNetDelete Unmount a redirected network drive

DiskExists
Check to see if a disk letter exists and is mapped to a valid drive.

Numara Software, Inc. and BMC Software, Inc. Confidential.


144 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
Bool DiskExists (String DrivePath)
DrivePath is the drive letter to check for validity.
Returns:
TRUE if the named disk drive exists, FALSE if the drive letter is not valid. If the supplied string is not exactly 1
character in length or if the supplied character is not a letter, 0 is returned and ErrCode is set to
ERR_INVALIDPARAM.
Comments:
The disk letter supplied can be in lower or upper case. The function DiskExists is an alias for DirFind and is
identical in operation.
The drive letter does not have to map to a physical device for it to be 'found'. It can also be a redirected network
drive. The supplied drivepath can be any path on the required drive as long as the first character is the correct
drive letter.

DiskFind
Check to see if a disk letter exists and is mapped to a valid drive.
Syntax:
Bool DiskFind (String DrivePath)
DrivePath is the drive letter to check for validity.
Returns:
TRUE if the named disk drive exists, FALSE if the drive letter is not valid. If the supplied string is not exactly 1
character in length or if the supplied character is not a letter, 0 is returned and ErrCode is set to
ERR_INVALIDPARAM.
Comments:
The disk letter supplied can be in lower or upper case. The function DiskExists is an alias for DirFind and is
identical in operation.
The drive letter does not have to map to a physical device for it to be 'found'. It can also be a redirected network
drive. The supplied drivepath can be any path on the required drive as long as the first character is the correct
drive letter.

DiskGetFree
Return the amount of free space on a disk, measured in bytes.
Syntax:
Int DiskGetFree (String DrivePath)
DrivePath is the drive letter to get the amount of free space for.
Returns:
The number of bytes of available space left on the disk, 0 if the drive letter is not valid. If the supplied string is not
exactly 1 character in length or if the supplied character is not a letter, 0 is returned and ErrCode is set to
ERR_INVALIDPARAM.
Comments:
The disk letter supplied can be in lower or upper case.
Example:
The following code example is taken from the BCM agent installation script for installation on NT. It checks the
pre-requisite conditions of the install and terminates the installation if the conditions are not fulfilled.
proc CheckPreRequisites ()
string DriveLetter, WWDir
WWDir = "C:\Programm Files\BMC Software\Client Management"

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 15 - Disk Functions - 145

string DriveLetter
DriveLetter = PathGetDrive (WWDir)
iFreeDisk = DiskGetFree (DriveLetter) / (1024 * 1024)
Print (LogFile, "Free space on drive " + DriveLetter + " =
" + MakeStr (iFreeDisk, “%d”) + "MB\r\n")
endproc

proc main ()
CheckPreRequisites ()
endproc

DiskGetFreeKb
Return the amount of free space on a disk, measured in kilobytes.
Syntax:
Int DiskGetFreeKb (String DrivePath)
DrivePath is the drive letter to get the amount of free space for.
Returns:
The number of kilobytes (KB) of available space left on the disk, 0 if the drive letter is not valid. If the supplied
string is not exactly 1 character in length or if the supplied character is not a letter, 0 is returned and ErrCode is set
to ERR_INVALIDPARAM.
Comments:
The disk letter supplied can be in lower or upper case.
Example:
The following example checks for and prints the free space on disk C in bytes and KB.
proc main ()

int FreeDisk, FreeDiskKB


string stringDisk
stringDisk = "C"
if (DiskFind (stringDisk) == TRUE)
FreeDisk = DiskGetFree (stringDisk)
FreeDiskKB = DiskGetFreeKb (stringDisk)
Print (LogFile, "Free Disk space in bytes = " + MakeStr (FreeDisk) + "\r\n")
Print (LogFile, "Free Disk space in KB = " + MakeStr (FreeDiskKB) + "\r\n")
endif

endproc

DiskGetLabel
Return the volume label of a drive on the system.
Syntax:
String DiskGetLabel (String DrivePath)
DrivePath is the drive letter.
Returns:
The volume label of the drive if the operation was successful or an empty string if an error occurs, if the label has
not been set or the function failed.
Comments:
The supplied drivepath can be any path on the required drive as long as the first character is the correct drive
letter.

Numara Software, Inc. and BMC Software, Inc. Confidential.


146 - BMC FootPrints Asset Core - Chilli Reference

DiskGetMask
Retrieve a bitmask representing the currently available disk drives.
Syntax:
Int DiskGetMask ()
Returns:
A a bitmask representing the currently available disk drives if the operation was successful. If the function fails,
the return value is 0.
Comments:
The return value is a bitmask representing the currently available disk drives. Bit position 0 (the least-significant
bit) is drive A, bit position 1 is drive B, bit position 2 is drive C, and so on.

DiskGetSerialNumber
Return the volume serial number of a drive on the system.
Syntax:
Int DiskGetSerialNumber (string DrivePath)
DrivePath is the drive letter.
Returns:
The volume serial number of the drive if the operation was successful or 0 if an error occurs or the function failed.
Comments:
The supplied drivepath can be any path on the required drive as long as the first character is the correct drive
letter.

DiskGetTotal
Get the total capacity (used + available) of a disk, measured in bytes.
Syntax:
Int DiskGetTotal (String DrivePath)
DrivePath is the drive letter to get the total amount of space for.
Returns:
The total capacity of the disk, 0 if the drive letter is not valid. If the supplied string is not exactly 1 character in
length or if the supplied character is not a letter, 0 is returned and ErrCode is set to ERR_INVALIDPARAM.
Comments:
The disk letter supplied can be in lower or upper case.
Example:
The following example checks for and prints the total space of disk C in bytes.
proc main ()

int TotalDisk
string stringDisk
stringDisk = "C"

if (DiskFind (stringDisk) == TRUE)


TotalDisk = DiskGetTotal (stringDisk)
Print (LogFile, "Total Disk space in bytes = " + MakeStr (TotalDisk) + "\r\n")
endif

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 15 - Disk Functions - 147

DiskGetTotalKb
Get the total capacity (used + available) of a disk, measured in kilobytes.
Syntax:
Int DiskGetTotalKb (String DrivePath)
DrivePath is the drive letter to get the total amount of space for.
Returns:
The total capacity of the disk in kilobytes (KB), 0 if the drive letter is not valid. If the supplied string is not exactly
1 character in length or if the supplied character is not a letter, 0 is returned and ErrCode is set to
ERR_INVALIDPARAM.
Comments:
The disk letter supplied can be in lower or upper case.
Example:
The following example checks for and prints the total space of disk C in KB.
proc main ()

int TotalDiskKB
string stringDisk
stringDisk = "C"

if (DiskFind (stringDisk) == TRUE)


TotalDiskKB = DiskGetTotalKb (stringDisk)
Print (LogFile, "Total Disk space in KB = " + MakeStr (TotalDiskKB) + "\r\n")
endif

endproc

DiskGetType
Determine whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive.
Syntax:
Int DiskGetType (string DrivePath)
DrivePath is the drive letter.
Returns:
One of the predefined constants to indicate the drive type if the operation was successful or 0 if the function
failed.
Comments:
The supplied drivepath can be any path on the required drive as long as the first character is the correct drive
letter. The possible return values and their meanings are:

DISK_UNKNOWN The drive type cannot be determined.


DISK_NOROOTDIR The root path is invalid. For example, no volume is mounted at the path.
DISK_REMOVABLE The disk can be removed from the drive.
DISK_FIXED The disk cannot be removed from the drive.
DISK_REMOTE The drive is a remote (network) drive.
DISK_CDROM The drive is a CD-ROM drive.
DISK_RAMDISK The drive is a RAM disk.

DiskNetAdd
Redirect a drive letter to a network drive using the standard Windows networking software.

Numara Software, Inc. and BMC Software, Inc. Confidential.


148 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
Bool DiskNetAdd (String DrivePath, String Server, String Directory, String Password)
DrivePath is the drive letter to redirect. This must not be allocated already. It can be any path on the
required drive as long as the first character is the correct drive letter.
Server is the network name of the server which provides the redirected network resource.
Directory is the path of the directory (sometimes called share) on the server which is available to this host
for redirection.
Password is the login password of the current system user needed to access the resources on the machine
identified in Server.
Returns:
TRUE if the redirection is established successfully, FALSE if an error occurred. If the supplied string for the drive
letter is not exactly 1 character in length or if the supplied character is not a letter, 0 is returned and ErrCode is set
to ERR_INVALIDPARAM.
Comments:
This function uses the standard Windows networking features to attempt a redirection. It does not implement any
redirection functionality (such as NFS) itself and therefore fails if no suitable networking software has been
installed. The disk letter supplied can be in lower or upper case.
Example:
The following example checks if a drive is already mounted and then mounts it.
proc main ()

int mount
string driveletter, Server, ServerPath, Name, Password
driveletter = "H"
Server = "ftp.enterprise.com"
ServerPath = "/pub/sw/updates/agent/auto/"
Name = "anonymous"
Password = "passwd"

if (GetSysInfo (SYSINFO_WIN32))
mount = DiskNetAddEx (driveletter, Server, ServerPath, Name, Password)
if (mount == 0)
mount = DiskNetAdd (driveletter, Server, ServerPath, Password)
endif
else
mount = DiskNetAdd (driveletter, Server, ServerPath, Password)
endif

endproc

DiskNetAddEx
Redirect a drive letter to a network drive using the standard Windows networking software.
Syntax:
Bool DiskNetAddEx (String DrivePath, String Server, String Directory, String Username,
String Password)
DrivePath is the drive letter to redirect. This must not be allocated already. It can be any path on the
required drive as long as the first character is the correct drive letter.
Server is the network name of the server which provides the redirected network resource.
Directory is the path of the directory (sometimes called share) on the server which is available to this host
for redirection.
Username is a login name which is accepted by the server for access to the directory/share in Directory.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 15 - Disk Functions - 149

Password is the login password of the user name needed to access the resources on the machine identified
in Server.
Returns:
TRUE if the redirection is established successfully, FALSE if an error occurred. If the supplied string for the drive
letter is not exactly 1 character in length or if the supplied character is not a letter, 0 is returned and ErrCode is set
to ERR_INVALIDPARAM.
Comments:
This function only works on 32-bit Windows systems and uses the standard Windows networking features to try
and attempt a redirection. It does not implement any redirection functionality (such as NFS) itself and so fails if
no suitable networking software has been installed. The disk letter supplied can be in lower or upper case.
Example:
The following example checks if a drive is already mounted and then mounts it.
proc main ()

int mount
string driveletter, Server, ServerPath, Name, Password
driveletter = "H"
Server = "ftp.enterprise.com"
ServerPath = "/pub/sw/updates/agent/auto/"
Name = "anonymous"
Password = "passwd"

if (GetSysInfo (SYSINFO_WIN32))
mount = DiskNetAddEx (driveletter, Server, ServerPath, Name, Password)
if (mount == 0)
mount = DiskNetAdd (driveletter, Server, ServerPath, Password)
endif
else
mount = DiskNetAdd (driveletter, Server, ServerPath, Password)
endif

endproc

DiskNetAddEx2
Mount a network drive for a specific user.
Syntax:
Bool DiskNetAddEx2 (String DrivePath, String Server, String Directory, String Username,
String Password, Bool Persistant)
DrivePath is the drive letter to redirect. This must not be allocated already. The path can be any path on the
required drive as long as the first character is the correct drive letter. The disk letter supplied can be in
lower or upper case.
Server is the network name of the server which provides the redirected network resource.
Directory is the path of the directory (sometimes called share) on the server which is available to this host
for redirection.
Username is a login name which is accepted by the server for access to the directory/share in Directory.
Password is the login password of the user name needed to access the resources on the machine identified
in Server.
Persistent specifies if the path is the be mounted at every logon of the specified user.
Returns:
TRUE if the network drive is successfully mounted, FALSE if an error occurred.

Numara Software, Inc. and BMC Software, Inc. Confidential.


150 - BMC FootPrints Asset Core - Chilli Reference

Comments:
This function only works on 32-bit Windows systems (95 or NT) and uses the standard Windows networking
features to try and attempt a redirection. It does not implement any redirection functionality (such as NFS) itself
and so fails if no suitable networking software has been installed.
Example:
proc main ()

int mount
string driveletter, Server, ServerPath, Name, Password
bool percistent

driveletter = "H"
Server = "ftp.enterprise.com"
ServerPath = "/pub/sw/updates/agent/auto/"
Name = "anonymous"
Password = "passwd"
percistent = TRUE

mount = DiskNetAddEx2 (driveletter, Server, ServerPath, Name, Password, percistent)

endproc

DiskNetDelete
Cancel a network redirected drive.
Syntax:
Bool DiskNetDelete (String DrivePath)
DrivePath is the drive letter to cancel the redirection on.
Returns:
TRUE if the redirection is canceled successfully, FALSE if an error occurred. If the supplied string for the drive
letter is not exactly 1 character in length or if the supplied character is not a letter, 0 is returned and ErrCode is set
to ERR_INVALIDPARAM. If the supplied drive letter is not a redirected drive, 0 is returned and ErrCode is set to
ERR_FUNCFAILED.
Comments:
This function uses the standard Windows networking features to try canceling a redirected drive. The disk letter
supplied can be in lower or upper case.
Example:
The following example deletes a mounted drive.
proc main ()

int mount
string driveletter, Server, ServerPath, Name, Password
driveletter = "H"
Server = "ftp.enterprise.com"
ServerPath = "/pub/sw/updates/agent/auto/"
Name = "anonymous"
Password = "passwd"
mount = DiskNetAdd (driveletter, Server, ServerPath, Name Password)

if (mount != 0)
DiskNetDelete (driveletter)
endif
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 15 - Disk Functions - 151

15.3 Example
The following example illustrates the usage of the disk functions:
proc DiskFunctions ()
int FreeDisk, FreeDiskKB, TotalDisk, TotalDiskKB
string stringDisk
int mount
string driveletter, Server, ServerPath, Name, Password
stringDisk = "C"
if (DiskFind (stringDisk) == TRUE)
FreeDisk = DiskGetFree (stringDisk)
FreeDiskKB = DiskGetFreeKb (stringDisk)
TotalDisk = DiskGetTotal (stringDisk)
TotalDiskKB = DiskGetTotalKb (stringDisk)
Print (LogFile, "Free Disk space in bytes = " + MakeStr (FreeDisk) + "\r\n")
Print (LogFile, "Free Disk space in KB = " + MakeStr (FreeDiskKB) + "\r\n")
Print (LogFile, "Total Disk space in bytes = " + MakeStr (TotalDisk) + "\r\n")
Print (LogFile, "Total Disk space in KB = " + MakeStr (TotalDiskKB) + "\r\n")
endif

;Try and mount the remote drive


driveletter = "H"
Server = "ftp.enterprise.com"
ServerPath = "/pub/sw/updates/agent/auto/"
Name = "anonymous"
Password = "passwd"
if (GetSysInfo (SYSINFO_WIN32))
mount = DiskNetAddEx (driveletter, Server, ServerPath, Name, Password)
if (mount == 0)
mount = DiskNetAdd (driveletter, Server, ServerPath, Password)
endif
else
mount = DiskNetAdd (driveletter, Server, ServerPath, Password)
endif
if (mount != 0)
DiskNetDelete (driveletter)
endif
endproc

proc main ()
DiskFunctions ()
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


152 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Event Log Functions

This chapter explains all Windows NT event log functions of the Chilli Functions Library. These functions are
only supported on the Windows NT/2000/XP versions, on the other versions (Windows 95/98) they compiles but
return an FUNCNOTSUPP (function not supported) error to indicate failure.
All functions of this module are included in the ntevent.chx file. This group of functions is not applicable to
the UNIX environment.

16.1 Introduction
An event is an action or occurrence detected by a program. Events can be user actions, such as clicking a mouse
button or pressing a key, or system occurrences, such as running out of memory. Event logging in Microsoft
Windows provides a standard, centralized way for you to have your applications record important software and
hardware events in the Event Log. The Event Log Functions of the Chilli language allow you to view, filter and
examine these logged events outside of the standard Windows Event Log tool.

16.2 Predefined Constants


Following you find the complete list of all predefined constants of the Windows NT/2000/XP Event Log functions
group of the Chilli script language:

Name Type Description


EVENT_AUDITFAILURE Integer Failure Audit event
EVENT_AUDITSUCCESS Integer Success Audit event
EVENT_ERROR Integer Error event
EVENT_INFORMATION Integer Information event
EVENT_WARNING Integer Warning event
EVENTFILE_APPLICATION Integer The Application event file.
EVENTFILE_SECURITY Integer The Security event file.
EVENTFILE_SYSTEM Integer The System event file.

The value for the log file index identifying one of the standard Windows NT Event Log files should be one of the
following predefined constants:

Value Constant
1 EVENTFILE_APPLICATION
2 EVENTFILE_SECURITY
3 EVENTFILE_SYSTEM

Numara Software, Inc. and BMC Software, Inc. Confidential.


154 - BMC FootPrints Asset Core - Chilli Reference

16.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli NT Event Log function group has predefined data types of type
structure.

16.3.1 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated.
Following you find a list of all predefined data types of type structure:

Data Type Description


EventInfo A structure containing all available information for the event

EventInfo
The EventInfo structure contains all information which is available for a specific event in the Windows NT
Event Log.
Elements:
Elements Element Type Description
Id Integer The Id of the event in the event log.
Type Integer The type classification of the event severity. The type can be Error, Information or
Warning in the system and application logs; Audit Success or Audit Failure in the
secutity log.
Category Integer The classification of the event by the event source; used primarily in the security
log.
Timestamp Integer The timestamp of the event.
User String The name of the user on whose behalf the event occurred.This name can be the
client ID if the event was caused by a server process. It can be the primary ID if
impersonization is taking place.
Source String The software that logged the event, which can be either an application name or a
component of the system or of a large application.
Description String The textual description and any available binary data for the event. This
information is generated by the application that was the source of the event
record.
Computer String The name of the computer the event occurred on.

16.4 Functions
Following you find the list of all functions of the Windows NT/2000 Event Log function module:

Function OS Description
EventGetCategory Get the category for an event

EventGetComputer Get the name of the computer from which the event originated

EventGetCount Get the number of events in an event log file

EventGetDay Get the day part of the timestamp for an event

EventGetDescription Get the descriptive text for an event in a log file

EventGetFileName Get the name of an event log file given its index

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 16 - Event Log Functions - 155

Function OS Description
EventGetFilePath Get the full path of an event log file given its index

EventGetHour Get the hour part of the timestamp for an event

EventGetInfo Get all available information for an event in an event log file

EventGetId Get the event ID for an event in a log file

EventGetMaxSize Get the maximum allowable size for an event log file

EventGetMinute Get the minutes part of the timestamp for an event

EventGetMonth Get the month part of the timestamp for an event

EventGetOldest Get the index of the oldest event entry in a log file

EventGetSecond Get the seconds part of the timestamp for an event

EventGetSource Get the name of the source for an event entry

EventGetTimestamp Get the timestamp for an event in an event log file

EventGetType Get the type identifier for an event entry

EventGetUser Get the login name of the user who was logged on when an event was generated

EventGetYear Get the year part of the timestamp for an event

EventGetCategory
Get the category value for an event.
Syntax:
Int EventGetCategory (Int FileNumber, Int EventIndex)
FileNumber is the index of the event log file to be read.
EventIndex is the index of the event entry in the log file.
Returns:
If the indexed entry can be found in the event log, the function returns the category value for that event.
Otherwise the function returns 0 and ErrCode is set to ERR_FUNCFAILED.
Comments:
The category value is an application specific value, the meaning of which is defined by the application which
generated the event.
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This example script prints the event category as well as the computer from which it originated.
proc main ()

string computer
int categ

computer = EventGetComputer (1, 1)


categ = EventGetCategory (1, 1)
Print ("Event category = " + MakeStr (categ) + "\r\n")
Print ("Event computer = " + computer + "\r\n")

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


156 - BMC FootPrints Asset Core - Chilli Reference

EventGetComputer
Get the name of the computer from which the event originated.
Syntax:
String EventGetComputer (Int FileNumber, Int EventIndex)
FileNumber is the index of the event log file to be read.
EventIndex is the index of the event entry in the log file.
Returns:
If the indexed entry can be found in the event log, the function returns the name of the computer from which the
event originated. Otherwise the function returns an empty string and ErrCode is set to ERR_FUNCFAILED.
Comments:
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This example script prints the event category as well as the computer from which it originated.
proc main ()

string computer
int categ

computer = EventGetComputer (1, 1)


categ = EventGetCategory (1, 1)
Print ("Event category = " + MakeStr (categ) + "\r\n")
Print ("Event computer = " + computer + "\r\n")

endproc

EventGetCount
Get the number of events in an event log file.
Syntax:
Int EventGetCount (Int FileNumber)
FileNumber is the index of the event log file to be read.
Returns:
If the indexed log file can be found, the function returns the number of events in that file. Otherwise the function
returns 0 and ErrCode is set to ERR_FUNCFAILED.
Comments:
The events in a file are indexed by an internal number which does not have any relationship to the position of the
event in the file. For example if there are 1000 entries in a log file and the oldest event is number 500, to access
the first (oldest) entry, the event index should be 500. The latest (newest) entry is at index 1499.
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This example script counts the number of events in the Application event log file.
proc main ()

string path
int count

path = ’c:\temp\logfiles\’
count = EventGetCount (1)
Print (LogFile, "Event file path = " + path + "\r\n")

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 16 - Event Log Functions - 157

EventGetDay
Get the day part of the timestamp for an event.
Syntax:
Int EventGetDay (Int FileNumber, Int EventIndex)
FileNumber is the index of the event log file to be read.
EventIndex is the index of the event entry in the log file.
Returns:
If the indexed entry can be found in the event log, the function returns the day value for the timestamp of that
event. Otherwise the function returns 0 and ErrCode is set to ERR_FUNCFAILED.
Comments:
This time is measured as the number of seconds elapsed since 00:00:00 January 1, 1970, local time.
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This sample script prints the date of an event if the event exists.
proc main ()

int count, year, month, day, index


count = EventGetCount (1)

if (count != 0)
year = EventGetYear (1, index)
month = EventGetMonth (1, index)
day = EventGetDay (1, index)
Print (LogFile, "Date: " + MakeStr (year) + '/' + MakeStr (month) + '/'
+ MakeStr (day))
endif

endproc

EventGetDescription
Get the descriptive text for an event in a log file.
Syntax:
String EventGetDescription (Int FileNumber, Int EventIndex)
FileNumber is the index of the event log file to be read.
EventIndex is the index of the event entry in the log file.
Returns:
If the indexed entry can be found in the event log, the function returns the descriptive text which accompanies
the event. This is the same text as is displayed in the Windows NT Event Viewer application. If the function fails,
it returns an empty string and ErrCode is set to ERR_FUNCFAILED.
Comments:
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This sample script prints the source and the description of the oldest event in the Application event log file.
proc main ()

string Src, Desc


int index

index = EventGetOldest (1)


Src = EventGetSource (1, index)
Desc = EventGetDescription (1, index)

Numara Software, Inc. and BMC Software, Inc. Confidential.


158 - BMC FootPrints Asset Core - Chilli Reference

Print ("Event source = " + Src + "\r\n")


Print ("Event description = " + Desc + "\r\n")

endproc

EventGetFileName
Get the name of an event log file given its index.
Syntax:
String EventGetFileName (Int FileNumber)
FileNumber is the index of the event log file to be read.
Returns:
If successful, the function returns the name of the event log represented by the index. This is typically the name
visible in the Windows NT Event Viewer application. If the function fails, it returns an empty string and ErrCode
is set to ERR_FUNCFAILED.
Comments:
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This example script prints the file name, the file path and the maximum allowable size for the first event log file.
proc main ()

string file, path


int size

file = EventGetFileName (1)


path = EventGetFilePath (1)
size = EventGetMaxSize (1)

Print (LogFile, "Event file = " + file + "\r\n")


Print (LogFile, "Event file path = " + path + "\r\n")
Print (LogFile, "Event max size = " + MakeStr (size) + " KB\r\n")

endproc

EventGetFilePath
Get the full path of an event log file given its index.
Syntax:
String EventGetFilePath (Int FileNumber)
FileNumber is the index of the event log file to be read.
Returns:
If successful, the function returns the full path of the file in which the event log is stored. Otherwise the function
returns an empty string and ErrCode is set to ERR_FUNCFAILED.
Comments:
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This example script prints the file name, the file path and the maximum allowable size for the first event log file.
proc main ()

string file, path


int size

file = EventGetFileName (1)


path = EventGetFilePath (1)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 16 - Event Log Functions - 159

size = EventGetMaxSize (1)

Print (LogFile, "Event file = " + file + "\r\n")


Print (LogFile, "Event file path = " + path + "\r\n")
Print (LogFile, "Event max size = " + MakeStr (size) + " KB\r\n")

endproc

EventGetHour
Get the hour part of the timestamp for an event.
Syntax:
Int EventGetHour (Int FileNumber, Int EventIndex)
FileNumber is the index of the event log file to be read.
EventIndex is the index of the event entry in the log file.
Returns:
If the indexed entry can be found in the event log, the function returns the hours value for the timestamp of that
event. Otherwise the function returns 0 and ErrCode is set to ERR_FUNCFAILED.
Comments:
This time is measured as the number of seconds elapsed since 00:00:00 January 1, 1970, local time.
The log file index is an integer identifying one of the standard Windows NT Event Log files. The value for the
index should be one of the following pre-defined constants:

Value Constant
1 EVENTFILE_APPLICATION
2 EVENTFILE_SECURITY
3 EVENTFILE_SYSTEM

Example:
This sample script prints the time of an event if the event exists.
proc main ()

int count, hour, minute, second, index


count = EventGetCount (1)

if (count != 0)
hour = EventGetHour (1, index)
minute = EventGetMinute (1, index)
second = EventGetSecond (1, index)
Print (logFile, " at " + MakeStr (hour) + ':' + MakeStr (minute) + ':'
+ MakeStr (second) + "\r\n")
endif

endproc

EventGetId
Get the event ID for an event in a log file.
Syntax:
Int EventGetId (Int FileNumber, Int EventIndex)
FileNumber is the index of the event log file to be read.
EventIndex is the index of the event entry in the log file.

Numara Software, Inc. and BMC Software, Inc. Confidential.


160 - BMC FootPrints Asset Core - Chilli Reference

Returns:
If the indexed entry can be found in the event log, the function returns the event ID for that event. Otherwise the
function returns 0 and ErrCode is set to ERR_FUNCFAILED.
Comments:
The event ID value is an application specific value, the meaning of which is defined by the application which
generated the event.
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This example prints the event ID, the type of the event and the login name of the user who was logged on when
the event was generated.
proc main ()

int ID, Type, index


string User

index = EventGetOldest (1)


ID = EventGetId (1, index)
Type = EventGetType (1, index)
User = EventGetUser (1, index)
Print ("Event ID = " + MakeStr (ID) + "\r\n")
Print ("Event type = " + MakeStr (Type) + "\r\n")
Print ("Event user = " + User + "\r\n")

endproc

EventGetInfo
Get all available information for an event in an event log file.
Syntax:
EventInfo EventGetInfo (Int FileNumber, Int EventIndex)
FileNumber is the index of the event log file to be read.
EventIndex is the index of the event entry in the log file.
Returns:
An EventInfo structure containing all available information for the event if the operation was successful. The
returned stucture is empty if an error occurs or the function failed. If the function fails ErrCode is set to
ERR_FUNCFAILED.

EventGetMaxSize
Get the maximum allowable size for an event log file, expressed in KBs.
Syntax:
Int EventGetMaxSize (Int FileNumber)
FileNumber is the index of the event log file to be read.
Returns:
If successful, the function returns the maximum allowable size for the event log file, expressed in KBs. Otherwise
the function returns 0 and ErrCode is set to ERR_FUNCFAILED.
Comments:
When the size of an event log file exceeds the maximum size, the oldest events in the file are purged in order to
make room for the new entries.
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This example script prints the file name, the file path and the maximum allowable size for the first event log file.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 16 - Event Log Functions - 161

proc main ()

string file, path


int size

file = EventGetFileName (1)


path = EventGetFilePath (1)
size = EventGetMaxSize (1)

Print (LogFile, "Event file = " + file + "\r\n")


Print (LogFile, "Event file path = " + path + "\r\n")
Print (LogFile, "Event max size = " + MakeStr (size) + " KB\r\n")

endproc

EventGetMinute
Get the minutes part of the timestamp for an event.
Syntax:
Int EventGetMinute (Int FileNumber, Int EventIndex)
FileNumber is the index of the event log file to be read.
EventIndex is the index of the event entry in the log file.
Returns:
If the indexed entry can be found in the event log, the function returns the minutes value for the timestamp of
that event. Otherwise the function returns 0 and ErrCode is set to ERR_FUNCFAILED.
Comments:
This time is measured as the number of seconds elapsed since 00:00:00 January 1, 1970, local time.
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This sample script prints the time of an event if the event exists.
proc main ()

int count, hour, minute, second, index


count = EventGetCount (1)

if (count != 0)
hour = EventGetHour (1, index)
minute = EventGetMinute (1, index)
second = EventGetSecond (1, index)
Print (logFile, " at " + MakeStr (hour) + ':' + MakeStr (minute) + ':'
+ MakeStr (second) + "\r\n")
endif

endproc

EventGetMonth
Get the month part of the timestamp for an event.
Syntax:
Int EventGetMonth (Int FileNumber, Int EventIndex)
FileNumber is the index of the event log file to be read.
EventIndex is the index of the event entry in the log file.
Returns:
If the indexed entry can be found in the event log, the function returns the month value for the timestamp of that
event. Otherwise the function returns 0 and ErrCode is set to ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


162 - BMC FootPrints Asset Core - Chilli Reference

Comments:
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This sample script prints the date of an event if the event exists.
proc main ()

int count, year, month, day, index


count = EventGetCount (1)

if (count != 0)
year = EventGetYear (1, index)
month = EventGetMonth (1, index)
day = EventGetDay (1, index)
Print (LogFile, "Date: " + MakeStr (year) + '/' + MakeStr (month) + '/'
+ MakeStr (day))
endif

endproc

EventGetOldest
Get the index of the oldest event entry in a log file.
Syntax:
Int EventGetOldest (Int FileNumber)
FileNumber is the index of the event log file to be read.
Returns:
If successful, the function returns the index of the oldest event in the log file. Otherwise the function returns 0
and ErrCode is set to ERR_FUNCFAILED.
Comments:
The events in a file are indexed by an internal number which does not have any relationship to the position of the
event in the file. For example if there are 1000 entries in a log file and the oldest event is number 500, to access
the first (oldest) entry, the event index should be 500. The latest (newest) entry is at index 1499.
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This sample script prints the source and the description of the oldest event in the Application event log file.
proc main ()

int index, count


count = EventGetCount (1)

if (count != 0)
index = EventGetOldest (1)
Print (LogFile, "Oldest event information:\r\n")
endif

endproc

EventGetSecond
Get the seconds part of the timestamp for an event.
Syntax:
Int EventGetSecond (Int FileNumber, Int EventIndex)
FileNumber is the index of the event log file to be read.
EventIndex is the index of the event entry in the log file.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 16 - Event Log Functions - 163

Returns:
If the indexed entry can be found in the event log, the function returns the seconds value for the timestamp of that
event. Otherwise the function returns 0 and ErrCode is set to ERR_FUNCFAILED.
Comments:
This time is measured as the number of seconds elapsed since 00:00:00 January 1, 1970, local time.
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This sample script prints the time of an event if the event exists.
proc main ()

int count, hour, minute, second, index


count = EventGetCount (1)

if (count != 0)
hour = EventGetHour (1, index)
minute = EventGetMinute (1, index)
second = EventGetSecond (1, index)
Print (logFile, " at " + MakeStr (hour) + ':' + MakeStr (minute) + ':'
+ MakeStr (second) + "\r\n")
endif

endproc

EventGetSource
Get the name of the source for an event entry.
Syntax:
String EventGetSource (Int FileNumber, Int EventIndex)
FileNumber is the index of the event log file to be read.
EventIndex is the index of the event entry in the log file.
Returns:
If the indexed entry can be found in the event log, the function returns the name of the source for the event,
typically the application name. If the function fails, it returns an empty string and ErrCode is set to
ERR_FUNCFAILED.
Comments:
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This sample script prints the source and the description of the oldest event in the Application event log file.
proc main ()

string Src, Desc


int index

index = EventGetOldest (1)


Src = EventGetSource (1, index)
Desc = EventGetDescription (1, index)
Print ("Event source = " + Src + "\r\n")
Print ("Event description = " + Desc + "\r\n")

endproc

EventGetTimestamp
Get the timestamp for an event in an event log file.

Numara Software, Inc. and BMC Software, Inc. Confidential.


164 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
Int EventGetTimestamp (Int FileNumber, Int EventIndex)
FileNumber is the index of the event log file to be read.
EventIndex is the index of the event entry in the log file.
Returns:
If successful, the function returns the timestamp for the specified event, or 0 if the function failed.
Comments:
The timestamp is measured as the number of seconds elapsed since 00:00:00 January 1, 1970, local time.
Example:
This example ...

EventGetType
Get the type identifier for an event entry.
Syntax:
Int EventGetType (Int FileNumber, Int EventIndex)
FileNumber is the index of the event log file to be read.
EventIndex is the index of the event entry in the log file.
Returns:
If successful, the function returns one of the following pre-defined constants:

Value Constant
1 EVENT_ERROR
2 EVENT_WARNING
4 EVENT_INFORMATION
8 EVENT_AUDITSUCCESS
16 EVENT_AUDITFAILURE

If the function fails, it returns 0 and ErrCode is set to ERR_FUNCFAILED.


Comments:
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This example prints the event ID, the type of the event and the login name of the user who was logged on when
the event was generated.
proc main ()

int ID, Type, index


string User

index = EventGetOldest (1)


ID = EventGetId (1, index)
Type = EventGetType (1, index)
User = EventGetUser (1, index)
Print ("Event ID = " + MakeStr (ID) + "\r\n")
Print ("Event type = " + MakeStr (Type) + "\r\n")
Print ("Event user = " + User + "\r\n")

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 16 - Event Log Functions - 165

EventGetUser
Get the login name of the user who was logged on when an event was generated.
Syntax:
String EventGetUser (Int FileNumber, Int EventIndex)
FileNumber is the index of the event log file to be read.
EventIndex is the index of the event entry in the log file.
Returns:
If the indexed entry can be found in the event log, the function returns the login name of the user who was logged
onto the machine when the event was generated. Otherwise the function returns an empty string and ErrCode is
set to ERR_FUNCFAILED.
Comments:
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This example prints the event ID, the type of the event and the login name of the user who was logged on when
the event was generated.
proc main ()

int ID, Type, index


string User

index = EventGetOldest (1)


ID = EventGetId (1, index)
Type = EventGetType (1, index)
User = EventGetUser (1, index)
Print ("Event ID = " + MakeStr (ID) + "\r\n")
Print ("Event type = " + MakeStr (Type) + "\r\n")
Print ("Event user = " + User + "\r\n")

endproc

EventGetYear
Get the years part of the timestamp for an event.
Syntax:
Int EventGetYear (Int FileNumber, Int EventIndex)
FileNumber is the index of the event log file to be read.
EventIndex is the index of the event entry in the log file.
Returns:
If the indexed entry can be found in the event log, the function returns the year value for the timestamp of that
event. Otherwise the function returns 0 and ErrCode is set to ERR_FUNCFAILED.
Comments:
This time is measured as the number of seconds elapsed since 00:00:00 January 1, 1970, local time.
For more information about the log file index refer to paragraph Predefined Constants on page 153 in this chapter.
Example:
This sample script prints the date of an event if the event exists.
proc main ()

int count, year, month, day, index


count = EventGetCount (1)

if (count != 0)
year = EventGetYear (1, index)

Numara Software, Inc. and BMC Software, Inc. Confidential.


166 - BMC FootPrints Asset Core - Chilli Reference

month = EventGetMonth (1, index)


day = EventGetDay (1, index)
Print (LogFile, "Date: " + MakeStr (year) + '/' + MakeStr (month) + '/'
+ MakeStr (day))
endif

endproc

16.5 Example
The following code sample illustrates the event log functions. It shows a procedure that collects all possible
information about the first event log file and its events, such as file name and path, event source and description.
proc NTEventLogFunctions ()

string file, path


int index, count, year, month, day, hour, minute, second
int ID, categ, Type, size
string User, Src, Desc, computer

file = EventGetFileName (1)


path = EventGetFilePath (1)
size = EventgetMaxSize (1)

Print (LogFile, "Event file = " + file + "\r\n")


Print (LogFile, "Event file path = " + path + "\r\n")
Print (LogFile, "Event max size = " + MakeStr (size) + " KB\r\n")

count = EventGetCount (1)


Print (LogFile, "Event file path = " + path + "\r\n")

if (count != 0)
index = EventGetOldest (1)
Print (LogFile, "Oldest event information:\r\n")
year = EventGetYear (1, index)
month = EventGetMonth (1, index)
day = EventGetDay (1, index)
hour = EventGetHour (1, index)
minute = EventGetMinute (1, index)
second = EventGetSecond (1, index)

Print (LogFile, "Date: " + MakeStr (year) + '/' + MakeStr (month) +


'/' + MakeStr (day))
Print (logFile, " at " + MakeStr (hour) + ':' + MakeStr (minute) +
':' + MakeStr (second) + "\r\n")

ID = EventGetId (1, index)


Type = EventGetType (1, index)
User = EventGetUser (1, index)
Src = EventGetSource (1, index)
Desc = EventGetDescription (1, index)
computer = EventGetComputer (1, index)
categ = EventGetCategory (1, index)

Print (LogFile, "Event ID = " + MakeStr (ID) + "\r\n")


Print (LogFile, "Event type = " + MakeStr (Type) + "\r\n")
Print (LogFile, "Event user = " + User + "\r\n")
Print (LogFile, "Event source = " + Src + "\r\n")
Print (LogFile, "Event description = " + Desc + "\r\n")
Print (LogFile, "Event category = " + MakeStr (categ) + "\r\n")
Print (LogFile, "Event computer = " + computer + "\r\n")

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 16 - Event Log Functions - 167

endif
endproc

proc main ()
NTEventLogFunctions ()
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


168 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


File Functions

This chapter explains all general file functions of the Chilli script language. The File module is included in the
Chilli core and thus always accessible.
Some of these functions are not applicable to the UNIX environment.

17.1 Introduction
The Chilli File functions allow you to manipulate files stored on the local machine as well as through the Internet.
You can not only create, move, delete or query files, but also modify any type of text file, such as .txt, or .inf
files.
The file function module is divided into the following subgroups:
• File Manipulation Functions
• File Attribute Functions
• Text File Editing Functions
• File Date Functions
Ini file specific functions are collected in their own function module, INI Format File Manipulation Functions on
page 251 further on in this manual.

17.2 Error Codes


Following you find a list of all file manipulation error codes. These errors are run-time errors that causes the
handler specified in ErrorHandler to be invoked. Functions can return these in addition to the standard runtime
errors such as FUNCFAILED. You will find a list with all runtime errors in Appendix E - Chilli Error Codes on
page 677 at the end of the manual.

Name Description
ERR_BADFORMAT Supplied URL is incorrectly formatted
ERR_BADPATH Server did not find path
ERR_BADPROTOCOL Supplied URL specifies unrecognized protocol
ERR_CONNECT Failed to connect to server
ERR_DELFILE Failed to delete file
ERR_FILECREATEFAIL Failed to create file
ERR_FILENOTFOUND File does not exist
ERR_FILENOTVALID File is not valid for operation (not text, archive, INI)
ERR_FILEREADFAIL Failed to open file for reading
ERR_FILEWRITEFAIL Failed to open file for writing
ERR_GETFILE Failed to read file from source
ERR_LOGIN Failed to logon to server using user name/password

Numara Software, Inc. and BMC Software, Inc. Confidential.


170 - BMC FootPrints Asset Core - Chilli Reference

Name Description
ERR_PASSWORD Server rejected user password
ERR_PUTFILE Failed to write file to destination
ERR_SHARENAME Server rejected share name

17.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli File Attribute function group has Predefined Handle Data Types.

17.3.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


FileFindInfo Object type: reference to the list of files found in a directory
TextFileHandle Object type: reference to the handle of text file

FileFindInfo
The FileFindInfo data type is a reference to the internal data structure, which keeps track of the list of files
found in the directories.
The function FileFindOpen returns a value of this object type, which is used by a number of other file
functions and should be closed by the FileFindClose function.
This handle data type is only applicable to the File Attribute functions subgroup.

TextFileHandle
The TextFileHandle data type is a handle to an open text file.
The function FileTextOpen returns a value of this object type that other functions that manipulate the file’s
contents expect as their first argument. Any open text file and thus the value of this object type should always be
closed by the FileTextClose function.
This handle data type is only applicable to the Text File Editing functions subgroup.

17.4 File Manipulation Functions


File manipulation in Chilli can be executed on files located on the same as well as on different disk systems.
Depending on the files’ location two different ways of accessing these files are provided by the respective
functions:
• If the files are located on the same disk system they can be accessed by specifying their full or relative path.
• If the files are non-local files and thus need to be accessed through the network, they must be specified via
URLs. The supported protocols for this mode of access are file, http, ftp and smb (Microsoft LAN Manager).
Due to the two different methods of accessing files, some of the functions of this group only operate on local
system paths and some can handle URLs.

17.4.1 Syntax for Accessing Files through URLs


URLs (Uniform Resource Locator) are used to find resources (files) on a network, typically the Internet, by
providing an abstract identification of the resource location.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 171

In general, URLs are written as follows:


<scheme>:<scheme-specific-part>
A URL contains the name of the scheme being used (<scheme>), such as ftp or http, followed by a colon and then
a string (the <scheme-specific-part>) whose interpretation depends on the scheme. For more information about
the general rules of forming URLs refer to the respective RFC documents, such as RFC 1738, 1034, 1123, and so
on. Below you find a summary compiled from these RFCs.

17.4.1.1 File Specific Scheme


In this case the term local file is employed to specify files which are located on the same system. The syntax when
specifying a local file is either the full or relative path of the respective file.
Syntax:
file://<driveletter>/<dir1>/<dir2>/.../<dirN>/<filename>
Driveletter is the letter of the local or mapped drive on which the file is located. This parameter is optional
if the path is a relative path.
Dir1 - DirN list the directory hierarchy to the file. These parameters are optional.
Filename specifies the name of the file to be accessed with its extension.
17.4.1.1.1 HTTP Specific Scheme
The HTTP URL scheme is used to designate Internet resources accessible using HTTP (HyperText Transfer
Protocol).
Syntax:
http://<host>:<port>/<path>?<searchpart>
Host specifies the fully qualified domain name of a network host, or its IP address as a set of four decimal
digit groups separated by "."
Port specifies the port number to connect to. Another port number can optionally be supplied, in decimal,
separated from the host by a colon. If the port is not specified, the port defaults to 80.
Path specifies the path to the file on the host machine. This part is optional. If it is not present, the / can
also be omitted.
Searchpart defines the query information. It is a string composed of parameter=value pairs separated by
ampersand (&) symbols. This part is optional. If it is not present, its preceding ? and /<path> can also be
omitted.
17.4.1.1.2 FTP Specific Scheme
The FTP URL scheme is used to designate files and directories on Internet hosts accessible using the FTP
protocol.
Syntax:
ftp://<user>:<password>@<host>:<port>/<dir1>/<dir2>/.../<dirN>/<filename>;type=<typecode>
User specifies an optional user name.
Password specifies an optional password to the user name. If present, it follows the user name separated
from it by a colon.
Be sure to escape the @ of the email address when accessing an outside server with the anonymous login,
e.g.:
Unsafe characters, such as &, @ or :, should generally be escaped through the general escape scheme: %
digit digit, for example, @ is escaped to %40, : is escaped to %09, and so on.
Also note that an empty user name or password is different than no user name or password; there is no way
to specify a password without specifying a user name.
Port defines the port number to connect to. The default port is 21.
Dir1 - DirN list the directory hierarchy on the server to the file. These parameters are optional.
Filename specifies the name of the file to be accessed with its extension.
Typecode defines the mode of transfer for the file depending on the data content type of the file. Valid
values are the characters a, i or d. This parameter (;type=<typecode>) is optional.

Numara Software, Inc. and BMC Software, Inc. Confidential.


172 - BMC FootPrints Asset Core - Chilli Reference

Example 1:
Example for a password login.
ftp://myname:hello@lenny/lucky.gif
Example for an anonymous login with email address as password.
ftp://anonymous:myname%40spyinternation.com@lenny/lucky.gif/
Example 2:
The following table shows examples issue the use of no or empty user names and password:

ftp://@host.com/ has an empty user name and no password


ftp://host.com/ has no user name
ftp://foo:@host.com/ has a user name of foo and an empty password.

Example 3:
The following table shows different examples for the use of the Directory and Filename parameters.

ftp://myname@host.dom/%2Fetc/motd is interpreted by FTP-ing to host.dom, logging on as myname (prompting for


a password if it is asked for), and then executing CWD /etc and then RETR
motd.
ftp://myname@host.dom/etc/motd would CWD etc and then RETR motd; the initial CWD might be executed
relative to the default directory for myname.
ftp://myname@host.dom//etc/motd would CWD with a null argument, then CWD etc, and then RETR motd.

17.4.1.1.3 SMB Specific Scheme


Windows clients exchange messages with a server to access resources on that server. These messages are called
Server Message Blocks (smb).
Syntax:
smb://<user>:<password>@<host>/<share>/<dir1>/<dir2>/.../<dirN>/<filename>
User specifies an optional user name.
Password specifies an optional password to the user name. If present, it follows the user name separated
from it by a colon.
Host specifies the fully qualified domain name of a network host, or its IP address as the dotted set of four
decimal digit groups.
Share defines the name of the share on the remote server.
Dir1 - DirN list the directory hierarchy on the server to the file. These parameters are optional.
Filename specifies the name of the file to be accessed with its extension.

17.4.2 Functions
Following you find the complete list of all file manipulation functions:

Function OS Description
FileCompare Compare the size and contents of two files to see if they are identical

FileCompress Compress a file

FileConvertToCodePage Convert a UTF8 file into the specified CodePage

FileConvertToUTF8 Convert a file which has the specified CodePage into UTF8

FileCopy Copy a single file

FileCreate Create an empty file

FileCreateTemp Create a temporary file

FileDecompress Decompress a compressed file

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 173

Function OS Description
FileDelete Delete a single file

FileMd5 Compute the MD5 checksum of a file

FileGetLineCount Get the number of lines in a file

FileFindPcre Open a binary file type with the supplied file path

FileMove Move (rename) a single file

FileRename Rename a single file

FileToString Open a file with the supplied FilePath, and put its content into a string

FileCompare
Compare the size and contents of two files to see if they are identical.
Syntax:
Bool FileCompare (String FileName1, String FileName2)
FileName1 is the relative or absolute path of the first file.
FileName2 is the relative or absolute path of the second file.
Returns:
TRUE if the files are identical in length and contents, FALSE if the files differ or one or both cannot be found or
the operation failed. If the operation fails, in case of one of the files not being found, ErrCode is set to
ERR_FILENOTFOUND otherwise to ERR_FUNCFAILED.
Comments:
If the files are of different lengths then no comparison is necessary.
Example:
The following example compares a file after compressing and decompressing it.
proc main ()

string newfile, compressfile, oldfile

compressfile = "c:\\temp\\file.zip"
oldfile = "c:\\temp\\file1.txt"
newfile = "c:\\temp\\file2.txt"
FileCompress (oldfile, compressfile)
FileDecompress (compressfile, newfile)

if (FileCompare (oldfile, newfile) == TRUE)


Print (LogFile, "Compression/Decompression OK\r\n")
endif

endproc

FileCompress
Compress a file.
Syntax:
Int FileCompress (String SrcFileName, String DstFileName)
SrcFileName is the relative or absolute path of the file to be compressed.
DstFileName is the relative or absolute path of the compressed file to be created.
Returns:
Length of the compressed file if successful, 0 if the compression failed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


174 - BMC FootPrints Asset Core - Chilli Reference

Comments:
The original file is left untouched. The file format is proprietary and cannot be decompressed by any other tools.
Options to compress file archives, such as .zip files are provided by the Chilli Archive Functions.
Example:
The following example compares a file after compressing and decompressing it.
proc main ()

string newfile, compressfile, oldfile

compressfile = "c:\\temp\\file.zip"
oldfile = "c:\\temp\\file1.txt"
newfile = "c:\\temp\\file2.txt"
FileCompress (oldfile, compressfile)
FileDecompress (compressfile, newfile)

if (FileCompare (oldfile, newfile) == TRUE)


Print (LogFile, "Compression/Decompression OK\r\n")
endif

endproc

FileConvertToCodePage
Convert a UTF8 file into the specified CodePage.
Syntax:
Bool FileConvertToCodePage (String FileName, String FileDest, String CodePage)
FileName is the name of the UTF8 file to be converted.
FileDest is
CodePage is the identifier of the target CodePage, that is, ISO8859_1 to ISO8859_16.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED or one of the file manipulation specific errors listed above.
Example:
The following example copies a file in UTF-8 format into a file of format ISO8859_1 and then back again.
Bool CopyISO8859_1FileToUTF8File (string sourceFile, string destinationFile)

if (FileCopy (sourceFile, destinationFile))


return FileConvertToUTF8 (destinationFile, "ISO8859_1")
endif
return false

endproc

Bool CopyUTF8FileToISO8859_1File (string sourceFile, string destinationFile)

if (FileCopy (sourceFile, destinationFile))


return FileConvertToCodePage (destinationFile, "ISO8859_1")
endif
return false

endproc

proc main ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 175

copyUTF8FileToISO8859_1File ("C:/fileUTF8.txt", "C:/fileISO8859_1.txt")


copyISO8859_1FileToUTF8File ("C:/fileISO8859_1.txt", "C:/fileUTF8_2.txt")
endproc

FileConvertToUTF8
Convert a file which has the specified CodePage into UTF8.
Syntax:
Bool FileConvertToUTF8 (String FileName, String FileDest, String CodePage)
FileName is the name of the file to be converted to UTF8.
FileDest is
CodePage is the identifier of the CodePage as which the file is defined, that is, ISO8859_1 to ISO8859_16.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED or one of the file manipulation specific errors listed above.
Example:
The following example copies a file in UTF-8 format into a file of format ISO8859_1 and then back again.
Bool CopyISO8859_1FileToUTF8File (string sourceFile, string destinationFile)

if (FileCopy (sourceFile, destinationFile))


return FileConvertToUTF8 (destinationFile, "ISO8859_1")
endif
return false

endproc

Bool CopyUTF8FileToISO8859_1File (string sourceFile, string destinationFile)

if (FileCopy (sourceFile, destinationFile))


return FileConvertToCodePage (destinationFile, "ISO8859_1")
endif
return false

endproc

proc main ()

copyUTF8FileToISO8859_1File ("C:/fileUTF8.txt", "C:/fileISO8859_1.txt")


copyISO8859_1FileToUTF8File ("C:/fileISO8859_1.txt", "C:/fileUTF8_2.txt")
endproc

FileCopy
Copy a file into a second file. The function has the following two signatures:
Syntax:
Bool FileCopy (String SourceUrl, String DestinationUrl)
Bool FileCopy (String SourceUrl, String DestinationUrl, Bool ForceCopy)
SourceUrl is the relative or absolute path or the URL of the file to be copied.
DestinationUrl is the relative or absolute path or the URL of the file to be created.
ForceCopy defines if the file is to be copied to its new location even if the ReadOnly flag is set for the
destination file. By default this option is set to false.

Numara Software, Inc. and BMC Software, Inc. Confidential.


176 - BMC FootPrints Asset Core - Chilli Reference

Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED or one of the file manipulation specific errors listed above.
Comments:
The supplied parameter can be relative or absolute paths or URLs using the http, ftp, smb or 'file' protocols. If a
network protocol URL is used, success or failure is determined by whether the server allows the operation. For
non-URL paths, if the destination path exists it is overwritten. Also, for a non-URL path, if any part of the
destination path does not exist, it is created.
Example:
This following example is taken from the main rollout installation procedure for the BCM agent on Windows NT.
It defines a procedure to move Remote Control files to the Windows System directory.
proc MoveRPFiles ()

string SrcDir, DstDir, CPDir, RefSysDir


SrcDir = CPDir + '\rp\'
DstDir = RefSysDir + '\'

FileCopy (SrcDir + 'rp32mmth.dll', DstDir + 'rp32mmth.dll')


FileCopy (SrcDir + 'ntvdrv.dll', DstDir + 'ntvdrv.dll')
FileCopy (SrcDir + 'rp32ntv1.dll', DstDir + 'rp32ntv1.dll')

FileDelete (SrcDir + "rp32mmth.dll")


FileDelete (SrcDir + "ntvdrv.dll")
FileDelete (SrcDir + "rp32ntv1.dll")

endproc

proc main ()
MoveRPFiles ()
endproc

FileCreate
Create an empty file.
Syntax:
Bool FileCreate (String FileName)
FileName is the relative or absolute path of the file to be created.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
If the file to be created exists already, the function fails. You can use FileExists to check whether a file exists
already.
Example:
This following example is taken from the main rollout installation procedure for the BCM agent on Windows NT.
It creates the install.log file required to uninstall Remote Control.
proc CreateInstallLog ()

string File, RefSysDir


RefSysDir = 'C:\temp'

File = RefSysDir + "\\install.log"

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 177

FileCreate (File)
FileAddLine (File, "*** Installation ***\r\n")
FileAddLine (File, "Title: BMC Client Management Installation\r\n")
FileAddLine (File, "Source: C:\SETUP.EXE\r\n")

endproc

proc main ()
CreateInstallLog ()
endproc

FileCreateTemp
Create a temporary file.
Syntax:
String FileCreateTemp (String Prefix)
Prefix is the base name from which the temporary file name is created.
Returns:
A string containing the full path of the newly created temporary file, which is guaranteed to be unique by the
operating system, if the operation was successful, or an empty string if the function failed. If the operation fails,
ErrCode is set to one of the general runtime errors (see page 677).
Example:
This following example is taken from the main rollout installation procedure for the chilli Agent on Windows NT.
It creates the install.log file required to uninstall Remote Control.
proc CreateInstallLog ()

string File, RefSysDir

RefSysDir = 'C:\temp'
File = RefSysDir + "\\install.log"

FileCreateTemp (File)
FileAddLine (File, "*** Installation ***\r\n")
FileAddLine (File, "Title: Chilli Installation\r\n")
FileAddLine (File, "Source: C:\SETUP.EXE\r\n")

endproc

proc main ()
CreateInstallLog ()
endproc

FileDecompress
Decompress a file previously compressed with FileCompress.
Syntax:
Int FileDecompress (String SrcFileName, String DstFileName)
SrcFileName is the relative or absolute path of the file to be decompressed.
DstFileName is the relative or absolute path of the decompressed file to be created.
Returns:
1 if the file was successfully decompressed, 0 if the decompression failed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


178 - BMC FootPrints Asset Core - Chilli Reference

Comments:
The original compressed file is left untouched. This function only recognizes the compression in files executed
with FileCompress not those of any other tools. Options to decompress other file arcMEtroxhives, such as .zip
files are provided by the Chilli Archive Functions.
Example:
The following example compares a file after compressing and decompressing it.
proc main ()

string newfile, compressfile, oldfile

compressfile = "c:\\temp\\file.zip"
oldfile = "c:\\temp\\file1.txt"
newfile = "c:\\temp\\file2.txt"

FileCompress (oldfile, compressfile)


FileDecompress (compressfile, newfile)

if (FileCompare (oldfile, newfile) == TRUE)


Print (LogFile, "Compression/Decompression OK\r\n")
endif

endproc

FileDelete
Permanently delete a file. It has the following two signatures:
Syntax:
Bool FileDelete (String FileUrl)
Bool FileDelete (String DirectoryName, Bool ForceDelete)
FileUrl is the relative or absolute path or the URL of the file to be deleted.
ForceDelete indicates if the file is to be deleted if the ReadOnly flag is set. By default this option is set to
false.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The supplied parameter can be a relative or absolute path or a URL using the http, ftp, smb or 'file' protocols. If a
network protocol URL is used, success or failure is determined by whether the server allows the operation.
If the file to be deleted does not exist the function still returns TRUE to indicate success.
Example:
This following example is taken from the main rollout installation procedure for the BCM agent on Windows NT.
It defines a procedure to move Remote Control files to the Windows System directory.
proc MoveRPFiles ()
string SrcDir, DstDir
SrcDir = CPDir + '\rp\'
DstDir = RefSysDir + '\'

FileCopy (SrcDir + 'rp32mmth.dll', DstDir + 'rp32mmth.dll')


FileCopy (SrcDir + 'ntvdrv.dll', DstDir + 'ntvdrv.dll')
FileCopy (SrcDir + 'rp32ntv1.dll', DstDir + 'rp32ntv1.dll')

FileDelete (SrcDir + "rp32mmth.dll")


FileDelete (SrcDir + "ntvdrv.dll")
FileDelete (SrcDir + "rp32ntv1.dll")

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 179

endproc

FileFindPcre
Opens a binary file type with the supplied file path. If the supplied path does not exists a runtime error occurs.
Syntax:
String[] FileFindPcre (String FilePath, String CodePage, Bool CaseSensitive)
FilePath is the absolute path of the file to be searched into.
CodePage is the code page to be used to read the file.
CaseSensitive defines if the comparison is case sentitive or not. The possible values are TRUE: case
sensitive and FALSE: not case sensitive.
Returns:
Returns an array of strings that could be empty, depending on PCRE match result.
Example:
FileFindPcre ():

string strLogFile, vecErrorCode[]


strLogFile = "C:\\INSTALL.LOG" // Critical error (Code 6740)
vecErrorCode = FileFindPcre (strLogFile, "Critical error [(]Code ([0-9]+)[)]", false)
if (ArrayGetSize (vecErrorCode) == 1)
Print ("Critical error find in file [" + strLogFile + "]. Error code to parse: [" + vecErrorCode[1] +
"].")
endif

FileMd5
Compute the MD5 checksum of a file.
Syntax:
String FileMd5 (String FileName)
FileName is the relative or absolute path to the file.
Returns:
A string containing the checksum of the file. The string has a 0 lenght size if the function failed.
Example:
int main ()
string strFilePath
strFilePath = "C:\\Temp\\Setup.exe"

string strChecksum
strChecksum = FileMd5 (strFilePath)

Print ("Result is: " + strChecksum)


return 0
endproc

Result is: 45A8F563471F099DB74F78343C1DFCDD

FileGetLineCount
Get the total number of lines in a file.
Syntax:
Int FileGetLineCount (String FilePath)

Numara Software, Inc. and BMC Software, Inc. Confidential.


180 - BMC FootPrints Asset Core - Chilli Reference

FilePath is the absolute or relative path to the file to be counted.


Returns:
The number of lines contained in a file if the operation was successful or 0 if the function failed or the path is
invalid.

FileMove / FileRename
Rename or move a file.
Syntax:
Bool FileMove (String SourceUrl, String DestinationUrl)
Bool FileRename (String SourceUrl, String DestinationUrl)
SourceUrl is the relative or absolute path or the URL of the file to be moved.
DestinationUrl is the new relative or absolute path or the URL to give to the file.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The supplied parameter can be relative or absolute paths or URLs using the http, ftp, smb or 'file' protocols. If a
network protocol URL is used, success or failure is determined by whether the server allows the operation. In
particular a move operation can succeed in creating the destination file but fail to delete the source.
For non-URL paths, if the destination path exists it is overwritten. Also, for a non-URL path, if any part of the
destination does not exist, it is created.
Example:
The following example creates the chilli.ini file if it does not yet exist by renaming a temporary file to
chilli.ini.
proc UpdateWWINI ()

int iWWiniFind
string szWWDir
Print (LogFile, "\r\nUpdate chillichilli.ini\r\n")

iWWiniFind = FileFind (szWWDir + '\chilli.ini')

if (iWWiniFind == 1)
FileSetAttr (szWWDir + '\wwatchnt.tmp', 32)
FileSetAttr (szWWDir + '\chilli.ini', 32)
FileDelete (szWWDir + '\wwatchnt.tmp')
else
FileSetAttr (szWWDir + '\wwatchnt.txt', 32)
FileRename (szWWDir + '\wwatchnt.tmp', szWWDir + '\chilli.ini')
endif

endproc

proc main ()
UpdateWWINI ()
endproc

FileToString
Open a file with the supplied FilePath, and put its content into a string.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 181

Syntax:
String FileToString (String FilePath, Bool SingleLineOutput)
FilePath is the absolute path of the file to be read.
SingleLineOutput defines if the carriage returns have to be stripped out. The possible values are TRUE:
Strip the carriage returns and FALSE: Keep the original carriage returns.
Returns:
Returns a string that could be empty, depending on the file content.
Comments:
This string can optionally be on a single line (strip out carriage returns) to be used with RegEx later on, when
SingleLineOutput is set to TRUE. The advantage of having the file on a single line is to be able to perform a regular
expression or PCRE on the whole file in one go. If the supplied path does not exists, a runtime error occurs.
Example:
FileToString (string, bool):

string strFileContentInOneLine
strFileContentInOneLine = FileToString ("C:\\MESSAGE.LOG", true)
if (StrLen (strFileContentInOneLine) > 0)
Print (strFileContentInOneLine)
else
Print ("Could not open C:\MESSAGE.LOG file or void content.")
endif

17.5 File Attribute Functions


The functions of the File Attribute group get general information about a specific file.
Following you find the list of all functions of the File Attribute function group:

Function OS Description
FileExists Check for existence of a file

File Find Check for existence of a file

FileFindClose End a FileFindOpen operation

FileFindNext Continue a directory search for files started by FileFindOpen

FileFindOpen Start a FindFile operation

FileGetAttr Get the file attribute flags

FileGetMode Return the mode word for a file/directory

FileGetModules Check if the signature of a .EXE file is of the type NT and if it is then extract the
imported modules (DLLs) in the file
FileGetSize Get the length of a file in bytes

FileGetSizeKb Get the length of a file in kilobytes

FileGetSizeMb Get the length of a file in megabytes

FileGetVersionH Get the higher part of a file version stamp

FileGetVersionL Get the lower part of a file version stamp

FileGetVersionLanguages Get the list of version languages the file version

FileGetVersionValue Get the named file version resource value in the given language

Numara Software, Inc. and BMC Software, Inc. Confidential.


182 - BMC FootPrints Asset Core - Chilli Reference

Function OS Description
FileHasVersionInfo Check whether a given file exists and has some version information in it

FileIsText Check that a file contains only text

FileIsWritable Check that a file is writable

FileSetAttr Set the file attribute flag

FileSetMode Set the access mode for a file/directory

FileExists
Check to see if a single file exists.
Syntax:
Bool FileExists (String FileName)
FileName is the relative or absolute path of the file to be found.
Returns:
TRUE if the supplied path exists and is a file, FALSE if the path does not exist or the operation failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
If the supplied path exists but is a directory the return value also is FALSE.
Example:
This following example is taken from the main rollout installation procedure for the BCM agent on Windows NT.
It defines a procedure to delete a file installed in the installation directory.
proc DelFilWW (string target)

string target
target = C:\\example\\example.txt”

if (FileExists (target))
FileSetAttr (target, 32)
endif

FileDelete (target)
Print (LogFile, target + " has been deleted\r\n")

endproc

proc main ()
DelFilWW (target)
endproc

FileFind
Check to see if a single file exists.
Syntax:
Bool FileFind (String FileName)
FileName is the relative or absolute path of the file to be found.
Returns:
TRUE if the supplied path exists and is a file, FALSE if the path does not exist or the operation failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 183

Comments:
If the supplied path exists but is a directory the return value also is FALSE.
Example:
This following example is taken from the main rollout installation procedure for the BCM agent on Windows NT.
It defines a procedure to delete a file installed in the installation directory.
proc DelFilWW (string target)

string target
target = “C:\\example\\example.txt”

if (FileFind (target))
FileSetAttr (target, 32)
endif

FileDelete (target)
Print (LogFile, target + " has been deleted\r\n")

endproc

proc main ()
DelFilWW (target)
endproc

FileFindClose
End a FileFindOpen operation.
Syntax:
Bool FileFindClose (FileFindInfo FileInfo)
FileInfo is the handle to the internal data structure which keeps track of the list of files found in the
directory and obtained by the FileFindOpen function.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
If the close operation was successful, the supplied handle to the open file becomes invalid and can not be used in
any further search operations.
Any search function started by FileFindOpen must be terminated with the FileFindClose function. This
function can be used with FileFindOpen and FileFindNext to search a directory of files for files which
match a certain pattern. Start by calling FileFindOpen once to set up the reference to the data structure and
supplying the search pattern. Continue the search by calling FileFindNext until an empty string is returned.
Then terminate the search with FileFindClose. The FileFindClose function together with the
FileFindOpen and FileFindNext functions replaces the original FileFindFirst and FileFindNext
functions.
Example:
The following example prints the list of files in a specific directory.
proc main ()

FileFindInfo ptrFileInfo
string szFileName

ptrFileInfo = FileFindOpen ("/usr/local/bin/*")


print ("Here is the list of files in /usr/local/bin\n")

Numara Software, Inc. and BMC Software, Inc. Confidential.


184 - BMC FootPrints Asset Core - Chilli Reference

while (1)
szFileName = FileFindNext (ptrFileInfo)
if (szFileName == "")
break
else
print (szFileName + "\n")
endif
endwhile

if (FileFindClose (ptrFileInfo) == FALSE)


print ("Unable to close the FileInfo\n")
endif

endproc

FileFindNext
Step a FileFindOpen operation by getting the next file.
Syntax:
String FileFindNext (FileFindInfo FileInfo)
FileInfo is the handle to the internal data structure which keeps track of the list of files found in the
directory.
Returns:
A string containing the name of the next matching file if the operation was successful, or an empty string if no
more files were found or the search operation failed.
Comments:
If the function is successful, the returned filename does not contain any directory information. The function
FileFindOpen must have been called first before this function to set up the internal data structure, otherwise
the search fails. The search function must be ended with the FileFindClose function. Start by calling
FileFindOpen once to set up the reference to the data structure and supplying the search pattern. Continue the
search by calling FileFindNext until an empty string is returned. Then terminate the search with
FileFindClose. The FileFindNext function together with the FileFindOpen and FileFindClose
functions replaces the original FileFindFirst and FileFindNext functions.
Example:
The following example prints the list of files in a specific directory.
proc main ()

FileFindInfo ptrFileInfo
string szFileName

ptrFileInfo = FileFindOpen ("/usr/local/bin/*")


print ("Here is the list of files in /usr/local/bin\n")

while (1)
szFileName = FileFindNext (ptrFileInfo)
if (szFileName == "")
break
else
print (szFileName + "\n")
endif
endwhile

if (FileFindClose (ptrFileInfo) == FALSE)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 185

print ("Unable to close the FileInfo\n")


endif

endproc

FileFindOpen
Start a FileFind operation.
Syntax:
FileFindInfo FileFindOpen (String FilePattern)
FilePattern is the relative or absolute path of the files to be found and can contain wildcard characters.
Returns:
The handle to an internal data structure, which keeps track of the list of files found in the directory if the
operation was successful, or an empty handle if the operation failed.
Comments:
This function can be used with FileFindNext and FileFindClose to search a directory of files for files
which match a certain pattern. Start by calling FileFindOpen once to set up the reference to the data structure
and supplying the search pattern. Continue the search by calling FileFindNext until an empty string is
returned. Then terminate the search with FileFindClose. The FileFindOpen function together with the
FileFindNext and FileFindClose functions replaces the original FileFindFirst and FileFindNext
functions.
Example:
The following example prints the list of files in a specific directory.
proc main ()

FileFindInfo ptrFileInfo
string szFileName

ptrFileInfo = FileFindOpen ("/usr/local/bin/*")


print ("Here is the list of files in /usr/local/bin\n")

while (1)
szFileName = FileFindNext (ptrFileInfo)
if (szFileName == "")
break
else
print (szFileName + "\n")
endif
endwhile

if (FileFindClose (ptrFileInfo) == FALSE)


print ("Unable to close the FileInfo\n")
endif

endproc

FileGetAttr
Return the attribute flags of a file.
Syntax:
Int FileGetAttr (String FileName)
FileName is the relative or absolute path of the file to be accessed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


186 - BMC FootPrints Asset Core - Chilli Reference

Returns:
The attribute flags if the operation is successful, 0 if the file or directory cannot be found. If it cannot be found
ErrCode is set to ERR_FILENOTFOUND.
Comments:
The attribute flag only makes sense on Windows environments although it also works on UNIX/Linux. This
function is the equivalent to the FileGetMode function for the UNIX/Linux environment.
Comments for Windows:
The attribute flag of a file is an OR of one or more of the following:

Read Only 0x01


Hidden 0x02
System File 0x04
Subdirectory 0x10
Archive 0x20

For example, a file with an attribute value of 0x21 (33 decimal) has its archive and read-only attributes set. A file
with an attribute flag equal to 0 is a normal file which can be read and written without restriction.
Example:
The following example shows a procedure that deletes a file.
proc DeleteOneFile (string OldFile)

string szKey, szOldValue, szNewValue, szExt

if (FileFind (OldFile) == FALSE)


return
endif
szExt = PathGetFileExt (OldFile)

if (szExt == "")
return
endif

;Make sure the file to be deleted is not read-only


FileSetAttr (OldFile, FileGetAttr (OldFile))
FileDelete (OldFile)
endproc

proc main ()
string OldFile
OldFile = "C:\temp\example.txt"
DeleteOneFile (OldFile)
endproc

FileGetMode
Return the mode word for a file or directory. This is the mode value as returned by the ’stat’ system call.
Syntax:
Int FileGetMode (String FilePath)
FilePath is the absolute or relative path of the file for which the mode is required.
Returns:
The mode value if the operation was executed successfully or 0 if the operation failed. The operation fails if the
filename or filepath could not be found in which case the ErrCode is set to ERR_FILENOTFOUND.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 187

Comments:
The mode word only makes sense on UNIX/Linux environments although it also works on Windows. This
function is the equivalent to the FileGetAttr function for the Windows environment.
Comments for UNIX Environment:
This function returns the mode information about the specified file. You do not need any access rights to the file
to get this information but you need search rights to all directories named in the path leading to the file. The
following flags listed in hexadecimal format are defined for the file mode:

Bitmask Description
00140000 socket (not POSIX)
00120000 symbolic link (not POSIX)
00100000 regular file (not POSIX)
00060000 block device (not POSIX)
00040000 directory (not POSIX)
00020000 character device (not POSIX)
00010000 fifo (not POSIX)
00004000 set UID bit
00002000 set GID bit
00001000 sticky bit (not POSIX)
00000400 user has read permission
00000200 user has write permission
00000100 user has execute permission
00000040 group has read permission
00000020 group has write permission
00000010 group has execute permission
00000004 others have read permission
00000002 others have write permission
00000001 others have execute permission

Comments for Windows Environment:


In Chilli this function is also supported on Windows through the _stat call. This function returns the mode
information about the specified file. For Windows the following values are possible:

Bitmask Description
0040000 directory
0020000 character special
0010000 pipe
0100000 regular
0000400 read permission, owner
0000200 write permission, owner
0000100 execute/search permission, owner

FileGetModules
Check if the signature of a .exe file is of the type NT and if it is then extract the imported modules (DLLs) in the
file.
Syntax:
String[] FileGetModules (String FilePath, Bool Resolve, Bool Recurse)
FilePath is the relative or absolute path of the file.
Resolve is the

Numara Software, Inc. and BMC Software, Inc. Confidential.


188 - BMC FootPrints Asset Core - Chilli Reference

Recourse is the
Returns:
An array of strings containing the list of the imported modules if the operation was successful or an empty array if
an error occurred or thefunction failed.
Comments:
If Resolve is TRUE, each module found is searched for in the same way as the Windows OS would and the
returned name is in fact the path of the module rather than just the name. If Resolve is set and a name is returned
without a path, it means that a required DLL was not found.
If Recurse is TRUE, each newly found module is itself scanned for its dependent modules. Resurse TRUE implies
that Resolve is set as well, whatever the passed value.

FileGetSize
Return the size of a file in bytes.
Syntax:
Int FileGetSize (String FileName)
FileName is the relative or absolute path of the file to be accessed.
Returns:
The size of the file in bytes if the operation is successful, 0 if the file cannot be found. If the file cannot be found
ErrCode is set to ERR_FILENOTFOUND.
Comments:
The returned integer is limited to a value of +/- 2 147 483 647.
Example:
This function constructs the absolute pathname for a package file and copies the file from the depot to the current
directory.
proc main ()

string SrcPath, driveletter, Package, NewPkgPath


int SrvFileSize

driveletter = 'C'
Package = 'package.pkg'
NewPkgPath = 'C:\temp\package_new.pkg'

SrcPath = driveletter + ':\' + Package


SrvFileSize = FileGetSize (SrcPath)
FileCopy (SrcPath, NewPkgPath)
DiskNetDelete (driveletter)

endproc

FileGetSizeKb
Return the size of a file in kilobytes.
Syntax:
Int FileGetSizeKb (String FilePath)
FilePath is the relative or absolute path of the file to be accessed.
Returns:
The size of the file in kilobytes if the operation is successful, 0 if the file cannot be found. If the file cannot be
found ErrCode is set to ERR_FILENOTFOUND.
Comments:
The returned integer is limited to a value of +/- 2 147 483 647.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 189

FileGetSizeMb
Return the size of a file in megabytes.
Syntax:
Int FileGetSizeMb (String FilePath)
FilePath is the relative or absolute path of the file to be accessed.
Returns:
The size of the file in megabytes if the operation is successful, 0 if the file cannot be found. If the file cannot be
found ErrCode is set to ERR_FILENOTFOUND.
Comments:
The returned integer is limited to a value of +/- 2 147 483 647.

FileGetVersionH
Get the upper part of a file‘s version stamp.
Syntax:
Int FileGetVersionH (String FileName)
FileName is the relative or absolute path of the file to be read.
Returns:
The upper 32-bits of the 64 bit version number if successful, 0 otherwise.
Comments:
Most system and executable files (.EXE, .DLL and so on.) contain a 64 bit version stamp for the purposes of
identifying older versions of files which might need to be upgraded. This function, together with
FileGetVersionL can be used to extract the version information for comparison purposes.
This function is not applicable to the UNIX environment.
Example:
The following example checks the lower and upper version numbers.
proc main ()

int versionH, versionL, version23


string stringFile
stringFile = "C:\\chilli\\chilli.exe"
versionH = FileGetVersionH (stringFile)

if (versionH == 2)
versionL = FileGetVersionL (stringFile)
if (versionL == 3)
version23 = 1
else
version23 = 0
endif
else
version23 = 0
endif

endproc

FileGetVersionL
Get the lower part of a file‘s version stamp.

Numara Software, Inc. and BMC Software, Inc. Confidential.


190 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
Int FileGetVersionL (String FileName)
FileName is the relative or absolute path of the file to be read.
Returns:
The lower part of the 64 bit version number if successful, 0 otherwise.
Comments:
Most system and executable files (.EXE, .DLL and so on.) contain a 64 bit version stamp for the purposes of
identifying older versions of files which might need to be upgraded. This function, together with
FileGetVersionH can be used to extract the version information for comparison purposes.
This function is not applicable to the UNIX environment.
Example:
The following example checks the lower and upper version numbers.
proc main ()

int versionH, versionL, version23


string stringFile
stringFile = "C:\\chilli\\chilli.exe"
versionH = FileGetVersionH (stringFile)

if (versionH == 2)
versionL = FileGetVersionL (stringFile)
if (versionL == 3)
version23 = 1
else
version23 = 0
endif
else
version23 = 0
endif

endproc

FileGetVersionLanguages
Get the list of version languages the file version.
Syntax:
String[] FileGetVersionLanguages (String FilePath)
FilePath is the relative or absolute path of the file to be read.
Returns:
An array of strings containing the list of the file version languages if successful or an empty array if an error
occurs.
Comments:
If the supplied language code is an empty string, the first available language in the resource is used. If the file
contains some version information but the requested resource value is not found no error is generated and an
empty string is returned.
Example:
The following example prints all languages found in the file version information of a file.
proc main ()

string Langs[];
int i;

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 191

print (LogFile, "\n Language codes:\n");

Langs = FileGetVersionLanguages (szPath);

for (i=1; i<=ArrayGetSize (Langs); i+=1)


print (LogFile, " " + Langs[i] + "\n");
endfor

endproc

FileGetVersionValue
Get the named file version resource value in the given language.
Syntax:
String[] FileGetVersionValue (String FilePath, String LanguageCode, String Name)
FilePath is the relative or absolute path of the file to be read.
LanguageCode is the relative or absolute path of the file to be read.
Name is the name of the version resource to be read.
Returns:
An array of strings containing the string value of the specified resource if the operation was successful or an
empty string if an error occurs.
Comments:
If the supplied language code is an empty string, the first available language in the resource is used. If the file
contains some version information but the requested resource value is not found no error is generated and an
empty string is returned. The following are the predefined version information strings:

Comments CompanyName FileDescription


FileVersion InternalName LegalCopyright
LegalTrademarks OriginalFilename PrivateBuild
ProductName ProductVersion SpecialBuild

Example:
The following example script prints all version information contained in the version information of a file.
proc PrintFileVerValue (string szPath, string szValue)

print (LogFile, " " + szValue + ": " + FileGetVersionValue (szPath, "",
szValue) + "\n")

endproc

proc main ()

string szPath

szPath = 'C:\Program Files\BMC Software\Client Management\chilli\chilli.ini'

if (FileHasVersionInfo (szPath))
print (LogFile, "\n" + szPath + "\n")
PrintFileVerValue (szPath, 'Comments');
PrintFileVerValue (szPath, 'CompanyName');
PrintFileVerValue (szPath, 'FileDescription');
PrintFileVerValue (szPath, 'FileVersion');
PrintFileVerValue (szPath, 'InternalName');
PrintFileVerValue (szPath, 'LegalCopyright');
PrintFileVerValue (szPath, 'LegalTrademarks');
PrintFileVerValue (szPath, 'OriginalFilename');
PrintFileVerValue (szPath, 'PrivateBuild');
PrintFileVerValue (szPath, 'ProductName');

Numara Software, Inc. and BMC Software, Inc. Confidential.


192 - BMC FootPrints Asset Core - Chilli Reference

PrintFileVerValue (szPath, 'ProductVersion');


PrintFileVerValue (szPath, 'SpecialBuild');
endif

endproc

FileHasVersionInfo
Check whether a given file exists and has some version information in it.
Syntax:
Bool FileHasVersionInfo (String FilePath)
FilePath is the relative or absolute path of the file to be read.
Returns:
TRUE if the file exists and has some version information in it, or FALSE if an error occurs or the file does not have
any version information.
Example:
The following example script prints all version information contained in the version information of a file.
proc PrintFileVerValue (string szPath, string szValue)

print (LogFile, " " + szValue + ": " + FileGetVersionValue (szPath, "",
szValue) + "\n")

endproc

proc main ()

string szPath

szPath = 'C:\Program Files\BMC Software\Client Management\chilli\chilli.ini'

if (FileHasVersionInfo (szPath))
print (LogFile, "\n" + szPath + "\n")
PrintFileVerValue (szPath, 'Comments');
PrintFileVerValue (szPath, 'CompanyName');
PrintFileVerValue (szPath, 'FileDescription');
PrintFileVerValue (szPath, 'FileVersion');
PrintFileVerValue (szPath, 'InternalName');
PrintFileVerValue (szPath, 'LegalCopyright');
PrintFileVerValue (szPath, 'LegalTrademarks');
PrintFileVerValue (szPath, 'OriginalFilename');
PrintFileVerValue (szPath, 'PrivateBuild');
PrintFileVerValue (szPath, 'ProductName');
PrintFileVerValue (szPath, 'ProductVersion');
PrintFileVerValue (szPath, 'SpecialBuild');
endif

endproc

FileIsText
Check that a file contains only printable text characters.
Syntax:
Bool FileIsText (String FileName)
FileName is the relative or absolute path of the file to be checked.
Returns:
TRUE if the file is a valid text file, FALSE if it is not or the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 193

Comments:
To check whether a file is a text file or not, this function reads the first 256 bytes of the file and looks for
characters which have an ASCII code lower than 32 (space) but are not Carriage Return, Line Feed or TAB. If any
such characters are found, then the function returns FALSE, otherwise it returns TRUE.
Example:
The following example script adds a line to a file after making sure is is a configuration file and writable.
proc main ()

textfilehandle texthandle
string stringFile, line, newline
stringFile = "C:\\temp\\test.ini"

if (FileIsText (stringFile) == TRUE)


if (FileIsIni (stringFile) == TRUE)
if (FileIsWritable (stringFile) == FALSE)
FileSetAttr (stringFile, 32)
endif
line = "new text line"
FileInsertLine (stringFile, 1, line + "\r\n")
newline = FileGetLine (texthandle, 1)
endif
endif

endproc

FileIsWritable
Check that a file is writable and not otherwise locked.
Syntax:
Bool FileIsWritable (String FileName)
FileName is the relative or absolute path of the file to be checked.
Returns:
TRUE if the file is writable, FALSE if it is not or the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
A file can not be writable if it has its read-only attribute set or it is currently in use by another program. To check
whether a file is writable or not, this function attempts to open the file for a write operation. The open can fail if
the file cannot be found, it has its read-only attribute set or has already been opened for use by another program.
Regardless of the result of the test, the contents or the status of the file are not changed by this function.
Example:
The following example script adds a line to a file after making sure is is a configuration file and writable.
proc main ()

textfilehandle texthandle
string stringFile, line, newline
stringFile = "C:\\temp\\test.ini"

if (FileIsText (stringFile) == TRUE)


if (FileIsIni (stringFile) == TRUE)
if (FileIsWritable (stringFile) == FALSE)
FileSetAttr (stringFile, 32)
endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


194 - BMC FootPrints Asset Core - Chilli Reference

line = "new text line"


FileInsertLine (stringFile, 1, line + "\r\n")
newline = FileGetLine (texthandle, 1)
endif
endif

endproc

FileSetAttr
Set the attribute flags of a file.
Syntax:
Bool FileSetAttr (String FileName, Int Attributes)
FileName is the relative or absolute path of the file to be accessed.
Attributes is the attribute flag to apply to the file.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the file cannot be found ErrCode is set to
ERR_FILENOTFOUND.
Comments:
The attribute flag only makes sense on Windows environments although it also works on UNIX/Linux. This
function is the equivalent to the FileSetMode function for the UNIX/Linux environment.
Comments for Windows:
The attribute flag of a file is an OR of one or more of the following:

Read Only 0x01


Hidden 0x02
System File 0x04
Subdirectory 0x10
Archive 0x20

So for example, a file with an attribute value of 0x21 (33 decimal) has its archive and read-only attributes set. A
file with an attribute flag equal to 0 is a normal file which can be read and written to without restriction.
Example:
The following example script adds a line to a file after making sure is is a configuration file and writable.
proc main ()

textfilehandle texthandle
string stringFile, line, newline
stringFile = "C:\\temp\\test.ini"

if (FileIsText (stringFile) == TRUE)


if (FileIsIni (stringFile) == TRUE)
if (FileIsWritable (stringFile) == FALSE)
FileSetAttr (stringFile, 32)
endif
line = "new text line"
FileInsertLine (stringFile, 1, line + "\r\n")
newline = FileGetLine (texthandle, 1)
endif
endif

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 195

FileSetMode
Set the access mode for a file or directory. This is the mode value as returned by the ’stat’ system call.
Syntax:
Bool FileSetMode (String FilePath, Int FileMode)
FilePath is the absolute or relative path of the file for which the mode is to be set.
FileMode is the value the representing the mode to be set.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. The operation fails if the filename or filepath
could not be found in which case the ERR_CODE is set to ERR_FILENOTFOUND.
Comments:
The mode word only makes sense on UNIX/Linux environments although it also works on Windows. This
function is the equivalent to the FileSetAttr function for the Windows environment.
Comments for UNIX Environment
This function sets the mode of the specified file. You do need write access rights to the file to do so. However, only
the access type of the file can be changed. The file type can NOT be changed via this function.

17.6 Text File Editing Functions


This group of functions provides you with the possibility to read and edit text files.

Function OS Description
FileAddLine Add a line of text to the end of a file

FileDeleteLine Delete a line in a text file

FileGetLine Get a line of text from a file

FileGetLineCount Get the number of lines in a text file

FileGetPath Return the path of the file associated with a given handle

FileInsertLine Insert a line into a text file

FileTextClose Close an existing text file

FileTextOpen Open a text file

FileAddLine
Add a single line to the end of a text file.
Syntax:
Bool FileAddLine (String FileName, String LineText)
Bool FileAddLine (TextFileHandle TextHandle, String LineText)
FileName is the relative or absolute path of the file to be modified.
TextHandle is the reference to the handle of an open text file returned by the FileTextOpen function.
LineText is the entire text string to be added to the file.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


196 - BMC FootPrints Asset Core - Chilli Reference

Comments:
The function does not add any carriage return characters to the end of the added line, so if these are required they
must be included in LineText. If the file to which the line is to be added does not yet exist it is created.
Example 1:
Following you find an example taken from the main rollout installation procedure for the BCM agent on Windows
NT. It creates the install.log file required to uninstall Remote Control using the file name (first signature).
proc CreateInstallLog ()

string File, RefSysDir


File = RefSysDir + "\\install.log"

FileCreate (File)
FileAddLine (File, "*** Installation ***\r\n")
FileAddLine (File, "Title: BMC Client Management Installation\r\n")
FileAddLine (File, "Source: C:\\SETUP.EXE\r\n")

endproc

proc main ()
CreateInstallLog ()
endproc

Example 2:
Following you find an example taken from the main rollout installation procedure for the BCM agent on Windows
NT. It creates the install.log file required to uninstall Remote Control using the file handle (second signature).
proc CreateInstallLog ()

string File, RefSysDir


TextFileHandle texthandle

File = RefSysDir + "\\install.log"


FileCreate (File)
texthandle = FileTextOpen (File)
FileAddLine (texthandle, "*** Installation ***\r\n")
FileAddLine (texthandle, "Title: Chilli Installation\r\n")
FileAddLine (texthandle, "Source: C:\\SETUP.EXE\r\n")

FileTextClose (texthandle)
endproc

proc main ()
CreateInstallLog ()
endproc

FileDeleteLine
Delete a single line from a text file.
This function has the following two signatures.
Syntax:
Bool FileDeleteLine (String FileName, Int LineNumber)
Bool FileDeleteLine (TextFileHandle TextHandle, Int LineNumber)
FileName is the relative or absolute path of the file to be modified.
TextHandle is the reference to the handle of an open text file returned by the FileTextOpen function.
LineNumber is the number of the line (starting at 1) to be deleted.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 197

Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FILENOTVALID if the file does not exist or is not a text file, and ERR_FUNCFAILED if the specified line does
not exist.
Comments:
The signature using the textfilehandle can only be used if the text file to be manipulated was opened by the
FileTextOpen function.

Example 1:
The following example script inserts a line into and deletes a line from a file.
proc main ()

string stringFile, line, newline

stringFile = 'c:\temp\file1.txt'
line = "new text line"

FileInsertLine (stringFile, 1, line + "\r\n")


newline = FileGetLine (stringfile, 1)

if (newline == line)
FileDeleteLine (stringFile, 1)
endif

endproc

Example 2:
The following example script deletes the last three lines of a file after making sure it is a text file.
proc main ()

textfilehandle texthandle
string filename
int n
filename = "D:\\RefSysDir\install.log"

if (FileIsText (filename) == TRUE)


texthandle = FileTextOpen (filename)
n = FileGetLineCount (texthandle)
FileDeleteLine (texthandle, n-2)
FileDeleteLine (texthandle, n-1)
FileDeleteLine (texthandle, n)
FileTextClose (texthandle)
endif

endproc

FileGetLine
Get a single line from a text file.
This function has the following two signatures.
Syntax:
String FileGetLine (String FileName, Int LineNumber)
String FileGetLine (TextFileHandle TextHandle, Int LineNumber)
FileName is the relative or absolute path of the file to be read.
TextHandle is the reference to the handle of an open text file returned by the FileTextOpen function.
LineNumber is the number of the line (starting at 1) to read.

Numara Software, Inc. and BMC Software, Inc. Confidential.


198 - BMC FootPrints Asset Core - Chilli Reference

Returns:
The contents of the line if the operation was successful, an empty string if the operation failed. If the operation
fails, ErrCode is set to ERR_FILENOTVALID if the file does not exist or is not a text file, and ERR_FUNCFAILED if
the specified line does not exist.
Comments:
The signature using the textfilehandle can only be used if the text file to be manipulated was opened by the
FileTextOpen function.

Example 1:
The following example script inserts a line into and deletes a line from a file.
proc main ()

string stringFile, line, newline

stringFile = 'c:\temp\file1.txt'
line = "new text line"

FileInsertLine (stringFile, 1, line + "\r\n")


newline = FileGetLine (stringfile, 1)

if (newline == line)
FileDeleteLine (stringFile, 1)
endif

endproc

Example 2:
The following example searches a text file for a specific line of text.
proc main ()

textfilehandle texthandle
string filename, line, newline
int n
filename = "D:\\RefSysDir\install.log"
line = "new text line"
n = 1

if (FileIsText (filename) == TRUE)


texthandle = FileTextOpen (filename)
while (newline != line)

newline = FileGetLine (texthandle, n)


n=n+1
endwhile

FileTextClose (texthandle)
endif

endproc

FileGetLineCount
Get the total number of lines in a text file.
Syntax:
Int FileGetLineCount (TextFileHandle TextHandle)
TextHandle is the reference to the handle of the text file returned by the FileTextOpen function.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 199

Returns:
The number of lines of text contained in a text file if the operation was successful or 0 if the function failed or the
handle is invalid.
Comments:
This function can only be used if the text file to be manipulated was opened by the FileTextOpen function.
Example:
The following example script deletes the last three lines of a file after making sure it is a text file.
proc main ()

textfilehandle texthandle
string filename
int n
filename = "D:\\RefSysDir\install.log"

if (FileIsText (filename) == TRUE)


texthandle = FileTextOpen (filename)
n = FileGetLineCount (texthandle)
FileDeleteLine (texthandle, n-2)
FileDeleteLine (texthandle, n-1)
FileDeleteLine (texthandle, n)
FileTextClose (texthandle)
endif

endproc

FileGetPath
Return the path of the file associated with a given handle.
Syntax:
String FileGetPath (TextFileHandle TextHandle)
TextHandle is the reference to the handle of an open text file returned by the FileTextOpen function.
Returns:
The path of the file associated with the handle or an empty string if an error occurs or the handle is not valid.

FileInsertLine
Insert a single line of text in a text file.
Syntax:
Bool FileInsertLine (String FileName, Int LineNumber, String LineText)
Bool FileInsertLine (TextFileHandle TextHandle, Int LineNumber, String LineText)
FileName is the relative or absolute path of the file to be modified.
TextHandle is the reference to the handle of an open text file returned by the FileTextOpen function.
LineNumber is the number of the line before which the new line is to be inserted.
LineText is the entire text string to be inserted into the file.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FILENOTVALID if the file does not exist or is not a text file, and ERR_FUNCFAILED if the specified line does
not exist.
Comments:
The line number starts at 1 for the first line and must be equal or less than the total number of lines in the file.
The line number is effectively the number of the new line after it has been inserted, that is, the line is inserted
before the supplied line number.

Numara Software, Inc. and BMC Software, Inc. Confidential.


200 - BMC FootPrints Asset Core - Chilli Reference

The function does not add any carriage return characters to the end of the added line, so if these are required they
must be included in LineText.
Example 1:
The following example script inserts a line into and deletes a line from a file.
proc main ()

string stringFile, line, newline

stringFile = 'c:\temp\file1.txt'
line = "new text line"

FileInsertLine (stringFile, 1, line + "\r\n")


newline = FileGetLine (stringfile, 1)

if (newline == line)
FileDeleteLine (stringFile, 1)
endif

endproc

Example 2:
The following example script inserts a line into and deletes a line from a file.
proc main ()

string stringFile, line, newline


textfilehandle texthandle

stringFile = 'c:\temp\file1.txt'
line = "new text line"
texthandle = TextFileOpen (stringfile

FileInsertLine (texthandle, 1, line + "\r\n")


newline = FileGetLine (texthandle, 1)

if (newline == line)
FileDeleteLine (texthandle, 1)
endif

TextFileClose (texthandle)

endproc

FileTextClose
Close an existing text file.
Syntax:
Bool FileTextClose (TextFileHandle TextHandle)
TextHandle is the reference to the handle of the text file returned by the FileTextOpen function.
Returns:
TRUE if the operation was successful, FALSE if the operation failed or the handle is invalid. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.
Comments:
Any text file function started by the FileTextOpen function must be terminated with the FileTextClose
function. If the FileTextClose operation was successful, the supplied handle to the text file becomes invalid
and can not be used any more.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 201

Example:
The following example searches a text file for a specific line.
proc main ()

textfilehandle texthandle
string filename, line, newline
int n
filename = "D:\\RefSysDir\install.log"
line = "new text line"
n = 1

if (FileIsText (filename) == TRUE)


texthandle = FileTextOpen (filename)
while (newline != line)

newline = FileGetLine (texthandle, n)


n=n+1
endwhile

FileTextClose (texthandle)
endif

endproc

FileTextOpen
Open a text file
Syntax:
TextFileHandle FileTextOpen (String FilePath)
FilePath is the full directory path of the text file to be opened.
Returns:
The handle to the text file archive which was opened if the operation was successful, or 0 if the function fails. If
the operation fails ErrCode is set to ERR_FILENOTVALID.
Comments:
If the supplied path exists, but the specified file is not a valid text file or does not exist, a runtime error occurs.
Any text file function started by the FileTextOpen function must be closed with the FileTextClose function.
Example:
The following example searches a text file for a specific line.
proc main ()

textfilehandle texthandle
string filename, line, newline
int n

filename = "D:\\RefSysDir\install.log"
line = "new text line"

if (FileIsText (filename) == TRUE)


texthandle = FileTextOpen (filename)

while (newline != line)


newline = FileGetLine (texthandle, n)
endwhile n=n+1

FileTextClose (texthandle)

endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


202 - BMC FootPrints Asset Core - Chilli Reference

endproc

17.7 File Date Functions


The File Date function group contains all functions getting information about the date and time of the last time a
file was written to.

Function OS Description
FileGetDay Get the day part of a file’s last write date

FileGetHour Get the hours of a file’s last write time

FileGetMinute Get the minutes of a file’s last write time

FileGetMonth Get the month of a file’s last write date

FileGetSecond Get the seconds of a file’s last write time

FileGetYear Get the year of a file’s last write date

FileGetDay
Return the day information of the last write date of the file.
Syntax:
Int FileGetDay (String FileName)
FileName is the relative or absolute path of the file.
Returns:
The integer value between 1 and 31 representing the day information of the last write date of the file. If the file
cannot be found, the return value is 0 and ErrCode is set to ERR_FILENOTFOUND.

FileGetHour
Return the hour information of the last write time of the file.
Syntax:
Int FileGetHour (String FileName)
FileName is the relative or absolute path of the file.
Returns:
The integer value between 0 and 23 representing the hour information of the last write time of the file. If the file
cannot be found, the return value is 0 and ErrCode is set to ERR_FILENOTFOUND.

FileGetMinute
Return the minutes information of the last write time of the file.
Syntax:
Int FileGetMinute (String FileName)
FileName is the relative or absolute path of the file.
Returns:
The integer value between 0 and 59 representing the minutes information of the last write time of the file. If the
file cannot be found, the return value is 0 and ErrCode is set to ERR_FILENOTFOUND.

FileGetMonth
Return the month information of the last write date of the file.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 17 - File Functions - 203

Syntax:
Int FileGetMonth (String FileName)
FileName is the relative or absolute path of the file.
Returns:
The integer value between 1 and 12 representing the month information of the last write date of the file. If the file
cannot be found, the return value is 0 and ErrCode is set to ERR_FILENOTFOUND.

FileGetSecond
Return the seconds information of the last write time of the file.
Syntax:
Int FileGetSecond (String FileName)
FileName is the relative or absolute path of the file.
Returns:
The integer value between 0 and 59 representing the seconds information of the last write time of the file. If the
file cannot be found, the return value is 0 and ErrCode is set to ERR_FILENOTFOUND.

FileGetYear
Return the year information of the last write date of the file.
Syntax:
Int FileGetYear (String FileName)
FileName is the relative or absolute path of the file.
Returns:
The integer value representing the year information of the last write date of the file. If the file cannot be found, the
return value is 0 and ErrCode is set to ERR_FILENOTFOUND.

17.7.1 Example
The following example checks if a file is still the same after compressing and decompressing it and if so prints the
date and time information of the file.
proc main ()

string newfile, oldfile


oldfile = "c:\\temp\\file1.txt"
newfile = "c:\\temp\\file2.txt"

if (FileCompare (oldfile, newfile) == TRUE)


Print (LogFile, "Compression/Decompression OK\r\n")
Print (LogFile, "File Date:\r\n")
Print (LogFile, MakeStr (FileGetYear (oldfile)) + "/")
Print (LogFile, MakeStr (FileGetMonth (oldfile)) + "/")
Print (LogFile, MakeStr (FileGetDay (oldfile)))
Print (LogFile, "\r\n")
Print (LogFile, "at ")
Print (LogFile, MakeStr (FileGetHour (oldfile)) + ":")
Print (LogFile, MakeStr (FileGetMinute (oldfile)) + ":")
Print (LogFile, MakeStr (FileGetsecond (oldfile)))
Print (LogFile, "\r\n")
endif

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


204 - BMC FootPrints Asset Core - Chilli Reference

17.8 Example
The following code sample illustrates the file functions.
proc FileFunctions ()

int versionH, versionL, version23


textfilehandle texthandle
inifilehandle inihandle
string stringFile
string line, newline
string section1, section10, entry

stringFile = "C:\\chilli\\chilli.exe"
versionH = FileGetVersionH (stringFile)

if (versionH == 2)
versionL = FileGetVersionL (stringFile)
if (versionL == 3)
version23 = 1
else
version23 = 0
endif
else
version23 = 0
endif

stringFile = "C:\\temp\\test.ini"
if (FileIsText (stringFile) == TRUE)
if (FileIsIni (stringFile) == TRUE)
if (FileIsWritable (stringFile) == FALSE)
FileSetAttr (stringFile, 32)
endif

line = "new text line"


FileInsertLine (stringFile, 1, line + "\r\n")
newline = FileGetLine (stringFile, 1)

if (newline == line)
FileDeleteLine (stringFile, 1)
endif

inihandle = FileIniOpen (stringFile)


if (FileGetLineCount (inihandle) != 0)
if (FileGetSectionCount (inihandle) != 0)
section1 = FileGetSectionName (inihandle, 1)
section10 = FileGetSectionName (inihandle, 10)
if (FileGetEntryCount (inihandle, section10) != 0)
entry = FileGetEntryName (inihandle, section10, 1)
endif

endif
endif

FileIniClose (inihandle)
FileDeleteEntry (stringFile, section10, entry)
FileDeleteSection (stringFile, section1)

endif
endif

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


FTP Functions

This chapter explains all FTP (File Transfer Protocol) functions which are part of the Chilli language. All
functions of this module are included in the ftp.chx file for Windows or ftp.so file for UNIX and Linux.

18.1 Introduction
The FTP protocol is a TCP/IP protocol that enables users to copy files between systems and perform file
management functions, such as renaming or deleting files. It is a very common method of moving files between
two Internet sites. FTP provides a special way to login to another Internet site for the purposes of retrieving and/or
sending files.
This group of functions provides you with the possibility to create scripts which automatically establish
connections with FTP servers and execute file put or get actions as well as retrieve information from the server
when launched.

18.2 Predefined Constants


Following you find the complete list of all predefined constants of the FTP functions group of the Chilli script
language:

Name Type Description


FTP_DEFAULT_PORT Integer The default port of the FTP server

18.3 Error Codes


Following you find a list of all FTP error codes. These errors are run-time errors that causes the handler specified
in ErrorHandler to be invoked. Functions can return these in addition to the standard runtime errors such as
FUNCFAILED. You will find a list with all runtime errors in Appendix E - Chilli Error Codes on page 677 at the end
of the manual.

Name Description
ERR_FTPNOLOCALFILE Local file doesn't exist or can't be read/written
ERR_FTPNOLOCALSPACE Local disk does not have enough space
ERR_FTPNOMEMORY Not enough memory for file transfer buffer
ERR_FTPSYNTAXERROR Server does not recognise command
ERR_FTPBADSEQUENCE Server complained of bad sequence of commands
ERR_NOTLOGGEDIN User not logged on
ERR_NOPERMISSION Account required or no user permissions
ERR_FTPNOREMOTEFILE Remote file doesn't exist or can't be read/written
ERR_FTPNOREMOTESPACE Server does not have enough space

Numara Software, Inc. and BMC Software, Inc. Confidential.


206 - BMC FootPrints Asset Core - Chilli Reference

18.4 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli FTP function group has Predefined Handle Data Types.

18.4.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types used by the FTP functions:

Data Type Description


FtpHandle Object type: reference to the handle of an FTP connection

FtpHandle
The FtpHandle data type is a reference to the handle of the connection to the Ftp server.
A value of it is returned by the FtpConnect function and used by all other FTP functions as their first argument.
The open connection and thus the value must be closed with the FtpDisconnect function.

18.5 Functions
Following you find the list of all functions of the FTP function module.

Function OS Description
FtpCmdCwd Set the current working directory on a connected server

FtpCmdSite Execute a SITE command with given parameter on a connected server

FtpCmdStat Execute a STAT command of a given path on a connected server

FtpCmdUser Execute a USER command with given parameter on a connected server

FtpConnect Connect to the named FTP server at the specified port

FtpCreateDir Create a directory on a connected server

FtpDeleteDir Delete a directory on a connected server

FtpDeleteFile Delete a file on a connected server

FtpDisconnect Disconnect a connection to an FTP server

FtpGetCurrentDir Return the current working directory on a connected server

FtpGetFile Get a file from a server using FTP

FtpGetNameList Execute an NLST command on a connected server

FtpGetServerStatus Returns the last known status from the FTP server

FtpLogin Perform an FTP login to a connected server

FtpPutFile Put a file on a server using FTP

FtpRenameFile Rename a file on a connected server

FtpSetCurrentDir Set the current working directory on a connected server

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 18 - FTP Functions - 207

FtpCmdCwd
Set the current working directory on a connected server.
Syntax:
String FtpCmdCwd (FtpHandle Ftp, String Directory)
Ftp is the handle to the established connection to the FTP server.
Directory is the absolute or relative path of the working directory.
Returns:
A string containing the server response (FTP code + server text). If an error occurs, the returned string is empty.
Example:
FtpCmdCwd (FtpHandle, string):

# Connect to the server

FtpHandle hFtp
hFtp = FtpConnect (szIpAddress, iPort)

if (hFtp == 0)
Print ("Failed to connect to ["+ szIpAddress +"] on port ["+ iPort +"]. Exiting...")
return
endif

# Log onto it using the given parameters

if (FtpLogin (hFtp, szFtpUser, szFtpPassword))


Print ("Successfully logged on.")
else
Print ("Failed to log on using ["+ szFtpUser +"] - ["+ szFtpPassword +"]. Exiting...")
return
endif

# Use the CWD command with raw parameter

string strResult
strResult = FtpCmdCwd (hFtp, "/")
Print ("CWD / command result: RawData ["+ strResult +"]")

FtpCmdSite
Execute a SITE command with a given parameter on a connected server.
Syntax:
String FtpCmdSite (FtpHandle Ftp, String Param)
Ftp is the handle to the established connection to the FTP server.
Param is the parameter for the SITE command execution.
Returns:
A string containing the server response (FTP code + server text). If an error occurs, the returned string is empty.
Example:
# Connect to the server

FtpHandle hFtp

Numara Software, Inc. and BMC Software, Inc. Confidential.


208 - BMC FootPrints Asset Core - Chilli Reference

hFtp = FtpConnect (szIpAddress, iPort)

if (hFtp == 0)
Print ("Failed to connect to ["+ szIpAddress +"] on port ["+ iPort +"]. Exiting...")
return
endif

# Log onto it using the given parameters

if (FtpLogin (hFtp, szFtpUser, szFtpPassword))


Print ("Successfully logged on.")
else
Print ("Failed to log on using ["+ szFtpUser +"] - ["+ szFtpPassword +"]. Exiting...")
return
endif

# Use the SITE command with raw parameter

string strResult
strResult = FtpCmdSite (hFtp, "UNZIP zipfile.zip")
Print ("SITE UNZIP zipfile.zip command result: RawData ["+ strResult +"]")

FtpCmdStat
Execute a STAT command of a given path on a connected server.
Syntax:
String FtpCmdStat (FtpHandle Ftp, String ServerPath)
Ftp is the handle to the established connection to the FTP server.
ServerPath is the absolute or relative path of the server.
Returns:
A string containing the server response (FTP code + server text). If an error occurs, the returned string is empty.
Example:
# Connect to the server

FtpHandle hFtp
hFtp = FtpConnect (szIpAddress, iPort)

if (hFtp == 0)
Print ("Failed to connect to ["+ szIpAddress +"] on port ["+ iPort +"]. Exiting...")
return
endif

# Log onto it using the given parameters

if (FtpLogin (hFtp, szFtpUser, szFtpPassword))


Print ("Successfully logged on.")
else
Print ("Failed to log on using ["+ szFtpUser +"] - ["+ szFtpPassword +"]. Exiting...")
return
endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 18 - FTP Functions - 209

# Use the STAT command with null parameter

string strResult
strResult = FtpCmdStat (hFtp, "")
Print ("Server overall status: RawData ["+ strResult +"]")

FtpCmdUser
Execute a USER command with a given parameter on a connected server.
Syntax:
String FtpCmdUser (FtpHandle Ftp, String Param)
Ftp is the handle to the established connection to the FTP server.
Param is the parameter for the USER command execution.
Returns:
A string containing the server response (FTP code + server text). If an error occurs, the returned string is empty.
Example:
# Connect to the server

FtpHandle hFtp
hFtp = FtpConnect (szIpAddress, iPort)

if (hFtp == 0)
LogPrint ("Failed to connect to ["+ szIpAddress +"] on port ["+ iPort +"]. Exiting...")
return
endif

# Use the USER command with given parameter

string strResult
strResult = FtpCmdUser (hFtp, "admin")
Print ("USER admin command result: RawData ["+ strResult +"]")

FtpConnect
Connect to the named FTP server at the specified port.
Syntax:
FtpHandle FtpConnect (String Server, Int Port)
Server is the name or IP address in dotted notation of the ftp server with which the connection is to be
established.
Port is the port number on the ftp server.
Syntax:
If the connection is successfully established the function returns a handle to the connection which is to be used
by all other FTP functions. If the function fails, 0 is returned.
Comments:
The port is normally expected to be FTP_DEFAULT_PORT.
Example:
The following script example runs a number of tests in an ftp connection.
proc DoFtpTests (FtpHandle ftp)

Numara Software, Inc. and BMC Software, Inc. Confidential.


210 - BMC FootPrints Asset Core - Chilli Reference

int error, i;
string Files[]
FtpSetCurrentDir (ftp, "/tmp")
FtpDeleteFile (ftp, "ftp.chl")
FtpCreateDir (ftp, "batman")
FtpSetCurrentDir (ftp, "batman");
print ("Now in " + FtpGetCurrentDir (ftp) + "\n")
FtpPutFile (ftp, "ftp.chl", "")
FtpRenameFile (ftp, "ftp.chl", "ftp.copy")
Files = FtpGetNameList (ftp)
for (i=1; i<= ArrayGetSize (Files); i+=1)
print (Files[i] + "\n")
endfor
endproc

proc main ()
string depot, user, password
FtpHandle ftp

//DoFtpGet ()
depot="sparc"
user = "spectrum"
password="spectrum"
ErrHandler = INLINE_HANDLER
ftp = FtpConnect (depot, FTP_DEFAULT_PORT)
FtpLogin (ftp, user, password)
DoFtpTests (ftp)
FtpDisconnect (ftp);

endproc

FtpCreateDir
Create a directory on a connected server.
Syntax:
String FtpCreateDir (FtpHandle Ftp, String Directory)
Ftp is the handle to the established connection to the FTP server.
Directory is the absolute or relative path of the directory to create.
Returns:
A string containing the path reported by the server if the create operation was successful or an empty string if the
operation failed.
Example:
The following script example runs a number of tests in an ftp connection.
proc DoFtpTests (FtpHandle ftp)

int error, i;
string Files[]
FtpSetCurrentDir (ftp, "/tmp")
FtpDeleteFile (ftp, "ftp.chl")
FtpCreateDir (ftp, "batman")
FtpSetCurrentDir (ftp, "batman");
print ("Now in " + FtpGetCurrentDir (ftp) + "\n")
FtpPutFile (ftp, "ftp.chl", "")
FtpRenameFile (ftp, "ftp.chl", "ftp.copy")
Files = FtpGetNameList (ftp)
for (i=1; i<= ArrayGetSize (Files); i+=1)
print (Files[i] + "\n")

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 18 - FTP Functions - 211

endfor
endproc

proc main ()
string depot, user, password
FtpHandle ftp

//DoFtpGet ()
depot="sparc"
user = "spectrum"
password="spectrum"
ErrHandler = INLINE_HANDLER
ftp = FtpConnect (depot, FTP_DEFAULT_PORT)
FtpLogin (ftp, user, password)
DoFtpTests (ftp)
FtpDisconnect (ftp);

endproc

FtpDeleteDir
Delete a directory on a connected server.
Syntax:
Bool FtpDeleteDir (FtpHandle Ftp, String Directory)
Ftp is the handle to the established connection to the FTP server.
Directory is the absolute or relative path of the directory to delete.
Returns:
TRUE if the destroy operation was successful, FALSE if the operation failed. If the function fails, ErrCode is set to
one of the FTP specific error codes or a general error code.
Example:
The following script example runs a number of tests in an ftp connection.
proc DoFtpTests (FtpHandle ftp)

int error, i;
string Files[]
FtpSetCurrentDir (ftp, "/tmp")
FtpDeleteFile (ftp, "ftp.chl")
FtpCreateDir (ftp, "batman")
FtpSetCurrentDir (ftp, "batman");
print ("Now in " + FtpGetCurrentDir (ftp) + "\n")
FtpPutFile (ftp, "ftp.chl", "")
FtpRenameFile (ftp, "ftp.chl", "ftp.copy")
Files = FtpGetNameList (ftp)
for (i=1; i<= ArrayGetSize (Files); i+=1)
print (Files[i] + "\n")
endfor
endproc

proc main ()
string depot, user, password
FtpHandle ftp

//DoFtpGet ()
depot="sparc"
user = "spectrum"
password="spectrum"
ErrHandler = INLINE_HANDLER

Numara Software, Inc. and BMC Software, Inc. Confidential.


212 - BMC FootPrints Asset Core - Chilli Reference

ftp = FtpConnect (depot, FTP_DEFAULT_PORT)


FtpLogin (ftp, user, password)
DoFtpTests (ftp)
FtpDisconnect (ftp);

endproc

FtpDeleteFile
Delete a file on a connected server.
Syntax:
Bool FtpDeleteFile (FtpHandle Ftp, String File)
Ftp is the handle to the established connection to the FTP server.
File is the absolute or relative path of the file to be deleted.
Returns:
TRUE if the destroy operation was successful, FALSE if the operation failed. If the function fails, ErrCode is set to
one of the FTP specific error codes or a general error code.
Comments:
The file path can be relative to the current working directory on the server or absolute.
Example:
The following script example runs a number of tests in an ftp connection.
proc DoFtpTests (FtpHandle ftp)

int error, i;
string Files[]
FtpSetCurrentDir (ftp, "/tmp")
FtpDeleteFile (ftp, "ftp.chl")
FtpCreateDir (ftp, "batman")
FtpSetCurrentDir (ftp, "batman");
print ("Now in " + FtpGetCurrentDir (ftp) + "\n")
FtpPutFile (ftp, "ftp.chl", "")
FtpRenameFile (ftp, "ftp.chl", "ftp.copy")
Files = FtpGetNameList (ftp)
for (i=1; i<= ArrayGetSize (Files); i+=1)
print (Files[i] + "\n")
endfor
endproc

proc main ()
string depot, user, password
FtpHandle ftp

//DoFtpGet ()
depot="sparc"
user = "spectrum"
password="spectrum"
ErrHandler = INLINE_HANDLER
ftp = FtpConnect (depot, FTP_DEFAULT_PORT)
FtpLogin (ftp, user, password)
DoFtpTests (ftp)
FtpDisconnect (ftp);

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 18 - FTP Functions - 213

FtpDisconnect
Disconnect a connection to an FTP server.
Syntax:
Bool FtpDisconnect (FtpHandle Ftp)
Ftp is the handle to the established connection to the FTP server.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the function fails, ErrCode is set to one of
the FTP specific error codes or a general error code.
Comments:
After this call, whether successful or not, the supplied FtpHandle is no longer valid.
Example:
The following script example runs a number of tests in an ftp connection.
proc DoFtpTests (FtpHandle ftp)

int error, i;
string Files[]
FtpSetCurrentDir (ftp, "/tmp")
FtpDeleteFile (ftp, "ftp.chl")
FtpCreateDir (ftp, "batman")
FtpSetCurrentDir (ftp, "batman");
print ("Now in " + FtpGetCurrentDir (ftp) + "\n")
FtpPutFile (ftp, "ftp.chl", "")
FtpRenameFile (ftp, "ftp.chl", "ftp.copy")
Files = FtpGetNameList (ftp)

for (i=1; i<= ArrayGetSize (Files); i+=1)


print (Files[i] + "\n")
endfor

endproc

proc main ()

string depot, user, password


FtpHandle ftp;

//DoFtpGet ()

depot="sparc"
user = "spectrum"
password="spectrum"
ErrHandler = INLINE_HANDLER;
ftp = FtpConnect (depot, FTP_DEFAULT_PORT)
FtpLogin (ftp, user, password)
DoFtpTests (ftp)
FtpDisconnect (ftp);

endproc

FtpGetCurrentDir
Return the current working directory on a connected server.
Syntax:
String FtpGetCurrentDir (FtpHandle Ftp)
Ftp is the handle to the established connection to the FTP server.

Numara Software, Inc. and BMC Software, Inc. Confidential.


214 - BMC FootPrints Asset Core - Chilli Reference

Returns:
A string containing the absolute path of the current working directory if the operation was successful or an empty
string, if the operation failed.
Example:
The following example shows a procedure which recourses through a directory structure and prints the files it
finds at each level.
proc FtpListDirectory (FtpHandle ftp, string szDir, string szPad)

int error, i
string szCurrentDir, Files[]
error = !FtpSetCurrentDir (ftp, szDir);

if (error == 0)
szCurrentDir = FtpGetCurrentDir (ftp);
print (szPad + szCurrentDir + "\n");
Files = FtpGetNameList (ftp)
for (i=1; i<= ArrayGetSize (Files); i+=1)
FtpListDirectory (ftp, Files[i], szPad + " ")
FtpSetCurrentDir (ftp, szCurrentDir);
endfor
else
print (szPad + szDir + "\n");
endif

endproc

proc main ()

string depot, user, password


FtpHandle ftp
depot="sparc"
user = "spectrum"
password="spectrum"
ErrHandler = INLINE_HANDLER
ftp = FtpConnect (depot, FTP_DEFAULT_PORT)
FtpLogin (ftp, user, password)
FtpListDirectory (ftp, "/etc", "")
FtpDisconnect (ftp)

endproc

FtpGetFile
Get a file from a server using the FTP protocol.
This function has the following different signatures:
Syntax:
Bool FtpGetFile (String Server, String User, String Password, String ServerPath, String
LocalPath)
Server is the host name or the IP address of the server to access.
User is the user login name to use for the Server.
Password is the login password for the user on the server.
ServerPath is the path of the file on the server.
LocalPath is the path of the file on the local machine where the received copy is saved.
Bool FtpGetFile (FtpHandle Ftp, String ServerPath, String LocalPath)
Ftp is the handle to the established connection to the FTP server.
ServerPath is the absolute or relative path of the file on the server.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 18 - FTP Functions - 215

LocalPath is the absolute or relative path of the file on the local machine where the received copy is saved.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the function fails, ErrCode is set to one of
the FTP specific error codes or a general error code.
Comments:
The FTP transfer always uses a BINARY transfer regardless of the type of file being read.
The first signature is like a short procedure in itself, which creates the connection to the server, executes the get
function and closes the connection. It can therefore stand all by itself and has no need of any other Ftp function
such as FtpConnect, FtpLogin, FtpDisconnect, and so on.
The second signature works on an FtpHandle object which represents an already established connection to an
FTP server. It cannot be used only by itself like the first signature, but must always be used in combination with
the FtpConnect, FtpLogin, FtpDisconnect, etc, functions. The received file is placed in the supplied local
path. If the supplied local path is an empty string, the server path is used.
Example:
The following script example recovers and puts a file on a remote location through either ftp or smb.
proc main ()

string Server, ShareName, SrcPath, szPackage, szSrcPath


string Name, Password, NewPath, File, NewFile
int smb

Server = "Server"
ShareName = "Shared"
SrcPath = ’\pub\test\test1\’
Name = "anonymous"
Password = "passwd"
NewPath = ’C:\temp\’
File = ’chilli.exe’

smb = SmbGetFile (Server, Name, Password, ShareName, SrcPath + File, NewPath + File)
if (smb == 0)
Print (LogFile, "Failed to get " + szPackage + " from the ")
FtpGetFile (Server, Name, Password, szSrcPath + File, NewPath + File)

if (ErrCode == 0)
NewFile = "chilli2.exe"
FtpPutFile (Server, Name, Password, NewPath + File, SrcPath + NewFile)
endif

else
Print (LogFile, "The package has been successfully downloaded\r\n")
NewFile = "chilli2.exe"
SmbPutFile (Server, Name, Password, ShareName, NewPath + File, SrcPath + NewFile)
endif

endproc

FtpGetNameList
Execute an NLST command on a connected server.
Syntax:
String[] FtpGetNameList (FtpHandle Ftp)
Ftp is the handle to the established connection to the FTP server.
Returns:
An array of strings containing the file names if the operation was successful or an empty array if the function
failed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


216 - BMC FootPrints Asset Core - Chilli Reference

Example:
The following example shows a procedure which recurses through a directory structure and prints the files it
finds at each level.
proc FtpListDirectory (FtpHandle ftp, string szDir, string szPad)
int error, i
string szCurrentDir, Files[]
error = !FtpSetCurrentDir (ftp, szDir)
if (error == 0)
szCurrentDir = FtpGetCurrentDir (ftp);
print (szPad + szCurrentDir + "\n");
Files = FtpGetNameList (ftp)
for (i=1; i<= ArrayGetSize (Files); i+=1)
FtpListDirectory (ftp, Files[i], szPad + " ")
FtpSetCurrentDir (ftp, szCurrentDir);
endfor
else
print (szPad + szDir + "\n");
endif
endproc
proc main ()
string depot, user, password
FtpHandle ftp
depot="sparc"
user = "spectrum"
password="spectrum"
ErrHandler = INLINE_HANDLER
ftp = FtpConnect (depot, FTP_DEFAULT_PORT)
FtpLogin (ftp, user, password)
FtpListDirectory (ftp, "/etc", "")
FtpDisconnect (ftp)
endproc

FtpGetServerStatus
Returns the last known status from the FTP server.
Syntax:Syntax
Int FtpGetServerStatus (FtpHandle Ftp)
Ftp is the handle to the established connection to the FTP server.
Returns:
The integer value of the last known status of the FTP server if the operation was successful, or 0 if the function
failed.
Comments:
The value returned is one of the FTP status codes as defined in RFC 959.
Example:
The following script example tries to recover a file from a remote location through ftp.
proc DoFtpGet ()
int error
string depotpath, packagefile, depot, user, password
ftphandle ftp
depot="sparc"
user = "spectrum"
password="spectrum"
depotpath = ""
packagefile = depotpath + "/ww24_16.zip"
ErrHandler = INLINE_HANDLER

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 18 - FTP Functions - 217

print ("Doing get...\n")


ftp = FtpConnect (depot, FTP_DEFAULT_PORT)
error = FtpGetFile (depot, user, password, packagefile, "")
if (error == 0)
error = ErrCode;
print ("FTP error " + error + " = " + GetErrorName (error) + "\n");
print (GetErrorText (error) + "\n")
print ("Server Status = " + MakeStr (FtpGetServerStatus (ftp)) + ".\n\r")
endif
FtpDisconnect (ftp)
endproc

proc main ()
DoFtpGet ()
endproc

FtpLogin
Perform an FTP login to a connected server.
Syntax:
Bool FtpLogin (FtpHandle Ftp, String UserName, String Password)
Ftp is the handle to the established connection to the FTP server.
UserName is the login name of the user for the login on the FTP server.
Password is the corresponding password of the user name login.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the function fails, ErrCode is set to one of
the FTP specific error codes or a general error code.
Example:
The following script example runs a number of tests in an ftp connection.
proc DoFtpTests (FtpHandle ftp)
int error, i;
string Files[]
FtpSetCurrentDir (ftp, "/tmp")
FtpDeleteFile (ftp, "ftp.chl")
FtpCreateDir (ftp, "batman")
FtpSetCurrentDir (ftp, "batman");
print ("Now in " + FtpGetCurrentDir (ftp) + "\n")
FtpPutFile (ftp, "ftp.chl", "")
FtpRenameFile (ftp, "ftp.chl", "ftp.copy")
Files = FtpGetNameList (ftp)
for (i=1; i<= ArrayGetSize (Files); i+=1)
print (Files[i] + "\n")
endfor
endproc

proc main ()
string depot, user, password
FtpHandle ftp

//DoFtpGet ()
depot="sparc"
user = "spectrum"
password="spectrum"
ErrHandler = INLINE_HANDLER
ftp = FtpConnect (depot, FTP_DEFAULT_PORT)
FtpLogin (ftp, user, password)

Numara Software, Inc. and BMC Software, Inc. Confidential.


218 - BMC FootPrints Asset Core - Chilli Reference

FtpListDirectory (ftp, "/etc", "")


DoFtpTests (ftp)
FtpDisconnect (ftp)
endproc

FtpPutFile
Put a file on a server using the FTP protocol.
This function has the following different signatures:
Syntax:
Bool FtpPutFile (String Server, String User, String Password, String ServerPath, String
LocalPath)
Server is the host name or the IP address of the server to access.
User is the user login name to use for the Server.
Password is the login password for the user on the server.
ServerPath is the path of the file on the server.
LocalPath is the path of the file on the local system which is sent.
Bool FtpPutFile (FtpHandle Ftp, String LocalPath, String ServerPath)
Ftp is the handle to the established connection to the FTP server.
ServerPath is the absolute or relative path of the file on the server.
LocalPath is the absolute or relative path of the file on the local system which is sent.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the function fails, ErrCode is set to one of
the FTP specific error codes or a general error code.
Comments:
The FTP transfer always uses a BINARY transfer regardless of the type of file being read.
The first signature is like a short procedure in itself, which creates the connection to the server, executes the put
function and closes the connection. It can therefore stand all by itself and has no need of any other Ftp function
such as FtpConnect, FtpLogin, FtpDisconnect, and so on.
The second signature works on an FtpHandle object which represents an already established connection to an
FTP server. It cannot be used only by itself like the first signature, but must always be used in combination with
the FtpConnect, FtpLogin, FtpDisconnect, and so on, functions. If the supplied server path is an empty
string, the local path is used for the server. Note that the order of the server and local paths is different to the first
signature. The order here is the normal order of from->to.
Example:
The following script example recovers and puts a file on a remote location through either ftp or smb.
proc main ()

string Server, ShareName, SrcPath, szPackage, szSrcPath


string Name, Password, NewPath, File, NewFile
int smb

Server = "Server"
ShareName = "Shared"
SrcPath = ’\pub\test\test1\’
Name = "anonymous"
Password = "passwd"
NewPath = ’C:\temp\’
File = ’chilli.exe’

smb = SmbGetFile (Server, Name, Password, ShareName, SrcPath + File, NewPath + File)
if (smb == 0)
Print (LogFile, "Failed to get " + szPackage + " from the ")
FtpGetFile (Server, Name, Password, szSrcPath + File, NewPath + File)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 18 - FTP Functions - 219

if (ErrCode == 0)
NewFile = "chilli2.exe"
FtpPutFile (Server, Name, Password, NewPath + File, SrcPath + NewFile)
endif

else
Print (LogFile, "The package has been successfully downloaded\r\n")
NewFile = "chilli2.exe"
SmbPutFile (Server, Name, Password, ShareName, NewPath + File, SrcPath + NewFile)
endif

endproc

FtpRenameFile
Rename a file on a connected server.
Syntax:
Bool FtpRenameFile (FtpHandle Ftp, String SrcFile, String DstFile)
Ftp is the handle to the established connection to the FTP server.
SrcFile is the original path and name of the file to be renamed.
DstFile is the new path and name of the file to be renamed.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the function fails, ErrCode is set to one of
the FTP specific error codes or a general error code.
Comments:
The file paths can be relative to the current working directory on the server or absolute.
Example:
The following script example runs a number of tests in an ftp connection.
proc DoFtpTests (FtpHandle ftp)
int error, i
string Files[]
FtpSetCurrentDir (ftp, "/tmp")
FtpDeleteFile (ftp, "ftp.chl")
FtpCreateDir (ftp, "batman")
FtpSetCurrentDir (ftp, "batman")
print ("Now in " + FtpGetCurrentDir (ftp) + "\n")
FtpPutFile (ftp, "ftp.chl", "")
FtpRenameFile (ftp, "ftp.chl", "ftp.copy")
Files = FtpGetNameList (ftp)
for (i=1; i<= ArrayGetSize (Files); i+=1)
print (Files[i] + "\n")
endfor
endproc

proc main ()
string depot, user, password
FtpHandle ftp

//DoFtpGet ()
depot="sparc"
user = "spectrum"
password="spectrum"
ErrHandler = INLINE_HANDLER

Numara Software, Inc. and BMC Software, Inc. Confidential.


220 - BMC FootPrints Asset Core - Chilli Reference

ftp = FtpConnect (depot, FTP_DEFAULT_PORT)


FtpLogin (ftp, user, password)f
DoFtpTests (ftp)
FtpDisconnect (ftp)
Print ("The Script has terminated.\r\n")

endproc

FtpSetCurrentDir
Set the current working directory on a connected server.
Syntax:
Bool FtpSetCurrentDir (FtpHandle Ftp, String Directory)
Ftp is the handle to the established connection to the FTP server.
Directory is the absolute or relative path of the target directory.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the function fails, ErrCode is set to one of
the FTP specific error codes or a general error code.
Example:
The following example shows a procedure which recourses through a directory structure and prints the files it
finds at each level.
proc FtpListDirectory (FtpHandle ftp, string szDir, string szPad)
int error, i
string szCurrentDir, Files[]
error = !FtpSetCurrentDir (ftp, szDir)
if (error == 0)
szCurrentDir = FtpGetCurrentDir (ftp);
print (szPad + szCurrentDir + "\n");
Files = FtpGetNameList (ftp)
for (i=1; i<= ArrayGetSize (Files); i+=1)
FtpListDirectory (ftp, Files[i], szPad + " ")
FtpSetCurrentDir (ftp, szCurrentDir);
endfor
else
print (szPad + szDir + "\n");
endif
endproc
proc main ()
string depot, user, password
FtpHandle ftp
depot="sparc"
user = "spectrum"
password="spectrum"
ErrHandler = INLINE_HANDLER
ftp = FtpConnect (depot, FTP_DEFAULT_PORT)
FtpLogin (ftp, user, password)
FtpListDirectory (ftp, "/etc", "")
FtpDisconnect (ftp)
endproc

18.6 Example
The following code sample illustrates the ftp functions.
/***********************************************************************

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 18 - FTP Functions - 221

FtpListDirectory
Recurses through a directory structure and prints the files it finds
at each level.
***********************************************************************/

proc FtpListDirectory (FtpHandle ftp, string szDir, string szPad)


int error, i
string szCurrentDir, Files[]
error = !FtpSetCurrentDir (ftp, szDir)

if (error == 0)
szCurrentDir = FtpGetCurrentDir (ftp)
print (szPad + szCurrentDir + "\n")
Files = FtpGetNameList (ftp)
for (i=1; i<= ArrayGetSize (Files); i+=1)
FtpListDirectory (ftp, Files[i], szPad + " ")
FtpSetCurrentDir (ftp, szCurrentDir)
endfor
else
print (szPad + szDir + "\n")
endif
endproc

proc DoFtpTests (FtpHandle ftp)


int error, i
string Files[]
FtpSetCurrentDir (ftp, "/tmp")
FtpDeleteFile (ftp, "ftp.chl")
FtpCreateDir (ftp, "bahman")
FtpSetCurrentDir (ftp, "bahman")
print ("Now in " + FtpGetCurrentDir (ftp) + "\n")

FtpPutFile (ftp, "ftp.chl", "")


FtpRenameFile (ftp, "ftp.chl", "ftp.copy")

Files = FtpGetNameList (ftp)


for (i=1; i<= ArrayGetSize (Files); i+=1)
print (Files[i] + "\n")
endfor
endproc

proc main ()
string depot, user, password
FtpHandle ftp

depot="sparc"
user = "spectrum"
password="spectrum"

ErrHandler = INLINE_HANDLER
ftp = FtpConnect (depot, FTP_DEFAULT_PORT)
FtpLogin (ftp, user, password)
FtpListDirectory (ftp, "/etc", "")
DoFtpTests (ftp)

Numara Software, Inc. and BMC Software, Inc. Confidential.


222 - BMC FootPrints Asset Core - Chilli Reference

FtpDisconnect (ftp)
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Gif-Image Manipulation Functions

This chapter explains all features that handle the Gif image manipulation of the Chilli language. All functions of
this module are included in the gif.chx file for Windows or gif.so file for UNIX and Linux.

19.1 Introduction
Gif (graphics interchange format) is a common format for image files, especially suitable for images containing
large areas of the same color. This bit-mapped graphics file format is widely used by the Web and the CompuServe
for image representation.
The Gif functions group in Chilli enables you to create simple gif images on the fly via scripts, which can be used
in HTML pages. You can create new images as well as open and modify existing ones.
Be aware that the x- and y-axis references for the parameters of this module are not the same as in the general
mathematical sense. The 0 point for x and y is not the lower left hand corner, but the upper left hand corner:

19.2 Predefined Constants


Following you find the complete list of all predefined constants of the Gif Image Manipulation functions group of
the Chilli script language:

Name Type Description


GIF_BRUSHED Integer Used in place of a color when invoking a line-drawing function such as GifDrawLine or
GifDrawRectangle. When GIF_BRUSHED is used as the color, the brush image set with
GifSetBrush is drawn in place of each pixel of the line (the brush is usually larger than one pixel,
creating the effect of a wide paintbrush). See also GIF_STYLEDBRUSHED for a way to draw
broken lines with a series of distinct copies of an image.
GIF_FONTHUGE Integer Font of the character cell fixed width font family with a height of 15 pixels and a width of 9 pixels.
The characters are sans serif, of bold and upright stroke and have a normal setwidth. The
character set is ISO Latin2.
GIF_FONTLARGE Integer Font of the character cell fixed width font family with a height of 16 pixels and a width of 8 pixels.
The characters are of medium stroke and upright and have a normal setwidth. The character set is
ISO Latin2.
GIF_FONTMEDIUM Integer Font of the character cell fixed width font family with a height of 13 pixels and a width of 7 pixels.
The characters are sans serif, of bold and upright stroke and have a normal setwidth. The
character set is ISO Latin2.
GIF_FONTSMALL Integer Font of the character cell fixed width font family with a height of 12 pixels and a width of 6 pixels.
The characters are sans serif, of normal and upright stroke and have a semicondensed setwidth.
The character set is ISO Latin2.

Numara Software, Inc. and BMC Software, Inc. Confidential.


224 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


GIF_FONTTINY Integer Font of the character cell fixed width font family with a height of 8 pixels and a width of 5 pixels.
The characters are of medium and upright stroke and have a normal setwidth. The character set is
ISO Latin2.
GIF_MAXCOLOURS Integer The constant 256. This is the maximum number of colors in a GIF file according to the GIF
standard, and is also the maximum number of colors in a gd image.
GIF_STYLED Integer Used in place of a color when invoking a line-drawing function such GifDrawLine or
GifDrawRectangle. When GIF_STYLED is used as the color, the colors of the pixels are drawn
successively from the style that has been set with GifSetStyle. If the color of a pixel is equal to
GIF_TRANSPARENT, that pixel is not altered.
GIF_STYLEDBRUSHED Integer Used in place of a color when invoking a line-drawing function such as GifDrawLine or
GifDrawRectangle. When GIF_STYLEDBRUSHED is used as the color, the brush image set with
GifSetBrush is drawn at each pixel of the line, providing that the style set with GifSetStyle contains
a nonzero value (OR GIF_TRANSPARENT, which does not equal zero but is supported for
consistency) for the current pixel. Note that this differs from the behavior of GIF_STYLED, in which
the values in the style are used as actual pixel colors, except for GIF_TRANSPARENT.
GIF_TILED Integer Used in place of a normal color in GifDrawFilledRectangle, GifDrawFilledPolygon, GifFill, and
GifFillToBorder. GIF_TILED selects a pixel from the tile image set with GifSetTile in such a way as
to ensure that the filled area is tiled with copies of the tile image.
GIF_TRANSPARENT Integer Used in place of a normal color in a style to be set with GifSetStyle. GIF_TRANSPARENT is not the
transparent color index of the image; for that functionality see GifSetTransparent function.

19.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli Gif Image Manipulation function group has predefined data
types of types handle and structure.

19.3.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


GifImage Object type: reference to GIF image handle

GifImage
The GifImage data type is a reference to the handle of a Gif image.
The function GifCreateImage returns this object type and most of the other functions expect it as their first
argument. The data type should be closed by the GifDestroyImage function.

19.3.2 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated. For each predefined structure an array type of this structure also exists for usage
in the scripts.
Following you find a list of all predefined data types of type structure:

Data Type Description


GifHsvTriplet Define the HSV values of a color in a GIF image
GifPoint Define coordinates (x and y position) of a point in a GIF image
GifRgbTriplet Define the RGB values of a color in a GIF image

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 19 - Gif-Image Manipulation Functions - 225

GifHsvTriplet
The GifHsvTriplet structure represents the Hue, Saturation and Value indices of the supplied color in a gif
image.
This structure is used by the color conversion functions GifRgbToHsv and GifHsvToRgb.
Elements:

Elements Element Type Description


Hue integer The hue value of the supplied color index in a Gif image.
Saturation integer The saturation value of the supplied color index in a Gif image.
Value integer The value of the supplied color index in a Gif image.

GifPoint
The GifPoint structure represents a point in the coordinate space of a Gif image.
This structure is used by the polygon functions.
Elements:

Elements Element Type Description


x integer Coordinate of the point on the x-axis.
y integer Coordinate of the point on the y-axis.

GifRgbTriplet
The GifRgbTriplet structure represents the color indices of the blue, green and red components of the supplied
color in a gif image.
This structure is used by the color conversion functions GifRgbToHsv and GifHsvToRgb.
Elements:

Elements Element Type Description


Red integer The red component of the supplied color index in a Gif image.
Green integer The green component of the supplied color index in a Gif image.
Blue integer The blue component of the supplied color index in a Gif image.

19.4 Functions
Following you find a list of all available Gif-Image Manipulation functions in Chilli:

Function OS Description
GifAllocateColour Allocate a color in the color table of the image

GifCreateImage Create a GIF image

GifDestroyImage Close all remaining GD handles

GifDrawArc Draw an arc in an image

GifDrawFilledPolygon Draw a filled multi-point polygon in an image

GifDrawFilledRectangle Draw a filled rectangle in an image

GifDrawLine Draw a straight line in an image

GifDrawPolygon Draw a multi-point polygon in an image

GifDrawRectangle Draw a rectangle in a gif image

Numara Software, Inc. and BMC Software, Inc. Confidential.


226 - BMC FootPrints Asset Core - Chilli Reference

Function OS Description
GifDrawText Draw a text string in an image

GifDrawTextUp Draw a vertical text string in an image

GifFill Flood fill an area within an image

GifFillToBorder Flood fill an area within an image including the area’s borderline

GifGetColourBlue Get the blue component of the supplied color index in an image

GifGetColourClosest Get a color in the color table of the image which most closely matches the supplied
RGB values
GifGetColourExact Get a color in the color table of the image which exactly matches the supplied RGB
values
GifGetColourGreen Get the green component of the supplied color index in an image

GifGetColourRed Get the red component of the supplied color index in an image

GifGetFontHeight Get the height of a character in the specified font

GifGetFontWidth Get the width of a character in the specified font

GifGetImageHeight Get the width of an image

GifGetImageLength Get the height of an image

GifGetPixel Get the color index of an individual pixel in an image

GifGetTotalColours Get the total number of allocated colors in an image

GifGetTransparent Get the index of the transparent color in an image

GifHsvToRgb Convert the values in a HSV triplet to their equivalents in RGB

GifLoadImage Load a new image from a file

GifRgbToHsv Convert the values in a RGB triplet to their equivalents in HSV

GifSaveImage Save the image associated with the supplied handle to a file

GifSetBrush Set the image to be used for drawing shapes

GifSetPixel Set the color of an individual pixel in an image

GifSetStyle Set the drawing style of an image based on an array of colors

GifSetTile Set the image to be used for filling functions

GifSetTransparent Set the index of the transparent color in an image

GifAllocateColour
Allocate a color in the color table of the Gif image.
Syntax:
Int GifAllocateColour (GifImage Handle, Int R, Int G, Int B)
Handle is the reference to the Gif image handle.
R is the color index of red.
G is the color index of green.
B is the color index of blue.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 19 - Gif-Image Manipulation Functions - 227

Returns:
The index of the color if the operation was successful. In the event that all colors (256) have already been
allocated, GifAllocateColour returns -1 to indicate failure. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The GifAllocateColour function finds the first available color index in the Gif image specified, sets its RGB
values to those requested (255 is the maximum for each), and returns the index of the new color table entry. When
creating a new image, the first time you invoke this function, you are setting the background color for that image.
Note that GifAllocateColour does not check for existing colors that match your request, refer to the
GifGetColourExact and GifGetColourClosest functions for ways to locate existing colors that
approximate the intended color in situations where a new color is not available.
Example:
The following example script creates an oval button with a shadow around it, of which the color decreases in
depth with every turn.
proc main ()

// Create an oval button with a shadow around it. The shadow


// color decreases in depth with every turn.

int i, ShadowColour, Height, Width


GifImage ptrImage
Height = 50
Width = 150
ptrImage = GifCreateImage (Width, Height)

// 3 loops for shadow around button.


for (i=3; i>=1; i-=1)
//Color definition of the shadow.
ShadowColour = GifAllocateColour (ptrImage, 50*i, 50*i, 50*i)

// 2 horizontal lines for the upper and lower lines of the oval button
GifDrawLine (ptrImage, Height/2+i, i, (Width+i)-Height/2, i,
ShadowColour)
GifDrawLine (ptrImage, Height/2+i, (Height+i)-1, (Width+i)-Height/2,
(Height+i)-1, ShadowColour)

// 2 half circles (arches) on the left and right of the lines to


// connect the lines through an arch.
GifDrawArc (ptrImage, (Height/2+i)+1, (Height/2)+i, Height, Height, 90,
270, ShadowColour)
GifDrawArc (ptrImage, ((Width+i)-1)-Height/2, (Height/2)+i, Height,
Height, 270, 90, ShadowColour)

// Fill the button shape in the middle. Being flood fill, this
// ends up filling the whole button.

GifFillToBorder (ptrImage, Height+i, i+2, ShadowColour, ShadowColour)

endfor

GifDestroyImage (ptrImage)

endproc

GifCreateImage
Create a Gif image.
Syntax:
GifImage GifCreateImage (Int Length, Int Height)

Numara Software, Inc. and BMC Software, Inc. Confidential.


228 - BMC FootPrints Asset Core - Chilli Reference

Length is the width of the Gif image in pixels.


Height is the height of the Gif image in pixels.
Returns:
The reference to the handle of the newly created Gif image if the create operation was successful, or 0 if the Gif
image could not be created and the operation failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The image must be saved by the GifSaveImage function and must eventually be destroyed by the
GifDestroyImage function.
Example:
The following example script creates a button with a text written on it.
proc main ()

//Create a button with text.

int Index, ButtonFont, Foreground, ImgWidth, ImgHeight


GifImage ptrImage

ImgWidth = 250
ImgHeight = 250
ptrImage = GifCreateImage (ImgWidth, ImgHeight)

GifDrawFilledRectangle (ptrImage, 0, 0, ImgWidth, ImgHeight, Index)


GifDrawText (ptrImage, 80, 160, 'Stop', ButtonFont, Foreground)
if (GifSaveImage (ptrImage, 'Examples/buttons/' + 'Stop') == FALSE)
print ("Failed to save button GIF file in " + "Examples/buttons/" +
Stop")
endif

GifDestroyImage (ptrImage)

endproc

GifDestroyImage
Close an open GifImage handle.
Syntax:
Bool GifDestroyImage (GifImage Handle)
Handle is the reference to the Gif image handle.
Returns:
TRUE if the destroy operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
It is very important to save and close an open Gif image file before assigning a new image handle to the GifImage
variable or exiting the script.
Example:
The following example script creates a button with a text written on it.
proc main ()

//Create a button with text.

int Index, ButtonFont, Foreground, ImgWidth, ImgHeight


GifImage ptrImage

ImgWidth = 250
ImgHeight = 250

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 19 - Gif-Image Manipulation Functions - 229

ptrImage = GifCreateImage (ImgWidth, ImgHeight)

GifDrawFilledRectangle (ptrImage, 0, 0, ImgWidth, ImgHeight, Index)


GifDrawText (ptrImage, 80, 160, 'Stop', ButtonFont, Foreground)
if (GifSaveImage (ptrImage, 'Examples/buttons/' + 'Stop') == FALSE)
print ("Failed to save button GIF file in " + "Examples/buttons/" +
Stop")
endif

GifDestroyImage (ptrImage)

endproc

GifDrawArc
Draw an arc in a Gif image.
Syntax:
Bool GifDrawArc (GifImage Handle, Int X, Int Y, Int Length, Int Height, Int Start, Int End,
Int Color)
Handle is the reference to the Gif image handle.
X is the centre pixel position on the x-axis.
Y is the centre pixel position on the y-axis.
Length is the width of the arc.
Height is the height of the arc.
Start is the starting position of the arc in degrees.
End is the end position of the arc in degrees.
Color is the color index of the arc.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The GifDrawArc function is used to draw a partial ellipse centered at the X and Y
indicated coordinates. The arc begins at the position in degrees specified by Start and ends
at the position in degrees specified by End. A circle can be drawn by beginning from 1
degrees and ending at 360 degrees, with Height and Length being equal. The value of End
must always be greater than the value of Start. Values greater than 360 are interpreted as
(value - 360°).
The arc is drawn using the specified color index. Note that the color index can be an actual
color returned by the GifAllocateColour function, or one of GIF_STYLED,
GIF_BRUSHED, or GIF_STYLEDBRUSHED. For more information about this topic refer to
functions GifSetBrush, GifSetStyle and GifSetTile.
Example:
The following example script creates an oval button with a shadow around it, of which the color decreases in
depth with every turn.
proc main ()

// Create an oval button with a shadow around it. The shadow


// color decreases in depth with every turn.

int i, ShadowColour, Height, Width


GifImage ptrImage
Height = 50
Width = 150
ptrImage = GifCreateImage (Width, Height)

Numara Software, Inc. and BMC Software, Inc. Confidential.


230 - BMC FootPrints Asset Core - Chilli Reference

// 3 loops for shadow around button.


for (i=3; i>=1; i-=1)
//Color definition of the shadow.
ShadowColour = GifAllocateColour (ptrImage, 50*i, 50*i, 50*i)

// 2 horizontal lines for the upper and lower lines of the oval button
GifDrawLine (ptrImage, Height/2+i, i, (Width+i)-Height/2, i,
ShadowColour)
GifDrawLine (ptrImage, Height/2+i, (Height+i)-1, (Width+i)-Height/2,
(Height+i)-1, ShadowColour)

// 2 half circles (arches) on the left and right of the lines to


// connect the lines through an arch.
GifDrawArc (ptrImage, (Height/2+i)+1, (Height/2)+i, Height, Height, 90,
270, ShadowColour)
GifDrawArc (ptrImage, ((Width+i)-1)-Height/2, (Height/2)+i, Height,
Height, 270, 90, ShadowColour)

// Fill the button shape in the middle. Being flood fill, this
// ends up filling the whole button.

GifFillToBorder (ptrImage, Height+i, i+2, ShadowColour, ShadowColour)

endfor

GifDestroyImage (ptrImage)

endproc

GifDrawFilledPolygon
Draw a filled multi-point polygon in a Gif image.
Syntax:
Bool GifDrawFilledPolygon (GifImage Handle, GifPoint[] Coord, Int Color)
Handle is the reference to the Gif image handle.
Coord is the structure containing the coordinates of the polygon corners.
Color is the color index of the line.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The GifDrawFilledPolygon function is used to draw a filled polygon whereby at least three of its coordinates
must be specified through the array of GifPoints. The color index specified is used for the fill color. Note that
the color index can be an actual color returned by the GifAllocateColour, or one of GIF_STYLED,
GIF_BRUSHED, or GIF_STYLEDBRUSHED. For more information about this topic refer to functions
GifSetBrush, GifSetStyle and GifSetTile.

GifDrawFilledRectangle
Draw a filled rectangle in a Gif image.
Syntax:
Bool GifDrawFilledRectangle (GifImage Handle, Int X1, Int Y1, Int X2, Int Y2, Int Color)
Handle is the reference to the Gif image handle.
X1 is the pixel position on the x-axis of the top left rectangle corner.
Y1 is the pixel position on the y-axis of the top left rectangle corner.
X2 is the pixel position on the x-axis of the bottom right rectangle corner.
Y2 is the pixel position on the y-axis of the bottom right rectangle corner.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 19 - Gif-Image Manipulation Functions - 231

Color is the color index of the rectangle fill.


Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The GifDrawFilledRectangle function is used to draw a filled rectangle with two corners (upper left and
lower right) being specified. The color index specified is used for the fill color. Note that the color index can be an
actual color returned by the GifAllocateColour function, or one of GIF_STYLED, GIF_BRUSHED, or
GIF_STYLEDBRUSHED. For more information about this topic refer to functions GifSetBrush, GifSetStyle
and GifSetTile.
Example:
The following example script creates a rectangular button with text on it.
proc main ()

//Create a button with text.

int Index, ButtonFont, Foreground, ImgWidth, ImgHeight


GifImage ptrImage

ImgWidth = 250
ImgHeight = 250
ptrImage = GifCreateImage (ImgWidth, ImgHeight)

GifDrawFilledRectangle (ptrImage, 0, 0, ImgWidth, ImgHeight, Index)


GifDrawText (ptrImage, 80, 160, 'Stop', ButtonFont, Foreground)
if (GifSaveImage (ptrImage, 'Examples/buttons/' + 'Stop') == FALSE)
print ("Failed to save button GIF file in " + "Examples/buttons/" +
Stop")
endif

GifDestroyImage (ptrImage)

endproc

GifDrawLine
Draw a straight line in a Gif image.
Syntax:
Bool GifDrawLine (GifImage Handle, Int X1, Int Y1, Int X2, Int Y2, Int Color)
Handle is the reference to the Gif image handle.
X1 is the pixel position on the x-axis of the starting point of the line.
Y1 is the pixel position on the y-axis of starting point of the line.
X2 is the pixel position on the x-axis of the end point of the line.
Y2 is the pixel position on the y-axis of the end point of the line.
Color is the color index of the line.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
This function is used to draw a straight line between two endpoints defined through the x and y coordinates. The
line is drawn using the specified color index. Note that the color index can be an actual color returned by the
GifAllocateColour function, or one of GIF_STYLED, GIF_BRUSHED, or GIF_STYLEDBRUSHED. For more
information about this topic refer to functions GifSetBrush, GifSetStyle and GifSetTile.

Numara Software, Inc. and BMC Software, Inc. Confidential.


232 - BMC FootPrints Asset Core - Chilli Reference

Example:
The following example script creates an oval button with a shadow around it, of which the color decreases in
depth with every turn.
proc main ()

// Create an oval button with a shadow around it. The shadow


// color decreases in depth with every turn.

int i, ShadowColour, Height, Width


GifImage ptrImage
Height = 50
Width = 150
ptrImage = GifCreateImage (Width, Height)

// 3 loops for shadow around button.


for (i=3; i>=1; i-=1)
//Color definition of the shadow.
ShadowColour = GifAllocateColour (ptrImage, 50*i, 50*i, 50*i)

// 2 horizontal lines for the upper and lower lines of the oval button
GifDrawLine (ptrImage, Height/2+i, i, (Width+i)-Height/2, i,
ShadowColour)
GifDrawLine (ptrImage, Height/2+i, (Height+i)-1, (Width+i)-Height/2,
(Height+i)-1, ShadowColour)

// 2 half circles (arches) on the left and right of the lines to


// connect the lines through an arch.
GifDrawArc (ptrImage, (Height/2+i)+1, (Height/2)+i, Height, Height, 90,
270, ShadowColour)
GifDrawArc (ptrImage, ((Width+i)-1)-Height/2, (Height/2)+i, Height,
Height, 270, 90, ShadowColour)

// Fill the button shape in the middle. Being flood fill, this
// ends up filling the whole button.

GifFillToBorder (ptrImage, Height+i, i+2, ShadowColour, ShadowColour)

endfor

GifDestroyImage (ptrImage)

endproc

GifDrawPolygon
Draw a multi-point polygon in a Gif image.
Syntax:
Bool GifDrawPolygon (GifImage Handle, GifPoint[] Coord, Int Color)
Handle is the reference to the Gif image handle.
Coord is the structure containing the coordinates of the polygon corners.
Color is the color index of the line.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 19 - Gif-Image Manipulation Functions - 233

Comments:
The GifDrawFilledPolygon function is used to draw a polygon whereby at least three of its coordinates must
be specified through the array of GifPoints. The polygon is drawn using the specified color index. Note that the
color index can be an actual color returned by the GifAllocateColour function, or one of GIF_STYLED,
GIF_BRUSHED, or GIF_STYLEDBRUSHED. For more information about this topic refer to functions
GifSetBrush, GifSetStyle and GifSetTile.

GifDrawRectangle
Draw a rectangle in a Gif image.
Syntax:
Bool GifDrawRectangle (GifImage Handle, Int X1, Int Y1, Int X2, Int Y2, Int Color)
Handle is the reference to the Gif image handle.
X1 is the pixel position on the x-axis of the top left rectangle corner.
Y1 is the pixel position on the y-axis of the top left rectangle corner.
X2 is the pixel position on the x-axis of the bottom right rectangle corner.
Y2 is the pixel position on the y-axis of the bottom right rectangle corner.
Color is the color index of the rectangle line.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The GifDrawFilledRectangle function is used to draw a rectangle with two corners (upper left and lower
right) being specified. The rectangle is drawn using the specified color index. Note that the color index can be an
actual color returned by the GifAllocateColour function, or one of GIF_STYLED, GIF_BRUSHED, or
GIF_STYLEDBRUSHED. For more information about this topic refer to functions GifSetBrush, GifSetStyle
and GifSetTile.
Example:
The following example script draws an empty rectangle with a tripple shadow around it.
proc main ()

// Draw an empty rectangle with a triple shadow around it.

int i, ShadowColour, Height, Width, Index, BtnHeight, BtnWidth, ButtonFont


GifImage ptrImage

Height = 50
Width = 150
ptrImage = GifCreateImage (Width, Height)

ButtonFont = GIF_FONTMEDIUM
Index = GifAllocateColour (ptrImage, 50*i, 50*i, 50*i)
BtnHeight = GifGetFontHeight (ButtonFont)*5 / 3
BtnWidth = StrLen ('Start') * GifGetFontWidth (ButtonFont) + BtnHeight

// Draw rectangle
GifDrawFilledRectangle (ptrImage, 0, 0, BtnWidth, BtnHeight, Index)

// Loop 3 times around the button, drawing a faded shadow

for (i=3; i>=1; i-=1)


ShadowColour = GifAllocateColour (ptrImage, 50*i, 50*i, 50*i)
GifDrawLine (ptrImage, 3-i, Height -i, Width-i, Height -i,ShadowColour)
GifDrawLine (ptrImage, Width -i, 3-i, Width -i, Height-i, ShadowColour)
endfor

Numara Software, Inc. and BMC Software, Inc. Confidential.


234 - BMC FootPrints Asset Core - Chilli Reference

GifDestroyImage (ptrImage)

endproc

GifDrawText
Draw a horizontal text string in a Gif image.
Syntax:
Bool GifDrawText (GifImage Handle, Int X, Int Y, String Text, Int Font, Int Color)
Handle is the reference to the Gif image handle.
X is the position of the starting point of the text on the x-axis.
Y is the position of the starting point of the text on the y-axis of the text.
Text is the text string to be drawn into the Gif image.
Font is the index of the font to be used for the text string.
Color is the color index to be used for the text string.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The GifDrawText function is used to draw multiple characters on a Gif image. The text is drawn horizontally
from the left to the right departing at the starting point defined through the x and y coordinates in the specified
color. Pixels which are not set by a particular character retain their original color. The Font argument is a reference
to a font definition constant which can be one of the following five:

Name Description
GIF_FONTHUGE Font of the character cell fixed width font family with a height of 15 pixels and a width of 9 pixels. The
characters are sans serif, of bold and upright stroke and have a normal setwidth. The character set is ISO
Latin2.
GIF_FONTLARGE Font of the character cell fixed width font family with a height of 16 pixels and a width of 8 pixels. The
characters are of medium stroke and upright and have a normal setwidth. The character set is ISO Latin2.
GIF_FONTMEDIUM Font of the character cell fixed width font family with a height of 13 pixels and a width of 7 pixels. The
characters are sans serif, of bold and upright stroke and have a normal setwidth. The character set is ISO
Latin2.
GIF_FONTSMALL Font of the character cell fixed width font family with a height of 12 pixels and a width of 6 pixels. The
characters are sans serif, of normal and upright stroke and have a semicondensed setwidth. The character
set is ISO Latin2.
GIF_FONTTINY Font of the character cell fixed width font family with a height of 8 pixels and a width of 5 pixels. The
characters are of medium and upright stroke and have a normal setwidth. The character set is ISO Latin2.

All fonts used are character cell fonts, which are special monospaced fonts. In a monospaced font each character
has the same width, whereas character fonts go even a bit further and put each character in an invisible cell. The
spacing therefore relates to the size of the cell that contains a character rather than to the character itself.
The text is drawn using the specified color index. Note that the color index can be an actual color returned by the
GifAllocateColour function, or one of GIF_STYLED, GIF_BRUSHED, or GIF_STYLEDBRUSHED. For more
information about this topic refer to functions GifSetBrush, GifSetStyle and GifSetTile.
Example:
The following example script creates a rectangular button with text on it.
proc main ()

//Create a button with text.

int Index, ButtonFont, Foreground, ImgWidth, ImgHeight


GifImage ptrImage

ImgWidth = 250

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 19 - Gif-Image Manipulation Functions - 235

ImgHeight = 250
ptrImage = GifCreateImage (ImgWidth, ImgHeight)

GifDrawFilledRectangle (ptrImage, 0, 0, ImgWidth, ImgHeight, Index)


GifDrawText (ptrImage, 80, 160, 'Stop', ButtonFont, Foreground)
if (GifSaveImage (ptrImage, 'Examples/buttons/' + 'Stop') == FALSE)
print ("Failed to save button GIF file in " + "Examples/buttons/" +
Stop")
endif

GifDestroyImage (ptrImage)

endproc

GifDrawTextUp
Draw a vertical text string in a Gif image.
Syntax:
Bool GifDrawTextUp (GifImage Handle, Int X, Int Y, String Text, Int Font, Int Color)
Handle is the reference to the Gif image handle.
X is the position of the starting point of the text on the x-axis of the text.
Y is the position of the starting point of the text on the y-axis of the text.
Text is the text string to be drawn into the Gif image.
Font is the index of the font to be used for the text string.
Color is the color index to be used for the text string.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The GifDrawTextUp function is used to draw multiple characters on a Gif image, rotated by 90 degrees. The
text is drawn vertically from the bottom to the top departing at the starting point defined through the x and y
coordinates in the specified color. Pixels which are not set by a particular character retain their original color. The
Font argument is a reference to a font definition constant which can be one of the following five:

Name Description
GIF_FONTHUGE Font of the character cell fixed width font family with a height of 15 pixels and a width of 9 pixels. The
characters are sans serif, of bold and upright stroke and have a normal setwidth. The character set is ISO
Latin2.
GIF_FONTLARGE Font of the character cell fixed width font family with a height of 16 pixels and a width of 8 pixels. The
characters are of medium stroke and upright and have a normal setwidth. The character set is ISO Latin2.
GIF_FONTMEDIUM Font of the character cell fixed width font family with a height of 13 pixels and a width of 7 pixels. The
characters are sans serif, of bold and upright stroke and have a normal setwidth. The character set is ISO
Latin2.
GIF_FONTSMALL Font of the character cell fixed width font family with a height of 12 pixels and a width of 6 pixels. The
characters are sans serif, of normal and upright stroke and have a semicondensed setwidth. The character
set is ISO Latin2.
GIF_FONTTINY Font of the character cell fixed width font family with a height of 8 pixels and a width of 5 pixels. The
characters are of medium and upright stroke and have a normal setwidth. The character set is ISO Latin2.

All fonts used are character cell fonts, which are special monospaced fonts. In a monospaced font each character
has the same width, whereas character fonts go even a bit further and put each character in an invisible cell. The
spacing therefore relates to the size of the cell that contains a character rather than to the character itself.
The text is drawn using the specified color index. Note that the color index can be an actual color returned by the
GifAllocateColour function, or one of GIF_STYLED, GIF_BRUSHED, or GIF_STYLEDBRUSHED. For more
information about this topic refer to functions GifSetBrush, GifSetStyle and GifSetTile.

Numara Software, Inc. and BMC Software, Inc. Confidential.


236 - BMC FootPrints Asset Core - Chilli Reference

Example:
The following example script writes 'Start' on a button image.
proc main ()

//Write the start button label text.

int ButtonFont, Foreground, Height, Width


GifImage ptrImage

Height = 50
Width = 150
ptrImage = GifCreateImage (Width, Height)
Foreground = GifAllocateColour (ptrImage, 255, 255, 255)
ButtonFont = GIF_FONTSMALL

GifDrawTextUp (ptrImage, 50, 200, 'Start', ButtonFont, Foreground)

GifDestroyImage (ptrImage)

endproc

GifFill
Flood fill an area within a Gif image.
Syntax:
Bool GifFill (GifImage Handle, Int X, Int Y, Int Color)
Handle is the reference to the Gif image handle.
X is the pixel position of the starting point on the x-axis.
Y is the pixel position of the starting point on the y-axis.
Color is the color index of the area.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
This function fills a portion of a Gif image with the specified color. The flood fill starts at the indicated pixel and
colors the surrounding area of the same color as the starting point. The fill color can be GIF_TILED, resulting in
a tile fill using another image as the tile. The tile image cannot be transparent.
Example:
The following example script creates a circle divided into upper and lower half which are filled with different
colors.
proc main ()

int Background, LineColour, Color, Height, Width


GifImage ptrImage

Height = 50
Width = 150
ptrImage = GifCreateImage (Width, Height)

Background = GifAllocateColour (ptrImage, 0, 255, 0)


LineColour = GifAllocateColour (ptrImage, 0, 0, 255)
Color = GifAllocateColour (ptrImage, 255, 0, 0)

// Draw a circle with blue circle line color.


GifDrawArc (ptrImage, 5, 5, 5, 5, 0, 359, LineColour)

// Divide circle in two halfs through a line.


GifDrawLine (ptrImage, 0, 5, 10, 5, LineColour)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 19 - Gif-Image Manipulation Functions - 237

// Fill upper half in background color green with border color red.
GifFillToBorder (ptrImage, 5, 2, Background, Color)

// Fill lower half with background color red without changing


// the blue border color.
GifFill (ptrImage, 5, 8, Background)

GifDestroyImage (ptrImage)

endproc

GifFillToBorder
Flood fill an area within a Gif image including the area’s borderline.
Syntax:
Bool GifFillToBorder (GifImage Handle, Int X, Int Y, Int Color, Int Bordercolour)
Handle is the reference to the Gif image handle.
X is the pixel position of the starting point on the x-axis.
Y is the pixel position of the starting point on the y-axis.
Color is the color index of the area.
Bordercolour is the color index of the area border.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The area to be filled is identified by the starting point and by the color of its border. The border color must be a
solid color, it cannot be a special color, such as GIF_TILED. The fill color, however, can be a special color.
Example:
The following example script creates an oval button with a shadow around it, of which the color decreases in
depth with every turn.
proc main ()

// Create an oval button with a shadow around it. The shadow


// color decreases in depth with every turn.

int i, ShadowColour, Height, Width


GifImage ptrImage
Height = 50
Width = 150
ptrImage = GifCreateImage (Width, Height)

// 3 loops for shadow around button.


for (i=3; i>=1; i-=1)
//Color definition of the shadow.
ShadowColour = GifAllocateColour (ptrImage, 50*i, 50*i, 50*i)

// 2 horizontal lines for the upper and lower lines of the oval button
GifDrawLine (ptrImage, Height/2+i, i, (Width+i)-Height/2, i,
ShadowColour)
GifDrawLine (ptrImage, Height/2+i, (Height+i)-1, (Width+i)-Height/2,
(Height+i)-1, ShadowColour)

// 2 half circles (arches) on the left and right of the lines to


// connect the lines through an arch.
GifDrawArc (ptrImage, (Height/2+i)+1, (Height/2)+i, Height, Height, 90,
270, ShadowColour)
GifDrawArc (ptrImage, ((Width+i)-1)-Height/2, (Height/2)+i, Height,

Numara Software, Inc. and BMC Software, Inc. Confidential.


238 - BMC FootPrints Asset Core - Chilli Reference

Height, 270, 90, ShadowColour)

// Fill the button shape in the middle. Being flood fill, this
// ends up filling the whole button.

GifFillToBorder (ptrImage, Height+i, i+2, ShadowColour, ShadowColour)

endfor

GifDestroyImage (ptrImage)

endproc

GifGetColourBlue
Get the blue component of the supplied color index in a Gif image.
Syntax:
Int GifGetColourBlue (GifImage Handle, Int Color)
Handle is the reference to the Gif image handle.
Color is the color index.
Returns:
The component value of blue of the specified color index if the function was executed successfully, -1 if the
function failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.

GifGetColourClosest
Get a color in the color table of the Gif image which most closely matches the supplied RGB values.
Syntax:
Int GifGetColourClosest (GifImage Handle, Int R, Int G, Int B)
Handle is the reference to the Gif image handle.
R is the color index of red.
G is the color index of green.
B is the color index of blue.
Returns:
The color index if the operation was successful. If no colors have yet been allocated in the Gif image and the
operation fails, GifGetColourClosest returns -1, and ErrCode is set to ERR_FUNCFAILED.
Comments:
The GifGetColourClosest function searches the colors which have been defined thus far in the Gif image
specified and returns the index of the color with RGB values closest to those of the request. (Closeness is
determined by Euclidian distance, which is used to determine the distance in three-dimensional color space
between colors.)
This function is most useful as a backup method for choosing a drawing color when a Gif image already contains
all 256 colors and no more can be allocated. (This is not uncommon when working with existing Gif files that
already use many colors.) See GifGetColourExact for a method of locating exact matches only.

GifGetColourExact
Get the color in the color index of the Gif image which exactly matches the supplied RGB values.
Syntax:
Int GifGetColourExact (GifImage Handle, Int R, Int G, Int B)
Handle is the reference to the Gif image handle.
R is the color index of red.
G is the color index of green.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 19 - Gif-Image Manipulation Functions - 239

B is the color index of blue.


Returns:
The color index if the operation was successful. If no allocated color matches the request precisely and the
operation fails, GifGetColourExact returns -1, and ErrCode is set to ERR_FUNCFAILED.
Comments:
The GifGetColourExact function searches the colors which have been defined thus far in the Gif image
specified and returns the index of the first color with RGB values which exactly match those of the request. See
GifGetColourClosest for a way to find the color closest to the color requested.

GifGetColourGreen
Get the green component of the supplied color index in a Gif image.
Syntax:
Int GifGetColourGreen (GifImage Handle, Int Color)
Handle is the reference to the Gif image handle.
Color is the color index.
Returns:
The component value of green of the specified color index if the function was executed successfully, -1 if the
function failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.

GifGetColourRed
Get the red component of the supplied color index in a Gif image.
Syntax:
Int GifGetColourRed (GifImage Handle, Int Color)
Handle is the reference to the Gif image handle.
Color is the color index.
Returns:
The component value of red of the specified color index if the function was executed successfully, -1 if the
function failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.

GifGetFontHeight
Get the height of a character in the specified font.
Syntax:
Int GifGetFontHeight (Int Font)
Font is the index of the font.
Returns:
The height of the font as defined in the respective constant if the operation was successful, 0 if the operation
failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The Font argument is a reference to a font definition constant which can be one of the following five:

Name Description
GIF_FONTHUGE Font of the character cell fixed width font family with a height of 15 pixels and a width of 9 pixels. The
characters are sans serif, of bold and upright stroke and have a normal setwidth. The character set is ISO
Latin2.
GIF_FONTLARGE Font of the character cell fixed width font family with a height of 16 pixels and a width of 8 pixels. The
characters are of medium stroke and upright and have a normal setwidth. The character set is ISO Latin2.

Numara Software, Inc. and BMC Software, Inc. Confidential.


240 - BMC FootPrints Asset Core - Chilli Reference

Name Description
GIF_FONTMEDIUM Font of the character cell fixed width font family with a height of 13 pixels and a width of 7 pixels. The
characters are sans serif, of bold and upright stroke and have a normal setwidth. The character set is ISO
Latin2.
GIF_FONTSMALL Font of the character cell fixed width font family with a height of 12 pixels and a width of 6 pixels. The
characters are sans serif, of normal and upright stroke and have a semicondensed setwidth. The character
set is ISO Latin2.
GIF_FONTTINY Font of the character cell fixed width font family with a height of 8 pixels and a width of 5 pixels. The
characters are of medium and upright stroke and have a normal setwidth. The character set is ISO Latin2.
All fonts used are character cell fonts, which are special monospaced fonts. In a monospaced font each character
has the same width, whereas character fonts go even a bit further and put each character in an invisible cell. The
spacing therefore relates to the size of the cell that contains a character rather than to the character itself.
Example:
The following example script creates an empty rectangle with a tripple shadow around it.
proc main ()

// Draw an empty rectangle with a triple shadow around it.

int i, ShadowColour, Height, Width, Index, BtnHeight, BtnWidth, ButtonFont


GifImage ptrImage

Height = 50
Width = 150
ptrImage = GifCreateImage (Width, Height)

ButtonFont = GIF_FONTMEDIUM
Index = GifAllocateColour (ptrImage, 50*i, 50*i, 50*i)
BtnHeight = GifGetFontHeight (ButtonFont)*5 / 3
BtnWidth = StrLen ('Start') * GifGetFontWidth (ButtonFont) + BtnHeight

// Draw rectangle
GifDrawFilledRectangle (ptrImage, 0, 0, BtnWidth, BtnHeight, Index)

// Loop 3 times around the button, drawing a faded shadow

for (i=3; i>=1; i-=1)


ShadowColour = GifAllocateColour (ptrImage, 50*i, 50*i, 50*i)
GifDrawLine (ptrImage, 3-i, Height -i, Width-i, Height -i,ShadowColour)
GifDrawLine (ptrImage, Width -i, 3-i, Width -i, Height-i, ShadowColour)
endfor

GifDestroyImage (ptrImage)

endproc

GifGetFontWidth
Get the width of a character in the specified font.
Syntax:
Int GifGetFontWidth (Int Font)
Font is the index of the font.
Returns:
The width of the font as defined in the respective constant if the operation was successful, 0 if the operation
failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The Font argument is a reference to a font definition constant which can be one of the following five:

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 19 - Gif-Image Manipulation Functions - 241

Name Description
GIF_FONTHUGE Font of the character cell fixed width font family with a height of 15 pixels and a width of 9 pixels. The
characters are sans serif, of bold and upright stroke and have a normal setwidth. The character set is ISO
Latin2.
GIF_FONTLARGE Font of the character cell fixed width font family with a height of 16 pixels and a width of 8 pixels. The
characters are of medium stroke and upright and have a normal setwidth. The character set is ISO Latin2.
GIF_FONTMEDIUM Font of the character cell fixed width font family with a height of 13 pixels and a width of 7 pixels. The
characters are sans serif, of bold and upright stroke and have a normal setwidth. The character set is ISO
Latin2.
GIF_FONTSMALL Font of the character cell fixed width font family with a height of 12 pixels and a width of 6 pixels. The
characters are sans serif, of normal and upright stroke and have a semicondensed setwidth. The character
set is ISO Latin2.
GIF_FONTTINY Font of the character cell fixed width font family with a height of 8 pixels and a width of 5 pixels. The
characters are of medium and upright stroke and have a normal setwidth. The character set is ISO Latin2.

All fonts used are character cell fonts, which are special monospaced fonts. In a monospaced font each character
has the same width, whereas character fonts go even a bit further and put each character in an invisible cell. The
spacing therefore relates to the size of the cell that contains a character rather than to the character itself.
Example:
The following example script creates an empty rectangle with a triple shadow around it.
proc main ()

// Draw an empty rectangle with a triple shadow around it.

int i, ShadowColour, Height, Width, Index, BtnHeight, BtnWidth, ButtonFont


GifImage ptrImage

Height = 50
Width = 150
ptrImage = GifCreateImage (Width, Height)

ButtonFont = GIF_FONTMEDIUM
Index = GifAllocateColour (ptrImage, 50*i, 50*i, 50*i)
BtnHeight = GifGetFontHeight (ButtonFont)*5 / 3
BtnWidth = StrLen ('Start') * GifGetFontWidth (ButtonFont) + BtnHeight

// Draw rectangle
GifDrawFilledRectangle (ptrImage, 0, 0, BtnWidth, BtnHeight, Index)

// Loop 3 times around the button, drawing a faded shadow

for (i=3; i>=1; i-=1)


ShadowColour = GifAllocateColour (ptrImage, 50*i, 50*i, 50*i)
GifDrawLine (ptrImage, 3-i, Height -i, Width-i, Height -i,ShadowColour)
GifDrawLine (ptrImage, Width -i, 3-i, Width -i, Height-i, ShadowColour)
endfor

GifDestroyImage (ptrImage)

endproc

GifGetImageHeight
Get the height of a Gif image.
Syntax:
Int GifGetImageHeight (GifImage Handle)
Handle is the reference to the Gif image handle.
Returns:
The height of the Gif image in pixels if the function was executed successfully, 0 if the function failed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


242 - BMC FootPrints Asset Core - Chilli Reference

GifGetImageLength
Get the width of a Gif image.
Syntax:
Int GifGetImageLength (GifImage Handle)
Handle is the reference to the Gif image handle.
Returns:
The width of the Gif image in pixels if the function was executed successfully, 0 if the function failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.

GifGetPixel
Get the color index of an individual pixel in a Gif image.
Syntax:
Int GifGetPixel (GifImage Handle, Int X, Int Y)
Handle is the reference to the Gif image handle.
X is the pixel position on the x-axis.
Y is the pixel position on the y-axis
Returns:
The color index of the pixel if the operation was successful, -1 if the operation failed. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.

GifGetTotalColours
Get the total number of allocated colors in a Gif image.
Syntax:
Int GifGetTotalColours (GifImage Handle)
Handle is the reference to the Gif image handle.
Returns:
The number of colors currently allocated in the Gif image, if the operation was successful, -1 if the function failed.
If the operation fails, ErrCode is set to ERR_FUNCFAILED.

GifGetTransparent
Get the index of the transparent color in a Gif image.
Syntax:
Int GifGetTransparent (GifImage Handle)
Handle is the reference to the Gif image handle.
Returns:
The current transparent color index in the Gif image if the operation was successful, -1 if the function failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.

GifHsvToRgb
Convert the values in a HSV triplet to their equivalents in RGB.
Syntax:
GifRgbTriplet GifHsvToRgb (Struct GifHsvTriplet HSV)
HSV is the structure containing the Hue, Saturation and Value indices of the supplied color.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 19 - Gif-Image Manipulation Functions - 243

Returns:
A structure of type GifRgbTriplet with the corresponding RGB values if the operation was successful, or an
empty structure if the operation failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.

GifLoadImage
Load a new Gif image from a file.
Syntax:
GifImage GifLoadImage (String File)
File is the file name of the Gif image to be loaded.
Returns:
The reference to the handle of the newly created Gif image if the create operation was successful, 0 if the Gif
image could not be loaded (corrupt file or file does not contain a Gif image) and the operation failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The functions opens the file, saves the image to memory, creates the handle and closes the file again. The image
must eventually be destroyed by the GifImageDestroy function.

GifRgbToHsv
Convert the values in a RGB triplet to their equivalents in HSV.
Syntax:
GifHsvTriplet GifRgbToHsv (Struct GifRgbTriplet RGB)
RGB is the structure containing the blue, green and red indices of the supplied color.
Returns:
A structure of type GifHsvTriplet with the corresponding HSV values if the operation was successful, or an
empty structure if the operation failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.

GifSaveImage
Save the Gif image associated with the supplied handle to a file.
Syntax:
Bool GifSaveImage (GifImage Handle, String File)
Handle is the reference to the Gif image handle.
File is the file name into which the Gif image is to be saved.
Returns:
TRUE if the save operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
If the file into which the image is to be saved does not yet exist it is created by the function. The image is then
saved into the file and the file is closed. If the file exists already the contents is overwritten with the new image.
Example:
The following example script creates a button with text on it.
proc main ()

//Create a button with text.

int Index, ButtonFont, Foreground, ImgWidth, ImgHeight


GifImage ptrImage

ImgWidth = 250

Numara Software, Inc. and BMC Software, Inc. Confidential.


244 - BMC FootPrints Asset Core - Chilli Reference

ImgHeight = 250
ptrImage = GifCreateImage (ImgWidth, ImgHeight)

GifDrawFilledRectangle (ptrImage, 0, 0, ImgWidth, ImgHeight, Index)


GifDrawText (ptrImage, 80, 160, 'Stop', ButtonFont, Foreground)
if (GifSaveImage (ptrImage, 'Examples/buttons/' + 'Stop') == FALSE)
print ("Failed to save button GIF file in " + "Examples/buttons/" +
Stop")
endif

GifDestroyImage (ptrImage)

endproc

GifSetBrush
Set the Gif image to be used for drawing shapes.
Syntax:
Bool GifSetBrush (GifImage Handle1, GifImage Handle2)
Handle1 is the reference to the Gif image handle.
Handle2 is the reference to the Gif image handle.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
A brush is a Gif image used to draw wide, shaped strokes in another image. Just as a paintbrush is not a single
point, a brush image need not be a single pixel. Any Gif image can be used as a brush, and by setting the
transparent color index of the brush image, with GifSetTransparent, a brush of any shape can be created. All
line-drawing functions, such as GifDrawLine and GifDrawPolygon, uses the current brush if the special
"colour" GIF_BRUSHED or GIF_STYLEBRUSHED is used when calling them.
GifSetBrush is used to specify the brush to be used in a particular image. If the brush image does not have the
same color map as the first image, any colors missing from the first image is allocated. If not enough colors can be
allocated, the closest colors already available is used. This allows arbitrary Gifs to be used as brush images. It also
means that you should not set a brush unless you actually use it. If you set a rapid succession of different brush
images, you can quickly fill your color map, and the results is not optimal.
You need not take any special action when you are finished with a brush. As for any other image, if you is not
using the brush image for any further purpose, you should call GifDestroyImage. You must not use the color
GIF_BRUSHED if the current brush has been destroyed, you can however set a new brush to replace it.

GifSetPixel
Set the color of an individual pixel in a Gif image to a particular color index.
Syntax:
Bool GifSetPixel (GifImage Handle, Int X, Int Y, Int Color)
Handle is the reference to the Gif image handle.
X is the pixel position on the x-axis.
Y is the pixel position on the y-axis
Color is the color index of the pixel.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 19 - Gif-Image Manipulation Functions - 245

GifSetStyle
Set the drawing style of the Gif image based on an array of color indices.
Syntax:
Bool GifSetStyle (GifImage Handle, Int Colors[])
Handle is the reference to the Gif image handle.
Colours[] is the color index of the pixel.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
GifSetStyle can be used to set any intended series of colors, including a special color that leaves the
background intact, to be repeated during the drawing of a line. To use GifSetStyle, create an array of integers
and assign them the intended series of color values to be repeated. You can assign the special color value
GIF_TRANSPARENT to indicate that the existing color should be left unchanged for that particular pixel (allowing
a dashed line to be attractively drawn over an existing image). Then, to draw a line using the style, use the normal
GifDrawLine function with the special color value GIF_STYLED.
The color array is copied when you set the style, so you need not be concerned with keeping the array around
indefinitely. You can also combine styles and brushes to draw the brush image at intervals instead of in a
continuous stroke. When creating a style for use with a brush, the style values are interpreted differently: zero (0)
indicates pixels at which the brush should not be drawn, while one (1) indicates pixels at which the brush should
be drawn. To draw a styled, brushed line, you must use the special color value GIF_STYLEDBRUSHED.

GifSetTile
Set the Gif image to be used for filling functions.
Syntax:
Bool GifSetTile (GifImage Handle1, GifImage Handle2)
Handle1 is the reference to the Gif image used for tile filling functions.
Handle2 is the reference to the Gif image in which the above mentioned Gif image is to be used for filling
functions.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
A tile is a Gif image used to fill an area with a repeated pattern. Any Gif image can be used as a tile, and by setting
the transparent color index of the tile image with GifSetTransparent, a tile that allows certain parts of the
underlying area to shine through can be created. All region-filling functions, such as GifFill and
GifDrawFilledPolygon, uses the current tile if the special "colour" GIF_TILED is used when calling them.
GifSetTile is used to specify the tile to be used in a particular image. If the tile image does not have the same
color map as the first image, any colors missing from the first image is allocated. If not enough colors can be
allocated, the closest colors already available is used. This allows arbitrary Gifs to be used as tile images. It also
means that you should not set a tile unless you actually use it. If you set a rapid succession of different tile
images, you can quickly fill your color map, and the results is not optimal.
You need not take any special action when you are finished with a tile. As for any other image, if you is not using
the tile image for any further purpose, you should call GifDestroyImage. You must not use the color
GIF_TILED if the current tile has been destroyed, you can however set a new tile to replace it.

GifSetTransparent
Set the index of the transparent color in a Gif image.

Numara Software, Inc. and BMC Software, Inc. Confidential.


246 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
Bool GifSetTransparent (GifImage Handle, Int Color)
Handle is the reference to the Gif image handle.
Color is the color index of the color to be used as transparent.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The GifSetTransparent function sets the transparent color index for the specified image to the specified
index. To indicate that there should be no transparent color, invoke GifSetTransparent with a color index of
-1. The color index used should be an index allocated by GifAllocateColour, whether explicitly invoked by
your code or implicitly invoked by loading a Gif image. In order to ensure that your image has a reasonable
appearance when viewed by users who do not have transparent background capabilities, be sure to give
reasonable RGB values to the color you allocate for use as a transparent color, even though it is transparent on
systems that support transparency.
Example:
The following example script fills a rectangle with color which is then set as the transparency index.
proc main ()

Int TransIndex, Width, Height


GifImage ptrImage

Width = 150
Height = 50
ptrImage = GifCreateImage (Width, Height)
TransIndex = GifAllocateColour (ptrImage, 1, 2, 3)

// Fill the entire rectangle with a weird color which then


// becomes transparent.
GifDrawFilledRectangle (ptrImage, 0, 0, Width, Height, TransIndex)
GifSetTransparent (ptrImage, TransIndex)

GifDestroyImage (ptrImage)

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


HTML File Functions

This chapter details all elements and functions for HTML files in the Chilli language. All functions of this module
are included in the html.chx file for Windows or htnl.so file for UNIX and Linux.

20.1 Introduction
HTML (HyperText Markup Language) is the authoring language used to create documents on the Internet. It
defines the structure and layout of a Web document by using a variety of tags and attributes. This function
module allows you to read existing HTML files and retrieve a list of all tags used in this type of file.

20.2 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli HTML File function group module has predefined data types of
type structure.

20.2.1 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated. For each predefined structure an array type of this structure also exists for usage
in the scripts.
Following you find a list of all predefined data types of type structure:

Data Type Description


HtmlTag Represent an HTML tag in a file
HtmlTagList Represent a list of objects in an HTML file
HtmlTagParam Represent a parameter of an HTML tag

HtmlTag
The HtmlTag structure represents an HTML tag in a file.
Elements:

Elements Element Type Description


IsHtmlTag integer 1 if standard HTML tag, 0 if user defined tag.
IsEndTag integer 1 if the tag has an end tag, 0 if not.
TagLabel string Name of the tag.
TagParamCount integer Number of parameters in the tag.
TagParams HtmlTagParam[] array List of parameters in the tag.

Numara Software, Inc. and BMC Software, Inc. Confidential.


248 - BMC FootPrints Asset Core - Chilli Reference

HtmlTagList
The HtmlTagList structure represents a list of objects which can be either the tags used in an HTML page or the
text between the tags.
It is used when parsing an HTML file to get the complete list of all objects used in the file, that is, all tags and the
text they enclose.
Elements:

Elements Element Type Description


TagCount integer Number of tags.
Tags HtmlTag[] array List of objects (tags and text).

HtmlTagParam
The HtmlTagParam structure represents the parameters of an HTML tag. It is used when parsing an HTML file to
get the complete list of all parameters of a specific tag used in the file.
Elements:

Elements Element Type Description


TagParamName string Name of the tag parameter.
TagParamValue string Value of the tag parameter.

20.3 Functions
Following you find a list of all available HTML File functions:

Function OS Description
HtmlReadFile Read the specified file path and create an HtmlTagList structure

HtmlReadFile
Read the specified file path and create an HtmlTagList structure.
Syntax:
Struct HtmlTagList HtmlReadFile (String FilePath)
Filepath is the (relative or absolute) path of the html file to be read.
Returns:
A list of tags in the HTML file if successful, or an empty list if the operation failed, the file could not be found, or
the file does not contain any HTML tags. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
This function builds a list of all tags including all their parameters and values when it parses an HTML file. Chilli
scripts call this function to be able to manipulate the list in order to create their own output.
Example:
This example reads the list of tags used in the file 'my_file.html'.
proc main ()

HtmlTagList MyListOfTags

MyListOfTags = HtmlReadFile ("my_file.html")

print ("There are " + MyListOfTags.TagCount + " HTML tags in this file \n")
print ("There first tag is " + MyListOfTags.Tags[1].TagLabel + "
and has " +MyListOfTags.Tags[1].TagParamCount + " parameters \n")

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 20 - HTML File Functions - 249

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


250 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


INI Format File Manipulation Functions

This chapter details all elements and functions which handle the .ini file functions in the Chilli script
language. All functions of this module are included in the inifile.chx file for Windows or inifile.so file for
UNIX and Linux.

21.1 Introduction
.ini files are files which contain the configuration information of MS Windows programs and many other
application which all create their own .ini files. This group of functions enables you to retrieve information from
such files as well as to add or modify information within them.

21.2 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli Ini Format File Manipulation function group has Predefined
Handle Data Types.

21.2.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing an open
INI file. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


IniFileHandle Object type: reference to the handle of an INI format file

IniFileHandle
The IniFileHandle data type is a reference to the handle of an .ini file.
The function FileIniOpen returns a value of this object type that most of the other functions expect as their first
argument. Any open ini file and thus the value of this object type should always be closed by the FileIniClose
function.

21.3 Functions
Following you find the complete list of .ini file functions.

Function OS Description
FileDeleteEntry Delete an entry within a section in an INI format file

Numara Software, Inc. and BMC Software, Inc. Confidential.


252 - BMC FootPrints Asset Core - Chilli Reference

Function OS Description
FileDeleteSection Delete an entire section in an INI format file

FileGetEntryCount Get the number of entries in a section in an INI format file

FileGetEntryName Get the name of an entry in a section in an INI file using an integer index

FileGetLineCount Return the total number of lines in the file

FileGetSectionCount Get the number of sections in an INI format file

FileGetSectionName Get the name of a section in an INI file using an integer index

FileGetValue Get the value of an entry in a section in an INI file

FileIniClose Close an existing and open INI file

FileIniOpen Open an existing INI file archive

FileIsIni Check that a file is in INI format

FileMerge Merge a source file into a destination file

FileSetValue Set the value of an entry in a section in an INI file

FileDeleteEntry
Delete an entry within a section in an INI format file.
This function has the following signatures:
Syntax:
Bool FileDeleteEntry (String FileName, String SectionName, String EntryName)
Bool FileDeleteEntry (String FileName, String SectionName, Int EntryIndex)
Bool FileDeleteEntry (String FileName, Int SectionIndex, String EntryName)
Bool FileDeleteEntry (String FileName, Int SectionIndex, Int EntryIndex)
FileName is the relative or absolute path of the file to be modified.
SectionIndex is the index of the section to be modified.
SectionName is the name of the section to be modified.
EntryIndex is the index of the entry in the section to be deleted.
EntryName is the name of the entry to be deleted.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the supplied file is not a valid INI file the
operation fails and ErrCode is set to ERR_FILENOTVALID otherwise ErrCode is set to ERR_FILEFUNCFAILED.
Comments:
The numbering starts at 1 for the first section and entry.
The second and third parameters of these functions, specifying the section and entry, can be supplied as integers
or as string values. According to the data type of the value supplied the function then automatically uses the
appropriate signature.
Example:
The following example deletes an entry and a section from an .ini file.
proc main ()

string stringFile
string section, entry
stringFile = "C:\\temp\\test.ini"

if (FileIsIni (stringFile) == TRUE)


if (FileGetSectionCount (stringFile) != 0)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 21 - INI Format File Manipulation Functions - 253

section = FileGetSectionName (stringFile, 1)

if (FileGetEntryCount (stringFile, section) != 0)


entry = FileGetEntryName (stringFile, section, 1)
FileDeleteEntry (stringFile, section, entry)
endif

FileDeleteSection (stringFile, section)


endif
endif

endproc

FileDeleteSection
Delete an entire section from an .ini format file.
This function has two signatures:
Syntax:
Bool FileDeleteSection (String FileName, Int SectionIndex)
Bool FileDeleteSection (String FileName, String SectionName)
FileName is the relative or absolute path of the file to be read.
SectionIndex is the index of the section to be deleted.
SectionName is the name of the section to be deleted.
Returns:
TRUE if the delete operation was successful, FALSE if the path does not exist or the operation failed. If the
supplied file is not a valid .ini file the operation fails and ErrCode is set to ERR_FILENOTVALID otherwise
ErrCode is set to ERR_FILEFUNCFAILED.
Comments:
The numbering starts at 1 for the first section.
The second parameter of the function, specifying the section, can be supplied as an integer or a string value.
According to the data type of the value supplied the function then automatically uses the appropriate signature.
Example:
The following example deletes an entry and a section from an .ini file.
proc main ()

string stringFile
string section, entry
stringFile = "C:\\temp\\test.ini"

if (FileIsIni (stringFile) == TRUE)


if (FileGetSectionCount (stringFile) != 0)
section = FileGetSectionName (stringFile, 1)

if (FileGetEntryCount (stringFile, section) != 0)


entry = FileGetEntryName (stringFile, section, 1)
FileDeleteEntry (stringFile, section, entry)
endif

FileDeleteSection (stringFile, section)


endif
endif

endproc

FileGetEntryCount
Get the number of entries in a section of an INI format file.

Numara Software, Inc. and BMC Software, Inc. Confidential.


254 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
Int FileGetEntryCount (String FileName, Int SectionIndex)
Int FileGetEntryCount (String FileName, String SectionName)
Int FileGetEntryCount (IniFileHandle IniHandle, Int SectionIndex)
Int FileGetEntryCount (IniFileHandle IniHandle, String SectionName)
FileName is the relative or absolute path of the file to be read.
IniHandle is the handle of the ini file returned by the FileIniOpen function.
SectionIndex is the index of the section to be read.
SectionName is the name of the section to be read.
Returns:
If successful, the function returns the number of entries found in the specified section of the file or if the section
is not found 0 is returned. If the supplied file is not a valid INI file the function fails and ErrCode is set to
ERR_FILENOTVALID otherwise ErrCode is set to ERR_FILEFUNCFAILED.
Comments:
The numbering starts at 1 for the first section.
The second parameter of the function, specifying the section, can be supplied as an integer or a string value.
According to the data type of the value supplied the function then automatically uses the appropriate signature.
Example 1:
The following example deletes an entry and a section from an .ini file.
proc main ()

string stringFile
string section, entry
stringFile = "C:\\temp\\test.ini"

if (FileIsIni (stringFile) == TRUE)


if (FileGetSectionCount (stringFile) != 0)
section = FileGetSectionName (stringFile, 1)

if (FileGetEntryCount (stringFile, section) != 0)


entry = FileGetEntryName (stringFile, section, 1)
FileDeleteEntry (stringFile, section, entry)
endif

FileDeleteSection (stringFile, section)


endif
endif

endproc

Example 2:
The following example deletes an entry and a section from an .ini file, using the handle to the file.
proc main ()

inifilehandle inihandle
string stringFile
string section1, section10, entry
stringFile = "C:\\temp\\test.ini"

if (FileIsIni (stringFile) == TRUE)


inihandle = FileIniOpen (stringFile)

if (FileGetSectionCount (inihandle) != 0)
section1 = FileGetSectionName (inihandle, 1)
section10 = FileGetSectionName (inihandle, 10)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 21 - INI Format File Manipulation Functions - 255

if (FileGetEntryCount (inihandle, section10) != 0)


entry = FileGetEntryName (inihandle, section10, 1)
endif
endif

FileIniClose (inihandle)
FileDeleteEntry (stringFile, section10, entry)
FileDeleteSection (stringFile, section1)
endif

endproc

FileGetEntryName
Given the index to an entry in a section, get the name of that entry in an INI format file.
This function has the following signatures:
Syntax:
String FileGetEntryName (String FileName, String SectionName, Int EntryIndex)
String FileGetEntryName (String FileName, Int SectionIndex, Int EntryIndex)
String FileGetEntryName (IniFileHandle IniHandle, String SectionName, Int EntryIndex)
String FileGetEntryName (IniFileHandle IniHandle, Int SectionIndex, Int EntryIndex)
FileName is the relative or absolute path of the file to be read.
IniHandle is the handle of the ini file returned by the FileIniOpen function.
SectionIndex is the index of the section to be read.
SectionName is the name of the section to be read.
EntryIndex is the index of the entry in the section.
Returns:
If successful, the function returns the name of the entry. If the file, the section or the entry is not found, an empty
string is returned. If the supplied file is not a valid INI file the function fails and ErrCode is set to
ERR_FILENOTVALID otherwise ErrCode is set to ERR_FILEFUNCFAILED.
Comments:
The numbering starts at 1 for the first section and entry.
The second parameter of the function, specifying the section, can be supplied as an integer or a string value.
According to the data type of the value supplied the function then automatically uses the appropriate signature.
Example 1:
The following example deletes an entry and a section from an .ini file.
proc main ()

string stringFile
string section, entry
stringFile = "C:\\temp\\test.ini"

if (FileIsIni (stringFile) == TRUE)


if (FileGetSectionCount (stringFile) != 0)
section = FileGetSectionName (stringFile, 1)

if (FileGetEntryCount (stringFile, section) != 0)


entry = FileGetEntryName (stringFile, section, 1)
FileDeleteEntry (stringFile, section, entry)
endif

FileDeleteSection (stringFile, section)


endif
endif

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


256 - BMC FootPrints Asset Core - Chilli Reference

Example 2:
The following example deletes an entry and a section from an .ini file, using the handle to the file.
proc main ()

inifilehandle inihandle
string stringFile
string section1, section10, entry
stringFile = "C:\\temp\\test.ini"

if (FileIsIni (stringFile) == TRUE)


inihandle = FileIniOpen (stringFile)

if (FileGetSectionCount (inihandle) != 0)
section1 = FileGetSectionName (inihandle, 1)
section10 = FileGetSectionName (inihandle, 10)

if (FileGetEntryCount (inihandle, section10) != 0)


entry = FileGetEntryName (inihandle, section10, 1)
endif
endif

FileIniClose (inihandle)
FileDeleteEntry (stringFile, section10, entry)
FileDeleteSection (stringFile, section1)
endif

endproc

FileGetLineCount
Return the total number of lines in the INI file given its handle.
Syntax:
Int FileGetLineCount (IniFileHandle IniHandle)
IniHandle is the handle of the ini file returned by the FileIniOpen function.
Returns:
The total number of lines in the ini file if the operation was successful, or 0 if the operation failed. If the operation
fails due to the supplied file not being a valid .ini file the ErrCode is set to ERR_FILENOTVALID otherwise to
ERR_FUNCFAILED.
Example:
The following example deletes an entry and a section from an .ini file.
proc main ()

inifilehandle inihandle
string stringFile
string section1, section10, entry
int count
stringFile = "C:\\temp\\test.ini"

if (FileIsIni (stringFile) == TRUE)


inihandle = FileIniOpen (stringFile)

if (FileGetLineCount (inihandle)!= 0)
if (FileGetSectionCount (inihandle) != 0)
section1 = FileGetSectionName (inihandle, 1)
section10 = FileGetSectionName (inihandle, 10)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 21 - INI Format File Manipulation Functions - 257

if (FileGetEntryCount (inihandle, section10) != 0)


entry = FileGetEntryName (inihandle, section10, 1)
endif
endif
endif

FileIniClose (inihandle)
FileDeleteEntry (stringFile, section10, entry)
FileDeleteSection (stringFile, section1)
endif
endproc

FileGetSectionCount
Get the number of sections in an INI format file.
Syntax:
Int FileGetSectionCount (String FileName)
Int FileGetSectionCount (IniFileHandle IniHandle)
FileName is the relative or absolute path of the file to be read.
IniHandle is the handle of the ini file returned by the FileIniOpen function.
Returns:
If successful, the function returns the number of sections found in the file or 0 if the file or section can not be
found or the operation fails. If the supplied file is not a valid INI file the operation fails and ErrCode is set to
ERR_FILENOTVALID otherwise ErrCode is set to ERR_FUNCFAILED.
Example 1:
The following example deletes an entry and a section from an .ini file.
proc main ()

string stringFile
string section, entry
stringFile = "C:\\temp\\test.ini"

if (FileIsIni (stringFile) == TRUE)


if (FileGetSectionCount (stringFile) != 0)
section = FileGetSectionName (stringFile, 1)

if (FileGetEntryCount (stringFile, section) != 0)


entry = FileGetEntryName (stringFile, section, 1)
FileDeleteEntry (stringFile, section, entry)
endif

FileDeleteSection (stringFile, section)


endif
endif

endproc

Example 2:
The following example deletes an entry and a section from an .ini file, using the handle to the file.
proc main ()

inifilehandle inihandle
string stringFile
string section1, section10, entry
stringFile = "C:\\temp\\test.ini"

if (FileIsIni (stringFile) == TRUE)

Numara Software, Inc. and BMC Software, Inc. Confidential.


258 - BMC FootPrints Asset Core - Chilli Reference

inihandle = FileIniOpen (stringFile)

if (FileGetSectionCount (inihandle) != 0)
section1 = FileGetSectionName (inihandle, 1)
section10 = FileGetSectionName (inihandle, 10)

if (FileGetEntryCount (inihandle, section10) != 0)


entry = FileGetEntryName (inihandle, section10, 1)
endif
endif

FileIniClose (inihandle)
FileDeleteEntry (stringFile, section10, entry)
FileDeleteSection (stringFile, section1)
endif

endproc

FileGetSectionName
Given the index to a section, get the name of that section in an INI format file.
Syntax:
String FileGetSectionName (String FileName, Int SectionIndex)
String FileGetSectionName (IniFileHandle IniHandle, Int SectionIndex)
FileName is the relative or absolute path of the file to be read.
IniHandle is the handle of the ini file returned by the FileIniOpen function.
SectionIndex is the index of the section to be named.
Returns:
If successful, the function returns the name of the section. If the file or the indexed section is not found, an empty
string is returned. If the operation fails or the supplied file is not a valid INI file the function fails and ErrCode is
set to ERR_FILENOTVALID.
Comments:
The numbering starts at 1 for the first section.
The second parameter of the function, specifying the section, can be supplied as an integer or a string value.
According to the data type of the value supplied the function then automatically uses the appropriate signature.
Example 1:
The following example deletes an entry and a section from an .ini file.
proc main ()

string stringFile
string section, entry
stringFile = "C:\\temp\\test.ini"

if (FileIsIni (stringFile) == TRUE)


if (FileGetSectionCount (stringFile) != 0)
section = FileGetSectionName (stringFile, 1)

if (FileGetEntryCount (stringFile, section) != 0)


entry = FileGetEntryName (stringFile, section, 1)
FileDeleteEntry (stringFile, section, entry)
endif

FileDeleteSection (stringFile, section)


endif
endif

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 21 - INI Format File Manipulation Functions - 259

Example 2:
The following example deletes an entry and a section from an .ini file, using the handle to the file.
proc main ()

inifilehandle inihandle
string stringFile
string section1, section10, entry
stringFile = "C:\\temp\\test.ini"

if (FileIsIni (stringFile) == TRUE)


inihandle = FileIniOpen (stringFile)

if (FileGetSectionCount (inihandle) != 0)
section1 = FileGetSectionName (inihandle, 1)
section10 = FileGetSectionName (inihandle, 10)

if (FileGetEntryCount (inihandle, section10) != 0)


entry = FileGetEntryName (inihandle, section10, 1)
endif
endif

FileIniClose (inihandle)
FileDeleteEntry (stringFile, section10, entry)
FileDeleteSection (stringFile, section1)
endif

endproc

FileGetValue
Get the value of an entry in a section in an INI format file.
This function has the following signatures:
Syntax:
String FileGetValue (String FileName, Int SectionIndex, Int EntryIndex)
String FileGetValue (String FileName, Int SectionIndex, String EntryName)
String FileGetValue (String FileName, String SectionName, Int EntryIndex )
String FileGetValue (String FileName, String SectionName, String EntryName)
String FileGetValue (IniFileHandle IniHandle, Int SectionIndex, Int EntryIndex)
String FileGetValue (IniFileHandle IniHandle, Int SectionIndex, String EntryName)
String FileGetValue (IniFileHandle IniHandle, String SectionName, Int EntryIndex )
String FileGetValue (IniFileHandle IniHandle, String SectionName, String EntryName)
FileName is the relative or absolute path of the file to be read.
IniHandle is the handle of the ini file returned by the FileIniOpen function.
SectionIndex is the index of the section to be read.
SectionName is the name of the section to be read.
EntryIndex is the index of the entry in the section to be read.
EntryName is the name of the entry to be read.
Returns:
If successful, the function returns the value of the entry within the supplied section expressed as a string. If the
file, section or entry are not found an empty string is returned and no error is generated. If the operation fails or
the file is not a valid INI file the function fails and ErrCode is set to ERR_FILENOTVALID.
Comments:
The numbering starts at 1 for the first section and entry.
The function always returns a string value, even for integer values. You can use MakeInt to convert a string into
an integer type.

Numara Software, Inc. and BMC Software, Inc. Confidential.


260 - BMC FootPrints Asset Core - Chilli Reference

The second and third parameters of the function, specifying the section and entry, can be supplied as integers or
as string values. According to the data type of the value supplied the function then automatically uses the
appropriate signature.
Example 1:
This following example is taken from the main rollout installation procedure for the BCM agent on Windows NT.
It defines a procedure to check the pre-requisite conditions. If any of the conditions fails the installation
procedure is terminated. The procedure uses the signatures which takes a string as its first parameter.
proc GetInfo ()
string IniFile, CPDir, SendTrap, Silent
IniFile = PathGetTemp () + '\ro_boot.ini'
Print (LogFile, "\r\nReading information from " + IniFile + "\r\n")
;Get chilli installation directory
CPDir = FileGetValue (IniFile, 'Client Management', 'Directory')
SendTrap = FileGetValue (IniFile, 'Client Management', 'StartTrap')
Silent = FileGetValue (IniFile, 'Client Management', 'silent')
endproc

proc main ()
GetInfo ()
endproc

Example 2:
The following example is another taken from the main rollout installation procedure for the BCM agent on
Windows NT. This procedure uses a signature with the handle as its first argument.
proc GetInfo ()
inifilehandle IniHandle
string IniFile, CPDir, SendTrap, Silent
IniFile = PathGetTemp () + '\ro_boot.ini'
Print (LogFile, "\r\nReading information from " + IniFile + "\r\n")
;Get BMC Client Management installation directory
if (FileIsIni (IniFile)
inihandle = FileIniOpen (IniFile)
CPDir = FileGetValue (IniHandle, 'Client Management', 'Directory')
SendTrap = FileGetValue (IniHandle, 'Client Management', 'StartTrap')
Silent = FileGetValue (IniHandle, 'Client Management', 'silent')
FileIniClose (IniHandle)
endif
endproc

proc main ()
GetInfo ()
endproc

FileIniClose
Close an existing and open INI file given its handle.
Syntax:
Bool FileIniClose (IniFileHandle IniHandle)
IniHandle is the reference to the handle of the .ini file to be closed.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FILENOTVALID.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 21 - INI Format File Manipulation Functions - 261

Comments:
If the close operation was successful, the supplied handle to the open file becomes invalid and can not be used in
any further manipulation operations.
Any ini file read function started by the FileIniOpen function must be terminated with the FileIniClose
function.
Example:
The following example deletes an entry and a section from an .ini file.
proc main ()

inifilehandle inihandle
string stringFile
string section1, section10, entry
int count
stringFile = "C:\\temp\\test.ini"

if (FileIsIni (stringFile) == TRUE)


inihandle = FileIniOpen (stringFile)

if (FileGetLineCount (inihandle)!= 0)
if (FileGetSectionCount (inihandle) != 0)
section1 = FileGetSectionName (inihandle, 1)
section10 = FileGetSectionName (inihandle, 10)

if (FileGetEntryCount (inihandle, section10) != 0)


entry = FileGetEntryName (inihandle, section10, 1)
endif
endif
endif

FileIniClose (inihandle)
FileDeleteEntry (stringFile, section10, entry)
FileDeleteSection (stringFile, section1)
endif
endproc

FileIniOpen
Open an existing INI file archive given the path and name of the file.
Syntax:
IniFileHandle FileIniOpen (String FilePath)
FilePath is the full directory path of the .ini file to be opened.
Returns:
The handle to the .ini file archive which was opened if the operation was successful, or 0 if the function fails.
If the supplied path exists but is not a valid .ini file the operation fails and a runtime error occurs with ErrCode
being set to ERR_FILENOTVALID, otherwise ErrCode is set to ERR_FUNCFAILED.
Comments:
If the supplied path exists, but the specified file is not a valid ini file or the file does not exist, a runtime error
occurs. Any ini file read function started by the FileIniOpen function must be terminated with the
FileIniClose function.

Example:
The following example deletes an entry and a section from an .ini file.
proc main ()

inifilehandle inihandle
string stringFile

Numara Software, Inc. and BMC Software, Inc. Confidential.


262 - BMC FootPrints Asset Core - Chilli Reference

string section1, section10, entry


int count
stringFile = "C:\\temp\\test.ini"

if (FileIsIni (stringFile) == TRUE)


inihandle = FileIniOpen (stringFile)

if (FileGetLineCount (inihandle)!= 0)
if (FileGetSectionCount (inihandle) != 0)
section1 = FileGetSectionName (inihandle, 1)
section10 = FileGetSectionName (inihandle, 10)

if (FileGetEntryCount (inihandle, section10) != 0)


entry = FileGetEntryName (inihandle, section10, 1)
endif
endif
endif

FileIniClose (inihandle)
FileDeleteEntry (stringFile, section10, entry)
FileDeleteSection (stringFile, section1)
endif
endproc

FileIsIni
Check that a file is a valid INI format file.
Syntax:
Bool FileIsIni (String FileName)
FileName is the relative or absolute path of the file to be checked.
Returns:
TRUE if the file is a valid INI format file, FALSE if it is not or the operation failed. If the operation fails, ErrCode
is set to ERR_FUNCFAILED.
Comments:
For a description of the .INI file format refer to the Windows system documentation. To check whether a file is
an INI format file, this function applies the following algorithm:
• The file must be a text file, as defined by FileIsText.
• Starting from the first line, all lines which start with a semicolon (;) or a rem statement (rem) are ignored.
• The first line which is not ignored by the previous step must start with a ‘[‘ character signifying a section name,
otherwise the file is NOT valid.
• If the previous condition is satisfied, the file is a valid INI format file.
Example:
The following example inserts a line after having made sure the file is a configuration file and writable.
proc main ()

textfilehandle texthandle
string stringFile, line, newline
stringFile = "C:\\temp\\test.ini"

if (FileIsText (stringFile) == TRUE)


if (FileIsIni (stringFile) == TRUE)

if (FileIsWritable (stringFile) == FALSE)


FileSetAttr (stringFile, 32)
endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 21 - INI Format File Manipulation Functions - 263

line = "new text line"


FileInsertLine (stringFile, 1, line + "\r\n")
newline = FileGetLine (texthandle, 1)
endif
endif

endproc

FileMerge
Merge a source file into a destination file.
Syntax:
Bool FileMerge (String FileSource, String FileDest, Bool Override, Bool Delete)
FileSource is the full directory path to the file to be merged into another.
FileDest is the full directory path to the file into which the source file is merged.
Override defines if an existing value in the destination file is to be overwritten by the value of the source
file.
Delete defines if entries which do not exist in the source file are to be deleted from the destination file.
Returns:
TRUE if the operation was successful, FALSE otherwise.

Comments:
If the Override parameter is set to TRUE, entry values in the destination file is overwritten by the value of the same
entry of the source file. If there are no entries with the same name the parameter is ignored.
If the Delete parameter is set to TRUE, entries which exist in the destination file but not in the source file is
deleted.

FileSetValue
Set the value of an entry in a section in an INI format file.
This function has the following signatures:
Syntax:
Bool FileSetValue (String FileName, String SectionName, Int EntryIndex, String EntryValue)
Bool FileSetValue (String FileName, String SectionName, String EntryName, String EntryValue)
Bool FileSetValue (String FileName, Int SectionIndex, String EntryName, String EntryValue)
Bool FileSetValue (String FileName, Int SectionIndex, Int EntryIndex, String EntryValue)
FileName is the relative or absolute path of the file to be written.
SectionIndex is the index of the section to be written.
SectionName is the name of the section to be written.
EntryIndex is the index of the entry in the section to be written.
EntryName is the name of the entry to be written.
EntryValue is the new value to be written to the specified entry.
Returns:
TRUE if the operation was successful, FALSE if the file, section or entry could not be found or the operation
failed. If the operation fails due to an invalid file, ErrCode is set to ERR_FILENOTVALID, otherwise it is set to
ERR_FUNCFAILED.
Comments:
The numbering starts at 1 for the first section and entry.

Numara Software, Inc. and BMC Software, Inc. Confidential.


264 - BMC FootPrints Asset Core - Chilli Reference

The function only accepts string values to be written. To write an integer value, you can use MakeStr to convert
an integer value into a string type. If the specified entry and section do not exist, they are created by the function
before being written to. The second and third parameters of the function, specifying the section and entry, can be
supplied as integers or as string values. According to the data type of the value supplied the function then
automatically uses the appropriate signature.
Example:
This following example creates the chilli.ini file.
proc main ()

string CPDir, SendTrap, Silent


int iCPiniFind
iCPiniFind = FileFind (CPDir + '\chilli.ini')

if (iCPiniFind == 1)
FileSetAttr (CPDir + '\chilli.tmp', 32)
FileRename (CPDir + '\chilli.tmp', CPDir + '\chilli.ini')
endif

FileSetValue (CPDir + '\chilli.ini', "General", "StartTrap", SendTrap)


FileSetValue (CPDir + '\chilli.ini', "General", "silent", Silent)
FileSetValue (CPDir + '\chilli.ini', "InstalledSoftware",
"TranslationFile", CPDir + '\instalsw.trn')

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


LDAP Functions

This chapter explains all LDAP functions of the Chilli Function Library. On Microsoft Windows platforms, the
LDAP functions are supported on:
• Windows NT/2000: Requires Windows NT 4.0 SP4 or later
• Windows 95/98: Requires Windows 95/98 with IE 4.01 or later and DSClient (Active Directory Client Extension
- it enables the client platform to take advantage of features provided by the Windows 2000 Active Directory
Services.)
All functions of this module are included in the ldap.chx file for Windows or ldap.so file for UNIX and Linux.
These functions are also supported on Linux and Solaris versions.

22.1 Introduction
Lightweight Directory Access Protocol (LDAP) is a set of protocols for accessing information directories. It runs
directly over TCP, and can be used to access a standalone LDAP directory service or to access a directory service
that is back-ended by X.500.
Although not yet widely implemented, LDAP should eventually make it possible for almost any application
running on virtually any computer platform to obtain directory information, such as email addresses and public
keys. As LDAP is an open protocol, applications need not worry about the type of server hosting the directory.
LDAP directory service is based on a client-server model. One or more LDPA servers contain the data making up
the LDAP directory tree. An LDAP client connect to an LDAP server and asks it a question. The server responds
with the answer or with a pointer to whre the client can get more information, typically another LDAP server. No
matter which LDAP server a client connect to it sees the same view of the directory: a name presented to one
LDAP server references the same entry it would at another LDAP server.
The LDAP service model is based on entries. An entry is a collection of attributes that have a name, called a
distinguished name (DN). The DN is used to refer to the entry unambiguously. Each of the entry’s attributes has a
type and one or more values. The types are typically mnemonic strings, like “cn” for common name, or “mail” for
email address. The values depend on what type of attribute it is. Directories are arranged in a hierarchical tree-
like structure that reflects political, geographic and/or organizational boundaries. Entries representing countries
appear at the top of the tree. Below them are entries representing states or national organizations. Below them
might be entries representing people, organizational units, printers, documents or just about anything else you
can think of.
LDAP allows you to control which attributes are required and allowed in an entry through the use of a special
attribute called objectclass. The values of the objectclass attribute determines the schema rules the entry
must obey. An entry is referenced by its DN which is constructed by taking the name of the entry itself (called the
relativ distinguished name or RDN) and concatenating the names of its ancestor entries. LDAP defines operations
for interrogating and updating the directory. Operations are provided for adding and deleting an entry from the
directory, changing an existing entry and changing the name of an entry. Most of the time though LDAP is used to
search for information in the directory. The search operation allows some portion of the directory to be searched
for entries that match some criteria specified b a search filter. Information can be requested form each entry that
matches the criteria. LDAP also provides a method for a client to authenticate or prove its identity to a directory
server paving the way for rich access control to protect the information the server contains.

Numara Software, Inc. and BMC Software, Inc. Confidential.


266 - BMC FootPrints Asset Core - Chilli Reference

22.2 Predefined Constants


Following you find the complete list of all predefined constants of the LDAP functions group of the Chilli script
language:
The following are used in the LdapMod structure to indicate the modification operation to perform in an Add/
Modify/Delete function.

Name Type Description


LDAP_DEFAULT_PORT Integer The default port for the LDAP connection, 389
LDAP_MOD_ADD Integer The modification operation in the add function is to add an entry to the tree
LDAP_MOD_DELETE Integer The modification operation in the modify function is to delete an entry from the
tree
LDAP_MOD_REPLACE Integer The modification operation in the modify function is to replace an entry in the
tree
LDAP_SCOPE_BASE Integer The scope of the search operation is limited to the base
LDAP_SCOPE_ONELEVEL Integer The scope of the search operation is limited to the first level below the base
level, excluding the base entry
LDAP_SCOPE_SUBTREE Integer The scope of the search operation is extended to the complete subtree, that is,
the base entry plus all levels below

22.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli LDAP function group module has predefined handle data types
as well as predefined structures.

22.3.1 Predefined Handle Data Types


Predefined handle data types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all predefined handle data types:

Data Type Description


LdapConnectionHandle Object type: reference to the handle to a session with an LDAP server
LdapMessageHandle Object type: reference to the handle to a LDAP server message

LdapConnectionHandle
The LdapConnectionHandle data type is a reference to the handle to a session with an LDAP server.
The functions LdapInit and LdapOpen return a value of this object type that other functions expect as their first
argument. Any open session and thus the value of this object type should always be closed by the LdapUnbind
function.

LdapMessageHandle
The LdapMessageHandle data type is a reference to the handle to a search result message on an LDAP session.
The function LdapSearch returns a value of this object type that other functions expect as one of their
arguments. Any open message and thus the value of this object type should always be closed by the
LdapFreeMessage function.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 22 - LDAP Functions - 267

22.3.2 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated.
Following you find a list of all predefined data types of type structure:

Data Type Description


LdapMod Array specifying the type of operation to be executed on a tree and its elements

LdapMod
The LdapMod structure represents an array specifying the type of modify operation to be executed on an entry in
the tree.
The array specifies a single attribute per array element.
Elements:
Elements Element Type Description
Operation Integer The type of add or modify operation to be executed
Attribute String The attribute to be added or modified
Values String array The values of the attribute to be added or modified

22.4 Functions
Following you find a list of all available LDAP functions:

Function OS Description
LdapAdd Initiate a synchronous add operation that adds an entry to a tree

LdapBindSimple Authenticate a client to a server, using a clear text password

LdapCountEntries Count the number of search entries that a server returned

LdapDelete Remove a leaf entry from the directory tree

LdapFirstEntry Return the first entry of a message

LdapFreeMessage Free a message returned by a search and release any resources associated with the
message handle
LdapGetAttrValues Retrieve the list of values of a given attribute

LdapGetEntryAttrs Retrieve the name of the attributes for a given entry

LdapGetEntryDN Retrieve the distinguished name for a given entry

LdapGetEntryName Retrieve the distinguished name for a given entry

LdapInit Initialise a session with an LDAP server

LdapModify Initiate a synchronous operation to modify an existing entry.

LdapNextEntry Retrieve an entry from a search result chain

LdapOpen Create and initialize a connection block, then open the connection to an LDAP server

LdapSearch A synchronous operation to searche the LDAP directory and return a requested set of
attributes for each entry matched
LdapUnbind Free all resources associated with an LDAP session

Numara Software, Inc. and BMC Software, Inc. Confidential.


268 - BMC FootPrints Asset Core - Chilli Reference

LdapAdd
Initiate a synchronous add operation that adds an entry to a tree.
Syntax:
Bool LdapAdd (LdapConnectionHandle Handle, String DN, LdapMod Values[])
Handle is the handle to the session with the Ldap server.
DN is the distinguished name uniquely identifying the entry in the tree.
Values is the LdapMod array that specifies the add operation as well as the value and attributes of the
entries to be added to the tree.
Returns:
TRUE if the add operation was successful, or FALSE if the handle was invalid or the function failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The parent of the entry being added must already exist or the parent must be empty (equal to the root
distinguished name) for an add operation to succeed. As a synchronous operation, the function does not return
until the operation is complete.
The array of LdapMod structures specifies a single attribute per array element, the attributes cn, objectClass and
sAMAccountName are mandatory.

LdapBindSimple
Authenticate a client to a server, using a clear text password.
Syntax:
Bool LdapBindSimple (LdapConnectionHandle Handle, String UserDN, String Password)
Handle is the handle to the session with the Ldap server.
UserDN is the distinguished name uniquely identifying the user in the tree.
Password is the password corresponding to the user.
Returns:
TRUE if the bind operation was successful, or FALSE if the handle was invalid or the function failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
Subsequent bind calls can be used to re-authenticate over the same connection. Upon completion of the bind
operation, the function returns to the caller.

LdapCountEntries
Count the number of search entries that a server returned.
Syntax:
Int LdapCountEntries (LdapConnectionHandle Handle, LdapMessageHandle Msg)
Handle is the handle to the session with the Ldap server.
Msg is the handle to the message returned by the server.
Returns:
If the function succeeds, it returns the number of entries, otherwise the return value is 0 and the error code is set.
If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
A synchronous operation that removes a leaf entry from the directory tree. Note that LDAP does not support
deletion of entire subtrees in a single operation. As a synchronous operation, the function does not return until
the operation is complete.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 22 - LDAP Functions - 269

LdapDelete
Remove a leaf entry from the directory tree in a synchronous operation.
Syntax:
Bool LdapDelete (LdapConnectionHandle Handle, String DN)
Handle is the handle to the session with the Ldap server.
DN is the distinguished name uniquely identifying the entry in the tree.
Returns:
TRUE if the delete operation was successful, or FALSE if the handle was invalid or the function failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
A synchronous operation that removes a leaf entry from the directory tree. Note that LDAP does not support
deletion of entire subtrees in a single operation. As a synchronous operation, the function does not return until
the operation is complete.

LdapFirstEntry
Return the first entry of a message.
Syntax:
LdapMessageHandle LdapFirstEntry (LdapConnectionHandle Handle, LdapMessageHandle Msg)
Handle is the handle to the session with the Ldap server.
Msg is the handle to the message returned by the server.
Returns:
If the function succeeds, it returns a handle to the first entry in the reuslt chain, otherwise the return value is 0
and the error code is set to ERR_FUNCFAILED.
Comments:
Use the function in conjunction with LdapNextEntry to step through and retrieve the list of entries from a search
result chain.

LdapFreeMessage
Free a message returned by a search and release any resources associated with the message handle.
Syntax:
Bool LdapFreeMessage (LdapMessageHandle Msg)
Msg is the handle to the message returned by the server.
Returns:
TRUE if the operation was successful, FALSE if the operation failed or the handle was invalid. If the function fails,
the ErrCode is set to ERR_FUNCFAILED.

LdapGetAttrValues
Retrieve the list of values of a given attribute.
Syntax:
String[] LdapGetAttrValues (LdapConnectionHandle Handle, LdapMessageHandle Msg, String
AttrName)
Handle is the handle to the session with the Ldap server.
Msg is the handle to the message returned by the server.
AttrName is the of the attribute to read the values from.

Numara Software, Inc. and BMC Software, Inc. Confidential.


270 - BMC FootPrints Asset Core - Chilli Reference

Returns:
If the function is successful it returns an array of strings containing the values of the attribute. If the function fails
or no values were returned, the returned array is empty. If the function fails, ErrCode is set to ERR_FUNCFAILED.

LdapGetEntryAttrs
Retrieve the name of the attributes for a given entry.
Syntax:
String[] LdapGetEntryAttrs (LdapConnectionHandle Handle, LdapMessageHandle Msg)
Handle is the handle to the session with the Ldap server.
Msg is the handle to the message returned by the server.
Returns:
If the function is successful it returns an array of strings containing the names of the attributes returned for an
entry. If the function fails or no attributes were returned, the returned array is empty. If the function fails, ErrCode
is set to ERR_FUNCFAILED.

LdapGetEntryDN
Retrieve the distinguished name for a given entry.
Syntax:
String LdapGetEntryDN (LdapConnectionHandle Handle, LdapMessageHandle Msg)
Handle is the handle to the session with the Ldap server.
Msg is the handle to the message returned by the server.
Returns:
If the function is successful it returns the distinguished name of the supplied entry, otherwise the returned string
is empty. If the function fails, ErrCode is set to ERR_FUNCFAILED.

LdapGetEntryName
Retrieve the distinguished name for a given entry.
Syntax:
String LdapGetEntryName (LdapConnectionHandle Handle, LdapMessageHandle Msg)
Handle is the handle to the session with the Ldap server.
Msg is the handle to the message returned by the server.
Returns:
If the function is successful it returns the distinguished name of the supplied entry, otherwise the returned string
is empty. If the function fails, ErrCode is set to ERR_FUNCFAILED.

LdapInit
Initialise a session with an LDAP server.
Syntax:
LdapHandle LdapInit (String Host, Integer Port)
Host is the name of the server with which to initialize the session.
Port is the number of the port on which to initialize it.
Returns:
An LdapHandle representing the session if the operation was successful or 0 if the operation failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 22 - LDAP Functions - 271

LdapModify
Initiate a synchronous operation to modify an existing entry.
Syntax:
Bool LdapModify (LdapConnectionHandle Handle, String DN, LdapMod Values[])
Handle is the handle to the session with the Ldap server.
DN is the distinguished name uniquely identifying the entry in the tree.
Values is the LdapMod array that specifies the type of the modify operation and the value and attributes of
the entries in the tree to be modified. The type of modify operation can be one of the two follwoing values:
LDAP_MOD_DELETE or LDAP_MOD_REPLACE.
Returns:
TRUE if the modify operation was successful, or FALSE if the handle was invalid or the function failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
If values are being added to or replaced in the entry, the function creates the attribute, if necessary. If values are
being deleted, the function removes the attribute if no values remain. All modifications are performed in the order
in which they are listed.
The array of LdapMod structures specifies a single attribute per array element.

LdapNextEntry
Retrieve an entry from a search result chain.
Syntax:
LdapMessageHandle LdapNextEntry (LdapConnectionHandle Handle, LdapMessageHandle Msg)
Handle is the handle to the session with the Ldap server.
Msg is the handle to the message returned by the server.
Returns:
If the function is successful it returns a handle to the next entry on the result chain. Otherwise the return value is
0 and the error code is set.
Comments:
Use the function in conjunction with LdapFirstEntry to step through and retrieve the list of entries from a search
result chain.

LdapOpen
Create and initialize a connection block, then open the connection to an LDAP server.
Syntax:
LdapHandle LdapOpen (String Host, Integer Port)
Host is the name of the server with which to initialise the session.
Port is the number of the port on which to initialise it.
Returns:
An LdapHandle representing the session if the operation was successful or 0 if the operation failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.

LdapSearch
A synchronous operation to searche the LDAP directory and return a requested set of attributes for each entry
matched.

Numara Software, Inc. and BMC Software, Inc. Confidential.


272 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
LdapMessageHandle LdapSearch (LdapConnectionHandle Handle, String BaseDN, Int Scope, String
Filter, String Attributes[], Bool AttrsOnly)
Handle is the handle to the session with the Ldap server.
BaseDN is the base distinguished name uniquely identifying the start entry in the directory tree at which
the search is to be started.
Scope defines the scope of the search. The scope can be one of the following values: LDAP_SCOPE_BASE,
LDAP_SCOPE_ONELEVEL or LDAP_SCOPE_SUBTREE.
Filter is the filter to be applied to the search.
Attributes is the array of strings containing the attributes which are to be returned for each matching entry.
AttrsOnly defines if only attribute types (TRUE) or both the attibute types and values (FALSE) are to be
returned.
Returns:
TRUE if the search operation was successful, or FALSE if the handle was invalid or the function failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
As a synchronous operation, the function does not return until the operation is complete.
Search filters help you to manage complex queries more easily. They allow you to define search criteria and give
you better control to achieve more effective and efficient searches. For example, you might be interested in all the
users whose surname is "Smith". Or you might want to find out all the team members reporting to the manager
named "John Doe".
Chilli supports the LDAP search filters as defined in RFC2254. These search filters are represented by Unicode
strings. Some examples of LDAP search filters are as follows:

(objectClass=*) All objects


(&(objectCategory=person)(objectClass=user)(!cn=john)) All user objects but "john"
(sn=sm*) All objects with a surname that starts with "sm"
(&(objectCategory=person)(objectClass=contact)(|(sn=Doe)(s All contacts with a surname equal to "Doe" or "Johnson"
n=Johnson)))

These search filters use one of the following formats:


<filter>=(<attribute><operator><value>)
or
(<operator><filter1><filter2>)
If any of the following special characters need to appear in the search filter as literals, they need to be replaced by
the following escape sequence:

ASCII Character Escape Sequence


* \2a
( \28
) \29
\ \5c
NUL \00

LdapUnbind
Free all resources associated with an LDAP session.
Syntax:
Bool LdapUnbind (LdapConnectionHandle Handle)
Handle is the handle to the session with the Ldap server to be closed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 22 - LDAP Functions - 273

Returns:
TRUE if the unbind operation was successful, or FALSE if the handle was invalid or the function failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
After this function has been called the handle to the session is no longer be valid and thus can no longer be used
with other functions, regardless if the operation was successful or if it failed.

22.5 Example
Following you fill find some example scripts on how to use the ldap functions.
Example 1:
include "ldap.chx"
include "message.chx"

const SERVER_NAME "192.168.110.3"


const BASE_DN "DC=support, dc=sophia, dc=metrixsystems, DC=com"
const USER_DN "CN=administrateur, CN=users," + BASE_DN
const USER_PASSWORD "Xton2005"

//*******************************************************************
// DoSearch
//*******************************************************************

proc DoSearch (LdapConnectionHandle ldap, string szFilter)

string szAttrs[2]
int count, i, j, k;
string szValue, szValues[]
LdapMessageHandle msgg, msg[]

szAttrs[1] = "sn"
szAttrs[2] = "*"

msg = LdapSearch (ldap, "cn=Users, " + BASE_DN, LDAP_SCOPE_SUBTREE, szFilter, szAttrs,


TRUE)

if (ArrayGetSize (msg) >= 1)

count = LdapCountEntries (ldap, msg[1])


print (Logfile,"Found " + count + " entries\n")

for (i=1; i<=count; i+=1)


if (i==1)
msgg = LdapFirstEntry (ldap, msg[1])
else
msgg = LdapNextEntry (ldap, msgg)
endif

print (Logfile,"dn: " + LdapGetEntryDn (ldap, msgg) + "\n")

szAttrs = LdapGetEntryAttrs (ldap, msgg)


print (Logfile,"" + ArrayGetSize (szAttrs) + "\n")

for (j=1; j<=ArrayGetSize (szAttrs); j+=1)


print (Logfile," " + szAttrs[j] + " = ")
szValues = LdapGetAttrValues (ldap, msgg, szAttrs[j])
for (k=1; k<=ArrayGetSize (szValues); k+=1)

Numara Software, Inc. and BMC Software, Inc. Confidential.


274 - BMC FootPrints Asset Core - Chilli Reference

print (Logfile,szValues[k])
endfor
print (Logfile,"\n")
endfor

endfor

endif

endproc

//*******************************************************************
// Main
//*******************************************************************

proc main ()

int iError;

ErrHandler = INLINE_HANDLER

LdapConnectionHandle ldap
ldap = LdapOpen (SERVER_NAME, LDAP_DEFAULT_PORT);
if (ErrCode != ERR_SUCCESS)
print (Logfile,"connection failed")
exit (0)
else
print (Logfile,"connected ok...")
endif

LdapBindSimple (ldap, USER_DN, USER_PASSWORD)


if (ErrCode != ERR_SUCCESS)
print (Logfile,"binding failed")
exit (0)
else
print (Logfile,"binded ok...")
endif

string szFilter
szFilter = "(objectclass=*)"

/* String MODIFY_DN

MODIFY_DN = "CN=newperson,CN=Users,DC=support,DC=sophia,DC=metrixsystems,DC=com"

LdapMod LdapValues[1]
LdapValues[1].Operation = LDAP_MOD_REPLACE
LdapValues[1].Attribute = "description"
LdapValues[1].Values <<= "test toto"

LdapModify (ldap, MODIFY_DN, LdapValues)

iError = ErrCode

if (ErrCode != ERR_SUCCESS)
print ("modifying failed: " + iError + ", " + GetErrorName (iError) + ", " +
GetErrorText (iError))
exit (0)
else

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 22 - LDAP Functions - 275

print ("modified ok...")


endif
*/

String ADD_DN

ADD_DN = "CN=lionel,CN=Users,DC=support,DC=sophia,DC=metrixsystems,DC=com"

/* cn, sAMAccountName and objectClass are mandatory */

LdapMod LdapValues[3]
LdapValues[1].Operation = LDAP_MOD_ADD
LdapValues[1].Attribute = "cn"
LdapValues[1].Values <<= "lionel"

LdapValues[2].Operation = LDAP_MOD_ADD
LdapValues[2].Attribute = "objectClass"
LdapValues[2].Values <<= "user"

LdapValues[2].Operation = LDAP_MOD_ADD
LdapValues[2].Attribute = "sAMAccountName"
LdapValues[2].Values <<= "lionel"

LdapAdd (ldap, ADD_DN, LdapValues)

iError = ErrCode

if (ErrCode != ERR_SUCCESS)
print ("adding failed: " + iError + ", " + GetErrorName (iError) + ", " +
GetErrorText (iError))
exit (0)
else
print ("added ok...")
endif

LdapUnbind (ldap);

endproc
Example 2:
This script modifies the description of an LDAP distinguished name attribute.
const SERVER_NAME "192.168.194.2"

const BASE_DN "DC=labnet, DC=engineering, DC=enterprise, dc=com"


const USER_DN "cn=LDAP,cn=Users," + BASE_DN
const USER_PASSWORD "startrek"

const MODIFY_DN 'cn=Mr. Abraham Scott, o=Neutral Space Agency


\/ Victoria\/ St. Edwards Island\/ New Brunswick, dc=enterprise, dc=com'

//*******************************************************************
// DoSearch
//*******************************************************************

proc DoSearch (LdapConnectionHandle ldap, string szFilter)

string szAttrs[2]
szAttrs[1] = "sn"

Numara Software, Inc. and BMC Software, Inc. Confidential.


276 - BMC FootPrints Asset Core - Chilli Reference

szAttrs[2] = "*"

LdapMessageHandle msg
msg = LdapSearch (ldap, BASE_DN, LDAP_SCOPE_SUBTREE, szFilter, szAttrs,
true)

if (msg != 0)

int count
count = LdapCountEntries (ldap, msg)
print ("Found " + count + " entries\n")

int i, j, k;
for (i=1; i<=count; i+=1)
if (i==1)
msg = LdapFirstEntry (ldap, msg)
else
msg = LdapNextEntry (ldap, msg)
endif

print ("dn: " + LdapGetEntryDn (ldap, msg) + "\n")

szAttrs = LdapGetEntryAttrs (ldap, msg)


for (j=1; j<=ArrayGetSize (szAttrs); j+=1)
print (" " + szAttrs[j] + "\n")

string szValues[]
szValues = LdapGetAttrValues (ldap, msg, szAttrs[j])
for (k=1; k<=ArrayGetSize (szValues); k+=1)
print (" " + szValues[k] + "\n")
endfor
endfor

endfor
endif

endproc

//*******************************************************************
// Main
//*******************************************************************

proc main ()

int error;
LdapConnectionHandle ldap

ldap = LdapOpen (SERVER_NAME, LDAP_DEFAULT_PORT);

LdapBindSimple (ldap, USER_DN, USER_PASSWORD)

string szFilter
szFilter = "(objectclass=*)"

DoSearch (ldap, szFilter)

LdapMod LdapValues[1]
LdapValues[1].Operation = LDAP_MOD_REPLACE

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 22 - LDAP Functions - 277

LdapValues[1].Attribute = "description"
LdapValues[1].Values <<= "Just another guy"
LdapModify (ldap, MODIFY_DN, LdapValues)

LdapUnbind (ldap);

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


278 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Encryption Functions

This module contains all encryption functions of the Chilli language. It provides two types of encryption, MD5
hash encryption and DES base 64 encryption. All MD5 hash encryption functions are included in the md5.chx
file for Windows or md5.so file for UNIX and Linux, the DES base 64 encryption functions are included in the
Chilli core.

23.1 MD5 Hash Encryption Functions


MD5 is an algorithm that is used to create digital signatures. It is intended for use with 32 bit machines. MD5 is a
one-way hash function, meaning that it takes a message and converts it into a fixed string of digits.
When using a one-way hash function, one can compare a calculated message digest against the message digest
that is decrypted with a public key to verify that the message has not been tampered with. This comparison is
called a "hashcheck."

23.1.1 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli String Encryption function group module has Predefined Handle
Data Types.

23.1.1.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


MD5Context Object type: reference to the MD5 context

MD5Context
The MD5Context data type is a reference to the handle of an MD5 Context.
This reference is returned by the MD5Start function and is needed in subsequent calls to MD5Update and
MD5End to maintain context.

23.1.2 Functions
Following you find a complete list of all MD5 string encryption functions:

Function OS Description
MD5End End an MD5 Context and return a 32 character hash string

MD5Start Create an MD5 Context

Numara Software, Inc. and BMC Software, Inc. Confidential.


280 - BMC FootPrints Asset Core - Chilli Reference

Function OS Description
MD5Update Update an MD5 Context which the supplied string

MD5End
End an MD5 context and returns a 32 character hash string.
Syntax:
String MD5End (MD5Context)
MD5Context is the handle to the MD5 context returned by the MD5Start function.
Returns:
If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
This function executes the last hashing and returns the 32 character string.
Example:
The following example prints the hashed string of 'my string to hash'.
proc main ()

MD5Context ptrMD5Context
ptrMD5Context = MD5Start ()
MD5Update (ptrMD5Context, "my string to hash")
print ("The corresponding hashed string is " + MD5End (ptrMD5Context))

endproc

MD5Start
Create an MD5 Context.
Syntax:
MD5Context MD5Start ()
Returns:
The reference to the MD5 context if the operation was successful, 0 if the operation failed. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.
Comments:
This function executes the first hashing and returns the MD5 context necessary for all other MD5 functions.
Example:
The following example prints the hashed string of 'my string to hash'.
proc main ()

MD5Context ptrMD5Context
ptrMD5Context = MD5Start ()
MD5Update (ptrMD5Context, "my string to hash")
print ("The corresponding hashed string is " + MD5End (ptrMD5Context))

endproc

MD5Update
Update an MD5 Context with the supplied string.
Syntax:
Int MD5Update (MD5Context, StringToAdd)
MD5Context is the handle to the MD5 context returned by the MD5Start function.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 23 - Encryption Functions - 281

StringToAdd is the string to be added to the MD5 context.


Returns:
1 if the update operation was successful, 0 if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
This function is used to add the provided string to the current MD5 context.
Example:
The following example prints the hashed string of 'my string to hash'.
proc main ()

MD5Context ptrMD5Context
ptrMD5Context = MD5Start ()
MD5Update (ptrMD5Context, "my string to hash")
print ("The corresponding hashed string is " + MD5End (ptrMD5Context))

endproc

23.2 DES base 64 Encryption Functions


Following you find a complete list of all DES base 64 encryption functions:

Function OS Description
StrEncodeBase64 Return the base 64 encoded version of a given string

StrEncodeDESBase64 Return the DES base 64 encoded version of a given string and password.

StrDecodeBase64 Return the decoded version of a base 64 encoded string

StrDecodeDESBase64 Return the decoded version of a DES base 64 encoded string

StrEncodeBase64
Return the base 64 encoded version of a given string.
Syntax:
String StrEncodeBase64 (String Value)
Value is the string to be encoded to Base64.
Returns:
The base 64 encoded version of the given source string, or an empty string if the operation failed.

StrEncodeDESBase64
Return the DESbase 64 encoded version of a given string and password.
Syntax:
String StrEncodeDESBase64 (String Value, String Password)
Value is the string to be encoded to DESBase64.
Password is the key to be used for encryption.
Returns:
Given a source string and a password, The DESbase 64 encrypted version of the given source string and password,
or an empty string if the operation failed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


282 - BMC FootPrints Asset Core - Chilli Reference

StrDecodeBase64
Return the decoded version of a base 64 encoded string.
Syntax:
String StrDecodeBase64 (String Value)
Value is the string to be decoded from Base64.
Returns:
The decoded version of the base 64 encoded string or an empty string if the operation failed.

StrDecodeDESBase64
Return the decoded version of a DES base 64 encoded string and the associated key.
Syntax:
String StrDecodeDESBase64 (String Value, String Password)
Value is the string to be decoded from DESBase64.
Password is the key to be used for decryption.
Returns:
The decrypted version of the DES base 64 encoded string and the associated key or an empty string if the
operation failed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Message Dialog Box Functions

This chapter explains all message functions of the Chilli Function Library. All functions of this module are
included in the mesage.chx file. These functions are not applicable to the UNIX environment.

24.1 Introduction
A message dialog box is a small box that appears on the display screen to give you information or to warn you
about a potentially damaging operation. For example, it might warn you that the system is deleting one or more
files. Unlike normal dialog boxes, message boxes do not require any user input. However, you need to
acknowledge the alert box by pressing the Enter key or clicking a mouse button to make it go away. The functions
of this Chilli module enable you to create such boxes.

24.2 Predefined Constants


Following you find the complete list of all predefined constants of the Message functions group of the Chilli script
language:

Name Type Description


MD_BTN1 Integer Button 1 for a message dialog box.
MD_BTN2 Integer Button 2 for a message dialog box.
MD_BTN3 Integer Button 3 for a message dialog box.

24.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli Message Dialog Box function group module has Predefined
Handle Data Types.

24.3.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


dialog Object type: reference to the dialog box handle

Dialog
The Dialog data type is a reference to the handle of a message dialog box.

Numara Software, Inc. and BMC Software, Inc. Confidential.


284 - BMC FootPrints Asset Core - Chilli Reference

The function MessageCreate returns this object type and most of the other functions expect it as their first
argument. The data type should be closed by the MessageDestroy function.

24.4 Functions
Following you find a list of all existing functions for the Message Dialog Box function group module:

Function OS Description
MessageBox Create and popup a modal message dialog box

MessageCreate Create a message dialog box

MessageDestroy Destroy a message dialog box

MessagePopup Popup (display) a message dialog box

MessageSetButton Set the text on one of the buttons on a message dialog box

MessageSetText Set the text on a message dialog box

MessageSetTitle Set the title text on a message dialog box

MessageBox
Create and pop up a modal message dialog box.
This is a convenience function which does not require the multiple steps of setting up a message dialog box
before displaying it.
Syntax:
Bool MessageBox (String Title, String Text, String Button)
Title is the title string to display at the top of the dialog box.
Text is the main text displayed in the dialog box.
Button is the text displayed on the single button in the dialog box.
Returns:
TRUE to indicate success, FALSE if an error occurs.
Comments:
The displayed dialog box is modal, meaning that the script execution is suspended until the dialog box is closed
by the user by clicking the single button displayed in the dialog box. This function is useful for displaying status
or error messages where sophisticated dialog box management is not required.
Example:
The following example recuperates the first line of all log files and prints them into a .csv file.
proc main ()

string InventoryFile, FileName, InventoryLine


FileFindInfo ptrFileInfo

ptrFileInfo = FileFindOpen ("*.log")


InventoryFile = "InvFile.csv"

While (1)
FileName = FileFindNext (PtrFileInfo)
if FileName == ""
Break
else

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 24 - Message Dialog Box Functions - 285

InventoryLine = FileGetLine (FileName, 1)


Print (InventoryFile, InventoryLine + "\r\n")
endif
EndWhile

if (FileFindClose (ptrFileInfo) == 0)
MessageBox ("ERROR", "Could not close", "OK")
endif

endproc

MessageCreate
Create a message dialog box without displaying it.
Syntax:
Dialog MessageCreate (Int Buttons, Bool Modal)
Buttons is the number of push buttons to display in the dialog box and must be between 0 and 3.
Modal indicates if the dialog box should be Modal (TRUE) or Modeless (FALSE).
Returns:
The function returns a handle to the dialog box if successful and 0 if the operation failed. The function fails if
Modal is TRUE and the number of buttons is 0.
Comments:
To display message dialog boxes you have to use MessageCreate to first create the dialog box and then the other
message functions to set the characteristics of the dialog box. After the dialog box has been prepared, it can be
displayed by calling MessagePopup supplying the dialog box handle. Modal or blocking dialog boxes suspend the
execution of the script until the user closes the dialog box by clicking one of the buttons in the dialog box.
Modeless dialog boxes do not block the script and can be used to display changing text. If a modal dialog box is
being created, then Buttons must be between 1 and 3. Modal dialog boxes must have at least 1 button.

MessageDestroy
Destroy a message dialog box created by MessageCreate.
Syntax:
Bool MessageDestroy (Dialog Handle)
Handle is the handle of the dialog box returned by MessageCreate.
Returns:
TRUE if the message box was successfully destroyed, FALSE if an error occurs.
Comments:
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
MessageCreate. If the dialog box being destroyed is modal, then this function simply releases memory
resources being used by the handle. Due to its nature a modal dialog box cannot be displayed after a
MessagePopup function has completed execution. If the dialog box being destroyed is modeless, this function
removes the dialog box from the screen if it is being displayed and free up the resources being used by it.
Regardless of the dialog box type, after calling this function the supplied handle is no longer valid and can not be
used with any of the message functions.

MessagePopup
Display a message dialog box created by MessageCreate.
Syntax:
Int MessagePopup (Dialog Handle)

Numara Software, Inc. and BMC Software, Inc. Confidential.


286 - BMC FootPrints Asset Core - Chilli Reference

Handle is the handle of the dialog box returned by MessageCreate.


Returns:
The number of the button pressed if the operation was successful or 0 if the function failed or the handle was
invalid.
Comments:
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
MessageCreate. If the dialog is modal, the function does not return until the user clicks on one of the buttons.
The returned value is then the number of the button pressed. If the dialog is not modal, the function returns
immediately with the value TRUE if no other errors occur.

MessageSetButton
Set the text on one of the buttons in a dialog box created by MessageCreate.
Syntax:
Bool MessageSetButton (Dialog Handle, Int Button, String Text)
Handle is the handle of the dialog box returned by MessageCreate.
Button is the number of the button to be modified.
Text is the text to be displayed in the button.
Returns:
TRUE to indicate success, FALSE if an error occurs.
Comments:
The buttons are numbered from left to right with 1 for the first and 3 for the last button.
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
MessageCreate. The maximum length of the text for each button is 16 characters.

MessageSetText
Set the main dialog box text in a dialog box created by MessageCreate.
Syntax:
Bool MessageSetText (Dialog Handle, String Text)
Handle is the handle of the dialog box returned by MessageCreate.
Text is the main text displayed in the dialog box.
Returns:
TRUE to indicate success, FALSE if an error occurs.
Comments:
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
MessageCreate. If the handle is correct the main text message of the dialog box is set to the supplied text.

MessageSetTitle
Set the title bar of a dialog box created by MessageCreate.
Syntax:
Bool MessageSetTitle (Dialog Handle, String Text)
Handle is the handle of the dialog box returned by MessageCreate.
Text is the text displayed in the dialog box title bar.
Returns:
TRUE to indicate success, FALSE if an error occurs.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 24 - Message Dialog Box Functions - 287

Comments:
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
MessageCreate. If the handle is correct the title of the dialog box is set to the supplied text.

24.5 Examples
Code samples for message functions:
Example 1:
The following script creates a message dialog box with one button.
proc main ()

Dialog hMessage

;Create a modal message dialog box with 1 button


hMessage = MessageCreate (1, 1)

;Set the title of the dialog


MessageSetTitle (hMessage, ’Example Dialog Box’)

;Set the main text of the dialog


MessageSetText (hMessage, ’This is the text that appears in the
dialog box.’)

;Set the label of the first (and only button)


MessageSetButton (hMessage, 1, ’Close’)

;Display the dialog box and wait for user to close it


MessagePopup (hMessage)

;Destroy the dialog box handle to free up memory


MessageDestroy (hMessage)

endproc

Example 2:
This example script creates a dialog box with one button and a warning message.
proc main ()

dialog iHandle
int iBoot

iHandle = MessageCreate (2, 1)


MessageSetTitle (iHandle, 'Message Box')
MessageSetButton (iHandle, 1, 'Yes')
MessageSetButton (iHandle, 2, 'No')
MessageSetText (iHandle, "Do you want to reboot your PC now ?")
iBoot = MessagePopup (iHandle)
MessageDestroy (iHandle)

if (iBoot == 1)
MessageBox ("Warning", "Your PC is restarted now", "OK")
Reboot ()
endif

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


288 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Miscellaneous Functions

This chapter explains all miscellaneous functions of the Chilli Language. The string module is included in the
Chilli core and thus always accessible.

25.1 Introduction
This module collects all functions which are not part of any specific Chilli function group, functions which are of
general usage, such as print or wait.
Some of these functions are not applicable or have not yet been implemented for the UNIX environment.

25.2 Predefined Constants


Following you find the complete list of all predefined constants of the miscellaneous functions group of the Chilli
script language:

Name Type Description


SHARETYPE_DEVICE Integer Communication device
SHARETYPE_DISKTREE Integer Disk drive
SHARETYPE_IPC Integer Interprocess communication (IPC)
SHARETYPE_PRINTQ Integer Print queue
SHARETYPE_SPECIAL Integer Special share reserved for interprocess communication (IPC$) or remote administration of the
server (ADMIN$). Can also refer to administrative shares such as C$, D$, E$, and so forth.
SHARETYPE_TEMPORARY Integer A temporary share
SYSINFO__WIN2008_ENTERP Integer The GetSysInfo function returns TRUE if the operating system is Windows 2008 Enterprise,
RISE FALSE otherwise.
SYSINFO_ALPHA Integer The GetSysInfo function returns TRUE if the system is running on a DEC Alpha CPU, FALSE
otherwise.
SYSINFO_ANNVIX Integer The GetSysInfo function returns TRUE if the operating system is ANNVIX, FALSE otherwise.
SYSINFO_ARCH Integer The GetSysInfo function returns TRUE if the operating system is Arch, FALSE otherwise.
SYSINFO_ARKLINUX Integer The GetSysInfo function returns TRUE if the operating system is Ark Linux, FALSE otherwise.
SYSINFO_AUROX Integer The GetSysInfo function returns TRUE if the operating system is Aurox, FALSE otherwise.
SYSINFO_BLACKCAT Integer The GetSysInfo function returns TRUE if the operating system is BlackCat, FALSE otherwise.
SYSINFO_CENTOS Integer The GetSysInfo function returns TRUE if the operating system is CentOS, FALSE otherwise.
SYSINFO_COBALT Integer The GetSysInfo function returns TRUE if the operating system is Cobalt, FALSE otherwise.
SYSINFO_CONNECTIVA Integer The GetSysInfo function returns TRUE if the operating system is Connectiva, FALSE
otherwise.
SYSINFO_DEBIAN Integer The GetSysInfo function returns TRUE if the operating system is Debian, FALSE otherwise.
SYSINFO_FEDORA Integer The GetSysInfo function returns TRUE if the operating system is Fedora, FALSE otherwise.
SYSINFO_GENTOO Integer The GetSysInfo function returns TRUE if the operating system is Gentoo, FALSE otherwise.

Numara Software, Inc. and BMC Software, Inc. Confidential.


290 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


SYSINFO_IMMUNIX Integer The GetSysInfo function returns TRUE if the operating system is Immunix, FALSE otherwise.
SYSINFO_KNOPPIX Integer The GetSysInfo function returns TRUE if the operating system is Knoppix, FALSE otherwise.
SYSINFO_LFS Integer The GetSysInfo function returns TRUE if the operating system is LFS, FALSE otherwise.
SYSINFO_MANDRAKE Integer The GetSysInfo function returns TRUE if the operating system is Mandrake, FALSE otherwise.
SYSINFO_MACOSX Integer The GetSysInfo function returns TRUE if the operating system is Mac OS X, FALSE otherwise.
SYSINFO_MACOSXCHEETAH Integer The GetSysInfo function returns TRUE if the operating system is Mac Cheetah, FALSE
otherwise.
SYSINFO_MACOSXDP4 Integer The GetSysInfo function returns TRUE if the operating system is Mac DP 4, FALSE otherwise.
SYSINFO_MACOSXJAGUAR Integer The GetSysInfo function returns TRUE if the operating system is Mac Jaguar, FALSE
otherwise.
SYSINFO_MACOSXLEOPARD Integer The GetSysInfo function returns TRUE if the operating system is Mac Leopard, FALSE
otherwise.
SYSINFO_MACOSXPANTHER Integer The GetSysInfo function returns TRUE if the operating system is Mac Panther, FALSE
otherwise.
SYSINFO_MACOSXPUMA Integer The GetSysInfo function returns TRUE if the operating system is Mac Puma, FALSE otherwise.
SYSINFO_MACOSXPUBLICBE Integer The GetSysInfo function returns TRUE if the operating system is Mac Public Beta, FALSE
TA otherwise.
SYSINFO_MACOSXSERVER10 Integer The GetSysInfo function returns TRUE if the operating system is Mac Server 10, FALSE
otherwise.
SYSINFO_MACOSXSNOWLEO Integer The GetSysInfo function returns TRUE if the operating system is Mac Snow Leopard, FALSE
PARD otherwise.
SYSINFO_MACOSXTIGER Integer The GetSysInfo function returns TRUE if the operating system is Mac Tiger, FALSE otherwise.
SYSINFO_MANDRIVA Integer The GetSysInfo function returns TRUE if the operating system is Mandriva, FALSE otherwise.
SYSINFO_MKLINUX Integer The GetSysInfo function returns TRUE if the operating system is MK Linux, FALSE otherwise.
SYSINFO_NOVELLINUX Integer The GetSysInfo function returns TRUE if the operating system is Novell Linux, FALSE
otherwise.
SYSINFO_PLD Integer The GetSysInfo function returns TRUE if the operating system is PLD, FALSE otherwise.
SYSINFO_PPC Integer The GetSysInfo function returns TRUE if the operating system is PPC, FALSE otherwise.
SYSINFO_RAM Integer The GetSysInfo function returns the amount of installed physical RAM in MBs.
SYSINFO_REDHAT7 Integer The GetSysInfo function returns TRUE if the system is running Red Hat 7, FALSE otherwise.
SYSINFO_REDHAT8 Integer The GetSysInfo function returns TRUE if the system is running Red Hat 8, FALSE otherwise.
SYSINFO_REDHAT9 Integer The GetSysInfo function returns TRUE if the system is running Red Hat 9, FALSE otherwise.
SYSINFO_REDHAT9COMP Integer The GetSysInfo function returns TRUE if the operating system is Red Hat 9 Comp, FALSE
otherwise.
SYSINFO_RHEL Integer The GetSysInfo function returns TRUE if the operating system is Red Hat Enterprise Linux,
FALSE otherwise.
SYSINFO_SLACKWARE Integer The GetSysInfo function returns TRUE if the operating system is Slack Ware, FALSE
otherwise.
SYSINFO_SMESERVER Integer The GetSysInfo function returns TRUE if the operating system is SME Server, FALSE
otherwise.
SYSINFO_SOLARIS7 Integer The GetSysInfo function returns TRUE if the system is running Solaris 7, FALSE otherwise.
SYSINFO_SOLARIS8 Integer The GetSysInfo function returns TRUE if the system is running Solaris 8, FALSE otherwise.
SYSINFO_SOLARIS9 Integer The GetSysInfo function returns TRUE if the system is running Solaris 9, FALSE otherwise.
SYSINFO_SUSE Integer The GetSysInfo function returns TRUE if the operating system is SUSE, FALSE otherwise.
SYSINFO_SUSEES9 Integer The GetSysInfo function returns TRUE if the operating system is SUSE ES9, FALSE
otherwise.
SYSINFO_TINYSOFA Integer The GetSysInfo function returns TRUE if the operating system is tinysofa, FALSE otherwise.
SYSINFO_TURBOLINUX Integer The GetSysInfo function returns TRUE if the operating system is Turbolinux, FALSE otherwise.
SYSINFO_UBUNTU Integer The GetSysInfo function returns TRUE if the operating system is Ubuntu, FALSE otherwise.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 25 - Miscellaneous Functions - 291

Name Type Description


SYSINFO_ULTRAPENGUIN Integer The GetSysInfo function returns TRUE if the operating system is Ultra Penguin, FALSE
otherwise.
SYSINFO_UNITED Integer The GetSysInfo function returns TRUE if the operating system is United, FALSE otherwise.
SYSINFO_UNIX Integer The GetSysInfo function returns TRUE if the system is running on UNIX, FALSE otherwise.
SYSINFO_VALINUX Integer The GetSysInfo function returns TRUE if the operating system is VA Linux, FALSE otherwise.
SYSINFO_WIN16 Integer The GetSysInfo function returns TRUE if the system is running 16-bit Windows (3.1 or 3.11),
FALSE if it is 32-bits.
SYSINFO_WIN2000 Integer The GetSysInfo function returns TRUE if the operating system is Windows 2000, FALSE
otherwise.
SYSINFO_WIN2000PRO Integer The GetSysInfo function returns TRUE if the operating system is Windows 2000 Professional,
FALSE otherwise.
SYSINFO_WIN2000SRV Integer The GetSysInfo function returns TRUE if the operating system is Windows 2000 Server,
FALSE otherwise.
SYSINFO_WIN2003 Integer The GetSysInfo function returns TRUE if the operating system is Windows 2003, FALSE
otherwise.
SYSINFO_WIN2003_32 Integer The GetSysInfo function returns TRUE if the system is running 32-bit Windows 2003, FALSE
otherwise.
SYSINFO_WIN2003_64 Integer The GetSysInfo function returns TRUE if the system is running 64-bit Windows 2003, FALSE
otherwise.
SYSINFO_WIN2008R2 Integer The GetSysInfo function returns TRUE if the operating system is Windows 2008 R2, FALSE
otherwise.
SYSINFO_WIN2008R2_32 Integer The GetSysInfo function returns TRUE if the operating system is 32-bit Windows 2008 R2,
FALSE otherwise.
SYSINFO_WIN2008R2_64 Integer The GetSysInfo function returns TRUE if the operating system is 64-bit Windows 2008 R2,
FALSE otherwise.
SYSINFO_WIN2008SRV Integer The GetSysInfo function returns TRUE if the operating system is Windows 2008 Server,
FALSE otherwise.
SYSINFO_WIN2008SRV_32 Integer The GetSysInfo function returns TRUE if the system is running 32-bit Windows 2008 Server,
FALSE otherwise.
SYSINFO_WIN2008SRV_64 Integer The GetSysInfo function returns TRUE if the system is running 64-bit Windows 2008 Server,
FALSE otherwise.
SYSINFO_WIN2012SRV Integer The GetSysInfo function returns TRUE if the system is running Windows 2012 Server, FALSE
otherwise.
SYSINFO_WIN2012SRV_32 Integer The GetSysInfo function returns TRUE if the system is running 32-bit Windows 2012 Server,
FALSE otherwise.
SYSINFO_WIN2012SRV_64 Integer The GetSysInfo function returns TRUE if the system is running 64-bit Windows 2012 Server,
FALSE otherwise.
SYSINFO_WIN2012SRV_R2 Integer The GetSysInfo function returns TRUE if the system is running Windows 2012 R2 Server,
FALSE otherwise.
SYSINFO_WIN2012SRV_R2_6 Integer The GetSysInfo function returns TRUE if the system is running 64-bit Windows 2012 R2
4 Server, FALSE otherwise.
SYSINFO_WIN32 Integer The GetSysInfo function returns TRUE if the system is running 32-bit Windows (95/98,NT,
2000 or XP), FALSE otherwise.
SYSINFO_WIN64 Integer The GetSysInfo function returns TRUE if the system is running 64-bit Windows, FALSE
otherwise.
SYSINFO_WIN7 Integer The GetSysInfo function returns TRUE if the operating system is Windows 7, FALSE
otherwise.
SYSINFO_WIN7_32 Integer The GetSysInfo function returns TRUE if the operating system is 32-bit Windows 7, FALSE
otherwise.
SYSINFO_WIN7_64 Integer The GetSysInfo function returns TRUE if the operating system is 64-bit Windows 7, FALSE
otherwise.
SYSINFO_WIN8 Integer The GetSysInfo function returns TRUE if the operating system is Windows 8, FALSE
otherwise.

Numara Software, Inc. and BMC Software, Inc. Confidential.


292 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


SYSINFO_WIN8_32 Integer The GetSysInfo function returns TRUE if the operating system is 32-bit Windows 8, FALSE
otherwise.
SYSINFO_WIN8_64 Integer The GetSysInfo function returns TRUE if the operating system is 64-bit Windows 8, FALSE
otherwise.
SYSINFO_WIN8_1_32 Integer The GetSysInfo function returns TRUE if the operating system is 32-bit Windows 8.1, FALSE
otherwise.
SYSINFO_WIN8_1_64 Integer The GetSysInfo function returns TRUE if the operating system is 64-bit Windows 8.1, FALSE
otherwise.
SYSINFO_WIN95 Integer The GetSysInfo function returns TRUE if the operating system is Windows 95, FALSE
otherwise.
SYSINFO_WIN98 Integer The GetSysInfo function returns TRUE if the operating system is Windows 98, FALSE
otherwise.
SYSINFO_WINME Integer The GetSysInfo function returns TRUE if the operating system is Windows Millenium Edition
(ME), FALSE otherwise.
SYSINFO_WINNT Integer The GetSysInfo function returns TRUE if the operating system is Windows NT, FALSE
otherwise.
SYSINFO_WINNTSRV Integer The GetSysInfo function returns TRUE if the operating system is Windows NT Server, FALSE
otherwise.
SYSINFO_WINNTWKS Integer The GetSysInfo function returns TRUE if the operating system is Windows NT Workstation,
FALSE otherwise.
SYSINFO_WINVERH Integer Defines the major part of the Windows operating system version number.
SYSINFO_WINVERL Integer Defines the minor part of the Windows operating system version number.
SYSINFO_WINVISTA Integer The GetSysInfo function returns TRUE if the operating system is Windows Vista, FALSE
otherwise.
SYSINFO_WINVISTA32 Integer The GetSysInfo function returns TRUE if the system is running 32-bit Windows Vista, FALSE
otherwise.
SYSINFO_WINVISTA64 Integer The GetSysInfo function returns TRUE if the system is running 64-bit Windows Vista, FALSE
otherwise.
SYSINFO_WINXP Integer The GetSysInfo function returns TRUE if the operating system is Windows X, FALSE
otherwise.
SYSINFO_WINXP32 Integer The GetSysInfo function returns TRUE if the system is running 32-bit Windows XP, FALSE
otherwise.
SYSINFO_WINXP64 Integer The GetSysInfo function returns TRUE if the system is running 64-bit Windows XP, FALSE
otherwise.
SYSINFO_WINXPPRO Integer The GetSysInfo function returns TRUE if the operating system is Windows XP Professional,
FALSE otherwise.
SYSINFO_WINXPSRV Integer The GetSysInfo function returns TRUE if the operating system is Windows XP Server, FALSE
otherwise.
SYSINFO_YELLOWDOG Integer The GetSysInfo function returns TRUE if the operating system is Yellow Dog, FALSE
otherwise.
USER_PRIV_ADMIN Integer The user account type is Administrator.
USER_PRIV_GUEST Integer The user account type is Guest.
USER_PRIV_USER Integer The user account type is User.

25.3 Error Codes


Following you find a list of all error codes of the Miscellaneous functions. These errors are run-time errors that
causes the handler specified in ErrorHandler to be invoked. Functions can return these in addition to the standard
runtime errors such as FUNCFAILED. You will find a list with all runtime errors in Appendix E - Chilli Error Codes
on page 677 at the end of the manual.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 25 - Miscellaneous Functions - 293

Name Description
ERR_ACTINPARAM Unable to resolve action input pamareters
ERR_ACTOUTPARAM Unable to set action output pamareters
ERR_ACTFAILED Failed to execute agent action

25.4 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli Miscellaneous function group has predefined data types of type
structure.

25.4.1 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated.
Following you find a list of all predefined data types of type structure:

Data Type Description


CompileResult Structure containing the details of all generated compilation errors.
IpTable Structure containing the details of IpTable firewall rule of a UNIX device.
OpenedPort Structure containing the details of the list of open TCP or UDP port found on a device
SharedResource Structure containing the details of the shared resources found.
UnixOSInfo Structure containing the details of the UNIX operating system found installed on the devices.
WinOSInfo Structure containing the details of the Windows operating system found installed on the devices.

CompileResult
The CompileResult structure contains the details of all generated compilation errors.
Elements:

Elements Element Type Description


ErrorCode Integer The code of the generated error.
ErrorLine Integer The line in the script on which the error occurred.
ErrorText String The text corresponding to the generated error code.

IpTable
The IpTable structure contains the details of IpTable firewall rule of a UNIX device.
Elements:

Elements Element Type Description


Chain String
Target String
Protocol String The protocol of the rule or of the packet to check.
Options String
Source String Source specification. Address can be either a hostname, a network name, or
a plain IP address. The mask can be either a network mask or a plain
number, specifying the number of 1's at the left side of the network mask.
Thus, a mask of 24 is equivalent to 255.255.255.0. A "!" argument before
the address specification inverts the sense of the address.
Destination String Destination specification. See the description of the Source.
Detail String Details of the rule.

Numara Software, Inc. and BMC Software, Inc. Confidential.


294 - BMC FootPrints Asset Core - Chilli Reference

OpenedPort
The OpenedPort structure contains the details of the list of open TCP or UDP port found on a device.
Elements:

Elements Element Type Description


LocalAddress String The IP address of the local host.
LocalPort Integer The port number of the local host.
RemoteAddress String The IP address of the remote host.
RemotePort Integer The port number of the remote host.
State String The current state of the port which can be one of the following: CLOSED,
LISTENING, SYN_SENT, SYN_RECEIVED, ESTABLISHED, FIN_WAIT1,
FIN_WAIT2, CLOSE_WAIT, CLOSING, LAST_ACK, TIME_WAIT or
DELETE_TCB.

SharedResource
The SharedResource structure contains the details of the shared resources found.
Elements:

Elements Element Type Description


Name String The name of the shared resource.
Type Integer The type of the shared resource as defined in the above chapter for the
predefined constants.
Remark String A description of the shared resource if available.
Path String The local path for the shared resource, for example, c:\share, c$, and so on.

UnixOSInfo
The UnixOSInfo structure contains the details of the UNIX operating system found installed on the devices. It is
generally used together with the GetUnixSystemInfo function.
Elements:

Elements Element Type Description


OSName String The name of the operating system.
HostName String The name of the device.
MajorVersion Integer The major version number of the installed operating system.
MinorVersion Integer The minor version number of the installed operating system.

WinOSInfo
The WinOSInfo structure contains the details of the Windows operating system found installed on the devices. It
is generally used together with the GetWindowsSystemInfo function.
Elements:

Elements Element Type Description


OSName String The name of the installed operating system.
MajorVersion Integer The major version number of the installed operating system.
MinorVersion Integer The minor version number of the installed operating system.
BuildNumber Integer The build number of the installed operating system.
ServicePack String The service pack number of the installed operating system.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 25 - Miscellaneous Functions - 295

25.5 Functions
Following you find the list of all functions of the Miscellaneous function module:

Function OS Description
AddNetworkShare Add a network share

CallProcedure Call a Chilli procedure indirectly through its name

CompileScript Compile a chilli script file in order to perform syntax checking

DebugBreak Generate a breakpoint if compiled and running under the debugging environment

DebugDump Perform a debugging dump using the supplied section name to look into the INI file and
decide how the dump should be done
DebugFlushOutput Call the FlushOutput function to make sure that all buffered output is sent out at this point

DelNetworkShare Delete an existing network share

GetBootupTime Get the elapsed time from the last boot

GetEnvString Get the value of an environment variable

GetDomainName Return the Local Domain Name

GetHostName Get the system network name

GetIpTables Return the list of IpTable firewall rules

GetLocalIPAddress Return the local IP address

GetLocalUserAccounts Return the list of users of a specific user account type

GetMacAddress Return the local MAC address

GetNetworkShares Return the list of shared network resources

GetSysDir Get the Windows system directory

GetSysInfo Get a system information parameter

GetSystemDefaultLangID Return the language identifier of the device

GetTcpOpenedPorts Retrieve the list of open TCP ports on a device

GetUdpOpenedPorts Retrieve the list of open UDP ports on a device

GetUnixSystemInfo Retrieve information about the UNIX operating system on the local device

GetWindowsSystemInfo Retrieve information about the Windows operating system on the local device

GetWinDir Get the Windows installation directory

HostNameToIPAddress Return the IP address string in the dotted notation of a specified host machine

Logout Logout the current user on the system

Max Return the larger of two integers

Min Return the smaller of two integers

Print Print a string to a file

Rand Generate a random number

ReadLine Get a line from the console.

Numara Software, Inc. and BMC Software, Inc. Confidential.


296 - BMC FootPrints Asset Core - Chilli Reference

Function OS Description
Reboot Reboot the system

RunProgram Run a program

RunProgramToString Run a program and store its output in a string.

RunProgramAsWithNetwo Run a program and store its output in a string.


rk
SetEnvString Set the value of an environment variable

Shutdown Totally stop the system

Sleep Sleep for a specified number of milli-seconds

Wait Pause for the specified number of seconds

AddNetworkShare
Add a network share.
Syntax:
bool AddNetworkShare (string shareName, string sharePath)
shareName is the name of the newly added share.
sharePath is the path of the share.
Returns:
True if the operation was successful, False if it failed.

CallProcedure
Call a Chilli procedure indirectly through its name.
Syntax:
Bool CallProcedure (String ProcedureName, String ProcedureParms)
ProcedureName is the name of the Chilli procedure to be called.
ProcedureParms is the list of parameters used by the procedure. All elements of this list are enclosed in a
pair of double quotes and individual string elements are surrounded by an additional pair of single quotes.
Returns:
TRUE if the procedure call was successful, FALSE if it failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
This function is used when a script does not know procedure names at compile time and can use configuration
files to resolve the name of a procedure.
Example 1:
The following example line calls a procdure called 'My_proc' with a number of paramters. Note the string "hello"
enclosed in single quotes.
CallProcedure ("My_proc", "1, 4, 'hello', szTmp")

CompileScript
Compile a chilli script file in order to perform syntax checking.
Syntax:
CompileResult CompileScript (String ScriptPath, Bool EmulateCall)
Scriptpath is the full path to the script to be checked.
EmulateCall defines if the function is to be executed in the same way as the call statement.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 25 - Miscellaneous Functions - 297

Returns:
The result is returned in the CompileResult structure. If the file is not found a runtime error is generated. All
other compilation errors are returned in the CompileResult structure. If a fatal error is encountered in the
compiled script it generates a run time error for the running script and not a fatal error.
Comments:
If the EmulateCall boolean is set, the function works in exactly the same way as the 'call' statement except that the
compiled script is not executed. This means that the compiled script gets a copy of the current scripts registered
functions and global variables. If EmulateCall is FALSE, the function behaves like a standalone executable with
default functions and global variables. The result of the compilation, together with any errors is returned in the
CompileResult structure.

DebugBreak
Generate a breakpoint if compiled and running under the debugging environment.
Syntax:
Bool DebugBreak ()
Returns:
TRUE if the operation was successful, FALSE if it failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.

DebugDump
Perform a debugging dump using the supplied section name to look into the chilli.ini file and decide how the
dump should be done.
Syntax:
Bool DebugDump (String SectionName)
SectionName is the name of the debug section in the chilli.ini file.
Returns:
The function returns TRUE if the operation was successful, FALSE if it failed. If the operation fails, ErrCode is set
to ERR_FUNCFAILED.
Comments:
The conditions of the debug dump are defined in the chilli.ini file in the Debug section under the specified
[SectionName] section. This section consists of the following entries:
[SectionName]
OutputPrefix=****************************
OutputSuffix=****************************
OutputType=stdout
OutputName=
DumpSource=
DumpLocals=
DumpGlobals=*
DumpConstants=*
DumpTypes=*
DumpFunctions=*
For more information about the meaning of these entries refer to Configuration, Error Handling and Debugging on
page 65.
Example:
In the chilli.ini file:
[My_Debug_Configuration]
OutputPrefix=****************************<PRE align=left>
OutputSuffix=</PRE>****************************</BODY>
OutputType=stdout
OutputName=

Numara Software, Inc. and BMC Software, Inc. Confidential.


298 - BMC FootPrints Asset Core - Chilli Reference

DumpSource=
DumpLocals=*
DumpGlobals=*
DumpConstants=
DumpTypes=
DumpFunctions=
In the Chilli script:
DebugDump ("My_Debug_Configuration")

DebugFlushOutput
Call the FlushOutput function to make sure that all buffered output is sent out at this point.
Syntax:
Bool DebugFlushOutput ()
Returns:
TRUE if the operation was successful, FALSE if it failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.

DelNetworkShare
Delete an existing network share.
Syntax:
bool DelNetworkShare (string sharePath)
sharePath is the path of the share to be deleted.
Returns:
True if the operation was successful, False if it failed.

GetDomainName
Return the Local Domain Name.
Syntax:
string GetDomainName ()
Returns:
The local domain name if the operation was successful, or an empty string if it failed.
Example:
proc main ()
string szDomainName

szDomainName = GetDomainName ()
Print (LogFile, "The domain name is: " + szDomainName)
endproc

GetBootupTime
Get the elapsed time in seconds from the last boot.
Syntax:
Int GetBootupTime ()
Returns:
The elapsed time since the last boot in seconds if the operation was successful or 0 if the function failed.
Example:
proc main ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 25 - Miscellaneous Functions - 299

int iBootupTime
iBootupTime=GetBootupTime ()
Print („The device has been running for“ + iBootupTime + „seconds“.)

endproc

GetEnvString
Get the value of a system environment variable.
Syntax:
String GetEnvString (String Name)
Name is the environment variable to read.
Value is the string value of the environment variable.
Returns:
The function returns the value of the environment variable as a string if successful and an empty string if the
variable cannot be found.
Comments:
The function always returns a string value, even for integer values. You can use MakeInt to convert a string into
an integer type.
Example:
This example prints the value of the environment variable 'path'.
proc main ()

string Path, host, path


path = “C:\\temp\”
Path = GetEnvString ("path")
Path = Path + GetSysDir () + '\bin;' + GetWinDir () + \bin\ide;'
print (Path)

endproc

GetHostName
Return the system name as used to identify the system in a networked environment.
Syntax:
String GetHostName ()
Returns:
The string value representing the network name of the host the script is running on. The name is usually defined
in the Network applet of the Control Panel.
Example:
This example launches a program depending on the operating system.
proc main ()

string host
host = GetHostName ()

if (host == "HOSTNAME")
if (GetSysInfo (SYSINFO_WIN32))
RunProgram (GetWinDir () + '\program.exe -s', 0)
endif
else
Logout ()
endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


300 - BMC FootPrints Asset Core - Chilli Reference

endproc

GetIpTables
Return the list of IpTable firewall rules.
Syntax:
IpTable[] GetIpTables ()
Returns:
The IpTables array of structures containing the list of firewall rules if the operation was successful, or an empty
array if the operation failed.
Example:
proc main ()
IpTable IpTables[]
int iSize, i

IpTables = GetIpTables ()
iSize = ArrayGetSize (ipTables)

for (i = 1; i <= iSize; i += 1)


Print ("IpTable entry" + i + ": "+ IpTables[i].Chain + "/" + \
IpTables[i].Target + "/" + \
IpTables[i].Protocol + "/" + \
IpTables[i].Options + "/" + \
IpTables[i].Source + "/" + \
IpTables[i].Destination + "/" + \
IpTables[i].Detail + "\n")
endfor
endproc

GetLocalIPAddress
Return the local IP address.
Syntax:
String GetLocalIPAddress ()
Returns:
The IP address of the local host in its dotted notation or 0 if the function failed.
Comments:
The function uses the Socket equivalent to return the local IP address.

GetLocalUserAccounts
Return the list of users of a specific user account type.
Syntax:
string[] GetLocalUserAccounts (int AccountType)
AccountType is the constant defining the type of user account which is requested.
Returns:
Returns an array containing the list of users of the requested type if the operation was successful, or an empty
array if the operation failed.
Comments:
The possible AccountType constants are USER_PRIV_GUEST, USER_PRIV_USER and USER_PRIV_ADMIN.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 25 - Miscellaneous Functions - 301

GetMacAddress
Return the local MAC address.
Syntax:
string GetMacAddress ()
Returns:
Returns the local MAC address if the operation was successful or an empty string if it failed.
Example:
proc main ()
string szMacAddress

szMacAddress= GetMacAddress ()
Print (LogFile, "The MAC Address is: " + szMacAddress)
endproc

GetNetworkShares
Return the list of shared network resources.
Syntax:
SharedResource[] GetNetworkShares ()
Returns:
Returns a structure of type array containing the list of shared resources if the operation was successful or an
empty structure if the operation failed.
Example:
proc main ()
SharedResource Shares[]
int iSize, i
string szShareType

Shares = GetNetworkShares ()
iSize = ArrayGetSize (Shares)

for (i = 1; i <= iSize; i += 1)

// Format the share type in a readable value

if (Shares[i].Type == SHARETYPE_DISKTREE)
szShareType = "Disk Drive"
elif (Shares[i].Type == SHARETYPE_PRINTQ)
szShareType = "Print Queue"
elif (Shares[i].Type == SHARETYPE_DEVICE)
szShareType = "Communication Device"
elif (Shares[i].Type == SHARETYPE_IPC)
szShareType = "Interprocess Communication"
elif (Shares[i].Type == SHARETYPE_SPECIAL)
szShareType = "Special Share"
elif (Shares[i].Type == SHARETYPE_TEMPORARY)
szShareType = "Temporary Share"
endif

// Display share information

Numara Software, Inc. and BMC Software, Inc. Confidential.


302 - BMC FootPrints Asset Core - Chilli Reference

Print ("Share" + i + ": "+ Shares[i].Name + "/" + \


szShareType + "/" + \
Shares[i].Path + "/" + \
Shares[i].Remark + "\n")
endfor
endproc

GetSysDir
Return the Windows system directory.
Syntax:
String GetSysDir ()
Returns:
The string value equal to the full path of the system directory which resides in the Windows installation directory.
For 16-bit Windows this is typically C:\WINDOWS\SYSTEM and for 32 bit Windows this is usually
C:\WINDOWS\SYSTEM32.
This function is not applicable to the UNIX environment.
Example:
This example prints the value of the environment variable 'path'.
proc main ()

string Path, host, path


path = “C:\\temp\”
Path = GetEnvString ("path")
Path = Path + GetSysDir () + '\bin;' + GetWinDir () + \bin\ide;'
print (Path)

endproc

GetSysInfo
Get one of the system information parameters, such as the amount of physical RAM.
Syntax:
Int GetSysInfo (Int Info)
Info is a predefined constant specifying which system parameter to get.
Returns:
The function returns the integer value corresponding to the requested parameter as shown in the table listed
above unter the heading Predefined Constants. If the function fails, or the Info parameter is not valid, 0 is
returned. In this case ErrCode is set to ERR_INVALIDPARAM.
Example:
This following example is taken from the main rollout installation procedure for the BCM agent on Windows NT.
proc main ()

if (GetSysInfo (SYSINFO_WINNT) == FALSE)


Print (LogFile, "Error, this is not a Windows NT system.\r\n")
Print (LogFile, "The contents of the package are not suitable for this system\r\n")
endif

endproc

GetSystemDefaultLangID
Return the language ID of the device.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 25 - Miscellaneous Functions - 303

Syntax:
string GetSystemDefaultLangID ()
Returns:
The language ID of the device or 0 if unsupported.

GetTcpOpenedPorts
Retrieve the list of opened TCP ports on a device.
Syntax:
OpenedPort[] GetTcpOpenedPorts ()
Returns:
The OpenedPort structure containing all relevant information about the open TCP ports on the local machine if
the operation was successful, or an empty string if it failed.
Example:
proc main ()
OpenedPort TCP[]
int iSize, i

TCP = GetTcpOpenedPorts ()
iSize = ArrayGetSize (TCP)

for (i = 1; i <= iSize; i += 1)


Print ("Port" + i + ": "+ TCP[i].LocalAddress + "/" + \
TCP[i].LocalPort + "/" + \
TCP[i].RemoteAddress + "/" + \
TCP[i].RemotePort + "/" + \
TCP[i].State + "\n")
endfor
endproc

GetUdpOpenedPorts
Retrieve the list of opened UDP ports on a device.
Syntax:
OpenedPort[] GetUdpOpenedPorts ()
Returns:
The OpenedPort structure containing all relevant information about the open UDP ports on the local machine if
the operation was successful, or an empty string if it failed.
Example:
proc main ()
OpenedPort UDP[]
int iSize, i

UDP = GetUdpOpenedPorts ()
iSize = ArrayGetSize (UDP)

for (i = 1; i <= iSize; i += 1)


Print ("Port" + i + ": "+ UDP[i].LocalAddress + "/" + \
UDP[i].LocalPort + "/" + \
UDP[i].State + "\n")
endfor
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


304 - BMC FootPrints Asset Core - Chilli Reference

GetUnixSystemInfo
Retrieve information about the UNIX operating system on the local device.
Syntax:
UnixOSInfo GetUnixSystemInfo ()
Returns:
The UnixOSInfo structure containing all relevant information about the UNIX operating system installed on the
local device if the operation was successful, or an empty structure if it failed.
Example:
proc main ()

UnixOSInfo infos

infos = GetUnixSystemInfo ()

Print ("OS Name: " + infos.OSName)

endproc

GetWindowsSystemInfo
Retrieve information about the Windows operating system on the local device.
Syntax:
WinOSInfo GetWindowsSystemInfo ()
Returns:
The WinOSInfo structure containing all relevant information about the Windows operating system installed on
the local device if the operation was successful, or an empty structure if it failed.
Example:
proc main ()

WinOSInfo infos

infos = GetWindowsSystemInfo ()

Print ("OS Name: " + infos.OSName + " - Service Pack " + infos.ServicePack)

endproc

GetWinDir
Return the Windows installation directory.
Syntax:
String GetWinDir ()
Returns:
The string value equal to the full path of the directory in which the Windows operating system is installed. This is
typically C:\WINDOWS.
This function is not applicable to the UNIX environment.
Example:
This example runs a program depending on the operating system.
proc main ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 25 - Miscellaneous Functions - 305

string Path, host, path


path = ’C:\temp\’
Path = GetEnvString ("path")
Path = Path + GetSysDir () + '\bin;' + GetWinDir () + '\bin\ide;'
SetEnvString ("path", Path)

host = GetHostName ()
if (host == "HOSTNAME")
if (GetSysInfo (SYSINFO_WIN32))
RunProgram (GetWinDir () + '\program.exe -s', 0)
endif
else
Logout ()
endif

endproc

HostNameToIPAddress
Return the IP address string in the dotted notation of a specified host machine.
Syntax:
String HostNameToIPAddress (String HostName)
HostName is the name of the host machine.
Returns:
An IP address string in the classical form ‘194.7.204.4’ for the symbolic name of the specified machine if the
operation was successful, 0 if the operation failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.

Logout
Logout the current user on the system.
Syntax:
Bool Logout ()
Returns:
Syntactically the function returns TRUE or FALSE, but if the operation is successful, it does not actually return
because the Windows system log the current user out and close down most running programs. If the function
fails, it returns FALSE.
Example:
This example runs a program depending on the operating system.
....
string host
host = GetHostName ()
if (host = "HOSTNAME")
if (GetSysInfo (SYSINFO_WIN32))
RunProgram (GetWinDir () + '\program.exe -s', 0)
endif
else
Logout ()
endif
....

Max
Return the higher of two integer values.
Syntax:
Int Max (Int Value1, Int Value2)
Value1 and Value2 are the two integer values to compare.

Numara Software, Inc. and BMC Software, Inc. Confidential.


306 - BMC FootPrints Asset Core - Chilli Reference

Returns:
The integer value equal to the higher of the two supplied values.
Example:
This example returns first the lower and then the higher of two randomly generated integers.
proc main ()

int rand1, rand2, imin, imax


rand1 = Rand ()
Wait (10)

rand2 = Rand ()
imin = Min (rand1, rand2)
imax = Max (rand1, rand2)

endproc

Min
Return the lower of two integer values.
Syntax:
Int Min (Int Value1, Int Value2)
Value1 and Value2 are the two integer values to compare.
Returns:
The integer value equal to the lower of the two supplied values.
Example:
This example returns first the lower and then the higher of two randomly generated integers.
proc main ()

int rand1, rand2, imin, imax


rand1 = Rand ()
Wait (10)

rand2 = Rand ()
imin = Min (rand1, rand2)
imax = Max (rand1, rand2)

endproc

Print
Append a string expression to the end of a file or to stdout.
This function has the following two signatures:
Syntax:
Int Print (String Line)
Int Print (String FileName, String Line)
Line is the string expression to be appended to the end of the file specified in FileName.
FileName is the relative or absolute path of the file to be written to.
Returns:
Length of the printed line if successful, 0 if the function failed.
Comments:
The Print function takes a string parameter as the parameter to print and adds it to the end of the file if the file is
defined as its first argument. If no file name is defined the string parameter is printed to stdout. This function
can be combined with the + operator on strings and characters to create complex strings very easily.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 25 - Miscellaneous Functions - 307

Example:
This example prints a time string corresponding to the current system date and time, such as Script started on
23/9/2000 at 14:20:45. If the specified file does not exist it is created.
proc main ()

string LogFile
LogFile = “C:\\temp\\logfile.txt”

Print (LogFile, “\r\nScript started on ”)


Print (LogFile, MakeStr (TimeGetDay()) + “/”)
Print (LogFile, MakeStr (TimeGetMonth()) + “/”)
Print (LogFile, MakeStr (TimeGetYear()))
Print (LogFile, “ at “)
Print (LogFile, MakeStr (TimeGetHour()) + “:”)
Print (LogFile, MakeStr (TimeGetMinute()) + “:”)
Print (LogFile, MakeStr (TimeGetSecond()) + “.”)
Print (LogFile, “\r\n”)

endproc
This piece of code prints a time string corresponding to the current system date and time, such as Script
started on 23/9/2000 at 14:20:45. If the specified file does not exist it is created.

Rand
Return a randomly generated number between 0 and 32767.
Syntax:
Int Rand ()
Returns:
A randomly generated number between 0 and 32767 inclusive. This example returns first the lower and then the
higher of two randomly generated integers.
proc main ()

int rand1, rand2, imin, imax


rand1 = Rand ()
Wait (10)

rand2 = Rand ()
imin = Min (rand1, rand2)
imax = Max (rand1, rand2)

endproc

ReadLine
Get a line from the console.
Syntax:
string ReadLine ()
Returns:
The string entered by the user if the operation was successful or an empty string if the line contains no characters
or the function failed.
Comments:
The line consists of all characters up to and including the first newline character. This can also be an empty string
if the user just hit the Return key. The program pauses until the user enters something. Due to the limitations of
the lower level system calls used, the input buffer used to collect the user input is limited to 8192 bytes. If the
user enters more text than this limit the results are unpredictable.

Numara Software, Inc. and BMC Software, Inc. Confidential.


308 - BMC FootPrints Asset Core - Chilli Reference

The console is only opened if a previous Print function was used to output something to the console. This is
almost always the case as the print typically outputs the prompt to the user.

Reboot
Reboot the system.
Syntax:
Bool Reboot ()
Returns:
Syntactically the function returns TRUE or FALSE, but if the operation is successful, it does not actually return
because the Windows system exits and the system starts a reboot. If the function fails, it returns FALSE.
Comments:
This function has not yet been implemented for the UNIX environment.
Example:
This example creates a warning message box before rebooting a machine.
proc main ()

int iBoot
dialog iHandle

iHandle = MessageCreate (2, TRUE)


MessageSetTitle (iHandle, 'Message Box')
MessageSetButton (iHandle, 1, 'Yes')
MessageSetButton (iHandle, 2, 'No')
MessageSetText (iHandle, "Do you want to reboot your PC now ?")

iBoot = MessagePopup (iHandle)


MessageDestroy (iHandle)

if (iBoot == 1)
MessageBox ("Warning", "Your PC is restarted now", "OK")
Reboot ()
endif

endproc

RunProgram
Run a program and optionally wait for it to terminate. This function has several signatures.
Syntax:
Int RunProgram (String CommandLine, Int WaitTime)
Int RunProgram (String CommandLine, Int WaitTime, Bool BlindMode)
Int RunProgram (String CommandLine, Int WaitTime, String OutputFile, String ErrorFile)
Int RunProgram (String CommandLine, Int WaitTime, String OutputFile, String ErrorFile,
String ExitCodeVarName)
Int RunProgram (String CommandLine, Int WaitTime, String OutputFile, String ErrorFile,
String ExitCodeVarName, Bool BlindMode)
Int RunProgram (String CommandLine, Int WaitTime, String OutputFile, String ErrorFile,
String ExitCodeVarName, Bool BlindMode, Bool WorkingDirectory)
Int RunProgram (String CommandLine, Int WaitTime, String OutputFile, String ErrorFile,
String ExitCodeVarName, UserHandle UserToken)
Int RunProgram (String CommandLine, Int WaitTime, String OutputFile, String ErrorFile,
String ExitCodeVarName, Bool BlindMode, Bool WorkingDirectory, UserHandle UserToken)
CommandLine is the complete command line (including parameters) to be executed.
WaitTime is the maximum number of seconds to wait for the program to terminate.
BlindMode is an optional parameter defining if the program is run in hidden mode.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 25 - Miscellaneous Functions - 309

OutputFile is an optional parameter and provides path to the output redirection file.
ErrorFile is an optional parameter and provides path to the error redirection file.
ExitCodeVarName is an optional parameter and supplies the exit code variable name.
WorkingDirectory is an optional parameter is the absolute path to the directory from which the exectuable is
to be launched.
UserToken is an optional parameter defining the login as which the program is to be launched.
Returns:
1 if the program was successfully started, 0 otherwise.
Comments:
If the Wait time is 0, the script does not wait for the program to terminate. If the time is 9999 or more the scripts
waits for the child indefinitely. If an output/error redirection filename is specified and not empty the output/error
of the run program is redirected (concatenated) to the file.
Example:
This following example is taken from the main rollout installation procedure for the BCM agent on Windows NT.
proc main ()

string szRC, szWWDir

if (szRC == "Yes")
RunProgram (szWWDir + '\chilli.exe', 0)
endif

Wait (10)
DirSetCurrent (szWWDir + '\rp\')
RunProgram (szWWDir + '\rp\rp32nt.exe', 0)
Wait (6)

endproc

RunProgramAsWithNetwork
Run a program and optionally wait for it to terminate.
Syntax:
int RunProgramWithNetworkSession (string CommandLine, int Wait, string OutputFile, string
ErrorFile, string ExitCodeVarName, bool BlindMode, bool WorkingDirectory, string RunAs,
string RunAsPassword, string PathUser, string PathPassword, string Path)
CommandLine is the complete command line (including parameters) to be executed.
Returns:
TRUE if the file was successfully created and the output stored in it, FALSE otherwise.

RunProgramToString
Run a program and store its output in a string.
Syntax:
BOOL RunProgram (String CommandLine)
CommandLine is the complete command line (including parameters) to be executed.
Returns:
TRUE if the file was successfully created and the output stored in it, FALSE otherwise.

SetEnvString
Set the value of a system environment variable.

Numara Software, Inc. and BMC Software, Inc. Confidential.


310 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
Bool SetEnvString (String Name, String Value)
Name is the environment variable to change.
Value is the new string value for the environment variable.
Returns:
TRUE if the environment variable was set successfully, FALSE if it failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
If the named variable does not exist, it is created. This function is only supported on 32 bit version of Chilli,
namely those for Windows 95/98 and NT. On 16-bit Windows, the function returns FALSE with ErrCode set to
ERR_FUNCNOTSUPP.
Example:
This example runs a program depending on the operating system.
proc main ()

string Path, host, path


path = ’C:\temp\’
Path = GetEnvString ("path")
Path = Path + GetSysDir () + '\bin;' + GetWinDir () + '\bin\ide;'
SetEnvString ("path", Path)

host = GetHostName ()
if (host == "HOSTNAME")
if (GetSysInfo (SYSINFO_WIN32))
RunProgram (GetWinDir () + '\program.exe -s', 0)
endif
else
Logout ()
endif

endproc

Shutdown
Totally stop the system.
Syntax:
Int Shutdown ()
Returns:
Syntactically 1 for success or 0 for failed but if successful, the function does not return.
Comments:
Although this function is written to behave in the same way as any other function, its operation means that it does
not return in case of success.

Sleep
Sleep for a specified number of milli-seconds.
Syntax:
Bool Sleep (Int SleepTime)
SleepTime is the number of milli-seconds the operation is to sleep.
Returns:
TRUE if the operation was successful, FALSE if it failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 25 - Miscellaneous Functions - 311

Example:
Sleep (int):

int iSeconds
for (iSeconds = 0; iSeconds <= 60; iSeconds += 1)
Sleep (1000)
Print (MakeStr (iSeconds) + "\n")
endfor

Wait
Suspend script execution for a number of seconds.
Syntax:
Bool Wait (Int WaitTime)
WaitTime is the number of seconds to suspend the script.
Returns:
TRUE after the specified delay interval has successfully passed, FALSE if the function failed. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.
Comments:
This function has not yet been implemented into the UNIX environment.
Example:
This following example is taken from the main rollout installation procedure for the BCM agent on Windows NT.
proc main ()

int iHandle, iBoot


string szRCReg, RefWinDir, RefSysDir, szPackageFile

ErrHandler = INLINE_HANDLER
RefWinDir = GetWinDir ()
RefSysDir = GetSysDir ()
StrCase = True
LogFile = DirGetCurrent () + '\rollout.log'
szPackageFile = PathGetTemp () + '\ro_wwnt.pkg'

Wait (3)
Print (LogFile, "\r\n\r\n")
Print (LogFile, "\r\nSecond part of the installation started on ")

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


312 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


ODBC Functions

This chapter details all functions and elements which handle the ODBC support to access data on the BCM
databases. All functions of this module are included in the odbc.chx file for Windows or odbc.so file for UNIX
and Linux.
This module is limited in its handling of prepared statements, because all statement executions are immediate,
but they do not support prepared statements or parameters.

26.1 Introduction
ODBC (Open DataBase Connectivity) is a standard database access method, the goal of which is to make it
possible to access any data from any application, regardless of which database management system (DBMS) is
handling the data. It is based on the Call-Level Interface (CLI) specifications from X/Open and ISO/IEC for
database APIs and uses Structured Query Language (SQL) as its database access language. ODBC permits
maximum interoperability - an application can access data in diverse DBMSs through a single interface.
Furthermore, that application is independent of any DBMS from which it accesses data.
By using the functions of this Chilli module you can directly access and retrieve all data stored in the BCM
databases.

26.2 Predefined Constants


Following you find the complete list of all predefined constants of the ODBC functions group of the Chilli
language:

Constant Type Description


SQLFETCH Integer The rowset to return
SQLNULL Integer The column allows or disallows NULL values
SQLTYPE Integer The data type in which the value is returned

SQLFETCH
The SQL fetch constant is mainly used by the ODBCFetchScroll function and can be one of the following values:

Constant Description

SQL_FETCH_ABSOLUTE Return the rowset starting at row FetchOffset (1 for the first row)

SQL_FETCH_FIRST Return the first rowset in the result set; the value of FetchOffset is ignored

SQL_FETCH_LAST Return the last complete rowset in the result set; the value of FetchOffset is ignored

SQL_FETCH_NEXT Return the next rowset; the value of FetchOffset is ignored

SQL_FETCH_PRIOR Return the prior rowset; the value of FetchOffset is ignored

Numara Software, Inc. and BMC Software, Inc. Confidential.


314 - BMC FootPrints Asset Core - Chilli Reference

Constant Description

SQL_FETCH_RELATIVE Return the rowset FetchOffset from the start of the current rowset

SQLNULL
The SQL nullable constant is mainly used by the ODBCGetColumnIsNullable function and can be one of the
following values:

Constant Description

SQL_NO_NULLS The column does not allow NULL values

SQL_NULLABLE The column allows NULL values

SQL_NULLABLE_UNKNOWN The driver cannot determine if the column allows NULL values

SQLTYPE
The SQL data types constant is mainly used by the ODBCGetColumnType function and can be one of the following
values:

Constant Description

SQL_BIGINT Exact numeric value with precision 19 (if signed) or 20 (if unsigned) and scale 0
(signed: –2[63] <= n <= 2[63] – 1, unsigned: 0 <= n <= 2[64] – 1)

SQL_BINARY Binary data of fixed length n

SQL_BIT Single bit binary data

SQL_CHAR Character string of fixed string length n

SQL_DATE Return the year, month, and day fields, conforming to the rules of the Gregorian calendar in the format
of yyyy-mm-dd

SQL_DECIMAL Signed, exact, numeric value with a precision of at least p and scale s. (The maximum precision is
driver-defined; 1 <= p <= 15; s <= p)

SQL_DOUBLE Signed, approximate, numeric value with a binary precision 53 (zero or absolute value 10[–308] to
10[308])

SQL_FLOAT Signed, approximate, numeric value with a binary precision of at least p. (The maximum precision is
driver-defined.

SQL_INTEGER Exact numeric value with precision 10 and scale 0


(signed: –2[31] <= n <= 2[31] – 1, unsigned: 0 <= n <= 2[32] – 1)

SQL_LONGVARBINARY Variable length binary data. Maximum length is data source–dependent

SQL_LONGVARCHAR Variable length character data. Maximum length is data source–dependent

SQL_NUMERIC Signed, exact, numeric value with a precision p and scale s (1 <= p <= 15; s <= p)

SQL_REAL Signed, approximate, numeric value with a binary precision 24 (zero or absolute value 10[–38] to 10[38])

SQL_SMALLINT Exact numeric value with precision 5 and scale 0


(signed: –32,768 <= n <= 32,767, unsigned: 0 <= n <= 65,535)

SQL_TIME Return the hour, minute, and second fields, with valid values for hours of 00 to 23, valid values for
minutes of 00 to 59, and valid values for seconds of 00 to 59 and in the form of hh:mm:s

SQL_TIMESTAMP Return the year, month, day, hour, minute, and second fields, with valid values as defined for the DATE
and TIME data types in the form of yyyy-mm-dd hh:mm:ss

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 26 - ODBC Functions - 315

Constant Description

SQL_TINYINT Exact numeric value with precision 3 and scale 0


(signed: –128 <= n <= 127, unsigned: 0 <= n <= 255)

SQL_VARBINARY Variable length binary data of maximum length n; the maximum is set by the user

SQL_VARCHAR Variable-length character string with a maximum string length n

SQL_WCHAR Unicode character string of fixed string length n

SQL_WLONGVARCHAR Unicode variable-length character data; maximum length is data source–dependent

SQL_WVARCHAR Unicode variable-length character string with a maximum string length n

26.3 Error Codes


Following you find the complete list of ODBC error codes. These errors are run-time errors that causes the handler
specified in Error Handler to be invoked:

Name Description
ERR_ODBC Error ODBC
ERR_CONNECTION ODBCConnectionHandle error
ERR_STATEMENT ODBCStatementHandle error

26.4 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli ODBC function group has predefined handle data types as well
as predefined structures.

26.4.1 Predefined Handle Data Types


Predefined handle data types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all predefined handle data types:

Data Type Description


ODBCConnectionHandle Object type: reference to the handle of an ODBC connection
ODBCStatementHandle Object type: reference to the handle of an ODBC statement

ODBCConnectionHandle
The ODBCConnectionHandle data type is a reference to the handle of an ODBC connection.
The function ODBCConnect returns a value of this object type and many other functions expect it as their first
argument. Any open connection and thus the value of this object type must be closed by the ODBCDisconnect
function.

ODBCStatementHandle
The ODBCStatementHandle data type is a reference to the handle of any newly created ODBC statement.
The function ODBCCreateStatement returns a value of this object type and a number of other ODBC functions
expect it as their first argument.

Numara Software, Inc. and BMC Software, Inc. Confidential.


316 - BMC FootPrints Asset Core - Chilli Reference

26.4.2 Predefined Structures


Predefined structure data types are structures produced and used by functions for easier representation of data
that are to be manipulated. For each predefined structure an array type of this structure also exists for usage in the
scripts.
Following you find a list of all predefined structures of this module:

Data Type Description


ODBCDate Represents a calendar date
ODBCTime Represents a time value
ODBCDataSource Represents a list of available data sources and their descriptions

ODBCDate
The ODBCDate structure represents a list of date values conforming to the rules of the Gregorian calendar.
Elements:

Elements Element Type Description


Day Integer The day of the month, 1-31
Month Integer The month of the year, 1 being January, 2 February, and so on.
Year Integer The year in its full version, for example, 2002

ODBCTime
The ODBCTime structure represents a list of time values, with valid values for hours of 00 to 23, valid values for
minutes of 00 to 59, and valid values for seconds of 00 to 59.
Elements:

Elements Element Type Description


Hour Integer The hour value of a specific time
Minute Integer The minute value of a specific time
Second Integer The seconds value of a specific time

ODBCDataSource
The ODBCDataSource structure represents a list of available data source names and their descriptions.
Elements:

Elements Element Type Description


Name String The name of the data source
Description String The description of the data source

26.5 Functions
The ODBC functions are divided into the following subgroups:
• General Functions
• Methods from Statement
• Methods to retrieve attribute values either by column number or by name

26.5.1 General Functions


Following you find a list of all available general ODBC functions:

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 26 - ODBC Functions - 317

Function OS Description
ODBCConnect Open an ODBC connection

ODBCDisconnect Close an ODBC connection

ODBCEndTransaction Commit or roll back a transaction in manual-commit mode

ODBCGetColumns Return the list of column names in specified tables

ODBCGetDataSources Fetch a list of all available data sources on the system

ODBCGetTables Get the list of table, catalog, or schema names, and table types

ODBCConnect
Open an ODBC connection.
Syntax:
ODBCConnectionHandle ODBCConnect (String DSN, String Username, String Password)
DSN specifies the data source name to connect to.
UserID is the name of the user for the ODBC connection.
Password is the respective password of the user ID for the ODBC connection.
Returns:
A handle of type ODBCConnectionHandle which is needed for all query and update accesses to the database. If an
error occurs or the function fails, 0 is returned and the ErrCode is set to ERR_FUNCFAILED.
Comments:
Connecting to a data source means establishing communications with a DBMS in order to access the data. When
connecting to a data source from an application through an ODBC driver, the driver establishes the connection,
either locally or across a network.

ODBCDisconnect
Close an ODBC connection.
Syntax:
Bool ODBCDisconnect (ODBCConnectionHandle Handle)
Handle is the handle to the ODBC connection which is to be disconnected.
Returns:
TRUE if the connection was valid and closed, FALSE if the supplied handle was not valid or the function failed. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The ODBC connection is identified by the supplied handle. Closing a connection also invalidates all statements,
cursors and result sets associated with that connection.

ODBCGetColumns
Return the list of column names in specified tables.
Syntax:
Bool ODBCGetColumns (ODBCStatementHandle Statement, String CatalogName, String SchemaName,
String TableName, String ColumnName)
Statement is the handle to the statement of the ODBC connection
CatalogName is the name of the catalog.
SchemaName is the string search pattern for schema names.
TableName is the string search pattern for table names.

Numara Software, Inc. and BMC Software, Inc. Confidential.


318 - BMC FootPrints Asset Core - Chilli Reference

ColumnName is the string search pattern for column names.


Returns:
TRUE if the function was successfully executed, FALSE in case of an error or if the handle was invalid. If no error
occurs, the column information can be accessed through the ODBCGet functions using the supplied statement
handle. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The driver returns this information as a result set on the specified statement handle.
This function typically is used before statement execution to retrieve information about columns for a table or
tables from the data source's catalog. ODBCGetColumns can be used to retrieve data for all types of items returned
by ODBCGetTables. In addition to base tables, this can include (but is not limited to) views, synonyms, system
tables, and so on. By contrast, the functions ODBCGetColumnType, ODBCGetColumnName and so on describe the
columns in a given result set.
Note that the function might not return all columns. For example, a driver might not return information about
pseudo-columns, such as Oracle ROWID.
If a driver supports catalogs for some tables but not for others, such as when the driver retrieves data from
different DBMSs, an empty string ("") for the CatalogName denotes those tables that do not have catalogs.
CatalogName cannot contain a string search pattern.
If a driver supports schemas for some tables but not for others, such as when the driver retrieves data from
different DBMSs, an empty string ("") denotes those tables that do not have schemas. Schema name can be a
pattern value in the same way as for the ODBCGetTables function.
The following table lists the columns in the result set. Additional columns beyond column 18 (IS_NULLABLE)
can be defined by the driver. Some of the columns can be different depending on the driver.

Data
Column Name Number Description
Type

TABLE_CAT 1 Varchar Catalog name; NULL if not applicable to the data source. If a driver supports
catalogs for some tables but not for others, such as when the driver retrieves data
from different DBMSs, it returns an empty string ("") for those tables that do not
have catalogs.

TABLE_SCHEM 2 Varchar Schema name; NULL if not applicable to the data source. If a driver supports
schemas for some tables but not for others, such as when the driver retrieves data
from different DBMSs, it returns an empty string ("") for those tables that do not
have schemas.

TABLE_NAME 3 Varchar Table name.

COLUMN_NAME 4 Varchar Column name. The driver returns an empty string for a column that does not have a
name.

DATA_TYPE 5 Smallint SQL data type. This can be an ODBC SQL data type or a driver-specific SQL data
type.

TYPE_NAME 6 Varchar Data source–dependent data type name; for example, "CHAR", "VARCHAR",
"MONEY".

COLUMN_SIZE 7 Integer If DATA_TYPE is SQL_CHAR or SQL_VARCHAR, this column contains the


maximum length in characters of the column. For datetime data types, this is the
total number of characters required to display the value when converted to
characters. For numeric data types, this is either the total number of digits or the
total number of bits allowed in the column, according to the NUM_PREC_RADIX
column.

BUFFER_LENGTH 8 Integer The length in bytes of data transferred on reading the column.

DECIMAL_DIGITS 9 Smallint The total number of significant digits to the right of the decimal point.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 26 - ODBC Functions - 319

Data
Column Name Number Description
Type

NUM_PREC_RADIX 10 Smallint For numeric data types, either 10 or 2. If it is 10, the values in COLUMN_SIZE and
DECIMAL_DIGITS give the number of decimal digits allowed for the column. For
example, a DECIMAL(12,5) column would return a NUM_PREC_RADIX of 10, a
COLUMN_SIZE of 12, and a DECIMAL_DIGITS of 5; a FLOAT column could return a
NUM_PREC_RADIX of 10, a COLUMN_SIZE of 15, and a DECIMAL_DIGITS of NULL.
If it is 2, the values in COLUMN_SIZE and DECIMAL_DIGITS give the number of bits
allowed in the column. NULL is returned for data types where NUM_PREC_RADIX is
not applicable.

NULLABLE 11 Smallint SQL_NO_NULLS if the column could not include NULL values. SQL_NULLABLE if
the column accepts NULL values. SQL_NULLABLE_UNKNOWN if it is not known
whether the column accepts NULL values.

REMARKS 12 Varchar A description of the column.

COLUMN_DEF 13 Varchar The default value of the column. The value in this column should be interpreted as
a string if it is enclosed in quotation marks. If NULL was specified as the default
value, then this column is the word NULL, not enclosed in quotation marks.

SQL_DATA_TYPE 14 Smallint SQL data type.

SQL_DATETIME_SUB 15 Smallint The subtype code for datetime and interval data types.For other data types, this
column returns a NULL.

CHAR_OCTET_LENGT 16 Integer The maximum length in bytes of a character or binary data type column. For all
H other data types, this column returns a NULL.

ORDINAL_POSITION 17 Integer The ordinal position of the column in the table. The first column in the table is
number 1.

IS_NULLABLE 18 Varchar "NO" if the column does not include NULLs. "YES" if the column could include
NULLs. This column returns a zero-length string if nullability is unknown.

ODBCGetDataSources
Fetch a list of all available data sources on the system.
Syntax:
ODBCDataSource[] ODBCGetDataSources ()
Returns:
An array of ODBCDataSource structures which contain the data source names and descriptions. If an error occurs
or ODBC is not correctly set up, the returned array is empty. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
If the same statement is used to perform multiple queries, each result set must be closed before performing any
other queries.

ODBCEndTransaction
Commit or roll back a transaction in manual-commit mode.
Syntax:
Bool ODBCEndTransaction (ODBCConnectionHandle Handle, Bool Commit)
Handle is the handle to the ODBC connection.
Commit is the value of the commit transaction, which can be either TRUE or FALSE.
Returns:
TRUE if the operation was successful, FALSE if the supplied handle was not valid or the function failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


320 - BMC FootPrints Asset Core - Chilli Reference

Comments:
Drivers for DBMSs that support transactions typically implement this function by executing a COMMIT or
ROLLBACK statement. If the supplied Commit parameter is TRUE, the transaction is committed. If it is FALSE,
the transaction is rolled back.
You should not commit or roll back transactions by executing COMMIT or ROLLBACK statements. The effects of
doing this are undefined. Possible issues include the driver no longer knowing when a transaction is active and
these statements failing against data sources that do not support transactions.

ODBCGetTables
Get the list of table, catalog, or schema names, and table types, stored in a specific data source.
Syntax:
Bool ODBCGetTables (ODBCStatementHandle Statement, String CatalogName, String SchemaName,
String TableName, String TableType)
Statement is the handle to the statement of the ODBC connection
CatalogName is the string search pattern for catalog names.
SchemaName is the string search pattern for schema names.
TableName is the string search pattern for table names.
TableType is the list of table types to match.
Returns:
TRUE if the function was successfully executed, FALSE in case of an error or if the handle was invalid. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The driver returns the information as a result set which can then be accessed through the ODBCGet functions
using the supplied statement handle.
The CatalogName, SchemaName and TableName arguments accept search patterns. The search pattern characters
are:
• An underscore (_), which represents any single character.
• A percent sign (%), which represents any sequence of zero or more characters.
• An escape character, which is driver-specific and is used to include underscores, percent signs, and the escape
character as literals. If the escape character precedes a non-special character, the escape character has no
special meaning. If the escape character precedes a special character, it escapes the special character. For
example, \a would be treated as two characters, \ and a, but \% would be treated as the non-special single
character %.
If CatalogName is % and SchemaName and TableName are empty strings, the result set contains a list of valid
catalogs for the data source. (All returned columns except the TABLE_CAT column contain NULLs.)
If SchemaName is % and CatalogName and TableName are empty strings, the returned result set contains a list of
valid schemas for the data source. (All columns except the TABLE_SCHEM column contain NULLs.)
If TableType is % and CatalogName, SchemaName, and TableName are empty strings, the result set contains a list
of valid table types for the data source. (All columns except the TABLE_TYPE column contain NULLs.)
If TableType is not an empty string, it must contain a list of comma-separated values for the types of interest; each
value can be enclosed in single quotation marks (') or unquoted—for example, 'TABLE', 'VIEW' or TABLE,
VIEW. You should always specify the table type in uppercase; the driver converts the table type to whatever case is
needed by the data source.
If the data source does not support a specified table type, the function does not return any results for that type.
The following table lists the columns in the result set. Additional columns beyond column 5 (REMARKS) can be
defined by the driver. Some of the columns can be different depending on the driver.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 26 - ODBC Functions - 321

Data
Column Name Number Description
Type

TABLE_CAT 1 Varchar Catalog name; NULL if not applicable to the data source. If a driver supports catalogs for
some tables but not for others, such as when the driver retrieves data from different
DBMSs, it returns an empty string ("") for those tables that do not have catalogs.

TABLE_SCHE 2 Varchar Schema name; NULL if not applicable to the data source. If a driver supports schemas for
M some tables but not for others, such as when the driver retrieves data from different
DBMSs, it returns an empty string ("") for those tables that do not have schemas.

TABLE_NAME 3 Varchar Table name.

TABLE_TYPE 4 Varchar Table type name; one of the following: "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL
TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM", or a data source–specific type
name. The meanings of "ALIAS" and "SYNONYM" are driver-specific.

REMARKS 5 Varchar A description of the table.

26.5.2 Methods from Statement


Following you find a list of all available ODBC methods from statement:

Function OS Description
ODBCCloseCursor Close a cursor

ODBCCreateStatement Create a new statement using a ConnectionHandle

ODBCDestroyStatement Destroy a SQL statement

ODBCExecute Execute a SQL statement

ODBCFetchScroll Fetch the specified rowset of data from the result set

ODBCGetAffectedRowCount Return the number of rows affected by an UPDATE, INSERT, or DELETE statement
after it has been executed
ODBCGetColumnCount Return the number of columns in a result set

ODBCGetColumnDecimalDigits Get number of decimal digits of the column in a statement result set

ODBCGetColumnIsNullable Return a value that indicates whether a column in a statement result set allows NULL
values
ODBCGetColumnName Get the name of a column in a statement result set

ODBCGetColumnSize Get the size of a column in a statement result set

ODBCGetColumnType Get the SQL data type for a column in a statement result set

ODBCGetRowCount Return the number of rows in the result set of a statement after it has been executed

ODBCMoreResults Determine whether more results are available on a statement

ODBCCloseCursor
Close a cursor that has been opened on a statement and discard pending results.
Syntax:
Bool ODBCCloseCursor (ODBCStatementHandle Statement)
Statement is the handle to the result set of the ODBC connection.

Numara Software, Inc. and BMC Software, Inc. Confidential.


322 - BMC FootPrints Asset Core - Chilli Reference

Returns:
TRUE if the operation was successful, or FALSE if the function failed or the handle was invalid. If the supplied
statement has no cursor open, FALSE is returned but no error occurs. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
When a script has finished using a cursor, it calls ODBCCloseCursor to close the cursor. Until the script closes the
cursor, the statement on which the cursor is opened cannot be used for most other operations, such as executing
another SQL statement.
Cursors remain open until they are explicitly closed, except when a transaction is committed or rolled back, in
which case some data sources close the cursor. In particular, reaching the end of the result set, when
ODBCFetchScroll returns FALSE, does not close a cursor. Even cursors on empty result sets (result sets created
when a statement executed successfully but returned no rows) must be explicitly closed.

ODBCCreateStatement
Create a new statement using the ODBC connection handle.
Syntax:
ODBCStatementHandle ODBCCreateStatement (ODBCConnectionHandle Handle)
Handle is the handle to the ODBC connection.
Returns:
A handle of type ODBCStatementHandle which can be used for executing queries if the operation was successful.
If an error occurs or the function fails, 0 is returned and the ErrCode is set to ERR_FUNCFAILED.
Comments:
The returned ODBCStatementHandle can be used to execute a query or an update. The statement created is
configured to return result sets which are read-only and scrollable, with the data in them not being affected by
changes in the database.

ODBCDestroyStatement
Destroy a SQL statement.
Syntax:
Bool ODBCDestroyStatement (ODBCStatementHandle Statement)
Statement is the handle to the statement of the ODBC connection to be destroyed.
Returns:
TRUE if the statement was successfully destroyed, FALSE in case of an error or if the handle was invalid. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
Destroying a statement signifies that any processing associated with the specific statement is stopped, any open
cursors associated with the statement are closed, pending results are discarded and all resources associated with
the statement handle are freed up. After this function, the supplied statement handle can no longer be used.

ODBCExecute
Execute a SQL statement.
Syntax
Bool ODBCExecute (ODBCStatementHandle Statement, String SQLQuery)
Statement is the handle to the statement of the ODBC connection.
SQLQuery is the SQL query to be executed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 26 - ODBC Functions - 323

Returns
TRUE if the operation was successful, FALSE if the function failed or the handle was invalid. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.

ODBCFetchScroll
Fetch the specified rowset of data from the result set.
Syntax:
Bool ODBCFetchScroll (ODBCStatementHandle Statement, Int FetchOrientation, Int FetchOffset)
Statement is the handle to the created statement of the ODBC connection.
FetchOrientation defines the orientation in which to look for the rowset.
FetchOffset defines the Offset in which to look for the rowset.
Returns:
TRUE if the operation was successful, or FALSE if the function failed or the handle was invalid. If the cursor goes
past the last row, FALSE is returned but no error is flagged. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
Rowsets can be specified by absolute or relative position. This function can be called only while a result set
exists, that is, after a call that creates a result set and before the cursor over that result set is closed.
When the result set is created, the cursor is positioned before the start of the result set. ODBCFetchScroll
positions the block cursor based on the values of the FetchOrientation and FetchOffset arguments as follows:

Value Description

SQL_FETCH_NEXT Return the next rowset. The value of FetchOffset is ignored.

SQL_FETCH_PRIOR Return the prior rowset. The value of FetchOffset is ignored.

SQL_FETCH_RELATIVE Return the rowset FetchOffset from the start of the current rowset.

SQL_FETCH_ABSOLUTE Return the rowset starting at row FetchOffset (1 for the first row).

SQL_FETCH_FIRST Return the first rowset in the result set. The value of FetchOffset is ignored.

SQL_FETCH_LAST Return the last complete rowset in the result set. The value of FetchOffset is ignored.

ODBCGetAffectedRowCount
Return the number of rows affected by an UPDATE, INSERT, or DELETE statement after it has been executed.
Syntax:
Int ODBCGetAffectedRowCount (ODBCStatementHandle Statement)
Statement is the handle to the statement of the ODBC connection.
Returns:
The number of affected rows following an UPDATE, INSERT, or DELETE statement if the operation was
successful. The value is 0 if an error occurs or no rows were affected and -1 if the number of affected rows is not
available. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The statement should be one which performs an update rather than for example a SELECT in which case the
returned value is driver dependent. If the number of affected rows is not available the return value is -1, which
typically happens for the results of SELECT statements.

Numara Software, Inc. and BMC Software, Inc. Confidential.


324 - BMC FootPrints Asset Core - Chilli Reference

ODBCGetColumnCount
Return the number of columns in a result set.
Syntax:
Int ODBCGetColumnCount (ODBCStatementHandle Statement)
Statement is the handle to the statement of the ODBC connection.
Returns:
The number of columns in the statement results if the operation was successful or 0 if an error occurs or no
columns are returned by the statement. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The result set was either returned by an executed statement or to be returned by a prepared statement. If the
statement associated with the handle does not return columns the return value is 0.

ODBCGetColumnDecimalDigits
Get number of decimal digits of the column in a statement result set.
Syntax:
Int ODBCGetColumnDecimalDigits (ODBCStatementHandle Statement, Int ColumnNumber)
Statement is the handle to the statement of the ODBC connection.
ColumnNumber is the number of the column in the table.
Returns:
The number of decimal digits for the column if the operation was successful or 0 if an error occurs or the column
is not of the right type. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
This function can be executed after a call to ODBCExecute. The column numbers start at 1 for the first column.

ODBCGetColumnIsNullable
Returns a value that indicates whether a column in a statement result set allows NULL values.
Syntax:
Int ODBCGetColumnIsNullable (ODBCStatementHandle Statement, Int ColumnNumber)
Statement is the handle to the statement of the ODBC connection.
ColumnNumber is the number of the column in the table.
Returns:
The number of decimal digits for the column if the operation was successful or 0 if an error occurs or the column
is not of the right type. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The following are the possible returned values:

Value Description

SQL_NO_NULLS The column does not allow NULL values.

SQL_NULLABLE The column allows NULL values.

SQL_NULLABLE_UNKNOWN: The driver cannot determine if the column allows NULL values.

This function can be executed after a call to ODBCExecute. The column numbers start at 1 for the first column.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 26 - ODBC Functions - 325

ODBCGetColumnName
Get the name of a column in a statement result set.
Syntax:
String ODBCGetColumnName (ODBCStatementHandle Statement, Int ColumnNumber)
Statement is the handle to the statement of the ODBC connection.
ColumnNumber is the number of the column in the table.
Returns:
The name of the column if the operation was successful or an empty string if an error occurs or the function fails.
If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
This function can be executed after a call to ODBCExecute. The column numbers start at 1 for the first column.

ODBCGetColumnSize
Get the size of a column in a statement result set.
Syntax:
Int ODBCGetColumnSize (ODBCStatementHandle Statement, Int ColumnNumber)
Statement is the handle to the statement of the ODBC connection.
ColumnNumber is the number of the column in the table.
Returns:
The column size if the operation was successful or 0 if an error occurs or the function failed. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.
Comments:
The column size of numeric data types is defined as the maximum number of digits used by the data type of the
column, or the precision of the data. For character types, this is the length in characters of the data; for binary data
types, column size is defined as the length in bytes of the data. For the time, timestamp, and all interval data
types, this is the number of characters in the character representation of this data.
This function can be executed after a call to ODBCExecute. The column numbers start at 1 for the first column.

ODBCGetColumnType
Get the SQL data type for a column in a statement result set.
Syntax:
Int ODBCGetColumnType (ODBCStatementHandle Statement, Int ColumnNumber)
Statement is the handle to the statement of the ODBC connection.
ColumnNumber is the number of the column in the table.
Returns:
The SQL data type as one of the SQLTYPE constants as explained in the beginning of this chapter if the operation
was successful or 0 if an error occurs or the function failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
This function can be executed after a call to ODBCExecute. The column numbers start at 1 for the first column.

ODBCGetRowCount
Return the number of rows in the result set of a statement after it has been executed.
Syntax:
Int ODBCGetRowCount (ODBCStatementHandle Statement)

Numara Software, Inc. and BMC Software, Inc. Confidential.


326 - BMC FootPrints Asset Core - Chilli Reference

Statement is the handle to the statement of the ODBC connection.


Returns:
The number of affected rows following an UPDATE, INSERT, or DELETE statement. The value is 0 if an error
occurs or no rows were affected or -1 if the number of affected rows is not available. If the operation fails, ErrCode
is set to ERR_FUNCFAILED.
Comments:
The statement should be one which returns data rows like a SELECT rather than one which performs an update in
which case the ODBCGetAffectedRowCount function should be used.

ODBCMoreResults
Determine whether more results are available on a statement containing SELECT, UPDATE, INSERT, or DELETE
statements and, if so, initialise processing for those results.
Syntax:
Bool ODBCMoreResults (ODBCStatementHandle Statement)
Statement is the handle to the statement of the ODBC connection.
Returns:
TRUE if the operation was successful, or FALSE if the function failed or the handle was invalid. If the operation
fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
SELECT statements return result sets. UPDATE, INSERT, and DELETE statements return a count of affected rows.
If any of these statements are batched in procedures, they can return multiple result sets or row counts. After
executing the batch, the statement is positioned on the first result set. After you are done with the first result set,
you call ODBCMoreResults to move to the next result set. If another result set or count is available,
ODBCMoreResults returns TRUE and initializes the result set or count for additional processing. If any row count
generating statements appear in between result set generating statements, they can be stepped over by calling
ODBCMoreResults. After calling ODBCMoreResults for UPDATE, INSERT, or DELETE statements, you can call
ODBCGetRowCount.
If there was a current result set with unfetched rows, ODBCMoreResults discards that result set and makes the
next result set or count available. If all results have been processed, ODBCMoreResults returns FALSE but does not
raise an error.
An explicit batch is two or more SQL statements separated by semicolons (;). For example, the following batch of
SQL statements opens a new sales order. This requires inserting rows into both the Orders and Lines tables. Note
that there is no semicolon after the last statement.
INSERT INTO Orders (OrderID, CustID, OpenDate, SalesPerson, Status)
VALUES (2002, 1001, {fn CURDATE() 'Garcia', 'OPEN');
INSERT INTO Lines (OrderID, Line, PartID, Quantity)
VALUES (2002, 1, 1234, 10);
INSERT INTO Lines (OrderID, Line, PartID, Quantity)
VALUES (2002, 2, 987, 8);
INSERT INTO Lines (OrderID, Line, PartID, Quantity)
VALUES (2002, 4, 412, 500)

26.5.3 Methods to Retrieve Attribute Values


Following you find a list of all available ODBC methods available to retrieve attribute values either by column
number or by column name. All these functions have two signatures:

Function OS Description
ODBCGetBoolean Get a column's value as a boolean

ODBCGetDate Get a column's value as a date

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 26 - ODBC Functions - 327

Function OS Description
ODBCGetDouble Get a column's value as a double

ODBCGetFloat Get a column's value as a float value

ODBCGetInteger Get a column's value as an integer

ODBCGetString Get a column's value as a string

ODBCGetTime Get a column's value as a time

ODBCGetTimestamp Get a column's value as a timestamp

ODBCGetUnsignedInteger Get a column's value as an unsigned integer

ODBCValueIsNull Check whether the value of a column is null

ODBCGetBoolean
Get a column's value as a boolean, using either the name of the column or the column number.
Syntax:
Bool ODBCGetBoolean (ODBCStatementHandle Statement, Int ColumnNumber)
Bool ODBCGetBoolean (ODBCStatementHandle Statement, String ColumnName)
Statement is the handle to the result set of the ODBC connection.
ColumnNumber is index to the column number.
ColumnName is name of the column.
Returns:
The value of the column if successful, FALSE if the function failed or the handle was invalid. If the operation
fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
If the accessed column value is NULL, FALSE is returned with no error. In this case ODBCValueIsNull should be
called to check whether the column value is in fact NULL.
The column numbers start at 1 for the first column. The referenced column should be of the correct data type.

ODBCGetDate
Get a column's value as a date structure, using either the name of the column or the column number.
Syntax:
ODBCDate ODBCGetDate (ODBCStatementHandle Statement, Int ColumnNumber)
ODBCDate ODBCGetDate (ODBCStatementHandle Statement, String ColumnName)
Statement is the handle to the result set of the ODBC connection.
ColumnNumber is index to the column number.
ColumnName is name of the column.
Returns:
An ODBCDate structure containing the value of the column if successful, or an empty structure (all values 0) if
the function failed or the handle was invalid. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
If the accessed column value is NULL, an empty structure is returned with no error. In this case
ODBCValueIsNull should be called to check whether the column value is in fact NULL
The column numbers start at 1 for the first column. The referenced column should be of the correct data type.

ODBCGetDouble
Get a column's value as a double, using either the name of the column or the column number.

Numara Software, Inc. and BMC Software, Inc. Confidential.


328 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
Double ODBCGetDouble (ODBCStatementHandle Statement, Int ColumnNumber)
Double ODBCGetDouble (ODBCStatementHandle Statement, String ColumnName)
Statement is the handle to the result set of the ODBC connection.
ColumnNumber is index to the column number.
ColumnName is name of the column.
Returns:
The value of the column if successful, 0 if the function failed or the handle was invalid. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.
Comments:
If the accessed column value is NULL, 0 is returned with no error. In this case ODBCValueIsNull should be
called to check whether the column value is in fact NULL.
The column numbers start at 1 for the first column. The referenced column should be of the correct data type or
one of the 'number' types which are correctly converted to a double precision floating number.

ODBCGetFloat
Get a column's value as a float, using either the name of the column or the column number.
Syntax:
Float ODBCGetFloat (ODBCStatementHandle Statement, Int ColumnNumber)
Float ODBCGetFloat (ODBCStatementHandle Statement, String ColumnName)
Statement is the handle to the result set of the ODBC connection.
ColumnNumber is index to the column number.
ColumnName is name of the column.
Returns:
The value of the column if successful, 0 if the function failed or the handle was invalid. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.
Comments:
If the accessed column value is NULL, 0 is returned with no error. In this case ODBCValueIsNull should be
called to check whether the column value is in fact NULL.
The column numbers start at 1 for the first column. The referenced column should be of the correct data type or
one of the 'number' types which are correctly converted to a single precision floating number.

ODBCGetInteger
Get a column's value as an int, using either the name of the column or the column number.
Syntax:
Int ODBCGetInteger (ODBCStatementHandle Statement, Int ColumnNumber)
Int ODBCGetInteger (ODBCStatementHandle Statement, String ColumnName)
Statement is the handle to the result set of the ODBC connection.
ColumnNumber is index to the column number.
ColumnName is name of the column.
Returns:
The value of the column if successful, 0 if the function failed or the handle was invalid. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.
Comments:
If the accessed column value is NULL, 0 is returned with no error. In this case ODBCValueIsNull should be
called to check whether the column value is in fact NULL.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 26 - ODBC Functions - 329

The column numbers start at 1 for the first column. The referenced column should be of the correct data type or
one of the 'number' types which are correctly converted to a signed integer.

ODBCGetString
Get a column's value as a string, using either the name of the column or the column number.
Syntax:
String ODBCGetString (ODBCStatementHandle Statement, Int ColumnNumber)
String ODBCGetString (ODBCStatementHandle Statement, String ColumnName)
Statement is the handle to the result set of the ODBC connection.
ColumnNumber is index to the column number.
ColumnName is name of the column.
Returns:
The value of the column if successful, or an empty string if the function failed or the handle was invalid. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
If the accessed column value is NULL, an empty string (““) is returned with no error. In this case
ODBCValueIsNull should be called to check whether the column value is in fact NULL.
The function takes an ODBCStatementHandle as a parameter and a column number or name. The column
numbers start at 1 for the first column. The referenced column is either of SQL type string or of another type in
which case it is converted to a string representation and returned.

ODBCGetTime
Get a column's value as a time structure, using either the name of the column or the column number.
Syntax:
ODBCTime ODBCGetTime (ODBCStatementHandle Statement, Int ColumnNumber)
ODBCTime ODBCGetTime (ODBCStatementHandle Statement, String ColumnName)
Statement is the handle to the result set of the ODBC connection.
ColumnNumber is index to the column number.
ColumnName is name of the column.
Returns:
An ODBCTime structure containing the value of the column if successful, or an empty structure (all values 0) if
the function failed or the handle was invalid. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
If the accessed column value is NULL, an empty structure is returned with no error. In this case
ODBCValueIsNull should be called to check whether the column value is in fact NULL.
This function gets a column's value as a time structure, taking an ODBCStatementHandle as a parameter and a
column number or name. The column numbers start at 1 for the first column. The referenced column should be of
the correct data type.

ODBCGetTimestamp
Get a column's value as a timestamp integer, using either the name of the column or the column number.
Syntax:
Int ODBCGetTimestamp (ODBCStatementHandle Statement, Int ColumnNumber)
Int ODBCGetTimestamp (ODBCStatementHandle Statement, String ColumnName)
Statement is the handle to the result set of the ODBC connection.
ColumnNumber is index to the column number.
ColumnName is name of the column.

Numara Software, Inc. and BMC Software, Inc. Confidential.


330 - BMC FootPrints Asset Core - Chilli Reference

Returns:
The value of the column if successful, 0 if the function failed or the handle was invalid. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.
Comments:
If the accessed column value is NULL, 0 is returned with no error. In this case ODBCValueIsNull should be
called to check whether the column value is in fact NULL.
The timestamp integer counts the numbers of seconds since midnight January 1, 1970.
The column numbers start at 1 for the first column. The referenced column should be of the type SQL_TIMESTAMP
or the function fails. Note that using this function to access an ODBC timestamp value results in the fractional
seconds of the value being lost. To get the fractions value, access the column using the ODBCGetString function
which returns the value as a string formatted as yyyy-mm-dd hh:mm:ss.f, where up to nine digits can be used for
fractional seconds.

ODBCGetUnsignedInteger
Get a column's value as an unsigned integer, using either the name of the column or the column number.
Syntax:
Int ODBCGetUnsignedInteger (ODBCStatementHandle Statement, Int ColumnNumber)
Int ODBCGetUnsignedInteger (ODBCStatementHandle Statement, String ColumnName)
Statement is the handle to the result set of the ODBC connection.
ColumnNumber is index to the column number.
ColumnName is name of the column.
Returns:
The value of the column if successful, 0 if the function failed or the handle was invalid. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.
Comments:
If the accessed column value is NULL, 0 is returned with no error. In this case ODBCValueIsNull should be
called to check whether the column value is in fact NULL.
The column numbers start at 1 for the first column. The referenced column should be of the correct data type or
one of the 'number' types which are correctly converted to an unsigned integer.

ODBCValueIsNull
Check whether the value of a column is null .
Syntax:
Bool ODBCValueIsNull (ODBCStatementHandle Statement, Int ColumnNumber)
Bool ODBCValueIsNull (ODBCStatementHandle Statement, String ColumnName)
Statement is the handle to the result set of the ODBC connection.
ColumnNumber is index to the column number.
ColumnName is name of the column.
Returns:
TRUE if the value of the column is null, FALSE if the value is not null, the function failed or the handle was
invalid. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
This function does not return the value itself even if it is a boolean type. It simply verifies whether it is null or
not. It can be used where one of the ODBCGet functions returns an empty value (0, empty string or empty
structure) without an error to check whether the value accessed is actually 0 or null.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 26 - ODBC Functions - 331

26.6 Example
The following example gets the list of available data sources and prints their contents, returns specific type names
and returns the contents of a resultset handle
include "odbc.chx"
include "time.chx"

//*******************************************************************
// ListDataSources
// Gets the list of available data sources and prints the contents.
//*******************************************************************

proc ListDataSources ()

ODBCDataSource Sources[]
Sources = ODBCGetDataSources ()

int i;
for (i=1; i<=ArrayGetSize (Sources); i+=1)
print (Sources[i].Name + " - " + Sources[i].Description + "\n")
endfor

endproc

//*******************************************************************
// PrintType
// Given a column TypeId returns the type name.
//*******************************************************************

string GetType (int TypeId)

if (TypeId == SQL_CHAR)
return "SQL_CHAR"

elseif (TypeId == SQL_VARCHAR)


return "SQL_VARCHAR"

elseif (TypeId == SQL_LONGVARCHAR)


return "SQL_LONGVARCHAR"

elseif (TypeId == SQL_WCHAR)


return "SQL_WCHAR"

elseif (TypeId == SQL_WVARCHAR)


return "SQL_WVARCHAR"

elseif (TypeId == SQL_WLONGVARCHAR)


return "SQL_WLONGVARCHAR"

elseif (TypeId == SQL_DECIMAL)


return "SQL_DECIMAL"

elseif (TypeId == SQL_NUMERIC)


return "SQL_NUMERIC"

elseif (TypeId == SQL_SMALLINT)


return "SQL_SMALLINT"

Numara Software, Inc. and BMC Software, Inc. Confidential.


332 - BMC FootPrints Asset Core - Chilli Reference

elseif (TypeId == SQL_INTEGER)


return "SQL_INTEGER"

elseif (TypeId == SQL_REAL)


return "SQL_REAL"

elseif (TypeId == SQL_FLOAT)


return "SQL_FLOAT"

elseif (TypeId == SQL_DOUBLE)


return "SQL_DOUBLE"

elseif (TypeId == SQL_BIT)


return "SQL_BIT"

elseif (TypeId == SQL_TINYINT)


return "SQL_TINYINT"

elseif (TypeId == SQL_BIGINT)


return "SQL_BIGINT"

elseif (TypeId == SQL_BINARY)


return "SQL_BINARY"

elseif (TypeId == SQL_VARBINARY)


return "SQL_VARBINARY"

elseif (TypeId == SQL_LONGVARBINARY)


return "SQL_LONGVARBINARY"

elseif (TypeId == SQL_DATE)


return "SQL_DATE"

elseif (TypeId == SQL_TIME)


return "SQL_TIME"

elseif (TypeId == SQL_TIMESTAMP)


return "SQL_TIMESTAMP"

endif

return "???"

endproc

//*******************************************************************
// DumpResult
// Given a resultset handle, prints the contents.
//*******************************************************************

proc DumpResult (ODBCStatementHandle StatementHandle)

int i, j, iCols;

iCols = ODBCGetColumnCount (StatementHandle)

print ("Column Information:\n")

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 26 - ODBC Functions - 333

for (i=1; i<=iCols; i+=1)


print (ODBCGetColumnName (StatementHandle, i) + " (")
print ("Type: " + GetType (ODBCGetColumnType (StatementHandle, i)) + ", ")
print ("Size: " + ODBCGetColumnSize (StatementHandle, i) + ", ")
print ("Nullable: " + ODBCGetColumnIsNullable (StatementHandle, i) + "")
print (")\n")
endfor

while (ODBCFetchScroll (StatementHandle, SQL_FETCH_NEXT, 0))


for (j=1; j<=iCols; j+=1)

int iType
iType = ODBCGetColumnType (StatementHandle, j)

if ((iType == SQL_CHAR) || \
(iType == SQL_VARCHAR) || \
(iType == SQL_LONGVARCHAR) || \
(iType == SQL_WCHAR) || \
(iType == SQL_WVARCHAR) || \
(iType == SQL_WLONGVARCHAR))

print (ODBCGetString (StatementHandle, j))


print (ODBCGetString (StatementHandle, j))

elseif ((iType == SQL_DECIMAL) || \


(iType == SQL_NUMERIC) || \
(iType == SQL_REAL) || \
(iType == SQL_FLOAT))

print (MakeStr (ODBCGetFloat (StatementHandle, j)))

elseif (iType == SQL_DOUBLE)


print (MakeStr (ODBCGetDouble (StatementHandle, j)))

elseif ((iType == SQL_SMALLINT) || \


(iType == SQL_INTEGER) || \
(iType == SQL_TINYINT) || \
(iType == SQL_FLOAT))

print (MakeStr (ODBCGetInteger (StatementHandle, j)))


print (MakeStr (ODBCGetInteger (StatementHandle, j)))

elseif (iType == SQL_TIMESTAMP)

print (TimeFormat (ODBCGetTimestamp (StatementHandle, j), "%Y %b %d %H:%M:%S"))

else
print ("????")
endif

if (j < iCols)
print (", ")
endif

endfor
print ("\n")

endwhile

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


334 - BMC FootPrints Asset Core - Chilli Reference

proc DumpTables (GenSqlConnection conn)

int i, j;
string szTables[], szColumns[];

szTables = GenSqlListTables (conn);


for (i=1; i<=ArrayGetSize (szTables); i+=1)
print (szTables[i] + ":\r\n")

szColumns = GenSqlListColumns (conn, szTables[i]);

for (j=1; j<=ArrayGetSize (szColumns); j+=1)


print (" " + szColumns[j] + "\r\n")
endfor
endfor

endproc

proc main ()

ListDataSources ()

print ("Trying to connect...\r\n")

ODBCConnectionHandle ConnHandle
ConnHandle = ODBCConnect ("SQL Server - Northwind", "batman", "")

print ("Connected!\r\n")

ODBCStatementHandle StatementHandle
StatementHandle = ODBCCreateStatement (ConnHandle)

ODBCGetTables (StatementHandle, "", "", "%", "")


DumpResult (StatementHandle)
ODBCCloseCursor (StatementHandle)

ODBCExecute (StatementHandle, "select * from librarybooks order by title")


DumpResult (StatementHandle)
ODBCCloseCursor (StatementHandle)

ODBCDisconnect (ConnHandle)

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Path Functions

This chapter explains all path functions of the Chilli script language. The string module is included in the Chilli
core and thus always accessible.
Some of these functions are not applicable to the UNIX environment.

27.1 Introduction
A path is a list of directories where the operating system looks for files. The functions of this Chilli module
provide you with the possibility to create complete paths to files within scripts, to check for a path and to retrieve
information about an existing path.

27.2 Functions
Following you find the list of all functions of the Path function module:

Function OS Description
CompletePath Convert a relative path into a full path.

PathCreate Create all components in a path

PathExists Check for existence of all components in a path

PathFind Check for existence of all components in a path

PathGetDir Get the directory part of a path

PathGetDrive Get the drive letter part of a path

PathGetFileExt Get the file extension part of a path

PathGetFilename Get the filename part of a path including its extension

PathGetFileRoot Get the root file name of a path, excluding the file extension

PathGetShort Get the short file name equivalent for a Win32 long file name

PathGetTemp Get the path for temporary file

ResolvePath Convert a relative path to a full path

CompletePath
Convert a relative path into a full path.
Syntax:
String CompletePath (string Path)
Path is the relative path to be completed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


336 - BMC FootPrints Asset Core - Chilli Reference

Returns:
A string containing the complete path if the operation was successful, or a string with the original relative path if
the path could not be found.
Comments:
Supplied with a path string which can contain “.” or “..” components, this function removes these parts to come
up with a clean path string. If the path is a relative path, it is appended to the current working directory to come
up with a complete path.

PathCreate
Create all components in a directory path.
Syntax:
Bool PathCreate (String PathName)
PathName is the relative or absolute path of the directory to be created.
Returns:
TRUE if the create operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
If the named path exists already, the function returns 1, indicating a successful operation. This operation is very
similar to DirCreate except that if any of the components of the path do not exist, they are also created.
Example:
The following example creates a path if it does not yet exist.
proc main ()

string newPath, tempPath


newPath = tempPath + "\\temp1\\temp2"
if (PathFind (newPath) == FALSE)
PathCreate (newPath)
endif

endproc

PathExists
Check to see if all components in a file path exist.
Syntax:
Bool PathExists (String PathName)
PathName is the relative or absolute path to be found.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The function PathExists is an alias for PathFind and is identical in operation.
Example:
The following example creates a path if it does not yet exist.
proc main ()

string tempPath, newPath, filePath


tempPath = PathGetTemp ()
newPath = tempPath + "\\temp1\\temp2"

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 27 - Path Functions - 337

if (PathExists (newPath) == FALSE)


PathCreate (newPath)
endif

endproc

PathFind
Check to see if all components in a file path exist.
Syntax:
Bool PathFind (String PathName)
PathName is the relative or absolute path to be found.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The function PathExists is an alias for PathFind and is identical in operation.
Example:
The following example creates a path if it does not yet exist.
proc main ()

string tempPath, newPath, filePath


tempPath = PathGetTemp ()
newPath = tempPath + "\\temp1\\temp2"

if (PathFind (newPath) == FALSE)


PathCreate (newPath)
endif

endproc

PathGetDir
Get the directory part of a path.
Syntax:
String PathGetDir (String PathName)
PathName is the relative or absolute path to be parsed.
Returns:
The directory part of the path. If a directory part cannot be found, the returned string is empty.
Comments:
The returned directory path does not have any trailing backslashes (\). The exception to this is if the directory is
the root directory in which case the returned string contains just a single backslash.
Example:
The following example prints the drive and directory path of a file.
proc main ()

string filePath
filePath = "C:\\Progam Files\\Software1\\Software2\\file.txt"

Print (LogFile, "Drive = " + PathGetDrive (filePath) + "\r\n")


Print (LogFile, "Directory = " + PathGetDir (filePath) + "\r\n")

Numara Software, Inc. and BMC Software, Inc. Confidential.


338 - BMC FootPrints Asset Core - Chilli Reference

endproc

PathGetDrive
Get the drive letter from a path.
Syntax:
String PathGetDrive (String PathName)
PathName is the absolute path to be parsed.
Returns:
The drive letter part of the path. If a drive letter was not specified in the path, the returned string is empty.
Comments:
If successful, the returned string contains only a single letter and is not followed by a colon symbol.
This function is not applicable for the UNIX environment.
Example:
The following example prints the drive and directory path of a file.
proc main ()

string filePath
filePath = "C:\\Progam Files\\Software1\\Software2\\file.txt"

Print (LogFile, "Drive = " + PathGetDrive (filePath) + "\r\n")


Print (LogFile, "Directory = " + PathGetDir (filePath) + "\r\n")

endproc

PathGetFileExt
Get the filename extension part of a path.
Syntax:
String PathGetFileExt (String PathName)
PathName is the relative or absolute path to be parsed.
Returns:
The filename extension at the end of the path. If the extension does not exist, the returned string is empty.
Comments:
If successful, the returned extension string typically is 3 letters (but can be longer) and does not include the
leading period (.).
Example:
The following example prints the name and the extension part of a file.
proc main ()

string filePath
filePath = "C:\\Progam Files\\Software1\\Software2\\file.txt"

Print (LogFile, "File Name = " + PathGetFileName (filePath) + "\r\n")


Print (LogFile, "File Extension = " + PathGetFileExt (filePath) + "\r\n")

endproc

PathGetFilename
Get the filename part of a path.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 27 - Path Functions - 339

Syntax:
String PathGetFilename (String PathName)
PathName is the relative or absolute path to be parsed.
Returns:
The filename at the end of the path. This name is always returned even if the last part of a path refers to a
directory rather than a file.
Example:
The following example prints the name and extension part of a file.
proc main ()

string filePath
filePath = "C:\\Progam Files\\Software1\\Software2\\file.txt"

Print (LogFile, "File Name = " + PathGetFileName (filePath) + "\r\n")


Print (LogFile, "File Extension = " + PathGetFileExt (filePath) + "\r\n")

endproc

PathGetFileRoot
Get the filename part of a path excluding the file extension if any.
Syntax:
String PathGetFileRoot (String PathName)
PathName is the relative or absolute path to be parsed.
Returns:
The filename at the end of the path but without any extension. This name is always returned even if the last part
of a path refers to a directory rather than a file.
Comments:
The name found at the end of the path is stripped of its file extension if one exists and is returned. Normally the
period between the root part and the extension is also stripped.
Example:
The following example prints the file name without extension and the 8.3 equivalent if it is a Win32 type long file
name.
proc main ()

string filePath
filePath = "C:\\Progam Files\\Software1\\Software2\\file.txt"

Print (LogFile, "File root = " + PathGetFileRoot (filePath) + "\r\n")


Print (LogFile, "Short path = " + PathGetShort (filePath) + "\r\n")

endproc

PathGetShort
Get the short 8.3 equivalent name for a Win32 type long file name.
Syntax:
String PathGetShort (String LongPath)
LongPath is the relative or absolute path to be parsed.
Returns:
The short filename version of the path.

Numara Software, Inc. and BMC Software, Inc. Confidential.


340 - BMC FootPrints Asset Core - Chilli Reference

Comments:
This function is only useful on Windows 95/98 systems using a VFAT file system where each long file name also
has a short 8.3 format alias. On 16-bit systems, where there are no long format file names, the function returns the
supplied path in LongPath without any change.
This function is not applicable for the UNIX environment.
Example:
The following example prints the file name without extension and the 8.3 equivalent if it is a Win32 type long file
name.
proc main ()

string filePath
filePath = "C:\\Progam Files\\Software1\\Software2\\file.txt"

Print (LogFile, "File root = " + PathGetFileRoot (filePath) + "\r\n")


Print (LogFile, "Short path = " + PathGetShort (filePath) + "\r\n")

endproc

PathGetTemp
Get the full path of the temporary directory as defined by the Windows system.
Syntax:
String PathGetTemp ()
Returns:
The returned string is the full path, including drive letter but excluding any trailing backslashes, of the temporary
directory.
Comments:
The temporary directory can be used to create temporary files and directories which are only needed for a short
period of time.
Example:
The following example creates a new directory if it does not yet exist.
proc main ()

string tempPath, newPath


tempPath = PathGetTemp ()
newPath = tempPath + "\\temp1\\temp2"

if (PathFind (newPath) == FALSE)


PathCreate (newPath)
endif

endproc

ResolvePath
Convert a relative path to a clean path.
Syntax:
String ResolvePath (String Path)
Path is the relative path to be resolved.
Returns:
A string containing the complete path if the operation was successful, or a string with the original „incomplete“
path if the path could not be found.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 27 - Path Functions - 341

Comments:
Supplied with a path string which can contain “.” or “..” components, this function removes these parts to come
up with a clean path string. Contrary to CompletePath, if the path is a relative path, it is not appended to the
current working directory.
Example:
The following example displays a new relative path.
proc main ()

string strCurrentPath, strDisplayedPath


strCurrentPath = 'the/current/path/you/have/DELETEME/'
strDisplayedPath = ResolvePath (strCurrentPath + '..')
Print ("The new path is: " + strDisplayedPath + "without DELETEME folder.\n")

endproc

27.3 Example
The following code sample illustrates the path functions. It creates a path if it does not yet exist and prints
directory and file information, such as file name, path and drive.
proc PathFunctions ()
string tempPath, newPath, filePath
tempPath = PathGetTemp ()
newPath = tempPath + "\\temp1\\temp2"
if (PathFind (newPath) == FALSE)
PathCreate (newPath)
endif
filePath = "C:\\Progam Files\\Software1\\Software2\\file.txt"
Print (LogFile, "Drive = " + PathGetDrive (filePath) + "\r\n")
Print (LogFile, "Directory = " + PathGetDir (filePath) + "\r\n")
Print (LogFile, "File Name = " + PathGetFileName (filePath) + "\r\n")
Print (LogFile, "File Extension = " + PathGetFileExt (filePath) + "\r\n")
Print (LogFile, "File root = " + PathGetFileRoot (filePath) + "\r\n")
Print (LogFile, "Short path = " + PathGetShort (filePath) + "\r\n")
endproc

proc main ()
PathFunctions ()
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


342 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Network Functions

This chapter explains all network functions included in the Chilli functions. All functions of this module are
included in the network.chx file for Windows or network.so file for Linux.

28.1 Introduction
The Chilli network function group allows you to execute a large number of operations in your network such as
recovering information about the preferred network interface, port numbers and IP addresses, to establish and
close connections, to manipulate packets, and so on.

28.2 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli network function group has Predefined Handle Data Types.

28.2.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


NetHandle Object type: reference to the handle of an open socket on a server
NetToolHandle Object type: reference to the handle of a network raw tool object
NetPacketHandle Object type: reference to the handle of a packet object

NetHandle
The NetHandle data type is a reference to the handle of an open socket on a server.
The function NetCreateSocket returns a value of this object type that a number of other functions expect as
their argument. Any open socket and thus the value of this object type should always be closed by the
NetDeleteSocket function.

NetToolHandle
The NetToolHandle data type is a reference to the handle of a network raw tool object.
The function NetToolCreate returns a value of this object type that a number of other functions expect as their
argument. Any network raw tool object and thus the value of this object type should always be closed by the
NetToolDelete function.

Numara Software, Inc. and BMC Software, Inc. Confidential.


344 - BMC FootPrints Asset Core - Chilli Reference

NetPacketHandle
The NetPacketHandle data type is a reference to the handle of a packet object.
The function NetPacketCreate returns a value of this object type that a number of other functions expect as
their argument. Any packet object and thus the value of this object type should always be closed by the
NetPacketDelete function.

28.3 Functions
The Chilli network functions can be divided into the following groups:
• General Network Functions
• Functions Referencing NetHandle
• Functions Referencing NetHandle and Dedicated to SSL
• Functions Referencing NetToolHandle
• Functions Referencing NetPacketHandle

28.3.1 General Network Functions


Following you find the list of all functions of the network module not referencing any handle:

Function OS Description
NetExtractPortCount Return the number of ports in the specified range

NetExtractPortRange Extract a list of ports from a given port range

NetGetDnsName Get the DNS name of a device

NetGetInterface Get the preferred network interface

NetGetInterfaceList Get the list of network interfaces

NetGetIpAddress Get the IP address of a device

NetNameToIps Get the number of resolved IP addresses of a device

NetExtractPortCount
Return the number of ports in the specified range.
Syntax:
Int NetExtractPortCount (String PortRange)
PortRange is the given range of ports.
Returns:
Returns the number of individual ports in the whole range.
Example:
include "network.chx"

int main ()

string szOpenedPortRange
int iTotal

szOpenedPortRange = "1-4,10-12,15"
iTotal = NetExtractPortCount (szOpenedPortRange)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 345

Print ("Ports count [" + iTotal + "].")

return 0
endproc

Port count [8].

NetExtractPortRange
Extract a list of ports from a given port range.
Syntax:
Int[] NetExtractPortRange (String PortRange)
PortRange is the given range of ports.
Returns:
The list of ports extracted from port range.
Example:
include "network.chx"

int main ()

string szOpenedPortRange, strList


int vecPort[]
int iTotal, iLoop

szOpenedPortRange = "1-4,10-12,15"
vecPort = NetExtractPortRange (szOpenedPortRange)

iTotal = ArrayGetSize (vecPort)

if (iTotal == 0)
Print ("Failed to get the port range.")
return 1
endif

for (iLoop = 1; iLoop <= iTotal; iLoop += 1)


if (strList != "")
strList = strList + ","
endif

strList = strList + vecPort[iLoop]


endfor

Print ("Extracted ports [" + strList + "].")

return 0
endproc

Extracted ports [1,2,3,4,10,11,12,15].

NetGetDnsName
Get the DNS name of the specified device.

Numara Software, Inc. and BMC Software, Inc. Confidential.


346 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
String NetGetDnsName (String IpAddress)
IpAddress is the IP address in dotted notation of the device for which the DNS name is to be returned.
Returns:
The host DNS name if successful.
Example:
include "network.chx"

int main ()

string szDnsName, szIpAddress

szIpAddress = "87.248.113.14"

szDnsName = NetGetDnsName (szIpAddress)

Print ("DNS name for [" + szIpAddress + "] is [" + szDnsName + "]")

return 0
endproc

DNS name for [87.248.113.14] is [f1.us.www.vip.ird.yahoo.com]

NetGetInterface
Get the preferred network interface.
Syntax:
String NetGetInterface ()
Returns:
The name of the prefered network interface that can be opened with the underlying raw API.
Example:
include "network.chx"

int main ()

string szInterface

szInterface = NetGetInterface ()

if (StrLen (szInterface) == 0)
Print ("Failed to get the network interface.")
return 1
endif

Print ("Retrieved network interface [" + szInterface + "]")

return 0
endproc

Retrieved network interface [\Device\NPF_{1ED1B29E-A825-4547-9617-D2B2A69618A1}]

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 347

NetGetInterfaceList
Get the list of network interfaces.
Syntax:
String[] NetGetInterfaceList ()
Returns:
The list of network interface that can be opened with the underlying raw API.
Example:
include "network.chx"

int main ()

string vecInterfaces[]
string strList
int iTotal, iLoop

vecInterfaces = NetGetInterfaceList ()

iTotal = ArrayGetSize (vecInterfaces)

if (iTotal == 0)
Print ("Failed to get the network interface list.")
return 1
endif

for (iLoop = 1; iLoop <= iTotal; iLoop += 1)


if (strList != "")
strList = strList + ","
endif

strList = strList + vecInterfaces[iLoop]


endfor

Print ("Interfaces list is [" + strList + "]")

return 0
endproc

Interfaces list is [\Device\NPF_{1ED1B29E-A825-4547-9617-D2B2A69618A1},\Device\NPF_{2B6FA697-4784-4535-AC0E-


0C1D310D07AE},\Device\NPF_{100B8EC1-374C-4F17-95C9-5C0AFA7833C7}]

NetGetIpAddress
Get the IP address of the specified device.
Syntax:
String NetGetIpAddress (String HostDescriptor)
HostDescriptor is Name of the device for which the IP address is to be found.
Returns:
The host Ip address if successful.
Example:
include "network.chx"

Numara Software, Inc. and BMC Software, Inc. Confidential.


348 - BMC FootPrints Asset Core - Chilli Reference

int main ()

string szDescriptor, szIpAddress

szDescriptor = "www.yahoo.com"

szIpAddress = NetGetIpAddress (szDescriptor)

Print ("IP Address for [" + szDescriptor + "] is [" + szIpAddress + "]")

return 0
endproc

IP Address for [www.yahoo.com] is [87.248.113.14]

NetNameToIps
Get the number of resolved IP addresses of a device.
Syntax:
Int NetNameToIps (String MachineName, String[] ResolvedIps)
MachineName is the name of the device to resolve.
ResolvedIps is the list of strings containing the resolved IP addresses.
Returns:
The number of resolved IP addresses from the given device name or 0 if the operation failed.
Example:
include "network.chx"

int main ()

string vecIps[]
string szDnsName, strIpList
int iTotalIps, iLoopIp

szDnsName = "www.google.com"

iTotalIps = NetNameToIps (szDnsName, vecIps)

for (iLoopIp = 1; iLoopIp <= iTotalIps; iLoopIp += 1)


if (strIpList != "")
strIpList = strIpList + ","
endif

strIpList = strIpList + vecIps[iLoopIp]


endfor

Print ("IP address list for [" + szDnsName + "] is [" + strIpList + "]")

return 0
endproc

IP address list for [www.google.com] is [209.85.135.99,209.85.135.103,209.85.135.104,209.85.135.147]

28.3.2 Functions Referencing NetHandle


Following you find the list of all functions of the network module referencing the handle NetHandle:

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 349

Function OS Descrition
NetBind Bind to a designated port

NetConnect Perform a connect operation on the socket.

NetConnectT

NetCreateRaw Create a Raw connection using the previously opened socket

NetCreateSocket Create a socket to the named server

NetCreateTCP Create a TCP connection using the previously opened socket

NetCreateUDP Create a UDP connection using the previously opened socket

NetDeleteSocket Close the socket already opened to a server

NetDisconnect Close a connection

NetReceive Receive a packet from the socket

NetSend Transmit a packet on a connected socket

NetSendTo Transmit a packet on a UDP socket to a specified host and port

NetBind
Bind to a designated port.
Syntax:
Bool NetBind (NetHandle Socket, Int PortNumber)
Socket is the handle to the socket.
PortNumber is number of the port to bind to.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "network.chx"

int main ()

NetHandle hSocketListen
string strReceived
int iListenPort
bool fReturn

iListenPort = 3500

hSocketListen = NetCreateSocket ()
if (hSocketListen == 0)
Print ("Failed to create socket.")
return 1
endif

fReturn = NetCreateUDP (hSocketListen)

if (fReturn == FALSE)
Print ("Failed to create UDP connection.")

Numara Software, Inc. and BMC Software, Inc. Confidential.


350 - BMC FootPrints Asset Core - Chilli Reference

NetDeleteSocket (hSocketListen)
return FALSE
endif

fReturn = NetBind (hSocketListen, iListenPort)

if (fReturn == FALSE)
Print ("Failed to bind to local port [" + iListenPort + "].")
NetDisconnect (hSocket)
NetDeleteSocket (hSocketListen)
return 1
endif

strReceived = NetReceive (hSocketListen, 50, 300, 0)

Print ("Received [" + strReceived + "] from client.\n")

NetDeleteSocket (hSocketListen)
return 0
endproc

Received [Hello World\x0d\x0a] from client.

NetConnect
Perform a connect operation on the socket.
Syntax:
Bool NetConnect (NetHandle Socket, String ServerName, Int PortNumber)
Socket is the handle to the socket.
ServerName is the name of the server to connect to.
PortNumber is number of the port to connect to.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "network.chx"

int main ()

NetHandle hSocket
string strIpAddress, strSend, strReceived
int iPort
bool fReturn

strIpAddress = "87.248.113.14"
iPort = 80
strSend = 'GET / HTTP/1.0\r\n\r\n'

hSocket = NetCreateSocket ()

if (hSocket == 0)
Print ("Failed to create socket.")
return 1
endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 351

fReturn = NetCreateTCP (hSocket)

if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif

fReturn = NetConnect (hSocket, strIpAddress, iPort)

if (fReturn == false)
Print ("Failed to connect to [" + strIpAddress + "] on port [" + iPort + "].")
return 1
endif

Print ("Successfully connected to [" + strIpAddress + "] on port [" + iPort + "].\n")

if (NetSend (hSocket, strSend) == false)


Print ("Failed to send [" + strSend + "] to the server.")
NetDeleteSocket (hSocket)
return 1
endif

strReceived = NetReceive (hSocket, 15, 20, 0)

Print ("Received [" + strReceived + "] from server.")

NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 0
endproc

Successfully connected to [87.248.113.14] on port [80].


Received [HTTP/1.1 200 OK] from server.

NetConnectT
Perform a connect operation on the socket.
Syntax:
Bool NetConnect (NetHandle Socket, String ServerName, Int PortNumber, Int Timeout)
Socket is the handle to the socket.
ServerName is the name of the server to connect to.
PortNumber is number of the port to connect to.
Returns:
TRUE to indicate success, FALSE in case of failure.

NetCreateRaw
Create a Raw socket using the previously opened wrapper.
Syntax:
Bool NetCreateRaw (NetHandle Socket)
Socket is the handle to the socket.
Returns:
TRUE to indicate success, FALSE in case of failure.

Numara Software, Inc. and BMC Software, Inc. Confidential.


352 - BMC FootPrints Asset Core - Chilli Reference

Example:
include "network.chx"

int main ()

NetHandle hSocket
string strIpAddress, strSend, strReceived
int iPort
bool fReturn

strIpAddress = "87.248.113.14"
iPort = 7
strSend = 'Hello World\r\n\r\n'

hSocket = NetCreateSocket ()

if (hSocket == 0)
Print ("Failed to create socket.")
return 1
endif

fReturn = NetCreateUDP (hSocket)

if (fReturn == false)
Print ("Failed to create UDP socket.")
return 1
endif

if (NetSendTo (hSocket, strIpAddress, iPort, strSend) == false)


Print ("Failed to send [" + strSend + "] to the server.")
NetDeleteSocket (hSocket)
return 1
endif

Print ("Sent [" + strSend + "] to the server.\n")

NetDeleteSocket (hSocket)
return 0
endproc

Sent [Hello World\r\n] to the server.

NetCreateSocket
Create a socket wrapper to the named server.
Syntax:
NetHandle SocketCreateSocket ()
Returns:
If the socket is created successfully, the function returns a handle to the connection of type NetHandle for use
with other network functions. If the function fails, 0 is returned.
Example:
include "network.chx"

int main ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 353

NetHandle hSocket
string strIpAddress, strSend, strReceived
int iPort
bool fReturn

strIpAddress = "87.248.113.14"
iPort = 80
strSend = 'GET / HTTP/1.0\r\n\r\n'

hSocket = NetCreateSocket ()

if (hSocket == 0)
Print ("Failed to create socket.")
return 1
endif

fReturn = NetCreateTCP (hSocket)

if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif

fReturn = NetConnect (hSocket, strIpAddress, iPort)

if (fReturn == false)
Print ("Failed to connect to [" + strIpAddress + "] on port [" + iPort + "].")
return 1
endif

Print ("Successfully connected to [" + strIpAddress + "] on port [" + iPort + "].\n")

if (NetSend (hSocket, strSend) == false)


Print ("Failed to send [" + strSend + "] to the server.")
NetDeleteSocket (hSocket)
return 1
endif

strReceived = NetReceive (hSocket, 15, 20, 0)

Print ("Received [" + strReceived + "] from server.")

NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 0
endproc

Successfully connected to [87.248.113.14] on port [80].


Received [HTTP/1.1 200 OK] from server.

NetCreateTCP
Create a TCP socket using the previously opened wrapper.

Numara Software, Inc. and BMC Software, Inc. Confidential.


354 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
Bool NetCreateTCP (NetHandle Socket)
Socket is the handle to the socket.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "network.chx"

int main ()

NetHandle hSocket
string strIpAddress, strSend, strReceived
int iPort
bool fReturn

strIpAddress = "87.248.113.14"
iPort = 80
strSend = 'GET / HTTP/1.0\r\n\r\n'

hSocket = NetCreateSocket ()

if (hSocket == 0)
Print ("Failed to create socket.")
return 1
endif

fReturn = NetCreateTCP (hSocket)

if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif

fReturn = NetConnect (hSocket, strIpAddress, iPort)

if (fReturn == false)
Print ("Failed to connect to [" + strIpAddress + "] on port [" + iPort + "].")
return 1
endif

Print ("Successfully connected to [" + strIpAddress + "] on port [" + iPort + "].\n")

if (NetSend (hSocket, strSend) == false)


Print ("Failed to send [" + strSend + "] to the server.")
NetDeleteSocket (hSocket)
return 1
endif

strReceived = NetReceive (hSocket, 15, 20, 0)

Print ("Received [" + strReceived + "] from server.")

NetDisconnect (hSocket)
NetDeleteSocket (hSocket)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 355

return 0
endproc

Successfully connected to [87.248.113.14] on port [80].


Received [HTTP/1.1 200 OK] from server.

NetCreateUDP
Create an UDP socket using the previously opened wrapper.
Syntax:
Bool NetCreateUDP (NetHandle Socket)
Socket is the handle to the socket.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "network.chx"

int main ()

NetHandle hSocket
string strIpAddress, strSend, strReceived
int iPort
bool fReturn

strIpAddress = "87.248.113.14"
iPort = 7
strSend = 'Hello World\r\n\r\n'

hSocket = NetCreateSocket ()

if (hSocket == 0)
Print ("Failed to create socket.")
return 1
endif

fReturn = NetCreateUDP (hSocket)

if (fReturn == false)
Print ("Failed to create UDP socket.")
return 1
endif

if (NetSendTo (hSocket, strIpAddress, iPort, strSend) == false)


Print ("Failed to send [" + strSend + "] to the server.")
NetDeleteSocket (hSocket)
return 1
endif

Print ("Sent [" + strSend + "] to the server.\n")

NetDeleteSocket (hSocket)
return 0
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


356 - BMC FootPrints Asset Core - Chilli Reference

Sent [Hello World\r\n] to the server.

NetDeleteSocket
Destroy the socket wrapper. After this call, the supplied NetHandle is no longer valid.
Syntax:
Bool NetDeleteSocket (NetHandle Socket)
Socket is the handle to the socket.
Returns:
TRUE to indicate success, FALSE in case of failure.
Comments:
If the handle is not valid, the function validates the handle value passed to it and sets ErrCode to
ERR_BADHANDLE. Closing the socket frees up the resources associated with the handle and invalidates the
handle. After closing the socket the supplied NetHandle is no longer valid and the handle value can no longer be
used.
Example:
include "network.chx"

int main ()

NetHandle hSocket
string strIpAddress, strSend, strReceived
int iPort
bool fReturn

strIpAddress = "87.248.113.14"
iPort = 80
strSend = 'GET / HTTP/1.0\r\n\r\n'

hSocket = NetCreateSocket ()

if (hSocket == 0)
Print ("Failed to create socket.")
return 1
endif

fReturn = NetCreateTCP (hSocket)

if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif

fReturn = NetConnect (hSocket, strIpAddress, iPort)

if (fReturn == false)
Print ("Failed to connect to [" + strIpAddress + "] on port [" + iPort + "].")
return 1
endif

Print ("Successfully connected to [" + strIpAddress + "] on port [" + iPort + "].\n")

if (NetSend (hSocket, strSend) == false)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 357

Print ("Failed to send [" + strSend + "] to the server.")


NetDeleteSocket (hSocket)
return 1
endif

strReceived = NetReceive (hSocket, 15, 20, 0)

Print ("Received [" + strReceived + "] from server.")

NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 0
endproc

Successfully connected to [87.248.113.14] on port [80].


Received [HTTP/1.1 200 OK] from server.

NetDisconnect
Close a socket.
Bool NetDisconnect (NetHandle Socket)
Socket is the handle to the socket.
Returns:
TRUE to indicate success, FALSE in case of failure.
Comments:
This closes the connection but maintains the wrapper open and available for further socket creation. This
function is to be used with care, as one of the create TCP/UDP/Raw functions is required to reuse this socket. Use
the NetDeleteSocket functionto properly release the socket.
Example:
include "network.chx"

int main ()

NetHandle hSocket
string strIpAddress, strSend, strReceived
int iPort
bool fReturn

strIpAddress = "87.248.113.14"
iPort = 80
strSend = 'GET / HTTP/1.0\r\n\r\n'

hSocket = NetCreateSocket ()

if (hSocket == 0)
Print ("Failed to create socket.")
return 1
endif

fReturn = NetCreateTCP (hSocket)

if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1

Numara Software, Inc. and BMC Software, Inc. Confidential.


358 - BMC FootPrints Asset Core - Chilli Reference

endif

fReturn = NetConnect (hSocket, strIpAddress, iPort)

if (fReturn == false)
Print ("Failed to connect to [" + strIpAddress + "] on port [" + iPort + "].")
return 1
endif

Print ("Successfully connected to [" + strIpAddress + "] on port [" + iPort + "].\n")

if (NetSend (hSocket, strSend) == false)


Print ("Failed to send [" + strSend + "] to the server.")
NetDeleteSocket (hSocket)
return 1
endif

strReceived = NetReceive (hSocket, 15, 20, 0)

Print ("Received [" + strReceived + "] from server.")

NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 0
endproc

Successfully connected to [87.248.113.14] on port [80].


Received [HTTP/1.1 200 OK] from server.

NetReceive
Receive a packet from the socket.
Syntax:
String NetReceive (NetHandle Socket, Int MaxLength, Long WaitSeconds, Long WaitMilliseconds)
Socket is the handle to the socket.
MaxLength is maximum length of the message.
WaitSeconds is number of seconds to wait.
WaitMilliseconds is the number of additional milliseconds to wait.
Returns:
String containing the received content.
Comments:
If the message is longer than expected it is truncated at the maximum length.
Example:
include "network.chx"

int main ()

NetHandle hSocket
string strIpAddress, strSend, strReceived
int iPort
bool fReturn

strIpAddress = "87.248.113.14"

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 359

iPort = 80
strSend = 'GET / HTTP/1.0\r\n\r\n'

hSocket = NetCreateSocket ()

if (hSocket == 0)
Print ("Failed to create socket.")
return 1
endif

fReturn = NetCreateTCP (hSocket)

if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif

fReturn = NetConnect (hSocket, strIpAddress, iPort)

if (fReturn == false)
Print ("Failed to connect to [" + strIpAddress + "] on port [" + iPort + "].")
return 1
endif

Print ("Successfully connected to [" + strIpAddress + "] on port [" + iPort + "].\n")

if (NetSend (hSocket, strSend) == false)


Print ("Failed to send [" + strSend + "] to the server.")
NetDeleteSocket (hSocket)
return 1
endif

strReceived = NetReceive (hSocket, 15, 20, 0)

Print ("Received [" + strReceived + "] from server.")

NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 0
endproc

Successfully connected to [87.248.113.14] on port [80].


Received [HTTP/1.1 200 OK] from server.

NetSend
Transmit a payload on a connected socket (TCP dedicated).
Syntax:
Bool NetSend (NetHandle Socket, String Buffer)
Socket is the handle to the socket.
Buffer is the payload to send.
Returns:
TRUE to indicate success, FALSE in case of failure.

Numara Software, Inc. and BMC Software, Inc. Confidential.


360 - BMC FootPrints Asset Core - Chilli Reference

Example:
include "network.chx"

int main ()

NetHandle hSocket
string strIpAddress, strSend, strReceived
int iPort
bool fReturn

strIpAddress = "87.248.113.14"
iPort = 80
strSend = 'GET / HTTP/1.0\r\n\r\n'

hSocket = NetCreateSocket ()

if (hSocket == 0)
Print ("Failed to create socket.")
return 1
endif

fReturn = NetCreateTCP (hSocket)

if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif

fReturn = NetConnect (hSocket, strIpAddress, iPort)

if (fReturn == false)
Print ("Failed to connect to [" + strIpAddress + "] on port [" + iPort + "].")
return 1
endif

Print ("Successfully connected to [" + strIpAddress + "] on port [" + iPort + "].\n")

if (NetSend (hSocket, strSend) == false)


Print ("Failed to send [" + strSend + "] to the server.")
NetDeleteSocket (hSocket)
return 1
endif

strReceived = NetReceive (hSocket, 15, 20, 0)

Print ("Received [" + strReceived + "] from server.")

NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 0
endproc

Successfully connected to [87.248.113.14] on port [80].


Received [HTTP/1.1 200 OK] from server.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 361

NetSendTo
Transmit a payload on a UDP socket to a specified host and port.
Syntax:
Bool NetSendTo (NetHandle Socket, String ServerName, Int PortNumber, String Buffer)
Socket is the handle to the socket.
ServerName is the name of the server to connect to.
PortNumber is number of the port to bind to.
Buffer is the payload to send.
Returns:
TRUE to indicate success, FALSE in case of failure.

28.3.3 Functions Referencing NetHandle and Dedicated to SSL


Following you find the list of all functions of the network module dedicated to SSL and referencing the handle
NetHandle:

Function OS Description
NetSSLDizable Dizable SSL

NetSSLDizableSSLv2 Dizable SSLv2

NetSSLDizableSSLv3 Dizable SSLv3

NetSSLDizableTLSv1 Dizable TLSv1

NetSSLEnable Enable SSL

NetSSLEnableSSLv2 Enable SSLv2

NetSSLEnableSSLv3 Enable SSLv3

NetSSLEnableTLSv1 Enable TLSv1

NetSSLSetCertVerif Set the peer Cert verification policy

NetSSLDizable
Dizable SSL.
Syntax:
Bool NetSSLDizable (NetHandle Connection)
Connection is the handle to the server connection.
Returns:
TRUE to indicate success, FALSE in case of failure.

NetSSLDizableSSLv2
Dizable SSLv2.
Syntax:
Bool NetSSLDizableSSLv2 (NetHandle Connection)
Connection is the handle to the server connection.
Returns:
TRUE to indicate success, FALSE in case of failure.

Numara Software, Inc. and BMC Software, Inc. Confidential.


362 - BMC FootPrints Asset Core - Chilli Reference

NetSSLDizableSSLv3
Dizable SSLv3.
Syntax:
Bool NetSSLDizableSSLv3 (NetHandle Connection)
Connection is the handle to the server connection.
Returns:
TRUE to indicate success, FALSE in case of failure.

NetSSLDizableTLSv1
Dizable TLSv1.
Syntax:
Bool NetSSLDizableTLSv1 (NetHandle Connection)
Connection is the handle to the server connection.
Returns:
TRUE to indicate success, FALSE in case of failure.

NetSSLEnable
Enable SSL.
Syntax:
Bool NetSSLEnable (NetHandle Connection)
Connection is the handle to the server connection.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "network.chx"

int main ()

NetHandle hSocket
string strIpAddress, strSend, strReceived
int iPort
bool fReturn

strIpAddress = "87.248.113.14"
iPort = 443
strSend = 'GET / HTTP/1.0\r\n\r\n'

hSocket = NetCreateSocket ()

NetSSLEnable (hSocket)
NetSSLEnableSSLv2 (hSocket)
NetSSLEnableSSLv3 (hSocket)
NetSSLEnableTLSv1 (hSocket)
NetSSLDizableCACheck (hSocket)

fReturn = NetCreateTCP (hSocket)

if (fReturn == false)
Print ("Failed to create TCP socket.")

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 363

return 1
endif

fReturn = NetConnect (hSocket, strIpAddress, iPort)

if (fReturn == false)
Print ("Failed to connect")
NetDeleteSocket (hSocket)
return 1
endif

if (NetSend (hSocket, strSend) == false)


Print ("Failed to send [" + strSend + "] to the server.")
NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 1
endif

Print ("Sent [" + strSend + "] to the HTTPS server.\n")

strReceived = NetReceive (hSocket, 25, 20, 0)

Print ("Received [" + strReceived + "] from server.\n")

NetDeleteSocket (hSocket)
return 0
endproc

Sent [GET / HTTP/1.0\r\n\r\n] to the HTTPS server.


Received [HTTP/1.1 302 Found\x0d\x0aDate] from server.

NetSSLEnableSSLv2
Enable SSLv2.
Syntax:
Bool NetSSLEnableSSLv2 (NetHandle Connection)
Connection is the handle to the server connection.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "network.chx"

int main ()

NetHandle hSocket
string strIpAddress, strSend, strReceived
int iPort
bool fReturn

strIpAddress = "87.248.113.14"
iPort = 443
strSend = 'GET / HTTP/1.0\r\n\r\n'

hSocket = NetCreateSocket ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


364 - BMC FootPrints Asset Core - Chilli Reference

NetSSLEnable (hSocket)
NetSSLEnableSSLv2 (hSocket)
NetSSLEnableSSLv3 (hSocket)
NetSSLEnableTLSv1 (hSocket)
NetSSLDizableCACheck (hSocket)

fReturn = NetCreateTCP (hSocket)

if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif

fReturn = NetConnect (hSocket, strIpAddress, iPort)

if (fReturn == false)
Print ("Failed to connect")
NetDeleteSocket (hSocket)
return 1
endif

if (NetSend (hSocket, strSend) == false)


Print ("Failed to send [" + strSend + "] to the server.")
NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 1
endif

Print ("Sent [" + strSend + "] to the HTTPS server.\n")

strReceived = NetReceive (hSocket, 25, 20, 0)

Print ("Received [" + strReceived + "] from server.\n")

NetDeleteSocket (hSocket)
return 0
endproc

Sent [GET / HTTP/1.0\r\n\r\n] to the HTTPS server.


Received [HTTP/1.1 302 Found\x0d\x0aDate] from server.

NetSSLEnableSSLv3
Enable SSLv3.
Syntax:
Bool NetSSLEnableSSLv3 (NetHandle Connection)
Connection is the handle to the server connection.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "network.chx"

int main ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 365

NetHandle hSocket
string strIpAddress, strSend, strReceived
int iPort
bool fReturn

strIpAddress = "87.248.113.14"
iPort = 443
strSend = 'GET / HTTP/1.0\r\n\r\n'

hSocket = NetCreateSocket ()

NetSSLEnable (hSocket)
NetSSLEnableSSLv2 (hSocket)
NetSSLEnableSSLv3 (hSocket)
NetSSLEnableTLSv1 (hSocket)
NetSSLDizableCACheck (hSocket)

fReturn = NetCreateTCP (hSocket)

if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif

fReturn = NetConnect (hSocket, strIpAddress, iPort)

if (fReturn == false)
Print ("Failed to connect")
NetDeleteSocket (hSocket)
return 1
endif

if (NetSend (hSocket, strSend) == false)


Print ("Failed to send [" + strSend + "] to the server.")
NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 1
endif

Print ("Sent [" + strSend + "] to the HTTPS server.\n")

strReceived = NetReceive (hSocket, 25, 20, 0)

Print ("Received [" + strReceived + "] from server.\n")

NetDeleteSocket (hSocket)
return 0
endproc

Sent [GET / HTTP/1.0\r\n\r\n] to the HTTPS server.


Received [HTTP/1.1 302 Found\x0d\x0aDate] from server.

NetSSLEnableTLSv1
Enable TLSv1.

Numara Software, Inc. and BMC Software, Inc. Confidential.


366 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
Bool NetSSLEnableTLSv1 (NetHandle Connection)
Connection is the handle to the server connection.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "network.chx"

int main ()

NetHandle hSocket
string strIpAddress, strSend, strReceived
int iPort
bool fReturn

strIpAddress = "87.248.113.14"
iPort = 443
strSend = 'GET / HTTP/1.0\r\n\r\n'

hSocket = NetCreateSocket ()

NetSSLEnable (hSocket)
NetSSLEnableSSLv2 (hSocket)
NetSSLEnableSSLv3 (hSocket)
NetSSLEnableTLSv1 (hSocket)
NetSSLDizableCACheck (hSocket)

fReturn = NetCreateTCP (hSocket)

if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif

fReturn = NetConnect (hSocket, strIpAddress, iPort)

if (fReturn == false)
Print ("Failed to connect")
NetDeleteSocket (hSocket)
return 1
endif

if (NetSend (hSocket, strSend) == false)


Print ("Failed to send [" + strSend + "] to the server.")
NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 1
endif

Print ("Sent [" + strSend + "] to the HTTPS server.\n")

strReceived = NetReceive (hSocket, 25, 20, 0)

Print ("Received [" + strReceived + "] from server.\n")

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 367

NetDeleteSocket (hSocket)
return 0
endproc

Sent [GET / HTTP/1.0\r\n\r\n] to the HTTPS server.


Received [HTTP/1.1 302 Found\x0d\x0aDate] from server.

NetSSLSetCertVerif
Set the peer Cert verification policy.
Syntax:
Bool NetSSLSetCertVerif (NetHandle Connection, Int iPolicy)
Connection is the handle to the server connection.
iPolicy is the peer Cert verification policy to set.
Returns:
TRUE to indicate success, FALSE in case of failure.
Comments:
This function only verifies if the certificate has been signed by a trusted authority.
The iPolicy parameter can hold one of the following values:
CERT_VERIF_NONE:
Server mode: the server does not send a client certificate request to the client, so the client does not send a
certificate.
Client mode: The server sends a certificate which is checked, but the handshake is continued regardless of the
verification result.
CERT_VERIF_PEER:
Server mode: the server sends a client certificate request to the client, and the returned certificate is checked. If
the verification process fails, the TLS/SSL handshake is immediately terminated with an alert message
containing the reason for the verification failure. The behavior can be controlled by the additional
SSL_VERIFY_FAIL_IF_NO_PEER_CERT and SSL_VERIFY_CLIENT_ONCE flags.
Client mode: the server certificate is verified. If the verification process fails, the TLS/SSL handshake is
immediately terminated with an alert message containing the reason for the verification failure. If no server
certificate is sent, because an anonymous cipher is used, SSL_VERIFY_PEER is ignored.
CERT_VERIF_FAIL_IF_NO_PEER_CERT:
Server mode: if the client did not return a certificate, the TLS/SSL handshake is immediately terminated with
a handshake failure alert. This flag must be used together with SSL_VERIFY_PEER.
Client mode: ignored
CERT_VERIF_CLIENT_ONCE:
Server mode: only request a client certificate on the initial TLS/SSL handshake. Do not ask for a client
certificate again in case of a renegotiation. This flag must be used together with SSL_VERIFY_PEER.
Client mode: ignored
Example:
int main ()
NetHandle hSocket
hSocket = NetCreateSocket ()

if (NetCreateTCP (hSocket))
NetSSLEnable (hSocket)
NetSSLDizableSSLv2 (hSocket)
NetSSLEnableSSLv3 (hSocket)

Numara Software, Inc. and BMC Software, Inc. Confidential.


368 - BMC FootPrints Asset Core - Chilli Reference

NetSSLEnableTLSv1 (hSocket)
NetSSLSetCertVerif (hSocket, CERT_VERIF_NONE)

if (NetConnect (hSocket, "192.168.1.1", 80))


# Client Server Communication...
endif

NetDisconnect (hSocket)
return 0
endproc

28.3.4 Functions Referencing NetToolHandle


A net tool is a built-in low level network tool such as TCP & UDP port scanners. Following you find the list of all
functions of the network module referencing the handle NetToolHandle:

Function OS Description
NetToolCreate Create a new network raw tool object

NetToolDelete Delete an existing network raw tool object

NetToolExecute Execute the net raw tool

NetToolFcntl Apply a value to a member via dedicated function

NetToolGetResult Get the string representation of the execution result

NetToolGetResultEx Get the string representation of the execution result with a parameter

NetToolSetDebugAbort Set the debug abort object reference

NetToolSetDebugContext Set the debug context

NetToolCreate
Create a new network raw tool object.
Syntax:
NetToolHandle NetToolCreate (String ObjectName)
ObjectName is the new network raw tool object to create.
Returns:
A handle of type NetHandle if successful, 0 otherwise.
Comments:
The ObjectName parameter of the new network raw tool object can be one of the following values:

Name Description
IcmpPing Realize ping by sending ICMP ECHO requests and checking responses. This can be used for detecting
whether a peer server is up. Take care that devices can be configured for not to respond to such requests.
IcmpTraceroute Use the ICMP protocol for defining when possible the complete path up to the target host, router by router.
SimpleInterface This tool can be used for building any kind of low level tool directly in Chilli. The main functionnalities are the
ability to build fully custom IPv4, TCP and UDP packets to be sent on the wire, and to listen for the network in
order to gather any response.
SimpleRead This lightweight tool simply listen for the network and tries to acquire any packet matching the supplied filter.
TcpFingerprint Send up to 4 very special packets and gather any response from the peer server. The set of responses can
then be used for guessing the target operating system by analyzing the IP stack behavior.
TcpPortScanner Can be used for detecting when possible the list of opened, closed and filtered TCP ports. This scanner uses
the "half opened" or SYN/SYN-ACK technique.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 369

Name Description
UdpPortScanner Can be used for detecting when possible the list of opened, closed and filtered UDP ports. Unlike the TCP port
scanner which tries to prove that a port is opened, the UDP one assumes this by proving that a port is not
closed. For this reason, it is very difficult to make a difference between opened and filtered ports.

Example:
include "network.chx"

int main ()

NetToolHandle hNetTool
string strIpAddress, strNetReliability, strPortRange
string strOpened, strClosed, strInterface

strInterface = NetGetInterface ()

strIpAddress = "87.248.113.14"
strNetReliability = "2"
strPortRange = "1-200"

hNetTool = NetToolCreate ("TcpPortScanner")

if (hNetTool == 0)
Print ("Failed to create Tcp raw network object.")
return 1
endif

NetToolFcntl (hNetTool, "SetDestinationAddress", strIpAddress)


NetToolFcntl (hNetTool, "SetNetworkReliability", strNetReliability)
NetToolFcntl (hNetTool, "SetPortRange", strPortRange)

Print ("Scanning TCP port range [" + strPortRange + "].\n")


NetToolExecute (hNetTool, strInterface, 60)
Print ("Scan complete.\n")

strOpened = NetToolGetResultEx (hNetTool, "OpenedPortRange")


strClosed = NetToolGetResultEx (hNetTool, "ClosedPortRange")

NetToolDelete (hNetTool)

if ((StrLen (strOpened) > 0) || (StrLen (strClosed) > 0))


Print ("Opened ports: [" + strOpened + "].\n")
Print ("Closed ports: [" + strClosed + "].\n")
else
Print ("Host appears to be down.")
endif

return 0
endproc

Scanning TCP port range [1-200].


Scan complete.
Opened ports: [80].
Closed ports: [].

Numara Software, Inc. and BMC Software, Inc. Confidential.


370 - BMC FootPrints Asset Core - Chilli Reference

NetToolDelete
Delete an existing network raw tool object.
Syntax:
BOOL NetToolDelete (NetToolHandle RawTool)
RawTool is the handle to the network raw tool object.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "network.chx"

int main ()

NetToolHandle hNetTool
string strIpAddress, strNetReliability, strPortRange
string strOpened, strClosed, strInterface

strInterface = NetGetInterface ()

strIpAddress = "87.248.113.14"
strNetReliability = "2"
strPortRange = "1-200"

hNetTool = NetToolCreate ("TcpPortScanner")

if (hNetTool == 0)
Print ("Failed to create Tcp raw network object.")
return 1
endif

NetToolFcntl (hNetTool, "SetDestinationAddress", strIpAddress)


NetToolFcntl (hNetTool, "SetNetworkReliability", strNetReliability)
NetToolFcntl (hNetTool, "SetPortRange", strPortRange)

Print ("Scanning TCP port range [" + strPortRange + "].\n")


NetToolExecute (hNetTool, strInterface, 60)
Print ("Scan complete.\n")

strOpened = NetToolGetResultEx (hNetTool, "OpenedPortRange")


strClosed = NetToolGetResultEx (hNetTool, "ClosedPortRange")

NetToolDelete (hNetTool)

if ((StrLen (strOpened) > 0) || (StrLen (strClosed) > 0))


Print ("Opened ports: [" + strOpened + "].\n")
Print ("Closed ports: [" + strClosed + "].\n")
else
Print ("Host appears to be down.")
endif

return 0
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 371

Scanning TCP port range [1-200].


Scan complete.
Opened ports: [80].
Closed ports: [].

NetToolExecute
Execute the net raw tool.
Syntax:
BOOL NetToolExecute (NetToolHandle RawTool, String Interface, Int Duration)
RawTool is the handle to the network raw tool object.
Interface is the network interface or interface list provided by NetGetInterface.
Duration is the timout value in seconds, before the scan exits.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "network.chx"

int main ()

NetToolHandle hNetTool
string strIpAddress, strNetReliability, strPortRange
string strOpened, strClosed, strInterface

strInterface = NetGetInterface ()

strIpAddress = "87.248.113.14"
strNetReliability = "2"
strPortRange = "1-200"

hNetTool = NetToolCreate ("TcpPortScanner")

if (hNetTool == 0)
Print ("Failed to create Tcp raw network object.")
return 1
endif

NetToolFcntl (hNetTool, "SetDestinationAddress", strIpAddress)


NetToolFcntl (hNetTool, "SetNetworkReliability", strNetReliability)
NetToolFcntl (hNetTool, "SetPortRange", strPortRange)

Print ("Scanning TCP port range [" + strPortRange + "].\n")


NetToolExecute (hNetTool, strInterface, 60)
Print ("Scan complete.\n")

strOpened = NetToolGetResultEx (hNetTool, "OpenedPortRange")


strClosed = NetToolGetResultEx (hNetTool, "ClosedPortRange")

NetToolDelete (hNetTool)

if ((StrLen (strOpened) > 0) || (StrLen (strClosed) > 0))


Print ("Opened ports: [" + strOpened + "].\n")

Numara Software, Inc. and BMC Software, Inc. Confidential.


372 - BMC FootPrints Asset Core - Chilli Reference

Print ("Closed ports: [" + strClosed + "].\n")


else
Print ("Host appears to be down.")
endif

return 0
endproc

Scanning TCP port range [1-200].


Scan complete.
Opened ports: [80].
Closed ports: [].

NetToolFcntl
Apply a value to a member via dedicated function.
Syntax:
BOOL NetToolFcntl (NetToolHandle RawTool, String Operation, String Value)
RawTool is the handle to the network raw tool object.
Operation is operation to execute.
Value is the value associated with the operation specified above.
Returns:
TRUE to indicate success, FALSE in case of failure.
Comments:
The Operation parameter can be one of the following values:

Name Availability Description


SetNetworkReliability All Configure the network reliability. Possible values are "1" for bad reliability, "2" for
medium reliability and "3" for high reliability.
SetNetworkCapability All Configure the maximal bandwidth to be used during the test.
SetDestinationAddress All Configure the address of the target host.
SetDestinationPort TcpFingerprint Configure the TCP port of the target host.
SetKnownPortRange TcpPortScanner Configure the range for the known ports. These ports is scanned first, before the
and privileged and
UdpPortScanner remaining ports. The set of known ports is randomized before the scan in order to
be more stealth.
SetPrivilegedPortRange TcpPortScanner Configure the range for the privileged ports. By default, the range is "1-1024". These
and ports is
UdpPortScanner scanned after the privileged ports and before the remaining ones. The set of
privileged ports is
randomized before the scan in order to be more stealth.
SetPortRange TcpPortScanner Configure the full range of ports to be scanned. This range is separated into two
and different
UdpPortScanner subsets if the range of know ports is unset, and into three different subsets
otherwise. The ports
that are not known nor privileged is the last scanned. The set of remaining ports is
randomized before the scan in order to be more stealth.
SetCaptureFilter SimpleRead and Configure the listener filter in order to gather only packets matching the criteria.
SimpleInterface
EnableTest TcpFingerprint Enable the different tests.
BuildPacket SimpleInterface Build an IPv4, TCP or UDP packet using the supplied packet configuration.
ResetPacket SimpleInterface Reset the currently configured packet.
SendPacket SimpleInterface Send the currently configured packet.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 373

Example:
include "network.chx"

int main ()

NetToolHandle hNetTool
string strIpAddress, strNetReliability, strPortRange
string strOpened, strClosed, strInterface

strInterface = NetGetInterface ()

strIpAddress = "87.248.113.14"
strNetReliability = "2"
strPortRange = "1-200"

hNetTool = NetToolCreate ("TcpPortScanner")

if (hNetTool == 0)
Print ("Failed to create Tcp raw network object.")
return 1
endif

NetToolFcntl (hNetTool, "SetDestinationAddress", strIpAddress)


NetToolFcntl (hNetTool, "SetNetworkReliability", strNetReliability)
NetToolFcntl (hNetTool, "SetPortRange", strPortRange)

Print ("Scanning TCP port range [" + strPortRange + "].\n")


NetToolExecute (hNetTool, strInterface, 60)
Print ("Scan complete.\n")

strOpened = NetToolGetResultEx (hNetTool, "OpenedPortRange")


strClosed = NetToolGetResultEx (hNetTool, "ClosedPortRange")

NetToolDelete (hNetTool)

if ((StrLen (strOpened) > 0) || (StrLen (strClosed) > 0))


Print ("Opened ports: [" + strOpened + "].\n")
Print ("Closed ports: [" + strClosed + "].\n")
else
Print ("Host appears to be down.")
endif

return 0
endproc

Scanning TCP port range [1-200].


Scan complete.
Opened ports: [80].
Closed ports: [].

NetToolGetResult
Get the string representation of the execution result.

Numara Software, Inc. and BMC Software, Inc. Confidential.


374 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
String NetToolGetResult (NetToolHandle RawTool)
RawTool is the handle to the network raw tool object.
Returns:
TRUE to indicate success, FALSE in case of failure.
Comments:
This function is only available for IcmpPing, IcmpTraceroute, SimpleRead and SimpleInterface.

NetToolGetResultEx
Get the string representation of the execution result with a parameter.
Syntax:
String NetToolGetResultEx (NetToolHandle RawTool, String Param)
RawTool is the handle to the network raw tool object.
Param is the value of the parameter.
Returns:
The string representation on success, the empty string otherwise.
Comments:
This function is available for TcpPortScanner and UdpPortScanner with the following possible extra
parameter: OpenedPortRange, ClosedPortRange, FilteredPortRange, UnknownPortRange.
It is also available for TcpFingerprint with the following possible extra parameter: 0, 1, 2, 3 (get result for the
test concerning the first, second, third or fourth packet).
Example:
include "network.chx"

int main ()

NetToolHandle hNetTool
string strIpAddress, strNetReliability, strPortRange
string strOpened, strClosed, strInterface

strInterface = NetGetInterface ()

strIpAddress = "87.248.113.14"
strNetReliability = "2"
strPortRange = "1-200"

hNetTool = NetToolCreate ("TcpPortScanner")

if (hNetTool == 0)
Print ("Failed to create Tcp raw network object.")
return 1
endif

NetToolFcntl (hNetTool, "SetDestinationAddress", strIpAddress)


NetToolFcntl (hNetTool, "SetNetworkReliability", strNetReliability)
NetToolFcntl (hNetTool, "SetPortRange", strPortRange)

Print ("Scanning TCP port range [" + strPortRange + "].\n")


NetToolExecute (hNetTool, strInterface, 60)
Print ("Scan complete.\n")

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 375

strOpened = NetToolGetResultEx (hNetTool, "OpenedPortRange")


strClosed = NetToolGetResultEx (hNetTool, "ClosedPortRange")

NetToolDelete (hNetTool)

if ((StrLen (strOpened) > 0) || (StrLen (strClosed) > 0))


Print ("Opened ports: [" + strOpened + "].\n")
Print ("Closed ports: [" + strClosed + "].\n")
else
Print ("Host appears to be down.")
endif

return 0
endproc

Scanning TCP port range [1-200].


Scan complete.
Opened ports: [80].
Closed ports: [].

NetToolSetDebugAbort
Set the debug abort object reference.
Syntax:
BOOL NetToolSetDebugAbort (NetToolHandle RawTool, VarHandle Var)
RawTool is the handle to the network raw tool object.
Var is the handle to the debug context provided by the BCM agent.
Returns:
TRUE to indicate success, FALSE in case of failure.
Comments:
This function only works in connection with the BCM agent, which provides the debug context.

NetToolSetDebugContext
Set the debug context.
Syntax:
BOOL NetToolSetDebugContext (NetToolHandle RawTool, VarHandle Var)
RawTool is the handle to the network raw tool object.
Var is the handle to the debug context provided by the BCM agent.
Returns:
TRUE to indicate success, FALSE in case of failure.
Comments:
This can help aborting script execution.
This function only works in connection with the BCM agent, which provides the debug context.

28.3.5 Functions Referencing NetPacketHandle


Following you find the list of all functions of the network module referencing the handle NetPacketHandle:

Numara Software, Inc. and BMC Software, Inc. Confidential.


376 - BMC FootPrints Asset Core - Chilli Reference

Function OS Description
NetPacketAlign Align the buffer content to the supplied byte count

NetPacketCreate Create a new packet object

NetPacketDestroy Destroy a packet object

NetPacketDumpForPrint Make a printable string out of a given Handle from the given range

NetPacketGetSeek Return the current seek in the buffer

NetPacketIsLE Indicate whether packet is configured as little endian

NetPacketIsSysLE Indicate whether system is little endian

NetPacketReadInt16 Read a 2 byte integer from the packet at the current seek

NetPacketReadInt32 Read a 4 byte integer from the packet at the current seek

NetPacketReadInt8 Read a 1 byte integer from the packet at the current seek

NetPacketReadInt8X Read several bytes up to the supplied byte count from the packet at the current seek

NetPacketReceive Receive a packet from the socket

NetPacketSend Send function to transmit a packet on a connected socket

NetPacketSendTo Function to transmit a packet on a UDP socket to a specified host and port

NetPacketSetSeek Update the current seek in the buffer

NetPacketSkip Skip the supplied byte count in the buffer

NetPacketSwitchToBE Configure the packet object so it handles big endian integers

NetPacketSwitchToLE Configure the packet object so it handles little endian integers

NetPacketWriteInt16 Write a 2 byte integer in the packet at the current seek

NetPacketWriteInt32 Write a 4 byte integer in the packet at the current seek

NetPacketWriteInt8 Write a 1 byte integer in the packet at the current seek

NetPacketWriteInt8X Write a 1 byte integer repeated X times in the packet at the current seek

NetPacketWriteString Write a string in the packet at the current seek

NetPacketAlign
Align the buffer content to the supplied byte count.
Syntax:
Bool NetPacketAlign (NetPacketHandle Packet, Long Buffer)
Packet is the handle to the packet object.
Buffer is the offset to align.
Returns:
TRUE to indicate success, FALSE in case of failure.

NetPacketCreate
Create a new packet object.
Syntax:
NetPacketHandle NetPacketCreate (Long Buffer)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 377

Buffer is the maximum size of the buffer.


Returns:
A handle to the packet object if successful, 0 otherwise.

NetPacketDestroy
Destroy a packet object.
Syntax:
Bool NetPacketDestroy (NetPacketHandle Packet)
Packet is the handle to the packet object.
Returns:
TRUE to indicate success, FALSE in case of failure.

NetPacketDumpForPrint
Make a printable string out of a given Handle from the given range
Syntax:
string NetPacketDumpForPrint (NetPacketHandle Packet, Long lStartOffset, Long lStopOffset)
Packet is the handle to the packet object.
lStartOffset is the handle to the packet object.
lStopOffset is the handle to the packet object.
Returns:
TRUE to indicate success, FALSE in case of failure.

NetPacketGetSeek
Return the current seek in the buffer.
Syntax:
Long NetPacketGetSeek (NetPacketHandle Packet)
Packet is the handle to the packet object.
Returns:
The current packet seek.

NetPacketIsLE
Indicate whether the packet is configured as little endian.
Bool NetPacketIsLE (NetPacketHandle Packet)
Packet is the handle to the packet object.
Returns:
The packet configured endianess.

NetPacketIsSysLE
Indicate whether system is little endian.
Syntax:
Bool NetPacketIsSysLE (NetPacketHandle Packet)
Packet is the handle to the packet object.
Returns:
The system endianess.

Numara Software, Inc. and BMC Software, Inc. Confidential.


378 - BMC FootPrints Asset Core - Chilli Reference

NetPacketReadInt16
Read a 2 bytes integer from the packet at the current seek.
Syntax:
Long NetPacketReadInt16 (NetPacketHandle Packet)
Packet is the handle to the packet object.
Returns:
The read integer.

NetPacketReadInt32
Read a 4 bytes integer from the packet at the current seek.
Syntax:
Long NetPacketReadInt32 (NetPacketHandle Packet)
Packet is the handle to the packet object.
Returns:
The read integer.

NetPacketReadInt8
Read a 1 byte integer from the packet at the current seek.
Syntax:
Long NetPacketReadInt8 (NetPacketHandle Packet)
Packet is the handle to the packet object.
Returns:
The read integer.

NetPacketReadInt8X
Read several bytes up to the supplied byte count from the packet at the current seek.
Syntax:
String NetPacketReadInt8X (NetPacketHandle Packet, Long ByteCount)
Packet is the handle to the packet object.
ByteCount is the number of bytes to be read from the current seek.
Returns:
The read integers as an escaped string.

NetPacketReceive
Receive a packet from the socket.
Syntax:
Bool NetPacketReceive (NetHandle Socket, NetPacketHandle Packet, Long WaitSeconds, Long
WaitMilliseconds)
Socket is the handle to the socket.
Packet is the handle to the packet object.
WaitSeconds is number of seconds to wait.
WaitMilliseconds is the number of additional milliseconds to wait.
Returns:
TRUE to indicate success, FALSE in case of failure.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 379

NetPacketSend
Send function to transmit a packet on a connected socket.
Syntax:
Bool NetPacketSend (NetHandle Socket, NetPacketHandle Packet)
Socket is the handle to the socket.
Packet is the handle to the packet object.
Returns:
TRUE to indicate success, FALSE in case of failure.

NetPacketSendTo
Function to transmit a packet on a UDP socket to a specified host and port.
Syntax:
Bool NetPacketSendTo (NetHandle Socket, String Server, Int Port, NetPacketHandle Packet)
Socket is the handle to the socket.
Server is the name of the server.
Port is the port number of the server
Packet is the handle to the packet object.
Returns:
TRUE to indicate success, FALSE in case of failure.

NetPacketSetSeek
Update the current seek in the buffer.
Syntax:
Bool NetPacketSetSeek (NetPacketHandle Packet, Long Buffer)
Packet is the handle to the packet object.
Buffer is the absolute position in the buffer.
Returns:
TRUE to indicate success, FALSE in case of failure.

NetPacketSkip
Skip the supplied byte count in the buffer.
Syntax:
Bool NetPacketSkip (NetPacketHandle Packet, Long Buffer)
Packet is the handle to the packet object.
Buffer is the relative number of bytes to skip in the buffer.
Returns:
TRUE to indicate success, FALSE in case of failure.

NetPacketSwitchToBE
Configure the packet object so it handles big endian integers.
Syntax:
Bool NetPacketSwitchToBE (NetPacketHandle Packet)
Packet is the handle to the packet object.

Numara Software, Inc. and BMC Software, Inc. Confidential.


380 - BMC FootPrints Asset Core - Chilli Reference

Returns:
TRUE to indicate success, FALSE in case of failure.

NetPacketSwitchToLE
Configure the packet object so it handles little endian integers.
Syntax:
Bool NetPacketSwitchToLE (NetPacketHandle Packet)
Packet is the handle to the packet object.
Returns:
TRUE to indicate success, FALSE in case of failure.

NetPacketWriteInt16
Write a 2 byte integer in the packet at the current seek.
Syntax:
Bool NetPacketWriteInt16 (NetPacketHandle Packet, Long ByteValue)
Packet is the handle to the packet object.
ByteValue is the 2 byte integer to write.
Returns:
TRUE to indicate success, FALSE in case of failure.

NetPacketWriteInt32
Write a 4 byte integer in the packet at the current seek.
Syntax:
Bool NetPacketWriteInt32 (NetPacketHandle Packet, Long ByteValue)
Packet is the handle to the packet object.
ByteValue is the 4 byte integer to write.
Returns:
TRUE to indicate success, FALSE in case of failure.

NetPacketWriteInt8
Write a 1 byte integer in the packet at the current seek.
Syntax:
Bool NetPacketWriteInt8 (NetPacketHandle Packet, Long ByteValue)
Packet is the handle to the packet object.
ByteValue is the 1 byte integer to write.
Returns:
TRUE to indicate success, FALSE in case of failure.

NetPacketWriteInt8X
Write a 1 byte integer repeated X times in the packet at the current seek.
Syntax:
Bool NetPacketWriteInt8X (NetPacketHandle Packet, Long ByteValue, Long Repeat)
Packet is the handle to the packet object.
ByteValue is the 1 byte integer to write.
Repeat is the number of times the byte value is to be written.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 28 - Network Functions - 381

Returns:
TRUE to indicate success, FALSE in case of failure.

NetPacketWriteString
Write a string in the packet at the current seek.
Syntax:
Bool NetPacketWriteString (NetPacketHandle Packet, String StringValue, Bool IsEscaped)
Packet is the handle to the packet object.
StringValue is the string value to write.
IsEscaped identifies if the provides string contains already escaped characters.
Returns:
TRUE to indicate success, FALSE in case of failure.

Numara Software, Inc. and BMC Software, Inc. Confidential.


382 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Performance Monitoring Functions

This chapter details all functions, data types, constants and error codes which handle the NT/2000/XP
Performance functions in the Chilli script language. All functions of this module are included in the ntperf.chx
file.
These functions are only supported on the Windows NT/2000/XP versions, on the other versions (Windows 95/98)
they compiles but return an FUNCNOTSUPP (function not supported) error to indicate failure.

29.1 Introduction
The functions of the Performance Monitoring module expose the performance counter API of Windows NT/2000/
XP. The counter objects and instances that are accessible through these functions are the same as those available
through the Windows Performance Monitor and the System Monitor.
The mechanism by which performance data is collected are objects and counters. An object is defined as a
measurable entity and each object is associated with a different set of counters. For instance, the Physical Disk
object has counters that measure disk performance while the Memory object has counters that measure memory
performance.
In certain cases, there can be several copies of the same object. For example, several processes and threads run
simultaneously, and some computers contain more than one processor. These object copies are called object
instances. Each object instance has a set of standard counters assigned to it. If an object can have more than one
instance, an instance specification must be included in the counter path. An instance is an instantiation of a
particular object, such as a specific process or thread. All instances of a given object have the same counters. For
example, the Process object has an instance for each of the running processes. The Thread object has an instance
for each thread of each process in the system.
Performance monitoring also requires that each object and counter be identified by a unique index. This index is
stored in the registry with the object's name. Index values are always even numbers.
A counter is a performance data item whose name is stored in the registry. Each counter is related to a specific
area of system functionality. Examples include a processor's busy time, memory usage, or the number of bytes
received over a network connection. Most of these performance counters increment and are never reset to zero.
Each counter is uniquely identified through its name and its path or location, which consists of four elements: the
machine, the object, the object instance and the counter name. The counter name string is of special importance,
because this is the identifier of a counter for inclusion in gathering performance data. The counter names must be
formatted a specific way in order to be properly recognized. The syntax of a counter path is:
\\Machine\PerfObject(ParentInstance/ObjectInstance#InstanceIndex)\Counter
The \\Machine portion is optional. If it is included, it specifies the name of the machine. If you do not
include a machine name, the local machine is used. The machine specification is the network name of the
computer where the counter resides. This specification can be omitted if the counter is located on the local
machine; therefore, a single path string without the machine specification can be used on any computer the
counter is located on.
The \PerfObject component is required. It specifies the object that contains the counter. If the object
supports variable instances, then you must also specify an instance string. The format of the
(ParentInstance/ObjectInstance#InstanceIndex) portion depends on the type of object specified. If

Numara Software, Inc. and BMC Software, Inc. Confidential.


384 - BMC FootPrints Asset Core - Chilli Reference

the object has simple instances, then the format is just the instance name in parentheses. For example, an
instance for the Process object would be the process name such as (Explorer) or (MyApp).
If the instance of this object also requires a parent instance name, the parent instance name must come
before the object instance and be separated by a forward slash character. For example: (Explorer/0).
If the object has multiple instances that have the same name string, they can be indexed sequentially by
specifying the instance index prefixed by a pound sign. Instance indexes are 0-based, so all instances have
an implicit index of "0". For example: (Explorer/0#1).
The \Counter component is required. It specifies the performance counter. The available counters are
displayed in the Microsoft Performance Data Helper (PDH).
The following are two common counters in the counter path format:
\Processor(0)\% Processor Time
\System\% Total Processor Time

29.2 Predefined Constants


Following you find the complete list of all predefined constants of the Windows Performance Monitoring
functions group of the Chilli language:

Name Type Description


FMT Integer Define the scaling factor for the object value in which it is displayed.

FMT
This constant defines the scaling factor for the object value in which it is displayed. It can be a combination of the
following using the OR operator:

Name Type Description


FMT_NOSCALE Integer The database server is of type MySQL.
FMT_1000 Integer The database server is of type Postgres.

29.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli Performance function group has Predefined Handle Data Types.

29.3.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


PerfQueryHandle Object type: reference to the handle of a performance query
PerfCounterHandle Object type: reference to the handle of the counter in a performance query

PerfQueryHandle
The PerfQueryHandle data type is a reference to the handle of a performance query.
The function NtPerfOpenQuery returns a value of this object type that other performance query functions
expect as their first argument. Any open query and thus the value of this object type should always be closed by
the NtPerfCloseQuery function.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 29 - Performance Monitoring Functions - 385

PerfCounterHandle
The PerfCounterHandle data type is a reference to the handle of the counter of a performance query.
The function NtPerfAddCounter returns a value of this object type that other functions expect as their first
argument. Any open counter and thus the value of this object type should always be closed by the
NtPerfRemoveCounter function.

29.4 Functions
Following you find a list of all available Performance functions:

Function OS Description
NtPerfAddCounter Add a counter to a query

NtPerfCloseQuery Close the query as well as all counters contained in the specified query

NtPerfCollectQueryData Collect the current raw data value for all counters in the specified query and
update the status code of each counter
NtPerfGetCounters Return the available counters provided by the specified object on a machine

NtPerfGetCounterScale Get the current or default scale factor for the counter

NtPerfGetCounterText Get the descriptive text for a counter

NtPerfGetCounterValue Return the current value of a specified counter in the format requested

NtPerfGetInstances Return the available instances provided by the specified object on a machine

NtPerfGetObjects Return a list of counter objects available on a named machine

NtPerfMakeCounterPath Create a full counter path from the parameters for use in querying object values

NtPerfOpenQuery Create and initialise a unique query structure that is used to manage the
collection of performance data
NtPerfReadCounter Create a query and read the current value of the supplied counter

NtPerfRemoveCounter Remove a counter from its query

NtPerfSetCounterScale Set the scale factor that is applied to the calculated value of the specified counter
when requesting the formatted counter value
NtPerfValidatePath Validate that the specified counter is present on the machine specified in the
counter path

NtPerfAddCounter
Add a counter to a query.
Syntax:
PerfCounterHandle NtPerfAddCounter (PerfQueryHandle Handle, String CounterPath)
Handle is the handle of the query to which the counter is to be added.
CounterPath is the path of the counter to be added.
Returns:
A handle of type PerfCounterHandle if successful, 0 if the function failed.
Comments:
The returned handle must be used to read the value of the counter after each time that the query is updated with
a call to NtPerfCollectQueryData. The handle is also used to remove the counter from the query if required.

Numara Software, Inc. and BMC Software, Inc. Confidential.


386 - BMC FootPrints Asset Core - Chilli Reference

NtPerfCloseQuery
Close the query as well as all counters contained in the specified query.
Syntax:
Bool NtPerfCloseQuery (PerfQueryHandle Handle)
Handle is the handle of the query of which the counters are to be closed.
Returns:
TRUE if the operation was successful, FALSE if it failed.
Comments:
This function closes all handles related to the query, that is, the handle to the query itself as well as the handles to
all counters of the query, and frees all memory associated with it. After this call, whether successful or not, all
handles connected to the query are no longer valid.

NtPerfCollectQueryData
Collect the current raw data value for all counters in the specified query and update the status code of each
counter.
Syntax:
Bool NtPerfCollectQueryData (PerfQueryHandle Handle)
Handle is the handle of the query.
Returns:
TRUE if the operation was successful, FALSE if it failed.
Comments:
The function can succeed, but might not have collected data for all counters. Always check the status code of
each counter in the query before using the data.

NtPerfGetCounters
Return the available counters provided by the specified object on a machine.
Syntax
String[] NtPerfGetCounters (String MachineName, String ObjectName)
MachineName is the name of the computer for which the counters are to be checked.
ObjectName is the name of the object for which the counters are to be checked.
Returns
A list of counters available for the object on the specified machine. If an error occurred or the function failed, the
returned array is empty.

NtPerfGetCounterScale
Get the current or default scale factor for the counter.
Syntax:
Int NtPerfGetCounterScale (PerfCounterHandle Handle, Bool Default)
Handle is the handle of the counter in the query.
Default is the default setting of the scale factor, which can be TRUE or FALSE.
Returns:
The current or default scale factor for the counter if the operation was successful, 0 if it failed. If the return value
is 0 (a valid value) check the ErrCode to see if the function was successful or not.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 29 - Performance Monitoring Functions - 387

Comments:
If Default is FALSE the function returns the scale factor that is applied to the calculated value of the specified
counter when you request the formatted counter value.
If Default is TRUE the scale value returned by the function is the default recommended scale and not the actual
one currently set.

NtPerfGetCounterText
Get the descriptive text for a counter given its handle or its path.
The function has the following signatures:
Syntax:
String NtPerfGetCounterText (PerfCounterHandle Handle)
String NtPerfGetCounterText (String CounterPath)
Handle is the handle to the counter to be read.
CounterPath is full path to the counter to be read.
Returns:
The descriptive text of the counter if the operation was successful, an empty string if the function failed.
Comments:
In order to use the handle based signature of this function a query should already have been created with the
required couner added to it in order to obtain a counter handle.
The string based signature of this function is a convenience function which removes the need to create a query,
add a counter and perform the read separately.

NtPerfGetCounterValue
Return the current value of a specified counter in the format requested.
Syntax:
Double NtPerfGetCounterValue (PerfCounterHandle Handle, Int Format)
Handle is the handle of the counter in the query.
Format defines the format in which the value is to be returned.
Returns:
The last read value of the counter if the operation was successful, 0 if it failed or an error occurred.
Comments:
Obtaining the value of rate counters such as Page faults/sec requires that NtPerfCollectQueryData be called
twice, with a specific time interval between the two calls followed by this function.
The format of the value is a combination of the following using the OR operator:

PERF_FMT_NOSCALE Do not apply the default scaling factor.


PERF_FMT_1000 Multiply the actual value by 1000.

NtPerfGetInstances
Return the available instances provided by the specified object on a machine.
Syntax
String[] NtPerfGetInstances (String MachineName, String ObjectName)
MachineName is the name of the computer.
ObjectName is the name of the object for which the instances are to be checked.
Returns
A list of instances available for the object on the specified machine if the operation was successful. If an error
occurred or the function failed the returned array is empty.

Numara Software, Inc. and BMC Software, Inc. Confidential.


388 - BMC FootPrints Asset Core - Chilli Reference

NtPerfGetObjects
Return a list of counter objects available on a named machine.
Syntax
String[] NtPerfGetObjects (String MachineName)
MachineName is the name of the computer for which the objects are to be checked.
Returns
A list of objects available on the specified machine if the operation was successful. If an error occurred or the
operation failed the returned array is empty.

NtPerfMakeCounterPath
Create a full counter path from the parameters for use in querying object values.
Syntax:
String NtPerfMakeCounterPath (String MachineName, String ObjectName, String InstanceName,
String ParentInstance, Int InstanceIndex, String CounterName)
MachineName is the name of the computer.
ObjectName is the name of the object.
InstanceName is the name of the instance of the object.
ParentInstance is the instance of the parent of the object.
InstanceIndex is the index of the object instance.
CounterName is the name of the counter to be created.
Returns:
A string displaying the correctly formatted path made up from the passed components if the operation was
successful. This path can then be used for querying object values. If an error occurred or the function failed the
returned string is empty.

NtPerfOpenQuery
Create and initialise a unique query structure that is used to manage the collection of performance data.
Syntax:
PerfQueryHandle NtPerfOpenQuery ()
Returns:
A handle of type PerfQueryHandle if the operation was successful, 0 if the function failed.
Comments:
The returned handle must be used to add or remove counters from the query which can then be read.

NtPerfReadCounter
Create a query and read the current value of the supplied counter.
Syntax:
Double NtPerfReadCounter (String CounterPath)
CounterPath is the path of the counter for which the query is to be created and read.
Returns:
The immediately read value of the counter if the operation was successful, 0 if it failed.
Comments:
This convenience function removes the need to create a query, add a counter and perform the read separately. The
counter value is returned multiplied by the default scale value.
This function is not suitable for reading the value of rate counters such as Page faults/sec which require multiple
values read through the same query for any accuracy.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 29 - Performance Monitoring Functions - 389

NtPerfRemoveCounter
Remove a counter from its query.
Syntax:
Bool NtPerfRemoveCounter (PerfCounterHandle Handle)
Handle is the handle of the counter to be removed.
Returns:
TRUE if the operation was successful, FALSE if it failed.
Comments:
After this call, whether successful or not, the supplied handle is no longer valid.

NtPerfSetCounterScale
Set the scale factor that is applied to the calculated value of the specified counter when requesting the formatted
counter value.
Syntax:
Bool NtPerfSetCounterScale (PerfCounterHandle Handle, Int Scale)
Handle is the handle of the counter for which the scale is to be set.
Scale is the value to which the scale is to be set.
Returns:
TRUE if the operation was successful, FALSE if it failed.
Comments:
If the PERF_FMT_NOSCALE flag is set when reading the counter, the scale factor is ignored.
The Scale value is the power of ten by which to multiply the calculated value before returning it. The valid range
of this parameter is -7 (the returned value is the actual value times 10E-7) to (+7) (the returned value is the actual
value times 10E+7). A value of zero sets the scale to one, so that the actual value is returned.

NtPerfValidatePath
Validate that the specified counter is present on the machine specified in the counter path.
Syntax:
Bool NtPerfValidatePath (String CounterPath)
CounterPath is the full path and name of the counter to be checked.
Returns:
TRUE to indicate that the path is valid and does exist on the machine specified in the path. Returns FALSE if the
path does not exist, although no error is generated. If the supplied path is incorrect, the function fails and sets the
ErrCode.
Comments:
The reason for no error being created when FLASE is returned is the fact that the function does not know if a
nonexistent counter instance has been specified or one that exists but has not yet been created.

29.5 Example
The following code sample illustrates the performance monitoring functions.
proc ReadMemory ()

PerfQueryHandle qhandle;
PerfCounterHandle hCount1, hCount2;

Numara Software, Inc. and BMC Software, Inc. Confidential.


390 - BMC FootPrints Asset Core - Chilli Reference

qhandle = NtPerfOpenQuery ()

string szCount1, szCount2;


szCount1 = NtPerfMakeCounterPath ("", "Memory", "", "", 0, "Available
MBytes")
hCount1 = NtPerfAddCounter (qhandle, szCount1)

szCount2 = NtPerfMakeCounterPath ("", "Memory", "", "", 0, "Available


KBytes")
hCount2 = NtPerfAddCounter (qhandle, szCount2)

NtPerfCollectQueryData (qhandle)

print (szCount1 + "= " + NtPerfGetCounterValue (hCount1, 0) + "\n")


print (szCount2 + "= " + NtPerfGetCounterValue (hCount2, 0) + "\n")

endproc

#####################################################################
# PollCounter
# Used to repeatedly poll and print the value of a counter. fDiff
# is true if the value is a differential rather than absolute.
#####################################################################

proc PollCounter (string szCounter, int Seconds)

int i

PerfQueryHandle hQuery;
PerfCounterHandle hCount;

hQuery = NtPerfOpenQuery ()
hCount = NtPerfAddCounter (hQuery, szCounter)

// Get the starting value

NtPerfCollectQueryData (hQuery)

for (i=1; i<=Seconds; i+=1)


NtPerfCollectQueryData (hQuery)
print (szCounter + "= " + NtPerfGetCounterValue (hCount, 0) + "\n")

wait (1)

endfor

NtPerfCloseQuery (hQuery)

endproc

#####################################################################
# Main
#####################################################################

proc main ()

ErrHandler = INLINE_HANDLER

DirSetCurrent (PathGetDrive (ScriptFile) + ":" + PathGetDir (ScriptFile))

print ("Available Performance Objects:\r\n");

string PerfObjs[], Counters[], Instances[]

PerfObjs = NtPerfGetObjects ("")

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 29 - Performance Monitoring Functions - 391

int i, j

for (i=1; i<= ArrayGetSize (PerfObjs); i+=1)


print (PerfObjs[i] + "\r\n")

print (" Instances:\r\n");

Instances = NtPerfGetInstances ("", PerfObjs[i])


for (j=1; j<= ArrayGetSize (Instances); j+=1)
print (" " + Instances[j] + "\r\n")
endfor

print (" Counters:\r\n");

Counters = NtPerfGetCounters ("", PerfObjs[i])


for (j=1; j<= ArrayGetSize (Counters); j+=1)
print (" " + Counters[j] + ", Path: " +\
NtPerfMakeCounterPath ("", PerfObjs[i], "", "", -1, Counters[j]) + "\r\n")

if (ErrCode != ERR_SUCCESS)
print ("Function failed!\n")
exit
endif
endfor

endfor

string szCounter
szCounter = NtPerfMakeCounterPath ("", "System", "", "", 0, "File Control
Operations/sec")

PollCounter (szCounter, 20)

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


392 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Process Functions

This chapter explains all process functions of the Chilli Language. All functions of this module are included in
the process.chx and process.so file.

30.1 Introduction
The Chilli process functions can be used monitor processes, to get information about these processes and even to
terminate them.

30.2 Functions
Following you find a list of all existing functions for the Process function group module:

Function OS Description
GetRunningProcessList Return of list of running processes.

GetProcessIds Return of list of identifications for the specified process name.

GetProcessUser Return the user name of a process.

GetProcessPath Return the path of a process.

GetUserRunningProcessList Return the list of running processes for a specific user.

TerminateProcess Kill all the running processes who matches the provided module name.

GetProcessIds
Return of list of identifications for the specified process name.
Syntax:
int[] GetProcessIds (string szProcessName)
szProcessName is the name of the process to check for identifications.
Returns:
An array of integers containing the list of process IDs for the specified process, or an empty string if the function
fails or the supplied process name is not valid.

GetProcessUser
Return the user name of a process.
Syntax:
string GetProcessUser (int iProcessId)
iProcessId is the ID of the process for which the user name is to be found.

Numara Software, Inc. and BMC Software, Inc. Confidential.


394 - BMC FootPrints Asset Core - Chilli Reference

Returns:
A the name of the user which launched the process on the machine, or an empty string if the function fails or the
supplied process ID is not valid.

GetProcessPath
Return the path of a process.
Syntax:
String GetProcessPath (Int iProcessId)
iProcessId is the ID of the process for which the path is to be found.
Returns:
A string containing the path of the process if the operation was successful, or an empty string if the function
failed or the supplied process ID is not valid.

GetRunningProcessList
Return of list of running processes.
Syntax:
String[] GetRunningProcessList(bool fUseModuleName)

Returns:
An array of strings containing the list of currently running processes on the machine in form of their module
name, or an empty string if the function fails or the supplied module name is not valid.
Comments:
Each entry is a string, containing the name of the module for that process.

GetUserRunningProcessList
Return the list of running processes for a specific user.
Syntax:
String[] GetUserRunningProcessList (String UserName)
UserName is the name of the user for which the list of running processes is to be returned.
Returns:
The list of running processes for the specified user. Each entry is a string, containing the name of the module for
that process.
Example:
include "process.chx"

proc main ()

string aProcessList[]
int i, iCount

aProcessList = GetUserRunningProcessList ("Administrator")

iCount = ArrayGetSize (aProcessList )

for (i = 0; i <= iCount; i += 1)


Print ("Process " + i + ": " + aProcessList [i] + "\r\n")
endfor

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 30 - Process Functions - 395

endproc

TerminateProcess
Kill all the running processes who matches the provided module name.
Syntax:
Bool TerminateProcess (String Name)
Name is the name of the process to be stopped.
Returns:
TRUE if the function is successful, FALSE if the function fails or the module name is not valid.
Comments:
one
The process name in form of an executable file must be enclosed in double quotes, for example, TerminateProcess
("winzip32.exe").

Numara Software, Inc. and BMC Software, Inc. Confidential.


396 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Progress Dialog Box Functions

This chapter explains all progress functions of the Chilli Language. All functions of this module are included in
the progress.chx file. These functions are not applicable to the UNIX environment.

31.1 Introduction
A progress box is a small dialog box which displays a progress bar to keep you informed about the progress of an
operation, such as an install or a conversion operation. This dialog box does not need user input and
automatically disappears after the operation is completed. The functions of this module enable you to integrate
such boxes into your Chilli scripts.

31.2 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli Progress Dialog Box function group module has Predefined
Handle Data Types.

31.2.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


Progress Object type: reference to the progress window handle

Progress
The Progress data type is a reference to the handle of a progress window handle.
The function ProgressCreate returns this object type and most of the other functions expect it as their first
argument. The data type should be closed by the ProgressDestroy function.

31.3 Functions
Following you find a list of all existing functions for the Progress Dialog Box function group module:

Function OS Description
ProgressAddBar Increment the current position of the bar on a progress dialog box

ProgressCreate Create a progress bar dialog box

Numara Software, Inc. and BMC Software, Inc. Confidential.


398 - BMC FootPrints Asset Core - Chilli Reference

Function OS Description
ProgressDestroy Destroy a progress bar dialog box

ProgressGetBar Get the current position of the bar on a progress dialog box

ProgressSetBar Set the position of the bar on a progress dialog box

ProgressSetLine Set the text on one of the lines on a progress dialog box

ProgressSetTitle Set the title text on a progress dialog box

ProgressAddBar
Increment the current bar position in a modeless progress dialog box.
Syntax:
Bool ProgressAddBar (Progress Handle, Int Increment)
Handle is the handle of the dialog box returned by ProgressCreate.
Increment is the value to be added to the current position.
Returns:
TRUE if the function is successful, FALSE if the function fails or the supplied handle is not valid.
Comments:
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
ProgressCreate.
If the resulting position after the addition is larger than 100, the position is truncated to 100. The operation
returns a success value in this case.
Example:
The following example creates a progress window which displays only a progress bar.
proc main ()

progress hProgress
int count
count = 1
hProgress = ProgressCreate (2)

while (count < 99)


ProgressAddBar (hProgress, 1)
count = count + 1
wend

wait (3)
ProgressDestroy (hProgress)

endproc

ProgressCreate
Create and display a modeless progress dialog box.
Syntax:
Progress ProgressCreate (Int Lines)
Lines is the number of text lines which should appear on the dialog box and must be either 1 or 2.
Returns:
The function returns a handle to the dialog box if successful and 0 if the operation failed. The handle should be
used when calling all other progress functions.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 31 - Progress Dialog Box Functions - 399

Comments:
The progress dialog box consists of 1 or 2 lines of text appearing above a progress bar which can be set to any
value between 0 and 100%. The dialog box is modeless, meaning that when created, it is displayed on the screen
immediately and does not block the execution of the script.
Example:
The following example creates a progress bar dialog box with two lines of text.
proc main ()

;Create a progress bar dialog box with 2 lines of text

progress hProgress
hProgress = ProgressCreate (2)
ProgressSetTitle (hProgress, "BCM Deployment Manager")
ProgressSetLine (hProgress, 1, "Starting Software Distribution")
wait (3)
ProgressDestroy (hProgress)

endproc

ProgressDestroy
Destroy a modeless progress dialog box.
Syntax:
bool ProgressDestroy (Progress Handle)
Handle is the handle of the dialog box returned by ProgressCreate.
Returns:
TRUE if the message box was successfully destroyed, FALSE if the function fails or the supplied handle is not
valid.
Comments:
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
ProgressCreate. If the handle is valid, this function removes the dialog box from the screen and frees up the
resources being used by it. After the function returns, the supplied handle is no longer valid and can not be used
with any of the progress functions.
Example:
The following example creates a progress bar dialog box with two lines of text.
proc main ()

;Create a progress bar dialog box with 2 lines of text

progress hProgress
hProgress = ProgressCreate (2)
ProgressSetTitle (hProgress, "BCM Deployment Manager")
ProgressSetLine (hProgress, 1, "Starting Software Distribution")
wait (3)
ProgressDestroy (hProgress)

endproc

ProgressGetBar
Get the current position of the progress bar on a progress dialog box.
Syntax:
Int ProgressGetBar (Progress Handle)
Handle is the handle of the dialog box returned by ProgressCreate.

Numara Software, Inc. and BMC Software, Inc. Confidential.


400 - BMC FootPrints Asset Core - Chilli Reference

Returns:
The function returns a value between 0 and 100 to indicate the current position of the bar. If the operation fails,
the return value is 0.
Comments:
Note that 0 is also a valid value for the bar in which case the ErrCode needs to be checked to see if an error
occurred.
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
ProgressCreate.

Example:
The following example creates a progress bar window with a title.
proc main ()

progress hProgress
int bar

hProgress = ProgressCreate (1)


ProgressSetTitle (hProgress, "BCM Deployment Manager")
bar = ProgressGetBar (hProgress)

if (bar < 99)


ProgressSetBar (hProgress, 99)
endif

wait (3)
ProgressDestroy (hProgress)

endproc

ProgressSetBar
Set the position of the progress bar on a progress dialog box.
Syntax:
Bool ProgressSetBar (Progress Handle, Int Position)
Handle is the handle of the dialog box returned by ProgressCreate.
Position is the value to which the bar should be set and must be between 0 and 100.
Returns:
TRUE if the function is successful, FALSE if the function fails or the supplied handle is not valid.
Comments:
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
ProgressCreate. The progress bar displays the position value as a percentage. If the supplied position is larger
than 100, the bar is set the 100%.
Example:
The following example creates a progress bar window with a title.
proc main ()

progress hProgress
int bar

hProgress = ProgressCreate (1)


ProgressSetTitle (hProgress, "BCM Deployment Manager")
bar = ProgressGetBar (hProgress)

if (bar < 99)


ProgressSetBar (hProgress, 99)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 31 - Progress Dialog Box Functions - 401

endif

wait (3)
ProgressDestroy (hProgress)

endproc

ProgressSetLine
Set the text on one of the 2 lines in a dialog box created by ProgressCreate.
Syntax:
Bool ProgressSetLine (Progress Handle, Int Line, String Text)
Handle is the handle of the dialog box returned by ProgressCreate.
Line is the number of the line to be modified.
Text is the actual text to be displayed on the specified line.
Returns:
TRUE if the function is successful, FALSE if the function fails or the supplied handle is not valid. The function
fails if the supplied line number is not valid or is larger than the number of lines on the dialog box.
Comments:
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
ProgressCreate. If the handle is correct the line is set to the supplied text.

Example:
The following example creates a progress bar dialog box with two lines of text.
proc main ()

;Create a progress bar dialog box with 2 lines of text

progress hProgress
hProgress = ProgressCreate (2)
ProgressSetTitle (hProgress, "BCM Deployment Manager")
ProgressSetLine (hProgress, 1, "Starting Software Distribution")
wait (3)
ProgressDestroy (hProgress)

endproc

ProgressSetTitle
Set the title bar of a progress dialog box created by ProgressCreate.
Syntax:
Bool ProgressSetTitle (Progress Handle, String Text)
Handle is the handle of the dialog box returned by ProgressCreate.
Text is the text displayed in the dialog box title bar.
Returns:
TRUE if the function is successful, FALSE if the function fails or the supplied handle is not valid.
Comments:
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
ProgressCreate.

Example:
The following example creates a progress bar dialog box with two lines of text.
proc main ()

;Create a progress bar dialog box with 2 lines of text

Numara Software, Inc. and BMC Software, Inc. Confidential.


402 - BMC FootPrints Asset Core - Chilli Reference

progress hProgress
hProgress = ProgressCreate (2)
ProgressSetTitle (hProgress, "BCM Deployment Manager")
ProgressSetLine (hProgress, 1, "Starting Software Distribution")
wait (3)
ProgressDestroy (hProgress)

endproc

31.4 Examples
Code samples to illustrate the use of the progress bar:
Example 1:
The following example creates a progress bar dialog box with a title only.
proc main ()

progress hProgress
int count

;Create a progress bar dialog box with 1 line of text


hProgress = ProgressCreate (1)

;Set the title of the dialog


ProgressSetTitle (hProgress, ’Example Progress Dialog’)
count = 0;

while (count <= 100)

;Set the progress bar position


ProgressSetBar (hProgress, count)

;Set the text on first line of the dialog


ProgressSetLine (hProgress, 1, ’Current Position: ’ + MakeStr(count) + ’%’)

count = count + 1
wend
wait (10)

;Destroy the dialog box handle to free up memory


ProgressDestroy (hProgress)

endproc

Example 2:
The following example creates a progress bar dialog box with two lines of text: the title and a second line.
proc ProgressBarFunctions ()

progress hProgress
int count, bar
hProgress = ProgressCreate (2)
ProgressSetTitle (hProgress, "BCM Deployment Manager")
ProgressSetLine (hProgress, 1, "Starting Software Distribution")
count = 1

while (count < 99)


ProgressAddBar (hProgress, 1)
count = count + 1
wend

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 31 - Progress Dialog Box Functions - 403

bar = ProgressGetBar (hProgress)


if (bar < 99)
ProgressSetBar (hProgress, 99)
endif

Wait (5)
ProgressDestroy (hProgress)

endproc

proc main ()
ProgressBarFunctions ()
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


404 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Registry Functions

This chapter explains all registry functions of the Chilli language. All functions of this module are included in the
registry.chx file. These functions are not applicable for the UNIX environment.

32.1 Introduction
The registry is a database used by the Windows operating system to store configuration information. The
functions of this Chilli module enable you to read and write keys as well as key values of the local or a remote
registry without having to use the Windows Registry Editor.
Registry key paths are denoted in a similar way to file system paths, but start with a root key part which must be
one of the following:
HKEY_LOCAL_MACHINE
HKEY_CURRENT_USER
HKEY_CLASSES_ROOT
HKEY_USERS
Using one of the above as an example, a typical key might be:
‘HKEY_LOCAL_MACHINE\Software\BMC Software\Client Management\Chilli\Params’
Note that the string must be enclosed in hard (single) quotes, otherwise the backslash characters is interpreted as
escape sequences.
The root key part and the remainder of the path can be separated by any combination of ‘:’ or ‘\’. In addition, the
keynames within a path must be separated by ‘\’. So for example, all of the following are valid paths:
‘HKEY_LOCAL_MACHINE:Software\BMC Software\Client Management’
‘HKEY_LOCAL_MACHINE\Software\BMC Software\Client Management’
‘HKEY_LOCAL_MACHINE:\Software\BMC Software\Client Management’

32.2 Predefined Constants


Following you find the complete list of all predefined constants of the Registry functions group of the Chilli script
language:

Name Type Description


REG_BINARY Integer Binary data in any form.
REG_DWORD Integer A 32-bit number.
REG_EXPAND_SZ Integer A null-terminated string that contains unexpanded references to environment variables (for
example, “%PATH%”). It is a Unicode or ANSI string depending on whether you use the Unicode
or ANSI functions. To expand the environment variable references, use the StrExpandEnvString
function.
REG_MULTI_SZ Integer An array of null-terminated strings, terminated by two null characters.
REG_NONE Integer No defined value type.
REG_RESOURCE_LIST Integer A device-driver resource list.

Numara Software, Inc. and BMC Software, Inc. Confidential.


406 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


REG_SZ Integer A null-terminated string. It is a Unicode or ANSI string, depending on whether you use the Unicode or
ANSI functions.

32.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli Registry function group has predefined handle data types.

32.3.1 Predefined Handle Data Types


Predefined handle data types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all predefined handle data types:

Data Type Description


RegKeyHandle Object type: reference to the key handle of a remote registry

RegKeyHandle
The RegKeyHandle data type is a reference to the handle of a predefined root key of a remote registry.
The function RegConnect returns this object type and other functions expect it as their first argument when
trying to access a key or a value on a remote registry. The data type should be closed by the RegCloseKey
function.

32.4 Functions
Following you find the list of all functions of the Registry function module:

Function OS Description
RegAddKey Add a new key to the registry

RegCloseKey Close the registry key handle and free any associated resources

RegConnect Establish a connection to a predefined registry key on another computer

RegDeleteKey Delete a key from the registry

RegDeleteValue Delete a value from the registry

RegGetIntValue Get an integer value from the registry

RegGetKeyName Get the name of a key from the registry

RegGetStrValue Get a string value from the registry

RegGetSubKeys Get the names of all the sub-keys under a registry key

RegGetValueName Get the name of an indexed value under a registry key

RegGetValueNames Get the names of all the values of a registry key

RegGetValueType Get the type of a value in the registry

RegKeyExists Check whether a given registry key exists

RegOpenKey Open the specified registry key

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 32 - Registry Functions - 407

Function OS Description
RegSetValue Add or modify a value in the registry

RegValueExists Check whether a given registry value exists

RegAddKey
Add a new key to the Registry.
Syntax:
Bool RegAddKey (String KeyPath)
Bool RegAddKey (RegKeyHandle Handle, String KeyPath)
KeyPath is the complete local path of the key to be created.
Handle is the handle to the remote root registry key.
Returns:
TRUE if the create operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The supplied KeyPath must be a sensible string for the Registry key to be created.
Example:
This example adds a key if it doesn't yet exist, if it exists it prints the first subkey.
proc main ()

string RegKey, SubKey


RegKey = "HKEY_LOCAL_MACHINE:SOFTWARE\\BMC Software\\Client Management"

if (RegKeyExists (RegKey) == FALSE)


RegAddKey (RegKey)
else
SubKey = RegGetKeyName (RegKey, 1)
print ("Subkey is : " + SubKey + "\r\n")
endif

endproc

RegCloseKey
Close the registry key handle and free any associated resources.
Syntax:
Bool RegCloseKey (RegKeyHandle Handle)
Handle is the handle to the remote root registry key to be closed.
Returns:
TRUE if the function was successful, FALSE if the operation failed or the handle was invalid.
Comments:
After this function has been called the handle becomes invalid and thus can not be used with any longer with
other function, regardless if the operation executed with success or failed.

RegConnect
Establish a connection to a predefined registry key on another computer.
Syntax:
RegKeyHandle RegConnect (String Machine, String RootKeyName)

Numara Software, Inc. and BMC Software, Inc. Confidential.


408 - BMC FootPrints Asset Core - Chilli Reference

Machine is the name of the machine of which the registry is to be accessed.


RootKeyName is the root key name of the remote registry.
Returns:
A handle of type RegKeyHandle if the function was successful, 0 if the operation failed.
Comments:
Windows XP Pro: If the computer is joined to a workgroup and the Force network logons using local accounts to
authenticate as Guest policy is enabled, the function fails. Note that this policy is enabled by default for a
computer running Windows XP Professional that is joined to a workgroup.
Windows XP Home Edition: This function always fails.
Windows 95/98/Me: To use RegConnect, you must install the Microsoft Remote Registry service otherwise the
function fails.
The RootKeyName is one of the predefined root names as follows:
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000/XP:HKEY_PERFORMANCE_DATA
Windows 95/98/Me:HKEY_DYN_DATA
Windows 95/98/Me:HKEY_CURRENT_CONFIG
You cannot specify the HKEY_CLASSES_ROOT or HKEY_CURRENT_USER value for this parameter.

RegDeleteKey
Delete an existing key from the Registry.
Syntax:
Bool RegDeleteKey (String KeyPath)
Bool RegDeleteKey (RegKeyHandle Handle, String KeyPath)
Bool RegDeleteKey (RegKeyHandle Handle, Bool fRecurse)
Bool RegDeleteKey (RegKeyHandle, String KeyPath, Bool fRecurse)
KeyPath is the complete local path of the key to be deleted.
Handle is the handle to the remote root registry key.
fRecurse defines if all sub keys are deleted as well.
Returns:
TRUE if the delete operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The supplied KeyPath must be a sensible string for the Registry key to be deleted.
Example:
This example deletes a key in the registry after having performed a test on its value.
proc main ()

string RegKey, RegValue, strRegValue


int type

RegKey = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\Winlogon'
RegValue = "test"
type = RegGetValueType (RegKey, RegValue)

if (type == REG_SZ)
strRegValue = RegGetStrValue (RegKey, RegValue)
if (strRegValue == "test1")

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 32 - Registry Functions - 409

RegDeleteValue (RegKey, RegValue)


endif
endif

RegDeleteKey (RegKey)

endproc

RegDeleteValue
Delete a value from the Registry.
Syntax:
Bool RegDeleteValue (String KeyPath, String ValueName)
Bool RegDeleteValue (RegKeyHandle Handle, String KeyPath, String ValueName)
KeyPath is the complete local path of the key under which a value is to be deleted.
ValueName is the name of the value to be deleted.
Handle is the handle to the remote root registry key.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The combination of KeyPath and ValueName must be a sensible string for the Registry value to be deleted.
Example:
This example deletes a key in the registry after having deleted its value if it is not equal to "test1".
proc main ()

string RegKey, RegValue, strRegValue


int type

RegKey = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\Winlogon'
RegValue = "test"
type = RegGetValueType (RegKey, RegValue)

if (type == REG_SZ)
strRegValue = RegGetStrValue (RegKey, RegValue)
if (strRegValue == "test1")
RegDeleteValue (RegKey, RegValue)
endif
endif

RegDeleteKey (RegKey)

endproc

RegGetKeyName
Get the name of an indexed child of a registry key.
Syntax:
String RegGetKeyName (String KeyPath, Int ChildNum)
string RegGetKeyName (RegKeyHandle Handle, String KeyPath, Int ChildNum)
KeyPath is the complete local path of the key of which the child is searched.

Numara Software, Inc. and BMC Software, Inc. Confidential.


410 - BMC FootPrints Asset Core - Chilli Reference

ChildNum is the number of the indexed child.


Handle is the handle to the remote root registry key.
Returns:
A string containing the name of the subkey if the operation was successful, or an empty string if the operation
failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The children are numbered starting from 1 for the first one.
Example:
This example adds a key if it doesn't yet exist, if it exists it prints the first subkey.
proc main ()

string RegKey, SubKey


RegKey = "HKEY_LOCAL_MACHINE:SOFTWARE\\BMC Software\\Client Management"

if (RegKeyExists (RegKey) == FALSE)


RegAddKey (RegKey)
else
SubKey = RegGetKeyName (RegKey, 1)
print ("Subkey is : " + SubKey + "\r\n")
endif

endproc

RegGetIntValue
Get an integer value from the Registry.
Syntax:
Int RegGetIntValue (String KeyPath, String ValueName)
Int RegGetIntValue (RegKeyHandle Handle, String KeyPath, String ValueName)
KeyPath is the complete local path of the key containing the value to be read.
ValueName is the name of the value to be read.
Handle is the handle to the remote root registry key.
Returns:
The integer value of the entry to be read if the operation was successful, 0 if the operation failed. If the operation
fails, ErrCode is set to ERR_FUNCFAILED. If the addressed value is not of the type DWORD, then the operation
fails.
Comments:
The supplied KeyPath and ValueName must be sensible strings for the Registry value to be read.
Example:
This example deletes a value if it is equal to zero after having checked that it is of type integer.
proc main ()

string RegKey, RegValue


int type, intRegValue

RegKey = "HKEY_LOCAL_MACHINE:SOFTWARE\\BMC Software\\Client Management"


RegValue ="test"
type = RegGetValueType (RegKey, RegValue)

if (type == REG_DWORD)
intRegValue = RegGetIntValue (RegKey, RegValue)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 32 - Registry Functions - 411

if (intRegValue == 0)
RegDeleteValue (RegKey, RegValue)
endif
endif

endproc

RegGetStrValue
Get a string value from the Registry.
Syntax:
String RegGetStrValue (String KeyPath, String ValueName)
String RegGetStrValue (RegKeyHandle, String KeyPath, String ValueName)
KeyPath is the complete local path of the key containing the value to be read.
ValueName is the name of the value to be read.
Handle is the handle to the remote root registry key.
Returns:
The string value of the entry to be read if the operation was successful, 0 if the operation failed. If the operation
fails, ErrCode is set to ERR_FUNCFAILED. If the addressed value is not of a type which can be represented as a
string then the operation fails. Valid Registry types are:

Name Type Description


REG_BINARY Integer Binary data in any form.
REG_DWORD Integer A 32-bit number.
REG_EXPAND_SZ Integer A null-terminated string that contains unexpanded references to environment variables (for
example, “%PATH%”). It is a Unicode or ANSI string depending on whether you use the Unicode
or ANSI functions. To expand the environment variable references, use the StrExpandEnvString
function.
REG_MULTI_SZ Integer All values are returned in a single string separated by a comma.
REG_RESOURCE_LIST Integer A device-driver resource list.
REG_SZ Integer A null-terminated string. It is a Unicode or ANSI string, depending on whether you use the
Unicode or ANSI functions.

Example:
This example deletes a value if it is equal to the string "test1" after having checked that it is of type string.
proc main ()

string RegKey, RegValue, strRegValue


int type

RegKey = "HKEY_LOCAL_MACHINE:SOFTWARE\\BMC Software\\Client Management"


RegValue = "test"
type = RegGetValueType (RegKey, RegValue)

if (type == REG_SZ)
strRegValue = "test"
RegGetStrValue (RegKey, RegValue)
if (strRegValue == "test1")
RegDeleteValue (RegKey, RegValue)
endif
endif

RegDeleteKey (RegKey)

Numara Software, Inc. and BMC Software, Inc. Confidential.


412 - BMC FootPrints Asset Core - Chilli Reference

endproc

RegGetSubKeys
Get the names of all the sub-keys under a registry key.
Syntax:
String[] RegGetSubKeys (String KeyPath)
String[] RegGetSubKeys (RegKeyHandle Handle, String KeyPath)
KeyPath is the complete local path of the key of which the sub-keys are to be read.
Handle is the handle to the remote root registry key.
Returns:
The names of all the sub-keys if the operation was successful or an empty string array if the function failed.
Comments:
Values are not returned by this function.

RegGetValueName
Get the name of an indexed value under a registry key.
Syntax:
String RegGetValueName (String KeyPath, Int ValueNumber)
String RegGetValueName (RegKeyHandle, String KeyPath, Int ValueNum)
KeyPath is the complete local path of the key of which the child is searched.
ValueNumber is the number of the indexed value.
Handle is the handle to the remote root registry key.
Returns:
A string containing the name of the value if the operation was successful, or an empty string if the operation
failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Example:
This example obtains the value of a key it it does exist.
proc main ()

string RegKey, RegValue,


int type

RegKey = "HKEY_LOCAL_MACHINE:SOFTWARE\\BMC Software\\Client Management"


RegValue = "test"
type = RegGetValueType (RegKey, RegValue)

if (RegValueExists (RegKey, RegValue) == FALSE)


RegSetValue (RegKey, RegValue, type, REG_SZ)
else
RegValue = RegGetValueName (RegKey, 1)
endif

endproc

RegGetValueNames
Get the names of all the values of a registry key.
Syntax:
String[] RegGetValueNames (String KeyPath)
String[] RegGetValueNames (RegKeyHandle Handle, String KeyPath)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 32 - Registry Functions - 413

KeyPath is the complete local path of the key of which the children are searched.
Handle is the handle to the remote root registry key.
Returns:
The name of the values if the operation was successful, or an empty string array if the function failed.
Comments:
This function does not return the sub-keys under the key.

RegGetValueType
Get the type of a value in the Registry.
Syntax:
Int RegGetValueType (String KeyPath, String ValueName)
Int RegGetValueType (RegKeyHandle Handle, String KeyPath, String ValueName)
KeyPath is the complete local path of the key containing the value to be read.
ValueName is the name of the value to be read.
Handle is the handle to the remote root registry key.
Returns:
If successful, the function returns one of the following pre-defined constants:

Name Type Description


REG_BINARY Integer Binary data in any form.
REG_DWORD Integer A 32-bit number.
REG_EXPAND_SZ Integer A null-terminated string that contains unexpanded references to environment variables (for
example, “%PATH%”). It is a Unicode or ANSI string depending on whether you use the Unicode
or ANSI functions. To expand the environment variable references, use the StrExpandEnvString
function.
REG_MULTI_SZ Integer An array of null-terminated strings, terminated by two null characters.
REG_NONE Integer No defined value type.
REG_RESOURCE_LIST Integer A device-driver resource list.
REG_SZ Integer A null-terminated string. It is a Unicode or ANSI string, depending on whether you use the
Unicode or ANSI functions.

If the function fails, it returns 0 and ErrCode is set to ERR_FUNCFAILED.


Comments:
The supplied KeyPath and ValueName must be sensible strings for the Registry value to be read.
Example:
This example deletes a key in the registry after having performed a test on its value.
proc main ()

string RegKey, RegValue, strRegValue


int type

RegKey = "HKEY_LOCAL_MACHINE:SOFTWARE\\BMC Software\\Client Management"


RegValue = "test"
type = RegGetValueType (RegKey, RegValue)

if (type == REG_SZ)
strRegValue = "test"
RegGetStrValue (RegKey, RegValue)
if (strRegValue == "test1")
RegDeleteValue (RegKey, RegValue)

Numara Software, Inc. and BMC Software, Inc. Confidential.


414 - BMC FootPrints Asset Core - Chilli Reference

endif
endif

RegDeleteKey (RegKey)

endproc

RegKeyExists
Check whether a Registry key exists or not.
Syntax:
Bool RegKeyExists (String KeyPath)
Bool RegKeyExists (RegKeyHandle Handle, String KeyPath)
KeyPath is the complete local path of the key to be found.
Handle is the handle to the remote root registry key.
Returns:
TRUE if the key path was found in the Registry, FALSE otherwise or if the operation failed. If the operation fails,
ErrCode is set to ERR_FUNCFAILED. The comparison for keys is case insensitive.
Example:
This example adds a key if it doesn't yet exist, if it exists it prints the first subkey.
proc main ()

string RegKey, SubKey


RegKey = "HKEY_LOCAL_MACHINE:SOFTWARE\\BMC Software\\Client Management"

if (RegKeyExists (RegKey) == FALSE)


RegAddKey (RegKey)
else
SubKey = RegGetKeyName (RegKey, 1)
print ("Subkey is : " + SubKey + "\r\n")
endif

endproc

RegOpenKey
Open the specified registry key.
Syntax:
RegKeyHandle RegOpenKey (String KeyPath)
RegKeyHandle RegOpenKey (RegKeyHandle Handle, String KeyPath)
KeyPath is the complete local path of the key to be opened.
Handle is the handle to the remote root registry key.
Returns:
A handle of type RegKeyHandle if the function was successful, 0 if the operation failed.
Comments:
The supplied key path has the following possible formats:
ROOTKEY:Key1\Key2\Key2
or
ROOTKEY\Key1\Key2\Key2
The root key is one of the names:
HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 32 - Registry Functions - 415

HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000/XP: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA
In the handle based version of this function, the key path mightcan include the root key name. If supplied the
name is ignored and the path is opened relative to the root specified by the handle. When accessing remote
registries, the handle should be one obtained by calling the RegConnect function.

RegSetValue
Add or modify a value in the Registry. This function has the following signatures:
Syntax:
Bool RegSetValue (String KeyPath, String ValueName, Int Type, Int Value)
Bool RegSetValue (String KeyPath, String ValueName, Int Type, String Value)
Bool RegSetValue (RegKeyHandle Handle, String KeyPath, String ValueName, Int ValueType, Int
Value)
Bool RegSetValue (RegKeyHandle Handle, String KeyPath, String ValueName, Int ValueType,
String Value)
KeyPath is the complete local path of the key under which the value is to be added or modified.
ValueName is the name of the value to be modified or added.
Type is the type of value to be created.
Value is the integer or string value to be assigned to the new (or existing) value in the Registry.
Handle is the handle to the remote root registry key.
Returns:
TRUE if the create operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The combination of KeyPath and ValueName must be a valid string for the Registry value to be written. The type
parameter must be one of the following pre-defined constants:

Name Type Description


REG_BINARY Integer Binary data in any form.
REG_DWORD Integer A 32-bit number.
REG_EXPAND_SZ Integer A null-terminated string that contains unexpanded references to environment variables (for example,
“%PATH%”). It is a Unicode or ANSI string depending on whether you use the Unicode or ANSI functions.
To expand the environment variable references, use the StrExpandEnvString function.
REG_SZ Integer A null-terminated string. It is a Unicode or ANSI string, depending on whether you use the Unicode or
ANSI functions.

For an explanation of these types, refer to the Windows Registry Editor help. The Value parameter can be an
integer or string depending on the Type parameter. The Value must be an integer if type is REG_DWORD, and it
must be a string for any other Type value.
Example:
This example sets a value in the registry if it does not yet exist.
proc main ()

string RegKey, RegValue,


int type

RegKey = "HKEY_LOCAL_MACHINE:SOFTWARE\\BMC Software\\Client Management"


RegValue = "test"
type = RegGetValueType (RegKey, RegValue)

Numara Software, Inc. and BMC Software, Inc. Confidential.


416 - BMC FootPrints Asset Core - Chilli Reference

if (RegValueExists (RegKey, RegValue) == FALSE)


RegSetValue (RegKey, RegValue, type, REG_SZ)
else
RegValue = RegGetValueName (RegKey, 1)
endif

endproc

RegValueExists
Check whether a named value exists in the Registry.
Syntax:
Bool RegValueExists (String KeyPath, String ValueName)
Bool RegValueExists (RegKeyHandle Handle, String KeyPath, String ValueName)
KeyPath is the complete local path of the key containing the value to be found.
ValueName is the name of the value to be found.
Handle is the handle to the remote root registry key.
Returns:
If the given key and value are found, the function returns TRUE, otherwise if either key or the value are not found,
FALSE is returned. If the function fails, it returns FALSE and ErrCode is set to ERR_FUNCFAILED.
Example:
This example sets a value in the registry if it does not yet exist.
proc main ()

string RegKey, RegValue,


int type

RegKey = "HKEY_LOCAL_MACHINE:SOFTWARE\\BMC Software\\Client Management"


RegValue = "test"
type = RegGetValueType (RegKey, RegValue)

if (RegValueExists (RegKey, RegValue) == FALSE)


RegSetValue (RegKey, RegValue, type, REG_SZ)
else
RegValue = RegGetValueName (RegKey, 1)
endif

endproc

32.5 Example
Following you find an example illustrating the registry functions.
Example 1:
Following you find an example illustrating the registry functions on a local machine.
proc main ()
string RegKey, RegValue, SubKey
string strRegValue
int intRegValue
int type
RegKey = "HKEY_LOCAL_MACHINE:SOFTWARE\\BMC Software\\Client Management"
if (RegKeyExists (RegKey) == FALSE)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 32 - Registry Functions - 417

RegAddKey (RegKey)
else
SubKey = RegGetKeyName (RegKey, 1)
RegKey = RegKey + "\\" + SubKey
endif
RegValue = "test"
if (RegValueExists (RegKey, RegValue) == FALSE)
RegSetValue (RegKey, RegValue, REG_SZ)
else
RegValue = "test"RegGetValueName (RegKey, 1)
endif
type = RegGetValueType (RegKey, RegValue)
if (type == REG_DWORD)
intRegValue = "test"RegGetIntValue (RegKey, RegValue)
if (intRegValue == 0)
RegDeleteValue (RegKey, RegValue)
endif
endif
if (type == REG_SZ)
strRegValue = "test"
RegGetStrValue (RegKey, RegValue)
if (strRegValue == "test1")
RegDeleteValue (RegKey, RegValue)
endif
endif
RegDeleteKey (RegKey)
endproc

Example 2:
Following you find an example illustrating the registry functions on a remote machine.
include "ntservice.chx"
include "registry.chx"
include "inifile.chx"

string RefWinDir, RefSysDir

;*******************************************************
;Procedure to create registry keys and handle any errors
;*******************************************************

proc CreateOneKey (string NewKey, string szMachine)


RegKeyHandle hKey
hKey = RegConnect (szMachine, "HKEY_LOCAL_MACHINE")
if (RegKeyExists (hkey, NewKey) == 0)
RegAddKey (hKey, NewKey);
if (ErrCode != 0)
Print (LogFile, "Failed to create registry key " + NewKey + "\r\n")
else
Print (LogFile, "Added registry key " + NewKey + "\r\n")
endif
else
Print (LogFile, "Registry key " + NewKey + " exists already\r\n")
endif

RegCloseKey (hKey)
endproc

;*******************************************************
;Perform the creation of new registry keys
;*******************************************************

proc CreateKeys (string szMachine)

Numara Software, Inc. and BMC Software, Inc. Confidential.


418 - BMC FootPrints Asset Core - Chilli Reference

string szKey, szFile


int n, nSect, limit, proginc, progend
inifilehandle inihandle
Print (LogFile, "\r\nStarting creation of new registry keys\r\n")
szFile = DirGetCurrent() + "\\addkey.reg"

if (FileIsIni(szFile))
inihandle = FileIniOpen (szFile)
else
Print (LogFile, "\r\nInifile not valid INI format\r\n")
exit
endif

nSect = FileGetSectionCount (inihandle)


limit = nSect
n = 1
while (n <= nSect)
// print ("Loop: " + makestr(n) + " ")
if (CHILLI_VERH >= 3)
szKey = FileGetSectionName (inihandle, n)
else
szKey = FileGetSectionName (szFile, n)
endif

Print (LogFile, "creation of " + szKey + "\r\n")


CreateOneKey (szKey, szMachine)
n = n + 1
wend
if (CHILLI_VERH >= 3)
FileIniClose (inihandle)
endif
endproc

;*******************************************************
;Procedure to create string registry values
;*******************************************************

proc InstallStringValue (RegKeyHandle hKey, string KeyPath, string ValueName, int ValueType, string NewValue)
int OldType, iOldValue
string szOldValue
if (RegValueExists (hKey, KeyPath, ValueName))
OldType = RegGetValueType (hKey, KeyPath, ValueName)
if (OldType == REG_DWORD)
iOldValue = RegGetIntValue (hKey, KeyPath, ValueName)
szOldValue = MakeStr (iOldValue)
else
szOldValue = RegGetStrValue (hKey, KeyPath, ValueName)
szOldValue = StrToAscii (szOldValue)
endif

endif
if (ValueName == "(Default)")
RegSetValue (hKey, KeyPath, "", ValueType, NewValue)
else
RegSetValue (hKey, KeyPath, ValueName, ValueType, NewValue)
endif
if (ErrCode != 0)
Print (LogFile, "Failed to create registry value " + KeyPath + '\' + ValueName + "\r\n")
else
Print (LogFile, "Added registry value " + KeyPath + '\' + ValueName + "\r\n")

endif
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 32 - Registry Functions - 419

;*******************************************************
;Procedure to create integer registry values
;*******************************************************

proc InstallIntegerValue (RegKeyHandle hKey, string KeyPath, string ValueName, int ValueType, int NewValue)
int OldType, iOldValue
string szOldValue
if (RegValueExists (hKey, KeyPath, ValueName))
OldType = RegGetValueType (hKey, KeyPath, ValueName)
if (OldType == REG_DWORD)
iOldValue = RegGetIntValue (hKey, KeyPath, ValueName)
szOldValue = MakeStr (iOldValue)
else
szOldValue = RegGetStrValue (hKey, KeyPath, ValueName)
szOldValue = StrToAscii (szOldValue)
endif

endif
if (ValueName == "(Default)")
RegSetValue (hKey, KeyPath, "", ValueType, NewValue)
else
RegSetValue (hKey, KeyPath, ValueName, ValueType, NewValue)
endif
if (ErrCode != 0)
Print (LogFile, "Failed to create registry value " + KeyPath + '\' + ValueName + "\r\n")
else
Print (LogFile, "Added registry value " + KeyPath + '\' + ValueName + "\r\n")

endif
endproc

;*******************************************************
;Procedure to format integer registry values
;*******************************************************

proc CreateDwordValue (RegKeyHandle hKey, string szKey, string szName, string szValue)
int iValue
string szNewValue
szNewValue = "0x" + StrRight (szValue, StrLen (szValue) - 6)
iValue = MakeInt (szNewValue)
InstallIntegerValue (hKey, szKey, szName, REG_DWORD, iValue)
endproc

;*******************************************************
;Procedure to format string registry values
;*******************************************************

proc CreateStringValue (RegKeyHandle hKey, string szKey, string szName, string szValue)
int Type, iStart, i
string szNewValue, szTemp
int pathlen, winlen, syslen
if (StrLeft (szValue, 3) == "hex")
if (StrLeft (szValue, 4) == "hex:")
Type = REG_BINARY
iStart = 4
else
iStart = 7
if (StrLeft (szValue, 7) == "hex(2):")
Type = REG_EXPAND_SZ
elif (StrLeft (szValue, 7) == "hex(7):")
Type = REG_MULTI_SZ

Numara Software, Inc. and BMC Software, Inc. Confidential.


420 - BMC FootPrints Asset Core - Chilli Reference

else
Type = REG_BINARY
endif
endif
szValue = szValue + "_"
szValue = StrRight (szValue, StrLen (szValue) - iStart)
while (StrLen (szValue) > 2)
szNewValue = szNewValue + StrToBinary ("\\x" + StrLeft (szValue, 2))
szValue = StrRight(szValue, StrLen (szValue) - 3)
wend
else
Type = REG_SZ
szNewValue = szValue
pathlen = StrLen (szNewValue)
winlen = StrLen (RefWinDir)
syslen = StrLen (RefSysDir)
if (StrLeft (szNewValue, winlen) == RefWinDir)
szNewValue = GetWinDir() + StrRight (szNewValue, pathlen - winlen)
elif (StrLeft (szNewValue, syslen) == RefSysDir)
szNewValue = GetSysDir() + StrRight (szNewValue, pathlen - syslen)
endif
endif
InstallStringValue (hKey, szKey, szName, Type, szNewValue)
endproc

;*******************************************************
;Perform the creation of new/changed registry values
;*******************************************************

proc CreateValues (string szMachine)


int n, nSect, nEntry, m, limit, proginc, progend, iTotal
string szKey, szFile, szEntry, szValue, szNewEntry
if (CHILLI_VERH >= 3)
inifilehandle inihandle
endif
RegKeyHandle hKey
hKey = RegConnect (szMachine, "HKEY_LOCAL_MACHINE")
Print (LogFile, "\r\nStarting creation of registry values\r\n")
szFile = DirGetCurrent () + "\\addvalue.reg"
if (CHILLI_VERH >= 3)
inihandle = FileIniOpen (szFile)
nSect = FileGetSectionCount (inihandle)
else
nSect = FileGetSectionCount (szFile)
endif
limit = 0
n = 1
if (CHILLI_VERH >= 3)
limit = FileGetLineCount (inihandle) - nSect + 2
else
while (n <= nSect)
szKey = FileGetSectionName (szFile, n)
limit = limit + FileGetEntryCount (szFile, szKey)
n = n + 1
wend
endif

n = 1
iTotal = 1
while (n <= nSect)
if (CHILLI_VERH >= 3)
szKey = FileGetSectionName (inihandle, n)
nEntry = FileGetEntryCount (inihandle, szKey)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 32 - Registry Functions - 421

else
szKey = FileGetSectionName (szFile, n)
nEntry = FileGetEntryCount (szFile, szKey)
endif
m = 1
while (m <= nEntry)
if (CHILLI_VERH >= 3)
szEntry = FileGetEntryName (inihandle, szKey, m)
szValue = FileGetValue (inihandle, szKey, szEntry)
else
szEntry = FileGetEntryName (szFile, szKey, m)
szValue = FileGetValue (szFile, szKey, szEntry)
endif
szNewEntry = StrLeft (szEntry, StrLen (szEntry) - 1)
szNewEntry = StrRight (szNewEntry, StrLen (szNewEntry) - 1)
if (StrLeft (szValue, 6) == "dword:")
CreateDwordValue (hKey, szKey, szNewEntry, szValue)
else
CreateStringValue (hKey, szKey, szNewEntry, szValue)
endif

iTotal = iTotal + 1
m = m + 1
wend
n = n + 1
wend
if (CHILLI_VERH >= 3)
FileIniClose (inihandle)
endif
RegCloseKey (hKey)
endproc

;*******************************************************
; CreateOneService
; Generic procedure for renmote creation of one service
; as per the variables passed in the call
;*******************************************************

proc CreateOneService (string ServiceName, string DisplayName, string BinaryPath, string GroupName, string
UserName, int ServiceType, int StartType, int ErrorType, string szMachine)
SCManagerHandle hManager

hManager = ServiceConnectSCM (szMachine, SC_MANAGER_CREATE_SERVICE)


if (ErrCode != 0)
Print (LogFile, "Failed to connect to PC" + "\r\n")
return
endif

if (ServiceExists (hManager, ServiceName))


Print (LogFile, "Service " + ServiceName + " exists already" + "\r\n")
else
ServiceCreate (hManager, ServiceName, BinaryPath, ServiceType)
if (ErrCode != 0)
Print (LogFile, "Failed to create service " + ServiceName + "\r\n")
return
else
Print (LogFile, "Created service " + ServiceName + "\r\n")
endif
endif
ServiceSetName (hManager, ServiceName, DisplayName)
ServiceSetGroup (hManager, ServiceName, GroupName)
ServiceSetUser (hManager, ServiceName, UserName)
ServiceSetStart (hManager, ServiceName, StartType)

Numara Software, Inc. and BMC Software, Inc. Confidential.


422 - BMC FootPrints Asset Core - Chilli Reference

ServiceSetError (hManager, ServiceName, ErrorType)


ServiceDisconnectSCM (hManager)
endproc

;********************************************************
; InstallServices
; This procedure sets the variables for the remote
; creation of the SNMP service
;********************************************************

proc InstallServices (string szMachine)


string ServiceName, DisplayName, BinaryPath, GroupName, UserName
integer ServiceType, StartType, ErrorType
Print (LogFile, "\r\nStarting installation and configuration of SNMP services\r\n")
;Create SNMP Service
ServiceName = "SNMP"
DisplayName = "SNMP"
GroupName = ""
UserName = "LocalSystem"
BinaryPath = GetSysDir() + "\\snmp.exe"
ServiceType = 16
StartType = 2
ErrorType = 1
CreateOneService (ServiceName, DisplayName, BinaryPath, GroupName, UserName, ServiceType, StartType,
ErrorType, szMachine)
endproc

;********************************************************
; Main
;********************************************************

Proc Main()
string szMachine, szMachineList
TextFileHandle hMachineList
int i, iNumPC

RefWinDir = 'C:\WinNT'
RefSysDir = 'C:\WinNT\System32'
ErrHandler = INLINE_HANDLER

// Don't trust anyone: set your own current working directory

DirSetCurrent (PathGetDrive(ScriptFile) + ':' + PathGetDir(ScriptFile))

LogFile = PathGetFileRoot(ScriptFile) + '.log'

// Loop through the list of PCs and create and configure SNMP on each one
hMachineList = FileTextOpen ("List.txt")
iNumPC = FileGetLineCount (hMachineList)

For (i = 1; i <= iNumPC; i += 1)


szMachine = FileGetLine(hMachineList, i)
// Print ( szMachine + "\r\n")
Print (LogFile, "\r\n************\r\n\r\nProcessing: " + szMachine + "\r\n")
InstallServices (szMachine)
CreateKeys (szMachine)
CreateValues (szMachine)

Print (LogFile, "\r\n**** End Processing: " + szMachine + "\r\n")


Endfor

FileTextClose (hMachineList)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 32 - Registry Functions - 423

Endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


424 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


SDBM Database Functions

This chapter in the Chilli Reference explains in detail all functions accessing configuration information in a
SDBM format database file. All functions of this module are included in the sdbmconfig.chx file for Windows or
sdbmconfig.so file for UNIX and Linux.

33.1 Introduction
SDBM (substitute database management) is an open-source, Berkeley like database, that is, a hash table, and is
used for the management of database style files. However, it is NOT compatible with DBM, as sdbm and dbm use
different hashing mechanisms. This is used by the BCM agent modules to easily store and load complex
configuration data.
The functions of this module provide you with the possibility to open such files and read and write their content.

33.2 Error Codes


Following you find a list of all SDBM error codes. These errors are run-time errors that causes the handler
specified in ErrorHandler to be invoked. Functions can return these in addition to the standard runtime errors
such as FUNCFAILED. You will find a list with all runtime errors in Appendix E - Chilli Error Codes on page 677 at
the end of the manual.

Name Description
ERR_SDBMOUTOFHANDLES Out of SDBM file handles (too many opened at once)
ERR_SDBMBADHANDLE Invalid SDBM handle

33.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli SDBM function group has predefined handle data types.

33.3.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all predefined handle data types:

Data Type Description


SdbmHandle Object type: reference to the sdbm file handle

Numara Software, Inc. and BMC Software, Inc. Confidential.


426 - BMC FootPrints Asset Core - Chilli Reference

SdbmHandle
The SdbmHandle data type is a reference to the handle of an sdbm database file.
The function SdbmOpenFile returns this object type and most of the other functions expect it as their first
argument. The data type should be closed by the SdbmCloseFile function.

33.4 Functions
Following you find a complete list of all SDBM database functions:

Function OS Description
SdbmCloseFile Close an already open SDBM file

SdbmOpenFile Open an SDBM file if it exists already

SdbmTableAddRow Add a new row at the end of table

SdbmTableDeleteRow Delete the indexed row

SdbmTableGetInteger Retrieve the integer value at given line/column

SdbmTableGetRowCount Count rows in a table

SdbmTableGetString Retrieve the string value at given line/column

SdbmTableSetInteger Set an integer value at given line/column

SdbmTableSetString Set a string value at given line/column

SdbmCloseFile
Close an already open SDBM file.
Syntax:
Bool SdbmCloseFile (SdbmHandle Handle)
Handle is the handle to the SDBM file to be closed.
Returns:
TRUE if the operation was successful, FALSE if the operation failed or the handle was invalid. If the operation
fails, ErrCode is set to ERR_FUNCFAILED.

SdbmOpenFile
Open an SDBM file if it exists already.
Syntax:
SdbmHandle SdbmOpenFile (String FileName)
FileName is the name of the SDBM file to be opened.
Returns:
Returns a SDBM handle if successful, 0 otherwise. If the operation fails, ErrCode is set to ERR_FUNCFAILED.

SdbmTableAddRow
Add a new row at the end of table.
Syntax:
Bool SdbmTableAddRow (SdbmHandle Handle, String TableName)
Handle is the handle to the SDBM file.
TableName is the name of the table to which a new row is to be added.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 33 - SDBM Database Functions - 427

Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
New rows must be added before their column values can be set. Unlike plain keys, setting a non-existent row/
column does not automatically create it.

SdbmTableDeleteRow
Delete the identified row for a table.
Syntax:
Bool SdbmTableDeleteRow (SdbmHandle Handle, String TableName, Int LineIndex)
Handle is the handle to the SDBM file.
TableName is the name of the table.
LineIndex is the number of the row to be deleted.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
Row numbers start at 1 for the first row.

SdbmTableGetInteger
Retrieve the integer value at given line/column.
Syntax:
Int SdbmTableGetInteger (SdbmHandle Handle, String TableName, Int RowNumber, String
ColumnName)
Handle is the handle to the SDBM file.
TableName is the name of the table.
RowNumber is the line number within the table that contains the cell to be read.
ColumnName is the name of the column in the table that contains the cell to be read.
Returns:
The integer value of the defined table cell if the operation was successful, 0 if the operation failed, if for example,
the column is of the wrong type. If the operation fails, ErrCode is set to ERR_FUNCFAILED.

SdbmTableGetRowCount
Count rows in a table.
Syntax:
Int SdbmTableGetRowCount (SdbmHandle Handle, String TableName)
Handle is the handle to the SDBM file.
TableName is the name of the table to be counted.
Returns:
The number of rows of the table if the operation was successful, 0 if the table is not found or the operation failed.
If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The table name is formatted in a similar way as a simple key.

Numara Software, Inc. and BMC Software, Inc. Confidential.


428 - BMC FootPrints Asset Core - Chilli Reference

SdbmTableGetString
Retrieve the string value at given line/column.
Syntax:
String SdbmTableGetString (SdbmHandle Handle, String TableName, Int RowNumber, String
ColumnName)
Handle is the handle to the SDBM file.
TableName is the name of the table.
RowNumber is the line number within the table that contains the cell to be read.
ColumnName is the name of the column in the table that contains the string to be read that contains the cell
to be read.
Returns:
The string value of the defined table cell if the operation was successful, or an empty string if the operation failed,
or if, for example, the column is of the wrong type. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The caller must free the returned buffer.

SdbmTableSetInteger
Set an integer value at given line/column.
Syntax:
Bool SdbmTableSetInteger (SdbmHandle Handle, String TableName, Int RowNumber, String
ColumnName, Int Value)
Handle is the handle to the SDBM file.
TableName is the name of the table.
RowNumber is the line number within the table that contains the cell to be set.
ColumnName is the name of the column in the table that contains the cell to be set.
Value is the new integer value to be set.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
Row numbers start at 1 for the first row. If the named column does not exist, it is created and set. If the indexed
row does not exist the operation fails and an error occurs.

SdbmTableSetString
Set a string value at given line/column.
Syntax:
Bool SdbmTableSetString (SdbmHandle Handle, String TableName, Int RowNumber, String
ColumnName, String Value)
Handle is the handle to the SDBM file.
TableName is the name of the table.
RowNumber is the line number within the table that contains the cell to be set.
ColumnName is the name of the column in the table that contains the cell to be set.
Value is the new string value to be set.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 33 - SDBM Database Functions - 429

Comments:
Row numbers start at 1 for the first row. If the named column does not exist, it is created and set. If the indexed
row does not exist the operation fails and an error occurs.

Numara Software, Inc. and BMC Software, Inc. Confidential.


430 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Security Policy Functions

This chapter explains all security policy functions of the Chilli script language. All functions of this module are
included in the secupolicy.chx file for Windows or secupolicy.so file for UNIX and Linux.
These functions are only applicable to Windows NT and later.

34.1 Predefined Constants


Following you find the complete list of all predefined constants of the Windows security policy functions group of
the Chilli script language:

34.1.1 Audit Policies:


These constants represent the type of event the system can audit.

Name Type Description


AuditCategoryAccountManagement Integer Audit attempts to create, delete, or change user or group accounts. Also,
audit password changes.
AuditCategoryDetailedTracking Integer Audit specific events, such as program activation, some forms of handle
duplication, indirect access to an object, and process exit.
AuditCategoryLogon Integer Audit attempts to log on to or log off of the system and to make a network
connection.
AuditCategoryObjectAccess Integer Audit attempts to access securable objects, such as files.
AuditCategoryPolicyChange Integer Audit attempts to change Policy object rules.
AuditCategoryPrivilegeUse Integer Audit attempts to use privileges.
AuditCategorySystem Integer Audit attempts to shut down or restart the computer and events that affect
system security or the security log.

These constants represent the auditing options:

Name Type Description


POLICY_AUDIT_EVENT_FAILURE Integer Generate audit records for failed attempts to cause an event of this type to
occur.
POLICY_AUDIT_EVENT_NONE Integer Do not generate audit records for events of this type.
POLICY_AUDIT_EVENT_SUCCESS Integer Generate audit records for successful events of this type.

34.1.2 Account policies


These constants represent the type of account policies:

Numara Software, Inc. and BMC Software, Inc. Confidential.


432 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


AccountForceLogOff Integer Specifies, in seconds, the amount of time between the end of the valid logon
time and the time when the user is forced to log off the network. A value of
TIMEQ_FOREVER indicates that the user is never forced to log off. A value
of zero indicates that the user is forced to log off immediately when the valid
logon time expires.
AccountHistoryLen Integer Specifies the length of password history maintained. A new password
cannot match any of the previous AccountHistoryLen passwords. Valid
values for this element are zero through 8.
AccountLockoutDuration Integer Specifies, in seconds, how long a locked account remains locked before it is
automatically unlocked.
AccountLockoutObsWindow Integer Specifies the maximum time, in seconds, that can elapse between any two
failed logon attempts before lockout occurs.
AccountLockoutThreshold Integer Specifies the number of invalid password authentications that can occur
before an account is marked "locked out."
AccountMaxPasswordAge Integer Specifies, in seconds, the maximum allowable password age. A value of
TIMEQ_FOREVER indicates that the password never expires. The minimum
valid value for this element is 86400. The value specified must be greater
than or equal to the value for the AccountMinPasswordAge.
AccountMinPasswordAge Integer Specifies the minimum number of seconds that can elapse between the time
a password changes and when it can be changed again. A value of zero
indicates that no delay is required between password updates. The value
specified must be less than or equal to the value for the
AccountMaxPasswordAge.
AccountMinPasswordLen Integer Specifies the minimum allowable password length. Valid values for this
element are zero through 256.
AccountSAMName Integer Specifies the name of the Security Account Manager (SAM) domain.
AccountServerPrimary Integer Specifies the name of the domain controller that stores the primary copy of
the database for the user account manager.
AccountServerRole Integer Specifies the role of the logon server. Valid values are:
UAS_ROLE_STANDALONE, UAS_ROLE_MEMBER, UAS_ROLE_BACKUP, and
UAS_ROLE_PRIMARY.

34.1.3 Miscellaneous Defined Constants:


Other defined constants:

Name Type Description


TIMEQ_FOREVER Integer Constant that represents the maximum time.
UAS_ROLE_BACKUP Integer The logon server is a backup.
UAS_ROLE_MEMBER Integer The logon server is a member.
UAS_ROLE_PRIMARY Integer The logon server is a domain controller.
UAS_ROLE_STANDALONE Integer The logon server is a stand-alone server.

34.2 Functions
Following you find the list of all functions of the Path function module:

Function OS Description
FuncSecuPolicyGetAccountPolicy Get the value for the specified account policy

FuncSecuPolicyGetAuditPolicy Get the value for the specified audit policy

FuncSecuPolicySetAccountPolicy Set value for the specified account policy

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 34 - Security Policy Functions - 433

Function OS Description
FuncSecuPolicySetAuditPolicy Set the value for the specified audit policy

FuncSecuPolicyGetAccountPolicy
Get the value for the specified account policy.
Syntax:
String FuncSecuPolicyGetAccountPolicy (String Target, Int Policy)
Target is the DNS or NetBIOS name of the remote server. If Target is empty the local computer is used.
Policy is a defined constant of the account policy.
Returns:
The value of the specified policy. If the operation fails, ErrCode is set to ERR_FUNCFAILED or
ERR_INVALIDPARAM.
Example:
The following example gets the value of the AccountMinPasswordLen policy of the local computer:
proc main ()

string szRes

szRes = FuncSecuPolicyGetAccountPolicy ("", AccountMinPasswordLen)


Print (szRes + "\r\n")

endproc

FuncSecuPolicyGetAuditPolicy
Get the value for the specified audit policy.
Syntax:
Int FuncSecuPolicyGetAuditPolicy (String Target, Int Policy)
Target is the DNS or NetBIOS name of the remote server. If Target is empty then we use local computer.
Policy is a defined constant of the audit policy.
Returns:
The value of the specified policy which can be either of the following:

Value Description
0 No audit for the specified audit policy
1 Audit Failure events only
2 Audit Success events only.
3 Audit Success and Failure events.

If the operation fails, ErrCode is set to ERR_FUNCFAILED or ERR_INVALIDPARAM.


Example:
The following example gets the value of the AuditCategoryPolicyChange policy of the local computer:
proc main ()

string szRes

szRes = FuncSecuPolicyGetAuditPolicy ("", AuditCategoryPolicyChange)


Print (szRes + "\r\n")

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


434 - BMC FootPrints Asset Core - Chilli Reference

FuncSecuPolicySetAccountPolicy
Set value for the specified account policy.
Syntax:
Bool FuncSecuPolicySetAccountPolicy (String Target, Int Policy, Int Value)
Target is the DNS or NetBIOS name of the remote server. If Target is empty the local computer is used.
Policy is a defined constant of the account policy.
Value is the value to set for the specified policy.
Returns:
True if the specified policy has been set, false if it failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED or ERR_INVALIDPARAM.
Example:
The following example sets the value of the AccountMinPasswordLen policy to 8 of the local computer:
proc main ()

bool fRes

fRes = FuncSecuPolicySetAccountPolicy ("", AccountMinPasswordLen, 8)


if (fRes)
return 0
else
return 1
endif

endproc

FuncSecuPolicySetAuditPolicy
Set the value for the specified audit policy.
Syntax:
Bool FuncSecuPolicySetAuditPolicy (String Target, Int Policy, Int Flag, Bool Audit)
Target is the DNS or NetBIOS name of the remote server. If Target is empty then the local computer is used.
Policy is a defined constant of the audit policy.
Flag is the value to set for the specified Policy.
Audit indicates whether auditing is enabled:
Returns:
True if the specified audit policy has been set. If the operation fails, ErrCode is set to ERR_FUNCFAILED or
ERR_INVALIDPARAM.
Comments:
The Flag parameter can be set using the bitwise operator to set the policy with the following values:

POLICY_AUDIT_EVENT_SUCCESS Audit successful occurrences of events of this type.


POLICY_AUDIT_EVENT_FAILURE Audit failed attempts to cause an event of this type to occur.
POLICY_AUDIT_EVENT_NONE No Audit.

The Audit boolean value indicated the following audit situations:


• TRUE indicates to the system that it has to process audit policies depending on their value.
• FALSE indicates to the system that no audit policy is process.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 34 - Security Policy Functions - 435

Example:
The following example sets the value of the AuditCategoryPolicyChange policy to
POLICY_AUDIT_EVENT_FAILURE and POLICY_AUDIT_EVENT_SUCCESS of the local computer:
proc main ()

bool fRes

fRes = FuncSecuPolicySetAuditPolicy ("", AuditCategoryPolicyChange, POLICY_AUDIT_EVENT_FAILURE &


POLICY_AUDIT_EVENT_SUCCESS, true)
if (fRes)
return 0
else
return 1
endif

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


436 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Service Functions

This chapter explains all Windows service functions of the Chilli language. They are only supported on the
Windows NT/2000/XP versions, on the other versions (Windows 95/98) they compiles but return an
FUNCNOTSUPP (function not supported) error to indicate failure.
All functions of this module are included in the ntservice.chx file. This group of functions is not applicable to
the UNIX environment.

35.1 Introduction
Microsoft Windows services, formerly known as NT services, enable you to create long-running executable
applications that run in their own Windows sessions. These services can be automatically started when the
computer boots, can be paused and restarted, and do not show any user interface. This makes services ideal for
use on a server or whenever you need long-running functionality that does not interfere with other users who are
working on the same computer.
The functions of this Chilli module enable you to create such services, get information about a service or modify
items of a service outside of the Windows Services tool on the local or on a remote computer.

35.2 Predefined Constants


Following you find the complete list of all predefined constants of the Windows NT/2000/XP Service functions
group of the Chilli script language:

Name Type Description


SC_MANAGER_ALL_ACCESS Integer STANDARD_RIGHTS_REQUIRED is included in addition to all of the access
types listed in this table.
SC_MANAGER_CONNECT Integer Connecting to the service control manager is enabled.
SC_MANAGER_CREATE_SERVICE Integer Calling of the CreateService function to create a service object and add it to the
database is enabled.
SC_MANAGER_ENUMERATE_SERVICE Integer Calling of the EnumServicesStatus function to list the services that are in the
database is enabled.
SC_MANAGER_LOCK Integer Calling of the LockServiceDatabase function to acquire a lock on the database
is enabled.
SC_MANAGER_QUERY_LOCK_STATUS Integer Calling of the QueryServiceLockStatus function to retrieve the lock status
information for the database is enabled.
SERVICE_ACTIVE Integer Enumerates services that are in the following states:
SERVICE_START_PENDING, SERVICE_STOP_PENDING, SERVICE_RUNNING,
SERVICE_CONTINUE_PENDING, SERVICE_PAUSE_PENDING, and
SERVICE_PAUSED.
SERVICE_CONTINUE Integer The service is taken out of pause or is started.
SERVICE_CONTINUE_PENDING Integer A service continue request is pending.

Numara Software, Inc. and BMC Software, Inc. Confidential.


438 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


SERVICE_DRIVER Integer Enumerates services of type SERVICE_KERNEL_DRIVER and
SERVICE_FILE_SYSTEM_DRIVER.
SERVICE_ERROR_CRITICAL Integer The start-up program logs the error, if possible. If the last-known-good
configuration is being started, the start-up operation fails. Otherwise, the
system is restarted with the last-known-good configuration.
SERVICE_ERROR_IGNORE Integer The start-up (boot) program logs the error but continues the start-up operation.
SERVICE_ERROR_NORMAL Integer The start-up program logs the error and puts up a message box pop-up but
continues the start-up operation.
SERVICE_ERROR_SEVERE Integer The start-up program logs the error. If the last-known-good configuration is
being started, the start-up operation continues. Otherwise, the system is
restarted with the last-known-good configuration.
SERVICE_FILE_SYSTEM_DRIVER Integer Installable file system driver, for example an NFS file redirector.
SERVICE_INACTIVE Integer Enumerates services that are in the SERVICE_STOPPED state.
SERVICE_INTERROGATE Integer Enables calling of the ControlService function to ask the service to report its
status immediately.
SERVICE_KERNEL_DRIVER Integer Kernel driver, usually a device driver.
SERVICE_PAUSE Integer The service is paused.
SERVICE_PAUSE_PENDING Integer A service pause request is pending.
SERVICE_PAUSED Integer The service is paused
SERVICE_RUNNING Integer The service is running.
SERVICE_START_AUTO Integer Specifies a device driver or Win32 service started by the service control manager
automatically during system start-up.
SERVICE_START_BOOT Integer Specifies a device driver started by the operating system loader. This value is
valid only if the service type is SERVICE_KERNEL_DRIVER or
SERVICE_FILE_SYSTEM_DRIVER.
SERVICE_START_DEMAND Integer Specifies a device driver or Win32 service started by the service control
manager when using the control panel.
SERVICE_START_DISABLED Integer Specifies a device driver or Win32 service that can no longer be started.
SERVICE_START_PENDING Integer The service is starting.
SERVICE_START_SYSTEM Integer Specifies a device driver started at system start-up, after the boot drivers are
loaded. This value is valid only if the service type is SERVICE_KERNEL_DRIVER
or SERVICE_FILE_SYSTEM_DRIVER.
SERVICE_STATE_ALL Integer Combines the following states: SERVICE_ACTIVE and SERVICE_INACTIVE.
SERVICE_STOP Integer The service is stopped.
SERVICE_STOP_PENDING Integer The service is stopping.
SERVICE_STOPPED Integer The service is not running.
SERVICE_WIN32 Integer Enumerates services of type SERVICE_WIN32_OWN_PROCESS and
SERVICE_WIN32_SHARE_PROCESS.
SERVICE_WIN32_OWN_PROCESS Integer Specifies a service that runs in its own Win32 process.
SERVICE_WIN32_SHARE_PROCESS Integer Specifies a service that shares a Win32 process with other services.

35.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli Service function group has predefined handle data types.

35.3.1 Predefined Handle Data Types


Predefined handle data types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 35 - Service Functions - 439

Following you find a list of all predefined handle data types:

Data Type Description


SCManagerHandle Object type: reference to the handle of a connection with the service control manager on a specified
remote computer

SCManagerHandle
The SCManagerHandle data type is a reference to the connection with the service control manager on a specified
remote computer and the default service control manager database.
The function ServiceConnectSCM returns a value of this object type, which is used by other service functions
when trying to access services on a remote computer and should be closed by the ServiceDisconnectSCM
function.

35.4 Functions
Following you find the list of all functions of the Windows Service function module:

Function OS Description
ServiceConnectSCM Establish a connection to the service control manager on the specified computer

ServiceCreate Create a new service

ServiceDelete Delete an existing service

ServiceDisconnectSCM Close the connection to the Service Control Manager

ServiceExists Check whether a given service is installed

ServiceGetDescription Return the description for a service

ServiceGetError Get the error severity setting of an installed service

ServiceGetGroup Get the service group name for an installed service

ServiceGetName Get the display name of an installed service

ServiceGetPath Get the path of the executable for an installed service

ServiceGetStart Get the start-up condition of an installed service

ServiceGetStatus Get the current running status of an installed service

ServiceGetType Get the type of an installed service

ServiceGetUser Get the login user name for an installed service

ServiceList List the services which satisfy the supplied type and status values

ServiceSetError Set the error severity for an installed service

ServiceSetGroup Set the service group name for an installed service

ServiceSetName Set the display name of an installed service

ServiceSetPath Set the path of the executable for an installed service

ServiceSetStart Set the start-up condition of an installed service

ServiceSetStatus Set the current running status of an installed service

ServiceSetType Set the type of an installed service

ServiceSetUser Set the login user name for an installed service

Numara Software, Inc. and BMC Software, Inc. Confidential.


440 - BMC FootPrints Asset Core - Chilli Reference

Function OS Description
ServiceStart Start an installed service

ServiceStop Stop an installed service

ServiceConnectSCM
Establish a connection to the service control manager on the specified computer and open the default service
control manager database.
Syntax:
SCManagerHandle ServiceConnectSCM (String Machine, Int Access)
Machine is the name of the remote machine.
Access is the .
Returns:
A handle of type SCManagerHandle if the operation was successful or 0 if the function failed.

ServiceCreate
Create a new service.
Syntax:
Bool ServiceCreate (String Name, String Path, Int Type)
Bool ServiceCreate (SCManagerHandle Handle, String Name, String Path, Int Type)
Name is the internal name of the service to be created.
Path is the full path of the executable file for the service.
Type is the type of service to be created, such as device driver.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The type parameter must be one of the following predefined constants. For further explanation of each type of
service, consult the Microsoft Windows NT/2000/XP SDK documentation.

Name Description
SERVICE_KERNEL_DRIVER Kernel driver, usually a device driver.
SERVICE_FILE_SYSTEM_DRIVER Installable file system driver, for example, an NFS file redirector.
SERVICE_WIN32_OWN_PROCESS Specifies a service that runs in its own Win32 process.
SERVICE_WIN32_SHARE_PROCESS Specifies a service that shares a Win32 process with other services.

When created, the service is given the same display name as the supplied internal name. The display name can
then be changed using ServiceSetName.
Example:
This example creates a test service called "NTService" and changes its name to "NT Service Test".
proc main ()

string ServiceName, DisplayName, DisplayName2

ServiceName = "NTService"
ServiceCreate (ServiceName, "C:\\winnt\system32\\ntserv.exe",
SERVICE_WIN32_OWN_PROCESS)
DisplayName = "NT Service Test"
ServiceSetName (ServiceName, DisplayName)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 35 - Service Functions - 441

DisplayName2 = ServiceGetName (ServiceName)

if(DisplayName2 == DisplayName)
MessageBox ("Service", "Service Name is OK.\r\n", "OK")
endif

endproc

ServiceDelete
Delete an existing Windows NT/2000/XP service.
Syntax:
Bool ServiceDelete (String Name)
Bool ServiceDelete (SCManagerHandle Handle, String Name)
Name is the internal name of the service to be deleted.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
TRUE if the operation was successful, FALSE if the operation failed or if the named service could not be found. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The operation fails if the service to be removed is currently running, or the access rights do not allow its removal.
Example:
The following example checks if a service has been stopped before deleting it.
proc main ()

string ServiceName
bool iRes
ServiceName = "NTService"

if (ServiceExists (ServiceName))
if (ServiceGetStatus (ServiceName) != SERVICE_STOPPED)
iRes = ServiceSetStatus (ServiceName, SERVICE_STOP)

if (iRes == FALSE)
MessageBox ("Service", "Failed to stop a service.\r\n", "OK")
exit
endif

endif
ServiceDelete (ServiceName)
endif

endproc

ServiceDisconnectSCM
Close the connection to the Service Control Manager and free the supplied handle.
Syntax:
Bool ServiceDisconnectSCM (SCManagerHandle Handle)
Handle is the handle to the connection to the service control manager on the remote computer to be closed.
Returns:
TRUE if the function was successful, FALSE if the operation failed.
Comments:
After this function has been called the handle becomes invalid and thus can not be used with any longer with
other function, regardless if the operation executed with success or failed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


442 - BMC FootPrints Asset Core - Chilli Reference

ServiceExists
Check to see if a given service is installed.
Syntax:
Bool ServiceExists (String Name)
Bool ServiceExists (SCManagerHandle Handle, String Name)
Name is the internal name of the service to be checked.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Example:
The following example checks if a service exists and has been stopped before deleting it.
proc main ()

string ServiceName
bool iRes
ServiceName = "NTService"

if (ServiceExists (ServiceName))
if (ServiceGetStatus (ServiceName) != SERVICE_STOPPED)
iRes = ServiceSetStatus (ServiceName, SERVICE_STOP)

if (iRes == FALSE)
MessageBox ("Service", "Failed to stop a service.\r\n", "OK")
exit
endif

endif
ServiceDelete (ServiceName)
endif

endproc

ServiceGetDescription
Return the description for a service.
Syntax:
String ServiceGetDescription (String ServiceName)
String ServiceGetDescription (SCManagerHandle Handle, String ServiceName)
ServiceName is the internal name of the service to be checked.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
The description of the service if the operation succeeded, an empty string otherwise.
Example:
proc main ()
Print ("Service Description: " + ServiceGetDescription ("BCM Agent"))
endproc

ServiceGetError
Get the error severity setting of an installed service.
Syntax:
Int ServiceGetError (String Name)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 35 - Service Functions - 443

Int ServiceGetError (SCManagerHandle Handle, String Name)


Name is the internal name of the service to be checked.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
The function returns an integer from the following list of possible predefined values:

Name Description
SERVICE_ERROR_CRITICAL The start-up program logs the error, if possible. If the last-known-good configuration is
being started, the start-up operation fails. Otherwise, the system is restarted with the last-
known-good configuration.
SERVICE_ERROR_IGNORE The start-up (boot) program logs the error but continues the start-up operation.
SERVICE_ERROR_NORMAL The start-up program logs the error and puts up a message box pop-up but continues the
start-up operation.
SERVICE_ERROR_SEVERE The start-up program logs the error. If the last-known-good configuration is being started,
the start-up operation continues. Otherwise, the system is restarted with the last-known-
good configuration.

Comments:
The name supplied should be the service name and not the display name.
Example:
This example changes the error setting of a service from normal to severe.
proc main ()

string ServiceName
int type, error
ServiceName = "NTService"
type = ServiceGetStart (ServiceName)

if (type == SERVICE_WIN32_OWN_PROCESS)
ServiceSetType (ServiceName, SERVICE_WIN32_SHARE_PROCESS)
endif

error = ServiceGetError (ServiceName)


if (error == SERVICE_ERROR_NORMAL)
ServiceSetError (ServiceName, SERVICE_ERROR_SEVERE)
endif

endproc

ServiceGetGroup
Get the service group name for a service.
Syntax:
String ServiceGetGroup (String Name)
String ServiceGetGroup (SCManagerHandle Handle, String Name)
Name is the internal name of the service to be read.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
Returns a string that names the load ordering group of which this service is a member.
Comments:
The name supplied should be the service name and not the display name.

Numara Software, Inc. and BMC Software, Inc. Confidential.


444 - BMC FootPrints Asset Core - Chilli Reference

If the string is empty, the service does not belong to a group or an error occurred. The Windows Registry has a list
of load ordering groups at HKEY_LOCAL_MACHINE\System\
CurrentControlSet\Control\ServiceGroupOrder. The start-up program uses this list to load groups of services
in a specified order with respect to the other groups in the list. You can place a service in a group so that another
service can depend on the group.
Example:
This example gets the load ordering group of the SNMP service and assigns it to the service called "NT Service".
proc main ()

string ServiceName, group


int start

ServiceName = "NTService"
group = ServiceGetGroup ("SNMP")
ServiceSetGroup (ServiceName, group)
start = ServiceGetStart ("SNMP")

if (start == SERVICE_START_SYSTEM)
ServiceSetStart (ServiceName, start)
endif

endproc

ServiceGetName
Get the display name for a service.
This is the name that is displayed in the Control Panel Services applet.
Syntax:
String ServiceGetName (String Name)
String ServiceGetName (SCManagerHandle Handle, String Name)
Name is the internal name of the service to be read.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
Returns a string that contains the display name of the specified service. This is the name that is displayed in the
Control Panel Services applet. If an error occurs or the service does not exist, the returned string is empty.
Comments:
The name supplied should be the service name and not the display name.
Example:
This examples looks for the display name of the service called "NT Service Test".
proc main ()

string ServiceName, DisplayName, DisplayName2

ServiceName = "NTService"
ServiceCreate (ServiceName, "C:\\winnt\system32\\ntserv.exe",
SERVICE_WIN32_OWN_PROCESS)
DisplayName = "NT Service Test"
ServiceSetName (ServiceName, DisplayName)
DisplayName2 = ServiceGetName (ServiceName)

if(DisplayName2 == DisplayName)
MessageBox ("Service", "Service Name is OK.\r\n", "OK")
endif

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 35 - Service Functions - 445

ServiceGetPath
Get the path of the executable for an installed service.
Syntax:
String ServiceGetPath (String Name)
String ServiceGetPath (SCManagerHandle Handle, String Name)
Name is the internal name of the service to be read.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
Returns a string that is the full path of the binary executable for the service. If an error occurs or the service does
not exist, the returned string is empty.
Comments:
The name supplied should be the service name and not the display name.
Example:
The following example resets the path of a service.
proc main ()

string ServiceName, path


ServiceName = "NTService"
path = ServiceGetPath (ServiceName)

if (path != "C:\\winnt\system32\\ntserv.exe”)
ServiceSetPath (ServiceName, "C:\\winnt\system32\\ntserv.exe”)
endif

endproc

ServiceGetStart
Get the start-up condition of an installed service.
Syntax:
Int ServiceGetStart (String Name)
Int ServiceGetStart (SCManagerHandle Handle, String Name)
Name is the internal name of the service to be read.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
The function returns an integer from the following list of possible predefined values:

Name Description
SERVICE_START_AUTO Specifies a device driver or Win32 service started by the service control manager
automatically during system start-up.
SERVICE_START_BOOT Specifies a device driver started by the operating system loader. This value is valid only if
the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER.
SERVICE_START_DEMAND Specifies a device driver or Win32 service started by the service control manager when
using the control panel.
SERVICE_START_DISABLED Specifies a device driver or Win32 service that can no longer be started.
SERVICE_START_SYSTEM Specifies a device driver started at system start-up, after the boot drivers are loaded. This
value is valid only if the service type is SERVICE_KERNEL_DRIVER or
SERVICE_FILE_SYSTEM_DRIVER.

Comments:
The name supplied should be the service name and not the display name.

Numara Software, Inc. and BMC Software, Inc. Confidential.


446 - BMC FootPrints Asset Core - Chilli Reference

Example:
This example tests the startup condition of the service called "NTService".
proc main ()

string ServiceName
int type, error

ServiceName = "NTService"
type = ServiceGetStart (ServiceName)

if (type == SERVICE_START_DISABLED)
print("This service is dizabled\r\n")
else
print("This service is OK\r\n")
endif

enproc

ServiceGetStatus
Get the current running status of an installed service.
Syntax:
Int ServiceGetStatus (String Name)
Int ServiceGetStatus (SCManagerHandle Handle, String Name)
Name is the internal name of the service to be read.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
The function returns an integer from the following list of possible predefined values:

Name Description
SERVICE_CONTINUE_PENDING A service continue request is pending.
SERVICE_PAUSE_PENDING A service pause request is pending.
SERVICE_PAUSED The service is paused
SERVICE_RUNNING The service is running.
SERVICE_START_PENDING The service is starting.
SERVICE_STOP_PENDING The service is stopping.
SERVICE_STOPPED The service is not running.

Comments:
The name supplied should be the service name and not the display name.
Example:
This example checks if a service has been stopped and if not stops it.
proc main ()

string ServiceName
bool iRes
ServiceName = "NTService"

if (ServiceExists (ServiceName))
if (ServiceGetStatus (ServiceName) != SERVICE_STOPPED)
iRes = ServiceSetStatus (ServiceName, SERVICE_STOP)

if (iRes == FALSE)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 35 - Service Functions - 447

MessageBox ("Service", "Failed to stop a service.\r\n", "OK")


exit
endif

endif
ServiceDelete (ServiceName)
endif

endproc

ServiceGetType
Get the type of an installed service.
Syntax:
Int ServiceGetType (String Name)
Int ServiceGetType (SCManagerHandle Handle, String Name)
Name is the internal name of the service to be read.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
The function returns an integer from the following list of possible predefined values:

Name Description
SERVICE_KERNEL_DRIVER Kernel driver, usually a device driver.
SERVICE_FILE_SYSTEM_DRIVER Installable file system driver, for example, an NFS file redirector.
SERVICE_WIN32_OWN_PROCESS Specifies a service that runs in its own Win32 process.
SERVICE_WIN32_SHARE_PROCESS Specifies a service that shares a Win32 process with other services.

Comments:
The name supplied should be the service name and not the display name.

ServiceGetUser
Get the login user name for an installed service.
Syntax:
String ServiceGetUser (String Name)
String ServiceGetUser (SCManagerHandle Handle, String Name)
Name is the internal name of the service to be read.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
If the service type is SERVICE_WIN32_OWN_PROCESS, the account name is returned in the form of
DomainName\Username, which the service process is logged on as if it runs. If the service type is
SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER, the user name is the Windows driver object name
(that is, \FileSystem\Rdr or \Driver\Xns), which the input and output (I/O) system uses to load the device
driver. If an error occurs or the service does not exist, the returned string is empty.
Comments:
The name supplied should be the service name and not the display name.
Example:
This example sets the user of a service and then checks if this value has been correctly set.
proc main ()

string ServiceName, user, user2


ServiceName = "NTService"
user = "DomainName\Username"

Numara Software, Inc. and BMC Software, Inc. Confidential.


448 - BMC FootPrints Asset Core - Chilli Reference

ServiceSetUser (ServiceName, user)


user2 = ServiceGetUser (ServiceName)

if (user == user2)
MessageBox ("Service", "User Name is OK.\r\n", "OK")
endif

endproc

ServiceList
List the services which satisfy the supplied type and status values.
Syntax:
String[] ServiceList (Int ServiceType, Int Status)
String[] ServiceList (SCManagerHandle Handle, Int ServiceType, Int Status)
ServiceType defines the type fo the services to list.
Status defines the status of the services to list.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
A string array containing the list of service names if the operation was successful, or an empty array if the
function failed.
Comments:
The ServiceType value can be one or more (using OR) of the following:

Name Description
SERVICE_DRIVER Enumerates services of type SERVICE_KERNEL_DRIVER and SERVICE_FILE_SYSTEM_DRIVER.
SERVICE_WIN32 Enumerates services of type SERVICE_WIN32_OWN_PROCESS and SERVICE_WIN32_SHARE_PROCESS.

The Status value can be one of the following:

Name Description
SERVICE_ACTIVE Enumerates services that are in the following states:
SERVICE_START_PENDING, SERVICE_STOP_PENDING, SERVICE_RUNNING,
SERVICE_CONTINUE_PENDING, SERVICE_PAUSE_PENDING, and SERVICE_PAUSED.
SERVICE_INACTIVE Enumerates services that are in the SERVICE_STOPPED state.
SERVICE_STATE_ALL Combines the following states: SERVICE_ACTIVE and SERVICE_INACTIVE.

ServiceSetError
Set the error severity setting of an installed service.
Syntax:
Bool ServiceSetError (String Name, Int Severity)
Bool ServiceSetError (SCManagerHandle Handle, String Name, Int Severity)
Name is the internal name of the service to be modified.
Severity is the new error severity value for the service.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
TRUE if the operation was successful, FALSE if the operation failed or if the named service could not be found. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The severity value must be a predefined integer from the following list of possible values:

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 35 - Service Functions - 449

Name Description
SERVICE_ERROR_CRITICAL The start-up program logs the error, if possible. If the last-known-good configuration is
being started, the start-up operation fails. Otherwise, the system is restarted with the last-
known-good configuration.
SERVICE_ERROR_IGNORE The start-up (boot) program logs the error but continues the start-up operation.
SERVICE_ERROR_NORMAL The start-up program logs the error and puts up a message box pop-up but continues the
start-up operation.
SERVICE_ERROR_SEVERE The start-up program logs the error. If the last-known-good configuration is being started,
the start-up operation continues. Otherwise, the system is restarted with the last-known-
good configuration.

Example:
This example changes the error setting of a service from normal to severe.
proc main ()

string ServiceName
int type, error
ServiceName = "NTService"
type = ServiceGetStart (ServiceName)

if (type == SERVICE_WIN32_OWN_PROCESS)
ServiceSetType (ServiceName, SERVICE_WIN32_SHARE_PROCESS)
endif

error = ServiceGetError (ServiceName)


if (error == SERVICE_ERROR_NORMAL)
ServiceSetError (ServiceName, SERVICE_ERROR_SEVERE)
endif

endproc

ServiceSetGroup
Set the service group name for a service.
Syntax:
Bool ServiceSetGroup (String Name, String Group)
Bool ServiceSetGroup (SCManagerHandle Handle, String Name, String Group)
Name is the internal name of the service to be modified.
Group is the start-up group to apply to the service.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
TRUE if the operation was successful, FALSE if the operation failed or if the named service could not be found. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The Windows Registry has a list of load ordering groups at HKEY_LOCAL_MACHINE\System\
CurrentControlSet\Control\ServiceGroupOrder. The start-up program uses this list to load groups of services
in a specified order with respect to the other groups in the list. You can place a service in a group so that another
service can depend on the group.
Example:
This example gets the load ordering group of the SNMP service and assigns it to the service called "NT Service".
proc main ()

string ServiceName, group


int start

Numara Software, Inc. and BMC Software, Inc. Confidential.


450 - BMC FootPrints Asset Core - Chilli Reference

ServiceName = "NTService"
group = ServiceGetGroup ("SNMP")
ServiceSetGroup (ServiceName, group)
start = ServiceGetStart ("SNMP")

if (start == SERVICE_START_SYSTEM)
ServiceSetStart (ServiceName, start)
endif

endproc

ServiceSetName
Set the display name for a service.
This is the name that is displayed in the Control Panel Services applet.
Syntax:
Bool ServiceSetName (String Name, String DisplayName)
Bool ServiceSetName (SCManagerHandle Handle, String Name, String DisplayName)
Name is the internal name of the service to be renamed.
DisplayName is the display name to be given to the service.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
TRUE if the operation was successful, FALSE if the operation failed or if the named service could not be found. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.
Example:
This examples looks for the display name of the service called "NT Service Test".
proc main ()

string ServiceName, DisplayName, DisplayName2

ServiceName = "NTService"
ServiceCreate (ServiceName, "C:\\winnt\system32\\ntserv.exe",
SERVICE_WIN32_OWN_PROCESS)
DisplayName = "NT Service Test"
ServiceSetName (ServiceName, DisplayName)
DisplayName2 = ServiceGetName (ServiceName)

if(DisplayName2 == DisplayName)
MessageBox ("Service", "Service Name is OK.\r\n", "OK")
endif

endproc

ServiceSetPath
Set the path of the executable for an installed service.
Syntax:
Bool ServiceSetPath (String Name, String Path)
Bool ServiceSetPath (SCManagerHandle Handle, String Name, String Path)
Name is the internal name of the service to be modified.
Path is the new executable path for the service.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
TRUE if the operation was successful, FALSE if the operation failed or if the named service could not be found. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 35 - Service Functions - 451

Example:
The following example resets the path of a service.
proc main ()

string ServiceName, path


ServiceName = "NTService"
path = ServiceGetPath (ServiceName)

if (path != "C:\\winnt\system32\\ntserv.exe”)
ServiceSetPath (ServiceName, "C:\\winnt\system32\\ntserv.exe”)
endif

endproc

ServiceSetStart
Set the start-up condition of an installed service.
Syntax:
Bool ServiceSetStart (String Name, Int Start)
Bool ServiceSetStart (SCManagerHandle Handle, String Name, Int Start)
Name is the internal name of the service to be modified.
Start is the start-up condition to apply to the service.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
TRUE if the operation was successful, FALSE if the operation failed or if the named service could not be found. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The start value must be a predefined integer from the following list of possible values:

Name Description
SERVICE_START_AUTO Specifies a device driver or Win32 service started by the service control manager
automatically during system start-up.
SERVICE_START_BOOT Specifies a device driver started by the operating system loader. This value is valid only if
the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER.
SERVICE_START_DEMAND Specifies a device driver or Win32 service started by the service control manager when
using the control panel.
SERVICE_START_DISABLED Specifies a device driver or Win32 service that can no longer be started.
SERVICE_START_SYSTEM Specifies a device driver started at system start-up, after the boot drivers are loaded. This
value is valid only if the service type is SERVICE_KERNEL_DRIVER or
SERVICE_FILE_SYSTEM_DRIVER.

Example:
This examples assigns the same startup condition of the SNMP service to the service NTService.
proc main ()

string ServiceName, group


int start

ServiceName = "NTService"
group = ServiceGetGroup ("SNMP")
ServiceSetGroup (ServiceName, group)
start = ServiceGetStart ("SNMP")

if (start == SERVICE_START_SYSTEM)
ServiceSetStart (ServiceName, start)

Numara Software, Inc. and BMC Software, Inc. Confidential.


452 - BMC FootPrints Asset Core - Chilli Reference

endif

endproc

ServiceSetStatus
Set the current running status of an installed service.
Syntax:
Bool ServiceSetStatus (String Name, Int Status)
Bool ServiceSetStatus (SCManagerHandle Handle, String Name, Int Status)
Name is the internal name of the service to be modified.
Status is the running status to be applied to the service.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
TRUE if the operation was successful, FALSE if the operation failed or if the named service could not be found. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The status value must be a predefined integer from the following list of possible values:

Name Description
SERVICE_CONTINUE The service is taken out of pause or is started.
SERVICE_PAUSE The service is paused.
SERVICE_STOP The service is stopped.

Example:
The following example checks if a service has been stopped before deleting it.
proc main ()

string ServiceName
bool iRes
ServiceName = "NTService"

if (ServiceExists (ServiceName))
if (ServiceGetStatus (ServiceName) != SERVICE_STOPPED)
iRes = ServiceSetStatus (ServiceName, SERVICE_STOP)

if (iRes == FALSE)
MessageBox ("Service", "Failed to stop a service.\r\n", "OK")
exit
endif

endif
ServiceDelete (ServiceName)
endif

endproc

ServiceSetType
Set the type of an installed service.
Syntax:
Bool ServiceSetType (String Name, Int Type)
Bool ServiceSetType (SCManagerHandle Handle, String Name, Int Type)
Name is the internal name of the service to be modified.
Type is the service type setting to apply to the service.
Handle is the handle to the connection to the service control manager on the remote computer.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 35 - Service Functions - 453

Returns:
TRUE if the operation was successful, FALSE if the operation failed or if the named service could not be found. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The type value must be a predefined integer from the following list of possible values:

Name Description
SERVICE_KERNEL_DRIVER Kernel driver, usually a device driver.
SERVICE_FILE_SYSTEM_DRIVER Installable file system driver, for example, an NFS file redirector.
SERVICE_WIN32_OWN_PROCESS Specifies a service that runs in its own Win32 process.
SERVICE_WIN32_SHARE_PROCESS Specifies a service that shares a Win32 process with other services.

Example:
This example modifies the type setting of a service called NTService.
proc main ()

string ServiceName
int type, error
ServiceName = "NTService"
type = ServiceGetStart (ServiceName)

if (type == SERVICE_WIN32_OWN_PROCESS)
ServiceSetType (ServiceName, SERVICE_WIN32_SHARE_PROCESS)
endif

error = ServiceGetError (ServiceName)


if (error == SERVICE_ERROR_NORMAL)
ServiceSetError (ServiceName, SERVICE_ERROR_SEVERE)
endif

endproc

ServiceSetUser
Set the login user name for an installed service.
Syntax:
Bool ServiceSetUser (String Name, String User)
Bool ServiceSetUser (SCManagerHandle Handle, String Name, String User)
Name is the internal name of the service to be modified.
User is the user account name to be used when the service is running.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
TRUE if the operation was successful, FALSE if the operation failed or if the named service could not be found. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
If the service type is SERVICE_WIN32_OWN_PROCESS, the user name is the account name in the form of
DomainName\Username, which the service process is logged on as when it runs. If the account belongs to the built-
in domain, .\Username can be specified. Services of type SERVICE_WIN32_SHARE_PROCESS are not allowed to
specify an account other than LocalSystem
If the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER, the user name is the Windows
driver object name (that is, \FileSystem\Rdr or \Driver\Xns), which the input and output (I/O) system uses to
load the device driver. If an empty string is specified, the driver is run with a default object name created by the I/
O system, based on the service name.

Numara Software, Inc. and BMC Software, Inc. Confidential.


454 - BMC FootPrints Asset Core - Chilli Reference

Example:
This example sets the user of a service and then checks if this value has been correctly set.
proc main ()

string ServiceName, user, user2


ServiceName = "NTService"
user = "DomainName\Username"
ServiceSetUser (ServiceName, user)
user2 = ServiceGetUser (ServiceName)

if (user == user2)
MessageBox ("Service", "User Name is OK.\r\n", "OK")
endif

endproc

ServiceStart
Start a service.
Syntax:
Bool ServiceStart (String Name)
Bool ServiceStart (SCManagerHandle Handle, String Name)
Name is the internal name of the service to be started.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
TRUE if the operation was successful, FALSE if the operation failed or if the named service could not be found. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The service is only attempted to start if its current status is stopped or paused. This function is a simplification of
the ServiceSetStatus function.
Example:
The following example tries to start a service if it is not running.
proc main ()

string ServiceName
bool iRes
ServiceName = "NTService"

if (ServiceExists (ServiceName))
if (ServiceGetStatus (ServiceName) != SERVICE_RUNNING)
iRes = ServiceStart (ServiceName)

if (iRes == FALSE)
MessageBox ("Service", "Failed to start a service.\r\n", "OK")
exit
endif

endif
endif

endproc

ServiceStop
Stop a service.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 35 - Service Functions - 455

Syntax:
Bool ServiceStop (String Name)
Bool ServiceStop (SCManagerHandle Handle, String Name)
Name is the internal name of the service to be stopped.
Handle is the handle to the connection to the service control manager on the remote computer.
Returns:
TRUE if the operation was successful, FALSE if the operation failed or if the named service could not be found. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The service is only attempted to stop if its current status is started or paused. This function is a simplification of
the ServiceSetStatus function.
Example:
The following example checks if a service has been stopped before deleting it.
proc main ()

string ServiceName
bool iRes

ServiceName = "NTService"

if (ServiceExists (ServiceName))

if (ServiceGetStatus (ServiceName) != SERVICE_STOPPED)


iRes = ServiceStop (ServiceName)

if (iRes == FALSE)
MessageBox ("Service", "Failed to stop a service.\r\n", "OK")
exit
endif

endif
ServiceDelete (ServiceName)

endif

endproc

35.5 Example
This example illstrates the service functions.
proc ServicesFunctions ()
string ServiceName, DisplayName, DisplayName2, user, user2
string group, path
int start, type, error
bool iRes
ServiceName = "NTService"

if (ServiceExists (ServiceName))
if (ServiceGetStatus (ServiceName) != SERVICE_STOPPED)
iRes = ServiceSetStatus (ServiceName, SERVICE_STOP)

if (iRes == FALSE)
MessageBox ("Service", "Failed to stop a service.\r\n", "OK")

Numara Software, Inc. and BMC Software, Inc. Confidential.


456 - BMC FootPrints Asset Core - Chilli Reference

exit
endif

endif
ServiceDelete (ServiceName)
endif

ServiceCreate (ServiceName, "C:\\winnt\system32\\ntserv.exe",


SERVICE_WIN32_OWN_PROCESS)
DisplayName = "NT Service Test"
ServiceSetName (ServiceName, DisplayName)
DisplayName2 = ServiceGetName (ServiceName)

if(DisplayName2 == DisplayName)
MessageBox ("Service", "Service Name is OK.\r\n", "OK")
endif

user = "DomainName\Username"
ServiceSetUser (ServiceName, user)
user2 = ServiceGetUser (ServiceName)

if (user == user2)
MessageBox ("Service", "User Name is OK.\r\n", "OK")
endif

group = ServiceGetGroup ("SNMP")


ServiceSetGroup (ServiceName, group)
start = ServiceGetStart ("SNMP")

if (start == SERVICE_START_SYSTEM)
ServicesetStart (ServiceName, start)
endif

type = ServiceGetStart (ServiceName)


if (type == SERVICE_WIN32_OWN_PROCESS)
ServiceSetType (ServiceName, SERVICE_WIN32_SHARE_PROCESS)
endif

error = ServiceGetError (ServiceName)


if (error == SERVICE_ERROR_NORMAL)
ServiceSetError (ServiceName, SERVICE_ERROR_SEVERE)
endif

path = ServiceGetPath (ServiceName)


if (path != "C:\\winnt\system32\\ntserv.exe”)
ServiceSetPath (ServiceName, "C:\\winnt\system32\\ntserv.exe”)
endif

endproc

proc main ()
ServicesFunctions ()
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Shortcut Functions

This chapter explains all Windows shortcut functions of the Chilli Language. All functions of this module are
included in the shortcut.chx file. These functions are not applicable to the UNIX environment.
They are only supported on the Windows 32-bit versions, on the other versions (Windows 3.1/3.11) and in the
UNIX environment they compiles but return a FUNCNOTSUPP (function not supported) error to indicate failure.

36.1 Introduction
A shortcut creates a quick access to a specified action by passing Windows-based messages and parameters. The
functions of this group allow you access to all the same functions as provided by the Windows Shortcut Designer
to create shortcuts, modify existing ones or just retrieve information about them. The .lnk extension of any
mandatory path parameters of these functions is optional.

36.2 Predefined Constants


Following is the list of all predefined constants of the Windows Shortcut function group of the Chilli language:

Name Type Description


WIN_HIDDEN Integer The window is created hidden from view. Although the window exists it is not visible.
WIN_NORMAL Integer The window is created visible and is sized and positioned using default values determined by the
operating system.
WIN_MINIMISED Integer The window is created in an iconized state.
WIN_MAXIMISED Integer The window is created maximized, filling the entire viewing area of the screen.

36.3 Functions
Following you find the list of all functions of the Shortcut function module:

Function OS Description
ShortcutCreate Create a new shortcut

ShortcutGetArgs Get the arguments for a shortcut

ShortcutGetDescr Get the descriptive text for a shortcut

ShortcutGetDir Get the default working directory for a shortcut

ShortcutGetHotkey Get the hot key code for a shortcut

ShortcutGetIconFile Get the icon file for a shortcut

ShortcutGetIconIndex Get the index of the icon image used for a shortcut

Numara Software, Inc. and BMC Software, Inc. Confidential.


458 - BMC FootPrints Asset Core - Chilli Reference

Function OS Description
ShortcutGetShow Get the show status for a shortcut

ShortcutGetTarget Get the target file for a shortcut

ShortcutSetArgs Set the arguments for a shortcut

ShortcutSetDescr Set the descriptive text for a shortcut

ShortcutSetDir Set the default working directory for a shortcut

ShortcutSetHotkey Set the hot key code for a shortcut

ShortcutSetIcon Set the icon file and index for a shortcut

ShortcutSetShow Set the show status for a shortcut

ShortcutSetTarget Set the target file for a shortcut

ShortcutCreate
Create a new shortcut.
Syntax:
Bool ShortcutCreate (String ShortcutFile, String TargetFile)
ShortcutFile is the relative or full path of the shortcut file to be created.
TargetFile is the relative or full path of the file that the shortcut points to.
Returns:
TRUE if the create operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
The created file has a .lnk extension and can be copied or deleted as a normal file.
Example:
This example creates a shortcut to the target executable 'text.exe'.
proc main ()
string Name, Target
Name = GetWinDir() + "\\Profiles\\All Users\\StartMenu\\Programs\\NewFolder\\Test2.lnk"
Target = "D:\\Test\\Test.exe"
if (FileFind (Name) == FALSE)
PathCreate (PathGetDrive (Name) + “:” + PathGetDir (Name))
ShortcutCreate (Name, Target)
endif

endproc

ShortcutGetArgs
Get the command line arguments for a shortcut.
Syntax:
String ShortcutGetArgs (String ShortcutFile)
ShortcutFile is the relative or full path of the shortcut file to be read.
Returns:
A string containing the command line arguments if successful, or an empty string if the function fails or the
specified shortcut file cannot be found.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 36 - Shortcut Functions - 459

Comments:
The command line arguments are supplied to the target file when the user double-clicks the shortcut to execute
the target.
Example:
This example reads information of a shortcut.
proc main ()

string Name, Target1, Args1, WorkDir1


int index
Name = GetWinDir() + "\\Profiles\\All Users\\Start Menu\\Programs\\NewFolder\\Test2.lnk"
Target1 = ShortcutGetTarget (Name)
Args1 = ShortcutGetArgs (Name)
WorkDir1 = ShortcutGetDir (Name)
index = ShortcutGetIconIndex (Name)

endproc

ShortcutGetDescr
Get the descriptive text for a shortcut.
Syntax:
String ShortcutGetDescr (String ShortcutFile)
ShortcutFile is the relative or full path of the shortcut file to be read.
Returns:
The descriptive text for a shortcut if successful, an empty string if the specified file cannot be found or an error
occurs.
Comments:
The descriptive text is the text which appears in the properties dialog for a shortcut. It is used for identification
purposes only and does not affect the operation of the shortcut itself.
Example:
This example reads information of a shortcut.
proc main ()

string Name, IconFile1, Description1, IconFile1


int show, hotkey
Name = GetWinDir() + "\\Profiles\\All Users\\Start Menu\\Programs\\NewFolder\\Test2.lnk"
IconFile1 = ShortcutGetIconFile (Name)
show = ShortcutGetShow (Name)
hotkey = ShortcutGetHotkey (Name)
Description1 = ShortcutGetDescr (Name)

endproc

ShortcutGetDir
Get the default working directory for a shortcut.
Syntax:
String ShortcutGetDir (String ShortcutFile)
ShortcutFile is the relative or full path of the shortcut file to be read.
Returns:
The working directory of the shortcut if successful, an empty string if the specified file cannot be found or an
error occurs.

Numara Software, Inc. and BMC Software, Inc. Confidential.


460 - BMC FootPrints Asset Core - Chilli Reference

Comments:
The working directory path is the current working directory set by the shell when the program represented by the
shortcut is started.
Example:
This example reads information of a shortcut.
proc main ()

string Name, Target1, Args1, WorkDir1


int index
Name = GetWinDir() + "\\Profiles\\All Users\\Start Menu\\Programs\\NewFolder\\Test2.lnk"
Target1 = ShortcutGetTarget (Name)
Args1 = ShortcutGetArgs (Name)
WorkDir1 = ShortcutGetDir (Name)
index = ShortcutGetIconIndex (Name)

endproc

ShortcutGetHotkey
Get the hotkey code for a shortcut.
Syntax:
Int ShortcutGetHotkey (String ShortcutFile)
ShortcutFile is the relative or full path of the shortcut file to be read.
Returns:
The hotkey value for the icon if successful, 0 if the function fails or the shortcut file cannot be found.
Comments:
The Hotkey code is a code representing a set of keystrokes which, if pressed, ishave in the same way as a user
double-clicking the shortcut file icon. The result is always to start the program represented by the shortcut. To
find the shortcut codes, refer to the Windows shell help and individual shortcuts for examples.
Example:
This example reads information of a shortcut.
proc main ()

string Name, IconFile1, Description1, IconFile1


int show, hotkey
Name = GetWinDir() + "\\Profiles\\All Users\\Start Menu\\Programs\\NewFolder\\Test2.lnk"
IconFile1 = ShortcutGetIconFile (Name)
show = ShortcutGetShow (Name)
hotkey = ShortcutGetHotkey (Name)
Description1 = ShortcutGetDescr (Name)

endproc

ShortcutGetIconFile
Get the icon file for a shortcut.
Syntax:
String ShortcutGetIconFile (String ShortcutFile)
ShortcutFile is the relative or full path of the shortcut file to be read.
Returns:
If successful, the function returns the path to the file used to store the icon bitmap for the shortcut. If the shortcut
file cannot be found or an error occurs, an empty string is returned. An empty string is also returned if the icon
file is the shortcut target file, that is, the default executable file.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 36 - Shortcut Functions - 461

Example:
This example reads information of a shortcut.
proc main ()

string Name, IconFile1, Description1, IconFile1


int show, hotkey
Name = GetWinDir() + "\\Profiles\\All Users\\Start Menu\\Programs\\NewFolder\\Test2.lnk"
IconFile1 = ShortcutGetIconFile (Name)
show = ShortcutGetShow (Name)
hotkey = ShortcutGetHotkey (Name)
Description1 = ShortcutGetDescr (Name)

endproc

ShortcutGetIconIndex
Get the icon index for a shortcut.
Syntax:
Int ShortcutGetIconIndex (String ShortcutFile)
ShortcutFile is the relative or full path of the shortcut file to be read.
Returns:
If successful, the function returns the index of the icon used for the shortcut. If the shortcut file cannot be found
or an error occurs, 0 is returned.
Comments:
The bitmap used to display the icon for a shortcut is obtained from the file identified by the shortcuts IconFile.
In a file with more than a bitmap inside, IconIndex identifies the bitmap to be used.
Example:
This example reads information of a shortcut.
proc main ()

string Name, Target1, Args1, WorkDir1


int index
Name = GetWinDir() + "\\Profiles\\All Users\\Start Menu\\Programs\\NewFolder\\Test2.lnk"
Target1 = ShortcutGetTarget (Name)
Args1 = ShortcutGetArgs (Name)
WorkDir1 = ShortcutGetDir (Name)
index = ShortcutGetIconIndex (Name)

endproc

ShortcutGetShow
Get the show state for a shortcut.
Syntax:
Int ShortcutGetShow (String ShortcutFile)
ShortcutFile is the relative or full path of the shortcut file to be read.
Returns:
If successful, the function returns the integer representing the show state for the target program of the shortcut. If
the shortcut file cannot be found or an error occurs, 0 is returned.
Comments:
The show state specifies the state of the target program main window when it is started through the shortcut. The
values specify whether the window is normal, iconized or maximized when started.

Numara Software, Inc. and BMC Software, Inc. Confidential.


462 - BMC FootPrints Asset Core - Chilli Reference

Example:
This example reads information of a shortcut.
proc main ()

string Name, IconFile1, Description1, IconFile1


int show, hotkey
Name = GetWinDir() + "\\Profiles\\All Users\\Start Menu\\Programs\\NewFolder\\Test2.lnk"
IconFile1 = ShortcutGetIconFile (Name)
show = ShortcutGetShow (Name)
hotkey = ShortcutGetHotkey (Name)
Description1 = ShortcutGetDescr (Name)

endproc

ShortcutGetTarget
Get the path of the target file of a shortcut.
Syntax:
String ShortcutGetTarget (String ShortcutFile)
ShortcutFile is the relative or full path of the shortcut file to be read.
Returns:
If successful, the function returns the path of the target of the shortcut. If the shortcut file cannot be found or an
error occurs, an empty string is returned.
Comments:
The target of a shortcut is in effect the file or directory being represented by the shortcut. If the target is an
executable program, double-clicking the shortcut icon executes the program.
Example:
This example reads information of a shortcut.
proc main ()

string Name, Target1, Args1, WorkDir1


int index
Name = GetWinDir() + "\\Profiles\\All Users\\Start Menu\\Programs\\NewFolder\\Test2.lnk"
Target1 = ShortcutGetTarget (Name)
Args1 = ShortcutGetArgs (Name)
WorkDir1 = ShortcutGetDir (Name)
index = ShortcutGetIconIndex (Name)

endproc

ShortcutSetArgs
Set the argument string for the target file of a shortcut.
Syntax:
Bool ShortcutSetArgs (String ShortcutFile, String Args)
ShortcutFile is the relative or full path of the shortcut file to be modified.
Args is argument list which is supplied to the target when it is started.
Returns:
TRUE if the function is successful, FALSE if it fails or cannot find the shortcut file.
Comments:
The command line arguments are supplied to the target file when the user double-clicks the shortcut to execute
the target.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 36 - Shortcut Functions - 463

Example:
The following example sets the target and arguments of a shortcut.
proc main ()

string Name, Target, Args


Name = GetWinDir() + "\\Profiles\\All Users\\Start Menu\\Programs\\NewFolder\\Test2.lnk"
Target = "D:\\Test\\Test.exe"
Args = ""
ShortcutSetTarget (Name, Target)
ShortcutSetArgs (Name, Args)

endproc

ShortcutSetDescr
Set the descriptive text for a shortcut.
Syntax:
Bool ShortcutSetDescr (String ShortcutFile, String Description)
ShortcutFile is the relative or full path of the shortcut file to be modified.
Description is the free format text which is to be displayed in the properties dialog for the shortcut.
Returns:
TRUE if the function is successful, FALSE if it fails or cannot find the shortcut file.
Comments:
The descriptive text is text which appears in the properties dialog for a shortcut. It is used for identification
purposes only and does not affect the operation of the shortcut itself.
Example:
The following example sets the hotkey and description of a shortcut.
proc main ()

string Name, Description


Name = GetWinDir() + "\\Profiles\\All Users\\Start Menu\\Programs\\NewFolder\\Test2.lnk"
Description = "description"
ShortcutSetHotkey (Name, 0)
ShortcutSetDescr (Name, Description)

endproc

ShortcutSetDir
Set the working directory of the target file of a shortcut.
Syntax:
Bool ShortcutSetDir (String ShortcutFile, String Directory)
ShortcutFile is the relative or full path of the shortcut file to be modified.
Directory is the relative or full path of the working directory used when the target is started.
Returns:
TRUE if the function is successful, FALSE if it fails or cannot find the shortcut file.
Comments:
The working directory path is the current working directory set by the shell when the program represented by the
shortcut is started.
Example:
The following example sets the directory, icon and show status of a shortcut.
proc main ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


464 - BMC FootPrints Asset Core - Chilli Reference

string Name, WorkDir, IconFile


Name = GetWinDir() + "\\Profiles\\All Users\\Start Menu\\Programs\\NewFolder\\Test2.lnk"
WorkDir = "D:\\Test"
IconFile = "D:\\Test\\Test.exe"
ShortcutSetDir (Name, WorkDir)
ShortcutSetIcon (Name, IconFile, 1)
ShortcutSetShow (Name, 1)

endproc

ShortcutSetHotkey
Set the hotkey code for a shortcut.
Syntax:
Bool ShortcutSetHotkey (String ShortcutFile, Int Hotkey)
ShortcutFile is the relative or full path of the shortcut file to be modified.
Hotkey is the integer hotkey code to assign to the shortcut.
Returns:
TRUE if the function is successful, FALSE if it fails or cannot find the shortcut file.
Comments:
The Hotkey code is a code representing a set of keystrokes which if pressed ishave in the same way as a user
double-clicking the shortcut file icon. The result is always to start the program represented by the shortcut. To
find the shortcut codes, refer to the Windows 95/98 shell help and individual shortcuts for examples.
Example:
The following example sets the hotkey and description of a shortcut.
proc main ()

string Name, Description


Name = GetWinDir() + "\\Profiles\\All Users\\Start Menu\\Programs\\NewFolder\\Test2.lnk"
Description = "description"
ShortcutSetHotkey (Name, 0)
ShortcutSetDescr (Name, Description)

endproc

ShortcutSetIcon
Set the icon file and index for a shortcut.
Syntax:
Bool ShortcutSetIcon (String ShortcutFile, String IconFile, Int IconIndex)
ShortcutFile is the relative or full path of the shortcut file to be modified.
IconFile is the relative or full path of the icon to be used for the shortcut.
IconIndex is the index of the icon in the icon file to be used for the shortcut.
Returns:
TRUE if the function is successful, FALSE if it fails or cannot find the shortcut file.
Comments:
The bitmap used to display the icon for a shortcut is obtained from the file identified by the
ShortcutGetIconFile. In a file with more than a bitmap inside, ShortcutGetIconIndex identifies the bitmap to
be used. If ShortcutGetIconFile returned an empty string, ShortcutSetIconFile automatically takes the
executable file as its IconFile argument.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 36 - Shortcut Functions - 465

Example:
The following example sets the directory, icon and show status of a shortcut.
proc main ()

string Name, WorkDir, IconFile


Name = GetWinDir() + "\\Profiles\\All Users\\Start Menu\\Programs\\NewFolder\\Test2.lnk"
WorkDir = "D:\\Test"
IconFile = "D:\\Test\\Test.exe"
ShortcutSetDir (Name, WorkDir)
ShortcutSetIcon (Name, IconFile, 1)
ShortcutSetShow (Name, 1)

endproc

ShortcutSetShow
Set the Windows show state for a shortcut.
Syntax:
Bool ShortcutSetShow (String ShortcutFile, Int ShowState)
ShortcutFile is the relative or full path of the shortcut file to be modified.
ShowState is the integer show state to assign to the shortcut.
Returns:
TRUE if the function is successful, FALSE if it fails or cannot find the shortcut file.
Comments:
The ShowState specifies the state of the target program main window when it is started through the shortcut. The
values specify whether the window is normal, iconized or maximized when started. The ShowState parameter
must be one of the following predefined constants with the described results:

Name Type Description


WIN_HIDDEN Integer The window is created hidden from view. Although the window exists it is not visible.
WIN_NORMAL Integer The window is created visible and is sized and positioned using default values determined by
the operating system.
WIN_MINIMISED Integer The window is created in an iconized state.
WIN_MAXIMISED Integer The window is created maximized, filling the entire viewing area of the screen.

Example:
The following example sets the directory, icon and show status of a shortcut.
proc main ()

string Name, WorkDir, IconFile


Name = GetWinDir() + "\\Profiles\\All Users\\Start Menu\\Programs\\NewFolder\\Test2.lnk"
WorkDir = "D:\\Test"
IconFile = "D:\\Test\\Test.exe"
ShortcutSetDir (Name, WorkDir)
ShortcutSetIcon (Name, IconFile, 1)
ShortcutSetShow (Name, 1)

endproc

ShortcutSetTarget
Set the path of the target file of a shortcut.
Syntax:
Bool ShortcutSetTarget (String ShortcutFile, String TargetPath)
ShortcutFile is the relative or full path of the shortcut file to be modified.

Numara Software, Inc. and BMC Software, Inc. Confidential.


466 - BMC FootPrints Asset Core - Chilli Reference

TargetPath is the relative or full path of the target to be represented by the shortcut.
Returns:
TRUE if the function is successful, FALSE if it fails or cannot find the shortcut file or the target file does not exist.
Comments:
The target of a shortcut is in effect the file or directory being represented by the shortcut. If the target is an
executable program, double-clicking the shortcut icon executes the program. The program is supplied the
argument string set by ShortcutSetArgs.
Example:
The following example sets the target and arguments of a shortcut.
proc main ()

string Name, Target, Args


Name = GetWinDir() + "\\Profiles\\All Users\\Start Menu\\Programs\\NewFolder\\Test2.lnk"
Target = "D:\\Test\\Test.exe"
Args = ""
ShortcutSetTarget (Name, Target)
ShortcutSetArgs (Name, Args)

endproc

36.4 Example
The following code sample illustrates the shortcut functions.
proc main ()
string Name, Target, WorkDir, IconFile, Args, Description
string Target1, WorkDir1, Description1, IconFile1
int index, show, hotkey
Name = GetWinDir() + "\\Profiles\\All Users\\Start
Menu\\Programs\\NewFolder\\Test2.lnk"
Target = "D:\\Test\\Test.exe"
WorkDir = "D:\\Test"
IconFile = "D:\\Test\\Test.exe""
Args = ""
Description = "description"
if (FileFind (Name) == 0)
PathCreate (PathGetDrive (Name) + ':' + PathGetDir (Name))
ShortcutCreate (Name, Target)
endif
ShortcutSetTarget (Name, Target)
ShortcutSetArgs (Name, Args)
ShortcutSetDir (Name, WorkDir)
ShortcutSetIcon (Name, IconFile, 1)
ShortcutSetShow (Name, 1)
ShortcutSetHotkey (Name, 0)
ShortcutSetDescr (Name, Description)
Target1 = ShortcutGetTarget (Name)
Args1 = ShortcutGetArgs (Name)
WorkDir1 = ShortcutGetDir (Name)
index = ShortcutGetIconIndex (Name)
IconFile1 = ShortcutGetIconFile (Name)
show = ShortcutGetShow (Name)
hotkey = ShortcutGetHotkey (Name)
Description1 = ShortcutGetDescr (Name)
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


SMB Functions

This chapter explains all SMB functions of the built in Chilli functions. All functions of this module are included
in the smb.chx file for Windows or smb.so file for UNIX and Linux.

37.1 Introduction
The SMB protocol (also called Lan Manager) is typically used by Microsoft Windows machines for file transfer
and redirected drive operations. This function group should only be used with a system that supports the SMB
protocol. It allows you to access a remote Windows machine through the SMB protocol to read and write the
remote directory system and files.

37.2 Predefined Constants


Following you find the complete list of all predefined constants of the SMB functions group of the Chilli script
language:

Constant Type Description


RPC_LSA_ACCOUNT Integer Query class to be used with function RpcLsaQueryInfo in order to gather account
information through the Local Security Authority (LSA) pipe.
RPC_LSA_DOMAIN Integer Query class to be used with function RpcLsaQueryInfo in order to gather domain
information through the Local Security Authority (LSA) pipe.
RPC_PIPE_ATSVC Integer Constant to be supplied to the RpcBindInterface function for opening the ATSVC
pipe.
RPC_PIPE_BROWSER Integer Constant to be supplied to the RpcBindInterface function for opening the
BROWSER pipe.
RPC_PIPE_EVENTLOG Integer Constant to be supplied to the RpcBindInterface function for opening the
EVENTLOG pipe.
RPC_PIPE_LSARPC Integer Constant to be supplied to the RpcBindInterface function for opening the LSA
pipe.
RPC_PIPE_NETLOGON Integer Constant to be supplied to the RpcBindInterface function for opening the
NETLOGON pipe.
RPC_PIPE_SAMR Integer Constant to be supplied to the RpcBindInterface function for opening the SAMR
pipe.
RPC_PIPE_SPOOLSS Integer Constant to be supplied to the RpcBindInterface function for opening the
SPOOLSS pipe.
RPC_PIPE_SRVSVC Integer Constant to be supplied to the RpcBindInterface function for opening the SRVSVC
pipe.
RPC_PIPE_SVCCTL Integer Constant to be supplied to the RpcBindInterface function for opening the SVCCTL
pipe.
RPC_PIPE_WINREG Integer Constant to be supplied to the RpcBindInterface function for opening the WINREG
pipe.

Numara Software, Inc. and BMC Software, Inc. Confidential.


468 - BMC FootPrints Asset Core - Chilli Reference

Constant Type Description


RPC_PIPE_WKSSVC Integer Constant to be supplied to the RpcBindInterface function for opening the
WKSSVC pipe.
RPC_SERVICESTATE_CONTINUE Integer Constant returned in the State slot of a RpcServiceInfo structure when gathering
PENDING information concerning a Windows Service via RpcSvcCtlEnumServices. Actually,
the queried service is resuming.
RPC_SERVICESTATE_PAUSED Integer Constant returned in the State slot of a RpcServiceInfo structure when gathering
information concerning a Windows Service via RpcSvcCtlEnumServices. Actually,
the queried service is paused.
RPC_SERVICESTATE_PÄUSEPEN Integer Constant returned in the State slot of a RpcServiceInfo structure when gathering
DING information concerning a Windows Service via RpcSvcCtlEnumServices. Actually,
the queried service is pausing.
RPC_SERVICESTATE_RUNNING Integer Constant returned in the State slot of a RpcServiceInfo structure when gathering
information concerning a Windows Service via RpcSvcCtlEnumServices. Actually,
the queried service is running.
RPC_SERVICESTATE_STARTPEN Integer Constant returned in the State slot of a RpcServiceInfo structure when gathering
DING information concerning a Windows Service via RpcSvcCtlEnumServices. Actually,
the queried service is starting.
RPC_SERVICESTATE_STOPPED Integer Constant returned in the State slot of a RpcServiceInfo structure when gathering
information concerning a Windows Service via RpcSvcCtlEnumServices. Actually,
the queried service is stopped.
RPC_SERVICESTATE_STOPPEND Integer Constant returned in the State slot of a RpcServiceInfo structure when gathering
ING information concerning a Windows Service via RpcSvcCtlEnumServices. Actually,
the queried service is stopping.
RPC_SHARETYPE_DEVICE Integer Constant returned in the ShareType slot of a RpcShareInfo structure when
gathering information concerning a Windows Share via RpcSrvSvcEnumNetShare.
Actually, the share is a device.
RPC_SHARETYPE_DISKTREE Integer Constant returned in the ShareType slot of a RpcShareInfo structure when
gathering information concerning a Windows Share via RpcSrvSvcEnumNetShare.
Actually, the share is a directory.
RPC_SHARETYPE_HIDDEN Integer Constant returned in the ShareType slot of a RpcShareInfo structure when
gathering information concerning a Windows Share via RpcSrvSvcEnumNetShare.
Actually, the share is hidden.
RPC_SHARETYPE_IPC Integer Constant returned in the ShareType slot of a RpcShareInfo structure when
gathering information concerning a Windows Share via RpcSrvSvcEnumNetShare.
Actually, the share is the inter process communication one.
RPC_SHARETYPE_PRINTQ Integer Constant returned in the ShareType slot of a RpcShareInfo structure when
gathering information concerning a Windows Share via RpcSrvSvcEnumNetShare.
Actually, the share is a printer.
RPC_SRVSVC_ISAPPLE Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a Apple host.
RPC_SRVSVC_ISBACKUPBROWS Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
ER gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a backup browser server.
RPC_SRVSVC_ISBACKUPCONTR Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
OLER gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a backup domain controler.
RPC_SRVSVC_ISDIALINSERVER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a Dialin server.
RPC_SRVSVC_ISDOMAINCONTR Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
OLER gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a domain controler.
RPC_SRVSVC_ISDOMAINMASTE Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
RBROWSER gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a domain master browser server.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 469

Constant Type Description


RPC_SRVSVC_ISDOMAINMEMBE Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
R gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a domain member.
RPC_SRVSVC_ISMASTERBROW Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
SER gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a master browser server.
RPC_SRVSVC_ISNOVELLSERVER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a Novell server.
RPC_SRVSVC_ISNTSERVER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a Windows NT server.
RPC_SRVSVC_ISNTWORKSTATI Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
ON gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a NT workstation.
RPC_SRVSVC_ISOSF Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a OSF host.
RPC_SRVSVC_ISPOTENTIALBRO Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
WSER gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a server that can run the browser service.
RPC_SRVSVC_ISPRINTQUEUESE Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
RVER gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a print queue server.
RPC_SRVSVC_ISSERVER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a server.
RPC_SRVSVC_ISSQLSERVER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a server running SQL server.
RPC_SRVSVC_ISTIMESOURCE Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a time source.
RPC_SRVSVC_ISVMS Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a VMS host.
RPC_SRVSVC_ISWFW Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a Windows for Windows host.
RPC_SRVSVC_ISWIN9X Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a Windows 9x.
RPC_SRVSVC_ISWORKSTATION Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a workstation.
RPC_SRVSVC_ISXENIXSERVER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a Xenix server.
RPC_WINREG_HKCR Integer Constant to be supplied to the RpcWinregOpenHKey function when opening the
HKEY_CLASSES_ROOT registry.
RPC_WINREG_HKCU Integer Constant to be supplied to the RpcWinregOpenHKey function when opening the
HKEY_CURRENT_USER registry.
RPC_WINREG_HKLM Integer Constant to be supplied to the RpcWinregOpenHKey function when opening the
HKEY_LOCAL_MACHINE registry.
RPC_WINREG_HKPD Integer Constant to be supplied to the RpcWinregOpenHKey function when opening the
HKEY_PERFORMANCE_DATA registry.

Numara Software, Inc. and BMC Software, Inc. Confidential.


470 - BMC FootPrints Asset Core - Chilli Reference

Constant Type Description


RPC_WINREG_HKU Integer Constant to be supplied to the RpcWinregOpenHKey function when opening the
HKEY_USERS registry.
RPC_WINREG_REGVAL_BINARY Integer Constant returned in the ValueType slot of a RpcWinregValueInfo structure when
gathering information concerning a Windows registry key value via
RpcWinregQueryValue. Actually, the key value is a binary sequence.
RPC_WINREG_REGVAL_DWORD Integer Constant returned in the ValueType slot of a RpcWinregValueInfo structure when
gathering information concerning a Windows registry key value via
RpcWinregQueryValue. Actually, the key value is a 4 bytes integer.
RPC_WINREG_REGVAL_EXPAND Integer Constant returned in the ValueType slot of a RpcWinregValueInfo structure when
_SZ gathering information concerning a Windows registry key value via
RpcWinregQueryValue. Actually, the key value is an expand string.
RPC_WINREG_REGVAL_SZ Integer Constant returned in the ValueType slot of a RpcWinregValueInfo structure when
gathering information concerning a Windows registry key value via
RpcWinregQueryValue. Actually, the key value is a string.

37.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli SMB function group has Predefined Handle Data Types.

37.3.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.

NetPacketHandle
The NetPacketHandle data type is a reference to the handle of an SMB connection.
The function SmbCreate returns a value of this object type that other functions expect as their first argument.
Any open connection and thus the value of this object type should always be closed by the SmbDelete function.

SmbHandle
The SmbHandle data type is a reference to the handle of an SMB connection.
The function SmbCreate returns a value of this object type that other functions expect as their first argument.
Any open connection and thus the value of this object type should always be closed by the SmbDelete function.

37.3.2 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated.
Following you find a list of all predefined data types of type structure:

Data Type Description


RapFileInfo Structure returned as a result for the RapQueryPath function. This actually gather information about a
file path using the Remote API (RAP) through SMB transactions.
RapShareInfo Structure returned as a result for the RapEnumNetShare function. This actually gather information
about a share using the Remote API (RAP) through SMB transactions.
RpcDomainInfo01 Structure returned as a result for the RpcSamQueryDomain01 function. This actually gather information
about a domain.
RpcPolicyHandle A generic Windows Remote Procedure Call (RPC) handle returned by several functions which
represents an opened resource. This handle must be supplied each time an operation should be
executed for the acquired resource and then, closed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 471

Data Type Description


RpcServerInfo Structure returned as a result for the RpcSrvSvcQueryInfo function. This actually gather information
about a server.
RpcServiceInfo Structure returned as a result for the RpcSvcCtlEnumServices function. This actually gather
information about a service.
RpcShareInfo Structure returned as a result for the RpcSrvSvcEnumNetShare function. This actually gather
information about a share.
RpcSidInfo Structure returned as a result for the RpcLsaQueryInfo function. This actually gather information about
a domain or an account.
RpcWinregKeyInfo Structure returned as a result for the RpcWinregQueryKey and RpcWinregEnumKey functions. This
actually gather information about a registry key.
RpcWinregValueInfo Structure returned as a result for the RpcWinregQueryValue and RpcWinregEnumValue functions. This
actually gather information about a registry value.
SmbFileInfo Structure returned as a result for several RPC functions. This represents a kind of handle for any
opened file or RPC interface.
SmbSessionInfo Structure returned as a result for the SmbSessionGetInfo function. This actually returns information
about the current SMB session.
SmbTreeInfo Structure returned as a result for the SmbTreeConnect function. This represents a kind of handle for
any opened share (tree).

RapFileInfo
The RapFileInfo structure is returned as a result for the RapQueryPath function. This structure gathers
information about a file path using the Remote API (RAP) through SMB transactions.
Elements:

Elements Element Type Description


Attributes Long The file attributes.
Size Long The file size.

RapShareInfo
The RapShareInfo structure is returned as a result for the RapEnumNetShare function. It gathers information
about a share using the Remote API (RAP) through SMB transactions.
Elements:

Elements Element Type Description


ShareName String The name of the share.
ShareType Long The type of the share.
ShareInfo String Complementary information for the share.

RpcDomainInfo01
The RpcDomainInfo01 structure is returned as a result for the RpcSamQueryDomain01 function. It gathers
information about a domain.
Elements:

Elements Element Type Description


PasswordMinLength Long The domain password policy value concerning the minimal password
length.
PasswordHistory Long The domain password policy value concerning the password history.

Numara Software, Inc. and BMC Software, Inc. Confidential.


472 - BMC FootPrints Asset Core - Chilli Reference

RpcPolicyHandle
The RpcPolicyHandle structure is a generic Windows Remote Procedure Call (RPC) handle returned by several
functions and it represents an opened resource. This handle must be supplied each time an operation should be
executed for the acquired resource and then be closed again.
Elements:

Elements Element Type Description


Use2 Bool
Ptr Long The first internal data type building the RPC handle.
UUID String The second internal data type building the RPC handle.
AccessMask Long The second internal data type building the RPC handle.
PolicyHandle String The second internal data type building the RPC handle.

RpcServerInfo
The RpcServerInfo structure is returned as a result for the RpcSrvSvcQueryInfo function. It gathers
information about a server.
Elements:

Elements Element Type Description


PlatformId Long An identifier for the platform.
MajorVersion Long The major version for the operating system.
MinorVersion Long The minor version for the operating system.
ServerType Long A bit field slot holding several information concerning the server.

RpcServiceInfo
The RpcServiceInfo structure is returned as a result for the RpcSvcCtlEnumServices function. It gathers
information about a service.
Elements:

Elements Element Type Description


Name String The service name.
DisplayName String The service display name.
State Long The service state.

RpcShareInfo
The RpcShareInfo structure is returned as a result for the RpcSrvSvcEnumNetShare function. It gathers
information about a share.
Elements:

Elements Element Type Description


ShareName String The name of the share.
ShareType Long The type of the share.
ShareInfo String Complementary information for the share.

RpcSidInfo
The RpcSidInfo structure is returned as a result for the RpcLsaQueryInfo function. It gathers information
about a domain or an account.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 473

Elements:

Elements Element Type Description


Name String The domain or account name.
Sid String The domain or account Security Identifier (SID).
Type String The domain or account type (User, Domain Group, Domain, Alias, Well
Known Group, Deleted Account, Invalid Account, Unknown).
TranslatedName String The domain or account translated name.

RpcWinregKeyInfo
The RpcWinregKeyInfo structure is returned as a result for the RpcWinregQueryKey and RpcWinregEnumKey
functions. It gathers information about a registry key.
Elements:

Elements Element Type Description


Name String The name of the registry key.
KeyCount Long The total children registry key count.
ValueCount Long The total children registry value count.

RpcWinregValueInfo
The RpcWinregValueInfo structure is returned as a result for the RpcWinregQueryValue and
RpcWinregEnumValue functions. This structure gathers information about a registry value.

Elements:

Elements Element Type Description


Name String The name of the registry value.
Value String The actual registry value.
ValueType Long The type of the registry value.
ValueSize Long The size of the registry value.

SmbSessionInfo
The SmbSessionInfo structure is returned as a result for the SmbSessionGetInfo function. It returns
information about the current SMB session. Each structure slot gives low level information because we are facing
the row SMB protocol details.
Elements:

Elements Element Type Description


NegociatedDialects Long The list of dialects that had been negociated during the
SmbSessionNegotiate execution.
Flags Long The low level flags for extracted from the SMB header.
Flags2 Long The low level flags2 for extracted from the SMB header.
Capabilities Long The server capabilities.
SecurityMode Long The server security mode details.
Pid Long The low level Process Id (PID) extracted from the SMB header.
Mid Long The low level Multiplex Id (MID) extracted from the SMB header.
Uid Long The low level User Id (UID) extracted from the SMB header.
DomainName String The returned domain name.
ServerName String The returned server name.
NativeOs String The returned native operating system.
NativeLanMan String The returned native LAN Manager.

Numara Software, Inc. and BMC Software, Inc. Confidential.


474 - BMC FootPrints Asset Core - Chilli Reference

SmbTreeInfo
The SmbTreeInfo structure is returned as a result for the SmbTreeConnect function. This represents a handle
for any opened share (tree).
Elements:

Elements Element Type Description


Tid Long The identifier for the opened share.

37.4 Functions
Following you find the list of all functions of the SMB module:

Function OS Description
KrbSetConfigPath Specify the path to use for Kerberos configuration file

NbtSessionDisconnect Disconnect a NetBIOS session

NbtSessionRequest Request a NetBIOS session

RapEnumDirAndFiles Enumerate the files specified by given pattern using Remote API (RAP) through
SMB transactions
RapEnumNetShare Enumerate the network share using Remote API (RAP) through SMB
transactions
RapQueryPath Query information for the supplied file path using Remote API (RAP) through
SMB transactions
RpcBindInterface Open required pipe and bind to specified interface

RpcCloseInterface Close the interface for which a bind request has been done

RpcLsaClose Close the previously opened policy handle

RpcLsaLookupSid Query Sid and returns type and translated name

RpcLsaOpenPolicy Open a policy handle with maximum allowed security

RpcLsaQueryInfo Query Domain or Account information through the Lsa pipe

RpcSamClose Close the previously opened policy handle

RpcSamConnect Remote access to the SAM pipe through the RPC interface

RpcSamOpenDomain Open a policy handle with maximum allowed security

RpcSamQueryDomain01 Open a policy handle for the supplied Domain SID with maximum allowed
security
RpcSrvSvcEnumNetShare Enumerate the network share using the SRVSVC interface

RpcSrvSvcQueryInfo Query server information using the SRVSVC interface

RpcSvcCtlClose Close the previously opened policy handle

RpcSvcCtlEnumServices Enumerate the installed services

RpcSvcCtlOpenPolicy Open a policy handle with maximum allowed security

RpcWinregClose Close the previously opened policy handle

RpcWinregEnumKey Enum a key at the supplied index.

RpcWinregEnumValue Enum a value at the supplied index

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 475

Function OS Description
RpcWinregOpenHKey Remote access to the registry through the WINREG interface

RpcWinregOpenKey Open a key that must be located under an already opened HK

RpcWinregQueryKey Query a key that must be located under an already opened HK

RpcWinregQueryValue Query a key value

SmbCreate Create a new SMB client

SmbCreateRaw Create a new SMB client with/without NetBIOS layer

SmbDelete Delete an SMB client

SmbFileGet Get a remote file to be copied locally

SmbFileGetDescription Get a remote file description and set a boolean to confirm its existence

SmbFileGetVersion Get a remote file version and set a boolean to confirm his existence

SmbGetGssApiSupportKerberos Find if the target supports Kerberos 5

SmbGetGssApiSupportNtlmSsp Find if the target supports NTLM SSP

SmbSessionClose Exit the SMB session

SmbSessionGetInfo Get information about the session

SmbSessionLogOff Logoff after session has been settled

SmbSessionNegotiate Negotiate the SMB session with server

SmbSessionOpen Do all the required operations from TCP connection to SMB logon

SmbSessionSetup Logon after session has been negotiated

SmbSetDebugContext Set the debug context object

SmbTreeConnect Connect to a share

SmbTreeConnectWithServerName Connect to a share and give an indication about the server name

SmbTreeDisconnect Disconnect from actually connected tree

TcpConnect Perform connection at TCP level

TcpDisconnect Perform disconnection at TCP level

KrbSetConfigPath
Specify the path to use for Kerberos configuration file.
Syntax:
Bool KrbSetConfigPath (SmbHandle Smb, String ConfigPath)
Smb is the handle to the SMB client connection.
ConfigPath is the the path to the Kerberos configuration file.
Returns:
TRUE to indicate that the configuration is set and the file exists, FALSE otherwise.
Comments:
SmbLib creates this file base on information gathered by SmbSessionNegotiate and the user specified by
SmbSessionSetup.

Numara Software, Inc. and BMC Software, Inc. Confidential.


476 - BMC FootPrints Asset Core - Chilli Reference

NbtSessionDisconnect
Disconnect a NetBIOS session.
Syntax:
Bool NbtSessionDisconnect (SmbHandle Smb)
Smb is the handle to the SMB client connection.
Returns:
TRUE to indicate success, FALSE in case of failure.
Comments:
In fact, a NetBIOS session does not require the client to disconnect. Anyway, this function helps keeping the
client internal state accurate.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!TcpConnect (hSmb, "192.168.193.2", 139))


SmbDelete (hSmb)
return 1
endif

if (!NbtSessionRequest (hSmb, "*SMBSERVER"))


TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 1
endif

NbtSessionDisconnect (hSmb)
TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 0

endproc

NbtSessionRequest
Request a NetBIOS session.
Syntax:
Bool NbtSessionRequest (SmbHandle Smb, String HostName)
Smb is the handle to the SMB client connection.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 477

HostName is the ‘called’ NetBIOS name of the peer target to connect.


Returns:
TRUE to indicate success, FALSE in case of failure.
Comments:
This is required before sending any SMB packet to the server because our client is mainly NetBIOS based (often
port 139).
The HostName can be entered as its long or short network name, for example, Scotty or Scotty.enterprise.com or
as its IP address in dotted notation.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!TcpConnect (hSmb, "192.168.193.2", 139))


SmbDelete (hSmb)
return 1
endif

if (!NbtSessionRequest (hSmb, "*SMBSERVER"))


TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 1
endif

NbtSessionDisconnect (hSmb)
TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 0

endproc

RapEnumDirAndFiles
Enumerate the files specified by given pattern using Remote API (RAP) through SMB transactions.
Syntax:
Bool RapEnumDirAndFiles (SmbHandle Smb, SmbTreeInfo Tree, String Pattern, String FileList[],
String DirList[])
Smb is the handle to the SMB client connection.
Tree is the handle to the connected tree that must have been previously acquired through SmbTreeConnect.
Pattern is the pattern the files and directories need to match.

Numara Software, Inc. and BMC Software, Inc. Confidential.


478 - BMC FootPrints Asset Core - Chilli Reference

FileList[] is the list of files that matches the pattern.


DirList[] is the list of directories that matches the pattern.
Returns:
TRUE if the operation succeeded FALSE otherwise. The list of files and folders matching pattern.
Comments:
The specifications for the pattern syntax to use can be found in CIFS-TR-1p00_FINAL.pdf in SmbLib under
section 3.5 concerning wildcards.

RapEnumNetShare
Enumerate the network share using Remote API (RAP) through SMB transactions.
Syntax:
Bool RapEnumNetShare (SmbHandle Smb, SmbTreeInfo Tree, RapShareInfo Shares[])
Smb is the handle to the SMB client connection.
Tree is the handle to the connected tree that must have been previously acquired through SmbTreeConnect.
Shares is the vector of returned shares information.
Returns:
TRUE if the operation succeeded FALSE otherwise. The list of enumerated shares.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "C$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

RapShareInfo vecRapShareInfo[]

if (RapEnumNetShare (hSmb, hTree, vecRapShareInfo))


int iCpt

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 479

for (iCpt=1; iCpt<=ArrayGetSize (vecRapShareInfo); iCpt+=1)


Print (LogFile, "Share: " + vecRapShareInfo[iCpt].ShareName + "\r\n")
endfor
endif

SmbTreeDisconnect (hSmb, hTree)


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RapQueryPath
Query information for the supplied file path using Remote API (RAP) through SMB transactions.
Syntax:
Bool RapQueryPath (SmbHandle Smb, SmbTreeInfo Tree, String Path, RapFileInfo File)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected tree that must have been previously acquired through SmbTreeConnect.
Path is the path to the required information.
File is the returned file information.
Returns:
TRUE to indicate success, FALSE in case of failure. The file information.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "C$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


480 - BMC FootPrints Asset Core - Chilli Reference

RapFileInfo hFileInfo

if (RapQueryPath (hSmb, hTree, '\WINDOWS\system32\gdi32.dll', hFileInfo))


Print (LogFile, "Attributes: " + hFileInfo.Attributes + "\r\n")
endif

SmbTreeDisconnect (hSmb, hTree)


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcBindInterface
Open required pipe and bind to specified interface.
Syntax:
Bool RpcBindInterface (SmbHandle Smb, SmbTreeInfo Tree, Int Iface, SmbFileInfo[] File)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
Iface is the identifier for the RPC interface to bind.
File is the returned structure including the Fid of opened pipe.
Returns:
True if the operation succeeded, false otherwise. A structure including the Fid of opened pipe, 0 otherwise.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 481

endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_WINREG, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcCloseInterface
Close the interface for which a bind request has been done.
Syntax:
Bool RpcCloseInterface (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface that must have been previously acquired through
RpcBindInterface.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

Numara Software, Inc. and BMC Software, Inc. Confidential.


482 - BMC FootPrints Asset Core - Chilli Reference

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_WINREG, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcLsaClose
Remote access to the LSA pipe through the RPC interface. Close the previously opened policy handle.
Syntax:
Bool RpcLsaClose (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcPolicyHandle Policy)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_LSARPC in this case) that must have been previously
acquired through RpcBindInterface.
Policy is the handle to the LSA opened policy that must have been previously acquired through
RpcLsaOpenPolicy.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 483

endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_LSARPC, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hLsaHandle

if (RpcLsaOpenPolicy (hSmb, hTree, hFileInfo, hLsaHandle))


RpcLsaClose (hSmb, hTree, hFileInfo, hLsaHandle)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcLsaLookupSid
Query Sid and returns type and translated name.
Syntax:
Bool RpcLsaLookupSid (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcPolicyHandle
Policy, RpcSidInfo Sid, Int SubAuth)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_LSARPC in this case) that must have been previously
acquired through RpcBindInterface.
Policy is the handle to the LSA opened policy that must have been previously acquired through
RpcLsaOpenPolicy.
Sid is a security identifier object (SID) to be queried.
SubAuth is an integer value that completes the SID definition.

Numara Software, Inc. and BMC Software, Inc. Confidential.


484 - BMC FootPrints Asset Core - Chilli Reference

Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_LSARPC, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hLsaHandle
RpcSidInfo sidAccount
sidAccount.Sid = 'S-1-5-21-3749479926-2838610240-4085093052'

if (RpcLsaOpenPolicy (hSmb, hTree, hFileInfo, hLsaHandle))


int iCpt
int iUserCpt
iUserCpt = 1

for (iCpt=500; iCpt<=510; iCpt+=1)


if (RpcLsaLookupSid (hSmb, hTree, hFileInfo, hLsaHandle, sidAccount, iCpt))
if (sidAccount.Type == "User")
Print (LogFile, "Name[" + MakeStr (iUserCpt) + "] " + sidAccount.TranslatedName + "\r\n")
Print (LogFile, "SID[" + MakeStr (iUserCpt) + "] " + sidAccount.Sid+ "\r\n")

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 485

iUserCpt += 1
endif
endif
endfor
RpcLsaClose (hSmb, hTree, hFileInfo, hLsaHandle)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcLsaOpenPolicy
Remote access to the LSA pipe through the RPC interface. Open a policy handle with maximum allowed security.
The received policy handle has to be supplied for the next calls.
Syntax:
Bool RpcLsaOpenPolicy (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcPolicyHandle
Policy)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_LSARPC in this case) that must have been previously
acquired through RpcBindInterface.
Policy is the returned handle to the LSA opened policy.
Returns:
The policy handle.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

Numara Software, Inc. and BMC Software, Inc. Confidential.


486 - BMC FootPrints Asset Core - Chilli Reference

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_LSARPC, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hLsaHandle

if (RpcLsaOpenPolicy (hSmb, hTree, hFileInfo, hLsaHandle))


RpcLsaClose (hSmb, hTree, hFileInfo, hLsaHandle)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcLsaQueryInfo
Query Domain or Account information through the Lsa pipe.
Syntax:
Bool RpcLsaQueryInfo (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcPolicyHandle
Policy, Int QueryClass, RpcSidInfo Sid)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_LSARPC in this case) that must have been previously
acquired through RpcBindInterface.
Policy is the handle to the LSA opened policy that must have been previously acquired through
RpcLsaOpenPolicy.
QueryClass is the type of query (RPC_LSA_DOMAIN or RPC_LSA_ACCOUNT).
Sid is the handle to the returned Sid details.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 487

#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_LSARPC, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hLsaHandle
RpcSidInfo sidDomain

if (RpcLsaOpenPolicy (hSmb, hTree, hFileInfo, hLsaHandle))


if (RpcLsaQueryInfo (hSmb, hTree, hFileInfo, hLsaHandle, RPC_LSA_DOMAIN, sidDomain))
Print (LogFile, "Domain Name: " + sidDomain.Name + "\r\n");
Print (LogFile, "Domain SID: " + sidDomain.Sid + "\r\n");
endif
RpcLsaClose (hSmb, hTree, hFileInfo, hLsaHandle)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcSamClose
Remote access to the SAM pipe through the RPC interface. Close the previously opened policy handle.

Numara Software, Inc. and BMC Software, Inc. Confidential.


488 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
Bool RpcSamClose (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcPolicyHandle Policy)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_SAMR in this case) that must have been previously
acquired through RpcBindInterface.
Policy is the handle to the SAM opened policy that must have been previously acquired through
RpcSamConnect or RpcSamOpenDomain.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_SAMR, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hPolicyHandle

if (RpcSamConnect (hSmb, hTree, hFileInfo, hPolicyHandle))

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 489

RpcSamClose (hSmb, hTree, hFileInfo, hPolicyHandle)


endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcSamConnect
Remote access to the SAM pipe through the RPC interface. Open a policy handle with maximum allowed security.
The received policy handle has to be supplied for the next calls.
Syntax:
Bool RpcSamConnect (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcPolicyHandle
Policy)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_SAMR in this case) that must have been previously
acquired through RpcBindInterface.
Policy is the returned handle to the SAM opened policy.
Returns:
The policy handle.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)

Numara Software, Inc. and BMC Software, Inc. Confidential.


490 - BMC FootPrints Asset Core - Chilli Reference

return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_SAMR, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hPolicyHandle

if (RpcSamConnect (hSmb, hTree, hFileInfo, hPolicyHandle))


RpcSamClose (hSmb, hTree, hFileInfo, hPolicyHandle)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcSamOpenDomain
Remote access to the SAM pipe through the RPC interface. Open a policy handle for the supplied Domain SID
with maximum allowed security. The received policy handle has to be supplied for the next calls.
Syntax:
Bool RpcSamOpenDomain (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcPolicyHandle
Policy, RpcSIDInfo Sid, RpcPolicyHandle DomainPolicy)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_SAMR in this case) that must have been previously
acquired through RpcBindInterface.
Policy is the handle to the SAM opened policy that must have been previously acquired through
RpcSamConnect.
Sid is a security identifier object (SID) to be queried.
DomainPolicy is the returned handle to the SAM opened domain policy.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 491

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_SAMR, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hPolicyHandle, hPolicyHandle2


RpcSidInfo sidDomain
RpcDomainInfo01 hDomainInfo01

sidDomain.Sid = 'S-1-5-21-3749479926-2838610240-4085093052'

if (RpcSamConnect (hSmb, hTree, hFileInfo, hPolicyHandle))


if (RpcSamOpenDomain (hSmb, hTree, hFileInfo, hPolicyHandle, sidDomain, hPolicyHandle2))
if (RpcSamQueryDomain01 (hSmb, hTree, hFileInfo, hPolicyHandle2, hDomainInfo01))
Print (LogFile, "Min password length: " + MakeStr (hDomainInfo01.PasswordMinLength) + "\r\n")
Print (LogFile, "Password history: " + MakeStr (hDomainInfo01.PasswordHistory) + "\r\n")
endif
RpcSamClose (hSmb, hTree, hFileInfo, hPolicyHandle2)
endif
RpcSamClose (hSmb, hTree, hFileInfo, hPolicyHandle)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


492 - BMC FootPrints Asset Core - Chilli Reference

RpcSamQueryDomain01
Remote access to the SAM pipe through the RPC interface. Query a Domain (information level 1).
Syntax:
Bool RpcSamQueryDomain01 (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcPolicyHandle
DomainPolicy, RpcDomainInfo01 Domain)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_SAMR in this case) that must have been previously
acquired through RpcBindInterface.
DomainPolicy is the handle to the SAM opened policy that must have been previously acquired through
RpcSamOpenDomain.
Domain is the handle to the returned domain details.
Returns:
The policy handle.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_SAMR, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 493

endif

RpcPolicyHandle hPolicyHandle, hPolicyHandle2


RpcSidInfo sidDomain
RpcDomainInfo01 hDomainInfo01

sidDomain.Sid = 'S-1-5-21-3749479926-2838610240-4085093052'

if (RpcSamConnect (hSmb, hTree, hFileInfo, hPolicyHandle))


if (RpcSamOpenDomain (hSmb, hTree, hFileInfo, hPolicyHandle, sidDomain, hPolicyHandle2))
if (RpcSamQueryDomain01 (hSmb, hTree, hFileInfo, hPolicyHandle2, hDomainInfo01))
Print (LogFile, "Min password length: " + MakeStr (hDomainInfo01.PasswordMinLength) + "\r\n")
Print (LogFile, "Password history: " + MakeStr (hDomainInfo01.PasswordHistory) + "\r\n")
endif
RpcSamClose (hSmb, hTree, hFileInfo, hPolicyHandle2)
endif
RpcSamClose (hSmb, hTree, hFileInfo, hPolicyHandle)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcSrvSvcEnumNetShare
Enumerate the network share using the SRVSVC interface.
Syntax:
Bool RpcSrvSvcEnumNetShare (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcShareInfo
Shares[])
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_SRVSVC in this case) that must have been previously
acquired through RpcBindInterface.
Shares is the vector of returned shares information.
Returns:
The list of enumerated shares.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


494 - BMC FootPrints Asset Core - Chilli Reference

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_SRVSVC, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcShareInfo vecRpcShareInfo[]

if (RpcSrvSvcEnumNetShare (hSmb, hTree, hFileInfo, vecRpcShareInfo))


int iCpt
for (iCpt=1; iCpt<=ArrayGetSize (vecRpcShareInfo); iCpt+=1)
Print (LogFile, "Share Name: " + vecRpcShareInfo[iCpt].ShareName + "\r\n")
endfor
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcSrvSvcQueryInfo
Query server information using the SRVSVC interface.
Syntax:
Bool RpcSrvSvcQueryInfo (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcServerInfo
Server)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_SRVSVC in this case) that must have been previously
acquired through RpcBindInterface.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 495

Server is the returned server information.


Returns:
The server details.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_SRVSVC, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcServerInfo hServerInfo

if (RpcSrvSvcQueryInfo (hSmb, hTree, hFileInfo, hServerInfo))


Print (LogFile, "OS Version " + MakeStr (hServerInfo.MajorVersion) + "." + MakeStr
(hServerInfo.MinorVersion) + "\r\n")
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

Numara Software, Inc. and BMC Software, Inc. Confidential.


496 - BMC FootPrints Asset Core - Chilli Reference

endproc

RpcSvcCtlClose
Remote access to the SVCCTL pipe through the RPC interface. Close the previously opened policy handle.
Syntax:
Bool RpcSvcCtlClose (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcPolicyHandle
Policy)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_SVCCTL in this case) that must have been previously
acquired through RpcBindInterface.
Policy is the handle to the SVCCTL opened policy that must have been previously acquired through
RpcSvcCtlOpenPolicy.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_SVCCTL, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 497

SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hPolicyHandle

if (RpcSvcCtlOpenPolicy (hSmb, hTree, hFileInfo, hPolicyHandle))


RpcSvcCtlClose (hSmb, hTree, hFileInfo, hPolicyHandle)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcSvcCtlEnumServices
Remote access to the SVCCTL pipe through the RPC interface. Enumerate the installed services.
Syntax:
Bool RpcSvcCtlEnumServices (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File,
RpcPolicyHandle Policy, RpcServiceInfo Services[])
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_SVCCTL in this case) that must have been previously
acquired through RpcBindInterface.
Policy is the handle to the SVCCTL opened policy that must have been previously acquired through
RpcSvcCtlOpenPolicy.
Services is the vector of returned services information.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)

Numara Software, Inc. and BMC Software, Inc. Confidential.


498 - BMC FootPrints Asset Core - Chilli Reference

return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_SVCCTL, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hPolicyHandle
RpcServiceInfo vecRpcServiceInfo[]

if (RpcSvcCtlOpenPolicy (hSmb, hTree, hFileInfo, hPolicyHandle))


if (RpcSvcCtlEnumServices (hSmb, hTree, hFileInfo, hPolicyHandle, vecRpcServiceInfo))
int iCpt
for (iCpt=1; iCpt<=ArrayGetSize (vecRpcServiceInfo); iCpt+=1)
Print (LogFile, "Service Name: " + vecRpcServiceInfo[iCpt].Name + "\r\n")
endfor
endif
RpcSvcCtlClose (hSmb, hTree, hFileInfo, hPolicyHandle)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcSvcCtlOpenPolicy
Remote access to the SVCCTL pipe through the RPC interface. Open a policy handle with maximum allowed
security. The received policy handle has to be supplied for the next calls.
Bool RpcSvcCtlOpenPolicy (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcPolicyHandle
Policy)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_SVCCTL in this case) that must have been previously
acquired through RpcBindInterface.
Policy is the returned handle to the SVCCTL opened policy.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 499

Returns:
The policy handle.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_SVCCTL, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hPolicyHandle

if (RpcSvcCtlOpenPolicy (hSmb, hTree, hFileInfo, hPolicyHandle))


RpcSvcCtlClose (hSmb, hTree, hFileInfo, hPolicyHandle)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


500 - BMC FootPrints Asset Core - Chilli Reference

RpcWinregClose
Remote access to the registry through the WINREG interface. Close the previously opened policy handle.
Syntax:
Bool RpcWinregClose (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcPolicyHandle
Policy)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_WINREG in this case) that must have been previously
acquired through RpcBindInterface.
Policy is the handle to the WINREG opened policy that must have been previously acquired through
RpcWinregOpenHKey or RpcWinregOpenKey.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_WINREG, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 501

RpcPolicyHandle hHK, hK

if (RpcWinregOpenHKey (hSmb, hTree, hFileInfo, RPC_WINREG_HKLM, hHK))


if (RpcWinregOpenKey (hSmb, hTree, hFileInfo, hHK, 'SOFTWARE\Microsoft\Windows\CurrentVersion', hK))
RpcWinregClose (hSmb, hTree, hFileInfo, hK)
endif
RpcWinregClose (hSmb, hTree, hFileInfo, hHK)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcWinregEnumKey
Remote access to the registry through the WINREG interface. Enum a key at the supplied index. The key must be
located under an already opened HK.
Syntax:
Bool RpcWinregEnumKey (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcPolicyHandle
Policy, Long Index, RpcWinregKeyInfo Key)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_WINREG in this case) that must have been previously
acquired through RpcBindInterface.
Policy is the handle to the WINREG opened policy that must have been previously acquired through
RpcWinregOpenHKey or RpcWinregOpenKey.
Index is the zero based index of the key to be queried.
Key is the returned key details.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


502 - BMC FootPrints Asset Core - Chilli Reference

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_WINREG, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hHK, hK
RpcWinregKeyInfo hKeyInfo, hKeyInfo2
RpcWinregValueInfo hValueInfo, hValueInfo2

if (RpcWinregOpenHKey (hSmb, hTree, hFileInfo, RPC_WINREG_HKLM, hHK))


if (RpcWinregOpenKey (hSmb, hTree, hFileInfo, hHK, 'SOFTWARE\Microsoft\Windows\CurrentVersion', hK))
if (RpcWinregQueryKey (hSmb, hTree, hFileInfo, hK, hKeyInfo))
int iCpt
for (iCpt=0; iCpt<hKeyInfo.KeyCount; iCpt+=1)
if (RpcWinregEnumKey (hSmb, hTree, hFileInfo, hK, iCpt, hKeyInfo2)
Print (LogFile, "Key[" + MakeStr (iCpt) + "] " + hKeyInfo2.Name + "\r\n")
endif
endfor

for (iCpt=0; iCpt<hKeyInfo.ValueCount; iCpt+=1)


if (RpcWinregEnumValue (hSmb, hTree, hFileInfo, hK, iCpt, hValueInfo)
if (RpcWinregQueryValue (hSmb, hTree, hFileInfo, hK, hValueInfo.Name, hValueInfo2))
Print (LogFile, "Value[" + hValueInfo2.Name + "] " + hValueInfo2.Value + "\r\n")
endif
endif
endfor
endif
RpcWinregClose (hSmb, hTree, hFileInfo, hK)
endif
RpcWinregClose (hSmb, hTree, hFileInfo, hHK)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 503

endproc

RpcWinregEnumValue
Remote access to the registry through the WINREG interface. Enum a value at the supplied index. The key must
be located under an already opened HK.
Syntax:
Bool RpcWinregEnumValue (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcPolicyHandle
Policy, Long Index, RpcWinregValueInfo Value)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_WINREG in this case) that must have been previously
acquired through RpcBindInterface.
Policy is the handle to the WINREG opened policy that must have been previously acquired through
RpcWinregOpenHKey or RpcWinregOpenKey.
Index is the zero based index of the value to be queried.
Value is the returned value details.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_WINREG, hFileInfo))

Numara Software, Inc. and BMC Software, Inc. Confidential.


504 - BMC FootPrints Asset Core - Chilli Reference

SmbTreeDisconnect (hSmb, hTree)


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hHK, hK
RpcWinregKeyInfo hKeyInfo, hKeyInfo2
RpcWinregValueInfo hValueInfo, hValueInfo2

if (RpcWinregOpenHKey (hSmb, hTree, hFileInfo, RPC_WINREG_HKLM, hHK))


if (RpcWinregOpenKey (hSmb, hTree, hFileInfo, hHK, 'SOFTWARE\Microsoft\Windows\CurrentVersion', hK))
if (RpcWinregQueryKey (hSmb, hTree, hFileInfo, hK, hKeyInfo))
int iCpt
for (iCpt=0; iCpt<hKeyInfo.KeyCount; iCpt+=1)
if (RpcWinregEnumKey (hSmb, hTree, hFileInfo, hK, iCpt, hKeyInfo2)
Print (LogFile, "Key[" + MakeStr (iCpt) + "] " + hKeyInfo2.Name + "\r\n")
endif
endfor

for (iCpt=0; iCpt<hKeyInfo.ValueCount; iCpt+=1)


if (RpcWinregEnumValue (hSmb, hTree, hFileInfo, hK, iCpt, hValueInfo)
if (RpcWinregQueryValue (hSmb, hTree, hFileInfo, hK, hValueInfo.Name, hValueInfo2))
Print (LogFile, "Value[" + hValueInfo2.Name + "] " + hValueInfo2.Value + "\r\n")
endif
endif
endfor
endif
RpcWinregClose (hSmb, hTree, hFileInfo, hK)
endif
RpcWinregClose (hSmb, hTree, hFileInfo, hHK)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcWinregOpenHKey
Remote access to the registry through the WINREG interface. Open one of the available HK. The received policy
handle has to be supplied for the next calls.
Syntax:
Bool RpcWinregOpenHKey (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, Int HK,
RpcPolicyHandle HKeyPolicy)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_WINREG in this case) that must have been previously
acquired through RpcBindInterface.
HK is the registry root key identifier (RPC_WINREG_HKCR, RPC_WINREG_HKCU, RPC_WINREG_HKLM,
RPC_WINREG_HKPD or RPC_WINREG_HKU)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 505

HKeyPolicy is the returned handle to the WINREG opened policy.


Returns:
The policy handle.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_WINREG, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hHK, hK

if (RpcWinregOpenHKey (hSmb, hTree, hFileInfo, RPC_WINREG_HKLM, hHK))


if (RpcWinregOpenKey (hSmb, hTree, hFileInfo, hHK, 'SOFTWARE\Microsoft\Windows\CurrentVersion', hK))
RpcWinregClose (hSmb, hTree, hFileInfo, hK)
endif
RpcWinregClose (hSmb, hTree, hFileInfo, hHK)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)

Numara Software, Inc. and BMC Software, Inc. Confidential.


506 - BMC FootPrints Asset Core - Chilli Reference

SmbDelete (hSmb)
return 0

endproc

RpcWinregOpenKey
Remote access to the registry through the WINREG interface. Open a key that must be located under an already
opened HK.
Syntax:
Bool RpcWinregOpenKey (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File,
RpcPolicyHandleHKeyPolicy, String KeyName, RpcPolicyHandle KeyPolicy)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_WINREG in this case) that must have been previously
acquired through RpcBindInterface.
HKeyPolicy is the handle to the WINREG opened policy that must have been previously acquired through
RpcWinregOpenHKey.
KeyName is the name of the key to be queried.
KeyPolicy is the returned handle to the WINREG opened policy.
Returns:
The policy handle of the newly opened key.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 507

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_WINREG, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hHK, hK

if (RpcWinregOpenHKey (hSmb, hTree, hFileInfo, RPC_WINREG_HKLM, hHK))


if (RpcWinregOpenKey (hSmb, hTree, hFileInfo, hHK, 'SOFTWARE\Microsoft\Windows\CurrentVersion', hK))
RpcWinregClose (hSmb, hTree, hFileInfo, hK)
endif
RpcWinregClose (hSmb, hTree, hFileInfo, hHK)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcWinregQueryKey
Remote access to the registry through the WINREG interface. Query a key that must be located under an already
opened HK.
Syntax:
Bool RpcWinregQueryKey (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcPolicyHandle
Policy, RpcWinregKeyInfo Key)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_WINREG in this case) that must have been previously
acquired through RpcBindInterface.
Policy is the handle to the WINREG opened policy that must have been previously acquired through
RpcWinregOpenHKey or RpcWinregOpenKey.
Key is the returned key details.

Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


508 - BMC FootPrints Asset Core - Chilli Reference

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_WINREG, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hHK, hK
RpcWinregKeyInfo hKeyInfo, hKeyInfo2
RpcWinregValueInfo hValueInfo, hValueInfo2

if (RpcWinregOpenHKey (hSmb, hTree, hFileInfo, RPC_WINREG_HKLM, hHK))


if (RpcWinregOpenKey (hSmb, hTree, hFileInfo, hHK, 'SOFTWARE\Microsoft\Windows\CurrentVersion', hK))
if (RpcWinregQueryKey (hSmb, hTree, hFileInfo, hK, hKeyInfo))
int iCpt
for (iCpt=0; iCpt<hKeyInfo.KeyCount; iCpt+=1)
if (RpcWinregEnumKey (hSmb, hTree, hFileInfo, hK, iCpt, hKeyInfo2)
Print (LogFile, "Key[" + MakeStr (iCpt) + "] " + hKeyInfo2.Name + "\r\n")
endif
endfor

for (iCpt=0; iCpt<hKeyInfo.ValueCount; iCpt+=1)


if (RpcWinregEnumValue (hSmb, hTree, hFileInfo, hK, iCpt, hValueInfo)
if (RpcWinregQueryValue (hSmb, hTree, hFileInfo, hK, hValueInfo.Name, hValueInfo2))
Print (LogFile, "Value[" + hValueInfo2.Name + "] " + hValueInfo2.Value + "\r\n")
endif
endif
endfor
endif
RpcWinregClose (hSmb, hTree, hFileInfo, hK)
endif
RpcWinregClose (hSmb, hTree, hFileInfo, hHK)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 509

endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

RpcWinregQueryValue
Remote access to the registry through the WINREG interface. Query a key value.
Syntax:
Bool RpcWinregQueryValue (SmbHandle Smb, SmbTreeInfo Tree, SmbFileInfo File, RpcPolicyHandle
Policy, String ValueName, RpcWinregValueInfo Value)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (IPC$ in this case) that must have been previously acquired
through SmbTreeConnect.
File is the handle to the opened interface (RPC_PIPE_WINREG in this case) that must have been previously
acquired through RpcBindInterface.
Policy is the handle to the WINREG opened policy that must have been previously acquired through
RpcWinregOpenHKey or RpcWinregOpenKey.
ValueName is the name of the value to be queried.
Value is the returned value details.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "IPC$", hTree))


SmbSessionClose (hSmb)

Numara Software, Inc. and BMC Software, Inc. Confidential.


510 - BMC FootPrints Asset Core - Chilli Reference

SmbDelete (hSmb)
return 1
endif

SmbFileInfo hFileInfo

if (!RpcBindInterface (hSmb, hTree, RPC_PIPE_WINREG, hFileInfo))


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return false
endif

RpcPolicyHandle hHK, hK
RpcWinregKeyInfo hKeyInfo, hKeyInfo2
RpcWinregValueInfo hValueInfo, hValueInfo2

if (RpcWinregOpenHKey (hSmb, hTree, hFileInfo, RPC_WINREG_HKLM, hHK))


if (RpcWinregOpenKey (hSmb, hTree, hFileInfo, hHK, 'SOFTWARE\Microsoft\Windows\CurrentVersion', hK))
if (RpcWinregQueryKey (hSmb, hTree, hFileInfo, hK, hKeyInfo))
int iCpt
for (iCpt=0; iCpt<hKeyInfo.KeyCount; iCpt+=1)
if (RpcWinregEnumKey (hSmb, hTree, hFileInfo, hK, iCpt, hKeyInfo2)
Print (LogFile, "Key[" + MakeStr (iCpt) + "] " + hKeyInfo2.Name + "\r\n")
endif
endfor

for (iCpt=0; iCpt<hKeyInfo.ValueCount; iCpt+=1)


if (RpcWinregEnumValue (hSmb, hTree, hFileInfo, hK, iCpt, hValueInfo)
if (RpcWinregQueryValue (hSmb, hTree, hFileInfo, hK, hValueInfo.Name, hValueInfo2))
Print (LogFile, "Value[" + hValueInfo2.Name + "] " + hValueInfo2.Value + "\r\n")
endif
endif
endfor
endif
RpcWinregClose (hSmb, hTree, hFileInfo, hK)
endif
RpcWinregClose (hSmb, hTree, hFileInfo, hHK)
endif

RpcCloseInterface (hSmb, hTree, hFileInfo)


SmbTreeDisconnect (hSmb, hTree)
SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

SmbCreate
Create a new SMB client.
Syntax:
SmbHandle SmbCreate ()
Returns:
A handle to the newly created SMB client.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 511

Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

SmbDelete (hSmb)
return 0

endproc

SmbCreateRaw
Create a new SMB client with/without NetBIOS layer.
Syntax:
SmbHandle SmbCreateRaw (Bool fRemoveNetbiosLayer)
fRemoveNetbiosLayer if the new client is to have NetBIOS layer.
Returns:
A handle to the newly created SMB client.

SmbDelete
Delete an SMB client.
Syntax:
Bool SmbDelete (SmbHandle Smb)
Smb is the handle to the SMB client connection.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)

Numara Software, Inc. and BMC Software, Inc. Confidential.


512 - BMC FootPrints Asset Core - Chilli Reference

return 1
endif

SmbDelete (hSmb)
return 0

endproc

SmbFileGet
Get a remote file to be copied locally.
Syntax:
Bool SmbFileGet (SmbHandle Smb, SmbTreeInfo Tree, String RemotePath, String LocalPath)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (such as C$) that must have been previously acquired through
SmbTreeConnect.
RemotePath is the remote file path to be retrieved.
LocalPath is the local file path to be created.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "C$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

string szFileVersion
string szProductVersion
bool fFileExists

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 513

SmbFileGet (hSmb, hTree, '\WINDOWS\system32\gdi32.dll', 'C:\my_gdi32.dll')

SmbTreeDisconnect (hSmb, hTree)


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

SmbFileGetDescription
Get a remote file description and set a boolean to confirm its existence.
Syntax:
Bool SmbFileGetDescription (SmbHandle Smb, SmbTreeInfo Tree, String RemoteFilePath, String
FileDescription, Bool FileExists)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (such as C$) that must have been previously acquired through
SmbTreeConnect.
RemoteFilePath is the remote file path to be queried.
FileDescription is the returned file description of the queried remote file path.
FileExists is the returned boolean that defines whether the remote file path does exist.
Returns:
TRUE to indicate that the file description was retrieved, FALSE otherwise.

SmbFileGetVersion
Get a remote file version and set a boolean to confirm its existence.
Syntax:
Bool SmbFileGetVersion (SmbHandle Smb, SmbTreeInfo Tree, String RemoteFilePath, String
FileVersion, String ProductVersion, Bool FileExists)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share (such as C$) that must have been previously acquired through
SmbTreeConnect.
RemotePath is the remote file path to be queried.
FileVersion is the returned file version of the queried remote file path.
ProductVersion is the returned product version of the queried remote file path.
FileExists is the returned boolean that defines whether the remote file path does exist.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


514 - BMC FootPrints Asset Core - Chilli Reference

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (!SmbTreeConnect (hSmb, "C$", hTree))


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 1
endif

string szFileVersion
string szProductVersion
bool fFileExists

if (SmbFileGetVersion (hSmb, hTree, '\WINDOWS\system32\gdi32.dll', szFileVersion, szProductVersion,


fFileExists))
Print (LogFile, "File version: " + szFileVersion + "\r\n")
endif

SmbTreeDisconnect (hSmb, hTree)


SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

SmbGetGssApiSupportKerberos
Find if the target supports Kerberos 5.
Bool SmbGetGssApiSupportKerberos (SmbHandle Smb)
Smb is the handle to the SMB client connection.
Returns:
TRUE to indicate support, FALSE otherwise.

SmbGetGssApiSupportNtlmSsp
Find if the target supports NTLM SSP.
Bool SmbGetGssApiSupportNtlmSsp (SmbHandle Smb)
Smb is the handle to the SMB client connection.
Returns:
TRUE to indicate support, FALSE otherwise.

SmbSessionClose
Exit the SMB session.
Bool SmbSessionClose (SmbHandle Smb)
Smb is the handle to the SMB client connection.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 515

Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

SmbSessionGetInfo
Get information about the session.
Syntax:
Bool SmbSessionGetInfo (SmbHandle Smb, SmbSessionInfo Session)
Smb is the handle to the SMB client connection.
Session is the returned current SMB session details.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)

Numara Software, Inc. and BMC Software, Inc. Confidential.


516 - BMC FootPrints Asset Core - Chilli Reference

return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbSessionInfo hSession
SmbSessionGetInfo (hSmb, hSession)

Print (LogFile, "Successfully connected to the peer server:\r\n")


Print (LogFile, " - Domain Name: " + hSession.DomainName + "\r\n")
Print (LogFile, " - Server Name: " + hSession.ServerName + "\r\n")
Print (LogFile, " - Native Os: " + hSession.NativeOs + "\r\n")
Print (LogFile, " - Native Lan Manager: " + hSession.NativeLanMan + "\r\n")

SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

SmbSessionLogOff
Logoff after session has been settled.
Syntax:
Bool SmbSessionLogOff (SmbHandle Smb)
Smb is the handle to the SMB client connection.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!TcpConnect (hSmb, "192.168.193.2", 139))


SmbDelete (hSmb)
return 1
endif

if (!NbtSessionRequest (hSmb, "*SMBSERVER"))

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 517

TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 1
endif

if (!SmbSessionNegotiate (hSmb))
NbtSessionDisconnect (hSmb)
TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 1
endif

if (!SmbSessionSetup (hSmb, "Administrator", "metrix"))


NbtSessionDisconnect (hSmb)
TcpDisconnect (hSmb)
SmbDelete (hSmb)
return false
endif

SmbSessionLogOff (hSmb)
NbtSessionDisconnect (hSmb)
TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 0

endproc

SmbSessionNegotiate
Negotiate the SMB session with server.
Syntax:
Bool SmbSessionNegotiate (SmbHandle Smb)
Smb is the handle to the SMB client connection.
Returns:
TRUE to indicate success, FALSE in case of failure.
Comments:
This is required before the session setup can be executed.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


518 - BMC FootPrints Asset Core - Chilli Reference

if (!TcpConnect (hSmb, "192.168.193.2", 139))


SmbDelete (hSmb)
return 1
endif

if (!NbtSessionRequest (hSmb, "*SMBSERVER"))


TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 1
endif

if (!SmbSessionNegotiate (hSmb))
NbtSessionDisconnect (hSmb)
TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 1
endif

NbtSessionDisconnect (hSmb)
TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 0

endproc

SmbSessionOpen
Do all the required operations from TCP connection to SMB logon.
Syntax:
Bool SmbSessionOpen (SmbHandle Smb, String HostName, Int Port, String User, String Password)
Smb is the handle to the SMB client connection.
HostName is the name of the client.
Port is the number of the port at which the connection is to be established.
User is the login name with which to log on.
Password is the password corresponing to the login name.
Returns:
TRUE to indicate success, FALSE in case of failure.
Comments:
The HostName can be entered as its long or short network name, for example, Scotty or Scotty.enterprise.com or
as its IP address in dotted notation.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 519

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

SmbSessionSetup
Logon after session has been negotiated.
Syntax:
Bool SmbSessionSetup (SmbHandle Smb, String User, String Password)
Smb is the handle to the SMB client connection.
User is the login name with which to log on.
Password is the password corresponing to the login name.
Returns:
TRUE to indicate success, FALSE in case of failure.
Comments:
If the User parameter has one or more '\' characters all data before the first '\' is used to specify the domain name
or the KDC hostname/ip_address:port (depends on the proposed mechType by target in SmbSessionNegotiate.
Such data is not filtered/modifed.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!TcpConnect (hSmb, "192.168.193.2", 139))


SmbDelete (hSmb)
return 1
endif

if (!NbtSessionRequest (hSmb, "*SMBSERVER"))


TcpDisconnect (hSmb)

Numara Software, Inc. and BMC Software, Inc. Confidential.


520 - BMC FootPrints Asset Core - Chilli Reference

SmbDelete (hSmb)
return 1
endif

if (!SmbSessionNegotiate (hSmb))
NbtSessionDisconnect (hSmb)
TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 1
endif

if (!SmbSessionSetup (hSmb, "Administrator", "metrix"))


NbtSessionDisconnect (hSmb)
TcpDisconnect (hSmb)
SmbDelete (hSmb)
return false
endif

SmbSessionLogOff (hSmb)
NbtSessionDisconnect (hSmb)
TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 0

endproc

SmbSetDebugContext
Set the debug context object.
Syntax:
Bool SmbSetDebugContext (SmbHandle Smb, VarHandle Var)
Smb is the handle to the SMB client connection.
Var is the handle to the MtxDebugContext that must have been previously acquired from the debug.chx
Chilli module.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"
include "debug.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 521

DebugContextHandle hDebug
hDebug = DebugContextCreate ()

if (hDebug == 0)
SmbDelete (hSmb)
return 1
endif

DebugContextSetFilePath (hDebug, "test.log");


SmbSetDebugContext (hSmb, hDebug)

if (!TcpConnect (hSmb, "192.168.193.2", 139))


SmbDelete (hSmb)
DebugContextDestroy (hDebug)
return 1
endif

TcpDisconnect (hSmb)
SmbDelete (hSmb)
DebugContextDestroy (hDebug)
return 0

endproc

SmbTreeConnect
Connect to a share (disk, IPC or any other share type).
Syntax:
Bool SmbTreeConnect (SmbHandle Smb, String TreeName, SmbTreeInfo Tree)
Smb is the handle to the SMB client connection.
TreeName is the name of the share to be connected.
Tree is the returned handle to the connected share.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1

Numara Software, Inc. and BMC Software, Inc. Confidential.


522 - BMC FootPrints Asset Core - Chilli Reference

endif

SmbTreeInfo hTree

if (SmbTreeConnect (hSmb, "C$", hTree))


SmbTreeDisconnect (hSmb, hTree)
endif

if (SmbTreeConnect (hSmb, "IPC$", hTree))


SmbTreeDisconnect (hSmb, hTree)
endif

SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

SmbTreeConnectWithServerName
Connect to a share (disk, IPC or any other share type) and give an idea about the server name.
Syntax:
Bool SmbTreeConnect (SmbHandle Smb, String TreeName, SmbTreeInfo Tree, String
SuggestedServerName)
Smb is the handle to the SMB client connection.
TreeName is the name of the share to be connected.
Tree is the returned handle to the connected share.
SuggestedServerName is the name of the server.
Returns:
A flag indicating whether the tree has been connected or not.

SmbTreeDisconnect
Disconnect from actually connected tree.
Syntax:
Bool SmbTreeDisconnect (SmbHandle Smb, SmbTreeInfo Tree)
Smb is the handle to the SMB client connection.
Tree is the handle to the connected share that must have been previously acquired through
SmbTreeConnect.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 37 - SMB Functions - 523

hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!SmbSessionOpen (hSmb, "andrea", 139, "Administrator", "numara"))


SmbDelete (hSmb)
return 1
endif

SmbTreeInfo hTree

if (SmbTreeConnect (hSmb, "C$", hTree))


SmbTreeDisconnect (hSmb, hTree)
endif

if (SmbTreeConnect (hSmb, "IPC$", hTree))


SmbTreeDisconnect (hSmb, hTree)
endif

SmbSessionClose (hSmb)
SmbDelete (hSmb)
return 0

endproc

TcpConnect
Perform connection at TCP level.
Syntax:
Bool TcpConnect (SmbHandle Smb, String HostName, Int Port)
Smb is the handle to the SMB client connection.
HostName is the name of the
Port is the number of the port at which the connection is to be established.
Returns:
TRUE to indicate success, FALSE in case of failure.
Comments:
The HostName can be entered as its long or short network name, for example, Scotty or Scotty.enterprise.com or
as its IP address in dotted notation. The default port is 139.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


524 - BMC FootPrints Asset Core - Chilli Reference

if (hSmb == 0)
return 1
endif

if (!TcpConnect (hSmb, "192.168.193.2", 139))


SmbDelete (hSmb)
return 1
endif

TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 0

endproc

TcpDisconnect
Perform disconnection at TCP level.
Syntax:
Bool TcpDisconnect (SmbHandle Smb)
Smb is the handle to the SMB client connection.
Returns:
TRUE to indicate success, FALSE in case of failure.
Example:
include "smb.chx"

#####################################################################
# main
#####################################################################

int main ()

SmbHandle hSmb
hSmb = SmbCreate ()

if (hSmb == 0)
return 1
endif

if (!TcpConnect (hSmb, "192.168.193.2", 139))


SmbDelete (hSmb)
return 1
endif

TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 0

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


SMTP Functions

This chapter explains the SMTP functions (Simple Mail Transfer Protocol) which are part of the Chilli language.
All functions of this module are included in the smtp.chx file for Windows or smtp.so file for UNIX and Linux.

38.1 Introduction
SMTP is a TCP/IP protocol for sending e-mail messages between servers and is generally used to send messages
from a mail client to a mail server.
Sending a mail directly using the SMTP protocol produces a mail with only the From: and Date: header fields
set. To enter other fields, they must be entered as the first part of the DATA, separated from the actual body by a
completely blank line. Not even white space is allowed on this line, e.g.:
DATA
354 Enter Data end with .
From: superspy@spyinternational.com
To: spys@spyinternational.com
Subject: SMTP - [informational]

This is an introduction to SMTP


...
.
250 Mail accepted for delivery
When the mail is received, the MUA (mail user agent) separates the header from the rest of the body. The To:
headers are not included in header along with the From: and Date: as default headers, because recipients can
be in the To: list, the Cc: list and the Bcc: list. The To: and Cc: list behave the same way, but the Bcc: list
is a list of all recipients whose addresses must not show up in the mail header. As already noted, all recipients are
specified using the RCPT TO: command, the SMTP server does not distinguish between different types of
recipients. It is the responsibility of the sending MUA to properly format the mail header, to include only those
headers that should be included, and exclude those that shouldn't.
In theory, this always works. Unfortunately, some old MTAs (message transfer agent) caused issues by including
the To: header if none was specified. To work around it, many MUAs add a To: Undisclosed Recipients if
no recipients are specified. This is done at the sender's end, not at the recipient's end.

38.2 Predefined Constants


Following you find the complete list of all predefined constants of the SMTP functions group of the Chilli script
language:

Name Type Description


SMTP_DEFAULT_PORT Integer The default port of the SMTP server

Numara Software, Inc. and BMC Software, Inc. Confidential.


526 - BMC FootPrints Asset Core - Chilli Reference

38.3 Error Codes


Following you find a list of all SMTP error codes. These errors are run-time errors that causes the handler
specified in ErrorHandler to be invoked. Functions can return these in addition to the standard runtime errors
such as FUNCFAILED. You will find a list with all runtime errors in Appendix E - Chilli Error Codes on page 677 at
the end of the manual.

Name Description
ERR_SMTPSYNTAXERROR Server does not recognise command
ERR_SMTPBADSEQUENCE Server complained of bad sequence of commands
ERR_SMTPBADMAILBOX Remote mailbox doesn't exist or can't be read/written
ERR_SMTPNOSPACE Server does not have enough space

38.4 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli SMTP function group has Predefined Handle Data Types.

38.4.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


SmtpHandle Object type: reference to the handle of an SMTP connection

SmtpHandle
The SmtpHandle data type is a reference to the handle of the connection to the Smtp server.
A value of this data type is returned by the SmtpConnect function and used by all other SMTP functions as their
first argument. The SMTP session and thus the value must be closed with the SmtpDisconnect function.

38.5 Functions
Following you find the complete list of SMTP functions:

Function OS Description
SmtpAddBCCRecipient Add a blind carbon copy recipient to a mail message

SmtpAddCCRecipient Add a carbon copy recipient to a mail message

SmtpAddFile Add the supplied file as an attachment to the message of the mail message

SmtpAddHeader Add the supplied text to the header part of the mail message

SmtpAddMIMEHeader Add the supplied text to the MIME header part of the mail message

SmtpAddRecipient Identify a single Recipient for a mail message

SmtpAddSubject Add the supplied text as a subject field to the header part of the mail message

SmtpAddText Add the supplied text to the message part of the mail message

SmtpAddToRecipient Add a recipient to a mail message

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 38 - SMTP Functions - 527

Function OS Description
SmtpConnect Connect to the named SMTP server at the specified port

SmtpDisconnect Terminate the SMTP session

SmtpEndMail Contact the server in an established connection and send in order the headers, the
message text and any attached files
SmtpGetServerStatus Return the last known status from the SMTP server

SmtpStartMail Start a mail transaction

SmtpVerifyAddress Verify a mail address

SmtpAddBCCRecipient
Add a blind carbon copy recipient to a mail message.
Syntax:
Bool SmtpAddBCCRecipient (SmtpHandle Connection, String BCCRecipientAddress)
Connection is the handle to the connection with the SMTP server.
BCCRecipientAddress is the address of the blind carbon copy recipient to be added to the mail message.
Returns:
TRUE if the operation was successful, FALSE if it failed.
Comments:
This function adds a blind carbon copy recipient to a mail message by performing an SMTP RCPT command as
well as adding a BCC: <recipient> header to the message. This is similar to SmtpAddRecipient except that
SmtpAddRecipient does not add any headers to the message. This should only be sent after a MAIL command.
Any number of recipients can be identified before the mail message is sent.

SmtpAddCCRecipient
Add a carbon copy recipient to a mail message.
Syntax:
Bool SmtpAddCCRecipient (SmtpHandle Connection, String CCRecipientAddress)
Connection is the handle to the connection with the SMTP server.
CCRecipientAddress is the address of the carbon copy recipient to be added to the mail message.
Returns:
TRUE if the operation was successful, FALSE if it failed.
Comments:
This function adds a carbon copy recipient to a mail message by performing an SMTP RCPT command as well as
adding a CC: <recipient> header to the message. This is similar to SmtpAddRecipient except that
SmtpAddRecipient does not add any headers to the message. This should only be sent after a MAIL command.
Any number of recipients can be identified before the mail message is sent.

SmtpAddFile
Add the supplied file as an attachment to the message of the mail message.
Syntax:
Bool SmtpAddFile (SmtpHandle Connection, String FilePath)
Connection is the handle to the connection with the SMTP server.
FilePath is the relative or absolute path to the file to be attached to the mail message.

Numara Software, Inc. and BMC Software, Inc. Confidential.


528 - BMC FootPrints Asset Core - Chilli Reference

Returns:
TRUE if the file was successfully added, or FALSE if the operation failed or the file to be added does not exist.
Comments:
This can be called as many times as needed to attach as many files as required to the mail message. When a
SmtpEndMail is called the files are read and sent to the server in a MIME encoded message together with the
headers and plain text message created with the SmtpAddHeader and SmtpAddText functions.

SmtpAddHeader
Add the supplied text to the header part of the mail message.
Syntax:
Bool SmtpAddHeader (SmtpHandle Connection, String Text)
Connection is the handle to the connection with the SMTP server.
Text is the text to be added to the header of the message.
Returns:
TRUE if the operation was successful, FALSE if the operation failed.
Comments:
As many headers as required can be added to the message. These are then sent to the server when a SmtpEndMail
command is executed. The most common elements of a header are To, From, Subject and Date. Any of the
elements added to the header through this function can not be seen by the recipient, because this is included into
the part that is separated from the rest of the body at reception through the MUA. For exmaple, a subject added
through the SmtpAddHeader function cannot be seen. To add the visible subject line to the mail you must use the
SmtpAddSubject function.

SmtpAddMimeHeader
Add the supplied text to the MIME header part of the mail message.
Syntax:
Bool SmtpAddMIMEHeader (SmtpHandle Connection, string Text)
Connection is the handle to the connection with the SMTP server.
Text is the text to be added to the MIME header of the message.
Returns:
TRUE if the text was successfully added, or FALSE if the operation failed.
Comments:
Normally all mail messages are sent as plain text unless there are attached files. If there are any files attached to
the message through SmtpAddFile then the message is automatically sent in MIME format. If there are no
attached files but the message should be sent in MIME format, the SmtpAddMimeHeader function can be used to
set up the header fields and therefore signal that the message should be sent in MIME format. As many headers as
required can be added to the message. Typically to send a mail message already formatted in HTML, the MIME
header would be:
Content-Type:text/html; charset=us-ascii

SmtpAddRecipient
Identify a single recipient for a mail message.
Syntax:
Bool SmtpAddRecipient (SmtpHandle Connection, String RecipientAddress)
Connection is the handle to the connection with the SMTP server.
RecipientAddress is the e-mail address of the recipient to which the mail is to be sent.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 38 - SMTP Functions - 529

Returns:
TRUE if the identification operation was successful, FALSE if the operation failed.
Comments:
This function performs a command which then identifies the recipient address for the mail. The format of the e-
mail address is the common format, for example, kirk@enterprise.com. It should only be sent after a
SmtpStartMail command. Any number of recipients can be identified and added before the mail message is sent.
Any recipients added through the SmtpAddRecipient is not visible in the list of addressees, because they are
included into the part which is separated from the rest of the body at reception through the MUA. Adding a
recipient with SmtpAddRecipient is effectively an equivalent to adding a recipient as BCC. To add a recipient to
the normal list use the SmtpAddToRecipient or SmtpAddCCRecipient function.

SmtpAddSubject
Add the supplied text as a subject field to the header part of the mail message.
Syntax:
Bool SmtpAddSubject (SmtpHandle Connection, String SubjectText)
Connection is the handle to the connection with the SMTP server.
SubjectText is the text of the subject field or title of the mail.
Returns:
TRUE if the operation was successful, FALSE if it failed.
Comments:
This function is similar to the SmtpAddHeader function except that it adds the Subject: prefix to the supplied
SubjectText. Only a single subject header should be added to the message.

SmtpAddText
Add the supplied text to the message part of the mail message.
Syntax:
Bool SmtpAddText (SmtpHandle Connection, String Text)
Connection is the handle to the connection with the SMTP server.
Text is the text to be added to the message part of the mail message.
Returns:
TRUE if the operation was successful, FALSE if the operation failed.
Comments:
This can be called as many times as needed to compose a message text which is eventually sent to the server
when a SmtpEndMail command is executed.

SmtpAddToRecipient
Add a recipient to a mail message.
Syntax:
Bool SmtpAddToRecipient (SmtpHandle Connection, String ToRecipientAddress)
Connection is the handle to the connection with the SMTP server.
ToRecipientAddress is the address of the recipient to be added to the mail message.
Returns:
TRUE if the operation was successful, FALSE if it failed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


530 - BMC FootPrints Asset Core - Chilli Reference

Comments:
This function adds a recipient to a mail message by performing an SMTP RCPT command as well as adding a To:
<recipient> header to the message. This is similar to SmtpAddRecipient except that SmtpAddRecipient does
not add a To: header to the message. This recipient is not cut off together with the header at reception through
the MUA, it is displayed in the mail. This should only be sent after a MAIL command. Any number of recipients
can be identified before the mail message is sent.

SmtpConnect
Connect to the named SMTP server at the specified port.
Syntax:
SmtpHandle SmtpConnect (String Server, Int Port)
Server is the SMTP server to which a connection is to be established.
Port is the port on the SMTP server.
Returns:
If the connection is successfully established the function returns a handle to the connection which is to be used
by all other SMTP functions. If the function fails, 0 is returned.
Comments:
The port is normally expected to be SMTP_DEFAULT_PORT, the server name can be a host name or an IP address
expressed in the dotted notation. The sender-SMTP establishes a two-way transmission channel to a receiver-
SMTP. The receiver-SMTP can be either the ultimate destination or an intermediate. SMTP commands are
generated by the sender-SMTP and sent to the receiver-SMTP. SMTP replies are sent from the receiver-SMTP to
the sender-SMTP in response to the commands.

SmtpDisconnect
Terminate the SMTP session.
Syntax:
Bool SmtpDisconnect (SmtpHandle Connection)
Connection is the handle to the connection with the SMTP server.
Returns:
TRUE if the connection was successfully closed or FALSE if the operation failed.
Comments:
This function performs an SMTP QUIT followed by a disconnect to terminate the SMTP session. Be aware, that
the supplied handle is no longer valid after executing this operation, even if the disconnect operation is not
successful.

SmtpEndMail
Contact the server in an established connection and send in order the headers, the message text and any attached
files.
Syntax:
Bool SmtpEndMail (SmtpHandle Connection)
Connection is the handle to the connection with the SMTP server.
Returns:
TRUE if the operation was successful or FALSE if the operation failed.
Comments:
This function completes the mail transaction. However, the connection to the SMTP server remains open after
this so that another SmtpStartMail/SmtpEndMail transaction can be executed. If no more mail is to be sent, it
needs to be closed via the SmtpDisconnect function.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 38 - SMTP Functions - 531

SmtpGetServerStatus
Return the last known status from the SMTP server.
Syntax:
Int SmtpGetServerStatus (SmtpHandle Connection)
Connection is the handle to the connection with the SMTP server.
Returns:
The integer value of the last known server status if the operation was successful, or 0 if the function failed.
Comments:
The server status is returned in form of the SMTP status codes as defined in RFC 821, as detailed under heading
Error Codes later on in this chapter.
Example:
proc main ()

int error
SmtpHandle smtp

error = SmtpStartMail (smtp, "blackhelmet@spaceballs.com")


if (error == 0)
error = ErrCode
print ("SMTP error " + error + " = " + GetErrorName (error) + "\n")
print (GetErrorText (error) + "\n");
endif

endproc

SmtpStartMail
Start a mail transaction.
Syntax:
Bool SmtpStartMail (SmtpHandle Connection, String SenderAddress)
Connection is the handle to the connection with the SMTP server.
SenderAddress is the sender address from which the mail is to be sent.
Returns:
TRUE if the start send operation was successful, FALSE if the operation failed.
Comments:
This function should be followed by one or more SmtpAddRecipient functions and then a data file or buffer via
the SmtpAddHeader, SmptAddText and SmtpAddFile functions in order to successfully send a mail message.

SmtpVerifyAddress
Verify a mail address.
Syntax:
String SmtpVerifyAddress (SmtpHandle Connection, String MailAddress)
Connection is the handle to the connection with the SMTP server.
MailAddress is the e-mail address to be verified.
Returns:
The full address as recognized by the server if the operation was successful, or an empty string if the operation
failed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


532 - BMC FootPrints Asset Core - Chilli Reference

Comments:
The format of the e-mail address is the normal format such as kirk@enterprise.com. For some hosts the user
name is case sensitive, and SMTP implementations must take care to preserve the case of user names as they
appear in mailbox arguments. Host names are not case sensitive.

38.6 Examples
proc main ()
int error
smtpHandle smtp
smtp = SmtpConnect ("spacey", SMTP_DEFAULT_PORT)

SmtpStartMail (smtp, "blackhelmet@spaceballs.com")


SmtpAddRecipient (smtp, "blackhelmet@spaceballs.com")
SmtpAddRecipient (smtp, "engineering@spaceballs.com")
SmtpAddRecipient (smtp, "presidentscrooge@spaceballs.com")

SmtpAddHeader (smtp, "To: engineering@spaceballs.com")


SmtpAddHeader (smtp, "Subject: The new Beaming Regulations")
SmtpAddHeader (smtp, "CC: charleen@spaceballs.com")
SmtpAddHeader (smtp, "Cc: marleen@spaceballs.com")
SmtpAddHeader (smtp, "CC: charleen@spaceballs.com")

SmtpAddText (smtp, "Hi,\n")


SmtpAddText (smtp, "Please find following the newly revised beaming\n")
SmtpAddText (smtp, "regulations of the Spaceball Space Maid with\n")
SmtpAddText (smtp, "regards to the internal structure and the\n")
SmtpAddText (smtp, "handling of all computer and weapons systems\n")
SmtpAddText (smtp, "connections. Be very careful to not divulge\n")
SmtpAddText (smtp, "any of the secrets contained in this document,\n")
SmtpAddText (smtp, "as in this case we might not be able to\n")
SmtpAddText (smtp, "able to get ahold of the Princess of planet\n")
SmtpAddText (smtp, "Druidia. This means we will all die,\n")
SmtpAddText (smtp, "but I will kill you all before that happens!\n\n")
SmtpAddText (smtp, "Black Helmet.\n")

SmtpAddFile (smtp, "regs124beem585rev15.regs")


SmtpAddFile (smtp, "regs125beem585rev15.regs")

SmtpEndMail (smtp)
SmtpDisconnect (smtp)
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


SNMP Functions

This chapter details all elements which handle the SNMP Access functions in the Chilli language. All functions of
this module are included in the snmp.chx file for Windows or snmp.so file for UNIX and Linux.

39.1 Introduction
The Simple Network management Protocol (SNMP) provides a mechanism for obtaining information about the
operating characteristics of networks as well as for changing the parameters of certain network elements such as
routers and gateways.
The Chilli SNMP module is divided into two parts:
• Handle Based SNMP Functions
This group of functions demands the handle to a variable binding list as a parameter; some functions also need
the BCM agent to be running when they are executed.
• Structure Based SNMP Functions
These SNMP functions demand predefined structures as parameters and can be executed in any environment.

39.2 Predefined Constants


Following you find the complete list of all predefined constants of the SNMP functions group of the Chilli script
language:

Name Type Description


SNMP_COUNT Integer The object is a non-negative integer which monotonously increases until it reaches a
maximum value (not exceeding 232 - 1) and then wraps back to 0.
SNMP_GAUGE Integer The object is a non-negative integer which can increase or decrease, but which latches at
a maximum value.
SNMP_INT / SNMP_INTEGER Integer The value is an integer.
SNMP_IPADDR Integer The object is of type IP address which contains four digit strings. It is returned in its
printable ASCII representations in the StringValue member of the ObjectValue structure.
For example a 4 part IP address value of 192.168.8.10 is returned as the 12 character
ASCII string “192.168.8.10”.
SNMP_NULL Integer The object acts as a placeholder for read operations.
SNMP_OID Integer The object is of type Object ID which means it has a fixed number of sub-ids each of
which is a 32 bit integer.
SNMP_PHYS / SNMP_PHYSADDR Integer The object is of type Physical Address which contains six digit strings. It is returned in its
printable ASCII representations in the StringValue member of the ObjectValue structure.
SNMP_STR / SNMP_STRING Integer The value is a string.
SNMP_TABLE Integer The object is of type table.
SNMP_TIME Integer The object is a non-negative integer which counts the time in hundredths of a second
since some specific time, not exceeding 232 - 1.

Numara Software, Inc. and BMC Software, Inc. Confidential.


534 - BMC FootPrints Asset Core - Chilli Reference

39.3 Error Codes


Following you find a list of all SNMP error codes. These errors are run-time errors that causes the handler
specified in ErrorHandler to be invoked. Functions can return these in addition to the standard runtime errors
such as FUNCFAILED. You will find a list with all runtime errors in Appendix E - Chilli Error Codes on page 677 at
the end of the manual.

Name Description
ERR_SNMPBADOID SNMP invalid Object ID string
ERR_SNMPBADREQ SNMP unable to create request
ERR_SNMPBADSOCKET SNMP socket invalid or unable to bind to
ERR_SNMPBADVALUE SNMP varbind contains an incorrect value
ERR_SNMPGENERR SNMP general error
ERR_SNMPNOSUCHNAME SNMP specified OID is not supported
ERR_SNMPREADONLY SNMP read-only MIB variable
ERR_SNMPTIMEOUT SNMP request did not get a response
ERR_SNMPTOOBIG SNMP response message too big to send

39.4 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli SNMP function group has predefined data types of type handle
and structure.

39.4.1 Predefined Handle Data Types


Predefined data types of type handle are opaque handles which contain the necessary information for accessing
various data. They have a name and are returned by functions andpassed on to other functions or procedures
without changes.
Following you find a list of all predefined data types of type handle:

Data Type Description


VarBind Object type: reference to the variable list handle.

VarBind
The VarBind data type is a reference to the handle of an SNMP variable list.
The function SnmpCreateVars returns a value of this object type and most of the other functions expect it as their
first argument. Any open variable list and thus the value of this object type should be destroyed by the
SnmpDestroyVars function.
This handle data type is only applicable to the handle based SNMP function subgroup.

39.4.2 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated.
Following you find a list of all predefined data types of type structure:

Data Type Description


SnmpOid An array of SubIDs uniquely identifying a variable
SnmpVarBind Represent an SNMP variable binding identified by its OID and the assigned value
SnmpVarBindValue The value of a variable binding in a variable list

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 39 - SNMP Functions - 535

SnmpOid
The SnmpOid structure represents an array of SubIDs uniquely identifying a variable.
This structure data type is only applicable to the structure based SNMP function subgroup.
Elements:

Elements Element Type Description


SubIds Integer array The location of an SNMP variable within a MIB.

SnmpVarBind
The SnmpVarBind structure represents an SNMP variable binding identified by its OID and the assigned value.
This structure data type is only applicable to the structure based SNMP function subgroup.
Elements:

Elements Element Type Description


ObjectId SnmpOid structure The location of an SNMP variable within a MIB.
ObjectValue SnmpVarBindValue The value of a variable binding in a variable list.
structure

SnmpVarBindValue
The SnmpVarBindValue structure sets the value of a variable binding in a variable list.
This structure data type is only applicable to the structure based SNMP function subgroup.
Elements:

Elements Element Type Description


ValueType Integer The integer representing the type of the value.
IntegerValue Integer The integer value of the variable if the type is integer.
StringValue String The string value of the variable if the type is string.
OidValue SnmpOid structure The oid value of the variable if the type is oid.

Value Types:
Possible value types are: SNMP_INT, SNMP_STR, SNMP_OID and SNMP_UNKNOWN

39.5 Handle Based SNMP Functions


All functions of this group demand the handle to a variable binding list as one of their parameters and some of
them also need the BCM agent be running on the local machines when they are be executed.
Following you find the list of all functions currently available in this module:

Function OS Description
SnmpCreateVars Create a variable list for SNMP operations

SnmpDestroyVars Destroy a variable list used for SNMP operations

SnmpGet Perform an SNMP Get operation

SnmpGetIntValue Get the integer value of an object in a variable list

SnmpGetNext Perform an SNMP GetNext operation

SnmpGetOid Get the Object ID in a variable list

SnmpGetOidLength Get the number of elements in an Object ID in a variable list

Numara Software, Inc. and BMC Software, Inc. Confidential.


536 - BMC FootPrints Asset Core - Chilli Reference

Function OS Description
SnmpGetOidValueLengt Get the length of an Object ID value for an object in a variable list
h
SnmpGetOidValueSubi Get a sub-id of an Object ID value for an object in a variable list
d
SnmpGetStrValue Get the string value of an object in a variable list

SnmpGetSubid Get the integer value of one of the elements in an Object ID in a variable list

SnmpGetValueType Get the type of the value of an object in a variable list

SnmpSendTrap Send an SNMP trap

SnmpSet Perform an SNMP set operation

SnmpSetOid Set an Object ID in a variable list

SnmpSetOidLength Set the number of elements in an Object ID in a variable list

SnmpSetSubid Set the integer value of one of the elements in an Object ID in a variable list

SnmpSetValueType Set the type of the value of one of the variables in the supplied varbind structure

SnmpSetVarValue Set the value of a variable binding in a variable list

SnmpCreateVars
Create a list of variables which is used for SNMP operations such as reading MIBs and sending traps.
Syntax:
VarBind SnmpCreateVars (Int VarCount)
VarCount is the number of variables to allocate space for in the list. This cannot be changed later.
Returns:
If the operation was successful, it returns a handle of type VarBind to the list of variables created. If the function
failed, it returns 0.
Comments:
The variable list created is used with all other SNMP functions. The returned value is a handle to the list and
must not be modified like a normal integer because this makes it invalid.The variable list is a sequence of SNMP
Variable Bindings (VarBinds). Each VarBind consists of a MIB object Id (Oid) and a value. The various SNMP
functions permit the various parts of the VarBind to be manipulated. For a detailed understanding of SNMP and
VarBinds consult the Internet RFC 1157 or The Simple Book by Marshall T. Rose.

SnmpDestroyVars
Destroy a variable list used for SNMP operations.
Syntax:
Bool SnmpDestroyVars (VarBind Handle)
Handle is the handle to the variable list to be destroyed. It must be a value returned by SnmpCreateVars.
Returns:
TRUE if the operation was successful, FALSE if the function failed.
Comments:
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars. After calling this function, the Handle is no longer valid and cannot be used in any SNMP
functions. Doing so causes the called function to return an error.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 39 - SNMP Functions - 537

SnmpGet
Perform an SNMP get operation.
The SnmpGet functions has two signatures, whose usage depends on the fact if the BCM agent is running or not.

SnmpGet (BCM agent running)


Perform an SNMP get operation from the local BCM agent.
Syntax:
Bool SnmpGet (VarBind Handle)
Handle is the handle to the VarBind structure which should have been prepared already.

SnmpGet (no BCM agent running)


Perform a get operation from an SNMP agent given a handle to a VarBind structure which should have been
prepared already.
Bool SnmpGet (String Destination, Int Port, Int Timeout, String Community, VarBind Handle)
Destination is the address of the host the message is sent to.
Port is the port number on which the agent runs (usually 161).
Timeout is the time-out value in seconds used when opening a connection or waiting for a response from
the SNMP agent.
Community is the community string used when sending SNMP messages to the management station.
Handle is the handle to the variable list to be used in the access.
Returns:
TRUE if the function was successful, FALSE if it failed.
Comments:
If the function is successful, the supplied VarBind is updated with the read values. The function can fail if the
supplied handle is not valid, or if the BCM/SNMP agent is not running on the machine.
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars. The function causes the Chilli interpreter to contact the BCM agent or the SNMP agent and try
and perform a read operation in a very similar manner to incoming network requests. If the supplied VarBind list
is valid, the agent fills in the values of the individual VarBinds and returns.

SnmpGetIntValue
Get the value of an object of type integer in a variable list.
Syntax:
Int SnmpGetStrValue (VarBind Handle, Int Index)
Handle is the handle to the variable list to be read. It must be a value returned by SnmpCreateVars.
Index is the index of the variable binding to be read, starting at 1 for the first one.
Returns:
If the function was successful, it returns the integer value of the indexed object in the variable binding. If the
function failed, it returns a 0. The function can fail if the supplied handle is not valid, the VarBind supplied is 0
or larger than the number of VarBinds in the list, or if the indexed value is not of an integer type.
Comments:
The actual value must be suitable for expression as an integer.
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars.

SnmpGetNext
Perform an SNMP GetNext operation.

Numara Software, Inc. and BMC Software, Inc. Confidential.


538 - BMC FootPrints Asset Core - Chilli Reference

The SnmpGetNext functions has two signatures, whose usage depends on the fact if the BCM agent is running or
not.

SnmpGetNext (BCM agent running)


Perform an SNMP GetNext operation from the local BCM agent.
Syntax:
Bool SnmpGetNext (VarBind Handle)
Handle is the handle to the VarBind structure which should have been prepared already.

SnmpGetNext (no BCM agent running)


Perform a getnext operation from an SNMP agent given a handle to a VarBind structure which should have
been prepared already.
Syntax:
Bool SnmpGetNext (String Destination, Int Port, Int Timeout, String Community, VarBind
Handle)
Destination is the address of the host the message is sent to.
Port is the port number on which the agent runs (usually 161).
Timeout is the time-out value in seconds used when opening a connection or waiting for a response from
the SNMP agent.
Community is the community string used when sending SNMP messages to the management station.
Handle is the handle to the variable list to be used in the access.
Returns:
TRUE if the function was successful, FALSE if it failed.
Comments:
If the function is successful, the supplied VarBind is updated with the read values. The function can fail if the
supplied handle is not valid, or if the BCM/SNMP agent is not running on the machine.
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars. The function causes the Chilli interpreter to contact the BCM agent or the SNMP agent and try
and perform a GetNext operation in a very similar manner to incoming network requests. If the supplied
VarBind list is valid, the agent fills in the values of the individual VarBinds and returns. The only difference
between this and SnmpGet is that for each Oid in the VarBind list, the agent actually reads the next readable
object in the MIB tree that it supports, as per the SNMP standard. The returned VarBind list does not only have
the read values, but the Oids have been changed to those of the MIB objects which were read as a result of the
GetNext operation.

SnmpGetOid
Get the Object ID in a variable list as a text string.
Syntax:
String SnmpGetOid (VarBind Handle, Int Index)
Handle is the handle to the variable list to be read. It must be a value returned by SnmpCreateVars.
Index is the index of the variable binding to be read, starting at 1 for the first one.
Returns:
The ASCII representation of the Oid part of a variable binding if the function was successful, an empty string if it
failed. The function can fail if the supplied handle is not valid, or if the VarBind supplied is 0 or larger than the
number of VarBinds in the list.
Comments:
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars. The returned Oid string is a textual representation of the SNMP object Id, its form is a sequence
or integer values separated by dots (.), for example, 1.2.3 or 12.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 39 - SNMP Functions - 539

Example:
The example below shows an OID with 10 elements or SubIds.
''1.3.6.1.4.2.976.1.2.1''

SnmpGetOidLength
Get the length (number of elements) in an Object ID in a variable list.
Syntax:
Int SnmpGetOidLength (VarBind Handle, Int Index)
Handle is the handle to the variable list to be read. It must be a value returned by SnmpCreateVars.
Index is the index of the variable binding to be read, starting at 1 for the first one.
Returns:
If the function was successful, it returns the number of elements (SubIds) in the Oid part of a variable binding. If
the functions failed, it returns 0. The function can fail if the supplied handle is not valid, or if the VarBind
supplied is 0 or larger than the number of VarBinds in the list.
Comments:
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars. The number of SubIds in an Oid represents the number of terms in the Oid.

Example:
The example below shows an OID with 10 elements or SubIds.
''1.3.6.1.4.2.976.1.2.1''

SnmpGetOidValueLength
Get the length of an Object ID value for an object in a variable list.
Syntax:
Int SnmpGetOidValueLength (VarBind Handle, Int Index)
Handle is the handle to the variable list to be read. It must be a value returned by SnmpCreateVars.
Index is the index of the variable binding to be read, starting at 1 for the first one.
Returns:
If the function was successful, it returns the length (number of elements or SubIds) in the value part of a variable
binding if it is a value of type Object ID. If the functions failed, it returns 0.
Comments:
The actual value must be of type OID or the function fails. It can also fail, if the supplied handle is not valid, the
VarBind supplied is 0 or larger than the number of VarBinds in the list, or if the indexed value is not of an
Object ID type.
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars.
The number of SubIds in an Oid represents the number of terms in the Oid.
Example:
The example below shows an OID with 10 elements or SubIds.
''1.3.6.1.4.2.976.1.2.1''

SnmpGetOidValueSubid
Get the integer value of one of the elements in an Object ID type value in a variable list.
Syntax:
Int SnmpGetOidValueSubid (VarBind Handle, Int Index, Int SubId)
Handle is the handle to the variable list to be read. It must be a value returned by SnmpCreateVars.

Numara Software, Inc. and BMC Software, Inc. Confidential.


540 - BMC FootPrints Asset Core - Chilli Reference

Index is the index of the variable binding to be read, starting at 1 for the first variable.
SubId is the index of the subid in the Oid value to be read, starting at 1 for the first element.
Returns:
If the function was successful, it returns the integer value of the indexed element (SubId) in the value part of a
variable binding. If the functions failed, it returns 0.
Comments:
The function can fail if the supplied handle is not valid, if the VarBind supplied is 0 or larger than the number of
VarBinds in the list, if the SubId index is larger than the number of elements in the indexed Oid, or if the indexed
value is not of type Object ID.
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars.
The number of SubIds in an Oid represents the number of terms in the Oid.
Example:
The example below shows an OID with 10 elements or SubIds.
''1.3.6.1.4.2.976.1.2.1''

SnmpGetStrValue
Get the value of an object of type string in a variable list.
Syntax:
String SnmpGetStrValue (VarBind Handle, Int Index)
Handle is the handle to the variable list to be read. It must be a value returned by SnmpCreateVars.
Index is the index of the variable binding to be read, starting at 1 for the first one.
Returns:
If the function was successful, it returns the string value of the indexed object in the variable binding. If the
functions failed, it returns an empty string. The function can fail if the supplied handle is not valid, the VarBind
supplied is 0 or larger than the number of VarBinds in the list, or if the indexed value is not of a string type.
Comments:
Values of type STRING, IPADDR and PHYSADDR are returned in their ASCII representation.
The actual value must be suitable for expression as a string or the function fails.
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars.

SnmpGetSubid
Get the integer value of one of the elements in an Object ID in a variable list.
Syntax:
Int SnmpGetSubid (VarBind Handle, Int Index, Int SubIdIndex)
Handle is the handle to the variable list to be read. It must be a value returned by SnmpCreateVars.
Index is the index of the variable binding to be read, starting at 1 for the first variable.
SubIdIndex is the index of the subid in the Oid to be read, starting at 1 for the first element.
Returns:
If the function was successful, it returns the value of the indexed element (SubId) in the Oid part of a variable
binding. If the functions failed, it returns 0. The function can fail if the supplied handle is not valid, if the
VarBind supplied is 0 or larger than the number of VarBinds in the list, or if the SubId index is larger than the
number of elements in the indexed Oid.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 39 - SNMP Functions - 541

Comments:
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars. The number of SubIds in an Oid represents the number of terms in the Oid.

Example:
The example below shows an OID with 10 elements or SubIds.
''1.3.6.1.4.2.976.1.2.1''

SnmpGetValueType
Get the type of the value of an object in a variable list.
Syntax:
Int SnmpGetValueType (VarBind Handle, Int Index)
Handle is the handle to the variable list to be read. It must be a value returned by SnmpCreateVars.
Index is the index of the variable binding to be read, starting at 1 for the first variable.
Returns:
If the operation was successful it returns an integer value corresponding to the type of the value of the indexed
object as shown below.

Type Description
SNMP_UNKNOWN The value type is invalid. This could be as the varbind is not completely initialized or the last get request
using the varbind failed.
SNMP_INT The value is an integer.
SNMP_STR The value is a string. This includes objects of type IP Address which are four digit strings and Physical
Address which are six digit strings.
SNMP_OID The object is of type Object ID which means it has a fixed number of sub-ids each of which is a 32 bit
integer.

If the function failed, 0 is returned. In this case ErrCode is set to ERR_INVALIDPARAM.


Comments:
The function can fail if the supplied handle is not valid, or if the VarBind supplied is 0 or larger than the number
of VarBinds in the list.
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars.

SnmpSendTrap
Send a trap to a management station given the handle to a Varbind.
The SnmpSendTrap functions has two signatures, whose usage depends on the fact if the BCM agent is running or
not.

SnmpSendTrap (BCM agent running)


Send a trap to all trap hosts configured into the local BCM agent given a handle to a variable binding list which
should have been prepared already.
Syntax:
Bool SnmpSendTrap (VarBind Handle, Int SpecificId)
Handle is the handle to the variable list. It must be a value returned by SnmpCreateVars.
SpecificId is the Specific Trap Id to be included in the trap message being sent.

SnmpSendTrap (no BCM agent running)


Send a trap to an SNMP management station given a handle to a variable binding list which should have been
prepared already.

Numara Software, Inc. and BMC Software, Inc. Confidential.


542 - BMC FootPrints Asset Core - Chilli Reference

Bool SnmpSendTrap (String Destination, Int TrapPort, String Community, String EnterpriseOid,
Int GenericId, Int SpecificId, VarBind[] Variables)
Destination is the address of the host the message is sent to.
TrapPort is the port number on which the management station listens for incoming trap messages (usually
162).
Community is the community string used when sending SNMP messages to the management station.
EnterpriseOid is the OId of the management enterprise that defines the trap message.
GenericId defines the standard type of the trap message.
SpecificId is the Specific Trap Id to be included in the trap message being sent.
Variables is the handle to the list of trap variables. It must be a value returned by SnmpCreateVars.
Returns:
TRUE if the function is successful, FALSE if it fails. The function can fail if the supplied handle is not valid, or if
the BCM/SNMP agent is not running on the machine.
Comments (BCM agent running):
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars. The trap sent is an SNMP Specific Trap (type 6) using the supplied TrapId value. This function
depends on the BCM agent running on the local machine. It uses the SNMP capabilities of the agent to format the
trap message and send it to all trap destinations defined for the agent. It cannot send traps to specific hosts.
Comments (no BCM agent running):
A trap message is an unrequested event report message that is sent from an SNMP agent to a management station
indicating that some predefined condition or event has occurred. The variable bindings stored in the data of the
trap contain the identity and values of the MIB variables that provide information about the specific event.
The standard trap type defines the type of the trap message. It can be one of the following values:

Value Error
0 coldStart
1 warmStart
2 linkDown
3 linkUp
4 authenticationFailure
5 egpNeighborLoss
6 enterpriseSpecific

If the value in the standard trap type field is other than 6 the specific trap type value is 0 and is not used. If the
standard trap type is identified as 6/enterprise specific trap type in the standard trap type this field contains a
value greater than zero (0). This specifies which trap type object in the MIB identified in the Enterprise MIB OID
field defines this trap PDU.

SnmpSet
Perform an SNMP set operation.
The SnmpSet functions has two signatures, whose usage depends on the fact if the BCM agent is running or not.

SnmpSet (BCM agent running)


Perform an SNMP set operation to the local BCM agent.
Syntax:
Bool SnmpSet (VarBind Handle)
Handle is the handle to the VarBind structure which should have been prepared already.

SnmpSet (no BCM agent running)


Perform a set operation to an SNMP agent given a handle to a VarBind structure which should have been
prepared already.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 39 - SNMP Functions - 543

Syntax:
Bool SnmpSet (String Destination, Int Port, Int Timeout, String Community, VarBind Handle)
Destination is the address of the host the message is sent to.
Port is the port number on which the agent runs (usually 161).
Timeout is the time-out value in seconds used when opening a connection or waiting for a response from
the SNMP agent.
Community is the community string used when sending SNMP messages to the management station.
Handle is the handle to the variable list to be used in the access.
Returns:
TRUE if the function was successful, FALSE if it failed.
Comments:
If the function is successful, the supplied VarBind is updated with the read values. The function can fail if the
supplied handle is not valid, or if the BCM/SNMP agent is not running on the machine.
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars. The function causes the Chilli interpreter to contact the BCM agent or the SNMP agent and try
and perform a Set operation in a very similar manner to incoming network requests.

SnmpSetOid
Set the Object ID in a variable list using a string.
Syntax:
Bool SnmpSetOid (VarBind Handle, Int Index, String Oid)
Handle is the handle to the variable list to be written to. It must be a value returned by SnmpCreateVars.
Index is the index of the variable binding in the variable list to be set or modified, starting at 1 for the first
one.
Oid is the complete Oid to write to the indexed VarBind. It must consist of a set of valid integers separated
by stop marks (.).
Returns:
TRUE if the function was successful, FALSE if it failed. The function can fail if the supplied handle is not valid, if
the VarBind supplied is 0 or larger than the number of VarBinds in the list, or if the supplied string is not valid.
Comments:
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars. The supplied Oid string has to be a valid textual representation of an SNMP object Id. It should
be a sequence of integer values separated by dots (.) for example 1.2.3 or 12.
Example:
The example below shows an OID with 10 elements or SubIds.
''1.3.6.1.4.2.976.1.2.1''

SnmpSetOidLength
Set the length (number of elements) in an Object ID in a variable list.
Syntax:
Bool SnmpSetOidLength (VarBind Handle, Int Index, Int Length)
Handle is the handle to the variable list to be written to. It must be a value returned by SnmpCreateVars.
Index is the index of the variable binding to be modified, starting at 1 for the first one.
Length is the new value for the number of SubIds.

Numara Software, Inc. and BMC Software, Inc. Confidential.


544 - BMC FootPrints Asset Core - Chilli Reference

Returns:
TRUE if the operation was successful, FALSE if the function failed. The function can fail if the supplied handle is
not valid, if the VarBind supplied is 0 or larger than the number of VarBinds in the list, or if the supplied
SubIds count is larger than the maximum of 256.
Comments:
The length should be set before the terms of the OID are set. The length value represents the number of terms
(SubIds) in the OID.
Changing the number of elements in an Object Id, especially to a higher value, invalidates the Oid. The additional
elements in the Oid have to be set using SnmpSetSubid.
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars. The number of SubIds in an Oid represents the number of terms in the Oid.

Example:
The example below shows an OID with 10 elements or SubIds.
''1.3.6.1.4.2.976.1.2.1''

SnmpSetSubid
Set the integer value of one of the elements in an Object ID in a variable list.
Syntax:
Bool SnmpSetSubid (VarBind Handle, Int Index, Int SubIdIndex, Int SubId)
Handle is the handle to the variable list to be written to. It must be a value returned by SnmpCreateVars.
Index is the index of the variable binding to be modified, starting at 1 for the first variable.
SubIdIndex is the index of the subid in the Oid to be set, starting at 1 for the first element.
SubId is the actual SubId value to be written.
Returns:
If the operation was successful, it returns TRUE. If the functions failed, it returns FALSE. The function can fail if
the supplied handle is not valid, if the VarBind supplied is 0 or larger than the number of VarBinds in the list,
or if the SubId index is larger than the number of elements in the indexed Oid.
Comments:
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars. The number of SubIds in an Oid represents the number of terms in the Oid.

Example:
The example below shows an OID with 10 elements or SubIds.
''1.3.6.1.4.2.976.1.2.1''

SnmpSetValueType
Set the type of the value of one of the variables in the supplied VarBind structure.
Syntax:
Bool SnmpSetValueType (VarBind Handle, Int Index, Int Type)
Handle is the handle to the variable list. It must be a value returned by SnmpCreateVars.
Index is the index of the variable binding to be set, starting at 1 for the first variable.
Type is the type of the value to be set to.
Returns:
TRUE if the operation was successful, FALSE if the function failed.
Comments:
The supplied index starts at 1 for the first variable.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 39 - SNMP Functions - 545

The type of a variable should be set before its value otherwise the SnmpSetVarValue does not 'know' how to
interpret the value being set. The type value should be one of the SNMP_xxx constants such as SNMP_INT or
SNMP_IPADDR. For a complete list of these constants refer to heading Predefined Constants earlier in this chapter.

SnmpSetVarValue
Set the value of a variable binding in a variable list. This function has the following signatures:
Syntax:
Bool SnmpSetVarValue (VarBind Handle, Int Index, Int Value)
Bool SnmpSetVarValue (VarBind Handle, Int Index, String Value)
Handle is the handle to the variable list to be written to. It must be a value returned by SnmpCreateVars.
Index is the index of the variable binding to be changed, starting at 1 for the first variable.
Value is the integer or string value to be written.
Returns:
If the function was successful, it returns TRUE. If the functions failed it returns FALSE. The function can fail if
the supplied handle is not valid, or if the VarBind supplied is 0 or larger than the number of VarBinds in the
list.
Comments:
The type of a variable should be set before using the SnmpSetValueType function. If this is not done, the
supplied values are interpreted as SNMP_INT.
The supplied handle is verified and causes the function to fail if it is not the same as the value returned by
SnmpCreateVars. The supplied Value can be a string or an integer. The function automatically determines the
type and writes the correct value to the VarBind. The maximum length of a string value is 1024 characters.
Strings longer than this limit causes the function to fail.

39.6 Structure Based SNMP Functions


The structure based SNMP Chilli functions can run in any environment and talk to any SNMP agent and
management station.
Following you find the complete list of functions available in this module:

Function OS Description
SnmpGet Perform a get operation from an SNMP agent given an array of variables containing the
object to be read
SnmpGetNext Perform a getnext operation from an SNMP agent given an array of variables containing
the object to be read
SnmpOidToString Convert an OID value in an SnmpOid structure to its ASCII representation as a string

SnmpSendTrap Send a trap to an SNMP management station

SnmpSet Perform a set operation to an SNMP agent given an array of variables containing the
object to be written
SnmpStringToOid Convert an OID value expressed as a string into an SnmpOid structure

SnmpGet
Perform a get operation from an SNMP agent given an array of variables containing the object to be read.
Syntax:
SnmpVarBind[] SnmpGet (String Destination, Int Port, Int Timeout, String Community,
VarBind[] Variables)
Destination is the address of the host the message is sent to.
SNMP_port is the port number on which the agent runs (usually 161).

Numara Software, Inc. and BMC Software, Inc. Confidential.


546 - BMC FootPrints Asset Core - Chilli Reference

Timeout is the time-out value in milliseconds used when opening a connection or waiting for a response
from the SNMP agent.
Community is the community string used when sending SNMP messages to the management station.
VarBind is the list of variables to get.
Returns:
An array of SnmpVarBind structures containing the SNMP variable bindings if the operation was successful, or
an empty array if the function failed. If the operation fails, the ErrCode is set to one of the SNMP error codes
which are listed at the end of the chapter.
Comments:
The SnmpGet function is used by a management system to retrieve values from the managed objects maintained
by the agent, whereby the values of one or more MIB variables can be requested at one time. These variables can
be located in different MIBs, but all of them must be supported by the agent that receives the SnmpGet request.
The returned SnmpVarBind is a duplicate of the VarBind in the request with the object values updated by the
SnmpGet function.

Example:
The example below gets the Windows Major and Minor OS version on the current host. It also contains error
handling.
/**************************************************************************************
Get the Windows Major and Minor OS version on the current host. The Procedure contains
error handling.
**************************************************************************************/
proc main ()
SnmpVarBind elem
SnmpVarBind reply[]
SnmpVarBind handle[]

elem.ObjectId = SnmpStringToOid ("1.3.6.1.4.1.976.2.1.10.11.1.0")


print ("Oid IS " + SnmpOidToString (elem.ObjectId) + "\n")
handle <<= elem
ErrHandler = INLINE_HANDLER
reply = SnmpGet (GetHostName (), 161, 2, "public", handle)
if (ErrCode != ERR_SUCCESS)
print ("SnmpGet failed: " + \GetErrorName (ErrCode) + " - " +
GetErrorText (ErrCode) + \"\n")
exit ()
endif
print ("Windows OS major number: " + reply[1].ObjectValue.IntegerValue + "\n")
handle = reply
reply = SnmpGetNext (GetHostName (), 161, 2, "public", handle)
if (ErrCode != ERR_SUCCESS)
print ("SnmpGet failed: " + \
GetErrorName (ErrCode) + " - " + GetErrorText (ErrCode) + \"\n")
exit ()
endif
print ("Windows OS minor number: " + reply[1].ObjectValue.IntegerValue + "\n")
ErrHandler = DEFAULT_HANDLER
endproc

SnmpGetNext
Perform a getnext operation from an SNMP agent given an array of variables containing the object to be read.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 39 - SNMP Functions - 547

Syntax:
SnmpVarBind[] SnmpGetNext (String Destination, Int Port, Int Timeout, String Community,
VarBind[] Variables)
DestinationName is the address of the host the message is sent to.
SNMP_port is the port number on which the agent runs (usually 161).
Timeout is the time-out value in seconds used when opening a connection or waiting for a response from
the SNMP agent.
Community is the community string used when sending SNMP messages to the management station.
VarBind is the list of variables to get next.
Returns:
An array of SnmpVarBind structures containing the SNMP variable bindings if the operation was successful, or
an empty array if the function failed. If the operation fails, the ErrCode is set to one of the SNMP error codes,
which are listed at the end of the chapter.
Comments:
The SnmpGetNext function is used to retrieve values from the managed objects maintained by the agent, and is
similar to the SnmpGet function in behavior and format. If the supplied VarBind is valid, the agent fills in the
values of the individual VarBinds and returns. The only difference between this function and the SnmpGet
function is that for each OID in the VarBind the agent actually reads the next readable object in the MIB tree that
it supports, as per SNMP standard. The returned SnmpVarBind does not only have the read values, but the OIDs
has been changed to those of the MIB objects which were read as a result of the SnmpGetNext operation.
Example:
The example below gets the Windows Major and Minor OS version on the current host. It also contains error
handling.
/**************************************************************************************
Get the Windows Major and Minor OS version on the current host. The Procedure contains
error handling.
**************************************************************************************/
proc main ()
SnmpVarBind elem
SnmpVarBind reply[]
SnmpVarBind handle[]

elem.ObjectId = SnmpStringToOid ("1.3.6.1.4.1.976.2.1.10.11.1.0")


print ("Oid IS " + SnmpOidToString (elem.ObjectId) + "\n")
handle <<= elem
ErrHandler = INLINE_HANDLER
reply = SnmpGet (GetHostName (), 161, 2, "public", handle)
if (ErrCode != ERR_SUCCESS)
print ("SnmpGet failed: " + \
GetErrorName (ErrCode) + " - " + GetErrorText (ErrCode) + \"\n")
exit ()
endif
print ("Windows OS major number: " +
reply[1].ObjectValue.IntegerValue + "\n")
handle = reply
reply = SnmpGetNext (GetHostName (), 161, 2, "public", handle)
if (ErrCode != ERR_SUCCESS)
print ("SnmpGet failed: " + \
GetErrorName (ErrCode) + " - " + GetErrorText (ErrCode) + \"\n")
exit ()
endif
print ("Windows OS minor number: " + reply[1].ObjectValue.IntegerValue + "\n")
ErrHandler = DEFAULT_HANDLER

Numara Software, Inc. and BMC Software, Inc. Confidential.


548 - BMC FootPrints Asset Core - Chilli Reference

endproc

SnmpOidToString
Convert an OID value in an SnmpOid structure to its ASCII representation as a string.
Syntax:
String SnmpOidToString (SnmpOid Oid)
Oid is the OID value to be converted in its ASCII representation as a string.
Returns:
A string in ASCII format which is the representation of the SnmpOid if the operation was successful or 0 if the
operation failed. If the operation fails, the ErrCode is set to one of the SNMP error codes, which are listed at the
end of the chapter.
Example:
The example below gets the number of applications running on the host after converting the OID
1.3.6.1.4.1.976.2.1.13.4.1.0 into its string equivalent.
proc main ()

SnmpVarBind elem
SnmpVarBind reply[]
SnmpVarBind handle[]

elem.ObjectId = SnmpStringToOid (’1.3.6.1.4.1.976.2.1.1.1.0’)


print(LogFile, "OID "+SnmpOidToString(elem.ObjectId)+" has the following
value:\r\n")

handle <<= elem

reply = SnmpGet (GetHostName(), 161, 200, "public", handle)

Print (LogFile, ’handle[1].ObjectValue.IntegerValue’)

endproc

SnmpSendTrap
Send a trap to an SNMP management station given an array of VarBind structures.
Syntax:
Bool SnmpSendTrapToHost (String Destination, Int TrapPort, String Community, String
EnterpriseOID, Int GenericId, Int SpecificId, VarBind[] Variables)
Destination is the address of the host the message is sent to.
TrapPort is the port number on which the management station listens for incoming trap messages (usually
162).
Community is the community string used when sending SNMP messages to the management station.
EnterpriseOID is the OId of the management enterprise that defines the trap message.
GenericId defines the standard type of the trap message.
SpecificId defines the type of the specific enterprise trap message.
Variables is the list of trap variables.
Returns:
TRUE if the operation was successful, FALSE if the trap could not be sent. If the operation fails, the ErrCode is set
to one of the SNMP error codes, which are listed earlier in this chapter.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 39 - SNMP Functions - 549

Comments:
A trap message is an unrequested event report message that is sent from an SNMP agent to a management station
indicating that some predefined condition or event has occurred. The variable bindings stored in the data of the
trap contain the identity and values of the MIB variables that provide information about the specific event. All
MIB variables in the SnmpTrapPdu must reside within the MIB supported by the agent that generated the trap.
The standard trap type defines the type of the trap message. It can be one of the following values:

Value Error
0 coldStart
1 warmStart
2 linkDown
3 linkUp
4 authenticationFailure
5 egpNeighborLoss
6 enterpriseSpecific

If the value in the standard trap type field is other than 6 the specific trap type value is 0 and is not used. If the
standard trap type is identified as 6/enterprise specific trap type in the standard trap type this field contains a
value greater than zero (0). This specifies which trap type object in the MIB identified in the Enterprise MIB OID
field defines this trap PDU.
Example:
The example below sends the BMC specific trap 10200 with three string values.
/*************************************************
Sending BMC specific trap 10200 with three string values.
*************************************************/
proc main ()

string szDestinationName
int iTrapPort
string szCommunity
string szOID
int iStdType
int iSpecType
SnmpVarBind varBindList[3]

int iResult

szDestinationName = "hauraki"
iTrapPort = 162
szCommunity = "public"
szOID = "1.3.6.1.4.1.976"
iStdType = 6
iSpecType = 10200

varBindList[1].ObjectValue.ValueType = SNMP_STR
varBindList[1].ObjectValue.StringValue = "first string"

varBindList[2].ObjectValue.ValueType = SNMP_STR
varBindList[2].ObjectValue.StringValue = "second string"

varBindList[3].ObjectValue.ValueType = SNMP_STR
varBindList[3].ObjectValue.StringValue = "third string"

iResult = SnmpSendTrap (szDestinationName, iTrapPort, szCommunity, szOID, iStdType,


iSpecType, varBindList)

MessageBox ("Trap Sent", "Result: " + iResult, "OK")

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


550 - BMC FootPrints Asset Core - Chilli Reference

SnmpSet
Perform a set operation to an SNMP agent given an array of variables containing the object to be written to.
Syntax:
SnmpVarBind[] SnmpSet (String DestinationName, Int SNMP_port, Int Timeout, String Community,
SnmpVarBind[] VarBindList)
DestinationName is the address of the host the message is sent to.
SNMP_port is the port number on which the agent runs (usually 161).
Timeout is the time-out value in seconds used when opening a connection or waiting for a response from
the SNMP agent.
Community is the community string used when sending SNMP messages to the management station.
VarBindList is the list of variables to set.
Returns:
An SnmpVarBind array containing the SNMP variable bindings if the operation was successful, or an empty array
if the function failed. If the operation fails, the ErrCode is set to one of the SNMP error codes, which are listed at
the end of the chapter. The function can fail if there is no SNMP service running on the remote host, or if the
VarBind supplied is 0 or larger than the number of VarBinds in the list.

Comments:
The SnmpSet function is used to modify the management data maintained by the agent. It contains one VarBind
per MIB variable value to set, which in turn contains an OID with the identifier of the variable to set and the new
value. If no processing errors occur, each of the new values is assigned to its respective MIB variable. If an error
occurs NONE of the values is assigned.
Example:
The example below starts the calculator application on the current host and contains error handling.
/*************************************************
Start Calc on the current host. The Procedure contains error handling.
*************************************************/
proc main ()
SnmpVarBind elem
SnmpVarBind reply[]
SnmpVarBind handle[]

elem.ObjectId = SnmpStringToOid ("1.3.6.1.4.1.976.2.1.13.4.2.0")


elem.ObjectValue.ValueType = SNMP_STR
elem.ObjectValue.StringValue = "calc"
print ("Oid is: " + SnmpOidToString (elem.ObjectId) + "\n")
handle <<= elem

ErrHandler = INLINE_HANDLER
SnmpSet (GetHostName (), 161, 2, "public", handle)
if (ErrCode != ERR_SUCCESS)
print ("SnmpSet failed: " + GetErrorName (ErrCode) + " - " +
GetErrorText (ErrCode) + "\n")
exit ()
else
print ("SnmpSet succeeded\n")
endif
ErrHandler = DEFAULT_HANDLER
endproc

SnmpStringToOid
Convert an OID value expressed as a string into an SnmpOid structure.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 39 - SNMP Functions - 551

Syntax:
SnmpOid SnmpStringToOid (String OID)
Oid is the OID value expressed in the form of a string.
Returns:
An SnmpOid structure containing the OID value corresponding to the supplied ASCII representation if the
operation was successful, or an empty structure if the operation failed. If the operation fails, the ErrCode is set to
one of the SNMP error codes, which are listed at the end of the chapter.
Example:
The example below converts the string "1.3.6.1.4.1.976.2.1.13.4.1.0" into its OID equivalent.
proc main ()

SnmpVarBind elem

elem.ObjectId = SnmpStringToOid ("1.3.6.1.4.1.976.2.1.1.1.0")

print(LogFile, "OID "+SnmpOidToString(elem.ObjectId)+" has the


following value:\r\n")

endproc

39.7 Examples
Following you find a number of examples on how to use the SNMP functions within BMC Software products.
Example 1:
/*************************************************************************
This functions sends a DGM trap with an integer value that is used to
add or subtact models from groups. Works from chilli 2.5.
***************************************************************************/

proc SendDGMTrap (int TrapParam)


string szDestinationName
int iTrapPort
string szCommunity
string szOID
int iStdType
int iSpecType
SnmpVarBind varBindList[1]
int iResult

szDestinationName = "194.7.204.216"
iTrapPort = 162
szCommunity = "public"
szOID = "1.3.6.1.4.1.976.2.1.1"
iStdType = 6
iSpecType = 225

varBindList[1].ObjectValue.ValueType = SNMP_INT
varBindList[1].ObjectValue.IntegerValue = TrapParam
varBindList[1].ObjectId = SnmpStringToOID (szOID)

iResult = SnmpSendTrapToHost (szDestinationName, iTrapPort, szCommunity,


szOID, iStdType, iSpecType, varBindList)

MessageBox ("Trap Sent", "Result: " + iResult, "OK")

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


552 - BMC FootPrints Asset Core - Chilli Reference

;*************************************************************************
; Main procedure sending the DGM code 800.
;*************************************************************************

proc main ()

SendDGMTrap (800)

endproc

Example 2:
proc PrintOid (SnmpOid Oid)

int i;

for (i=1; i<=ArrayGetSize (Oid.Subids); i+=1)


print (MakeStr (Oid.Subids[i]) + ".")
endfor

endproc

proc main ()

int error;
string szAddress, szMail
SnmpOid Oid;
SnmpVarBind VarBind[1];

// ErrHandler = INLINE_HANDLER;

print ("Starting SNMP test...\n");

Oid = SnmpStringToOid ("1.4.6.1.3.976.2.1.0")


PrintOid (Oid);
print ("\n");

print ("After 2nd conversion: " + SnmpOidToString (Oid) + "\n")

VarBind[1].Objectid = SnmpStringToOid ("1.3.6.1.4.1.976.2.10.1.1.1.0");

VarBind = SnmpGetNext ("picsou", 1612, 4, "public", VarBind);


// VarBind = SnmpGet ("gromit", 161, 2, "public", VarBind);

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


SQL Database Functions

This chapter in the Chilli Reference explains in detail all functions permitting generic access to SQL databases
such as MySQL and Postgres. All functions of this module are included in the gensql.chx file for Windows or
gensql.so file for UNIX and Linux.

40.1 Introduction
The Chilli Generic SQL group provides a set of functions to manage SQL commands to multiple databases with
different types. The currently supported DBMSs are PostgreSQL and MySQL. The functions of the present module
allow you to query the database and extract data from it. Through the queries you can create, delete, modify,
update, and so on, data and tables in the databases.
Chilli also provides access to other databases through the ODBC Functions on page 313 earlier in this manual.

40.2 Predefined Constants


Following you find the complete list of all predefined constants of the generic SQL functions group of the Chilli
language:

Name Type Description


DBTYPE Integer Define the type of the database server to which a connection is to be opened.
DATATYPE Integer Define the data type of a column in a database table.

DBTYPE
This constant defines the type of the database server to which a connection is to be opened. It can be one of the
following two values:

Name Type Description


GENSQL_DBTYPE_INVALID Integer The type of the database server is invalid.
GENSQL_DBTYPE_MYSQL Integer The database server is of type MySQL.
GENSQL_DBTYPE_ODBC Integer The database server is of type ODBC.
GENSQL_DBTYPE_POSTGRES Integer The database server is of type Postgres.
GENSQL_DBTYPE_ORACLE Integer The database server is of type Oracle.
GENSQL_DBTYPE_SQLSERVER Integer The database server is of type SQL Server.
GENSQL_DBTYPE_SQLITE Integer The database server is of type SQLite.
GENSQL_DBTYPE_SQLITE3 Integer The database server is of type SQLite3.

DATATYPE
This constant defines the data type of a column in a database table. It can be one of the following values:

Numara Software, Inc. and BMC Software, Inc. Confidential.


554 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


DATATYPE_BIGINT Integer A large integer. The signed range is -9223372036854775808 to
9223372036854775807. The unsigned range is 0 to 18446744073709551615.
As all arithmetic is done using signed BIGINT or DOUBLE values, so you shouldn't use
unsigned big integers larger than 9223372036854775807 (63 bits) except with bit
functions! If you do that, some of the last digits in the result can be wrong because of
rounding errors when converting the BIGINT to a DOUBLE.
You can always store an exact integer value in a BIGINT column by storing it as a string,
because in this case there is no intermediate double representation.
`-', `+', and `*' use BIGINT arithmetic when both arguments are INTEGER values! This
means that if you multiply two big integers (or results from functions that return integers)
you might get unexpected results when the result is larger than 9223372036854775807.
DATATYPE_BINARY Integer A fixed length text string (case-insensitive). Any input that is shorter than the length is
padded with spaces at the end. Any trailing spaces are removed when outputting values.
The BINARY type is equivalent to CHAR with the BINARY modifier.
DATATYPE_BIT Integer This datatype is a synonym for the CHAR datatype.
DATATYPE_CHAR Integer A fixed-length string that is always right-padded with spaces to the specified length when
stored. The range of M is 1 to 255 characters. Trailing spaces are removed when the value
is retrieved. CHAR values are sorted and compared in case-insensitive fashion according
to the default character set unless the BINARY keyword is given.
DATATYPE_DATE Integer A date. The supported range is '1000-01-01' to '9999-12-31'. It displays DATE values in
'YYYY-MM-DD' format, but allows you to assign values to DATE columns using either
strings or numbers.
DATATYPE_DATETIME Integer A date and time combination. The supported range is '1000-01-01 00:00:00' to '9999-12-31
23:59:59'. It displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format, but allows
you to assign values to DATETIME columns using either strings or numbers.
DATATYPE_DECIMAL Integer An unpacked floating-point number. Cannot be unsigned. Behaves like a CHAR column:
“unpacked” means the number is stored as a string, using one character for each digit of
the value. The decimal point and, for negative numbers, the `-' sign, are not counted in M
(but space for these are reserved). If D is 0, values has no decimal point or fractional part.
The maximum range of DECIMAL values is the same as for DOUBLE, but the actual range
for a given DECIMAL column can be constrained by the choice of M and D. If D is left out
it's set to 0. If M is left out it's set to 10. Note that in MySQL Version 3.22 the M argument
had to includes the space needed for the sign and the decimal point.
DATATYPE_DOUBLE Integer A normal-size (double-precision) floating-point number. Cannot be unsigned. Allowable
values are -1.7976931348623157E+308 to -2.2250738585072014E-308, 0, and
2.2250738585072014E-308 to 1.7976931348623157E+308. The M is the display width
and D is the number of decimals. DOUBLE without an argument or FLOAT(X) where 25 <=
X <= 53 stands for a double-precision floating-point number.
DATATYPE_FLOAT Integer A small (single-precision) floating-point number. Cannot be unsigned. Allowable values are
-3.402823466E+38 to -1.175494351E-38, 0, and 1.175494351E-38 to
3.402823466E+38. The M is the display width and D is the number of decimals. FLOAT
without an argument or with an argument of <= 24 stands for a single-precision floating-
point number.
DATATYPE_INTEGER Integer An integer. The signed range is -2147483648 to 2147483647. The unsigned range is 0 to
4294967295.
DATATYPE_LONGVARBINARY Integer A binary field with a maximum length of 64 KB of text.
DATATYPE_LONGVARCHAR Integer A text field with a maximum length of 64 KB of text.
DATATYPE_NULL Integer The fields in this column can contain NULL values.
DATATYPE_NUMERIC Integer This datatype is a synonym for the DECIMAL type.
DATATYPE_REAL Integer This datatype is a synonym for the DOUBLE type.
DATATYPE_SMALLINT Integer A small integer. The signed range is -32768 to 32767. The unsigned range is 0 to 65535.
DATATYPE_TIME Integer A time. The range is '-838:59:59' to '838:59:59'. It displays TIME values in 'HH:MM:SS'
format, but allows you to assign values to TIME columns using either strings or numbers.
DATATYPE_TIMESTAMP Integer A timestamp. The range is '1970-01-01 00:00:00' to sometime in the year 2037. It displays
TIMESTAMP values in YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD, or YYMMDD
format, depending on whether M is 14 (or missing), 12, 8, or 6, but allows you to assign
values to TIMESTAMP columns using either strings or numbers.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 40 - SQL Database Functions - 555

Name Type Description


DATATYPE_TINYINT Integer A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.
DATATYPE_UNKNOWN Integer The data type of the column is not known or not supported.
DATATYPE_VARBINARY Integer A variable-length text string (case-insensitive) with a predefined maximum length. The
maximum length must be between 1 and 255 characters. Any trailing spaces are removed
before storing data of this type. The VARBINARY type is equivalent to VARCHAR with the
BINARY modifier.
DATATYPE_VARCHAR Integer A variable-length string. Trailing spaces are removed when the value is stored (this differs
from the ANSI SQL specification). The range of M is 1 to 255 characters. VARCHAR values
are sorted and compared in case-insensitive fashion unless the BINARY keyword is given.

40.3 Error Codes


Following you find a list of all generic SQL error codes. These errors are run-time errors that causes the handler
specified in ErrorHandler to be invoked. Functions can return these in addition to the standard runtime errors
such as FUNCFAILED. You will find a list with all runtime errors in Appendix E - Chilli Error Codes on page 677 at
the end of the manual.

Name Description
ERR_BADLIBRARY Missing or incorrect database library DLL
ERR_BADHOSTNAME Host name or IP address not found
ERR_CONNFAIL Failed to connect to server
ERR_CONNLOST Connection to server lost or timed-out
ERR_NOMEMORY Not enough memory for the operation
ERR_BADDBNAME Database name invalid or not found
ERR_ACCESSDENIED Access denied to database or table
GENSQL_ERR_INTERNAL Internal error in the library
GENSQL_ERR_BADPARAM Parameter error in a call
GENSQL_ERR_BADSQL Error in an SQL statement passed to the server
GENSQL_ERR_BADCOLUMNORDER Columns are not being accessed in increasing column order

40.4 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli generic SQL function group has Predefined Handle Data Types.

40.4.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


GenSqlConnection Object type: reference to the current SQL connection handle
GenSqlResult Object type: reference to the current SQL result handle

GenSqlConnection
The GenSqlConnection data type is a reference to the handle of an open sql connection.

Numara Software, Inc. and BMC Software, Inc. Confidential.


556 - BMC FootPrints Asset Core - Chilli Reference

The function GenSqlConnect returns a value of this object type that some other functions expect as their first
argument. Any open connection and thus the value of this object type should always be closed by the
GenSqlClose function.

GenSqlResult
The GenSqlResult data type is a reference to the handle of a sql result object.
The function GenSqlQuery returns a value of this object type that many of the other functions expect as their
first argument. Any open result object and thus the value of this object type should always be closed by the
GenSqlFreeResult function.

40.5 Functions
Following you find a complete list of all generic SQL database functions:

Function OS Description
GenSqlClose Close the connection specified by the supplied handle

GenSqlConnect Perform a connect to the specified server

GenSqlFirstRow Move the current row index within the result object to the first one

GenSqlFreeResult Close the GenSqlResult handle of a result object

GenSqlGetColumnCount Return the number of columns in the supplied result

GenSqlGetColumnName Get the name of a column in the supplied result

GenSqlGetColumnType Return an integer to identify the data type of a column given its index

GenSqlGetColumnValueByIndex Get the value of a column in the current row of the result set

GenSqlGetErrorText Return the database specific error message for the supplied result or connection

GenSqlGetRowCount Return the number of rows in the supplied result object

GenSqlIsFirstRow Check whether the current row being examined in the result set is the first row or not

GenSqlIsLastRow Check whether the current row being examined in the result set is the last row or not

GenSqlListColumns Get the list of columns in a table in the connected database

GenSqlListTables Get the list of tables in the connected database

GenSqlNextRow Move the current row index within the result object to the next one

GenSqlPreviousRow Move the current row index within the result object to the previous one

GenSqlQuery Execute an SQL query on the supplied connection

GenSqlSeekRow Move the current row index within the result object to the number specified

GenSqlSqlite3ToHtml Convert an Sqlite database to a human readable HTML file

GenSqlSqliteToSqlite3 Convert an Sqlite database to its Sqlite3 equivalent

GenSqlClose
Close the connection specified by the supplied handle.
Syntax:
Bool GenSqlClose (GenSqlConnection Connection)
Connection is the handle to the connection to be closed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 40 - SQL Database Functions - 557

Returns:
TRUE if the operation was successful, FALSE if an error occurred.
Comments:
After this call, if successful or not, the handle is invalid and can not be used for any other operations.

GenSqlConnect
Perform a connect to the specified server given the server type, name, database and user login and password.
Syntax:
GenSqlConnection GenSqlConnect (Int DbType, String Host, String Database, String
UserName, String Password)
DbType is the type of the database server to which a connection is to be opened. It can be any of the DBTYPE
values mentioned in paragraph Predefined Constants earlier in this chapter.
Host is the name of the server on which resides the database.
Database is the name of the database.
UserName is the login name of the user to be used for the connection.
Password is the respective password for the user login.
Returns:
A connection handle of type GenSqlConnection if the operation was successful, 0 if the operation failed.
Comments:
The requested database server type must match the actual server being connected to otherwise the function fails.

GenSqlFirstRow
Move the current row index within the result object to the first one.
Syntax:
Bool GenSqlFirstRow (GenSqlResult Result)
Result is the handle to the result object to be read.
Returns:
TRUE if the operation was successful, FALSE if it failed or an error occurred.
Comments:
If the current row is already the first one, the function returns TRUE.

GenSqlFreeResult
Close the GenSqlResult handle of a result object.
Syntax:
Bool GenSqlFreeResult (GenSqlResult Result)
Result is the handle to the result object to be closed.
Returns:
TRUE if the operation was successful, or FALSE if it failed or an error occurred.
Comments:
The result returned from a query should be closed as soon as it is no longer required to keep the memory usage of
the Chilli environment from growing excessively.
After this function has executed, successful or not, the handle iscome invalid and can not be used for any other
operations.

Numara Software, Inc. and BMC Software, Inc. Confidential.


558 - BMC FootPrints Asset Core - Chilli Reference

GenSqlGetColumnCount
Return the number of columns in the supplied result object.
Syntax:
Int GenSqlGetColumnCount (GenSqlResult Result)
Result is the handle to the result object to be read.
Returns:
The number of columns in the result object if the operation was successful or 0 in case of error.

GenSqlGetColumnName
Get the name of a column in the supplied result.
Syntax:
String GenSqlGetColumnName (GenSqlResult Result, Int ColumnNumber)
Result is the handle to the result object to be read.
ColumnNumber is the number of the column for which the name is to be checked.
Returns:
The name of the indexed column in the result object if the operation was successful or an empty string in case of
error.
Comments:
Column numbers start at 0 for the first column.

GenSqlGetColumnType
Return an integer to identify the data type of a column given its index.
Syntax:
Int GenSqlGetColumnType (GenSqlResult Result, Int ColumnNumber)
Result is the handle to the result object to be read.
ColumnNumber is the index number of the column for which the type is to be checked.
Returns:
An integer value identifying the data type of the indexed column in the result object if the operation was
successful, or 0 if the operation failed or an error occurred. The type can be any of the DATATYPE values
mentioned in paragraph Predefined Constants earlier in this chapter.
Comments:
Column numbers start at 0 for the first column.

GenSqlGetColumnValueByIndex
Get the value of a column in the current row of the result set.
The function has the following signatures:
Syntax:
String GenSqlGetColumnValueByIndex (GenSqlResult Result, Int ColumnNumber)
String GenSqlGetColumnValueByIndex (GenSqlResult Result, String ColumnName)
Result is the handle to the result object to be read.
ColumnNumber is the number of the column for which the value is to be checked.
ColumnName is the name of the column for which the value is to be checked.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 40 - SQL Database Functions - 559

Returns:
The value of the column as a string if the operation was successful or an empty string if the column was not
found, an error occurred or the function failed. Note that an empty string might be a valid value, therefore the
error status must be checked.
Comments:
For the signature using the column number it accesses the column by using its 0 based index. For the signature
using the column name it accesses the column by using its name which is case insensitive.
Example:
proc DumpResult (GenSqlResult result)
print ("Result has " + MakeStr (GenSqlGetRowCount (result)) + " rows\n")
int i;
for (i=0; i<GenSqlGetRowCount (result); i+=1)
GenSqlSeekRow (result, i);
print (GenSqlGetColumnValue (result, 0) + "\n")
endfor
endproc

GenSqlGetErrorText
Return the database specific error message for the supplied result or connection.
The function has the following signatures:
Syntax:
String GenSqlGetErrorText (GenSqlResult Result)
String GenSqlGetErrorText (GenSqlConnection Connection)
Result is the handle to the result object.
Connection is the handle to the connection.
Returns:
The last error text if the operation was successful or an empty string if the function failed.
Comments:
When the result is first returned for a query this is the same as the LastError value for the connection. The
difference is that this value does not change whereas the LastError of the connection changes with every operation
on that connection.

GenSqlGetRowCount
Return the number of rows in the supplied result object.
Syntax:
Long GenSqlGetRowCount (GenSqlResult Result)
Result is the handle to the result object to be read.
Returns:
The number of rows in the result object if the operation was successful, or 0 if the operation failed or an error
occurred.
Example:
proc DumpResult (GenSqlResult result)
print ("Result has " + MakeStr (GenSqlGetRowCount (result)) + " rows\n")
int i;
for (i=0; i<GenSqlGetRowCount (result); i+=1)
GenSqlSeekRow (result, i);
print (GenSqlGetColumnValue (result, 0) + "\n")
endfor
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


560 - BMC FootPrints Asset Core - Chilli Reference

GenSqlIsFirstRow
Checks whether the current row being examined in the result object is the first row.
Syntax:
Bool GenSqlIsFirstRow (GenSqlResult Result)
Result is the handle to the result object to be read.
Returns:
TRUE if the current row is the first one, FALSE otherwise.

GenSqlIsLastRow
Check whether the current row being examined in the result object is the last row.
Syntax:
Bool GenSqlIsLastRow (GenSqlResult Result)
Result is the handle to the result object to be read.
Returns:
TRUE if the current row is the last one, FALSE otherwise.

GenSqlListColumns
Get the list of columns in a table in the connected database.
Syntax:
String[] GenSqlListColumns (GenSqlConnection Connection, String TableName)
Connection is the handle to the connection to be read.
TableName is the name of the table to be read.
Returns:
An array of strings containing the found table column names if the operation was successful or an empty array if
the function failed or an error occurred.

GenSqlListTables
Get the list of tables in the connected database.
Syntax:
String[] GenSqlListTables (GenSqlConnection Connection)
Connection is the handle to the connection to be read.
Returns:
An array of strings containing the found table names if the operation was successful or an empty array if the
function failed or an error occurred.

GenSqlNextRow
Move the current row index within the result object to the next one.
Syntax:
Bool GenSqlNextRow (GenSqlResult Result)
Result is the handle to the result object.
Returns:
TRUE if the operation was successful, FALSE if an error occurred or the current row was already the last one.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 40 - SQL Database Functions - 561

GenSqlPreviousRow
Move the current row index within the result object to the previous one.
Syntax:
Bool GenSqlPreviousRow (GenSqlResult Result)
Result is the handle to the result object to be read.
Returns:
TRUE if the operation was successful, FALSE if an error occurred or the current row was already the first one.

GenSqlQuery
Execute an SQL query on the supplied connection.
Syntax:
GenSqlResult GenSqlQuery (GenSqlConnection Connection, String Query)
Connection is the handle to the connection to be closed.
Query contains the query for the database.
Returns:
A handle to the result object containing the result of the query if the operation was successful, 0 if the operation
failed.
Comments:
The returned value is a handle to a result set which can then be examined row by row using the relevant
functions.

GenSqlSeekRow
Move the current row index within the result object to the number specified.
Syntax:
Bool GenSqlSeekRow (GenSqlResult Result, Long RowNumber)
Result is the handle to the result object to be read.
RowNumber is the number to which the current row index is to be moved to.
Returns:
TRUE of the operation was successful or FALSE if an error occurred such as an incorrect row number or the
function failed.
Comments:
Row numbers start at 0 for the first row.
Example:
proc DumpResult (GenSqlResult result)
print ("Result has " + MakeStr (GenSqlGetRowCount (result)) + " rows\n")
int i;
for (i=0; i<GenSqlGetRowCount (result); i+=1)
GenSqlSeekRow (result, i);
print (GenSqlGetColumnValue (result, 0) + "\n")
endfor
endproc

GenSqlSqlite3ToHtml
Convert an Sqlite database to a human readable HTML file.
Syntax:
Bool GenSqlSqlite3ToHtml (String Src, String Dst)

Numara Software, Inc. and BMC Software, Inc. Confidential.


562 - BMC FootPrints Asset Core - Chilli Reference

Src is the name and path of the source database.


Dst is the name and path of the destination database.
Returns:
TRUE of the operation was successful or FALSE if an error occurred.
Example:
int main ()
string strDbInput, strDbOutput
strDbInput= "C:\\FileStore.sqlite3"
strDbOutput= "C:\\FileStore.html"

# Turn the database into HTML.

GenSqlSqlite3ToHtml (strDbInput, strDbOutput)


return 0
endproc

GenSqlSqliteToSqlite3
Convert an Sqlite database to its Sqlite3 equivalent.
Syntax:
Bool GenSqlSqliteToSqlite3 (String Src, String Dst)
Src is the name and path of the source database.
Dst is the name and path of the destination database.
Returns:
TRUE of the operation was successful or FALSE if an error occurred.
Example:
int main ()
string strDbInput, strDbOutput
strDbInput= "C:\\FileStore.sqlite"
strDbOutput= "C:\\FileStore.sqlite3"

# Turn the database into Sqlite3.

GenSqlSqliteToSqlite3 (strDbInput, strDbOutput)


return 0
endproc

40.6 Example
Example 1:
proc DumpResult (GenSqlResult result)
print ("Result has " + MakeStr (GenSqlGetRowCount (result)) + " rows\n")
int i;
for (i=0; i<GenSqlGetRowCount (result); i+=1)
GenSqlSeekRow (result, i);
print (GenSqlGetColumnValue (result, 0) + "\n")
endfor
endproc

proc main ()
GenSqlConnection conn;
GenSqlResult result;

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 40 - SQL Database Functions - 563

conn = GenSqlConnect (GENSQL_DBTYPE_MYSQL, "gromit", "ddmdb", "spectrum",


"spectrum")
result = GenSqlQuery (conn, "show tables");
DumpResult (result)
endproc

Example 2:
For this to work you must have a live running installed version of MySQL and be aware of the relevant user
name(s) and passwords. You must edit the user name and password supplied below to suit your database
configuration.
Proc Main ()

int i, j

GenSqlConnection conn
GenSqlResult result

string szStatement

ErrHandler = INLINE_HANDLER
DirSetCurrent (PathGetDrive(ScriptFile) + ':' + PathGetDir(ScriptFile))

LogFile = PathGetFileRoot(ScriptFile) + '.log'


Print (LogFile, "******************************************\r\n")

// Create a connection to the database server. In this case MySQL

conn = GenSqlConnect (GENSQL_DBTYPE_MYSQL, "localhost", "mysql", "misuser", "")


if (ErrCode != 0)
Print (LogFile, "Error: Could not connect to MySQL database server\r\n")
Print (LogFile, "Chilli ErrCode: " + MakeStr(ErrCode) + "\r\n")
else
Print (LogFile, "OK: Connected to Mysql Database server - database mysql\r\n")
endif
GenSqlFreeResult(result)

// Start by Creating a brand new database

szStatement = 'Drop Database If Exists MtxSample;'


result = GenSqlQuery (conn, szStatement)
if (ErrCode != 0)
Print (LogFile, "Error: Could not Drop Database MtxSample\r\n")
Print (LogFile, "Chilli ErrCode: " + MakeStr(ErrCode) + "\r\n")
Print (LogFile, "SQL Error text: " + GenSqlGetErrorText(result) + "\r\n")
else
Print (LogFile, "OK: Dropped Database MtxSample\r\n")
endif
GenSqlFreeResult(result)

szStatement = 'Create Database MtxSample;'


result = GenSqlQuery (conn, szStatement)
if (ErrCode != 0)
Print (LogFile, "Error: Could not Create Database MtxSample\r\n")
Print (LogFile, "Chilli ErrCode: " + MakeStr(ErrCode) + "\r\n")
Print (LogFile, "SQL Error text: " + GenSqlGetErrorText(result) + "\r\n")
else
Print (LogFile, "OK: Created new Database MtxSample\r\n")
endif
GenSqlFreeResult(result)

GenSqlClose (conn)

Numara Software, Inc. and BMC Software, Inc. Confidential.


564 - BMC FootPrints Asset Core - Chilli Reference

conn = GenSqlConnect (GENSQL_DBTYPE_MYSQL, "localhost", "MtxSample", "misuser", "")


if (ErrCode != 0)
Print (LogFile, "Error: Could not Connect to database MtxSample\r\n")
Print (LogFile, "Chilli ErrCode: " + MakeStr(ErrCode) + "\r\n")
else
Print (LogFile, "OK: Connected to new database MtxSample\r\n")
endif

// Create a new table in the new database

szStatement = 'CREATE TABLE MtxPC ('


szStatement = szStatement + ' ' + 'PCID VARCHAR (20) PRIMARY KEY, '
szStatement = szStatement + ' ' + 'PCHostName VARCHAR (255),'
szStatement = szStatement + ' ' + 'PCModel VARCHAR (50),'
szStatement = szStatement + ' ' + 'PCManufacturer VARCHAR (50),'
szStatement = szStatement + ' ' + 'PCRAM INT,'
szStatement = szStatement + ' ' + 'PCOSVersionName VARCHAR (20)'
szStatement = szStatement + ' ' + ');'

result = GenSqlQuery (conn, szStatement)


if (ErrCode != 0)
Print (LogFile, "Error: Could not Create Table MtxPC\r\n")
Print (LogFile, "Chilli ErrCode: " + MakeStr(ErrCode) + "\r\n")
Print (LogFile, "SQL Error text: " + GenSqlGetErrorText(result) + "\r\n")
else
Print (LogFile, "OK: Created new table MtxPC\r\n")
endif

GenSqlFreeResult(result)

// Load some sample data into the table

szStatement = 'insert into MtxPC (PCID, PCHostName, PCModel, PCManufacturer, PCRAM, PCOSVersionName) values '
szStatement = szStatement + '( "0001", "Host-0001", "Optiplex", "Dell", "128", "Win98" )'
szStatement = szStatement + ',( "0002", "Host-0002", "TopModel", "NoName", "256", "Win2K" )'
szStatement = szStatement + ',( "0003", "Host-0003", "BlueModel", "IBM", "512", "Linux" )'
szStatement = szStatement + ',( "0004", "Host-0004", "Screamer-2", "AtticWorks", "256", "Win98" )'
szStatement = szStatement + ',( "0005", "Host-0005", "XPS-XT", "Dell", "128", "WinNT4" )'
szStatement = szStatement + ',( "0006", "Host-0006", "Optiplex", "Dell", "128", "Win98" )'
szStatement = szStatement + ' ;'

result = GenSqlQuery (conn, szStatement)


if (ErrCode != 0)
Print (LogFile, "Error: Could not Insert PC Records in Database\r\n")
Print (LogFile, "Chilli ErrCode: " + MakeStr(ErrCode) + "\r\n")
Print (LogFile, "SQL Error text: " + GenSqlGetErrorText(result) + "\r\n")
else
Print (LogFile, "OK: Loaded 6 rows into table MtxPC\r\n")
endif
GenSqlFreeResult(result)

// Select all columns for all records in MtxPC and print the
// entire result set without knowing how many rows or how many
// columns.

szStatement = 'Select * from MtxPC order by PCID;'


result = GenSqlQuery (conn, szStatement)

if (ErrCode != 0)
Print (LogFile, "Error: Failed to select all PC records in MtxSample\r\n")
Print (LogFile, "Chilli ErrCode: " + MakeStr(ErrCode) + "\r\n")
Print (LogFile, "SQL Error text: " + GenSqlGetErrorText(result) + "\r\n")
else

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 40 - SQL Database Functions - 565

Print (LogFile, "\r\n -------- querying the database -------\r\n")


Print (LogFile, "There are: " + MakeStr(GenSqlGetRowCount(result)) + " Rows\r\n")
Print (LogFile, "The Column Names and Types are: \r\n")

For (j=0; j<GenSqlGetColumnCount(result); j+=1)


Print (LogFile, " " + GenSqlGetColumnName(result, j) + ' of type ')
Print (LogFile, " " + MakeStr(GenSqlGetColumnType(result, j)) + "\r\n")
Endfor

// With two nested loops we can dump the entire result from the blind query

Print (LogFile, "\r\n\r\nDumping all data from MtxPC\r\n\r\n")

GenSqlFirstRow(result)
For (i=0; i<GenSqlGetRowCount(result); i+=1) // Loop for each row
GenSqlSeekRow (result, i) // Goto row number i

For (j=0; j<GenSqlGetColumnCount(result); j+=1) // Loop for each column


Print (LogFile, GenSqlGetColumnValue(result, j) + ' ')
Endfor
Print (LogFile, "\r\n") // Carriage Return and newline

Endfor

Print (LogFile, " -------- End of query session -------\r\n")


endif

GenSqlFreeResult(result)
GenSqlClose (conn)

Print (LogFile, "******************************************\r\n\r\n")

// Note: Database and data still intact: We have not cleaned up the sample

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


566 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


SSH Functions

This chapter explains all SSH functions of the Chilli Function Library. All functions of this module are included
in the ssh.chx file for Windows or ssh.so file for Linux.

41.1 Introduction
SSH (Secure Shell) is a network protocol that allows data to be exchanged over a secure channel between two
computers. Encryption provides confidentiality and integrity of data. SSH uses public-key cryptography to
authenticate the remote computer and allow the remote computer to authenticate the user, if necessary.

41.2 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli SSH function group module has predefined handle and
predefined structure data types.

41.2.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


SshHandle Object type: reference to the handle of a user

SshHandle
The SshHandle data type is a reference to the handle of an SSH client.
The function SshCreate returns a value of this object type that other functions expect as their first argument.
Any open SSH client and thus the value of this object type should always be closed by the SshDelete function.

41.2.2 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated.
Following you find a list of all predefined data types of type structure:

Data Type Description


SshExecInfo Structure containing an array of information about .

SshExecInfo
The SshExecInfo structure represents an array of information about a .

Numara Software, Inc. and BMC Software, Inc. Confidential.


568 - BMC FootPrints Asset Core - Chilli Reference

Elements:
Elements Element Type Description
Stdout String The result as extracted from the standard output file descriptor.
Stderr String The result as extracted from the standard error file descriptor.

41.3 Functions
Following you find a list of all existing functions for the WMI function group module:

Function OS Description
SshConnect Perform an SSH connection including authentication

SshCreate Create a new SSH client

SshDelete Delete an SSH client

SshDisconnect Perform an SSH disconnection

SshExecute Execute a command on the remote connected host, returning the command output and error
channels content
SshSetDebugContext Set the debug context object

SshConnect
Perform an SSH connection including authentication.
Syntax:
Bool SshConnect (SshHandle Ssh, String IpAddress, Int Port, String User, String Password)
Ssh is the handle to the SMB client.
IpAddress is the IP address of the host to be connected
Port is the remote port to be connected
User is the login name with which to connect on.
Password is the password corresponding to the login name.
Returns:
A flag indicating whether peer has been connected or not.
Example:
include "ssh.chx"

#####################################################################
# main
#####################################################################

int main ()

SshHandle hSsh
hSsh = SshCreate ()

if (hSsh == 0)
return 1
endif

if (SshConnect (hSsh, "192.168.1.123", 22, "root", "numara"))

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 41 - SSH Functions - 569

SshDisconnect (hSsh)
endif

SshDelete (hSsh)
return 0

endproc

SshCreate
Create a new SSH client.
Syntax:
SshHandle SshCreate ()
Returns:
A handle to the newly created SMB client.
Example:
include "ssh.chx"

#####################################################################
# main
#####################################################################

int main ()

SshHandle hSsh
hSsh = SshCreate ()

if (hSsh == 0)
return 1
endif

SshDelete (hSsh)
return 0

endproc

SshDelete
Delete an SSH client.
Syntax:
Bool SshDelete (SshHandle Ssh)
Ssh is the handle to the SMB client.
Returns:
A flag indicating whether operation was successful.
Example:
include "ssh.chx"

#####################################################################
# main
#####################################################################

Numara Software, Inc. and BMC Software, Inc. Confidential.


570 - BMC FootPrints Asset Core - Chilli Reference

int main ()

SshHandle hSsh
hSsh = SshCreate ()

if (hSsh == 0)
return 1
endif

SshDelete (hSsh)
return 0

endproc

SshDisconnect
Perform an SSH disconnection.
Syntax:
Bool SshDisconnect (SshHandle Ssh)
Ssh is the handle to the SMB client.
Returns:
A flag indicating whether peer has been disconnected or not.
Example:
include "ssh.chx"

#####################################################################
# main
#####################################################################

int main ()

SshHandle hSsh
hSsh = SshCreate ()

if (hSsh == 0)
return 1
endif

if (SshConnect (hSsh, "192.168.1.123", 22, "root", "numara"))


SshDisconnect (hSsh)
endif

SshDelete (hSsh)
return 0

endproc

SshExecute
Execute a command on the remote connected host, returning the command output and error channels content.
Bool SshExecute (SshHandle Ssh, String Cmd, Int Timeout, Bool Atomic, SshExecInfo Exec)
Ssh is the handle to the SMB client.
Cmd is the command line to execute.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 41 - SSH Functions - 571

Timeout is the timeout in seconds to be used when reading the socket response.
Atomic is a boolean value that indicates whether the entire command response can be extracted using a
single socket read.
Exec is the returned command line result.
Returns:
A flag indicating whether operation was successful.
Example:
include "ssh.chx"

#####################################################################
# main
#####################################################################

int main ()

SshHandle hSsh
hSsh = SshCreate ()

if (hSsh == 0)
return 1
endif

if (SshConnect (hSsh, "192.168.1.129", 22, "root", "numara"))


SshExecInfo execInfo
if (SshExecute (hSsh, "sfdisk -l", 1, true, execInfo))
Print (LogFile, "Response: " + execInfo.Stdout + "\r\n")
endif
SshDisconnect (hSsh)
endif

SshDelete (hSsh)
return 0

endproc

SshSetDebugContext
Set the debug context object.
Syntax:
Bool SshSetDebugContext (SshHandle Ssh, VarHandle Var)
Ssh is the handle to the SMB client.
Var is the handle to the MtxDebugContext that must have been previously acquired from the debug.chx
Chilli module.
Returns:
A flag indicating whether operation was successful.
Example:
include "ssh.chx"
include "debug.chx"

#####################################################################

Numara Software, Inc. and BMC Software, Inc. Confidential.


572 - BMC FootPrints Asset Core - Chilli Reference

# main
#####################################################################

int main ()

SshHandle hSsh
hSsh = SshCreate ()

if (hSsh == 0)
return 1
endif

DebugContextHandle hDebug
hDebug = DebugContextCreate ()

if (hDebug == 0)
SshDelete (hSsh)
return 1
endif

DebugContextSetFilePath (hDebug, "test.log");


SshSetDebugContext (hSsh, hDebug)

SshDelete (hSsh)
DebugContextDestroy (hDebug)
return 0

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


String Functions

This chapter explains all string functions of the Chilli Function Library. The string module is included in the
Chilli core and thus always accessible.

42.1 Introduction
A string is a series of characters manipulated as a group. A character string differs from a name in that it does not
represent anything. The string function module provides you with functions necessary for the manipulation of
strings, such as string conversion, encryption, or finding and matching strings. It also provides you with extended
search functions through the regular expression functions group.
This module is divided into the following subgroups:
• General String Functions
• Regular Expression String Functions

42.2 Predefined Constants


Following you find the complete list of all predefined constants of the String functions group of the Chilli script
language:

Name Type Description


INTBASE_DEC Integer The integer value is converted into a string using base 10
INTBASE_HEXL Integer The integer value is converted into a hexadecimal string using lowercase letters for a-c.
INTBASE_HEXU Integer The integer value is converted into a hexadecimal string using upper-case letters for A-C.

42.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli String function module has predefined data types of type
structure.

42.3.1 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated. For each predefined structure an array type of this structure also exists for usage
in the scripts.
Following you find a list of all predefined data types of type structure:

Data Type Description


RegexMatch Represent the matched expression and sub-expressions

Numara Software, Inc. and BMC Software, Inc. Confidential.


574 - BMC FootPrints Asset Core - Chilli Reference

RegexMatch
The RegexMatch structure represents the matched expression and sub-expressions within the regular expression.
This structure is returned by the StrFindRegEx2 function.
This data type is only applicable to the Regular Expression String functions.
Elements:

Elements Element Type Description


Offset integer The character position, starting at 1 for the first matched character.
Length integer The number of matched characters.

42.4 General String Functions


Following you find a table with all general string functions supported by Chilli:

Function OS Description
CompareVersions Compare two strings containing a version number

StrEncrypt Return an encrypted version of a given string

StrEscapeHtml Convert special character in their HTML value

StrEscapeHtmlUrl Convert special characters to their hexadecimal values

StrExpandEnvString Replace an environment variables with its string value

StrFind Find a substring within another string

StrLeft Extract a substring from the left hand side (beginning) of a string

StrLen Get the number of characters in a string

StrMatch Perform wildcard match and comparison between two strings

StrMid Extract a substring from the middle of a string

StrRight Extract a substring from the right hand side (end) of a string

StrSort Sort a string array

StrToAscii Convert all of the characters in a string to printable ASCII

StrToBinary Convert all of the characters in a string from printable ASCII to their actual binary value

StrTokenise Define the elements and the separator of a string array

StrToLower Convert all characters in a string to lower case

StrToNumbers Convert the contents of an ASCII string value to the equivalent decimal values

StrToUpper Convert all characters in a string to upper case

StrTruncateRight Return a subset of a string by counting raw characters from the 'left' of the string.

UTF16HexToStr Convert a unicode string encoded in hexadecimal to an ansi string.

CompareVersions
Compare two strings containing a version number.
Syntax:
Bool CompareVersions (String Version1, String Operator, String Version2)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 42 - String Functions - 575

Version1 is the left side of the comparison.


Operator is the operation to be performed. It can only be LTET or LT or E or GT or GTET in upper case.
Version2 is the right side of the comparison.
Returns:
If the operation is successful TRUE is returned, FALSE if otherwise.
Comments:
A version is a separated list of numbers. The separator is detected and can be one of the following characters: .,_
with the restriction that a version must have the same separator within its body. Two versions can have different
separators. If the token count is different for the two versions to compare, the test fails. Use padding in order to
ensure that versions can be compared: 2.3.0 cannot be compared with 2.31, use 2.31.0 instead. The comparison
can be executed with the following operators: LTET (less than or equel than), LT (less than), E (equals), GT
(greater than), GTET (greater than or equal than).
Example:
CompareVersions (string, string, string):

string strVersion
strVersion = "6_0_3790_118"
if (CompareVersions (strVersion, "LT", "6_0_3790_365")
Print ("Deprecated version found [" + strVersion + "].")
endif

StrEncrypt
Return an encrypted version of a given string.
Syntax:
String StrEncrypt (String StringValue, String cType)
StringValue is the string to search for an occurrence of SubString.
cType specifies the algorithm to use for the hashing.
Returns:
The encrypted string of the source string if the operation was successful or an empty string if the operation failed.
Comments:
Given a source string, it returns an encrypted version of it, using the algorithm specified by 'cType'.
Notice that there are no chilli functions for decrypting. This is deliberate: Some of the BMC Software products
and technologies rely on encryption for protection and exposing the decrypt function(s) in chilli would be similar
to installing an expensive lock and then hanging the keys on the doorhandle. Also note that the name of the
function is actually a misleading name. Strictly speaking the function encodes the argument string rather than
encrypting it.
Example:
The following example tries to map a network drive.
proc main ()

int RetVal
string DriveLetter, Server, Share, User, Password

FileFindInfo ptrFileInfo
string szFileName

// Set up the current working dir and baptise our LogFile to be


// the name of our scriptfile plus a .log suffix

DirSetCurrent (PathGetDrive(ScriptFile) + ':' + PathGetDir(ScriptFile))


LogFile = PathGetFileRoot(ScriptFile) + '.log'

Numara Software, Inc. and BMC Software, Inc. Confidential.


576 - BMC FootPrints Asset Core - Chilli Reference

DriveLetter = "T"
Server = "Coyote"
Share = "Sample"
User = "Guest"

// Encrypt the password


// The possible arguments for the cType (second argument) are
// "A" "B" "C" "D"
// "B" is the recommended option
// The actual meaning of these options are deliberately not
// documented for security reasons.

Password = StrEncrypt ("GuestPassword", "B")

// Try to map driveletter T to the sample share


// We are supplying an encrypted string in the variable "Password"
// The DiskNetAddEx chilli function is able to handle both enrypted
// as well as clear unencrypted strings in the password argument.

RetVal = DiskNetAddEx (DriveLetter, Server, Share, User, Password)


if (Retval != TRUE)
Print (LogFile, "Error: Could not map drive T to share " + Share + "on " + Server +
"\r\n")
else
Print (LogFile, "OK: Mapped drive T to share " + Share + "on " + Server + "\r\n")
endif

// Start a file find operation and get a pointer

ptrFileInfo = FileFindOpen ('T:\*')

// Loop forever ... we'll break out of the loop


// when there are no more files found in this dir
// This is useful when you don't know in advance
// exactly what the loop condition is

Print (LogFile, "******* List of Files and Folders *******\r\n")


while (1)

szFileName = FileFindNext (ptrFileInfo)


if (szFileName == "")

// No more files found - break out of the while loop

break
else
if ((szFilename != '.') && (szFilename != '..'))

Print (LogFile, szFileName + "\r\n")


endif
endif
endwhile
Print (LogFile, "******* End of list *******\r\n")

DiskNetDelete (DriveLetter)

endproc

StrEscapeHtml
This function converts special characters to their HTML value.
Syntax:
String StrEscapeHtml (String SourceCharacters)
SourceCharacters is the string of characters to be converted to their HTML value.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 42 - String Functions - 577

Returns:
The HTML value of the character, for example a space ( ) is converted to “&#32;”.
Example:
proc main ()

string szStringToConvert

Print ("<INPUT type='button' value='" + StrEscapeHtml (szStringToConvert) + "'>")

endproc

StrEscapeHtmlUrl
This function converts special characters to their hexadecimal values.
Syntax:
String StrEscapeHtmlUrl (String SourceCharacters)
SourceCharacters is the string of characters to be converted to their hexadecimal value.
Returns:
The hexadecimal value of the character, for example a space ( ) is converted to “%20”.
Example:
proc main ()

string szStringToConvert

Print ("<A href='" + StrEscapeHtmlUrl (szStringToConvert) + "'>This is the test</A>")

endproc

StrExpandEnvString
Replace an environment variables with its string value.
Syntax:
String StrExpandEnvString (String Path)
Path is the directory path to a target directory containing environment variables.
Returns:
The string value of the path with the environment variable being replaces by its value, if the operation was
successful, if the environment variable does not exist it is replaces by a space ( ).
Comments:
The path parameter can contain more than one environment variable.The variable must be enclosed in ${}, for
example ${WINDIR}\temp.

StrFind
Find the first occurrence of a substring within another string.
Syntax:
Int StrFind (String StringValue, String SubString)
StringValue is the string to search for an occurrence of SubString.
SubString is the string which is to be searched for within StringValue.

Numara Software, Inc. and BMC Software, Inc. Confidential.


578 - BMC FootPrints Asset Core - Chilli Reference

Returns:
The returned value is the offset of SubString within StringValue if the substring was found and 0 if the search
failed.
Comments:
The comparison is affected by the value of the predefined variable StrCase. If StrCase is TRUE, then the search is
done using case sensitive compare and every character in the substring must have an exact match in StringValue.
If StrCase is FALSE, then the comparison ignores the case of each character. By default the value of the predefined
variable StrCase is set to FALSE thus the comparison is case insensitive by default.
Example:
The following example manipulates strings using various functions of the string module.
proc main ()

string strLine, strABCD, strFGHI


int Pos
strLine = "ABCDEFGHI"
Pos = StrFind (strLine, 'E')
strABCD = StrLeft (strLine, Pos - 1)
strFGHI = StrRight (strLine, StrLen (strLine) - Pos)

if (StrMatch (strLine, "A*F?HI") == TRUE)


strFGHI = StrMid (strLine, 6, 4)
endif

endproc

StrLeft
Extract a substring from the beginning of a string.
Syntax:
String StrLeft (String StringValue, Int Count)
StringValue is the string from which the substring should be extracted.
Count is the number of characters which are to be copied into the substring.
Returns:
The returned value is a substring containing Count characters copied from the beginning of StringValue.
Comments:
If the value in Count is larger than the number of characters in StringValue, then the substring is equal to
StringValue. The function does not change the value of StringValue.
Example:
The following example looks for a comma in a string and then copies all characters to the left of the comma into a
new string and all characters to the right into a second new string.
proc main ()

string Value, SubValue


string Right, Left
int iOffset, iLen
iOffset = StrFind (Value, ',')

if (iOffset != 0)
iLen = StrLen (Value)
Right = StrRight (Value, iLen - iOffset)
Left = StrLeft (Value, iOffset - 1)
endif

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 42 - String Functions - 579

StrLen
Get the number of characters in a string value.
Syntax:
Int StrLen (String StringValue)
StringValue is the string which is to be counted.
Returns:
The returned value is the number of characters in the string and can be 0 for an empty string.
Example:
The following example manipulates strings using various functions of the string module.
proc main ()

string strLine, strABCD, strFGHI


int Pos
strLine = "ABCDEFGHI"
Pos = StrFind (strLine, 'E')
strABCD = StrLeft (strLine, Pos - 1)
strFGHI = StrRight (strLine, StrLen (strLine) - Pos)

if (StrMatch (strLine, "A*F?HI") == TRUE)


strFGHI = StrMid (strLine, 6, 4)
endif

endproc

StrMatch
Perform a string compare where the second parameter can contain wildcard characters (*).
Syntax:
Int StrMatch (String StringValue, String MatchPattern)
StringValue is the string to match against MatchPattern .
MatchPattern is the string which is to be matched against StringValue.
Returns:
The returned value is 1 if the pattern in MatchPattern matches the string in StringValue and is FALSE if it does not.
Comments:
This function works in a similar way to the is equal operator (==) except that the MatchPattern can contain one
or more wildcard characters: ‘?’ matches one character, ‘*’ matches 0 or more characters in StringValue.
Example:
The following example manipulates strings using various functions of the string module.
proc main ()

string strLine, strABCD, strFGHI


int Pos
strLine = "ABCDEFGHI"
Pos = StrFind (strLine, 'E')
strABCD = StrLeft (strLine, Pos - 1)
strFGHI = StrRight (strLine, StrLen (strLine) - Pos)

if (StrMatch (strLine, "A*F?HI") == TRUE)


strFGHI = StrMid (strLine, 6, 4)
endif

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


580 - BMC FootPrints Asset Core - Chilli Reference

StrMid
Extract a substring from any position within another string.
Syntax:
String StrMid (String StringValue, Int Offset, Int Count)
StringValue is the string from which the substring should be extracted.
Offset is the character position within StringValue (starting at 1 for the first character) where the copying
should start.
Count is the number of characters which are to be copied into the substring.
Returns:
The returned value is a substring containing Count characters copied starting from Offset characters from the
beginning of StringValue.
Comments:
If the Offset is larger than the length of StringValue, an empty string is returned. If the value in Count is longer
than the string, only the valid part of StringValue is returned. The function does not change the value of
StringValue.
Example:
The following example manipulates strings using various functions of the string module.
proc main ()

string strLine, strABCD, strFGHI


int Pos
strLine = "ABCDEFGHI"
Pos = StrFind (strLine, 'E')
strABCD = StrLeft (strLine, Pos - 1)
strFGHI = StrRight (strLine, StrLen (strLine) - Pos)

if (StrMatch (strLine, "A*F?HI") == TRUE)


strFGHI = StrMid (strLine, 6, 4)
endif

endproc

StrRight
Extract a substring from the end of a string.
Syntax:
String StrRight (String StringValue, Int Count)
StringValue is the string from which the substring should be extracted.
Count is the number of characters which are to be copied into the substring.
Returns:
The returned value is a substring containing Count characters copied counting back from the end of StringValue.
Comments:
If the value in Count is larger than the number of characters in StringValue, then the substring is equal to
StringValue. The function does not changes the value of StringValue.
Example:
The following example looks for a comma in a string and then copies all characters to the left of the comma into a
new string and all characters to the right into a second new string.
proc main ()

string Value, SubValue


string Right, Left

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 42 - String Functions - 581

int iOffset, iLen


iOffset = StrFind (Value, ',')

if (iOffset != 0)
iLen = StrLen (Value)
Right = StrRight (Value, iLen - iOffset)
Left = StrLeft (Value, iOffset - 1)
endif

endproc

StrSort
Sort a string array.
Syntax:
String[] StrSort (String[] Variables, Bool fAscending, Bool CaseSensitive)
Variables is array of strings to be sorted.
fAscending is the order in which to sort the string array. Possible values are TRUE and FALSE. The sort
order is ascending if fAscending is set to TRUE, descending if set to FALSE.
CaseSensitive defines if the sorting is case sensitive or not. The possible values are TRUE: case sensitive
and FALSE: not case sensitive.
Returns:
The sorted array of strings if the operation was successful, an empty array if the operation failed. If the operation
fails, ErrCode is set to ERR_FUNCFAILED.
Example:
The following example prints a sorted array.
proc main ()

string ptrNames[4]
string ptrNamesSorted[4]
int i

ptrNames[1] = "Smith"
ptrNames[2] = "Doe"
ptrNames[3] = "Chang"
ptrNames[4] = "White"
ptrNamesSorted = StrSort (ptrNames, TRUE, TRUE)

for (i=1; i<=4; i+=1)


print (ptrNamesSorted[i] + "\n")
endfor

endproc

StrToAscii
Convert all of the characters in a string to printable ASCII.
Syntax:
String StrToAscii (String StringValue)
StringValue is the string to change.
Returns:
The returned value is a string which is the printable ASCII equivalent of the characters in StringValue.

Numara Software, Inc. and BMC Software, Inc. Confidential.


582 - BMC FootPrints Asset Core - Chilli Reference

Comments:
This function can be used to convert binary, non-printable strings into strings which can be written into a plain
text file. For example, binary string values read from the Registry contain characters such as 0 or CR/LF (Carriage
Return and Line Feed) which when written to a text file make the file unreadable. This function converts such
characters by escaping them with \ or printing their equivalent hex codes such as \x0f.
You can use StrToBinary to convert an ASCII version of a string back into the correct binary format.
Example:
The following example converts a string to all lower and all upper case and another to binary format and ASCII
format.
proc main ()

string strLine, StrLower, strUpper


string strAscii, strBin, strUpper, strLower

strLower = StrToLower ("aZevTEDHilhgt")


strUpper = StrToUpper ("aZevTEDHilhgt")
strBin = StrToBinary ("\x0f\t")
strAscii = StrToAscii ("\x0f\t")

endproc

StrToBinary
Convert all of the escaped characters in a string to their correct binary values.
Syntax:
String StrToBinary (String StringValue)
StringValue is the string to change.
Returns:
The returned value is a string which is the binary equivalent of StringValue but with all escaped characters
converted.
Comments:
This function is the opposite of StrToAscii in that it takes an ASCII string with escaped codes in it and converts
it to binary. Examples of escaped characters include \n for Carriage Return, \t for horizontal tab and \x80 for ASCII
character 128 which cannot normally be printed into a file.
Example:
The following example converts a string to all lower and all upper case and another to binary format and ASCII
format.
proc main ()

string strLine, StrLower, strUpper


string strAscii, strBin, strUpper, strLower

strLower = StrToLower ("aZevTEDHilhgt")


strUpper = StrToUpper ("aZevTEDHilhgt")
strBin = StrToBinary ("\x0f\t")
strAscii = StrToAscii ("\x0f\t")

endproc

StrTokenise
Tokenise a string given a separator.
Syntax:
String[] StrTokenise (String Value, String Separator)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 42 - String Functions - 583

Value is a string that contains subvalues which can be separated through separators.
Separator is a string of potential separators any of which can be used to delimit the substrings.
Returns:
A string array with the elements defined in the Tokenise string, if the operation executed successfully, otherwise
an empty array of strings.
Comments:
The Separator string can contain any number of charaters, each of which is a potential separator. If a separator in
the list is not preceeded by a string value it is ignored. Leading spaces is removed.
Example 1:
The following examples display the results of tokenized strings.

Call Returns
StrTokenise ("Jan\nFeb\nMar\n", "\n") Jan, Feb, Mar
StrTokenise ("Jan\nFeb\n\nMar\n", "\n") Jan, Feb, Mar
StrTokenise ("\n", "\n") empty array of strings

Example 2:
The following example counts the number of elements in an array.
proc main ()

int i, length
string Employees[], CurrentValues[]

Employees = StrTokenise ("Ferrars\nDashwood\nWickham\n", "\n")


length = ArrayGetSize (Employees)
CurrentValues = ArraySetSize (CurrentValues, length)

if (length<=0)
print ("There are no employees listed.")
else
if (length==1)
print ("There is 1 employee listed.")
else
print ("There are " + length + " employees listed.")
endif
endif

endproc

StrToLower
Convert all characters in a string to lower case.
Syntax:
String StrToLower (String StringValue)
StringValue is the string to change.
Returns:
The returned value is a string which is the same as StringValue but with all characters converted to lower case.
Example:
The following example converts a string to all lower and all upper case and another to binary format and ASCII
format.
proc main ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


584 - BMC FootPrints Asset Core - Chilli Reference

string strLine, StrLower, strUpper


string strAscii, strBin, strUpper, strLower

strLower = StrToLower ("aZevTEDHilhgt")


strUpper = StrToUpper ("aZevTEDHilhgt")
strBin = StrToBinary ("\x0f\t")
strAscii = StrToAscii ("\x0f\t")

endproc

StrToNumbers
Convert the contents of an ASCII string value to the equivalent decimal values, character by character, evaluating
escaped non-printable characters if necessary.
Syntax:
Int[] StrToNumbers (String StringValue)
StringValue is the string to convert to numbers.
Returns:
An array containing the decimal values of the ASCII string or an empty array if nothing is found or an error
occurred.
Example:

StrToUpper
Convert all characters in a string to upper case.
Syntax:
String StrToUpper (String StringValue)
StringValue is the string to change.
Returns:
The returned value is a string which is the same as StringValue but with all characters converted to upper case.
Example:
The following example converts a string to all lower and all upper case and another to binary format and ASCII
format.
proc main ()

string strLine, StrLower, strUpper


string strAscii, strBin, strUpper, strLower

strLower = StrToLower ("aZevTEDHilhgt")


strUpper = StrToUpper ("aZevTEDHilhgt")
strBin = StrToBinary ("\x0f\t")
strAscii = StrToAscii ("\x0f\t")

endproc

StrTruncateRight
Return a subset of a string by counting raw characters from the 'left' of the string.
Syntax:
String StrTruncateRight (String Value, Int Count)
Value is the string which is to be truncated.
Count is the number of characters from the left to be kept.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 42 - String Functions - 585

Returns:
The truncated string, that is, the first X (= count) characters, if the operation was successful, or an empty string
if the original string was shorter than the number of characters to be kept or the operation failed.
Example:
The function
String StrTruncateRight (StringValueToTruncate, 6)
returns the value “String”.

UTF16HexToStr
Convert a unicode string encoded in hex to a regular ANSI string.
Syntax:
String UTF16HexToStr (String Value, String Tokens)
Value is the hexadecimal unicode string.
Tokens is the type of separator used in the unicode string.
Returns:
A string containing the ansi format of the hexadecimal string if the operation was successful, or an empty string if
the operation failed.
Example:
The function
String UTF16HexToStr (6e,00,6f,00,00,00, ,)
returns the ansi value “no”, same as the function
String UTF16HexToStr (6e006f000000, )

Numara Software, Inc. and BMC Software, Inc. Confidential.


586 - BMC FootPrints Asset Core - Chilli Reference

42.5 Regular Expression Functions


Regular expressions are patterns that describe a sequence of zero or more characters. They are constructed
analogously to arithmetic expressions, by using various operators to combine smaller expressions, and they are
matched against an input string. Matching a string to the specified pattern is called "pattern matching." Pattern
matching either succeeds or fails, that is it returns a Boolean value, which depends on whether or not the string can
be parsed as a sentence of the Chilli language. You can use a regular expression to find patterns in strings: for
example, to look for a specific name in a phone list or all of the names that start with the letter a.
The search for a matching sequence starts at the beginning of a string and stops when the first sequence matching
the expression is found. If a regular expression can match two different parts of an input string, it matches the
earliest part first. If the pattern permits a variable number of matching characters and thus there is more than one
such sequence starting at that point, the longest such sequence is matched.
Regular expressions are a way to specify text patterns when searching for a text in a buffer. Regular expressions
consist of normal characters and special operator characters with a special meanings. Operators allow you to
anchor matches, match classes of characters, match given pattern several times or match alternate patterns.
Operators can be also used to group patterns. Regular expressions are very powerful. Every single character in a
regular expression has a special meaning. A regular expression is really just a sequence or a pattern of characters
that is matched against a string of text when performing searches and replacements. A simple regular expression
consists of a single character or a set of characters that matches itself.
Example:
bb*matches the second to fourth characters of abbbc
(wee|week)(knights|night)matches all ten characters of weeknights.
Many tasks can be done with regular expressions. The most common one is to find out whether a given string
matches a particular pattern. You can also find out where the matching substring is located within the string. You
can use a substitution command to replace matching sections with another string of your choice.
Chilli supports the extended regular expressions only. A simple character in the extended regular expressions
supported by Chilli is a regular expression that matches itself. It is any character in the supported character set
except for the special characters. A special character has special properties in certain contexts. Outside those
contexts, or when preceded by a backslash, such a character is an ERE that matches the special character itself. The
extended regular expression special characters and the contexts in which they have their special meaning are:

Character Description
. The period, left-bracket, backslash and left-parenthesis are special except when used in a bracket expression.
[ Outside a bracket expression, a left-parenthesis immediately followed by a right-parenthesis produces undefined
\ results.
(
) The right-parenthesis is special when matched with a preceding left-parenthesis, both outside a bracket expression.
* The asterisk, plus-sign, question-mark and left-brace are special except when used in a bracket expression. Any of
+ the following uses produce undefined results:
? - if these characters appear first in a regular expression, or immediately following a vertical-line,
{ circumflex or left-parenthesis
- if a left-brace is not part of a valid interval expression.
| The pipe is special except when used in a bracket expression. A vertical-line appearing first or last in a regular
expression, or immediately following a vertical-line or a left-parenthesis, or immediately preceding a right-parenthesis,
produces undefined results.
^ The caret is special when used:
- as an anchor
- as the first character of a bracket expression.
$ The dollar sign is special when used as an anchor.

For a detailed explanation of regular expressions consult The Single UNIX Specification, Version 2 of The Open
Group or Mastering Regular Expressions from Jeffrey E.F. Friedl (O’Reilly Press).

42.5.1 Functions
Following you find a table containing all regular expression functions:

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 42 - String Functions - 587

Function OS Description
StrFindPcre Find all the matches of the given regex within the given string and returns the list of captured
substrings
StrFindRegEx Match a regular expression within a string and return an array of matching strings

StrFindRegEx2 Match a regular expression within a string and return a RegexMatch structure of matching strings

StrMatchPcre Match a Perl Compatible Regular Expression (PCRE) within a string

StrMatchRegEx Match a regular expression within a string

StrReplacePcre Match a regular expression within a string and replace it with the supplied replacement string

StrReplaceRegEx Match a regular expression within a string and replace it with the supplied replacement string

StrFindPcre
Find all the matches of the given regex within the given string and returns the list of captured substrings. The
RegEx is in Perl Compatible Regular Expression (PCRE) format.
Syntax:
Bool StrFindPcre (String Value, String RegEx, String Result[], Bool CaseSensitive)
Bool StrFindPcre (String Value, String RegEx, String Result[], Bool CaseSensitive, Bool
ValueSafe, Bool RegexSafe)
Value is the source string to be matched.
RegEx is the regular expression the string value is to be matched to.
Result is the array of strings containing the matched expressions and sub-expressions within the regular
expression.
CaseSensitive defines if the comparison is case sentitive or not. The possible values are TRUE: case
sensitive and FALSE: not case sensitive.
ValueSafe defines if the provided Value is safe to be used with no convertion.
RegexSafe defines if the provided RegEx is safe to be used with no convertion.
Returns:
If nothing is found or an error occurred, an empty array is set for Result and FALSE is returned.
Comments:
The flags ValueSafe and RegexSafe indicate if the given Value and RegEx contain escaped hex characters (\\xXX) or
not. If set to TRUE it means the corresponding string does not contain hex and is used 'as is'. If set to FALSE it
means the corresponding string can contain hexadecimal escaped characters that need to be converted to their
ASCII value before performing further operations.
Example 1:
"hello\\x20world" is transformed to "hello world" where \x20 are four characters ([\][x][2][0]) in the string,
and only one in ASCII ([ ]) after being converted because the flag was set to FALSE.
Example 2:
StrFindPcre (string, string, string[], bool):

string strLogData, vecStat[]


strLogData = "We have found 27 errors and 68 warnings in log files."
if (StrFindPcre (strLogData, "^.*([0-9]+ error)[s]?( and ([0-9]+ warning)[s]?)?" , vecStat, false)
Print (vecStat[1] + "(s) and " + vecStat[3] + "(s).")
endif

StrFindRegEx
Match a regular expression within a string and return an array of matching strings.

Numara Software, Inc. and BMC Software, Inc. Confidential.


588 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
String[] StrFindRegEx (String Value, String RegEx, Bool CaseSensitive)
Value is the string value to be matched.
RegEx is the regular expression the string value is to be matched to.
CaseSensitive defines if the comparison is case sensitive or not. The possible values are TRUE: case
sensitive and FALSE: not case sensitive.
Returns:
Returns an array of strings containing the matched expressions and sub-expressions within the regular expression
if the operation was successful or an empty array if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Example:
The following example uses regular expressions to search for a specific word in a string.
proc main ()

string MySentence
string ptrResult []
MySentence = "The little grey cat"
ptrResult = StrFindRegEx (MySentence, "*little (.*) cat", TRUE)

if (ArrayGetSize (ptrResult) == 2)
print ("In the following sentence: " + ptrResult[1])
print ("I determined that the color of the cat is " + ptrResult[2] + "\n")
else
print ("Could not match the regular expression\n")
endif

endproc

StrFindRegEx2
Match a regular expression within a string and return a RegexMatch structure of matching strings.
Syntax:
RegexMatch[] StrFindRegEx2 (String Value, String RegEx, Bool CaseSensitive)
Value is the string value to be matched.
RegEx is the regular expression the string value is to be matched to.
CaseSensitive defines if the comparison is case sensitive or not. The possible values are TRUE: case
sensitive and FALSE: not case sensitive.
Returns:
Returns an array of RegexMatch structures which are the matched expression and sub-expressions within the
regular expression if the operation was successful or an empty array if the operation failed. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.
Comments:
The RegexMatch structure stores the matched sub-strings as offsets (from start of value) and lengths.
Example:
The following example uses structures of regular expressions to search for a specific word in a string.
proc main ()

string MySentence
RegexMatch ptrResult []
int i, count

MySentence = "The dark grey cat is obviously grey"


ptrResult = StrFindRegEx2 (MySentence, "(grey)", TRUE)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 42 - String Functions - 589

count = ArrayGetSize (ptrResult)

if ( count > 0)
print ("In the following sentence: " + MySentence)
print (" I found the word 'grey' in " + count +" places:\n")

for (i=1; i<=count; i+=1)


print (i + ": from character " + ptrResult[i].Offset)
print (" to character " + (ptrResult[i].Offset + ptrResult[i].Length)
+ "\n")

endfor
else
print ("Could not match the regular expression\n")
endif

endproc

StrMatchPcre
Match a Perl Compatible Regular Expression (PCRE) within a string.
Syntax:
Bool StrMatchPcre (String Value, String RegEx)
Bool StrMatchPcre (String Value, String RegEx, Bool CaseSensitive)
Bool StrMatchPcre (String Value, String Regex, Bool CaseSensitive, Bool StringSafe,
Bool RegexSafe)
Value is the source string to be matched.
RegEx is the regular expression the string value is to be matched to.
CaseSensitive defines if the comparison is case sentitive or not. The possible values are TRUE: case
sensitive and FALSE: not case sensitive.
StringSafe defines if the provided String is safe to be used with no convertion.
RegexSafe defines if the provided RegEx is safe to be used with no convertion.
Returns:
If the match failed or an error occurred FALSE is returned, TRUE if otherwise.
Comments:
The flags ValueSafe and RegexSafe indicate if the given Value and RegEx contain escaped hex characters
(\\xXX) or not. If set to TRUE it means the corresponding string does not contain hex and is used 'as is'. If set
to FALSE it means the corresponding string can contain hexadecimal escaped characters that need to be
converted to their ASCII value before performing further operations.
Example 1:
"hello\\x20world" is transformed to "hello world" where \x20 are four characters ([\][x][2][0]) in the
string, and only one in ASCII ([ ]) after being converted because the flag was set to FALSE.
Example 2:
StrMatchPcre (string, string, bool):

string strMessage
strMessage = "Hello the world !"
if (StrMatchPcre (strMessage, "^.*[Hh]ello.*!$", true))
Print ("Hi! How do you do ?")
endif

StrMatchRegEx
Match a regular expression within a string.
Syntax:
Bool StrMatchRegEx (String Value, String RegEx, Bool CaseSensitive)
Numara Software, Inc. and BMC Software, Inc. Confidential.
Value is the string value to be matched.
RegEx is the regular expression the string value is to be matched to.
590 - BMC FootPrints Asset Core - Chilli Reference

CaseSensitive defines if the comparison is case sensitive or not. The possible values are TRUE: case
sensitive and FALSE: not case sensitive.
Returns:
Returns TRUE if the string matches the regular expression or FALSE if string does not match or the operation
failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Example:
The following example checks if a string is composed of only digits.
proc main ()

string Number
Number = "123"

if (StrMatchRegEx (Number, "^ *[0-9]* *$", FALSE) == TRUE)


print (Number + " is a valid number\n")
else
print (Number + " is not a valid number\n")
endif

Number = "123dw"
if (StrMatchRegEx (Number, "^ *[0-9]* *$", FALSE) == TRUE)
print (Number + " is a valid number\n")
else
print (Number + " is not a valid number\n")
endif

endproc

StrReplacePcre
Match a Perl compatible Regular Expression (PCRE) within a string and replace it with the supplied replacement
string.
Syntax:
String StrReplacePcre (String Value, String RegEx, String Replace, Bool CaseSensitive)
Value is the string value to be matched.
RegEx is the regular expression the string value is to be matched to.
Replace is the replacement string.
CaseSensitive defines if the comparison is case sensitive or not. The possible values are TRUE: case
sensitive and FALSE: not case sensitive.
Returns:
A string containing the replaced value if the operation was successful or an empty string if the operation failed. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The match is done as many times as possible within the string. The match is done as many times as possible
within the string. The replacement string can contain x sequences within it where x ranges from 0 to 9 to identify
the matched parenthesized sub-string (back-referencing).
Example 1:
The following example removes all spaces from a string.
proc main ()
string MyString
MyString = "This is a beautiful day "
print ("I determined that without trailing spaces your string would be '")
print (StrReplacePcre (MyString, " *$", "", FALSE) + "'\n")
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 42 - String Functions - 591

Example 2:
This example replaces the first letter of the string by a 'z' and the letter 'a' following an 'f' by a k, using a regular
expression and back references.
int main ()
string strMyString
strMyString = "abcdefabcdef"

strMyString = StrReplacePcre (strMyString, "^.(.*f)a(.*)$", 'z\1k\2', true)


# equivalent to:
# strMyString = StrReplacePcre (strMyString, "^.(.*)$", "z\\1k\\2", true)
Print ("Result is: " + strMyString)
return 0
endproc

Rhe result is: zbcdefkbcdef

StrReplaceRegEx
Match a regular expression within a string and replace it with the supplied replacement string.
Syntax:
String StrReplaceRegEx (String Value, String RegEx, String Replace, Bool CaseSensitive)
Value is the string value to be matched.
RegEx is the regular expression the string value is to be matched to.
Replace is the replacement string.
CaseSensitive defines if the comparison is case sensitive or not. The possible values are TRUE: case
sensitive and FALSE: not case sensitive.
Returns:
A string containing the replaced value if the operation was successful or an empty string if the operation failed. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The match is done as many times as possible within the string. The replacement string can contain \x sequences
within it where x ranges from 0 to 9 to identify the matched parenthesized sub-string (back-referencing).
Example:
The following example removes all spaces from a string.
proc main ()

string MyString
MyString = "This is a beautiful day "
print ("I determined that without trailing spaces your string would be '")
print (StrReplaceRegEx (MyString, " *$", "", FALSE) + "'\n")

endproc

42.6 Examples
Example 1:
The following example finds occurrence of an email address in a text:
proc main ()
bool first, second
first = StrMatchRegEx ("an e-mail addy (foo@foo) that is too short to be correct", "[A-z]+@[A-z]+(\\.[A-z]+)+", false)
second = StrMatchRegEx ("an valid (foo@foo.com) e-mail addy", "[A-z]+@[A-z]+(\\.[A-z]+)+", false)

Numara Software, Inc. and BMC Software, Inc. Confidential.


592 - BMC FootPrints Asset Core - Chilli Reference

Print (logfile, "First fails: "+first+" while second succeeds: "+second+"\n")


endproc

Example 2:
The following example strips html tags from a page:
proc main ()

string pagesource
pagesource = "<html><p>a paragraph <b>with bold text</b></html>"
StrReplaceRegEx (pagesource, "<[^>]*>", "", false)

endproc
This returns "a paragraph with bold text"
Example 3:
This example procedure replaces all 1.1 paragraphs by 1.1.1 style paragraphs in a LaTeX file:
proc main ()

StrReplaceRegEx ("abc \\section def", "section", "subsection", false)

endproc

Example 4:
This example converts special characters in an ASCII file to be HTML ready:
proc main ()

StrReplaceRegEx ("French is cluttered with words like évident and "\


+"héritage", "é", "\\&eacute;", false)

endproc
This returns "French is cluttered with words like &eacute;vident and h&eacute;ritage"

Numara Software, Inc. and BMC Software, Inc. Confidential.


Time Functions

This chapter explains all time and timer functions of the Chilli Language. All functions of this module are
included in the time.chx file for Windows or time.so file for UNIX and Linux.

43.1 Introduction
The Chilli time module provides you with functions necessary to retrieve information about the stored time
information as well as with timer functions, which enable you to create, use and delete specific timers.
It is split into the following subcategories:
• General Time Functions
• Timer Functions

43.2 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli Time function group has Predefined Handle Data Types.

43.2.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


TimerHandle Object type: reference to the handle of a timer object

TimerHandle
The TimerHandle data type is a reference to the handle of a timer object.
The function TimerCreate returns a value of this object type that other functions expect as their first argument.
Any open timer object and thus the value of this object type should always be closed by the TimerDestroy
function.
This handle data type is only applicable to the Timer function subgroup.

43.3 General Time Functions


Following you find the list of all functions of the General Time functions module:

Numara Software, Inc. and BMC Software, Inc. Confidential.


594 - BMC FootPrints Asset Core - Chilli Reference

Function OS Description
TimeFormat Format a value of absolute seconds using the supplied formatting string

TimeGetAbsSeconds Get the number of absolute seconds

TimeGetDay Get the current day from the system clock

TimeGetHour Get the current hour from the system clock

TimeGetMinute Get the current minute from the system clock

TimeGetMonth Get the current month from the system clock

TimeGetSecond Return the current second from the system clock

TimeGetUTCDiff Return the difference in seconds between local time and UTC time

TimeGetWeekday Get the current weekday from the system clock

TimeGetYear Get the current year from the system clock

TimeFormat
Format a value of absolute seconds using the supplied formatting string.
Syntax:
String TimeFormat (Int Format, String Value)
Format is the integer defining the output format.
Value is the string value to be formatted.
Returns:
The formatted string of absolute seconds if the operation was successful or an empty string if the operation failed.
If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The format string consists of zero or more conversion specifications and ordinary characters. A conversion
specification consists of a % (percent) character and one or two terminating conversion characters that determine
the conversion specification's behavior. All ordinary characters are copied unchanged into the array.
Each conversion specification is replaced by appropriate characters as described in the following list.
If a conversion specification does not correspond to any of the above the behavior is undefined and 0 is returned.
The difference between %U and %W (and also between modified conversion specifications %OU and %OW) lies
in which day is counted as the first of the week. Week number 1 is the first week in January starting with a
Sunday for %U or a Monday for %W. Week number 0 contains those days before the first Sunday or Monday in
January for %U and %W.
The formatting of the value is similar in idea to printf. The formatting is done using the strftime library function.
The meaning of the formatting string is as below, copied from the strftime man page.

Format Description
%% same as %
%a abbreviated weekday name
%A full weekday name
%b abbreviated month name
%B full month name
%c appropriate date and time representation
%C date and time representation as produced by the unix date command
%d day of month [1,31]; single digits are preceded by 0

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 43 - Time Functions - 595

Format Description
%D date as %m/%d/%y
%e day of month [1,31]; single digits are preceded by a space
%h locale’s abbreviated month name
%H hour (24-hour clock) [0,23]; single digits are preceded by 0
%I hour (12-hour clock) [1,12]; single digits are preceded by 0
%j day number of year [1,366]; single digits are preceded by 0
%k hour (24-hour clock) [0,23]; single digits are preceded by a blank
%l hour (12-hour clock) [1,12]; single digits are preceded by a blank
%m month number [1,12]; single digits are preceded by 0
%M minute [00,59]; leading zero is permitted but not required
%n insert a newline
%p locale’s equivalent of either a.m. or p.m.
%r appropriate time representation in 12-hour clock format with %p
%R time as %H:%M
%S seconds [00,61]”
%t insert a tab
%T time as %H:%M:%S
%u weekday as a decimal number [1,7], with 1 representing Sunday
%U week number of year as a decimal number [00,53], with Sunday as the first day of week 1
%V week number of the year as a decimal number [01,53], with Monday as the first day of the week. If the week
containing 1 January has four or more days in the new year, then it is considered week 1; otherwise, it is week 53 of
the previous year, and the next week is week 1.
%w weekday as a decimal number [0,6], with 0 representing Sunday
%W week number of year as a decimal number [00,53], with Monday as the first day of week 1
%x locale’s appropriate date representation
%X locale’s appropriate time representation
%y year within century [00,99]
%Y year, including the century (for example 1993)
%Z time zone name or abbreviation, or no bytes if no time zone information exists

Example:
This example handles the printing of integer attributes as an absolute time string.
proc main ()

int TimeNow;
TimeNow = TimeGetAbsSeconds ()

FileAddLine (szFile, TimeFormat (TimeNow, "%Y:%m:%d %H:%M:%S") + "," +\ MakeStr (TimeNow,


"%lu") + "," + szData + "\r\n")

endproc

TimeGetAbsSeconds
Get the number of absolute seconds since midnight January 1, 1970.
This function has the following signatures:
Syntax:
Int TimeGetAbsSeconds ()
Int TimeGetAbsSeconds (Int Year, Int Month, Int Day, Int Hour, Int Minute, Int Seconds)
Day is a number between 1 and 31 to give the day of the month.
Month is a number between 1 and 12 to indicate the calendar month.

Numara Software, Inc. and BMC Software, Inc. Confidential.


596 - BMC FootPrints Asset Core - Chilli Reference

Year is the number of years since 1900 expressed with 4 digits, for example, 1964.
Hour is a number between 0 and 23 to indicate the hour of the day..
Minute is a number between 0 and 59 to indicate the minutes of the hour.
Seconds is a number between 0 and 59 to indicate the seconds of the minute.
Returns:
Returns the number of seconds elapsed since midnight January 1, 1970 for the provided date (this is UTC time), if
the operation was successful or 0 if the operation failed. If the calendar time can not be represented, the function
returns the value -1. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Example:
This example prints the current time.
proc main ()

int TimeNow;
TimeNow = TimeGetAbsSeconds ()

FileAddLine (szFile, TimeFormat (TimeNow, "%Y:%m:%d %H:%M:%S") + "," +\ MakeStr (TimeNow,


"%lu") + "," + szData + "\r\n")

endproc

TimeGetDay
Get the current day from the system clock.
Syntax:
Int TimeGetDay ()
Returns:
An integer value between 1 and 31 representing the day of the current date as reported by the system clock.

TimeGetHour
Get the current hour from the system clock.
Syntax:
Int TimeGetHour ()
Returns:
An integer value between 0 and 23 representing the hour of the current time as reported by the system clock.
Comments:
This function has the following alias:
Int TimeGetHours ()

TimeGetMinute
Get the current minute from the system clock.
Syntax:
Int TimeGetMinute ()
Returns:
An integer value between 0 and 59 representing the minute of the current time as reported by the system clock.
Comments:
This function has the following alias:
Int TimeGetMinutes ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 43 - Time Functions - 597

TimeGetMonth
Get the current month from the system clock.
Syntax:
Int TimeGetMonth ()
Returns:
An integer value between 1 and 12 representing the month of the current date as reported by the system clock.

TimeGetSecond
Get the current seconds reading from the system clock.
Syntax:
Int TimeGetSecond ()
Returns:
An integer value between 0 and 59 representing the seconds of the current time as reported by the system clock.
Comments:
This function has the following alias:
Int TimeGetSeconds ()

TimeGetUTCDiff
Return the difference in seconds between local time and UTC time.
Syntax:
Int TimeGetUTCDiff ()
Returns:
Returns the difference in seconds between local time and UTC time, if the operation was successful or 0 if the
operation failed. If the calendar time can not be represented, the function returns the value -1. If the operation
fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
To calculate the number of absolute seconds elapsed since 00:00:00 UTC, this function can either be used together
with the TimeGetAbsSeconds function which provides the local time in seconds elapsed since 1 January 1970,
00:00:00, or the computer uses its internal local time. Note that the difference in seconds can be a positive or
negative number.
Example:
If you want the absolute second number elapsed since 00:00:00 UTC, January 1, 1970 for the local time 12:11:00
Feb. 14., 1999, use TimeGetAbsSeconds (1999, 2, 14, 12, 11, 00) + TimeGetUTCDiff ().
TimeGetAbsSeconds (1999, 2, 14, 12, 11, 00)
returns 918987060
TimeGetUTCDiff ()
returns 3600 if you are in Paris (GMT+1) and -10800 if you are in Buenos Aires
(GMT-3).
print (“Your local time is GMT“ + TimeGetUTCDiff ()/3600)

TimeGetWeekday
Get the current weekday from the system clock.
Syntax:
Int TimeGetWeekday ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


598 - BMC FootPrints Asset Core - Chilli Reference

Returns:
An integer value between 1 (Sunday) and 7 (Saturday) representing the day of the week as reported by the system
clock.

TimeGetYear
Get the current year from the system clock.
Syntax:
Int TimeGetYear ()
Returns:
The integer value representing the year part of the current date as reported by the system clock.

43.3.1 Example
Code sample to demonstrate Time functions:
;Note that with double quotes (“) the backslashes are escaped.
proc main ()
string LogFile
LogFile = “C:\\temp\\logfile.txt”)
Print (LogFile, “\r\nScript started on ”)
Print (LogFile, MakeStr (TimeGetYear()) + “/”)
Print (LogFile, MakeStr (TimeGetMonth()) + “/”)
Print (LogFile, MakeStr (TimeGetDay()))
Print (LogFile, “ at “)
Print (LogFile, MakeStr (TimeGetHour()) + “:”)
Print (LogFile, MakeStr (TimeGetMinute()) + “:”)
Print (LogFile, MakeStr (TimeGetSecond()))
Print (LogFile, “\r\n”)
endproc

43.4 Timer Functions


This group of functions manages a high resolution timer counting in milliseconds.
Following you find the list of all functions of the Timer functions:

Function OS Description
TimerCreate Create a timer object

TimerDestroy Destroy an existing timer given a valid timer handle

TimerRead Read the current value of the supplied timer object

TimerReset Reset a timer object to 0 and stops it so that it can be used for a new measurement

TimerStart Start a timer object

TimerStop Stop a timer object

TimerCreate
Create a timer object.
Syntax:
TimerHandle TimerCreate ()
Returns:
The handle to the timer if the operation was successful, or 0 if the operation failed. If the operation fails, ErrCode
is set to ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 43 - Time Functions - 599

Comments:
The function can fail if high resolution timers are not supported by the system hardware.
The timer object can be used for measuring time intervals in milliseconds. It is created already reset to 0 and
stopped.

TimerDestroy
Destroy an existing timer given a valid timer handle.
Syntax:
Bool TimerDestroy (TimerHandle Timer)
Timer is the handle to the timer to be destroyed.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
If the handle is not valid, the function validates the handle value passed to it and sets ErrCode to
ERR_BADHANDLE. Closing the timer object frees up the resources associated with the handle and invalidates it.
After closing the timer the handle value can no longer be used.

TimerRead
Read the current value of the supplied timer object.
Syntax:
Int TimerRead (TimerHandle Timer)
Timer is the handle to the timer to be read.
Returns:
The current value of the timer if successful, 0 if the function failed. The returned value can also be 0 if the timer
is reset and not running.
Comments:
The value is expressed in milliseconds.

TimerReset
Reset a timer object to 0 and stops it so that it can be used for a new measurement.
Syntax:
Bool TimerReset (TimerHandle Timer)
Timer is the handle to the timer to be reset.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.

TimerStart
Start a timer object.
Syntax:
Bool TimerStart (TimerHandle Timer)
Timer is the handle to the timer to be started.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


600 - BMC FootPrints Asset Core - Chilli Reference

Comments:
The timer starts counting from its last stopped value. If the timer is already running, this has no effect.

TimerStop
Stop a timer object.
Syntax:
Int TimerStop (TimerHandle Timer)
Timer is the handle to the timer to be stopped.
Returns:
The total value of the timer in milliseconds after being stopped if the operation was successful, or 0 if the
operation failed. If the timer was not started, the interval also is 0.
Comments:
The timer can then be read after it is stopped. If the timer is already stopped, this has no effect.

43.4.1 Example
# InitLog
# If the file does not exist create it and add the title.

proc InitLog (string szFile, string szTitle)

if (!FileExists (szFile))
FileCreate (szFile)
FileAddLine (szFile, szTitle + "\r\n")
endif

endproc

# LogData
# Logs the supplied data string with the current timestamp.

proc LogData (string szFile, string szData)

int TimeNow;
TimeNow = TimeGetAbsSeconds ()

FileAddLine (szFile, TimeFormat (TimeNow, "%Y:%m:%d %H:%M:%S") + "," +\


MakeStr (TimeNow, "%lu") + "," + szData + "\r\n")

endproc

proc main ()

TimerHandle HandleTime;
FtpHandle HandleFtp;

ErrHandler = INLINE_HANDLER

DirSetCurrent (PathGetDrive (ScriptFile) + ":" + PathGetDir (ScriptFile))


print ("Working directory is " + DirGetCurrent () + "\r\n")

InitLog (PERFLOG, "FTP Logon")

HandleTime = TimerCreate ();


TimerStart (HandleTime);

HandleFtp = FtpConnect (SERVERNAME, FTP_DEFAULT_PORT);


if (HandleFtp == 0)
LogData (PERFLOG, "Connect Failed")
exit
endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 43 - Time Functions - 601

if (!FtpLogin (HandleFtp, USERNAME, USERPASS))


LogData (PERFLOG, "Login Failed")
exit
endif

TimerStop (HandleTime);

LogData (PERFLOG, MakeStr (TimerRead (HandleTime), "%lu"))

TimerReset (HandleTime)

print ("Reset - Timer value is " + TimerRead (HandleTime) + "\r\n")


print ("Absolute time is " + TimeGetAbsSeconds () + "\r\n")

FtpDisconnect (HandleFtp);
TimerDestroy (HandleTime);

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


602 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


UNIX Service Functions

This chapter explains all UNIX Service type functions of the Chilli Function Library. All functions of this module
are included in the unixservice.so file. These functions are only applicable to the UNIX environment.

44.1 Introduction
This group of Chilli functions enables you to get information about a service or a list of services on the local
computer.

44.2 Functions
Following you find a list of all existing functions for the UNIX Service function group module:

Function OS Description
ServiceGetStatus Return the status of the specified service.

ServiceList List services which satisfy the supplied type and status values.

ServiceGetStatus
Gives the status of the specified service name.
Syntax:
String[] ServiceGetStatus (String Servicename)
Servicename is the name of the service for which the current status is requested.
Returns:
An array of strings describing the current status of the requested service if the operation was successful or an
empty array if the operation failed.
Example:
proc main ()
string szServiceState[]
int i

szServiceState = ServiceGetStatus ("anacron")

Print ("The status of the anacron service is:\n")

for (i = 1; i <= ArrayGetSize (szServiceState); i += 1)


Print (szServiceState[i] + "\n")
endfor
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


604 - BMC FootPrints Asset Core - Chilli Reference

ServiceList
Lists services which satisfy the supplied type and status values.
Syntax:
String[] ServiceList ()
Returns:
An array containing the list of service names if the function succeeded, an empty array otherwise.
Example:
proc main ()
string szServiceList
int i

szServiceList = ServiceList ()

for (i = 1; i <= ArrayGetSize (szServiceList); i += 1)


Print ("Service " + i + ": " + szServiceList[i] + "\n")
endfor
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


User Functions

This chapter explains all user functions of the Chilli language. All functions of this module are included in the
user.chx file. These functions are not applicable to the UNIX environment.

45.1 Introduction
The Chilli user functions can be used to impersonate another user and then cancel the impersonation again.
Impersonating another user can be useful for purposes of testing the rights of another user or to obtain
administrator rights for a specific task execution.

45.2 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli User function group has Predefined Handle Data Types.

45.2.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


UserHandle Object type: reference to the handle of a user

UserHandle
The UserHandle data type is a reference to the handle of a user.
The function UserChange returns a value of this object type that the functions UserRevertToSelf expect as
its argument.

45.2.2 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated.
Following you find a list of all predefined data types of type structure:

Data Type Description


UserInfo Structure returned as a result for the UserGetList function. This structure provides information about
the user.

Numara Software, Inc. and BMC Software, Inc. Confidential.


606 - BMC FootPrints Asset Core - Chilli Reference

UserInfo
The UserInfo structure is returned as a result for the UserGetList function. This structure provides
information about the user.
Elements:

Elements Element Type Description


Name String The user login name.
FullName String The name of the user.
Description String A textual description about the user.
Privilege Integer The user privilege, that is, if the user is a user or administrator.
Dizabled Integer Defines if the user is enabled or dizabled.
Lockout Integer Defines if the account is enabled or blocked.
PwdRequired Integer Specifies if a password is required.
PwdChangeable Integer Specifies if the password can be modified by the user.
PwdExpires Integer Specifies if the password has an expiration date.

45.3 Functions
Following you find the list of all functions of the user function module:

Function OS Description
UserChange Modify the user ID of a program to another user.

UserGetGroups List the Windows groups the User is member of.

UserGetId Return the UNIX user ID.

UserGetList Retrieve local user information list.

UserGetPrivileges Return the privileges of the specified user.

UserGetUserStringSid Get the sid of a user

UserGetType Return type information about the specified user.

UserGroupExists Check if a user group exists

UserRevertToSelf Call the Windows NT RevertToSelf function to cancel out any impersonation.

UserChange
Modify the user ID of a program to another user.
Syntax:
UserHandle UserChange (String Domain, String UserName, String Password)
Domain is the name of the domain to log on to.
UserName is the name of the user with which to log on to the specified domain.
Password is the password for the specified user name.
Returns:
TRUE if the function succeeded, FALSE otherwise.
Comments:
Logs on the named user to the named domain and than changes the user id of the program to that of the new user.
This can be used for situations like gaining Administrator or root privileges on a system.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 45 - User Functions - 607

UserGetGroups
List the Windows groups the user is a member of.
Syntax:
String[] UserGetGroups (String UserName)
UserName is the name of the user to check the groups for.
Returns:
An array of strings representing the groups the user belongs to if the operation was successful or an empty array if
the operation failed.
Example:
proc main ()
string strList[]
int i
strList = UserGetGroups ("Administrator")
for (i=1; i <= ArrayGetSize (strList);i+=1)
Print ("Group " + i + " : " + strList[i] + "\r\n")
endfor
endproc

UserGetId
Return the logged UNIX user identifier. This function is only applicable to the UNIX environment.
Syntax:
Int UserGetId (String Login)
Returns:
TRUE if the check operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Example:
proc main ()
int iUserId
iUserId = UserGetId ()
if (iUserId == 0)
Print ("The current User is 'Root'\r\n")
endif
endproc

UserGetList
Retrieve local user information list.
Syntax:
UserInfo[] UserGetList ()
Returns:
A strucuture of type UserInfo containing all required user information.

UserGetPrivileges
Return the list of Windows privileges of the given user.
Syntax:
String[] UserGetPrivileges (String UserName)
UserName is the name of the user for which the privileges are checked.

Numara Software, Inc. and BMC Software, Inc. Confidential.


608 - BMC FootPrints Asset Core - Chilli Reference

Returns:
TRUE if the function succeeded, FALSE otherwise.
Example:
proc main ()
string strList[]
int i
strList = UserGetPrivileges ("Administrator")
for (i=1; i <= ArrayGetSize (strList);i+=1)
Print ("Privilege " + i + " : " + strList[i] + "\r\n")
endfor
endproc

UserGetUserStringSid
Get the sid of a user.
Syntax:
String UserGetUserStringSid (String Domain, String Name)
Domain is the name of the domain to log on to.
Name is the name of the user with which to log on to the specified domain.
Returns:
TRUE if the function succeeded, FALSE otherwise.
Comments:
The sid is represented by a character string.

UserGetType
Return type information of the specified user.
Syntax:
Int UserGetType (String ServerName, String UserName, String UserPasswordEnc)
ServerName is the name of the server on which the user to check is defined.
UserName is the user name of which the type is to be checked.
UserPasswordEnc is the encrypted password for the user name.
Returns:
If the function was successful the type of the specified user is returned in form of an interger, or, if the user does
not exist, -1 and ErrCode is set to ERR_FUNCFAILED.
The possible user types are:
0 = Guest
1 = User
2 = Admin
Comments:
The encrypted password is created with the Chilli function StrEncrypt (password, ’B’). Also if you are in the
HCHL environment you can use the variable HTTP_REMOTE_PASSWORD for this value, if it is already available.

UserGroupExists
Check if a user group exists.
Syntax:
Bool UserGroupExists (String GroupName)
GroupName is the name of the group of which the existence is to be verified.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 45 - User Functions - 609

Returns:
TRUE if the group exists, FALSE otherwise.
Example:
include "user.chx"

proc main ()
bool fGroupExists

fGroupExists = UserGroupExists ("Administrators")

if (fGroupExists)
Print (LogFile, "The user group Administrators exists.")
else
Print (LogFile, "The user group Administrators does not exist.")
endif
endproc

UserRevertToSelf
Call the Windows NT RevertToSelf function to cancel out any impersonation.
Syntax:
Bool UserRevertToSelf (UserHandle hToken)
hToken is the handle of the user which is to return to its previous login.
Returns:
TRUE if the cancel operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
Always use this function after impersonating another user on a machine to close the user handle.

Numara Software, Inc. and BMC Software, Inc. Confidential.


610 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Variable Functions

This chapter explains all functions concerning the indirect manipulation of variables in the Chilli function
modules. The variable module is included in the Chilli core and thus always accessible.

46.1 Introduction
A variable is a symbol or name that stands for a value. Variables play an important role because they enable to
write flexible programs. Rather than entering data directly into a program, a programmer can use variables to
represent the data. Then, when the program is executed, the variables are replaced with real data. This makes it
possible for the same program to process different sets of data.
These functions allow you to access variable values when the name becomes available only at runtime. It can be
divided into the following subgroups:
• General Variable Functions
• Variable Manipulation Functions

46.2 Predefined Constants


Following is the list of all predefined constants of the Variable functions group of the Chilli language:

Name Type Description


VARTYPE_BOOL Integer Variable is of type boolean.
VARTYPE_BOOLEAN_ARRAY Integer Variable is of type boolean array.
VARTYPE_CHAR Integer Variable is of type character.
VARTYPE_CHAR_ARRAY Integer Variable is of type character array.
VARTYPE_DOUBLE Integer Variable is of type double.
VARTYPE_DOUBLE_ARRAY Integer Variable is of type double array.
VARTYPE_FLOAT Integer Variable is of type float.
VARTYPE_FLOAT_ARRAY Integer Variable is of type float array.
VARTYPE_INTEGER Integer Variable is of type integer.
VARTYPE_INTEGER_ARRAY Integer Variable is of type integer array.
VARTYPE_STRING Integer Variable is of type string.
VARTYPE_STRING_ARRAY Integer Variable is of type string array.
VARTYPE_STRUCT Integer Variable is of type structure.
VARTYPE_STRUCT_ARRAY Integer Variable is of type structure array.

46.3 General Variable Functions


Following you find a list containing all functions of the general variable manipulation group:

Numara Software, Inc. and BMC Software, Inc. Confidential.


612 - BMC FootPrints Asset Core - Chilli Reference

Function OS Description
Defined Check that variable or constant name is defined

Export Export a local variable to have global scope

VarCreate Create a new simple variable based on the supplied type and add it to the global variable
list
VarGetBooleanValue Get the boolean value of a variable

VarGetCharValue Get the character value of a variable

VarGetDoubleValue Get the double precision floating point value of a variable

VarGetFloatValue Get the floating point value of a variable

VarGetIntegerValue Get the integer value of a variable

VarGetStringValue Get the string value of a variable

VarGetType Get the type of a variable

VarSetBooleanValue Set the boolean value of the variable whose name is supplied

VarSetCharValue Set the character value of the variable whose name is supplied

VarSetDoubleValue Set the double value of the variable whose name is supplied

VarSetFloatValue Set the float value of the variable whose name is supplied

VarSetIntegerValue Set the integer value of the variable whose name is supplied

VarSetStringValue Set the string value of the variable whose name is supplied

Defined
Check that a given variable, constant, function or procedure name is defined and in scope.
Syntax:
Int Defined (String Name)
Name is the variable or constant name to check.
Returns:
The function returns 1 if the supplied name is defined and in scope, 0 if it is not.
Comments:
In the Chilli language, referencing a variable or constant which is not in scope causes a fatal error and terminate
the script. This function can be used to check whether a name is in scope or not. Note that the Name parameter
must be supplied as a quoted string otherwise it is interpreted as a reference to the actual variable, and if the
variable does not exist a fatal error occurs.
Example:
The following example is an excerpt from a procedure which deletes certain files after a rollout procedure from
the Rollout script to rollout the BCM agent on Windows NT.
proc main ()

if (Defined ("cmd_dir"))
FileDelete ("cmd_dir" + '\ro_boot.ini')
FileDelete ("cmd_dir" + '\ro_boot.chl')
FileDelete ("cmd_dir" + '\chilli16.exe')
FileDelete ("cmd_dir" + '\privacy.pvc')
DirDelete ("cmd_dir")
endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 46 - Variable Functions - 613

endproc

Export
Export a local variable to give it global scope.
Syntax:
Int Export (String Name)
Name is the variable or constant name to export.
Returns:
The function returns 1 if the variable was successfully exported and 0 if an error occurs. ErrCode is set to
ERR_INVALIDPARAM if the supplied name does not exist in local scope.
Comments:
After exporting a variable, the local copy is destroyed and any references to the variable uses the global variable.
Example:
The following example defines and exports the variable 'hprogress' if it is not defined.
proc main ()

progress hProgress
if (Defined ("hProgress") == 0)
int hProgress
hProgress = 0
Export ("hProgress")
endif

endproc

VarCreate
Create a new simple variable based on the supplied type and add it to the global variable list.
Syntax:
Bool VarCreate (String Name, Int Type)
Name is the name of the variable to be created.
Type is the type of the variable to be created.
Returns:
TRUE if the operation was successful or FALSE if the operation failed.
Comments:
This function can only create simple variables such as integer, float and string. It cannot create structures or
arrays.
Example:
The following example gets the value of the Euro as a double value or defines it as a float if it does not yet exist.
proc main ()

bool Result
double eurovalue

if (defined ('euro'))
if (VarGetType ('euro') == VARTYPE_DOUBLE)
eurovalue = VarGetDoubleValue ('euro')

if (eurovalue == 1.955830)
print ('The Euro variable is a double and its value is ' + eurovalue)
else
print ('The Euro variable is a double and its value has been
set to ' + VarSetDoubleValue ('euro', 1.955830))

Numara Software, Inc. and BMC Software, Inc. Confidential.


614 - BMC FootPrints Asset Core - Chilli Reference

endif

else
print ('The Euro variable is not a double')
endif

else
print ('The Euro variable is not defined, defining it now.')
Result = VarCreate ('euro', VARTYPE_DOUBLE)
if (Result == TRUE)
print ('The Euro variable has been successfully defined and its
value was set to ' + VarSetFloatValue ('euro', 1.955830) + '.')
else
print ('The Euro variable could not be defined.')
endif
endif

endproc

VarGetBooleanValue
Get the boolean value of a variable.
Syntax:
Bool VarGetBooleanValue (String VarName)
VarName is the name of the variable for which the boolean value is demanded.
Returns:
The boolean value of the variable if the operation was successful, or FALSE if the variable is not found or the
operation failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
If the named variable is not of the correct type, its value is cast to boolean.
Example:
The following example script tests if a variable is a boolean and if so gets its value.
proc main ()

bool Result
if (defined ('my_boolean_variable'))
if (VarGetType ('my_boolean_variable') == VARTYPE_BOOL)
Result = VarGetBooleanValue ('my_boolean_variable')
print ('This variable is a boolean and its value is '+Result)
else
print ('This variable is not a boolean')
endif
else
print ('This variable is not defined')
endif

endproc

VarGetCharValue
Get the character value of a variable
Syntax:
Char VarGetBooleanValue (String VarName)
VarName is the name of the variable for which the character value is demanded.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 46 - Variable Functions - 615

Returns:
The character value of the variable if the operation was successful, or FALSE if the variable is not found or the
operation failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
If the named variable is not of the correct type, its value is cast to character.
Example:
The following example script tests if a variable is a character and if so gets its value.
proc main ()

char Result
if (defined ('my_char_variable'))

if (VarGetType ('my_char_variable') == VARTYPE_CHAR)


Result = VarGetCharValue ('my_char_variable')
print ('This variable is a char and its value is '+Result)
else
print ('This variable is not a char')
endif

else
print ('This variable is not defined')
endif

endproc

VarGetDoubleValue
Get the double precision floating point value of a variable.
Syntax:
Double VarGetDoubleValue (String VarName)
VarName is the name of the variable for which the double value is demanded.
Returns:
The double value of the variable if the operation was successful, or FALSE if the variable is not found or the
operation failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
If the named variable is not of the correct type, its value is cast to double.
Example:
The following example script tests if a variable is a double floating point and if so gets its value.
proc main ()

double Result
if (defined ('my_double_variable'))

if (VarGetType ('my_double_variable') == VARTYPE_DOUBLE)


Result = VarGetDoubleValue ('my_double_variable')
print ('This variable is a double and its value is '+Result)
else
print ('This variable is not a double')
endif

else
print ('This variable is not defined')
endif

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


616 - BMC FootPrints Asset Core - Chilli Reference

VarGetFloatValue
Get the floating point value of a variable.
Syntax:
Float VarGetFloatValue (String VarName)
VarName is the name of the variable for which the float value is demanded.
Returns:
The float value of the variable if the operation was successful, or FALSE if the variable is not found or the
operation failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
If the named variable is not of the correct type, its value is cast to float.
Example:
The following example script tests if a variable is a float value and if so gets its value.
proc main ()

float Result
if (defined ('my_float_variable'))

if (VarGetType ('my_float_variable') == VARTYPE_FLOAT)


Result = VarGetFloatValue ('my_float_variable')
print ('This variable is a float and its value is '+Result)
else
print ('This variable is not a float')
endif

else
print ('This variable is not defined')
endif

endproc

VarGetIntegerValue
Get the integer value of a variable.
Syntax:
Int VarGetIntValue (String VarName)
VarName is the name of the variable for which the integer value is demanded.
Returns:
The integer value of the variable if the operation was successful, or FALSE if the variable is not found or the
operation failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
If the named variable is not of the correct type, its value is cast to integer.
Example:
The following example script tests if a variable is an integer and if so gets its value.
proc main ()

integer Result
if (defined ('my_integer_variable'))

if (VarGetType ('my_integer_variable') == VARTYPE_INTEGER)


Result = VarGetIntegerValue ('my_integer_variable')
print ('This variable is a integer and its value is '+Result)
else

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 46 - Variable Functions - 617

print ('This variable is not a integer')


endif

else
print ('This variable is not defined')
endif

endproc

VarGetStringValue
Get the string value of a variable.
Syntax:
String VarGetStringValue (String VarName)
VarName is the name of the variable for which the string value is demanded.
Returns:
The string value of the variable if the operation was successful, or an empty string if the variable is not found or
the operation failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
If the named variable is not of the correct type, an error occurs and an empty string is returned.
Example:
The following example script tests if a variable is a string and if so gets its value.
proc main ()

string Result
if (defined ('my_string_variable'))

if (VarGetType ('my_string_variable') == VARTYPE_STRING)


Result = VarGetStringValue ('my_string_variable')
print ('This variable is a string and its value is '+Result)
else
print ('This variable is not a string')
endif

else
print ('This variable is not defined')
endif

endproc

VarGetType
Get the type of a variable.
Syntax:
Int VarGetType (String VarName)
VarName is the name of the variable for which the type is demanded.
Returns:
The function returns an integer value corresponding to the type of the variable. If the function fails, or the
variable name is not valid, 0 is returned. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The returned constant can be one of the predefined constants listed previously in this chapter.
Example:
The following example script tests if a variable is a string.
proc main ()

Numara Software, Inc. and BMC Software, Inc. Confidential.


618 - BMC FootPrints Asset Core - Chilli Reference

if (defined ('my_string_variable'))

if (VarGetType ('my_string_variable') == VARTYPE_STRING)


print ('This variable is a string')
else
print ('This variable is not a string')
endif

else
print ('This variable is not defined')
endif

endproc

VarSetBooleanValue
Set the boolean value of the variable whose name is supplied.
Syntax:
Bool VarSetBooleanValue (String Name, Bool Value)
Name is the name of the variable whose value is to be set.
Value is the boolean value to which the variable is to be set.
Returns:
TRUE if the operation was successful or FALSE if the operation failed. The function fails if the variable does not
exist and ErrCode is set to ERR_FUNCFAILED.
Example:
The following example script tests if a variable is a boolean and if so sets its value.
proc main ()

bool Result
if (defined ('my_boolean_variable'))
if (VarGetType ('my_boolean_variable') == VARTYPE_BOOL)
Result = VarGetBooleanValue ('my_boolean_variable')

if (Result == TRUE)
print ('This variable is a boolean and its value is '+Result)
else
print ('This variable is a boolean and its value has been set
to ' + VarSetBooleanValue ('my_boolean_variable', TRUE))
endif

else
print ('This variable is not a boolean')
endif

else
print ('This variable is not defined')
endif

endproc

VarSetCharValue
Set the character value of the variable whose name is supplied.
Syntax:
Bool VarSetCharValue (String Name, Char Value)
Name is the name of the variable whose value is to be set.
Value is the character value to which the variable is to be set.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 46 - Variable Functions - 619

Returns:
TRUE if the operation was successful or FALSE if the operation failed. The function fails if the variable does not
exist and ErrCode is set to ERR_FUNCFAILED.
Example:
The following example script tests if a variable is a character and if so sets its value.
proc main ()

char Result
if (defined ('my_char_variable'))
if (VarGetType ('my_char_variable') == VARTYPE_CHAR)
Result = VarGetCharValue ('my_char_variable')

if (Result == '@')
print ('This variable is a character and its value is ' + Result)
else
print ('This variable is a character and its value has been
set to ' + VarSetCharValue ('my_boolean_variable', '@'))
endif

else
print ('This variable is not a char')
endif

else
print ('This variable is not defined')
endif

endproc

VarSetDoubleValue
Set the double value of the variable whose name is supplied.
Syntax:
Bool VarSetDoubleValue (String Name, Double Value)
Name is the name of the variable whose value is to be set.
Value is the double precision floating point value to which the variable is to be set.
Returns:
TRUE if the operation was successful or FALSE if the operation failed. The function fails if the variable does not
exist and ErrCode is set to ERR_FUNCFAILED.
Example:
The following example gets the value of the Euro as a double value.
proc main ()

double eurovalue
if (defined ('euro'))
if (VarGetType ('euro') == VARTYPE_DOUBLE)
eurovalue = VarGetDoubleValue ('euro')

if (eurovalue == 1.955830)
print ('The Euro variable is a double and its value is ' +
eurovalue)
else
print ('The Euro variable is a double and its value has been
set to ' + VarSetDoubleValue ('euro', 1.955830))
endif

else
print ('The Euro variable is not a double')

Numara Software, Inc. and BMC Software, Inc. Confidential.


620 - BMC FootPrints Asset Core - Chilli Reference

endif

else
print ('The Euro variable is not defined.
endif

endproc

VarSetFloatValue
Set the float value of the variable whose name is supplied.
Syntax:
Bool VarSetFloatValue (String Name, Float Value)
Name is the name of the variable whose value is to be set.
Value is the floating point value to which the variable is to be set.
Returns:
TRUE if the operation was successful or FALSE if the operation failed. The function fails if the variable does not
exist and ErrCode is set to ERR_FUNCFAILED.
Example:
The following example gets the value of the Euro as a float value.
proc main ()

float eurovalue
if (defined ('euro'))

if (VarGetType ('euro') == VARTYPE_FLOAT)


eurovalue = VarGetFloatValue ('euro')

if (eurovalue == 1.96)
print ('The Euro variable is a float and its value is ' +
eurovalue)
else
print ('The Euro variable is a float and its value has been
set to ' + VarSetFloatValue ('euro', 1.96))
endif

else
print ('The Euro variable is not a float')
endif

else
print ('The Euro variable is not defined.
endif

endproc

VarSetIntegerValue
Set the integer value of the variable whose name is supplied.
Syntax:
Bool VarSetIntegerValue (String Name, Int Value)
Name is the name of the variable whose value is to be set.
Value is the integer value to which the variable is to be set.
Returns:
TRUE if the operation was successful or FALSE if the operation failed. The function fails if the variable does not
exist and ErrCode is set to ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 46 - Variable Functions - 621

Example:
The following example script tests if a variable is an integer and if so sets its value.
proc main ()

integer Result
if (defined ('my_integer_variable'))
if (VarGetType ('my_integer_variable') == VARTYPE_INTEGER)
Result = VarGetIntegerValue ('my_integer_variable')

if (Result == 15)
print ('This variable is an integer and its value is '+Result)
else
print ('This variable is an integer and its value has been set
to ' + VarSetIntegerValue ('my_integer_variable', 15))
endif

else
print ('This variable is not a integer')
endif

else
print ('This variable is not defined')
endif

endproc

VarSetStringValue
Set the string value of the variable whose name is supplied.
Syntax:
Bool VarSetStringValue (String Name, String Value)
Name is the name of the variable whose value is to be set.
Value is the string value to which the variable is to be set.
Returns:
TRUE if the operation was successful or FALSE if the operation failed. The function fails if the variable does not
exist and ErrCode is set to ERR_FUNCFAILED.
Example:
The following example script tests if a variable is a string and if so sets its value.
proc main ()

string Result
if (defined ('my_string_variable'))
if (VarGetType ('my_string_variable') == VARTYPE_STRING)
Result = VarGetStringValue ('my_string_variable')

if (Result == 'Euro')
print ('This variable is a string and its value is '+Result)
else
print ('This variable is a string and its value has been set
to ' + VarSetStringValue ('my_integer_variable', 'Euro'))
endif

else
print ('This variable is not a string')
endif

else
print ('This variable is not defined')
endif

Numara Software, Inc. and BMC Software, Inc. Confidential.


622 - BMC FootPrints Asset Core - Chilli Reference

endproc

46.4 Variable Manipulation Functions


Following you find a table with all String Variable Manipulation functions supported by Chilli:

Function OS Description
ArrayFind Find the first entry in an array of strings, doubles, floats or integer where the returned value
matches the supplied value
ArrayGetSize Return the number of elements in an array variable

ArrayRemoveDup Remove duplicate values in an array

ArraySetSize Extend or shrink the number of elements in an array variable

ArraySort Sort an array of strings, integers, floating points, doubles or structures

EvalStr Convert a string to an integer

GetErrorName Convert the supplied integer parameter into its equivalent error code name

GetErrorText Convert the supplied integer parameter into its equivalent error code message text

MakeInt Convert a string to an integer

MakeStr Convert an integer, a character, a float or a double value into a string

StrEvalAsBoolean Evaluate a string on the stack as an expression the value of which is expected to be a boolean

StrEvalAsChar Evaluate a string on the stack as an expression the value of which is expected to be a character

StrEvalAsDouble Evaluate a string on the stack as an expression the value of which is expected to be a double

StrEvalAsFloat Evaluate a string on the stack as an expression the value of which is expected to be a float

StrEvalAsInteger Evaluate a string on the stack as an expression the value of which is expected to be an integer

StrEvalAsString Evaluate a string on the stack as an expression the value of which is expected to be a string

StrEvalGetType Return the type of the string if evaluated as an expression

ArrayFind
Find the first entry in an array of strings, doubles, floats or integer or the first entry in an array of structures where
the returned value matches the supplied value.
Syntax:
Int ArrayFind (Array[] Variable, String Value, Int StartIndex)
Int ArrayFind (Array[] Variable, Double Value, Int StartIndex)
Int ArrayFind (Array[] Variable, Float Value, Int StartIndex)
Int ArrayFind (Array[] Variable, Int Value, Int StartIndex)
Variable is the name of the array variable.
Value is the value to be matched.
StartIndex defines the position within the array on where to start the search.
Int ArrayFind (Array[] Variable, String ElementName, String Value, Int StartIndex)
Int ArrayFind (Array[] Variable, String ElementName, Double Value, Int StartIndex)
Int ArrayFind (Array[] Variable, String ElementName, Float Value, Int StartIndex)
Int ArrayFind (Array[] Variable, String ElementName, Int Value, Int StartIndex)
Variable is the name of the array variable.
ElementName is the name of the structure element.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 46 - Variable Functions - 623

Value is the value of the element to be matched.


StartIndex defines the position within the array on where to start the search.
Returns:
The 1 based index of the entry if found or 0 if the entry is not found or the function failed.
Comments:
For string values, the comparison is case insensitive. The StartIndex can be set to a value other than 1 to start the
search somewhere other than the beginning of the array.

ArrayGetSize
Return the number of elements in an array variable.
Syntax:
Int ArrayGetSize (Array[] Variable)
Variable is the name of the array variable.
Returns:
The number of elements in the array if the operation was successful or 0 if the supplied variable is not an array or
the operation failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The variable must be an array, Chilli determines of which type the array elements are. If the array is wrong in
itself or it doesn’t exist a Chilli parse error occurs and the script is not executed.
Example:
The following example script gets the size of an array.
proc main ()

string Months[]
int length, i

Months = StrTokenise ("January\nFebruary\nMarch\n", "\n")


length=ArrayGetSize (Months)

for (i=1; i<=length; i+=1)


print ('Month no. ' + i + ' is ' + Months[i] + ".\n\r")
endfor

endproc

ArrayRemoveDup
Remove duplicate values in an array.
The function has the following signatures:
Syntax:
array[] ArrayRemoveDup (Array[] Variable)
array[] ArrayRemoveDup (Array[] Variable, Bool CaseSensitive)
Variable is the name of the array variable.
CaseSensitive defines if the sort order is case sensitive (TRUE) or case insensitive (FALSE).
Returns:
The new array with no duplicate values if the operation was successful or the original unchanged array if the
operation failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
The boolean argument for the case sensitivity is necessary if the sort order should be case sensitive. By default it
is case INsensitive.

Numara Software, Inc. and BMC Software, Inc. Confidential.


624 - BMC FootPrints Asset Core - Chilli Reference

Example:
The following example script removes duplicates from an array.
proc main ()

int IntArray[]
int i

IntArray = ArraySetSize(IntArray, 10)


for (i=1; i<=5; i+=1)
IntArray[i]= Rand();
IntArray[i+5]= IntArray[i];
endfor

IntArray = ArrayRemoveDup(IntArray)

endproc

ArraySetSize
Extend or shrink the number of elements in an array variable.
Syntax:
array[] ArraySetSize (Array[] Variable, Int ElementCount)
Variable is the name of the array variable.
ElementCount is the number of elements the array should have.
Returns:
The newly sized array if the operation is successful, or an empty array if the operation failed. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.
Comments:
The changes in the array to adapt to the new size always take place at the end of the array. That is, if the size of the
array is reduced, the last elements of the array is cut, and if the array is extended, new empty elements is added at
the end of the original array.
If the array is wrong in itself or it doesn’t exist a Chilli parse error occurs and the script is not executed.
Example:
The following example script sets the size of an array.
proc main ()

int i, length
string Employees[], CurrentValues[]

Employees = StrTokenise ("Ferrars\nDashwood\nWickham\n", "\n")


length = ArrayGetSize (Employees)
CurrentValues = ArraySetSize (CurrentValues, length)

if (length<=0)
print ("There are no employees listed.")
else
if (length==1)
print ("There is 1 employee listed.")
else
print ("There are " + length + " employees listed.")
endif
endif

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 46 - Variable Functions - 625

ArraySort
Sort an array of elements.
The function has the following signatures:
Syntax:
Array[] ArraySort (Array[] Variable, String ElementName, Bool Ascending)
Array[] ArraySort (Array[] Variable, String ElementName, Bool Ascending, Bool CaseSensitive)
Array[] ArraySort (Array[] Variable, Bool Ascending)
Array[] ArraySort (Array[] Variable, Bool Ascending, Bool CaseSensitive)
Variable is the array to sort.
ElementName is the structure element according to which the array is to be sorted.
Ascending defines if the sort order is ascending (TRUE) or descending (FALSE).
CaseSensitive defines if the sort order is case sensitive (TRUE) or case insensitive (FALSE).
Returns:
The sorted array if the operation was successful, or the original unchanged array if the function failed.
Comments:
The first and second signature are only applicable to structures, the third and fourth signatures can be used for
any of the following data types: string, integer, float or double. The default sort order is case INsensitive for
signatures that don’t specify this parameter.
Example:
The following example script sorts an array of structures.
struct Person
string name
int age
endstruct

proc main ()

int i
Person Employees[4]
Person EmployeesSortedByAge[4]
Employees[1].name = "Smith"
Employees[1].age = 34
Employees[2].name = "Doe"
Employees[2].age = 27
Employees[3].name = "Chang"
Employees[3].age = 40
Employees[4].name = "White"
Employees[4].age = 31

EmployeesSortedByAge = ArraySort (Employees, "age", TRUE)

for (i=1; i<=4; i+=1)


print (EmployeesSortedByAge[i].name +" is " + EmployeesSortedByAge[i].age + "\n")
endfor

endproc

EvalStr
Evaluate a string of digits and return an integer equivalent.
Syntax:
Int EvalStr (String Expression)
Expression is the string containing digits to be evaluated as a number.

Numara Software, Inc. and BMC Software, Inc. Confidential.


626 - BMC FootPrints Asset Core - Chilli Reference

Returns:
If the Expression contains valid characters, the return value is the integer equivalent to the string. If an error
occurs, the return value is 0.
Comments:
EvalStr is an alias for MakeInt and behaves in an identical manner.
Example:
The following example script evaluates a string and converts it to integer and back to string.
proc main ()

string strInt, strInt2


int intStr
strInt = "1950"
intStr = MakeInt (StrInt)
intStr = intStr + 10
strInt = MakeStr (intStr)
IntStr = EvalStr (StrInt + 10)

endproc

GetErrorName
Convert the supplied integer parameter into its equivalent error code name.
Syntax:
String GetErrorName (Int ErrCode)
ErrCode is the numeric code of the returned error from which the error code name is to be retrieved.
Returns:
The string value of the variable if the operation was successful, or an empty string if the operation failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
Typically this function would be called with the value of the global variable ErrCode in order to get the name of
the error constant matching the last error value. If the supplied value is not a valid error code, the returned string
is empty.
Example:
The following example script tries to retrieve a file through ftp and prints the error if the operation failed.
proc main ()

int error
string depotpath, packagefile, depot, user, password

depot="sparc"
user = "spectrum"
password="spectrum"
depotpath = ""
packagefile = depotpath + "/ww24_16.zip"
ErrHandler = INLINE_HANDLER
print ("Doing get...\n")
error = FtpGetFile (depot, user, password, packagefile, "")

if (error == 0)
error = ErrCode;
print ("FTP error " + error + " = " + GetErrorName (error) + "\n");
print (GetErrorText (error) + "\n");
endif

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 46 - Variable Functions - 627

GetErrorText
Convert the supplied integer parameter into its equivalent error code message text.
Syntax:
String GetErrorText (Int ErrCode)
ErrCode is the numeric code of the returned error of which the message text is to be retrieved.
Returns:
The string value of the variable if the operation was successful, or an empty string if the operation failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Comments:
Typically this would be called with the value of the global variable ErrCode in order to get the textual message
normally associated with the error. If the supplied value is not a valid error code, the returned string is empty.
Example:
The following example script tries to retrieve a file through ftp and prints the error if the operation failed.
proc main ()

int error
string depotpath, packagefile, depot, user, password

depot="sparc"
user = "spectrum"
password="spectrum"
depotpath = ""
packagefile = depotpath + "/ww24_16.zip"
ErrHandler = INLINE_HANDLER
print ("Doing get...\n")
error = FtpGetFile (depot, user, password, packagefile, "")

if (error == 0)
error = ErrCode;
print ("FTP error " + error + " = " + GetErrorName (error) + "\n");
print (GetErrorText (error) + "\n");
endif

endproc

MakeInt
Evaluate a string of digits and return an integer equivalent.
Syntax:
Int MakeInt (String Expression)
Expression is the string containing digits to be evaluated as number.
Returns:
If the Expression contains valid characters, the return value is the integer equivalent to the string. If an error
occurs, the return value is 0.
Comments:
MakeInt is an alias for EvalStr and behaves in an identical manner.
Example:
This following example is taken from the main rollout installation procedure for the BCM agent on Windows NT.
....
int iSWD, iCFG, WWSTOP, iCHLHLP, iSNMPServ
string szIniFile

Numara Software, Inc. and BMC Software, Inc. Confidential.


628 - BMC FootPrints Asset Core - Chilli Reference

szIniFile = “C:\\temp\test.ini”
iSWD = MakeInt (FileGetValue (szIniFile, 'WWFiles', 'SWD'))
iCFG = MakeInt (FileGetValue (szIniFile, 'WWFiles', 'CFG'))
iWWSTOP = MakeInt (FileGetValue (szIniFile, 'WWFiles', 'WWSTOP'))
iCHLHLP = MakeInt (FileGetValue (szIniFile, 'WWFiles', 'CHLHLP'))
iSNMPServ = ServiceExists ("SNMP")
if (iSNMPServ)
Print (LogFile, "\r\nSNMP Service is already installed\r\n")
Print (LogFile, "BMC Client Management is installed as\r\n")
Print (LogFile, "a sub-agent to the SNMP service\r\n")
else
Print (LogFile, "\r\nSNMP Service is not installed\r\n")
Print (LogFile, "BMC Client Management is installed as\r\n")
Print (LogFile, "a stand alone agent\r\n")
endif
....

MakeStr
Create a string out of an integer, character, float or double value.
The function MakeStr has the following four signatures:
Syntax:
String MakeStr (Char Number, String StringFormat)
String MakeStr (Double Number, String StringFormat)
String MakeStr (Float Number, String StringFormat)
String MakeStr (Int Number, String StringFormat)
Number is the integer, character, float or double value which is to be converted into a string.
StringFormat is the string format into which the number is to be converted.
Returns:
The returned value is a string of digits representing the value passed in Number.
Comments:
The StringFormat variable must be enclosed in double quotes and be preceded by a percent (%) symbol. It can be
one of the following values:

Character Argument type converted to


d,I INT; signed decimal notation.
o INT; unsigned octal notation without leading zero.
x, X INT; unsigned hexadecimal notation without leading 0x or 0X, using abcdef for 0x or ABCDEF for 0X.
u INT; unsigned decimal notation.
c INT; single character, after conversion to unsigned character.
f DOUBLE; decimal notation of the form [-]mmm.ddd, where the number of ds is specified by the precision. The
default precision is 6; a precision of 0 suppresses the decimal point.
e, E DOUBLE; decimal notation of the form [-]m.dddddde+/-xx or [-]m.dddddde+/-XX, where the number of d’s is
specified by the precision. The default precision is 6; a precision of 0 suppresses the decimal point.
g, G DOUBLE; %e or %R is used if the exponent is less than -4 or greater than or equal to the precision; other wise %f
is used. Trailing zeros and a trailing decimal point are not printed.
% no argument is converted; convert to a %.

Example 1:
The following example script evaluates a string and converts it to integer and back to string.
proc main ()

string strInt
int intStr

strInt = "1950"

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 46 - Variable Functions - 629

intStr = MakeInt (StrInt)


intStr = intStr + 10
strInt = MakeStr (intStr, ’%u’)
print (intStr)

endproc

Example 2:
The following example demonstrates the use of the Chilli character data type in combination with the MakeStr
and Print functions.
proc main ()

string szTmp
char ptrChar[]
int i
szTmp = "Hello"

// Assigning a string to an array of characters sets the size of


// the array to the number of characters in the string and assigns
// each character of the string to an element of the array

ptrChar = szTmp
for (i=1; i<=StrLen (szTmp); i+=1)
print ("Using MakeStr, ASCII code for "+ptrChar[i]+" is "+MakeStr
(ptrChar[i], "%d")+"\n")
endfor
endproc
OUTPUT
Using MakeStr, ASCII code for H is 72
Using MakeStr, ASCII code for e is 101
Using MakeStr, ASCII code for l is 108
Using MakeStr, ASCII code for l is 108
Using MakeStr, ASCII code for o is 111

StrEvalAsBoolean
Evaluate a string on the stack as an expression the value of which is expected to be a boolean. Whatever the result
type is it is returned as a boolean.
Syntax:
Bool StrEvalAsBoolean (String Expression)
Expression is the string on the stack.
Returns:
Returns the boolean value of the string on the stack if the operation was successful or FALSE if the operation
failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Example:
The following example script evaluates a string as a boolean value.
proc main ()

bool a, b, c
a = TRUE
b = FALSE
c = StrEvalAsBoolean ("a || b")

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


630 - BMC FootPrints Asset Core - Chilli Reference

StrEvalAsChar
Evaluate a string on the stack as an expression the value of which is expected to be a character. Whatever the
result type is it is returned as a character.
Syntax:
Char StrEvalAsChar (String Expression)
Expression is the string on the stack.
Returns:
Returns the character value of the string on the stack if the operation was successful or 0 if the operation failed. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.
Example:
The following example script evaluates a string as a character value.
proc main ()

string file, strchar


file = 'C:\temp\install.log'

strchar = FileGetLine (file, 3)


Print ("The character value of the string " + strchar + " is " +
StrEvalAsChar ("strchar") + ".\r\n")

endproc

StrEvalAsDouble
Evaluates a string on the stack as an expression the value of which is expected to be a double. Whatever the result
type is it is returned as a double.
Syntax:
Double StrEvalAsDouble (String Expression)
Expression is the string on the stack.
Returns:
Returns the double precision value of the string on the stack if the operation was successful or 0 if the operation
failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Example:
The following example script evaluates a string as a double value.
proc main ()

string file, strdbl


file = 'C:\temp\install.log'

strdbl = FileGetLine (file, 3)


Print ("The character value of the string " + strdbl + " is " +
StrEvalAsDouble ("strdbl") + ".\r\n")

endproc

StrEvalAsFloat
Evaluates a string on the stack as an expression the value of which is expected to be a float. Whatever the result
type is it is returned as a float.
Syntax:
Float StrEvalAsFloat (String Expression)
Expression is the string on the stack.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 46 - Variable Functions - 631

Returns:
Returns the float value of the string on the stack if the operation was successful or 0 if the operation failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.
Example:
The following example script evaluates a string as a float value.
proc main ()

string file, strflt


file = 'C:\temp\install.log'

strflt = FileGetLine (file, 3)


Print ("The character value of the string " + strflt + " is " +
StrEvalAsDouble ("strflt") + ".\r\n")

endproc

StrEvalAsInteger
Evaluate a string on the stack as an expression the value of which is expected to be an integer. Whatever the result
type is it is returned as an integer.
Syntax:
Int StrEvalAsInteger (String Expression)
Expression is the string on the stack.
Returns:
Returns the integer value of the string on the stack if the operation was successful or 0 if the operation failed. If
the operation fails, ErrCode is set to ERR_FUNCFAILED.
Example:
The following example script evaluates some strings as a integer values.
proc main ()

int iRed, iGreen, iBlue


string szColour
szColour = "#ffaa44"
iRed = StrEvalAsInteger ("0x" + StrMid (szColour, 2, 2))
iGreen = StrEvalAsInteger ("0x" + StrMid (szColour, 4, 2))
iBlue = StrEvalAsInteger ("0x" + StrMid (szColour, 6, 2))

endproc

StrEvalAsString
Evaluates a string on the stack as an expression the value of which is expected to be a string. Whatever the result
type is it is returned as a string.
Syntax:
String StrEvalAsString (String Expression)
Expression is the string on the stack.
Returns:
Returns the string value of the string on the stack if the operation was successful or an empty string if the
operation failed. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Example:
The following example script evaluates a string as a string value.
proc main ()

print ("The value of constant ERR_VARTOOLONG is ")

Numara Software, Inc. and BMC Software, Inc. Confidential.


632 - BMC FootPrints Asset Core - Chilli Reference

print (StrEvalAsString ("ERR_VARTOOLONG"))

endproc

StrEvalGetType
Return the type of the string if evaluated as an expression.
Syntax:
Int StrEvalGetType (String Expression)
Expression is the string on the stack.
Returns:
The type of the evaluated expression if the operation was successful or 0 if the expression can not be evaluated
into a sensible value or the function failed.
Comments:
If the expression can not be evaluated the return value is 0 but no error is generated. Note that the supplied
expression is actually evaluated and executed, which means that if it contains any function calls, those functions
is called.

46.5 Example
Code sample to demonstrate Print, Time and MakeStr functions.
;Note that with double quotes (“) the backslashes are escaped.
proc main ()
string LogFile
LogFile = (“C:\\temp\\logfile.txt”)

Print (LogFile, “\r\nScript started on “)


Print (LogFile, MakeStr (TimeGetYear()) + “/”)
Print (LogFile, MakeStr (TimeGetMonth()) + “/”)
Print (LogFile, MakeStr (TimeGetDay()))
Print (LogFile, “ at “)
Print (LogFile, MakeStr (TimeGetHour()) + “:”)
Print (LogFile, MakeStr (TimeGetMinute()) + “:”)
Print (LogFile, MakeStr (TimeGetSecond()))
Print (LogFile, “\r\n”)
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Windowing Functions

This chapter explains all window functions of the Chilli language. All functions of this module are included in
the window.chx file. These functions are not applicable to the UNIX environment.

47.1 Introduction
A window is a viewport on the screen that displays data, programs or information. A window can be moved,
resized, opened and closed, allowing you to organise the data on your computer screen. The windowing functions
of the Chilli language only work for windows or dialog boxes which are displaying information such as warnings.

47.2 Predefined Constants


Following you find the complete list of all predefined constants of the Window functions group of the Chilli script
language:

47.2.1 Window Class Constants


Following you find the predefined control classes which can be specified for the window:

Name Type Description


WIN_CLASS_BUTTON String Designates a small rectangular child window that represents a button the user can click to turn it
on or off. Button controls can be used alone or in groups, and they can either be labeled or appear
without text. Button controls typically change appearance when the user clicks them.
WIN_CLASS_COMBOBOX String Designates a control consisting of a list box and a selection field similar to an edit control. When
using this style, an application should either display the list box at all times or enable a drop-down
list box.
Depending on the style of the combo box, the user can or cannot edit the contents of the selection
field. If the list box is visible, typing characters into the selection field highlights the first list box
entry that matches the characters typed. Conversely, selecting an item in the list box displays the
selected text in the selection field.
WIN_CLASS_EDIT String Designates a rectangular child window into which the user can type text from the keyboard. The
user selects the control and gives it the keyboard focus by clicking it or moving to it by pressing
the TAB key. The user can type text when the edit control displays a flashing caret; use the mouse
to move the cursor, select characters to be replaced, or position the cursor for inserting
characters; or use the BACKSPACE key to delete characters.
Edit controls use the variable-pitch system font and display characters from the ANSI character
set. The WM_SETFONT message can also be sent to the edit control to change the default font.
Edit controls expand tab characters into as many space characters as are required to move the
caret to the next tab stop. Tab stops are assumed to be at every eighth character position.
WIN_CLASS_LISTBOX String Designates a list of character strings. Specify this control whenever an application must present a
list of names, such as file names, from which the user can select. The user can select a string by
clicking it. A selected string is highlighted, and a notification message is passed to the parent
window. Use a vertical or horizontal scroll bar with a list box to scroll lists that are too long for the
control window. The list box automatically hides or shows the scroll bar, as needed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


634 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


WIN_CLASS_RICHEDIT String Designates a window in which the user can enter, edit, format, print, and save text. The text can
be assigned character and paragraph formatting, and can include embedded Component Object
Model (COM) objects. Rich edit controls support almost all of the messages and notification
messages used with multiline edit controls. Thus, applications that already use edit controls can
be easily changed to use rich edit controls. Additional messages and notifications enable
applications to access the functionality unique to rich edit controls.
WIN_CLASS_RICHEDIT2 String WIN_CLASS_RICHEDIT2 provides a window with the same possibilities as
WIN_CLASS_RICHEDIT with the addition of single line or multiline capabilities and plain or rich
text.
WIN_CLASS_scroll bar String Designates a rectangle that contains a scroll box and has direction arrows at both ends. The
scroll bar sends a notification message to its parent window whenever the user clicks the control.
The parent window is responsible for updating the position of the scroll box, if necessary. Scroll
bar controls have the same appearance and function as scroll bars used in ordinary windows.
Unlike scroll bars, however, scroll bar controls can be positioned anywhere in a window for use
whenever scrolling input is needed for a window.
The scroll bar class also includes size box controls. A size box is a small rectangle the user can
expand to change the size of the window.
WIN_CLASS_STATIC String Designates a simple text field, box, or rectangle used to label, box, or separate other controls.
Static controls take no input and provide no output.

47.2.2 Showstate Constants


The following table shows all constants concerning the way the window is displayed on the screen:

Name Type Description


WIN_HIDDEN Integer The window is created hidden from view. Although the window exists it is not visible.
WIN_NORMAL Integer The window is created visible and is sized and positioned using default values determined by
the operating system.
WIN_MINIMISED Integer The window is created in an iconized state.
WIN_MINIMIZED Integer The window is created in an iconized state.
WIN_MAXIMISED Integer The window is created maximized, filling the entire viewing area of the screen.
WIN_MAXIMIZED Integer The window is created maximized, filling the entire viewing area of the screen.
WIN_CW_CENTER Integer The window is created centered on the screen.
WIN_CW_USEDEFAULT Integer Windows defines where and in which size the window is to be put on the screen.

47.2.3 Window Style Constants


Following are the constants used for the possible window styles:

Name Type Description


WIN_WS_BORDER Integer Creates a window that has a thin-line border.
WIN_WS_CAPTION Integer Creates a window that has a title bar (includes the WIN_WS_BORDER style).
WIN_WS_CHILD Integer Creates a child window. This style cannot be used with the WIN_WS_POPUP style.
WIN_WS_CHILDWINDOW Integer Same as the WIN_WS_CHILD style.
WIN_WS_CLIPCHILDREN Integer Excludes the area occupied by child windows when drawing occurs within the parent window.
This style is used when creating the parent window.
WIN_WS_CLIPSIBLINGS Integer Clips child windows relative to each other; that is, when a particular child window receives a
WM_PAINT message, the WIN_WS_CLIPSIBLINGS style clips all other overlapping child
windows out of the region of the child window to be updated. If WIN_WS_CLIPSIBLINGS is not
specified and child windows overlap, it is possible, when drawing within the client area of a
child window, to draw within the client area of a neighboring child window.
WIN_WS_DISABLED Integer Creates a window that is initially dizabled. A dizabled window cannot receive input from the
user.
WIN_WS_DLGFRAME Integer Creates a window that has a border of a style typically used with dialog boxes. A window with
this style cannot have a title bar.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 47 - Windowing Functions - 635

Name Type Description


WIN_WS_GROUP Integer Specifies the first control of a group of controls. The group consists of this first control and all
controls defined after it, up to the next control with the WIN_WS_GROUP style. The first control
in each group usually has the WIN_WS_TABSTOP style so that the user can move from group to
group. The user can subsequently change the keyboard focus from one control in the group to
the next control in the group by using the direction keys.
WIN_WS_HSCROLL Integer Creates a window that has a horizontal scroll bar.
WIN_WS_ICONIC Integer Creates a window that is initially minimized. Same as the WIN_WS_MINIMIZE style.
WIN_WS_MAXIMIZE Integer Creates a window that is initially maximized.
WIN_WS_MAXIMIZEBOX Integer Creates a window that has a Maximize button. Cannot be combined with the
WS_EX_CONTEXTHELP style. The WIN_WS_SYSMENU style must also be specified.
WIN_WS_MINIMIZE Integer Creates a window that is initially minimized. Same as the WIN_WS_ICONIC style.
WIN_WS_MINIMIZEBOX Integer Creates a window that has a Minimize button. Cannot be combined with the
WS_EX_CONTEXTHELP style. The WIN_WS_SYSMENU style must also be specified.
WIN_WS_OVERLAPPED Integer Creates an overlapped window. An overlapped window has a title bar and a border. Same as the
WIN_WS_TILED style.
WIN_WS_OVERLAPPEDWIN Integer Creates an overlapped window with the WIN_WS_OVERLAPPED, WIN_WS_CAPTION,
DOW WIN_WS_SYSMENU, WIN_WS_THICKFRAME, WIN_WS_MINIMIZEBOX, and
WIN_WS_MAXIMIZEBOX styles. Same as the WIN_WS_TILEDWINDOW style.
WIN_WS_POPUP Integer Creates a pop-up window. This style cannot be used with the WIN_WS_CHILD style.
WIN_WS_POPUPWINDOW Integer Creates a pop-up window with WIN_WS_BORDER, WIN_WS_POPUP, and WIN_WS_SYSMENU
styles. The WIN_WS_CAPTION and WIN_WS_POPUPWINDOW styles must be combined to
make the window menu visible.
WIN_WS_SIZEBOX Integer Creates a window that has a sizing border. Same as the WIN_WS_THICKFRAME style.
WIN_WS_SYSMENU Integer Creates a window that has a window-menu on its title bar. The WIN_WS_CAPTION style must
also be specified.
WIN_WS_TABSTOP Integer Specifies a control that can receive the keyboard focus when the user presses the TAB key.
Pressing the TAB key changes the keyboard focus to the next control with the
WIN_WS_TABSTOP style.
WIN_WS_THICKFRAME Integer Creates a window that has a sizing border. Same as the WIN_WS_SIZEBOX style.
WIN_WS_TILED Integer Creates an overlapped window. An overlapped window has a title bar and a border. Same as the
WIN_WS_OVERLAPPED style.
WIN_WS_TILEDWINDOW Integer Creates an overlapped window with the WIN_WS_OVERLAPPED, WIN_WS_CAPTION,
WIN_WS_SYSMENU, WIN_WS_THICKFRAME, WIN_WS_MINIMIZEBOX, and
WIN_WS_MAXIMIZEBOX styles. Same as the WIN_WS_OVERLAPPEDWINDOW style.
WIN_WS_VISIBLE Integer Creates a window that is initially visible.
WIN_WS_VSCROLL Integer Creates a window that has a vertical scroll bar.

47.2.4 Extended Window Style Constants


Following are the constants used for the possible extended window styles:

Name Type Description


WIN_WS_EX_ACCEPTFILES Integer Specifies that a window created with this style accepts drag-drop files.
WIN_WS_EX_APPWINDOW Integer Forces a top-level window onto the task bar when the window is visible.
WIN_WS_EX_CLIENTEDGE Integer Specifies that a window has a border with a sunken edge.
WIN_WS_EX_CONTEXTHELP Integer Includes a question mark in the title bar of the window. When the user clicks the
question mark, the cursor changes to a question mark with a pointer. If the user then
clicks a child window, the child receives a WM_HELP message. The child window
should pass the message to the parent window procedure, which should call the
WinHelp function using the HELP_WM_HELP command. The Help application displays
a pop-up window that typically contains help for the child window.
WIN_WS_EX_CONTEXTHELP cannot be used with the WIN_WS_MAXIMIZEBOX or
WIN_WS_MINIMIZEBOX styles.

Numara Software, Inc. and BMC Software, Inc. Confidential.


636 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


WIN_WS_EX_CONTROLPARENT Integer The window itself contains child windows that should take part in dialog box
navigation. If this style is specified, the dialog manager recourses into children of this
window when performing navigation operations such as handling the TAB key, an
arrow key, or a keyboard mnemonic.
WIN_WS_EX_DLGMODALFRAME Integer Creates a window that has a double border; the window can, optionally, be created
with a title bar by specifying the WIN_WS_CAPTION style in the dwStyle parameter.
WIN_WS_EX_LAYOUTRTL Integer Creates a window whose horizontal origin is on the right edge. Increasing horizontal
values advance to the left.
WIN_WS_EX_LEFT Integer Creates a window that has generic left-aligned properties. This is the default.
WIN_WS_EX_LEFTscroll bar Integer Draws the vertical scroll bar on the left side of the control.
WIN_WS_EX_LTRREADING Integer The window text is displayed using left-to-right reading-order properties. This is the
default.
WIN_WS_EX_MDICHILD Integer Creates a multiple-document interface (MDI) child window.
WIN_WS_EX_NOINHERITLAYOUT Integer A window created with this style does not pass its window layout to its child windows.
WIN_WS_EX_NOPARENTNOTIFY Integer Specifies that a child window created with this style does not send the
WM_PARENTNOTIFY message to its parent window when it is created or destroyed.
WIN_WS_EX_OVERLAPPEDWINDOW Integer Combines the WIN_WS_EX_CLIENTEDGE and WIN_WS_EX_WINDOWEDGE styles.
WIN_WS_EX_PALETTEWINDOW Integer Combines the WIN_WS_EX_WINDOWEDGE, WIN_WS_EX_TOOLWINDOW, and
WIN_WS_EX_TOPMOST styles.
WIN_WS_EX_RIGHT Integer The window has generic "right-aligned" properties. This depends on the window
class. Using the WIN_WS_EX_RIGHT style for static or edit controls has the same
effect as using the WIN_SS_RIGHT or WIN_ES_RIGHT style. Using this style with
button controls has the same effect as using WIN_BS_RIGHT and
WIN_BS_RIGHTBUTTON styles.
WIN_WS_EX_RIGHTscroll bar Integer Draws the vertical scroll bar on the right side of the client area. This is the default.
WIN_WS_EX_RTLREADING Integer The window text is displayed using right-to-left reading-order properties.
WIN_WS_EX_STATICEDGE Integer Creates a window with a three-dimensional border style intended to be used for items
that do not accept user input.
WIN_WS_EX_TOOLWINDOW Integer Creates a tool window; that is, a window intended to be used as a floating tool bar. A
tool window has a title bar that is shorter than a normal title bar, and the window title
is drawn using a smaller font. A tool window does not appear in the task bar or in the
dialog that appears when the user presses ALT+TAB. If a tool window has a system
menu, its icon is not displayed on the title bar. However, you can display the system
menu by right-clicking or by typing ALT+SPACE.
WIN_WS_EX_TOPMOST Integer Specifies that a window created with this style should be placed above all non-
topmost windows and should stay above them, even when the window is deactivated.
WIN_WS_EX_TRANSPARENT Integer Specifies that a window created with this style should not be painted until siblings
beneath the window (that were created by the same thread) have been painted. The
window appears transparent because the bits of underlying sibling windows have
already been painted.
WIN_WS_EX_WINDOWEDGE Integer Specifies that a window has a border with a raised edge.

47.2.5 Edit Control Style Constants


The following table displays the constants representing the edit control styles:

Name Type Description


WIN_ES_AUTOHSCROLL Integer Automatically scrolls text to the right by 10 characters when the user types a character at the end
of the line. When the user presses the ENTER key, the control scrolls all text back to position zero.
WIN_ES_AUTOVSCROLL Integer Automatically scrolls text up one page when the user presses the ENTER key on the last line.
WIN_ES_CENTER Integer Centers text in a multiline edit control.
WIN_ES_LEFT Integer Left-aligns text.
WIN_ES_LOWERCASE Integer Converts all characters to lowercase as they are typed into the edit control.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 47 - Windowing Functions - 637

Name Type Description


WIN_ES_MULTILINE Integer Designates a multiline edit control. The default is single-line edit control.
When the multiline edit control is in a dialog box, the default response to pressing the ENTER key
is to activate the default button. To use the ENTER key as a carriage return, use the
WIN_ES_WANTRETURN style.
When the multiline edit control is not in a dialog box and the WIN_ES_AUTOVSCROLL style is
specified, the edit control shows as many lines as possible and scrolls vertically when the user
presses the ENTER key. If you do not specify WIN_ES_AUTOVSCROLL, the edit control shows as
many lines as possible and beeps if the user presses the ENTER key when no more lines can be
displayed.
If you specify the WIN_ES_AUTOHSCROLL style, the multiline edit control automatically scrolls
horizontally when the caret goes past the right edge of the control. To start a new line, the user
must press the ENTER key. If you do not specify WIN_ES_AUTOHSCROLL, the control
automatically wraps words to the beginning of the next line when necessary. A new line is also
started if the user presses the ENTER key. The window size determines the position of the word
wrap. If the window size changes, the word wrapping position changes and the text is
redisplayed.
Multiline edit controls can have scroll bars. An edit control with scroll bars processes its own
scroll bar messages. Note that edit controls without scroll bars scroll as described in the previous
paragraphs and process any scroll messages sent by the parent window.
WIN_ES_NOHIDESEL Integer Negates the default behavior for an edit control. The default behavior hides the selection when the
control loses the input focus and inverts the selection when the control receives the input focus. If
you specify WIN_ES_NOHIDESEL, the selected text is inverted, even if the control does not have
the focus.
WIN_ES_NUMBER Integer Allows only digits to be entered into the edit control.
WIN_ES_OEMCONVERT Integer Converts text entered in the edit control. The text is converted from the Windows character set to
the OEM character set and then back to the Windows set. This ensures proper character
conversion when the application calls the CharToOem function to convert a Windows string in the
edit control to OEM characters. This style is most useful for edit controls that contain filenames.
WIN_ES_PASSWORD Integer Displays an asterisk (*) for each character typed into the edit control. You can use the
WIN_EM_SETPASSWORDCHAR message to change the character that is displayed.
WIN_ES_READONLY Integer Prevents the user from typing or editing text in the edit control.
WIN_ES_RIGHT Integer Right-aligns text in a multiline edit control.
WIN_ES_UPPERCASE Integer Converts all characters to uppercase as they are typed into the edit control.
WIN_ES_WANTRETURN Integer Specifies that a carriage return be inserted when the user presses the ENTER key while entering
text into a multiline edit control in a dialog box. If you do not specify this style, pressing the ENTER
key has the same effect as pressing the dialog box’s default push button. This style has no effect
on a single-line edit control.

47.2.6 Static Control Style Constants


Name Type Description
WIN_SS_BITMAP Integer Specifies a bitmap is to be displayed in the static control. The error code text is the name
of a bitmap (not a filename) defined elsewhere in the resource file. The style ignores the
nWidth and nHeight parameters; the control automatically sizes itself to accommodate the
bitmap.
WIN_SS_BLACKFRAME Integer Specifies a box with a frame drawn in the same color as the window frames. This color is
black in the default Windows color scheme.
WIN_SS_BLACKRECT Integer Specifies a rectangle filled with the current window frame color. This color is black in the
default Windows color scheme.
WIN_SS_CENTER Integer Specifies a simple rectangle and centers the error code text in the rectangle. The text is
formatted before it is displayed. Words that extend past the end of a line are automatically
wrapped to the beginning of the next centered line.
WIN_SS_CENTERIMAGE Integer Specifies that the midpoint of a static control with the WIN_SS_BITMAP or WIN_SS_ICON
style is to remain fixed when the control is resized. The four sides are adjusted to
accommodate a new bitmap or icon.
If a static control has the WIN_SS_BITMAP style and the bitmap is smaller than the
control’s client area, the client area is filled with the color of the pixel in the upper-left
corner of the bitmap. If a static control has the WIN_SS_ICON style, the icon does not
appear to paint the client area.

Numara Software, Inc. and BMC Software, Inc. Confidential.


638 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


WIN_SS_ENDELLIPSIS Integer Replaces part of the given string with ellipses, if necessary, so that the result fits in the
specified rectangle. WIN_SS_ENDELLIPSIS can be specified to replace characters at the
end of a string.
WIN_SS_ENHMETAFILE Integer Specifies that an enhanced metafile is to be displayed in the static control. The given text is
the name of a metafile. An enhanced metafile static control has a fixed size; the metafile is
scaled to fit the static control’s client area.
WIN_SS_ETCHEDFRAME Integer Draws the frame of the static contorl using the EDGE_ETCHED edge style.
WIN_SS_ETCHEDHORZ Integer Draws the top and bottom edges of the static control using the EDGE_ETCHED edge style.
WIN_SS_ETCHEDVERT Integer Draws the left and right edges of the static control using the EDGE_ETCHED edge style.
WIN_SS_GRAYFRAME Integer Specifies a box with a frame drawn with the same color as the screen background
(desktop). This color is gray in the default Windows color scheme.
WIN_SS_GRAYRECT Integer Specifies a rectangle filled with the current screen background color. This color is gray in
the default Windows color scheme.
WIN_SS_ICON Integer Specifies an icon displayed in the dialog box. The given text is the name of an icon (not a
filename) defined elsewhere in the resource file. The style ignores the nWidth and nHeight
parameters; the icon automatically sizes itself.
WIN_SS_LEFT Integer Specifies a simple rectangle and left-aligns the given text in the rectangle. The text is
formatted before it is displayed. Words that extend past the end of a line are automatically
wrapped to the beginning of the next left-aligned line.
WIN_SS_LEFTNOWORDWRAP Integer Specifies a simple rectangle and left-aligns the given text in the rectangle. Tabs are
expanded but words are not wrapped. Text that extends past the end of a line is clipped.
WIN_SS_NOPREFIX Integer Prevents interpretation of any ampersand (&) characters in the control’s text as accelerator
prefix characters. These are displayed with the ampersand removed and the next character
in the string underlined. This static control style can be included with any of the defined
static controls.
An application can combine WIN_SS_NOPREFIX with other styles by using the bitwise OR
(|) operator. This can be useful when filenames or other strings that can contain an
ampersand (&) must be displayed in a static control in a dialog box.
WIN_SS_NOTIFY Integer Sends the parent window STN_CLICKED, STN_DBLCLK, STN_DISABLE, and
STN_ENABLE notification messages when the user clicks or double-clicks the control.
WIN_SS_OWNERDRAW Integer Specifies that the owner of the static control is responsible for drawing the control. The
owner window receives a WM_DRAWITEM message whenever the control needs to be
drawn.
WIN_SS_PATHELLIPSIS Integer Replaces part of the given string with ellipses, if necessary, so that the result fits in the
specified rectangle. WIN_SS_PATHELLIPSIS can be specified to replace characters in the
middle of a string. If the string contains backslash (\) characters, WIN_SS_PATHELLIPSIS
preserves as much of the text after the last backslash as possible.
WIN_SS_REALSIZECONTROL Integer Windows XP Adjusts the bitmap to fit the size of the static control. For example, changing
the locale can change the system font, and thus controls might be resized. If a static
control had a bitmap, the bitmap would no longer fit the control. This style bit dictates
automatic redimensioning of bitmaps to fit their controls.
If WIN_SS_CENTERIMAGE is specified, the bitmap or icon is centered (and clipped if
needed). If WIN_SS_CENTERIMAGE is not specified, the bitmap or icon is stretched or
shrunk.
Note that the redimensioning in the two axes are independent, and the result can have a
changed aspect ratio.
WIN_SS_REALSIZEIMAGE Integer Prevents a static icon or bitmap control (that is, static controls that have the WIN_SS_ICON
or WIN_SS_BITMAP style) from being resized as it is loaded or drawn. If the icon or bitmap
os larger than the destination area, the image is clipped.
WIN_SS_RIGHT Integer Specifies a simple rectangle and right-aligns the given text in the rectangle. The text is
formatted before it is displayed. Words that extend past the end of a line are automatically
wrapped to the beginning of the next right-aligned line.
WIN_SS_RIGHTJUST Integer Specifies that the lower right corner of a static control with the WIN_SS_ICON or
WIN_SS_BITMAP style is to remain fixed with the control is resized. Only the top and left
sides are adjusted to accommodate a new bitmap or icon.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 47 - Windowing Functions - 639

Name Type Description


WIN_SS_SIMPLE Integer Specifies a simple rectangle and displays a single line of left-aligned text in the rectangle.
The text line cannot be shortened or altered in any way. Also, if the control is dizabled, the
control does not gray its text.
WIN_SS_SUNKEN Integer Draws a half-sunken order around a static control.
WIN_SS_WHITEFRAME Integer Specifies a box with a frame drawn with the same color as the window backgrounds. This
color is white in the default Windows color scheme.
WIN_SS_WHITERECT Integer Specifies a rectangle filled with the current window background color. This color is white in
the default Windows color scheme.
WIN_SS_WORDELLIPSIS Integer Truncates text that does not fit and adds ellipses.

47.2.6.0.1 Combobox Style Constants


Following are the constants representing the available combobox class styles:

Name Type Description


WIN_CBS_AUTOHSCROLL Integer Automatically scrolls the text in an edit control to the right when the user types a
character at the end of the line. If this style is not set, only text that fits within the
rectangular boundary is allowed.
WIN_CBS_DISABLENOSCROLL Integer Shows a dizabled vertical scroll bar in the list box when the box does not contain
enough items to scroll. Without this style, the scroll bar is hidden when the list box does
not contain enough items.
WIN_CBS_DROPDOWN Integer Similar to WIN_CBS_SIMPLE, except that the list box is not displayed unless the user
selects an icon next to the edit control.
WIN_CBS_DROPDOWNLIST Integer Similar to WIN_CBS_DROPDOWN, except that the edit control is replaced by a static
text item that displays the current selection in the list box.
WIN_CBS_HASSTRINGS Integer Specifies that an owner-drawn combo box contains items consisting of strings. The
combo box maintains the memory and address for the strings, so the application can
use the WIN_CB_GETLBTEXT message to retrieve the text for a particular item.
WIN_CBS_LOWERCASE Integer Converts to lowercase any uppercase characters entered into the edit control of a
combo box.
WIN_CBS_NOINTEGRALHEIGHT Integer Specifies that the size of the combo box is exactly the size specified by the application
when it created the combo box. Normally, Windows sizes a combo box so that it does
not display partial items.
WIN_CBS_OEMCONVERT Integer Converts text entered in the combo box edit control. The text is converted from the
Windows character set to the OEM character set and then back to the Windows set.
This ensures proper character conversion when the application calls the CharToOem
function to convert a Windows string in the combo box to OEM characters. This style is
most useful for combo boxes that contain filenames and applies only to combo boxes
created with the WIN_CBS_SIMPLE or WIN_CBS_DROPDOWN style.
WIN_CBS_OWNERDRAWFIXED Integer Specifies that the owner of the list box is responsible for drawing its contents and that
the items in the list box are all the same height. The owner window receives a
WM_MEASUREITEM message when the combo box is created and a WM_DRAWITEM
message when a visual aspect of the combo box has changed.
WIN_CBS_OWNERDRAWVARIABLE Integer Specifies that the owner of the list box is responsible for drawing its contents and that
the items in the list box are variable in height. The owner window receives a
WM_MEASUREITEM message for each item in the combo box when you create the
combo box; the owner window receives a WM_DRAWITEM message when a visual
aspect of the combo box has changed.
WIN_CBS_SIMPLE Integer Displays the list box at all times. The current selection in the list box is displayed in the
edit control.
WIN_CBS_SORT Integer Automatically sorts strings entered into the list box.
WIN_CBS_UPPERCASE Integer Converts to uppercase any lowercase characters entered into the edit control of a
combo box.

47.2.7 Combobox Message Constants


Following is the list of constants representing the combobox messages:

Numara Software, Inc. and BMC Software, Inc. Confidential.


640 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


WIN_CB_ADDSTRING Integer Adds a string to the list box of a combo box. If the combo box does not have the
WIN_CBS_SORT style, the string is added to the end of the list. Otherwise, the
string is inserted into the list, and the list is sorted.
WIN_CB_DELETESTRING Integer Deletes a string in the list box of a combo box.
WIN_CB_DIR Integer Adds names to the list displayed by the combo box. The message adds the names
of directories and files that match a specified string and set of file attributes.
WIN_CB_DIR can also add mapped drive letters to the list.
WIN_CB_FINDSTRING Integer Searches the list box of a combo box for an item beginning with the characters in a
specified string.
WIN_CB_FINDSTRINGEXACT Integer Finds the first list box string in a combo box that matches the string specified in the
lParam parameter.
WIN_CB_GETCOUNT Integer Retrieves the number of items in the list box of a combo box.
WIN_CB_GETCURSEL Integer Retrieves the index of the currently selected item, if any, in the list box of a combo
box.
WIN_CB_GETDROPPEDCONTROLRECT Integer Retrieves the screen coordinates of a combo box in its dropped-down state.
WIN_CB_GETDROPPEDSTATE Integer Determines whether the list box of a combo box is dropped down.
WIN_CB_GETDROPPEDWIDTH Integer Retrieves the minimum allowable width, in pixels, of the list box of a combo box
with the WIN_CBS_DROPDOWN or WIN_CBS_DROPDOWNLIST style.
WIN_CB_GETEDITSEL Integer Gets the starting and ending character positions of the current selection in the edit
control of a combo box.
WIN_CB_GETEXTENDEDUI Integer Determines whether a combo box has the default user interface or the extended
user interface.
WIN_CB_GETHORIZONTALEXTENT Integer Retrieves from a combo box the width, in pixels, by which the list box can be
scrolled horizontally (the scrollable width). This is applicable only if the list box has
a horizontal scroll bar.
WIN_CB_GETITEMDATA Integer Retrieves the application-supplied value associated with the specified item in the
combo box.
WIN_CB_GETITEMHEIGHT Integer Determines the height of list items or the selection field in a combo box.
WIN_CB_GETLBTEXT Integer Retrieves a string from the list of a combo box.
WIN_CB_GETLBTEXTLEN Integer Retrieve the length, in characters, of a string in the list of a combo box.
WIN_CB_GETLOCALE Integer Retrieves the current locale of the combo box. The locale is used to determine the
correct sorting order of displayed text for combo boxes with the WIN_CBS_SORT
style and text added by using the WIN_CB_ADDSTRING message.
WIN_CB_GETTOPINDEX Integer Retrieves the zero-based index of the first visible item in the list box portion of a
combo box. Initially, the item with index 0 is at the top of the list box, but if the list
box contents have been scrolled, another item can be at the top.
WIN_CB_INITSTORAGE Integer Allocates memory for storing list box items and is sent before adding a large
number of items to the list box portion of a combo box.
WIN_CB_INSERTSTRING Integer Inserts a string into the list box of a combo box. Unlike the WIN_CB_ADDSTRING
message, the WIN_CB_INSERTSTRING message does not cause a list with the
WIN_CBS_SORT style to be sorted.
WIN_CB_LIMITTEXT Integer Limits the length of the text the user can type into the edit control of a combo box.
WIN_CB_RESETCONTENT Integer Removes all items from the list box and edit control of a combo box.
WIN_CB_SELECTSTRING Integer Searches the list of a combo box for an item that begins with the characters in a
specified string. If a matching item is found, it is selected and copied to the edit
control.
WIN_CB_SETCURSEL Integer Selects a string in the list of a combo box. If necessary, the list scrolls the string
into view. The text in the edit control of the combo box changes to reflect the new
selection, and any previous selection in the list is removed.
WIN_CB_SETDROPPEDWIDTH Integer Sets the maximum allowable width, in pixels, of the list box of a combo box with the
WIN_CBS_DROPDOWN or WIN_CBS_DROPDOWNLIST style.
WIN_CB_SETEDITSEL Integer Selects characters in the edit control of a combo box.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 47 - Windowing Functions - 641

Name Type Description


WIN_CB_SETEXTENDEDUI Integer Selects either the default user interface or the extended user interface for a combo
box that has the WIN_CBS_DROPDOWN or WIN_CBS_DROPDOWNLIST style.
WIN_CB_SETHORIZONTALEXTENT Integer Sets the width, in pixels, by which a list box can be scrolled horizontally (the
scrollable width). If the width of the list box is smaller than this value, the horizontal
scroll bar horizontally scrolls items in the list box. If the width of the list box is equal
to or greater than this value, the horizontal scroll bar is hidden or, if the combo box
has the WIN_CBS_DISABLENOSCROLL style, dizabled.
WIN_CB_SETITEMDATA Integer Sets the value associated with the specified item in a combo box.
WIN_CB_SETITEMHEIGHT Integer Sets the height of list items or the selection field in a combo box.
WIN_CB_SETLOCALE Integer Sets the current locale of the combo box. If the combo box has the
WIN_CBS_SORT style and strings are added using WIN_CB_ADDSTRING, the
locale of a combo box affects how list items are sorted.
WIN_CB_SETTOPINDEX Integer Ensures that a particular item is visible in the list box of a combo box. The system
scrolls the list box contents so that either the specified item appears at the top of
the list box or the maximum scroll range has been reached.
WIN_CB_SHOWDROPDOWN Integer Shows or hides the list box of a combo box that has the WIN_CBS_DROPDOWN or
WIN_CBS_DROPDOWNLIST style.

47.2.8 Font Weight Constants


The following constants represent the font weights in the range 0 through 1000. For example, 400 is normal and
700 is bold. If this value is zero, a default weight is used:

Name Type Description


WIN_FW_DONTCARE Integer 0
WIN_FW_THIN Integer 100
WIN_FW_EXTRALIGHT Integer 200
WIN_FW_ULTRALIGHT Integer 200
WIN_FW_LIGHT Integer 300
WIN_FW_NORMAL Integer 400
WIN_FW_REGULAR Integer 400
WIN_FW_MEDIUM Integer 500
WIN_FW_SEMIBOLD Integer 600
WIN_FW_DEMIBOLD Integer 600
WIN_FW_BOLD Integer 700
WIN_FW_EXTRABOLD Integer 800
WIN_FW_ULTRABOLD Integer 800
WIN_FW_HEAVY Integer 900
WIN_FW_BLACK Integer 900

47.2.9 Window System Metric Constants


The table below lists all system metric constants

Name Type Description


WIN_SM_ARRANGE Integer Windows 95 only: Flags specifying how the system arranged minimized windows. For
more information about minimized windows, see the following Remarks section.
WIN_SM_CLEANBOOT Integer Windows 95 only: Value that specifies how the system was started:0 Normal boot1 Fail-
safe boot2 Fail-safe with network bootFail-safe boot (also called SafeBoot) bypasses
the user's startup files.
WIN_SM_CMONITORS Integer Number of monitors
WIN_SM_CMOUSEBUTTONS Integer Number of mouse buttons
WIN_SM_CXBORDER Integer Window border width

Numara Software, Inc. and BMC Software, Inc. Confidential.


642 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


WIN_SM_CXCURSOR Integer Cursor width
WIN_SM_CXDLGFRAME Integer Dialog window frame width
WIN_SM_CXDOUBLECLK Integer Windows NT only: Height of a rectangle around the location of a first click in a double-
click sequence. The second click must occur within this rectangle for the system to
consider the two clicks a double-click.Windows 95 only: Height, in pixels, of the
rectangle within which two successive mouse clicks must fall to generate a double-click.
(The two clicks must also occur within a specified time.)
WIN_SM_CXDRAG Integer Avoid drag x tolerance
WIN_SM_CXEDGE Integer 3-D border width
WIN_SM_CXFIXEDFRAME Integer Dialog window frame width
WIN_SM_CXFRAME Integer Width of window frame for a window that can be resized.
WIN_SM_CXFULLSCREEN Integer Full screen client area width
WIN_SM_CXHSCROLL Integer Horizontal scroll arrow width
WIN_SM_CXHTHUMB Integer Width of horizontal scroll bar thumb box
WIN_SM_CXICON Integer Icon width; this is typically 32 , but can vary depending on the installed display
hardware.Windows 95 only: The LoadIcon function can only load icons of these
dimensions.
WIN_SM_CXICONSPACING Integer Horizontal icon spacing. Windows NT only: Width of rectangular cell that Program
Manager uses to position tiled icons.Windows 95 only: Width of a grid cell for items in
large icon view, in pixels. Each item fits into a rectangle of this size when arranged.
These values are always greater than or equal to WIN_SM_CXICON and
WIN_SM_CYICON.
WIN_SM_CXMAXIMIZED Integer Default width of a maximized top-level window, in pixels
WIN_SM_CXMAXTRACK Integer Windows 95 only: Default maximum width of a window that has a caption and sizing
borders. The user cannot drag the window frame to a size larger than these dimensions.
A window can override these values by processing the WM_GETMINMAXINFO message.
WIN_SM_CXMENUCHECK Integer Width of the default menu check-mark bitmap, in pixels.
WIN_SM_CXMENUSIZE Integer Width of menu bar buttons (such as multiple document (MIDI) child close), in pixels.
WIN_SM_CXMIN Integer Minimum window width, in pixels
WIN_SM_CXMINIMIZED Integer Minimized window width, in pixels
WIN_SM_CXMINSPACING Integer Minimized window spacing width; Dimensions of a grid cell for minimized windows, in
pixels. Each minimized window fits into a rectangle this size when arranged. These
values are always greater than or equal to WIN_SM_CXMINIMIZED and
WIN_SM_CYMINIMIZED.
WIN_SM_CXMINTRACK Integer Minimum tracking width of a window. The user cannot drag the window frame to a size
smaller than these dimensions. A window can override these values by processing the
WM_GETMINMAXINFO message.
WIN_SM_CXSCREEN Integer Screen width in pixels
WIN_SM_CXSIZE Integer Minimize/Maximize icon width
WIN_SM_CXSIZEFRAME Integer Window sizing frame width
WIN_SM_CXSMICON Integer Small icon width
WIN_SM_CXSMSIZE Integer Small caption button width
WIN_SM_CXVIRTUALSCREEN Integer Virtual screen width
WIN_SM_CXVSCROLL Integer Vertical scroll arrow width
WIN_SM_CYBORDER Integer Window border height
WIN_SM_CYCAPTION Integer Caption bar height
WIN_SM_CYCURSOR Integer Cursor height
WIN_SM_CYDLGFRAME Integer Dialog window frame height

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 47 - Windowing Functions - 643

Name Type Description


WIN_SM_CYDOUBLECLK Integer Windows NT only: Width of a rectangle around the location of a first click in a double-
click sequence. The second click must occur within this rectangle for the system to
consider the two clicks a double-click.Windows 95 only: width, in pixels, of the rectangle
within which two successive mouse clicks must fall to generate a double-click. (The two
clicks must also occur within a specified time.)
WIN_SM_CYDRAG Integer Avoid drag y tolerance
WIN_SM_CYEDGE Integer 3-D border height
WIN_SM_CYFIXEDFRAME Integer Dialog window frame height
WIN_SM_CYFRAME Integer Height of window frame for a window that can be resized.
WIN_SM_CYFULLSCREEN Integer Full screen client area height
WIN_SM_CYHSCROLL Integer Screen height in pixels
WIN_SM_CYICON Integer Icon height; this is typically 32 , but can vary depending on the installed display
hardware.Windows 95 only: The LoadIcon function can only load icons of these
dimensions.
WIN_SM_CYICONSPACING Integer Vertical icon spacing. Windows NT only: Height of rectangular cell that Program Manager
uses to position tiled icons.Windows 95 only: Height of a grid cell for items in large icon
view, in pixels. Each item fits into a rectangle of this size when arranged. These values
are always greater than or equal to WIN_SM_CXICON and WIN_SM_CYICON.
WIN_SM_CYKANJIWINDOW Integer Kanji window height
WIN_SM_CYMAXIMIZED Integer Height of maximized window
WIN_SM_CYMAXTRACK Integer Windows 95 only: Default maximum dimensions of a window that has a caption and
sizing borders. The user cannot drag the window frame to a size larger than these
dimensions. A window can override these values by processing the
WM_GETMINMAXINFO message.
WIN_SM_CYMENU Integer Menu bar height
WIN_SM_CYMENUCHECK Integer Menu check-mark height
WIN_SM_CYMENUSIZE Integer Height of menu bar buttons (such as multiple document (MIDI) child close), in pixels.
WIN_SM_CYMIN Integer Minimum window height
WIN_SM_CYMINIMIZED Integer Minimized window height
WIN_SM_CYMINSPACING Integer Minimized window spacing height; height of a grid cell for minimized windows, in pixels.
Each minimized window fits into a rectangle this size when arranged. These values are
always greater than or equal to WIN_SM_CXMINIMIZED and WIN_SM_CYMINIMIZED.
WIN_SM_CYMINTRACK Integer Minimum tracking height of a window. The user cannot drag the window frame to a size
smaller than these dimensions. A window can override these values by processing the
WM_GETMINMAXINFO message.
WIN_SM_CYSCREEN Integer Screen height in pixels
WIN_SM_CYSIZE Integer Minimize/Maximize icon height
WIN_SM_CYSIZEFRAME Integer Window sizing frame height
WIN_SM_CYSMCAPTION Integer Small caption height
WIN_SM_CYSMICON Integer Small icon height
WIN_SM_CYSMSIZE Integer Small caption button height
WIN_SM_CYVIRTUALSCREEN Integer Virtual screen height
WIN_SM_CYVSCROLL Integer Vertical scroll arrow height
WIN_SM_CYVTHUMB Integer Vertical scroll thumb height
WIN_SM_DBCSENABLED Integer Double-Byte Char Set enabled
WIN_SM_DEBUG Integer Debug version flag
WIN_SM_MENUDROPALIGNMENT Integer Left or right menu drop
WIN_SM_MIDEASTENABLED Integer Hebrew and Arabic enabled flag
WIN_SM_MOUSEPRESENT Integer Mouse present flag
WIN_SM_MOUSEWHEELPRESENT Integer Mouse wheel present flagMouse wheel present flag
WIN_SM_NETWORK Integer Network present flag

Numara Software, Inc. and BMC Software, Inc. Confidential.


644 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


WIN_SM_PENWINDOWS Integer Pen extensions installed
WIN_SM_REMOTESESSION Integer This system metric is used in a Terminal Services environment. If the calling process is
associated with a Terminal Services client session, the return value is nonzero. If the
calling process is associated with the Terminal Server console session, the return value
is zero. The console session is not necessarily the physical console
WIN_SM_SAMEDISPLAYFORMAT Integer Same color format flag
WIN_SM_SECURE Integer Security present flag
WIN_SM_SHOWSOUNDS Integer Present sounds visually
WIN_SM_SLOWMACHINE Integer Slow processor flag
WIN_SM_SWAPBUTTON Integer Mouse buttons swapped flag
WIN_SM_XVIRTUALSCREEN Integer Virtual screen x origin
WIN_SM_YVIRTUALSCREEN Integer Virtual screen y origin

47.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli Windowing function group module has Predefined Handle Data
Types and Predefined Structures.

47.3.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Data Type Description


Window Object type: reference to the Windows Window WinHandle
Font Object type: reference to the font handle

Window
The Window data type is a reference to the handle of a window.
The function WindowCreate returns a value of this object type that other functions expect as their first argument.
Any open window and thus the value of this object type should always be closed by the WindowDestroy
function. Also the functions WindowFind, WindowListChildren and WindowListTopLevel return a handle of
this type. Handles returned by these functions must NOT be closed, because they are handles generated by
Windows.

Font
The Font data type is a reference to the handle to a font used in a window.
The function WindowCreateFont returns a value of this object type that other functions might expect because an
argument for window font definition.

47.3.2 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated.
Following you find a list of all predefined data types of type structure:

Data Type Description


WindowSize A list of integers defining the size of windows.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 47 - Windowing Functions - 645

WindowSize
The WindowSize structure represents a list of integers defining the size of a number of windows.
Elements:

Elements Element Type Description


Width Integer The width of the window displayed.
Height Integer The height of the window displayed.

47.4 Functions
Following you find a list of all existing functions for the Windowing functions module:

Function OS Description
IsWindow Check the validity of a window handle

WindowCreate Create a window

WindowCreateFont Create a logical font with the specified characteristics

WindowDestroy Destroy a Chilli window

WindowFind Find a system Window with matching title

WindowGetClassName Get the name of the class to which the specified window belongs

WindowGetClientSize Return the size of a window's client area.

WindowGetSize Return the size of a window.

WindowGetSystemMetric Retrieve various system metrics and system configuration settings.

WindowGetText Get the specified window's title bar

WindowGetTextSize Compute the width and height of the specified string of text using the given font.

WindowListChildren Find all child windows that belong to the specified parent window

WindowListTopLevel Find all top-level windows on the screen

WindowMove Change the position and dimensions of the specified window.

WindowRegisterMsg Register a window system message

WindowSendMsg Send a message to another window

WindowSetText Set the text of the specified window's title bar

IsWindow
Check the validity of a window handle.
Syntax:
Bool IsWindow (Window WinHandle)
WinHandle is the handle of the window to be verified.
Returns:
TRUE if the handle is valid or FALSE if the handle is invalid or the operation failed.

WindowCreate
Create a new window. The function has the following signatures:

Numara Software, Inc. and BMC Software, Inc. Confidential.


646 - BMC FootPrints Asset Core - Chilli Reference

Syntax:
Window WindowCreate (String Title, Int Show)
Window WindowCreate (Int ExtStyle, Int Style, String Proc, String Class, String Title, Int x,
Int y, Int Width, Int Height, Window hParent, Int Show)
Title is the window title to give to the newly created window.
Show is the initial state the window is displayed in.
ExtStyle defines the extended style of the window to be created. This can be any of the predefined
contstants listed above.
Style defines the style of the window to be created. This can be any of the predefined constants listed above.
Proc defines a callback procedure for user interaction with the window.
Class defines the class of the window to be created. This can be any of the predefined constants listed
above.
x defines the horizontal position of the upper left window corner from the upper left corner of the screen.
y defines the vertical position of the upper left window corner from the upper left corner of the screen.
Width defines the width of the window in pixels.
Height defines the height of the window in pixels.
hParent is the handle to the parent window if the current window is a child. If the window does not have a
parent the value is 0.
Returns:
The function returns a handle to the window if successful or 0 if the operation failed. The handle should be used
when calling all other window functions.
Comments:
The Show parameter must be one of the predefined constants with the described results, listed under Predefined
Constants earlier in this chapter. For a full-fledged window creation function use the optional parameters Style,
Proc, Class, and so on, which allow the creation of any type of information using most of the possible Windows
parameters, which are also described in the paragraph Predefined Constants. The procedure to be executed can be
user defined and must be located either in the same script or in a linked script. The name of the procedure must
be enclosed in quotes (“).

WindowCreateFont
Create a logical font with the specified characteristics.
Font WindowCreateFont ()
Returns:
The handle of the font if successful, 0 otherwise.
Comments:
The created font can be used for drawing any window text in any window.

WindowDestroy
Destroy a window created by WindowCreate.
Syntax:
Bool WindowDestroy (Window WinHandle)
WinHandle is the handle to the window to be destroyed, which was returned by the WindowCreate
function.
Returns:
TRUE if the window was successfully destroyed, FALSE if the function failed or the supplied handle is invalid.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 47 - Windowing Functions - 647

Comments:
The supplied handle is verified and causes the function to fail if it is not the same because the value returned by
WindowCreate. This function does not destroy other windows such as those found by WindowFind, because a
process cannot destroy a window created by a different process. This is a limitation imposed by the Microsoft
Windows environment.

WindowFind
Find a Windows window using the title string as the search criterion.
Syntax:
Window WindowFind (String Title)
Title is the window title to search for.
Returns:
The function returns a Windows handle to the window if successful and 0 if the operation failed. This handle is
not the same type as the handle returned by WindowCreate.
Comments:
The function matches the first window which has a title that exactly matches the supplied string. The comparison
is case sensitive.
The returned handle is an actual MS Windows handle and can be used to send messages to the window using the
WindowSendMsg function. The handle is generated by the Windows operating systems and thus cannot be
destroyed through Chilli. This is due to the fact that in MS Windows a window can only be destroyed by its
owner, that is, the application that created it. This is a limitation imposed by the Microsoft Windows
environment.
Example:
This example sends a message to all children of the parent window.
proc main ()

int i, iChildren[]
string szText, WindowName, ButtonName
window win

win = WindowFind (WindowName)


ButtonName = “Cancel”

iChildren = WindowListChildren (win);

for (i=1; i<=ArrayGetSize (iChildren); i+=1)


szText = WindowGetText (iChildren[i]);
if (szText == ButtonName)
WindowSendMsg (iChildren[i], 0x0201, 0, 0)
WindowSendMsg (iChildren[i], 0x0202, 0, 0)
return
endif
endfor
endproc

WindowGetClassName
Get the name of the class to which the specified window belongs.
Syntax:
String WindowGetClassName (Window WinHandle)
WinHandle is the handle to the window.
Returns:
The class name of the identified window if the operation was successful, or an empty string if the supplied handle
was not valid or the function failed otherwise.

Numara Software, Inc. and BMC Software, Inc. Confidential.


648 - BMC FootPrints Asset Core - Chilli Reference

Comments:
A window class is a set of attributes that the system uses as a template to create a window. Every window is a
member of a window class. Examples of some predefined system classes include BUTTON, COMBOBOX and STATIC.
Example:
This example prints the title and the class name of all windows found.
proc ListChildren (Int win)

int i, iChildren[];
string szText;
window win

iChildren = WindowListChildren (win);

for (i=1; i<=ArrayGetSize (iChildren); i+=1)


szText = WindowGetText (iChildren[i])
if (szText != '')
print (" " + szText + "/" + WindowGetClassName (iChildren[i]) + "\r\n")
endif
endfor

endproc

WindowGetClientSize
Return the size of a window's client area.
Syntax:
WindowSize WindowGetClientSize (Window hWindow)
Returns:
A WindowSize structure containing the width and height of the client area, or an empty structure if the operation
failed.
Comments:
The client are size excludes the title bar and any edges.

WindowGetSize
Return the size of a window.
Syntax:
WindowSize WindowGetSize (Window hWindow)
Returns:
A WindowSize structure containing the width and height of the window.

WindowGetSystemMetric
Retrieve various system metrics and system configuration settings.
Syntax:
Int WindowGetSystemMetric (Int Metric)
Returns:
An integer value for the metric requested if the operation was successful or 0 if the function failed.
Comments:
Possible system metrics to be retrieved are the widths and heights of display elements.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 47 - Windowing Functions - 649

WindowGetText
Get the specified window's title bar (if it has one).
Syntax:
String WindowGetText (Window WinHandle)
WinHandle is the handle to the window.
Returns:
The title of the identified window if the operation was successful, or an empty string if the window does not have
a title or the function failed.
Comments:
If the specified window is a control, the text of the control is copied. However, this function can not retrieve the
text of a control in another application.
Example:
This example prints the title and the class name of all windows found.
proc ListChildren (Int win)

int i, iChildren[];
string szText;

iChildren = WindowListChildren (win);

for (i=1; i<=ArrayGetSize (iChildren); i+=1)


szText = WindowGetText (iChildren[i])
if (szText != '')
print (" " + szText + "/" + WindowGetClassName (iChildren[i]) + "\r\n")
endif
endfor

endproc

WindowGetTextSize
Compute the width and height of the specified string of text using the given font.
Syntax:
WindowSize WindowGetTextSize (string Text, Font hFont)
Returns:
A WindowSize structure containing the width and height of the supplied text string in the given font.

WindowListChildren
Find all the child windows that belong to the specified parent window.
Syntax:
Window[] WindowListChildren (Window WinHandle)
WinHandle is the handle to the window.
Returns:
An array of Window WinHandles representing the list of all the children windows found. The list is empty if an
error occurred.
Comments:
If a child window has created child windows of its own, this function lists those windows as well.

Numara Software, Inc. and BMC Software, Inc. Confidential.


650 - BMC FootPrints Asset Core - Chilli Reference

The returned handles are Windows handles and can be used to send messages to the window using the
WindowSendMsg function. The handles are generated by the Windows operating systems and thus cannot and
must not be destroyed through Chilli. This is due to the fact that in Windows a window can only be destroyed by
its owner, that is, the application that created it.
Example:
This example prints the title and the class name of all windows found.
proc ListChildren (Int win)

int i, iChildren[];
string szText;

iChildren = WindowListChildren (win);

for (i=1; i<=ArrayGetSize (iChildren); i+=1)


szText = WindowGetText (iChildren[i])
if (szText != '')
print (" " + szText + "/" + WindowGetClassName (iChildren[i]) + "\r\n")
endif
endfor

endproc

WindowListTopLevel
Find all top-level windows on the screen.
Syntax:
window[] WindowListTopLevel ()
Returns:
An array of Window WinHandles representing the list of all the top level windows found if the operation was
successful. The list is empty if an error occurred or if the operation failed.
Comments:
The returned handles are Windows handles and can be used to send messages to the window using the
WindowSendMsg function. The handles are generated by the Windows operating systems and thus cannot and
must not be destroyed through Chilli. This is due to the fact that in Windows a window can only be destroyed by
its owner, that is, the application that created it.
Example:
This example prints the title of each top level window found.
proc main ()

int i, iWindow[]
string szText

iWindow = WindowListTopLevel ()

for (i=1; i<=ArrayGetSize (iWindow); i+=1)


szText = WindowGetText (iWindow[i])
if (szText != '')
print (szText + "\r\n")
endif
endfor

endproc

WindowMove
Change the position and dimensions of the specified window.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 47 - Windowing Functions - 651

Syntax:
Bool WindowMove (Window WinHandle, Int x, Int y, Int Width, Int Height)
Returns:
TRUE if the function succeeded, FALSE otherwise.
Comments:
For a top-level window, the position and dimensions are relative to the upper-left corner of the screen. For a child
window, they are relative to the upper-left corner of the parent window's client area.

WindowRegisterMsg
Register a unique Windows message.
Syntax:
Int WindowRegisterMsg (String MessageName)
MessageName is a unique name to identify a message number which is guaranteed to be unique within the
Windows environment.
Returns:
If the message is successfully registered, the return value is a message identifier in the range 0xC000 through
0xFFFF. If the function fails, the return value is zero.

Comments:
This function defines a new window message that is guaranteed to be unique throughout the system. The message
value can be used when sending or posting messages. Registered Windows messages are used to provide a simple
means of communication between different programs. This is possible because the Windows system makes sure
that different applications registering the same message string get the same message number.
This function has the following alias:
Int WindowRegMsg (String MessageName)

WindowSendMsg
Send a Windows message to another application window.
Syntax:
Int WindowSendMsg (Window WinHandle, Int Message, Int wParam, Int StringParam)
WinHandle is the Windows handle of the window to send the message to. This should be a value obtained
from WindowFind.
Message is the actual message number to send to the window. This is typically a default Windows message
or a number returned by WindowRegMsg.
wParam is a message dependent parameter, the value of which depends on the message.
StringParam is a message dependent parameter, the value of which depends on the message.
Returns:
The return value specifies the result of the message processing; it depends on the message sent.
Comments:
Care must be exercised when sending Windows messages to other applications because this can cause unexpected
behavior.
Example:
This example sends a message to all children windows of the Error Message window.
proc ClickButton (string WindowName, string ButtonName)

int i, win, iChildren[];


string szText;

win = WindowFind (WindowName)

Numara Software, Inc. and BMC Software, Inc. Confidential.


652 - BMC FootPrints Asset Core - Chilli Reference

iChildren = WindowListChildren (win);

for (i=1; i<=ArrayGetSize (iChildren); i+=1)


szText = WindowGetText (iChildren[i]);
if (szText == ButtonName)
WindowSendMsg (iChildren[i], 0x0201, 0, 0)
WindowSendMsg (iChildren[i], 0x0202, 0, 0)
return
endif
endfor
endproc

proc main ()
ClickButton (“Error Message”, “Cancel”)
endproc

WindowSetText
Set the text of the specified window's title bar (if it has one) using the specified font.
Syntax:
Bool WindowSetText (Window WinHandle, String WinTitle)
Bool WindowSetText (Window WinHandle, String WinTitle, Font hFont)
WinHandle is the handle to the window.
WinTitle is the text to be set in the specified window’s title bar.
hFont is the handle to the font to be used for the window.
Returns:
TRUE if successful, FALSE otherwise.
Comments:
If the specified window is a control, the text of the control is changed. However, WindowSetText cannot change
the text of a control in another application.
Example:
This example changes the title of all top level windows.
proc main ()

int i, iWindow[];
string szText;

iWindow = WindowListTopLevel ()

for (i=1; i<=ArrayGetSize (iWindow); i+=1)


szText = WindowGetText (iWindow[i]);
if (szText != '')
print (szText + "\r\n");
else
WindowSetText (iWindow, "Warning")
endif
endfor
endproc

47.5 Examples
The following code sample illustrates the window functions.
proc ListChildren (int win)

int i, iChildren[];
string szText;

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 47 - Windowing Functions - 653

iChildren = WindowListChildren (win);

for (i=1; i<=ArrayGetSize (iChildren); i+=1)


szText = WindowGetText (iChildren[i]);
if (szText != '')
print (" " + szText + "/" + WindowGetClassName (iChildren[i]) + "\r\n")
endif
endfor
endproc

proc ListWindows ()

int i, iWindow[];
string szText;

iWindow = WindowListTopLevel ()

for (i=1; i<=ArrayGetSize (iWindow); i+=1)


szText = WindowGetText (iWindow[i]);
if (szText != '')
print (szText + "\r\n");
endif
ListChildren (iWindow[i])
endfor
endproc

proc ClickButton (string WindowName, string ButtonName)

int i, win, iChildren[];


string szText;

win = WindowFind (WindowName)

iChildren = WindowListChildren (win);

for (i=1; i<=ArrayGetSize (iChildren); i+=1)


szText = WindowGetText (iChildren[i]);
if (szText == ButtonName)
WindowSendMsg (iChildren[i], 0x0201, 0, 0)
WindowSendMsg (iChildren[i], 0x0202, 0, 0)
return
endif
endfor
endproc

proc main ()

window winCancel

ListWindows ()
ClickButton ("Print", "Cancel")
ClickButton ("Quick Open", "&Browse")

endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


654 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


WMI Functions

This chapter explains all Windows WMI functions of the Chilli Function Library. All functions of this module are
included in the wmi.chx file. These functions are not applicable to the UNIX environment.

48.1 Introduction
Windows Management Instrumentation (WMI) is a set of extensions to the Windows Driver Model that provides
an operating system interface through which instrumented components can provide information and notification.
Based on the CIM (Common Information Model) model, WMI includes real-world manageable components,
available from the DMTF standards with some specific extensions that represent the various Windows
components. WMI allows for the effective management of PC and server systems in an enterprise network
through well-instrumented computer software and hardware, which allow system components to be monitored
and controlled, both locally and remotely.

48.2 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli Windows WMI function group module has predefined
predefined structure data types.

48.2.1 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated.
Following you find a list of all predefined data types of type structure:

Data Type Description


WMIProperty Structure containing an array of information about a WMI property.

WMIProperty
The WMIProperty structure represents an array of information about a WMI property.
Elements:
Elements Element Type Description
Name String The name of the property.
Value String The value of the property.
Type String The type of the property, for example, INTEGER, STING, and so on.

Numara Software, Inc. and BMC Software, Inc. Confidential.


656 - BMC FootPrints Asset Core - Chilli Reference

48.3 Functions
Following you find a list of all existing functions for the WMI function group module:

Function OS Description
IsWMIInstalled Return if WMI is installed on the computer

WMIFilterToInventory

WMIGetPropertyValues Return the properties for a specified class and for all its instances

IsWMIInstalled
Verify if WMI is installed on the computer.
Syntax:
Bool IsWMIInstalled ()
Returns:
Returns TRUE if WMI is installed on the device, FALSE if not or if the function failed.

WMIFilterToInventory

Syntax:
Bool WMIFilterToInventory (String Hostname, String User, String Password, String NameSpace,
String FilterPath, String InventoryPath)

Returns:
TRUE on success, FALSE otherwise.

WMIGetPropertyValues
Return the properties for a specified class and for all its instances.
Syntax:
WMIProperty[] WMIGetPropertyValues (String NameSpace, String Class, String Property)
NameSpace is the path to the class, for which the values are requested.
Class specifies the name of the WMI class containing the property.
Property specifies the name of the property.
Returns:
The WMIProperty[] structure containing list of WMI property information if the operation was successful, an
empty structure if the operation failed.

48.4 Example
proc main ()
if (!IsWMIInstalled ())
Print ("WMI is not installed")
else
// WMI is installed

WMIProperty FWPropDisplayName[]
int iSize, i

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 48 - WMI Functions - 657

FWPropDisplayName = WMIGetPropertyValues ("\\\\.\\root\\SecurityCenter", "FirewallProduct",


"displayName")

// List all installed firewalls

iSize = ArrayGetSize (FWPropDisplayName)

for (i = 1; i <= iSize; i += 1)


Print ("Firewall name, instance" + i + ": " + FWPropDisplayName[i].Value + "\n")
endfor
endif
endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


658 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


WNet Functions

This chapter explains all Windows Wnet functions of the Chilli Function Library. All functions of this module are
included in the wnet.chx file. These functions are not applicable to the UNIX environment.

49.1 Introduction
The Windows networking (WNet) functions allow you to implement networking capabilities in your application
without making allowances for a particular network provider or physical network implementation. This is
because the WNet functions are network independent. Windows WNet functions are used for enumerating
devices on the network and handling network shares.

49.2 Predefined Constants


Following you find the complete list of all predefined constants of the Windows Wnet functions group of the
Chilli script language:

Name Type Description


WNETSRVTYPE Integer The type of the server found in a domain

WNET_SRVTYPE
The Wnet_SrvType constant represents all possible types that the servers found in a domain can be:

Name Type Description


WNET_SRVTYPE_WORKSTATION Integer The resource found in the domain is of type workstation
WNET_SRVTYPE_SERVER Integer The resource found in the domain is of type server
WNET_SRVTYPE_SQLSERVER Integer The resource found in the domain is of type SQL Server
WNET_SRVTYPE_DOMAIN_CTRL Integer The resource found in the domain is of type Domain Control Server
WNET_SRVTYPE_DOMAIN_BAKCTRL Integer The resource found in the domain is of type
WNET_SRVTYPE_TIME_SOURCE Integer The resource found in the domain is of type
WNET_SRVTYPE_AFP Integer The resource found in the domain is of type
WNET_SRVTYPE_NOVELL Integer The resource found in the domain is of type Novell Server
WNET_SRVTYPE_DOMAIN_MEMBER Integer The resource found in the domain is of type
WNET_SRVTYPE_LOCAL_LIST_ONLY Integer The resource found in the domain is of type
WNET_SRVTYPE_PRINTQ_SERVER Integer The resource found in the domain is of type Print Server
WNET_SRVTYPE_DIALIN_SERVER Integer The resource found in the domain is of type Dial-in Server
WNET_SRVTYPE_XENIX_SERVER Integer The resource found in the domain is of type Xenix Server
WNET_SRVTYPE_SERVER_MFPN Integer The resource found in the domain is of type
WNET_SRVTYPE_NT Integer The resource found in the domain is of type NT workstation
WNET_SRVTYPE_WFW Integer The resource found in the domain is of type

Numara Software, Inc. and BMC Software, Inc. Confidential.


660 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


WNET_SRVTYPE_SERVER_NT Integer The resource found in the domain is of type NT Server
WNET_SRVTYPE_POTENTIAL_BROWSER Integer The resource found in the domain is of type
WNET_SRVTYPE_BACKUP_BROWSER Integer The resource found in the domain is of type
WNET_SRVTYPE_MASTER_BROWSER Integer The resource found in the domain is of type
WNET_SRVTYPE_DOMAIN_MASTER Integer The resource found in the domain is of type Domain Master
WNET_SRVTYPE_DOMAIN_ENUM Integer The resource found in the domain is of type
WNET_SRVTYPE_WINDOWS Integer The resource found in the domain is of type
WNET_SRVTYPE_ALL Integer The resource found in the domain is of type
WNET_SRVTYPE_TERMINALSERVER Integer The resource found in the domain is of type
WNET_SRVTYPE_CLUSTER_NT Integer The resource found in the domain is of type
WNET_SRVTYPE_CLUSTER_VS_NT Integer The resource found in the domain is of type

49.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli Windows Wnet function group module has predefined handle
data types as well as predefined structures.

49.3.1 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated.
Following you find a list of all predefined data types of type structure:

Data Type Description


WNetServerInfo Structure containing information about computers found on a domain

WNetServerInfo
The WNetServerInfo structure represents an array of information concerning the computers found on a domain.
Elements:
Elements Element Type Description
ServerName String The name of the computer that is published on the network as the “computer name”.
PlatformId Integer The platform identification of the computer.
VersionMajor Integer The major version number of the operating system running on the server.
VersionMinor Integer The minor version number of the operating system running on the server.
Type Integer The type of the resource.

49.4 Functions
Following you find a list of all existing functions for the Wnet function group module:

Function OS Description
WNetEnumServers List all servers of the specified type that are visible in a domain

WNetEnumServers
List all servers of the specified type that are visible in a domain.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 49 - WNet Functions - 661

Syntax:
WNetServerInfo[] WNetEnumServers (String DomainName, Int TypeFlags)
DomainName is the name of the domain which is to be searched.
TypeFlags specifies the resource types to enumerate.
Returns:
A structure containing the list of all servers of the specified type found in the domain if the operation was
successful, or an empty structure if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


662 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


XML and XSLT File Functions

This chapter details all elements and functions which handle the XML/XSLT functions in the Chilli script
language. All functions of this module are included in the xml.chx file for Windows or xml.so file for UNIX
and Linux.

50.1 Introduction
The Extensible Markup Language (XML) is the universal format for structured documents and data on the Web.
XSLT (Extensible Style Language Transformation) is the language used in XSL style sheets to transform XML
documents into other XML documents. An XSL processor reads the XML document and follows the instructions
in the XSL style sheet, then it outputs a new XML document or XML-document fragment.
This set of functions uses XPath to address parts of the XML documents, designed to be used by XSLT. It provides
a set of methods for selecting nodes from an element based on an XPath. XPath uses a compact, non-XML syntax
to facilitate use of XPath within URIs and XML attribute values. It operates on the abstract, logical structure of an
XML document, rather than its surface syntax. This logical structure is known as the data model, which defines
the information in an XML document that is available to an XPath processor. XPath is designed to be embedded in
a host language such as XSLT.

50.2 Predefined Constants


Following you find the complete list of all predefined constants of the XML/XSLT functions group of the Chilli
script language:

Name Type Description


ERR_XML_OPEN Integer Failed to open XML file
ERR_XML_INVALID Integer XML file handle is invalid
ERR_XML_PROCESS Integer An error occurred while processing XSLT

50.3 Module Specific Data Types


Some modules of Chilli create their own additional module specific data types at start up time for easier
manipulation of data in Chilli scripts. The Chilli XML file function group has Predefined Handle Data Types.

50.3.1 Predefined Handle Data Types


Predefined Handle Data Types are opaque handles which contain the necessary information for accessing various
data. They have a name and are returned by functions and passed on to other functions or procedures without
changes.
Following you find a list of all Predefined Handle Data Types:

Numara Software, Inc. and BMC Software, Inc. Confidential.


664 - BMC FootPrints Asset Core - Chilli Reference

Data Type Description


XMLFileHandle Object type: reference to the handle of an XML file
XMLDocumentHandle

XMLFileHandle
The XMLFileHandle data type is a reference to the handle of an XML file.
The function XMLOpen returns this object type and most of the other functions expect it as their first argument.
The data type should be closed by the XMLClose function.

XMLDocumentHandle
The XMLDocumentHandle data type is a reference to the handle of an XML file.
The function XMLOpen returns this object type and most of the other functions expect it as their first argument.
The data type should be closed by the XMLClose function.

50.3.2 Predefined Structures


Predefined data types of type structure are structures produced and used by functions for easier representation of
data that are to be manipulated. For each predefined structure an array type of this structure also exists for usage
in the scripts.

ModuleFunctions
The HtmlTag structure represents an HTML tag in a file.
Elements:

Elements Element Type Description


IsHtmlTag integer 1 if standard HTML tag, 0 if user defined tag.
IsEndTag integer 1 if the tag has an end tag, 0 if not.
TagLabel string Name of the tag.
TagParamCount integer Number of parameters in the tag.
TagParams HtmlTagParam[] array List of parameters in the tag.

50.4 Functions
Following you find a list of all available XML file functions:

Function OS Description
XMLAddValue Add an XML element using the supplied XPath key

XMLApplyXSL Apply an XSL Transformation buffer to the current buffer and return the resulting buffer

XMLApplyXSLFile Apply an XSL Transformation file to the current buffer and return the resulting buffer

XMLClose Delete an open XMLFileHandle

XMLDeleteValue Delete an XML element using the supplied XPath key

XMLGetAttributeValue Get an XML element attribute value using the supplied XPath key

XMLGetContent Get the XML buffer of a XMLFileHandle

XMLGetValue Get the value of an XML element using the supplied XPath key

XMLOpen Load an XML file into a new XMLFileHandle

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 50 - XML and XSLT File Functions - 665

Function OS Description
XMLSave Save the XML file

XMLSaveAs Save the XML file under a new name

XMLSetAttributeValue Set an XML element attribute value using the supplied XPath key

XMLSetContent Set the XML buffer of a XMLFileHandle

XMLSetValue Set an XML value using the supplied XPath key

XMLAddValue
Add an XML element using the supplied XPath key.
Syntax:
Bool XMLAddValue (XMLFileHandle Handle, String XPathKey, String Value)
Handle is the handle to the XML file to which the value is to be added.
XPathKey is the location path key to the XML element.
Value is the new value of the XML element.
Returns:
TRUE if the operation was successful, FALSE if the function failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Example:
The following example line adds a new XML value to the supplied path.
XMLAddValue ("/DOCUMENT/CHAPTER1/TITLE4", "my title")

XMLApplyXSL
Apply an XSL Transformation buffer.
Syntax:
String XMLApplyXSL (XMLFileHandle Handle, String XSLTBuffer, String XSLTParms)
Handle is the handle to the XML file to be transformed.
XSLTBuffer is the transformation buffer to apply.
XSLTParms is the list of XSLT parameters.
Returns:
The transformed contents of the XML file if successful or an empty string if an error occurs. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.
Comments:
The XSLTParms list is a space-separated list of pairs like [param]=[value].

XMLApplyXSLFile
Apply an XSL Transformation file.
Syntax:
String XMLApplyXSLFile (XMLFileHandle Handle, String XSLTFileName, String XSLTParms)
Handle is the handle to the XML file to be transformed.
XSLTFileName is the name of the XSLT file that contains the XSL instructions.
XSLTParms is the list of XSLT parameters.
Returns:
The transformed contents of the XML file if successful or an empty string if an error occurs. If the operation fails,
ErrCode is set to ERR_FUNCFAILED.

Numara Software, Inc. and BMC Software, Inc. Confidential.


666 - BMC FootPrints Asset Core - Chilli Reference

Comments:
The XSL transformation file is applied to the file referenced by the resulting buffer supplied handle and returns
the resulting buffer. The XSLTParms list used for the transformation is a space-separated list of pairs like
[param]=[value].

XMLClose
Close and delete an open XMLFileHandle.
Syntax:
Bool XMLClose (XMLFileHandle Handle)
Handle is the handle to the XML file to be closed.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
After this call, which typically only fails if the supplied handle is not valid, the supplied XMLFileHandle is no
longer valid.

XMLDeleteValue
Delete an XML element using the supplied XPath key.
Syntax:
Bool XMLDeleteValue (XMLFileHandle Handle, String XPathKey)
Handle is the handle to the XML file.
XPathKey is the location path key to the XML element to be deleted.
Returns:
TRUE if the operation was successful, FALSE if the operation failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Example:
The following example line deletes a XML value from the supplied path.
XMLDeleteValue (ptr, "/DOCUMENT/CHAPTER1/TITLE4")

XMLGetAttributeValue
Get an XML element attribute value using the supplied XPath key.
Syntax:
String XMLGetAttributeValue (XMLFileHandle Handle, String XPathKey, String AttrName)
Handle is the handle to the XML file to be read.
XPathKey is the location path key to the XML element.
AttrName is the name of the attribute of which the value is to be read.
Returns:
The value of the named parameter of the referenced XML element if successful or an empty string if an error
occurs or the element or the parameter are not found. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Example:
The following example line gets the attribue value of the XML element 'parag'.
XMLGetAttributeValue (Handle, "/DOCUMENT/CHAPTER1/TITLE1", "PARAG")

XMLGetContent
Get the XML buffer of a XMLFileHandle.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 50 - XML and XSLT File Functions - 667

Syntax:
String XMLGetContent (XMLFileHandle Handle)
Handle is the handle to the XML file to be read.
Returns:
The contents of the object referenced by the supplied handle or an empty string if an error occurs. If the operation
fails, ErrCode is set to ERR_FUNCFAILED.

XMLGetValue
Get the value of an XML element using the supplied XPath key.
Syntax:
String XMLGetValue (XMLFileHandle Handle, String XPathKey)
Handle is the handle to the XML file to be read.
XPathKey is the location path key to the XML element.
Returns:
The value of the referenced XML element if successful or an empty string if an error occurs or the element is not
found. If the operation fails, ErrCode is set to ERR_FUNCFAILED.
Example:
The following example line gets the value of an XML element.
XMLGetValue (Handle, "count (/DOCUMENT/CHAPTER1/TITLE)")

XMLOpen
Load an XML file into a new XMLFileHandle.
Syntax:
XMLFileHandle XMLOpen (String Filename)
Filename is the name of the XML file to be read.
Returns:
An XML file handle of type XMLFileHandle if successful, or 0 if an error occurs or the function failed. If the
operation fails, ErrCode is set to ERR_FUNCFAILED.

XMLSave
Save the XML file.
Syntax:
Bool XMLSave (XMLFileHandle Handle)
Handle is the handle to the XML file to be saved.
Returns:
TRUE if the operation was successful, FALSE if the function failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
Saves the XML file referenced through the supplied handle keeping any changes applied to the handle.

XMLSaveAs
Save the XML file under a new name.
Syntax:
Bool XMLSaveAs (XMLFileHandle Handle, String OutputFilename)
Handle is the handle to the XML file to be saved under a new name.

Numara Software, Inc. and BMC Software, Inc. Confidential.


668 - BMC FootPrints Asset Core - Chilli Reference

OutputFileName is the new name of the file under which the original file is to be saved.
Returns:
TRUE if the operation was successful, FALSE otherwise if the function failed. If the operation fails, ErrCode is set
to ERR_FUNCFAILED.
Comments:
Saves the XML file referenced through the supplied handle into a file other than where the handle was loaded
from.

XMLSetAttributeValue
Set an XML element attribute value using the supplied XPath key.
Syntax:
Bool XMLSetAttributeValue (XMLFileHandle Handle, String XPathKey, String AttrName, String
Value)
Handle is the handle to the XML file to be read.
XPathKey is the location path key to the XML element.
AttrName is the name of the attribute of which the value is to be set.
Value is the new value of the XML element.
Returns:
TRUE if the operation was successful, FALSE if the function failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Example:
The following example line sets the attribute value of the XML element 'parag' to 'my new text'.
XMLSetAttributeValue ("/DOCUMENT/CHAPTER1/TITLE1", "PARAG", "my new text")

XMLSetContent
Set the XML buffer of a XMLFileHandle.
Syntax:
Bool XMLSetContent (XMLFileHandle Handle, String XMLStringBuffer)
Handle is the handle to the XML file to be read.
XMLStringBuffer is the name of the buffer to be set.
Returns:
TRUE if the operation was successful, FALSE if the function failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Comments:
XMLSetcontent sets the XML buffer of the object referenced through a XMLFileHandle. If the object was loaded
through a file, its contents is replaced by the supplied text. The original file is not affected unless the object is
'Saved’.

XMLSetValue
Set an XML value using the supplied XPath key.
Syntax:
Bool XMLSetValue (XMLFileHandle Handle, String XPathKey, String Value)
Handle is the handle to the XML file to be read.
XPathKey is the location path key to the XML element.
Value is the new value of the XML element.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 50 - XML and XSLT File Functions - 669

Returns:
TRUE if the operation was successful, FALSE if the function failed. If the operation fails, ErrCode is set to
ERR_FUNCFAILED.
Example:
The following example line sets the value of the XML element to 'my new title'.
XMLSetValue (ptr, "/DOCUMENT/CHAPTER1/TITLE[position ()=1]", "my new title")

50.5 Example
The sample chilli script below requires an XML file with a structure like the one listed below. Cut and paste the
XML into a file and name that xml file the same as this file - except with ".xml" suffix.
<A>
<B>
<C>
<D>
<E>first element</E>
</D>
</C>
<C>
<D>
<E>Second element</E>
</D>
</C>
<C>
<D>
<E>Third element</E>
</D>
</C>
</B>
</A>
Following now the Chilli script:
include "xml.chx"
/*********************************************************************
Main
Example showing how to loop through elements in an XML file
There are two different syntaxes shown.
Refer to associated XML sample file
*********************************************************************/

Proc Main ()

int i
string szTmp1, szTmp2, szCount
XMLFileHandle hXML_CFG_FILE

// Set current working directory. If we don't then the current working dir is that
// of chilli.exe

DirSetCurrent (PathGetDrive(ScriptFile) + ':' + PathGetDir(ScriptFile))

// Open the XML file

hXML_CFG_FILE = XMLOpen (DirGetCurrent() + '\' + "x-test.xml")

Numara Software, Inc. and BMC Software, Inc. Confidential.


670 - BMC FootPrints Asset Core - Chilli Reference

// Get a count of entries /A/B/C


// Note that the returned value is the count as a string

szCount = XMLGetValue (hXML_CFG_FILE, "count (/A/B/C)")

// Loop through the /A/B/C section of the XML file


// We convert the szCount string to integer for use in the loop

For (i=1; i <= MakeInt (szCount); i+=1)

// The first syntax uses straight forward brackets enclosing an integer


// encoded as a string:

szTmp1 = XMLGetValue (hXML_CFG_FILE, "/A/B/C[" + MakeStr(i) + "]/D/E")

// The second syntax also uses brackets inside which the 'position()'
// function is called and given an integer encoded as string as its argument

szTmp2 = XMLGetValue (hXML_CFG_FILE, "/A/B/C[position ()=" + MakeStr(i) + "]/D/E")

// The Print function - in absense of any other arguments - output to


// "standard out", which in most cases is a DOS box or terminal window

Print ("Syntax 1 - Element " + MakeStr(i) + ": " + szTmp1 + "\r\n")


Print ("Syntax 2 - Element " + MakeStr(i) + ": " + szTmp2 + "\r\n")
Print ("====================\r\n")
Endfor

XMLClose (hXML_CFG_FILE)

Endproc

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 50 - XML and XSLT File Functions - 671

Numara Software, Inc. and BMC Software, Inc. Confidential.


Section III

Appendix
The appendix contains a number of appendices providing references to Chilli which you might
find useful:
• Reserved Words
• Chilli Error Codes
• Language Operators
• Predefined Variables and Constants
• Chilli Function Group Modules

Numara Software, Inc. and BMC Software, Inc. Confidential.


Reserved Words

There are a number of reserved words in Chilli. These are words that you cannot (or should not) use as identifiers
(such as variable names) in your Chilli script programs. The following table only lists the keywords in Chilli. In
addition to those all function names, module specific data type names, predefined variable and constants names,
and so on, should not be used. All these words have special meaning to Chilli - they are part of the language
syntax itself. This means that they should not be used in any other way:
Bool Boolean
Break Call
Char Character
Const Constant
Continue Double
Elif Else
Elseif Endfor
Endif EndProc
Endstruct Endwhile
Exit Extern
False Float
For If
Include Int
Integer Proc
Return String
Str Struct
True Wend
While

Numara Software, Inc. and BMC Software, Inc. Confidential.


676 - BMC FootPrints Asset Core - Chilli Reference

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chilli Error Codes

The error codes below are run-time errors that causes the handler specified in ErrorHandler to be invoked. These
errors can be returned directly as the error code value and the core generates the correct message for them.
Following you find the list of general errors:

Name Description
ERR_SUCCESS No error

ERR_BADHANDLE Invalid handle for the required operation


ERR_DIRNOTFOUND Directory does not exist
ERR_FILECREATEFAIL Failed to create file
ERR_FILENOTFOUND File does not exist
ERR_FILENOTVALID File is not valid for operation (not text, archive, INI)
ERR_FILEREADFAIL Failed to open file for reading
ERR_FILEWRITEFAIL Failed to open file for writing
ERR_FUNCFAILED Function failed (generic error)
ERR_FUNCNOTSUPP Function is not supported
ERR_INVALIDPARAM Invalid parameter value
ERR_KEYNOTFOUND Specified registry key not found
ERR_SOCKETERROR There was a socket level failure
ERR_STRINGTOOBIG String value is too long for operation
ERR_TCPCONNECTED Already connected to a host
ERR_TCPCONNFAIL TCP connect to server failed
ERR_TCPCONNTIMEOUT TCP connect to server timed-out
ERR_TCPCREATEFAIL Failed to create TCP socket
ERR_TCPINVALIDHOST Invalid host address supplied
ERR_TCPNOTCONNECTED Not connected to a host
ERR_TCPRESET The TCP socket has been reset
ERR_TCPTIMEOUT TCP operation timed out

The following table lists all function module specific runtime errors:

Name Description
ERR_ACCESSDENIED Access denied to database or table
ERR_ACTFAILED Failed to execute agent action
ERR_ACTINPARAM Unable to resolve action input pamareters
ERR_ACTOUTPARAM Unable to set action output pamareters
ERR_BADDBNAME Database name invalid or not found
ERR_BADHOSTNAME Host name or IP address not found

Numara Software, Inc. and BMC Software, Inc. Confidential.


678 - BMC FootPrints Asset Core - Chilli Reference

Name Description
ERR_BADLIBRARY Missing or incorrect database library DLL
ERR_CONNECTION ODBCConnectionHandle error
ERR_CONNFAIL Failed to connect to server
ERR_CONNLOST Connection to server lost or timed-out
ERR_FTPBADSEQUENCE Server complained of bad sequence of commands
ERR_FTPNOLOCALFILE Local file doesn't exist or can't be read/written
ERR_FTPNOLOCALSPACE Local disk does not have enough space
ERR_FTPNOMEMORY Not enough memory for file transfer buffer
ERR_FTPNOREMOTEFILE Remote file doesn't exist or can't be read/written
ERR_FTPNOREMOTESPACE Server does not have enough space
ERR_FTPSYNTAXERROR Server does not recognise command
ERR_NOMEMORY Not enough memory for the operation
ERR_NOPERMISSION Account required or no user permissions
ERR_NOTLOGGEDIN User not logged on
ERR_ODBC Error ODBC
ERR_SDBMBADHANDLE Invalid SDBM handle
ERR_SDBMOUTOFHANDLES Out of SDBM file handles (too many opened at once)
ERR_SMBBADDIALECT Our SMB dialect is not supported by server
ERR_SMBCLOSEFAILED SMB file close operation failed
ERR_SMBLOGINFAILED Logon to SMB server failed
ERR_SMBNETBIOSFAIL There was a NetBIOS protocol failure
ERR_SMBNOLOCALFILE Local file doesn't exist or can't be read/written
ERR_SMBNOLOCALSPACE Local disk does not have enough space
ERR_SMBNOMEMORY Not enough memory for file transfer buffer
ERR_SMBOPENFAILED Failed to open file on SMB server
ERR_SMBREADFAILED SMB file read operation failed
ERR_SMBSHCONNFAILED Share connect failed
ERR_SMBWRITEFAILED SMB file write operation failed
ERR_SMTPBADMAILBOX Remote mailbox doesn't exist or can't be read/written
ERR_SMTPBADSEQUENCE Server complained of bad sequence of commands
ERR_SMTPNOSPACE Server does not have enough space
ERR_SMTPSYNTAXERROR Server does not recognise command
ERR_SNMPBADOID SNMP invalid Object ID string
ERR_SNMPBADREQ SNMP unable to create request
ERR_SNMPBADSOCKET SNMP socket invalid or unable to bind to
ERR_SNMPBADVALUE SNMP varbind contains an incorrect value
ERR_SNMPGENERR SNMP general error
ERR_SNMPNOSUCHNAME SNMP specified OID is not supported
ERR_SNMPREADONLY SNMP read-only MIB variable
ERR_SNMPTIMEOUT SNMP request did not get a response
ERR_SNMPTOOBIG SNMP response message too big to send
ERR_SPECNOTCONNECTED Not connected to a server
ERR_STATEMENT ODBCStatementHandle error
ERR_XML_INVALID XML file handle is invalid
ERR_XML_OPEN Failed to open XML file
ERR_XML_PROCESS An error occurred while processing XSLT

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 52 - Chilli Error Codes - 679

Name Description
GENSQL_ERR_BADCOLUMNORDER Columns are not being accessed in increasing column order
GENSQL_ERR_BADPARAM Parameter error in a call
GENSQL_ERR_BADSQL Error in an SQL statement passed to the server
GENSQL_ERR_INTERNAL Internal error in the library

All following error codes causes immediate termination of the script.

Name Description
ERR_ASSIGNCONSTANT Cannot assign a value to a constant
ERR_ASSIGNMISMATCH Assignment variable type not same as expression
ERR_ASSIGNNOEQUAL Assignment variable not followed by = sign
ERR_BADSTATEMENT Unrecognized statement or variable name
ERR_BREAKALONE BREAK statement does not appear on its own
ERR_BREAKUNMATCHED BREAK without matching WHILE or FOR
ERR_CONTINUEALONE CONTINUE statement does not appear on its own
ERR_CONTUNMATCHED CONTINUE without matching WHILE or FOR
ERR_ELIFNOEND ELIF without ending ENDIF
ERR_ELIFUNMATCHED ELIF without matching IF or ELIF
ERR_ELSEALONE ELSE statement does not appear on its own
ERR_ELSENOEND ELSE without ending ENDIF
ERR_ELSEUNMATCHED ELSE without matching IF or ELIF
ERR_ENDIFALONE ENDIF statement does not appear on its own
ERR_ENDIFUNMATCHED ENDIF without matching IF, ELSE or ELIF
ERR_ENDPROCALONE ENDPROC does not appear on its own on the line
ERR_ENDPROCNOPROC ENDPROC statement without preceding PROC definition
ERR_EXPRBADFORMAT Expression is not correctly formed
ERR_EXPRBADFUNC Function name unknown
ERR_EXPRBADTOKEN Unrecognized token in expression
ERR_EXPREMPTY Expression is empty
ERR_EXPRFUNCBADPAR Function call has no closing parenthesis
ERR_EXPRFUNCNOPAR Function name not followed by parenthesis
ERR_EXPRFUNCPARCOUNT Insufficient number of parameters on stack for function call
ERR_EXPROPBADPARAMS Operator parameters incorrect or missing
ERR_EXPRPARMMATCH Parameter type mismatch
ERR_EXPRPARMTYPE One or more parameters are of the wrong type
ERR_EXPRSIGNATURE No function definition match these parameters
ERR_FORBADSYNTAX Syntax error in FOR statement
ERR_FORNOENDFOR FOR without ending ENDFOR
ERR_IFNOEND IF without matching ELSE, ELIF or ENDIF
ERR_INCLUDEBADFILE Parameter to include statement not a valid file
ERR_INCLUDENOTTEXT Parameter to include statement not a text string
ERR_INTERNAL An unexpected internal error has occurred
ERR_MAXMEMORYEXCEED Memory usage exceeded maximum defined in INI file
ERR_NOERRHANDLER User defined error handler procedure not found
ERR_NOEXTERNVAR External variable has not been defined
ERR_NOMEMORY Failed to allocate memory for operation
ERR_PROCBADVARTYPE Unknown type specified for procedure parameter declaration

Numara Software, Inc. and BMC Software, Inc. Confidential.


680 - BMC FootPrints Asset Core - Chilli Reference

Name Description
ERR_PROCCALLMAIN The main procedure cannot be called within the script
ERR_PROCDUPLICATE Procedure name is reserved or already defined
ERR_PROCNESTEDDEF Found nested procedure definition
ERR_PROCNOEND No ENDPROC statement after PROC definition
ERR_PROCNOMAIN ‘Main’ procedure not defined anywhere
ERR_PROCNOOPENPAR PROC definition does not have a ‘(‘ after name
ERR_PROCNOTFOUND Procedure definition not found
ERR_PROCPARMCOUNT Number of parameters does not match procedure definition
ERR_RETURNALONE RETURN statement does not appear on its own
ERR_SCRBADQUOTE Unexpected quote found on the line
ERR_SCRNOMORELINES No more lines in script file
ERR_SCRNOQUOTE A quoted string ended without a terminating quote
ERR_SCRNOTOKEN No tokens found on the line
ERR_VARBADNAME Bad name for variable or constant name
ERR_VARBADTYPE Unrecognized type name
ERR_VAREXISTS Variable or constant is already declared
ERR_VARISFUNC Variable or constant is a function name
ERR_VARISPROC Variable/constant is the name of a procedure in script
ERR_VARISSTATEMENT Variable or constant is a statement name
ERR_VARNOCOMMA No comma after variable or constant name
ERR_VARTOOLONG Variable or constant name is too long
ERR_WENDALONE ENDWHILE/WEND statement does not appear on its own
ERR_WENDUNMATCHED ENDWHILE/WEND without matching WHILE
ERR_WHILENOWEND WHILE without ending ENDWHILE or WEND

Numara Software, Inc. and BMC Software, Inc. Confidential.


Language Operators

53.1 Expression Operators:


The following expression operators are supported in Chilli. You will find detailed explanations for each of them in
Section I -Expression Operators on page 39 of this manual.

Symbol P Data Types Description


() 12 String, Int, Float, Double Used to change the evaluation precedence in a compound statement.
- 11 Int, Float, Double Unary operator - used to reverse the sign of the argument.
! 11 Boolean, Int, Float, Double Unary operator - used to perform a logical negation, that is, a “not”.
* 10 Int, Float, Double Multiply the LHS by the RHS.
/ 10 Int, Float, Double Divide the LHS by the RHS.
% 10 Int, Float, Double Calculate the remainder when the LHS is divided by the RHS.
+ 9 String, Int, Float, Double Add the LHS to the RHS. If used with two string values, this operator concatenates the
two strings together.
- 9 Int, Float, Double Subtract the RHS from the LHS.
<< 8 Int, Float, Double Shift all bits in the LHS to the left by the number of places specified by the RHS.
>> 8 Int, Float, Double Shift all bits in the LHS to the right by the number of places specified by the RHS.
< 7 String, Int, Float, Double The result is non-zero if the LHS is smaller than the RHS. When used with strings, the
value is true if the first mismatched character in the LHS is alphabetically lower than
that in the RHS.
> 7 String, Int, Float, Double The result is non-zero if the LHS is larger than the RHS.
<= 7 String, Int, Float, Double The result is non-zero if the LHS is smaller than or equal to the RHS.
>= 7 String, Int, Float, Double The result is non-zero if the LHS is larger than or equal to the RHS.
== 6 String, Int, Float, Double The result is non-zero if the LHS is equal to the RHS.
!= 6 String, Int, Float, Double The result is non-zero if the LHS is not equal to the RHS.
& 5 Int, Float, Double A bit is set in the result if a corresponding bit is set in the LHS AND in the RHS.
| 4 Int, Float, Double A bit is set in the result if a corresponding bit is set in the LHS AND in the RHS, or in the
LHS OR the RHS.
^ 3 Int, Float, Double A bit is set in the result if a corresponding bit is set in the LHS OR in the RHS.
&& 2 Int, Float, Double The result is non-zero if both the LHS and the RHS are non-zero.
|| 1 Int, Float, Double The result is non-zero if either the LHS or the RHS is non-zero.

53.2 Assignment Operators:


The following assignment operators are supported in Chilli. You will find detailed explanations for each of them in
Section I - Assignment Operators on page 45 of this manual.

Numara Software, Inc. and BMC Software, Inc. Confidential.


682 - BMC FootPrints Asset Core - Chilli Reference

Operator Data Type Description Example Equivalent


+= String, Int, Add the LHS to the RHS and assign result to LHS. If used with two a += b a=a+b
Float, Double string values, this operator concatenates the two strings together.
+= Array Increase the number of elements of an array. array += #Elements
-= Int, Float, Subtract the RHS from the LHS and assign result to LHS. a -= b a=a-b
Double
-= Array Reduce the number of elements of an array. array -= #Elements
*= Int, Float, Multiply the LHS by the RHS and assign result to LHS. a *= b a=a*b
Double
/= Int, Float, Divide the LHS by the RHS and assign result to LHS. a /= b a=a/b
Double
%= Int Calculate the remainder when the LHS is divided by the RHS and a %= b a=a%b
assign result to LHS.
<<= Int, Float, Shift all bits in the LHS to the left by the number of places a <<= b a = a << b
Double specified by the RHS.
<<= Array Append a specific element to the end of an array. Array <<=
array_element
>>= Int, Float, Shift all bits in the LHS to the right by the number of places a >>= b a = a >> b
Double specified by the RHS.
&= Int, Float, A bit is set in the result if a corresponding bit is set in the LHS a &= b a=a&b
Double AND in the RHS. The result is assigned to the LHS.
|= Int, Float, A bit is set in the result if a corresponding bit is set in the LHS AND a |= b a=a|b
Double in the RHS, or in the LHS OR the RHS. The result is assigned to
the LHS.
^= Int, Float, A bit is set in the result if a corresponding bit is set in the LHS OR a ^= b a=a^b
Double in the RHS. The result is assigned to the LHS.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Predefined Variables and Constants

This appendix lists all predefined variables and constants which are used in the Chilli language.

54.1 Predefined Variables


Upon starting the Chilli interpreter declares and defines a number of variables with global scope which are used
by various functions to determine their default operation. These variables can be read and written to like any
other variable, although special care must be taken when changing their values because this can change the
operation of functions which depend on them. The table below lists the predefined variables along with their type
and meaning.

Name Type Description


ErrCode Integer The error code from the last function executed. This is set by each function. The default value
is ERR_SUCCESS.
ErrHandler String The name of the default error handler in case of run-time errors.
ErrLine Integer The line number in the script where the latest run-time error has occurred.
IntBase Integer The integer conversion base used by the Integer to String conversion function MakeStr.
LogFile String The name of the default log file. This is set to the name of the script file except it has a .log
extension. If required, it can be changed.
ScriptFile String The name of the script file currently being executed. This value should not be changed.
StrCase Integer Case sensitivity flag for string comparisons.

ErrCode
The error code from the last function executed. This variable is cleared before each new function execution and is
set if the function has an error. If an error occurs and the ErrCode variable is set, it must be copied to a new
variable before calling a function, otherwise it is lost. The default value is ERR_SUCCESS. For a complete list of
possible error codes see Chilli Error Codes on page 677.

ErrHandler
The name of the default error handler in case of run-time errors. This can be one of the following 2 predefined
constants:

Value Type Meaning


DEFAULT_HANDLER String The default handler prints the error code with a message to the file named in the LogFile and
terminates the program.
INLINE_HANDLER String The error is handled by the script itself. In this case the script is responsible for checking the result of
each function and taking appropriate action.

The default value is DEFAULT_HANDLER.

Numara Software, Inc. and BMC Software, Inc. Confidential.


684 - BMC FootPrints Asset Core - Chilli Reference

IntBase
The integer conversion base used by the Integer to String conversion function. This can be set to any of the
following 3 predefined constants:

Value Type Meaning


INTBASE_DEC Integer The integer value is converted into a string using base 10.
INTBASE_HEXU Integer The integer value is converted into a hexadecimal string using uppercase letters for A-C.
INTBASE_HEXL Integer The integer value is converted into a hexadecimal string using lowercase letters for a-c.

The default value is INTBASE_DEC.

LogFile
This variable defines the name of the default log file. This is set to the name of the script file except it has a .log
extension. If required, it can be changed.
If a preload script is specified through the Preload entry in the [ChilliConfig] section of the chilli.ini
file, the LogFile variable is set according to the name of the preload file as found in the chilli.ini file. When
the preload file has been executed and the main script starts, the variable is set to a new value based on the name
of the main script file. This means that if the variable is set in the preload script, the changes is lost as soon as the
main script starts.

ScriptFile
This variable defines the name of the script file currently being executed. This value should not be changed.
If a preload script is specified through the Preload entry in the [ChilliConfig] section of the chilli.ini
file, the ScriptFile variable is set according to the name of the preload file as found in the chilli.ini file. When
the preload file has been executed and the main script starts, the variable is set to a new value based on the name
of the main script file. This means that if the variable is set in the preload script, the changes is lost as soon as the
main script starts.

StrCase
Determines case sensitivity in string comparisons. If TRUE then all string comparison functions, including
operators such as <=, == and != compare their string parameters using case sensitive compare. If FALSE
(default), the case is ignored.

Value Type Meaning


TRUE Boolean All comparison functions are using case sensitive compare for string parameters.
FALSE Boolean All comparison functions are using non-case sensitive compare for string parameters.

54.2 Predefined Constants


Upon starting the Chilli compiler declares and defines a number of constants with global scope which are used by
various functions to determine their default operation. This paragraph lists all predefined constants.

Name Type Description


CONTAINER_ENTRY_BOOLEAN Integer The entry type of the container is boolean
CONTAINER_ENTRY_CONTAINER Integer The entry type of the container is container
CONTAINER_ENTRY_DOUBLE Integer The entry type of the container is double
CONTAINER_ENTRY_INTEGER Integer The entry type of the container is integer
CONTAINER_ENTRY_NONE Integer The entry type of the container can not be defined
CONTAINER_ENTRY_STRING Integer The entry type of the container is string
DATATYPE Integer Define the data type of a column in a database table

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 54 - Predefined Variables and Constants - 685

Name Type Description


DATATYPE_BIGINT Integer A large integer. The signed range is -9223372036854775808 to
9223372036854775807. The unsigned range is 0 to 18446744073709551615.
As all arithmetic is done using signed BIGINT or DOUBLE values, so you
shouldn't use unsigned big integers larger than 9223372036854775807 (63
bits) except with bit functions! If you do that, some of the last digits in the result
might be wrong because of rounding errors when converting the BIGINT to a
DOUBLE.
You can always store an exact integer value in a BIGINT column by storing it as
a string, because in this case there is no intermediate double representation.
`-', `+', and `*' use BIGINT arithmetic when both arguments are INTEGER
values! This means that if you multiply two big integers (or results from
functions that return integers) you might get unexpected results when the result
is larger than 9223372036854775807.
DATATYPE_BINARY Integer A fixed length text string (case-insensitive). Any input that is shorter than the
length is padded with spaces at the end. Any trailing spaces are removed when
outputting values. The BINARY type is equivalent to CHAR with the BINARY
modifier.
DATATYPE_BIT Integer This datatype is a synonym for the CHAR datatype.
DATATYPE_CHAR Integer A fixed-length string that is always right-padded with spaces to the specified
length when stored. The range of M is 1 to 255 characters. Trailing spaces are
removed when the value is retrieved. CHAR values are sorted and compared in
case-insensitive fashion according to the default character set unless the
BINARY keyword is given.
DATATYPE_DATE Integer A date. The supported range is '1000-01-01' to '9999-12-31'. It displays DATE
values in 'YYYY-MM-DD' format, but allows you to assign values to DATE
columns using either strings or numbers.
DATATYPE_DATETIME Integer A date and time combination. The supported range is '1000-01-01 00:00:00' to
'9999-12-31 23:59:59'. It displays DATETIME values in 'YYYY-MM-DD
HH:MM:SS' format, but allows you to assign values to DATETIME columns
using either strings or numbers.
DATATYPE_DECIMAL Integer An unpacked floating-point number. Cannot be unsigned. Behaves like a CHAR
column: ``unpacked'' means the number is stored as a string, using one
character for each digit of the value. The decimal point and, for negative
numbers, the `-' sign, are not counted in M (but space for these are reserved).
If D is 0, values has no decimal point or fractional part. The maximum range of
DECIMAL values is the same as for DOUBLE, but the actual range for a given
DECIMAL column can be constrained by the choice of M and D. If D is left out
it's set to 0. If M is left out it's set to 10. Note that in MySQL Version 3.22 the M
argument had to includes the space needed for the sign and the decimal point.
DATATYPE_DOUBLE Integer A normal-size (double-precision) floating-point number. Cannot be unsigned.
Allowable values are -1.7976931348623157E+308 to -
2.2250738585072014E-308, 0, and 2.2250738585072014E-308 to
1.7976931348623157E+308. The M is the display width and D is the number of
decimals. DOUBLE without an argument or FLOAT(X) where 25 <= X <= 53
stands for a double-precision floating-point number.
DATATYPE_FLOAT Integer A small (single-precision) floating-point number. Cannot be unsigned.
Allowable values are -3.402823466E+38 to -1.175494351E-38, 0, and
1.175494351E-38 to 3.402823466E+38. The M is the display width and D is
the number of decimals. FLOAT without an argument or with an argument of
<= 24 stands for a single-precision floating-point number.
DATATYPE_INTEGER Integer An integer. The signed range is -2147483648 to 2147483647. The unsigned
range is 0 to 4294967295.
DATATYPE_LONGVARBINARY Integer A binary field with a maximum length of 64 KB of text.
DATATYPE_LONGVARCHAR Integer A text field with a maximum length of 64 KB of text.
DATATYPE_NULL Integer The fields in this column can contain NULL values.
DATATYPE_NUMERIC Integer This datatype is a synonym for the DECIMAL type.
DATATYPE_REAL Integer This datatype is a synonym for the DOUBLE type.

Numara Software, Inc. and BMC Software, Inc. Confidential.


686 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


DATATYPE_SMALLINT Integer A small integer. The signed range is -32768 to 32767. The unsigned range is 0
to 65535.
DATATYPE_TIME Integer A time. The range is '-838:59:59' to '838:59:59'. It displays TIME values in
'HH:MM:SS' format, but allows you to assign values to TIME columns using
either strings or numbers.
DATATYPE_TIMESTAMP Integer A timestamp. The range is '1970-01-01 00:00:00' to sometime in the year 2037.
It displays TIMESTAMP values in YYYYMMDDHHMMSS, YYMMDDHHMMSS,
YYYYMMDD, or YYMMDD format, depending on whether M is 14 (or missing),
12, 8, or 6, but allows you to assign values to TIMESTAMP columns using either
strings or numbers.
DATATYPE_TINYINT Integer A very small integer. The signed range is -128 to 127. The unsigned range is 0
to 255.
DATATYPE_UNKNOWN Integer The data type of the column is not known or not supported.
DATATYPE_VARBINARY Integer A variable-length text string (cas-insensitive) with a predefined maximum
length. The maximum length mus be betweem 1 and 255 characters. Any
trailing spaces are removed before storing data of ths type. The VARBINARY
type is equivalent to VARCHAR with the BINARY modifier.
DATATYPE_VARCHAR Integer A variable-length string. Trailing spaces are removed when the value is stored
(this differs from the ANSI SQL specification). The range of M is 1 to 255
characters. VARCHAR values are sorted and compared in case-insensitive
fashion unless the BINARY keyword is given.
DBTYPE Integer Define the type of the database server to which a connection is to be opened
DBTYPE_MYSQL Integer The database server is of type MySQL.
DBTYPE_POSTGRES Integer The database server is of type Postgres.
EVENT_AUDITFAILURE Integer Failure Audit event
EVENT_AUDITSUCCESS Integer Success Audit event
EVENT_ERROR Integer Error event
EVENT_INFORMATION Integer Information event
EVENT_WARNING Integer Warning event
EVENTFILE_APPLICATION Integer An Application event file.
EVENTFILE_SECURITY Integer A Security event file.
EVENTFILE_SYSTEM Integer A System event file.
FMT Integer Define the scaling factor for the object value in which it is displayed.
FMT_1000 Integer The database server is of type Postgres.
FMT_NOSCALE Integer The database server is of type MySQL.
FTP_DEFAULT_PORT Integer The default port of the FTP server
GENSQL_DBTYPE_INVALID Integer The type of the database server is invalid.
GENSQL_DBTYPE_ODBC Integer The database server is of type ODBC.
GENSQL_DBTYPE_ORACLE Integer The database server is of type Oracle.
GIF_BRUSHED Integer Used in place of a color when invoking a line-drawing function such as
GifDrawLine or GifDrawRectangle. When GIF_BRUSHED is used as the color,
the brush image set with GifSetBrush is drawn in place of each pixel of the line
(the brush is usually larger than one pixel, creating the effect of a wide
paintbrush). See also GIF_STYLEDBRUSHED for a way to draw broken lines
with a series of distinct copies of an image.
GIF_FONTHUGE Integer Font of the character cell fixed width font familiy with a height of 15 pixels and a
width of 9 pixels. The characters are sans serif, of bold and upright stroke and
have a normal setwidth. The character set is ISO Latin2.
GIF_FONTLARGE Integer Font of the character cell fixed width font familiy with a height of 16 pixels and a
width of 8 pixels. The characters are of medium stroke and upright and have a
normal setwidth. The character set is ISO Latin2.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 54 - Predefined Variables and Constants - 687

Name Type Description


GIF_FONTMEDIUM Integer Font of the character cell fixed width font familiy with a height of 13 pixels and a
width of 7 pixels. The characters are sans serif, of bold and upright stroke and
have a normal setwidth. The character set is ISO Latin2.
GIF_FONTSMALL Integer Font of the character cell fixed width font familiy with a height of 12 pixels and a
width of 6 pixels. The characters are sans serif, of normal and upright stroke
and have a semicondensed setwidth. The character set is ISO Latin2.
GIF_FONTTINY Integer Font of the character cell fixed width font familiy with a height of 8 pixels and a
width of 5 pixels. The characters are of medium and upright stroke and have a
normal setwidth. The character set is ISO Latin2.
GIF_MAXCOLOURS Integer The constant 256. This is the maximum number of colors in a GIF file
according to the GIF standard, and is also the maximum number of colors in a
gd image.
GIF_STYLED Integer Used in place of a color when invoking a line-drawing function such
GifDrawLine or GifDrawRectangle. When GIF_STYLED is used as the color, the
colors of the pixels are drawn successively from the style that has been set
with GifSetStyle. If the color of a pixel is equal to GIF_TRANSPARENT, that pixel
is not altered.
GIF_STYLEDBRUSHED Integer Used in place of a color when invoking a line-drawing function such as
GifDrawLine or GifDrawRectangle. When GIF_STYLEDBRUSHED is used as the
color, the brush image set with GifSetBrush is drawn at each pixel of the line,
providing that the style set with GifSetStyle contains a nonzero value (OR
GIF_TRANSPARENT, which does not equal zero but is supported for
consistency) for the current pixel. Note that this differs from the behavior of
GIF_STYLED, in which the values in the style are used as actual pixel colors,
except for GIF_TRANSPARENT.
GIF_TILED Integer Used in place of a normal color in GifDrawFilledRectangle,
GifDrawFilledPolygon, GifFill, and GifFillToBorder. GIF_TILED selects a pixel
from the tile image set with GifSetTile in such a way as to ensure that the filled
area is tiled with copies of the tile image.
GIF_TRANSPARENT Integer Used in place of a normal color in a style to be set with GifSetStyle.
GIF_TRANSPARENT is not the transparent color index of the image; for that
functionality see GifSetTransparent function.
GROUP_COMMON Integer The new group is common which means it is available to all users of the
system. If the current user does not have Administrator priviledges, the function
fails.
GROUP_USER Integer The new group is only created for the currently logged-on user.
INTBASE_DEC Integer The integer value is converted into a string using base 10
INTBASE_HEXL Integer The integer value is converted into a hexadecimal string using lowercase letters
for a-c.
INTBASE_HEXU Integer The integer value is converted into a hexadecimal string using uppercase
letters for A-C.
LDAP_DEFAULT_PORT Integer The default port for the LDAP connection, 389
LDAP_MOD_ADD Integer The modification operation in the add function is to add an entry to the tree
LDAP_MOD_DELETE Integer The modification operation in the modify function is to delete an entry from the
tree
LDAP_MOD_REPLACE Integer The modification operation in the modify function is to replace an entry in the
tree
LDAP_SCOPE_BASE Integer The scope of the search operation is limited to the base
LDAP_SCOPE_ONELEVEL Integer The scope of the search operation is limited to the first level below the base
level, excluding the base entry
LDAP_SCOPE_SUBTREE Integer The scope of the search operation is extended to the complete subtree, that is,
the base entry plus all levels below
MD_BTN1 Integer Button 1 for a message dialog box.
MD_BTN2 Integer Button 2 for a message dialog box.
MD_BTN3 Integer Button 3 for a message dialog box.

Numara Software, Inc. and BMC Software, Inc. Confidential.


688 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


REG_BINARY Integer Binary data in any form.
REG_DWORD Integer A 32-bit number.
REG_EXPAND_SZ Integer A null-terminated string that contains unexpanded references to environment
variables (for example, “%PATH%”). It is a Unicode or ANSI string depending
on whether you use the Unicode or ANSI functions. To expand the environment
variable references, use the StrExpandEnvString function.
REG_MULTI_SZ Integer An array of null-terminated strings, terminated by two null characters.
REG_NONE Integer No defined value type.
REG_RESOURCE_LIST Integer A device-driver resource list.
REG_SZ Integer A null-terminated string. It is a Unicode or ANSI string, depending on whether you
use the Unicode or ANSI functions.
RPC_LSA_ACCOUNT Integer Query class to be used with function RpcLsaQueryInfo in order to gather
account information through the Local Security Authority (LSA) pipe.
RPC_LSA_DOMAIN Integer Query class to be used with function RpcLsaQueryInfo in order to gather
domain information through the Local Security Authority (LSA) pipe.
RPC_PIPE_ATSVC Integer Constant to be supplied to the RpcBindInterface function for opening the
ATSVC pipe.
RPC_PIPE_BROWSER Integer Constant to be supplied to the RpcBindInterface function for opening the
BROWSER pipe.
RPC_PIPE_EVENTLOG Integer Constant to be supplied to the RpcBindInterface function for opening the
EVENTLOG pipe.
RPC_PIPE_LSARPC Integer Constant to be supplied to the RpcBindInterface function for opening the LSA
pipe.
RPC_PIPE_NETLOGON Integer Constant to be supplied to the RpcBindInterface function for opening the
NETLOGON pipe.
RPC_PIPE_SAMR Integer Constant to be supplied to the RpcBindInterface function for opening the SAMR
pipe.
RPC_PIPE_SPOOLSS Integer Constant to be supplied to the RpcBindInterface function for opening the
SPOOLSS pipe.
RPC_PIPE_SRVSVC Integer Constant to be supplied to the RpcBindInterface function for opening the
SRVSVC pipe.
RPC_PIPE_SVCCTL Integer Constant to be supplied to the RpcBindInterface function for opening the
SVCCTL pipe.
RPC_PIPE_WINREG Integer Constant to be supplied to the RpcBindInterface function for opening the
WINREG pipe.
RPC_PIPE_WKSSVC Integer Constant to be supplied to the RpcBindInterface function for opening the
WKSSVC pipe.
RPC_SERVICESTATE_CONTINUEPENDING Integer Constant returned in the State slot of a RpcServiceInfo structure when
gathering information concerning a Windows Service via
RpcSvcCtlEnumServices. Actually, the queried service is resuming.
RPC_SERVICESTATE_PAUSED Integer Constant returned in the State slot of a RpcServiceInfo structure when
gathering information concerning a Windows Service via
RpcSvcCtlEnumServices. Actually, the queried service is paused.
RPC_SERVICESTATE_PÄUSEPENDING Integer Constant returned in the State slot of a RpcServiceInfo structure when
gathering information concerning a Windows Service via
RpcSvcCtlEnumServices. Actually, the queried service is pausing.
RPC_SERVICESTATE_RUNNING Integer Constant returned in the State slot of a RpcServiceInfo structure when
gathering information concerning a Windows Service via
RpcSvcCtlEnumServices. Actually, the queried service is running.
RPC_SERVICESTATE_STARTPENDING Integer Constant returned in the State slot of a RpcServiceInfo structure when
gathering information concerning a Windows Service via
RpcSvcCtlEnumServices. Actually, the queried service is starting.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 54 - Predefined Variables and Constants - 689

Name Type Description


RPC_SERVICESTATE_STOPPED Integer Constant returned in the State slot of a RpcServiceInfo structure when
gathering information concerning a Windows Service via
RpcSvcCtlEnumServices. Actually, the queried service is stopped.
RPC_SERVICESTATE_STOPPENDING Integer Constant returned in the State slot of a RpcServiceInfo structure when
gathering information concerning a Windows Service via
RpcSvcCtlEnumServices. Actually, the queried service is stopping.
RPC_SHARETYPE_DEVICE Integer Constant returned in the ShareType slot of a RpcShareInfo structure when
gathering information concerning a Windows Share via
RpcSrvSvcEnumNetShare. Actually, the share is a device.
RPC_SHARETYPE_DISKTREE Integer Constant returned in the ShareType slot of a RpcShareInfo structure when
gathering information concerning a Windows Share via
RpcSrvSvcEnumNetShare. Actually, the share is a directory.
RPC_SHARETYPE_HIDDEN Integer Constant returned in the ShareType slot of a RpcShareInfo structure when
gathering information concerning a Windows Share via
RpcSrvSvcEnumNetShare. Actually, the share is hidden.
RPC_SHARETYPE_IPC Integer Constant returned in the ShareType slot of a RpcShareInfo structure when
gathering information concerning a Windows Share via
RpcSrvSvcEnumNetShare. Actually, the share is the inter process
communication one.
RPC_SHARETYPE_PRINTQ Integer Constant returned in the ShareType slot of a RpcShareInfo structure when
gathering information concerning a Windows Share via
RpcSrvSvcEnumNetShare. Actually, the share is a printer.
RPC_SRVSVC_ISAPPLE Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a Apple host.
RPC_SRVSVC_ISBACKUPBROWSER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a backup browser server.
RPC_SRVSVC_ISBACKUPCONTROLER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a backup domain controler.
RPC_SRVSVC_ISDIALINSERVER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a Dialin server.
RPC_SRVSVC_ISDOMAINCONTROLER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a domain controler.
RPC_SRVSVC_ISDOMAINMASTERBROWSER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a domain master browser server.
RPC_SRVSVC_ISDOMAINMEMBER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a domain member.
RPC_SRVSVC_ISMASTERBROWSER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a master browser server.
RPC_SRVSVC_ISNOVELLSERVER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a Novell server.
RPC_SRVSVC_ISNTSERVER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a Windows NT server.
RPC_SRVSVC_ISNTWORKSTATION Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a NT workstation.

Numara Software, Inc. and BMC Software, Inc. Confidential.


690 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


RPC_SRVSVC_ISOSF Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a OSF host.
RPC_SRVSVC_ISPOTENTIALBROWSER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a server that can run the browser service.
RPC_SRVSVC_ISPRINTQUEUESERVER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a print queue server.
RPC_SRVSVC_ISSERVER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a server.
RPC_SRVSVC_ISSQLSERVER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a server running SQL server.
RPC_SRVSVC_ISTIMESOURCE Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a time source.
RPC_SRVSVC_ISVMS Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a VMS host.
RPC_SRVSVC_ISWFW Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a Windows for Windows host.
RPC_SRVSVC_ISWIN9X Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a Windows 9x.
RPC_SRVSVC_ISWORKSTATION Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a workstation.
RPC_SRVSVC_ISXENIXSERVER Integer Bit field returned in the ServerType slot of a RpcServerInfo structure when
gathering information concerning a Windows Server via RpcSrvSvcQueryInfo.
When set, the server is a Xenix server.
RPC_WINREG_HKCR Integer Constant to be supplied to the RpcWinregOpenHKey function when opening the
HKEY_CLASSES_ROOT registry.
RPC_WINREG_HKCU Integer Constant to be supplied to the RpcWinregOpenHKey function when opening the
HKEY_CURRENT_USER registry.
RPC_WINREG_HKLM Integer Constant to be supplied to the RpcWinregOpenHKey function when opening the
HKEY_LOCAL_MACHINE registry.
RPC_WINREG_HKPD Integer Constant to be supplied to the RpcWinregOpenHKey function when opening the
HKEY_PERFORMANCE_DATA registry.
RPC_WINREG_HKU Integer Constant to be supplied to the RpcWinregOpenHKey function when opening the
HKEY_USERS registry.
RPC_WINREG_REGVAL_BINARY Integer Constant returned in the ValueType slot of a RpcWinregValueInfo structure
when gathering information concerning a Windows registry key value via
RpcWinregQueryValue. Actually, the key value is a binary sequence.
RPC_WINREG_REGVAL_DWORD Integer Constant returned in the ValueType slot of a RpcWinregValueInfo structure
when gathering information concerning a Windows registry key value via
RpcWinregQueryValue. Actually, the key value is a 4 bytes integer.
RPC_WINREG_REGVAL_EXPAND_SZ Integer Constant returned in the ValueType slot of a RpcWinregValueInfo structure
when gathering information concerning a Windows registry key value via
RpcWinregQueryValue. Actually, the key value is an expand string.
RPC_WINREG_REGVAL_SZ Integer Constant returned in the ValueType slot of a RpcWinregValueInfo structure
when gathering information concerning a Windows registry key value via
RpcWinregQueryValue. Actually, the key value is a string.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 54 - Predefined Variables and Constants - 691

Name Type Description


SC_MANAGER_ALL_ACCESS Integer STANDARD_RIGHTS_REQUIRED is included in addition to all of the access
types listed in this table.
SC_MANAGER_CONNECT Integer Connecting to the service control manager is enabled.
SC_MANAGER_CREATE_SERVICE Integer Calling of the CreateService function to create a service object and add it to the
database is enabled.
SC_MANAGER_ENUMERATE_SERVICE Integer Calling of the EnumServicesStatus function to list the services that are in the
database is enabled.
SC_MANAGER_LOCK Integer Calling of the LockServiceDatabase function to acquire a lock on the database
is enabled.
SC_MANAGER_QUERY_LOCK_STATUS Integer Calling of the QueryServiceLockStatus function to retrieve the lock status
information for the database is enabled.
SERVICE_ACTIVE Integer Enumerates services that are in the following states:
SERVICE_START_PENDING, SERVICE_STOP_PENDING, SERVICE_RUNNING,
SERVICE_CONTINUE_PENDING, SERVICE_PAUSE_PENDING, and
SERVICE_PAUSED.
SERVICE_CONTINUE Integer The service is taken out of pause or is started.
SERVICE_CONTINUE_PENDING Integer A service continue request is pending.
SERVICE_DRIVER Integer Enumerates services of type SERVICE_KERNEL_DRIVER and
SERVICE_FILE_SYSTEM_DRIVER.
SERVICE_ERROR_CRITICAL Integer The startup program logs the error, if possible. If the last-known-good
configuration is being started, the startup operation fails. Otherwise, the
system is restarted with the last-known-good configuration.
SERVICE_ERROR_IGNORE Integer The startup (boot) program logs the error but continues the startup operation.
SERVICE_ERROR_NORMAL Integer The startup program logs the error and puts up a message box pop-up but
continues the startup operation.
SERVICE_ERROR_SEVERE Integer The startup program logs the error. If the last-known-good configuration is
being started, the startup operation continues. Otherwise, the system is
restarted with the last-known-good configuration.
SERVICE_FILE_SYSTEM_DRIVER Integer Installable file system driver, for example an NFS file redirector.
SERVICE_INACTIVE Integer Enumerates services that are in the SERVICE_STOPPED state.
SERVICE_INTERROGATE Integer Enables calling of the ControlService function to ask the service to report its
status immediately.
SERVICE_KERNEL_DRIVER Integer Kernel driver, usually a device driver.
SERVICE_PAUSE Integer The service is paused.
SERVICE_PAUSE_PENDING Integer A service pause request is pending.
SERVICE_PAUSED Integer The service is paused
SERVICE_RUNNING Integer The service is running.
SERVICE_START_AUTO Integer Specifies a device driver or Win32 service started by the service control manager
automatically during system startup.
SERVICE_START_BOOT Integer Specifies a device driver started by the operating system loader. This value is
valid only if the service type is SERVICE_KERNEL_DRIVER or
SERVICE_FILE_SYSTEM_DRIVER.
SERVICE_START_DEMAND Integer Specifies a device driver or Win32 service started by the service control
manager when using the control panel.
SERVICE_START_DISABLED Integer Specifies a device driver or Win32 service that can no longer be started.
SERVICE_START_PENDING Integer The service is starting.
SERVICE_START_SYSTEM Integer Specifies a device driver started at system startup, after the boot drivers are
loaded. This value is valid only if the service type is SERVICE_KERNEL_DRIVER
or SERVICE_FILE_SYSTEM_DRIVER.
SERVICE_STATE_ALL Integer Combines the following states: SERVICE_ACTIVE and SERVICE_INACTIVE.
SERVICE_STOP Integer The service is stopped.
SERVICE_STOP_PENDING Integer The service is stopping.

Numara Software, Inc. and BMC Software, Inc. Confidential.


692 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


SERVICE_STOPPED Integer The service is not running.
SERVICE_WIN32 Integer Enumerates services of type SERVICE_WIN32_OWN_PROCESS and
SERVICE_WIN32_SHARE_PROCESS.
SERVICE_WIN32_OWN_PROCESS Integer Specifies a service that runs in its own Win32 process.
SERVICE_WIN32_SHARE_PROCESS Integer Specifies a service that shares a Win32 process with other services.
SHARETYPE_DEVICE Integer Communication device
SHARETYPE_DISKTREE Integer Disk drive
SHARETYPE_IPC Integer Interprocess communication (IPC)
SHARETYPE_PRINTQ Integer Print queue
SHARETYPE_SPECIAL Integer Special share reserved for interprocess communication (IPC$) or remote
administration of the server (ADMIN$). Can also refer to administrative shares
such as C$, D$, E$, and so forth.
SHARETYPE_TEMPORARY Integer A temporary share
SMTP_DEFAULT_PORT Integer The default port of the SMTP server
SNMP_COUNT Integer The object is a non-negative integer which monotonically increases until it
reaches a maximum value (not exceeding 232 - 1) and then wraps back to 0.
SNMP_GAUGE Integer The object is a non-negative integer which can increase or decrease, but which
latches at a maximum value.
SNMP_INT / SNMP_INTEGER Integer The value is an integer.
SNMP_IPADDR Integer The object is of type IP address which contains four digit strings.
SNMP_NULL Integer The object acts as a placeholder for read operations.
SNMP_OID Integer The object is of type Object ID which means it has a fixed number of sub-ids
each of which is a 32 bit integer.
SNMP_PHYS / SNMP_PHYSADDR Integer The object is of type Physical Address which contains six digit strings.
SNMP_STR / SNMP_STRING Integer The value is a string.
SNMP_TABLE Integer The object is of type table.
SNMP_TIME Integer The object is a non-negative integer which counts the time in hundredths of a
second since some specific time, not exceeding 232 - 1.
SQL_BIGINT Integer Exact numeric value with precision 19 (if signed) or 20 (if unsigned) and scale 0
(signed: –2[63] <= n <= 2[63] – 1, unsigned: 0 <= n <= 2[64] – 1)
SQL_BINARY Integer Binary data of fixed length n
SQL_BIT Integer Single bit binary data
SQL_CHAR Integer Character string of fixed string length n
SQL_DATE Integer Return the year, month, and day fields, conforming to the rules of the Gregorian
calendar in the format of yyyy-mm-dd
SQL_DECIMAL Integer Signed, exact, numeric value with a precision of at least p and scale s. (The
maximum precision is driver-defined; 1 <= p <= 15; s <= p)
SQL_DOUBLE Integer Signed, approximate, numeric value with a binary precision 53 (zero or
absolute value 10[–308] to 10[308])
SQL_FETCH_ABSOLUTE Integer Return the rowset starting at row FetchOffset (1 for the first row)
SQL_FETCH_FIRST Integer Return the first rowset in the result set; the value of FetchOffset is ignored
SQL_FETCH_LAST Integer Return the last complete rowset in the result set; the value of FetchOffset is
ignored
SQL_FETCH_NEXT Integer Return the next rowset; the value of FetchOffset is ignored
SQL_FETCH_PRIOR Integer Return the prior rowset; the value of FetchOffset is ignored
SQL_FETCH_RELATIVE Integer Return the rowset FetchOffset from the start of the current rowset
SQL_FLOAT Integer Signed, approximate, numeric value with a binary precision of at least p. (The
maximum precision is driver-defined.
SQL_INTEGER Integer Exact numeric value with precision 10 and scale 0
(signed: –2[31] <= n <= 2[31] – 1, unsigned: 0 <= n <= 2[32] – 1)

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 54 - Predefined Variables and Constants - 693

Name Type Description


SQL_LONGVARBINARY Integer Variable length binary data. Maximum length is data source–dependent
SQL_LONGVARCHAR Integer Variable length character data. Maximum length is data source–dependent
SQL_NO_NULLS Integer The column does not allow NULL values
SQL_NULLABLE Integer The column allows NULL values
SQL_NULLABLE_UNKNOWN Integer The driver cannot determine if the column allows NULL values
SQL_NUMERIC Integer Signed, exact, numeric value with a precision p and scale s (1 <= p <= 15; s
<= p)
SQL_REAL Integer Signed, approximate, numeric value with a binary precision 24 (zero or
absolute value 10[–38] to 10[38])
SQL_SMALLINT Integer Exact numeric value with precision 5 and scale 0
(signed: –32,768 <= n <= 32,767, unsigned: 0 <= n <= 65,535)
SQL_TIME Integer Return the hour, minute, and second fields, with valid values for hours of 00 to
23, valid values for minutes of 00 to 59, and valid values for seconds of 00 to
59 and in the form of hh:mm:s
SQL_TIMESTAMP Integer Return the year, month, day, hour, minute, and second fields, with valid values
as defined for the DATE and TIME data types in the form of yyyy-mm-dd
hh:mm:ss
SQL_TINYINT Integer Exact numeric value with precision 3 and scale 0
(signed: –128 <= n <= 127, unsigned: 0 <= n <= 255)
SQL_VARBINARY Integer Variable length binary data of maximum length n; the maximum is set by the
user
SQL_VARCHAR Integer Variable-length character string with a maximum string length n
SQL_WCHAR Integer Unicode character string of fixed string length n
SQL_WLONGVARCHAR Integer Unicode variable-length character data; maximum length is data source–
dependent
SQL_WVARCHAR Integer Unicode variable-length character string with a maximum string length n
SYSINFO_ALPHA Integer The GetSysInfo function returns TRUE if the system is running on a DEC Alpha
CPU, FALSE otherwise.
SYSINFO_ANNVIX Integer The GetSysInfo function returns TRUE if the operating system is ANNVIX,
FALSE otherwise.
SYSINFO_ARCH Integer The GetSysInfo function returns TRUE if the operating system is Arch, FALSE
otherwise.
SYSINFO_ARKLINUX Integer The GetSysInfo function returns TRUE if the operating system is Ark Linux,
FALSE otherwise.
SYSINFO_AUROX Integer The GetSysInfo function returns TRUE if the operating system is Aurox, FALSE
otherwise.
SYSINFO_BLACKCAT Integer The GetSysInfo function returns TRUE if the operating system is BlackCat,
FALSE otherwise.
SYSINFO_CENTOS Integer The GetSysInfo function returns TRUE if the operating system is CentOS,
FALSE otherwise.
SYSINFO_COBALT Integer The GetSysInfo function returns TRUE if the operating system is Cobalt, FALSE
otherwise.
SYSINFO_CONNECTIVA Integer The GetSysInfo function returns TRUE if the operating system is Connectiva,
FALSE otherwise.
SYSINFO_DEBIAN Integer The GetSysInfo function returns TRUE if the operating system is Debian, FALSE
otherwise.
SYSINFO_FEDORA Integer The GetSysInfo function returns TRUE if the operating system is Fedora, FALSE
otherwise.
SYSINFO_GENTOO Integer The GetSysInfo function returns TRUE if the operating system is Gentoo,
FALSE otherwise.
SYSINFO_IMMUNIX Integer The GetSysInfo function returns TRUE if the operating system is Immunix,
FALSE otherwise.

Numara Software, Inc. and BMC Software, Inc. Confidential.


694 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


SYSINFO_KNOPPIX Integer The GetSysInfo function returns TRUE if the operating system is Knoppix,
FALSE otherwise.
SYSINFO_LFS Integer The GetSysInfo function returns TRUE if the operating system is LFS, FALSE
otherwise.
SYSINFO_MACOSX Integer The GetSysInfo function returns TRUE if the operating system is Mac OS X,
FALSE otherwise.
SYSINFO_MACOSXCHEETAH Integer The GetSysInfo function returns TRUE if the operating system is Mac Cheetah,
FALSE otherwise.
SYSINFO_MACOSXDP4 Integer The GetSysInfo function returns TRUE if the operating system is Mac DP 4,
FALSE otherwise.
SYSINFO_MACOSXJAGUAR Integer The GetSysInfo function returns TRUE if the operating system is Mac Jaguar,
FALSE otherwise.
SYSINFO_MACOSXLEOPARD Integer The GetSysInfo function returns TRUE if the operating system is Mac Leopard,
FALSE otherwise.
SYSINFO_MACOSXPANTHER Integer The GetSysInfo function returns TRUE if the operating system is Mac Panther,
FALSE otherwise.
SYSINFO_MACOSXPUMA Integer The GetSysInfo function returns TRUE if the operating system is Mac Puma,
FALSE otherwise.
SYSINFO_MACOSXPUBLICBETA Integer The GetSysInfo function returns TRUE if the operating system is Mac Public
Beta, FALSE otherwise.
SYSINFO_MACOSXSERVER10 Integer The GetSysInfo function returns TRUE if the operating system is Mac Server 10,
FALSE otherwise.
SYSINFO_MACOSXSNOWLEOPARD Integer The GetSysInfo function returns TRUE if the operating system is Mac Snow
Leopard, FALSE otherwise.
SYSINFO_MACOSXTIGER Integer The GetSysInfo function returns TRUE if the operating system is Mac Tiger,
FALSE otherwise.
SYSINFO_MANDRAKE Integer The GetSysInfo function returns TRUE if the operating system is Mandrake,
FALSE otherwise.
SYSINFO_MANDRIVA Integer The GetSysInfo function returns TRUE if the operating system is Mandriva,
FALSE otherwise.
SYSINFO_MKLINUX Integer The GetSysInfo function returns TRUE if the operating system is MK Linux,
FALSE otherwise.
SYSINFO_NOVELLINUX Integer The GetSysInfo function returns TRUE if the operating system is Novell Linux,
FALSE otherwise.
SYSINFO_PLD Integer The GetSysInfo function returns TRUE if the operating system is PLD, FALSE
otherwise.
SYSINFO_PPC Integer The GetSysInfo function returns TRUE if the operating system is PPC, FALSE
otherwise.
SYSINFO_RAM Integer The GetSysInfo function returns the amount of installed physical RAM in MBs.
SYSINFO_REDHAT7 Integer True if the system is running Red Hat 7
SYSINFO_REDHAT8 Integer True if the system is running Red Hat 8
SYSINFO_REDHAT9 Integer True if the system is running Red Hat 9
SYSINFO_REDHAT9COMP Integer The GetSysInfo function returns TRUE if the operating system is Red Hat 9
Comp, FALSE otherwise.
SYSINFO_RHEL Integer The GetSysInfo function returns TRUE if the operating system is Red Hat
Enterprise Linux, FALSE otherwise.
SYSINFO_SLACKWARE Integer The GetSysInfo function returns TRUE if the operating system is Slack Ware,
FALSE otherwise.
SYSINFO_SMESERVER Integer The GetSysInfo function returns TRUE if the operating system is SME Server,
FALSE otherwise.
SYSINFO_SOLARIS7 Integer True if the system is running Solaris 7
SYSINFO_SOLARIS8 Integer True if the system is running Solaris 8
SYSINFO_SOLARIS9 Integer True if the system is running Solaris 9

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 54 - Predefined Variables and Constants - 695

Name Type Description


SYSINFO_SUSE Integer The GetSysInfo function returns TRUE if the operating system is SUSE, FALSE
otherwise.
SYSINFO_SUSEES9 Integer The GetSysInfo function returns TRUE if the operating system is SUSE ES9,
FALSE otherwise.
SYSINFO_TINYSOFA Integer The GetSysInfo function returns TRUE if the operating system is tinysofa,
FALSE otherwise.
SYSINFO_TURBOLINUX Integer The GetSysInfo function returns TRUE if the operating system is Turbolinux,
FALSE otherwise.
SYSINFO_ULTRAPENGUIN Integer The GetSysInfo function returns TRUE if the operating system is Ultra Penguin,
FALSE otherwise.
SYSINFO_UNITED Integer The GetSysInfo function returns TRUE if the operating system is United, FALSE
otherwise.
SYSINFO_UNIX Integer The GetSysInfo function returns TRUE if the system is running on UNIX, FALSE
otherwise.
SYSINFO_VALINUX Integer The GetSysInfo function returns TRUE if the operating system is VA Linux,
FALSE otherwise.
SYSINFO_WIN16 Integer The GetSysInfo function returns TRUE if the system is running 16-bit Windows
(3.1 or 3.11), FALSE if it is 32-bits.
SYSINFO_WIN2000 Integer The GetSysInfo function returns TRUE if the operating system is Windows
2000, FALSE otherwise.
SYSINFO_WIN2000PRO Integer The GetSysInfo function returns TRUE if the operating system is Windows
2000 Professional, FALSE otherwise.
SYSINFO_WIN2000SRV Integer The GetSysInfo function returns TRUE if the operating system is Windows
2000 Server, FALSE otherwise.
SYSINFO_WIN2003 Integer The GetSysInfo function returns TRUE if the operating system is Windows
2003, FALSE otherwise.
SYSINFO_WIN2003_32 Integer The GetSysInfo function returns TRUE if the system is running 32-bit Windows
2003, FALSE otherwise.
SYSINFO_WIN2003_64 Integer The GetSysInfo function returns TRUE if the system is running 64-bit Windows
2003, FALSE otherwise.
SYSINFO_WIN32 Integer The GetSysInfo function returns TRUE if the system is running 32-bit Windows
(95/98 or NT), FALSE if it is 16-bits.
SYSINFO_WIN64 Integer The GetSysInfo function returns TRUE if the system is running 64-bit Windows,
FALSE otherwise.
SYSINFO_WIN95 Integer The GetSysInfo function returns TRUE if the operating system is Windows 95,
FALSE otherwise.
SYSINFO_WIN98 Integer The GetSysInfo function returns TRUE if the operating system is Windows 98,
FALSE otherwise.
SYSINFO_WINME Integer The GetSysInfo function returns TRUE if the operating system is Windows
Millenium Edition (ME), FALSE otherwise.
SYSINFO_WINNT Integer The GetSysInfo function returns TRUE if the operating system is Windows NT,
FALSE otherwise.
SYSINFO_WINNTSRV Integer The GetSysInfo function returns TRUE if the operating system is Windows NT
Server, FALSE otherwise.
SYSINFO_WINNTWKS Integer The GetSysInfo function returns TRUE if the operating system is Windows NT
Workstation, FALSE otherwise.
SYSINFO_WINVERH Integer Defines the major part of the Windows operating system version number.
SYSINFO_WINVERL Integer Defines the minor part of the Windows operating system version number.
SYSINFO_WINVISTA Integer The GetSysInfo function returns TRUE if the operating system is Windows
Vista, FALSE otherwise.
SYSINFO_WINVISTA32 Integer The GetSysInfo function returns TRUE if the system is running 32-bit Windows
Vista, FALSE otherwise.
SYSINFO_WINVISTA64 Integer The GetSysInfo function returns TRUE if the system is running 64-bit Windows
Vista, FALSE otherwise.

Numara Software, Inc. and BMC Software, Inc. Confidential.


696 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


SYSINFO_WINXP Integer The GetSysInfo function returns TRUE if the operating system is Windows X,
FALSE otherwise.
SYSINFO_WINXP32 Integer The GetSysInfo function returns TRUE if the system is running 32-bit Windows
XP, FALSE otherwise.
SYSINFO_WINXP64 Integer The GetSysInfo function returns TRUE if the system is running 64-bit Windows
XP, FALSE otherwise.
SYSINFO_WINXPPRO Integer The GetSysInfo function returns TRUE if the operating system is Windows XP
Professional, FALSE otherwise.
SYSINFO_WINXPSRV Integer The GetSysInfo function returns TRUE if the operating system is Windows XP
Serve, FALSE otherwise.
SYSINFO_YELLOWDOG Integer The GetSysInfo function returns TRUE if the operating system is Yellow Dog,
FALSE otherwise.
USER_PRIV_ADMIN Integer The user account type is Administrator.
USER_PRIV_GUEST Integer The user account type is Guest.
USER_PRIV_USER Integer The user account type is User.
VARTYPE_BOOL Integer Variable is of type boolean.
VARTYPE_BOOLEAN_ARRAY Integer Variable is of type boolean array.
VARTYPE_CHAR Integer Variable is of type character.
VARTYPE_CHAR_ARRAY Integer Variable is of type character array.
VARTYPE_DOUBLE Integer Variable is of type double.
VARTYPE_DOUBLE_ARRAY Integer Variable is of type double array.
VARTYPE_FLOAT Integer Variable is of type float.
VARTYPE_FLOAT_ARRAY Integer Variable is of type float array.
VARTYPE_INTEGER Integer Variable is of type integer.
VARTYPE_INTEGER_ARRAY Integer Variable is of type integer array.
VARTYPE_STRING Integer Variable is of type string.
VARTYPE_STRING_ARRAY Integer Variable is of type string array.
VARTYPE_STRUCT Integer Variable is of type structure.
VARTYPE_STRUCT_ARRAY Integer Variable is of type structure array.
WIN_CB_ADDSTRING Integer Adds a string to the list box of a combo box. If the combo box does not have the
WIN_CBS_SORT style, the string is added to the end of the list. Otherwise, the
string is inserted into the list, and the list is sorted.
WIN_CB_DELETESTRING Integer Deletes a string in the list box of a combo box.
WIN_CB_DIR Integer Adds names to the list displayed by the combo box. The message adds the
names of directories and files that match a specified string and set of file
attributes. WIN_CB_DIR can also add mapped drive letters to the list.
WIN_CB_FINDSTRING Integer Searches the list box of a combo box for an item beginning with the characters
in a specified string.
WIN_CB_FINDSTRINGEXACT Integer Finds the first list box string in a combo box that matches the string specified in
the lParam parameter.
WIN_CB_GETCOUNT Integer Retrieves the number of items in the list box of a combo box.
WIN_CB_GETCURSEL Integer Retrieves the index of the currently selected item, if any, in the list box of a
combo box.
WIN_CB_GETDROPPEDCONTROLRECT Integer Retrieves the screen coordinates of a combo box in its dropped-down state.
WIN_CB_GETDROPPEDSTATE Integer Determines whether the list box of a combo box is dropped down.
WIN_CB_GETDROPPEDWIDTH Integer Retrieves the minimum allowable width, in pixels, of the list box of a combo box
with the WIN_CBS_DROPDOWN or WIN_CBS_DROPDOWNLIST style.
WIN_CB_GETEDITSEL Integer Gets the starting and ending character positions of the current selection in the
edit control of a combo box.
WIN_CB_GETEXTENDEDUI Integer Determines whether a combo box has the default user interface or the
extended user interface.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 54 - Predefined Variables and Constants - 697

Name Type Description


WIN_CB_GETHORIZONTALEXTENT Integer Retrieves from a combo box the width, in pixels, by which the list box can be
scrolled horizontally (the scrollable width). This is applicable only if the list box
has a horizontal scroll bar.
WIN_CB_GETITEMDATA Integer Retrieves the application-supplied value associated with the specified item in
the combo box.
WIN_CB_GETITEMHEIGHT Integer Determines the height of list items or the selection field in a combo box.
WIN_CB_GETLBTEXT Integer Retrieves a string from the list of a combo box.
WIN_CB_GETLBTEXTLEN Integer Retrieve the length, in characters, of a string in the list of a combo box.
WIN_CB_GETLOCALE Integer Retrieves the current locale of the combo box. The locale is used to determine
the correct sorting order of displayed text for combo boxes with the
WIN_CBS_SORT style and text added by using the WIN_CB_ADDSTRING
message.
WIN_CB_GETTOPINDEX Integer Retrieves the zero-based index of the first visible item in the list box portion of a
combo box. Initially, the item with index 0 is at the top of the list box, but if the
list box contents have been scrolled, another item might be at the top.
WIN_CB_INITSTORAGE Integer Allocates memory for storing list box items and is sent before adding a large
number of items to the list box portion of a combo box.
WIN_CB_INSERTSTRING Integer Inserts a string into the list box of a combo box. Unlike the
WIN_CB_ADDSTRING message, the WIN_CB_INSERTSTRING message does
not cause a list with the WIN_CBS_SORT style to be sorted.
WIN_CB_LIMITTEXT Integer Limits the length of the text the user can type into the edit control of a combo
box.
WIN_CB_RESETCONTENT Integer Removes all items from the list box and edit control of a combo box.
WIN_CB_SELECTSTRING Integer Searches the list of a combo box for an item that begins with the characters in
a specified string. If a matching item is found, it is selected and copied to the
edit control.
WIN_CB_SETCURSEL Integer Selects a string in the list of a combo box. If necessary, the list scrolls the
string into view. The text in the edit control of the combo box changes to reflect
the new selection, and any previous selection in the list is removed.
WIN_CB_SETDROPPEDWIDTH Integer Sets the maximum allowable width, in pixels, of the list box of a combo box with
the WIN_CBS_DROPDOWN or WIN_CBS_DROPDOWNLIST style.
WIN_CB_SETEDITSEL Integer Selects characters in the edit control of a combo box.
WIN_CB_SETEXTENDEDUI Integer Selects either the default user interface or the extended user interface for a
combo box that has the WIN_CBS_DROPDOWN or WIN_CBS_DROPDOWNLIST
style.
WIN_CB_SETHORIZONTALEXTENT Integer Sets the width, in pixels, by which a list box can be scrolled horizontally (the
scrollable width). If the width of the list box is smaller than this value, the
horizontal scroll bar horizontally scrolls items in the list box. If the width of the
list box is equal to or greater than this value, the horizontal scroll bar is hidden
or, if the combo box has the WIN_CBS_DISABLENOSCROLL style, dizabled.
WIN_CB_SETITEMDATA Integer Sets the value associated with the specified item in a combo box.
WIN_CB_SETITEMHEIGHT Integer Sets the height of list items or the selection field in a combo box.
WIN_CB_SETLOCALE Integer Sets the current locale of the combo box. If the combo box has the
WIN_CBS_SORT style and strings are added using WIN_CB_ADDSTRING, the
locale of a combo box affects how list items are sorted.
WIN_CB_SETTOPINDEX Integer Ensures that a particular item is visible in the list box of a combo box. The
system scrolls the list box contents so that either the specified item appears at
the top of the list box or the maximum scroll range has been reached.
WIN_CB_SHOWDROPDOWN Integer Shows or hides the list box of a combo box that has the
WIN_CBS_DROPDOWN or WIN_CBS_DROPDOWNLIST style.
WIN_CBS_AUTOHSCROLL Integer Automatically scrolls the text in an edit control to the right when the user types
a character at the end of the line. If this style is not set, only text that fits within
the rectangular boundary is allowed.

Numara Software, Inc. and BMC Software, Inc. Confidential.


698 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


WIN_CBS_DISABLENOSCROLL Integer Shows a dizabled vertical scroll bar in the list box when the box does not
contain enough items to scroll. Without this style, the scroll bar is hidden when
the list box does not contain enough items.
WIN_CBS_DROPDOWN Integer Similar to WIN_CBS_SIMPLE, except that the list box is not displayed unless
the user selects an icon next to the edit control.
WIN_CBS_DROPDOWNLIST Integer Similar to WIN_CBS_DROPDOWN, except that the edit control is replaced by a
static text item that displays the current selection in the list box.
WIN_CBS_HASSTRINGS Integer Specifies that an owner-drawn combo box contains items consisting of strings.
The combo box maintains the memory and address for the strings, so the
application can use the WIN_CB_GETLBTEXT message to retrieve the text for a
particular item.
WIN_CBS_LOWERCASE Integer Converts to lowercase any uppercase characters entered into the edit control of
a combo box.
WIN_CBS_NOINTEGRALHEIGHT Integer Specifies that the size of the combo box is exactly the size specified by the
application when it created the combo box. Normally, Windows sizes a combo
box so that it does not display partial items.
WIN_CBS_OEMCONVERT Integer Converts text entered in the combo box edit control. The text is converted from
the Windows character set to the OEM character set and then back to the
Windows set. This ensures proper character conversion when the application
calls the CharToOem function to convert a Windows string in the combo box to
OEM characters. This style is most useful for combo boxes that contain
filenames and applies only to combo boxes created with the WIN_CBS_SIMPLE
or WIN_CBS_DROPDOWN style.
WIN_CBS_OWNERDRAWFIXED Integer Specifies that the owner of the list box is responsible for drawing its contents
and that the items in the list box are all the same height. The owner window
receives a WM_MEASUREITEM message when the combo box is created and a
WM_DRAWITEM message when a visual aspect of the combo box has
changed.
WIN_CBS_OWNERDRAWVARIABLE Integer Specifies that the owner of the list box is responsible for drawing its contents
and that the items in the list box are variable in height. The owner window
receives a WM_MEASUREITEM message for each item in the combo box when
you create the combo box; the owner window receives a WM_DRAWITEM
message when a visual aspect of the combo box has changed.
WIN_CBS_SIMPLE Integer Displays the list box at all times. The current selection in the list box is
displayed in the edit control.
WIN_CBS_SORT Integer Automatically sorts strings entered into the list box.
WIN_CBS_UPPERCASE Integer Converts to uppercase any lowercase characters entered into the edit control of
a combo box.
WIN_CLASS_BUTTON String Designates a small rectangular child window that represents a button the user
can click to turn it on or off. Button controls can be used alone or in groups,
and they can either be labeled or appear without text. Button controls typically
change appearance when the user clicks them.
WIN_CLASS_COMBOBOX String Designates a control consisting of a list box and a selection field similar to an
edit control. When using this style, an application should either display the list
box at all times or enable a drop-down list box.
Depending on the style of the combo box, the user can or cannot edit the
contents of the selection field. If the list box is visible, typing characters into the
selection field highlights the first list box entry that matches the characters
typed. Conversely, selecting an item in the list box displays the selected text in
the selection field.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 54 - Predefined Variables and Constants - 699

Name Type Description


WIN_CLASS_EDIT String Designates a rectangular child window into which the user can type text from
the keyboard. The user selects the control and gives it the keyboard focus by
clicking it or moving to it by pressing the TAB key. The user can type text when
the edit control displays a flashing caret; use the mouse to move the cursor,
select characters to be replaced, or position the cursor for inserting
characters; or use the BACKSPACE key to delete characters.
Edit controls use the variable-pitch system font and display characters from the
ANSI character set. The WM_SETFONT message can also be sent to the edit
control to change the default font.
Edit controls expand tab characters into as many space characters as are
required to move the caret to the next tab stop. Tab stops are assumed to be at
every eighth character position.
WIN_CLASS_LISTBOX String Designates a list of character strings. Specify this control whenever an
application must present a list of names, such as file names, from which the
user can select. The user can select a string by clicking it. A selected string is
highlighted, and a notification message is passed to the parent window. Use a
vertical or horizontal scroll bar with a list box to scroll lists that are too long for
the control window. The list box automatically hides or shows the scroll bar, as
needed.
WIN_CLASS_RICHEDIT String Designates a window in which the user can enter, edit, format, print, and save
text. The text can be assigned character and paragraph formatting, and can
include embedded Component Object Model (COM) objects. Rich edit controls
support almost all of the messages and notification messages used with
multiline edit controls. Thus, applications that already use edit controls can be
easily changed to use rich edit controls. Additional messages and notifications
enable applications to access the functionality unique to rich edit controls.
WIN_CLASS_RICHEDIT2 String WIN_CLASS_RICHEDIT2 provides a window with the same possibilities as
WIN_CLASS_RICHEDIT with the addition of single line or multiline capabilities
and plain or rich text.
WIN_CLASS_scroll bar String Designates a rectangle that contains a scroll box and has direction arrows at
both ends. The scroll bar sends a notification message to its parent window
whenever the user clicks the control. The parent window is responsible for
updating the position of the scroll box, if necessary. Scroll bar controls have the
same appearance and function as scroll bars used in ordinary windows. Unlike
scroll bars, however, scroll bar controls can be positioned anywhere in a
window for use whenever scrolling input is needed for a window.
The scroll bar class also includes size box controls. A size box is a small
rectangle the user can expand to change the size of the window.
WIN_CLASS_STATIC String Designates a simple text field, box, or rectangle used to label, box, or separate
other controls. Static controls take no input and provide no output.
WIN_CW_CENTER Integer The window is created centered on the screen.
WIN_CW_USEDEFAULT Integer Windows defines where and in which size the window is to be put on the
screen.
WIN_ES_AUTOHSCROLL Integer Automatically scrolls text to the right by 10 characters when the user types a
character at the end of the line. When the user presses the ENTER key, the
control scrolls all text back to position zero.
WIN_ES_AUTOVSCROLL Integer Automatically scrolls text up one page when the user presses the ENTER key
on the last line.
WIN_ES_CENTER Integer Centers text in a multiline edit control.
WIN_ES_LEFT Integer Left-aligns text.
WIN_ES_LOWERCASE Integer Converts all characters to lowercase as they are typed into the edit control.

Numara Software, Inc. and BMC Software, Inc. Confidential.


700 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


WIN_ES_MULTILINE Integer Designates a multiline edit control. The default is single-line edit control.
When the multiline edit control is in a dialog box, the default response to
pressing the ENTER key is to activate the default button. To use the ENTER key
as a carriage return, use the WIN_ES_WANTRETURN style.
When the multiline edit control is not in a dialog box and the
WIN_ES_AUTOVSCROLL style is specified, the edit control shows as many
lines as possible and scrolls vertically when the user presses the ENTER key. If
you do not specify WIN_ES_AUTOVSCROLL, the edit control shows as many
lines as possible and beeps if the user presses the ENTER key when no more
lines can be displayed.
If you specify the WIN_ES_AUTOHSCROLL style, the multiline edit control
automatically scrolls horizontally when the caret goes past the right edge of the
control. To start a new line, the user must press the ENTER key. If you do not
specify WIN_ES_AUTOHSCROLL, the control automatically wraps words to the
beginning of the next line when necessary. A new line is also started if the user
presses the ENTER key. The window size determines the position of the word
wrap. If the window size changes, the word wrapping position changes and the
text is redisplayed.
Multiline edit controls can have scroll bars. An edit control with scroll bars
processes its own scroll bar messages. Note that edit controls without scroll
bars scroll as described in the previous paragraphs and process any scroll
messages sent by the parent window.
WIN_ES_NOHIDESEL Integer Negates the default behavior for an edit control. The default behavior hides the
selection when the control loses the input focus and inverts the selection when
the control receives the input focus. If you specify WIN_ES_NOHIDESEL, the
selected text is inverted, even if the control does not have the focus.
WIN_ES_NUMBER Integer Allows only digits to be entered into the edit control.
WIN_ES_OEMCONVERT Integer Converts text entered in the edit control. The text is converted from the
Windows character set to the OEM character set and then back to the Windows
set. This ensures proper character conversion when the application calls the
CharToOem function to convert a Windows string in the edit control to OEM
characters. This style is most useful for edit controls that contain filenames.
WIN_ES_PASSWORD Integer Displays an asterisk (*) for each character typed into the edit control. You can
use the WIN_EM_SETPASSWORDCHAR message to change the character that
is displayed.
WIN_ES_READONLY Integer Prevents the user from typing or editing text in the edit control.
WIN_ES_RIGHT Integer Right-aligns text in a multiline edit control.
WIN_ES_UPPERCASE Integer Converts all characters to uppercase as they are typed into the edit control.
WIN_ES_WANTRETURN Integer Specifies that a carriage return be inserted when the user presses the ENTER
key while entering text into a multiline edit control in a dialog box. If you do not
specify this style, pressing the ENTER key has the same effect as pressing the
dialog box’s default push button. This style has no effect on a single-line edit
control.
WIN_FW_BLACK Integer 900
WIN_FW_BOLD Integer 700
WIN_FW_DEMIBOLD Integer 600
WIN_FW_DONTCARE Integer 0
WIN_FW_EXTRABOLD Integer 800
WIN_FW_EXTRALIGHT Integer 200
WIN_FW_HEAVY Integer 900
WIN_FW_LIGHT Integer 300
WIN_FW_MEDIUM Integer 500
WIN_FW_NORMAL Integer 400
WIN_FW_REGULAR Integer 400
WIN_FW_SEMIBOLD Integer 600
WIN_FW_THIN Integer 100

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 54 - Predefined Variables and Constants - 701

Name Type Description


WIN_FW_ULTRABOLD Integer 800
WIN_FW_ULTRALIGHT Integer 200
WIN_HIDDEN Integer The window is created hidden from view. Although the window exists it is not
visible.
WIN_MAXIMISED Integer The window is created maximized, filling the entire viewing area of the screen.
WIN_MINIMISED Integer The window is created in an iconized state.
WIN_NORMAL Integer The window is created visible and is sized and positioned using default values
determined by the operating system.
WIN_SM_ARRANGE Integer Windows 95 only: Flags specifying how the system arranged minimized
windows. For more information about minimized windows, see the following
Remarks section.
WIN_SM_CLEANBOOT Integer Windows 95 only: Value that specifies how the system was started:0 Normal
boot1 Fail-safe boot2 Fail-safe with network bootFail-safe boot (also called
SafeBoot) bypasses the user's startup files.
WIN_SM_CMONITORS Integer Number of monitors
WIN_SM_CMOUSEBUTTONS Integer Number of mouse buttons
WIN_SM_CXBORDER Integer Window border width
WIN_SM_CXCURSOR Integer Cursor width
WIN_SM_CXDLGFRAME Integer Dialog window frame width
WIN_SM_CXDOUBLECLK Integer Windows NT only: Height of a rectangle around the location of a first click in a
double-click sequence. The second click must occur within this rectangle for
the system to consider the two clicks a double-click.Windows 95 only: Height,
in pixels, of the rectangle within which two successive mouse clicks must fall to
generate a double-click. (The two clicks must also occur within a specified
time.)
WIN_SM_CXDRAG Integer Avoid drag x tolerance
WIN_SM_CXEDGE Integer 3-D border width
WIN_SM_CXFIXEDFRAME Integer Dialog window frame width
WIN_SM_CXFRAME Integer Width of window frame for a window that can be resized.
WIN_SM_CXFULLSCREEN Integer Full screen client area width
WIN_SM_CXHSCROLL Integer Horizontal scroll arrow width
WIN_SM_CXHTHUMB Integer Width of horizontal scroll bar thumb box
WIN_SM_CXICON Integer Icon width; this is typically 32 , but can vary depending on the installed display
hardware.Windows 95 only: The LoadIcon function can only load icons of these
dimensions.
WIN_SM_CXICONSPACING Integer Horizontal icon spacing. Windows NT only: Width of rectangular cell that
Program Manager uses to position tiled icons.Windows 95 only: Width of a grid
cell for items in large icon view, in pixels. Each item fits into a rectangle of this
size when arranged. These values are always greater than or equal to
WIN_SM_CXICON and WIN_SM_CYICON.
WIN_SM_CXMAXIMIZED Integer Default width of a maximized top-level window, in pixels
WIN_SM_CXMAXTRACK Integer Windows 95 only: Default maximum width of a window that has a caption and
sizing borders. The user cannot drag the window frame to a size larger than
these dimensions. A window can override these values by processing the
WM_GETMINMAXINFO message.
WIN_SM_CXMENUCHECK Integer Width of the default menu check-mark bitmap, in pixels.
WIN_SM_CXMENUSIZE Integer Width of menu bar buttons (such as multiple document (MIDI) child close), in
pixels.
WIN_SM_CXMIN Integer Minimum window width, in pixels
WIN_SM_CXMINIMIZED Integer Minimized window width, in pixels

Numara Software, Inc. and BMC Software, Inc. Confidential.


702 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


WIN_SM_CXMINSPACING Integer Minimized window spacing width; Dimensions of a grid cell for minimized
windows, in pixels. Each minimized window fits into a rectangle this size when
arranged. These values are always greater than or equal to
WIN_SM_CXMINIMIZED and WIN_SM_CYMINIMIZED.
WIN_SM_CXMINTRACK Integer Minimum tracking width of a window. The user cannot drag the window frame
to a size smaller than these dimensions. A window can override these values
by processing the WM_GETMINMAXINFO message.
WIN_SM_CXSCREEN Integer Screen width in pixels
WIN_SM_CXSIZE Integer Minimize/Maximize icon width
WIN_SM_CXSIZEFRAME Integer Window sizing frame width
WIN_SM_CXSMICON Integer Small icon width
WIN_SM_CXSMSIZE Integer Small caption button width
WIN_SM_CXVIRTUALSCREEN Integer Virtual screen width
WIN_SM_CXVSCROLL Integer Vertical scroll arrow width
WIN_SM_CYBORDER Integer Window border height
WIN_SM_CYCAPTION Integer Caption bar height
WIN_SM_CYCURSOR Integer Cursor height
WIN_SM_CYDLGFRAME Integer Dialog window frame height
WIN_SM_CYDOUBLECLK Integer Windows NT only: Width of a rectangle around the location of a first click in a
double-click sequence. The second click must occur within this rectangle for
the system to consider the two clicks a double-click.Windows 95 only: width, in
pixels, of the rectangle within which two successive mouse clicks must fall to
generate a double-click. (The two clicks must also occur within a specified
time.)
WIN_SM_CYDRAG Integer Avoid drag y tolerance
WIN_SM_CYEDGE Integer 3-D border height
WIN_SM_CYFIXEDFRAME Integer Dialog window frame height
WIN_SM_CYFRAME Integer Height of window frame for a window that can be resized.
WIN_SM_CYFULLSCREEN Integer Full screen client area height
WIN_SM_CYHSCROLL Integer Screen height in pixels
WIN_SM_CYICON Integer Icon height; this is typically 32, but can vary depending on the installed display
hardware.Windows 95 only: The LoadIcon function can only load icons of these
dimensions.
WIN_SM_CYICONSPACING Integer Vertical icon spacing. Windows NT only: Height of rectangular cell that Program
Manager uses to position tiled icons.Windows 95 only: Height of a grid cell for
items in large icon view, in pixels. Each item fits into a rectangle of this size
when arranged. These values are always greater than or equal to
WIN_SM_CXICON and WIN_SM_CYICON.
WIN_SM_CYKANJIWINDOW Integer Kanji window height
WIN_SM_CYMAXIMIZED Integer Height of maximized window
WIN_SM_CYMAXTRACK Integer Windows 95 only: Default maximum dimensions of a window that has a caption
and sizing borders. The user cannot drag the window frame to a size larger
than these dimensions. A window can override these values by processing the
WM_GETMINMAXINFO message.
WIN_SM_CYMENU Integer Menu bar height
WIN_SM_CYMENUCHECK Integer Menu check-mark height
WIN_SM_CYMENUSIZE Integer Height of menu bar buttons (such as multiple document (MIDI) child close), in
pixels.
WIN_SM_CYMIN Integer Minimum window height
WIN_SM_CYMINIMIZED Integer Minimized window height

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 54 - Predefined Variables and Constants - 703

Name Type Description


WIN_SM_CYMINSPACING Integer Minimized window spacing height; height of a grid cell for minimized windows,
in pixels. Each minimized window fits into a rectangle this size when arranged.
These values are always greater than or equal to WIN_SM_CXMINIMIZED and
WIN_SM_CYMINIMIZED.
WIN_SM_CYMINTRACK Integer Minimum tracking height of a window. The user cannot drag the window frame
to a size smaller than these dimensions. A window can override these values
by processing the WM_GETMINMAXINFO message.
WIN_SM_CYSCREEN Integer Screen height in pixels
WIN_SM_CYSIZE Integer Minimize/Maximize icon height
WIN_SM_CYSIZEFRAME Integer Window sizing frame height
WIN_SM_CYSMCAPTION Integer Small caption height
WIN_SM_CYSMICON Integer Small icon height
WIN_SM_CYSMSIZE Integer Small caption button height
WIN_SM_CYVIRTUALSCREEN Integer Virtual screen height
WIN_SM_CYVSCROLL Integer Vertical scroll arrow height
WIN_SM_CYVTHUMB Integer Vertical scroll thumb height
WIN_SM_DBCSENABLED Integer Double-Byte Char Set enabled
WIN_SM_DEBUG Integer Debug version flag
WIN_SM_MENUDROPALIGNMENT Integer Left or right menu drop
WIN_SM_MIDEASTENABLED Integer Hebrew and Arabic enabled flag
WIN_SM_MOUSEPRESENT Integer Mouse present flag
WIN_SM_MOUSEWHEELPRESENT Integer Mouse wheel present flagMouse wheel present flag
WIN_SM_NETWORK Integer Network present flag
WIN_SM_PENWINDOWS Integer Pen extensions installed
WIN_SM_REMOTESESSION Integer This system metric is used in a Terminal Services environment. If the calling
process is associated with a Terminal Services client session, the return value
is nonzero. If the calling process is associated with the Terminal Server console
session, the return value is zero. The console session is not necessarily the
physical console
WIN_SM_SAMEDISPLAYFORMAT Integer Same color format flag
WIN_SM_SECURE Integer Security present flag
WIN_SM_SHOWSOUNDS Integer Present sounds visually
WIN_SM_SLOWMACHINE Integer Slow processor flag
WIN_SM_SWAPBUTTON Integer Mouse buttons swapped flag
WIN_SM_XVIRTUALSCREEN Integer Virtual screen x origin
WIN_SM_YVIRTUALSCREEN Integer Virtual screen y origin
WIN_SS_BITMAP Integer Specifies a bitmap is to be displayed in the static control. The error code text is
the name of a bitmap (not a filename) defined elsewhere in the resource file.
The style ignores the nWidth and nHeight parameters; the control automatically
sizes itself to accommodate the bitmap.
WIN_SS_BLACKFRAME Integer Specifies a box with a frame drawn in the same color as the window frames.
This color is black in the default Windows color scheme.
WIN_SS_BLACKRECT Integer Specifies a rectangle filled with the current window frame color. This color is
black in the default Windows color scheme.
WIN_SS_CENTER Integer Specifies a simple rectangle and centers the error code text in the rectangle.
The text is formatted before it is displayed. Words that extend past the end of a
line are automatically wrapped to the beginning of the next centered line.

Numara Software, Inc. and BMC Software, Inc. Confidential.


704 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


WIN_SS_CENTERIMAGE Integer Specifies that the midpoint of a static control with the WIN_SS_BITMAP or
WIN_SS_ICON style is to remain fixed when the control is resized. The four
sides are adjusted to accommodate a new bitmap or icon.
If a static control has the WIN_SS_BITMAP style and the bitmap is smaller than
the control’s client area, the client area is filled with the color of the pixel in the
upper-left corner of the bitmap. If a static control has the WIN_SS_ICON style,
the icon does not appear to paint the client area.
WIN_SS_ENDELLIPSIS Integer Replaces part of the given string with ellipses, if necessary, so that the result
fits in the specified rectangle. WIN_SS_ENDELLIPSIS can be specified to
replace characters at the end of a string.
WIN_SS_ENHMETAFILE Integer Specifies that an enhanced metafile is to be displayed in the static control. The
given text is the name of a metafile. An enhanced metafile static control has a
fixed size; the metafile is scaled to fit the static control’s client area.
WIN_SS_ETCHEDFRAME Integer Draws the frame of the static control using the EDGE_ETCHED edge style.
WIN_SS_ETCHEDHORZ Integer Draws the top and bottom edges of the static control using the EDGE_ETCHED
edge style.
WIN_SS_ETCHEDVERT Integer Draws the left and right edges of the static control using the EDGE_ETCHED
edge style.
WIN_SS_GRAYFRAME Integer Specifies a box with a frame drawn with the same color as the screen
background (desktop). This color is gray in the default Windows color scheme.
WIN_SS_GRAYRECT Integer Specifies a rectangle filled with the current screen background color. This color
is gray in the default Windows color scheme.
WIN_SS_ICON Integer Specifies an icon displayed in the dialog box. The given text is the name of an
icon (not a filename) defined elsewhere in the resource file. The style ignores
the nWidth and nHeight parameters; the icon automatically sizes itself.
WIN_SS_LEFT Integer Specifies a simple rectangle and left-aligns the given text in the rectangle. The
text is formatted before it is displayed. Words that extend past the end of a line
are automatically wrapped to the beginning of the next left-aligned line.
WIN_SS_LEFTNOWORDWRAP Integer Specifies a simple rectangle and left-aligns the given text in the rectangle. Tabs
are expanded but words are not wrapped. Text that extends past the end of a
line is clipped.
WIN_SS_NOPREFIX Integer Prevents interpretation of any ampersand (&) characters in the control’s text as
accelerator prefix characters. These are displayed with the ampersand
removed and the next character in the string underlined. This static control
style can be included with any of the defined static controls.
An application can combine WIN_SS_NOPREFIX with other styles by using the
bitwise OR (|) operator. This can be useful when file names or other strings
that can contain an ampersand (&) must be displayed in a static control in a
dialog box.
WIN_SS_NOTIFY Integer Sends the parent window STN_CLICKED, STN_DBLCLK, STN_DISABLE, and
STN_ENABLE notification messages when the user clicks or double-clicks the
control.
WIN_SS_OWNERDRAW Integer Specifies that the owner of the static control is responsible for drawing the
control. The owner window receives a WM_DRAWITEM message whenever the
control needs to be drawn.
WIN_SS_PATHELLIPSIS Integer Replaces part of the given string with ellipses, if necessary, so that the result
fits in the specified rectangle. WIN_SS_PATHELLIPSIS can be specified to
replace characters in the middle of a string. If the string contains backslash (\)
characters, WIN_SS_PATHELLIPSIS preserves as much of the text after the last
backslash as possible.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 54 - Predefined Variables and Constants - 705

Name Type Description


WIN_SS_REALSIZECONTROL Integer Windows XP Adjusts the bitmap to fit the size of the static control. For example,
changing the locale can change the system font, and thus controls might be
resized. If a static control had a bitmap, the bitmap would no longer fit the
control. This style bit dictates automatic redimensioning of bitmaps to fit their
controls.
If WIN_SS_CENTERIMAGE is specified, the bitmap or icon is centered (and
clipped if needed). If WIN_SS_CENTERIMAGE is not specified, the bitmap or
icon is stretched or shrunk.
Note that the redimensioning in the two axes are independent, and the result
might have a changed aspect ratio.
WIN_SS_REALSIZEIMAGE Integer Prevents a static icon or bitmap control (that is, static controls that have the
WIN_SS_ICON or WIN_SS_BITMAP style) from being resized as it is loaded or
drawn. If the icon or bitmap os larger than the destination area, the image is
clipped.
WIN_SS_RIGHT Integer Specifies a simple rectangle and right-aligns the given text in the rectangle. The
text is formatted before it is displayed. Words that extend past the end of a line
are automatically wrapped to the beginning of the next right-aligned line.
WIN_SS_RIGHTJUST Integer Specifies that the lower right corner of a static control with the WIN_SS_ICON
or WIN_SS_BITMAP style is to remain fixed with the control is resized. Only the
top and left sides are adjusted to accommodate a new bitmap or icon.
WIN_SS_SIMPLE Integer Specifies a simple rectangle and displays a single line of left-aligned text in the
rectangle. The text line cannot be shortened or altered in any way. Also, if the
control is dizabled, the control does not gray its text.
WIN_SS_SUNKEN Integer Draws a half-sunken order around a static control.
WIN_SS_WHITEFRAME Integer Specifies a box with a frame drawn with the same color as the window
backgrounds. This color is white in the default Windows color scheme.
WIN_SS_WHITERECT Integer Specifies a rectangle filled with the current window background color. This
color is white in the default Windows color scheme.
WIN_SS_WORDELLIPSIS Integer Truncates text that does not fit and adds ellipses.
WIN_WS_BORDER Integer Creates a window that has a thin-line border.
WIN_WS_CAPTION Integer Creates a window that has a title bar (includes the WIN_WS_BORDER style).
WIN_WS_CHILD Integer Creates a child window. This style cannot be used with the WIN_WS_POPUP
style.
WIN_WS_CHILDWINDOW Integer Same as the WIN_WS_CHILD style.
WIN_WS_CLIPCHILDREN Integer Excludes the area occupied by child windows when drawing occurs within the
parent window. This style is used when creating the parent window.
WIN_WS_CLIPSIBLINGS Integer Clips child windows relative to each other; that is, when a particular child
window receives a WM_PAINT message, the WIN_WS_CLIPSIBLINGS style
clips all other overlapping child windows out of the region of the child window
to be updated. If WIN_WS_CLIPSIBLINGS is not specified and child windows
overlap, it is possible, when drawing within the client area of a child window, to
draw within the client area of a neighboring child window.
WIN_WS_DISABLED Integer Creates a window that is initially dizabled. A dizabled window cannot receive
input from the user.
WIN_WS_DLGFRAME Integer Creates a window that has a border of a style typically used with dialog boxes.
A window with this style cannot have a title bar.
WIN_WS_EX_ACCEPTFILES Integer Specifies that a window created with this style accepts drag-drop files.
WIN_WS_EX_APPWINDOW Integer Forces a top-level window onto the task bar when the window is visible.
WIN_WS_EX_CLIENTEDGE Integer Specifies that a window has a border with a sunken edge.

Numara Software, Inc. and BMC Software, Inc. Confidential.


706 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


WIN_WS_EX_CONTEXTHELP Integer Includes a question mark in the title bar of the window. When the user clicks
the question mark, the cursor changes to a question mark with a pointer. If the
user then clicks a child window, the child receives a WM_HELP message. The
child window should pass the message to the parent window procedure, which
should call the WinHelp function using the HELP_WM_HELP command. The
Help application displays a pop-up window that typically contains help for the
child window. WIN_WS_EX_CONTEXTHELP cannot be used with the
WIN_WS_MAXIMIZEBOX or WIN_WS_MINIMIZEBOX styles.
WIN_WS_EX_CONTROLPARENT Integer The window itself contains child windows that should take part in dialog box
navigation. If this style is specified, the dialog manager recourses into children
of this window when performing navigation operations such as handling the
TAB key, an arrow key, or a keyboard mnemonic.
WIN_WS_EX_DLGMODALFRAME Integer Creates a window that has a double border; the window can, optionally, be
created with a title bar by specifying the WIN_WS_CAPTION style in the dwStyle
parameter.
WIN_WS_EX_LAYOUTRTL Integer Creates a window whose horizontal origin is on the right edge. Increasing
horizontal values advance to the left.
WIN_WS_EX_LEFT Integer Creates a window that has generic left-aligned properties. This is the default.
WIN_WS_EX_LEFTscroll bar Integer Draws the vertical scroll bar on the left side of the control.
WIN_WS_EX_LTRREADING Integer The window text is displayed using left-to-right reading-order properties. This
is the default.
WIN_WS_EX_MDICHILD Integer Creates a multiple-document interface (MDI) child window.
WIN_WS_EX_NOINHERITLAYOUT Integer A window created with this style does not pass its window layout to its child
windows.
WIN_WS_EX_NOPARENTNOTIFY Integer Specifies that a child window created with this style does not send the
WM_PARENTNOTIFY message to its parent window when it is created or
destroyed.
WIN_WS_EX_OVERLAPPEDWINDOW Integer Combines the WIN_WS_EX_CLIENTEDGE and WIN_WS_EX_WINDOWEDGE
styles.
WIN_WS_EX_PALETTEWINDOW Integer Combines the WIN_WS_EX_WINDOWEDGE, WIN_WS_EX_TOOLWINDOW, and
WIN_WS_EX_TOPMOST styles.
WIN_WS_EX_RIGHT Integer The window has generic "right-aligned" properties. This depends on the
window class. Using the WIN_WS_EX_RIGHT style for static or edit controls
has the same effect as using the WIN_SS_RIGHT or WIN_ES_RIGHT style.
Using this style with button controls has the same effect as using
WIN_BS_RIGHT and WIN_BS_RIGHTBUTTON styles.
WIN_WS_EX_RIGHTscroll bar Integer Draws the vertical scroll bar on the right side of the client area. This is the
default.
WIN_WS_EX_RTLREADING Integer The window text is displayed using right-to-left reading-order properties.
WIN_WS_EX_STATICEDGE Integer Creates a window with a three-dimensional border style intended to be used for
items that do not accept user input.
WIN_WS_EX_TOOLWINDOW Integer Creates a tool window; that is, a window intended to be used as a floating tool
bar. A tool window has a title bar that is shorter than a normal title bar, and the
window title is drawn using a smaller font. A tool window does not appear in the
task bar or in the dialog that appears when the user presses ALT+TAB. If a tool
window has a system menu, its icon is not displayed on the title bar. However,
you can display the system menu by right-clicking or by typing ALT+SPACE.
WIN_WS_EX_TOPMOST Integer Specifies that a window created with this style should be placed above all non-
topmost windows and should stay above them, even when the window is
deactivated.
WIN_WS_EX_TRANSPARENT Integer Specifies that a window created with this style should not be painted until
siblings beneath the window (that were created by the same thread) have been
painted. The window appears transparent because the bits of underlying sibling
windows have already been painted.
WIN_WS_EX_WINDOWEDGE Integer Specifies that a window has a border with a raised edge.

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chapter 54 - Predefined Variables and Constants - 707

Name Type Description


WIN_WS_GROUP Integer Specifies the first control of a group of controls. The group consists of this first
control and all controls defined after it, up to the next control with the
WIN_WS_GROUP style. The first control in each group usually has the
WIN_WS_TABSTOP style so that the user can move from group to group. The
user can subsequently change the keyboard focus from one control in the
group to the next control in the group by using the direction keys.
WIN_WS_HSCROLL Integer Creates a window that has a horizontal scroll bar.
WIN_WS_ICONIC Integer Creates a window that is initially minimized. Same as the WIN_WS_MINIMIZE
style.
WIN_WS_MAXIMIZE Integer Creates a window that is initially maximized.
WIN_WS_MAXIMIZEBOX Integer Creates a window that has a Maximize button. Cannot be combined with the
WS_EX_CONTEXTHELP style. The WIN_WS_SYSMENU style must also be
specified.
WIN_WS_MINIMIZE Integer Creates a window that is initially minimized. Same as the WIN_WS_ICONIC
style.
WIN_WS_MINIMIZEBOX Integer Creates a window that has a Minimize button. Cannot be combined with the
WS_EX_CONTEXTHELP style. The WIN_WS_SYSMENU style must also be
specified.
WIN_WS_OVERLAPPED Integer Creates an overlapped window. An overlapped window has a title bar and a
border. Same as the WIN_WS_TILED style.
WIN_WS_OVERLAPPEDWINDOW Integer Creates an overlapped window with the WIN_WS_OVERLAPPED,
WIN_WS_CAPTION, WIN_WS_SYSMENU, WIN_WS_THICKFRAME,
WIN_WS_MINIMIZEBOX, and WIN_WS_MAXIMIZEBOX styles. Same as the
WIN_WS_TILEDWINDOW style.
WIN_WS_POPUP Integer Creates a pop-up window. This style cannot be used with the WIN_WS_CHILD
style.
WIN_WS_POPUPWINDOW Integer Creates a pop-up window with WIN_WS_BORDER, WIN_WS_POPUP, and
WIN_WS_SYSMENU styles. The WIN_WS_CAPTION and
WIN_WS_POPUPWINDOW styles must be combined to make the window menu
visible.
WIN_WS_SIZEBOX Integer Creates a window that has a sizing border. Same as the
WIN_WS_THICKFRAME style.
WIN_WS_SYSMENU Integer Creates a window that has a window-menu on its title bar. The
WIN_WS_CAPTION style must also be specified.
WIN_WS_TABSTOP Integer Specifies a control that can receive the keyboard focus when the user presses
the TAB key. Pressing the TAB key changes the keyboard focus to the next
control with the WIN_WS_TABSTOP style.
WIN_WS_THICKFRAME Integer Creates a window that has a sizing border. Same as the WIN_WS_SIZEBOX
style.
WIN_WS_TILED Integer Creates an overlapped window. An overlapped window has a title bar and a
border. Same as the WIN_WS_OVERLAPPED style.
WIN_WS_TILEDWINDOW Integer Creates an overlapped window with the WIN_WS_OVERLAPPED,
WIN_WS_CAPTION, WIN_WS_SYSMENU, WIN_WS_THICKFRAME,
WIN_WS_MINIMIZEBOX, and WIN_WS_MAXIMIZEBOX styles. Same as the
WIN_WS_OVERLAPPEDWINDOW style.
WIN_WS_VISIBLE Integer Creates a window that is initially visible.
WIN_WS_VSCROLL Integer Creates a window that has a vertical scroll bar.
WNET_SRVTYPE_AFP Integer The resource found in the domain is of type
WNET_SRVTYPE_ALL Integer The resource found in the domain is of type
WNET_SRVTYPE_BACKUP_BROWSER Integer The resource found in the domain is of type
WNET_SRVTYPE_CLUSTER_NT Integer The resource found in the domain is of type
WNET_SRVTYPE_CLUSTER_VS_NT Integer The resource found in the domain is of type
WNET_SRVTYPE_DIALIN_SERVER Integer The resource found in the domain is of type Dial-in Server
WNET_SRVTYPE_DOMAIN_BAKCTRL Integer The resource found in the domain is of type

Numara Software, Inc. and BMC Software, Inc. Confidential.


708 - BMC FootPrints Asset Core - Chilli Reference

Name Type Description


WNET_SRVTYPE_DOMAIN_CTRL Integer The resource found in the domain is of type Domain Control Server
WNET_SRVTYPE_DOMAIN_ENUM Integer The resource found in the domain is of type
WNET_SRVTYPE_DOMAIN_MASTER Integer The resource found in the domain is of type Domain Master
WNET_SRVTYPE_DOMAIN_MEMBER Integer The resource found in the domain is of type
WNET_SRVTYPE_LOCAL_LIST_ONLY Integer The resource found in the domain is of type
WNET_SRVTYPE_MASTER_BROWSER Integer The resource found in the domain is of type
WNET_SRVTYPE_NOVELL Integer The resource found in the domain is of type Novell Server
WNET_SRVTYPE_NT Integer The resource found in the domain is of type NT workstation
WNET_SRVTYPE_POTENTIAL_BROWSER Integer The resource found in the domain is of type
WNET_SRVTYPE_PRINTQ_SERVER Integer The resource found in the domain is of type Print Server
WNET_SRVTYPE_SERVER Integer The resource found in the domain is of type server
WNET_SRVTYPE_SERVER_MFPN Integer The resource found in the domain is of type
WNET_SRVTYPE_SERVER_NT Integer The resource found in the domain is of type NT Server
WNET_SRVTYPE_SQLSERVER Integer The resource found in the domain is of type SQL Server
WNET_SRVTYPE_TERMINALSERVER Integer The resource found in the domain is of type
WNET_SRVTYPE_TIME_SOURCE Integer The resource found in the domain is of type
WNET_SRVTYPE_WFW Integer The resource found in the domain is of type
WNET_SRVTYPE_WINDOWS Integer The resource found in the domain is of type
WNET_SRVTYPE_WORKSTATION Integer The resource found in the domain is of type workstation
WNET_SRVTYPE_XENIX_SERVER Integer The resource found in the domain is of type Xenix Server

Numara Software, Inc. and BMC Software, Inc. Confidential.


Chilli Function Group Modules

This following table displays a list of all existing Chilli function modules and for which platforms they are
applicable:

Function Group Include File Windows UNIX Mac


Vista/
95/98 NT 2000 XP 2003 2008*
7
Archive archive.chx
archive.so
BCM agent mtxagent.ch
x
mtxagent.so
CSV File csv.chx
csv.so
cURL curl.chx
curl.so
DBM Database dbm.chx
dbm.so
Directory core

Disk disk.chx
disk.so
Encryption md5.chx
md5.so
Event Log ntevent.chx

File core

FTP ftp.chx
ftp.so
Gif-Image gif.chx
Manipulation gif.so
HTML File html.chx
html.so
INI Format File inifile.chx
Manipulation inifile.so
LDAP ldap.chx
ldap.so
Message Dialog message.ch
Box x
Miscellaneous core

Network network.chx
network.so
ODBC odbc.chx
odbc.so

Numara Software, Inc. and BMC Software, Inc. Confidential.


710 - BMC FootPrints Asset Core - Chilli Reference

Function Group Include File Windows UNIX Mac


Vista/
95/98 NT 2000 XP 2003 2008*
7
Path core

Performance ntper.chx
Monitoring
Process process.chx
process.so
Progress Dialog progress.ch
Box x
Registry registry.chx

SDBM Database sdbmconfig.


chx
sdbmconfig.
so
Security Policy sdbmconfig.
chx
sdbmconfig.
so
Services ntservice.ch
x
Shortcut shortcut.chx

SMB smb.chx
smb.so
SMTP smtp.chx
smtp.so
SNMP snmp.chx
snmp.so
SQL gensql.chx
gensql.so
SSH ssh.chx
ssh.so
String core

Time time.chx
time.so
UNIX Services unixservice.
so
User user.chx
user.so
Variables core

Windowing window.chx

WMI wmi.chx

WNet wnet.chx

XML/XSLT xml.chx
xml.so
* Depending on the installation.

Numara Software, Inc. and BMC Software, Inc. Confidential.


*458309*

45828309

You might also like