Professional Documents
Culture Documents
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.
Organization
The Chilli Reference is a comprehensive guide to the Chilli language and is divided into the following sections:
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
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.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.
*/
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.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.
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 (^=)
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:
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.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.
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"
ptrChar = szTmp
"%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
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.
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 ...]
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
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.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.
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]
x[4] = 10
int i,j
string szTmp
char ptrChar[]
szTmp = "Hello"
ptrChar = szTmp
for (i=1; i<=StrLen (szTmp); i+=1)
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.
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.
endstruct
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.
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”
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.
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
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.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:
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:
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:
Long Command
cmd Description
Format
-v --version Show Chilli executable version string.
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”
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.
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
Examples
Constantpi3.14159
ConstantLitPerGal.26425
Constantcount12
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
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.
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.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.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”
“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
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.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.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
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:
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.
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.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
...
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.
• 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.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
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
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.
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 ()
Employee EmployeeList []
// 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
Endfor
Endwhile
XMLClose (hXMLFile)
Endproc
The xml file to be read has the following contents:
<?xml version="1.0" encoding="ISO-8859-1"?>
<EMPLIST>
<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
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.
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.
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
proc main ()
string Name
Name=Dog
GetName (Name)
print (Name)
endproc
Printed Output
Cat
string LogFile
LogFile = “C:\\temp\\logfile.txt”
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)
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)
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
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.
§ 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.
• 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
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)
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.
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.
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:
Function OS Description
ArchiveAdd Add a file to 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
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
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 ()
file = 'install.chl'
handle = ArchiveOpen ('C:\package.pkg')
if (ErrCode != 0)
Print (LogFile, 'The archive ' + file + ' is not valid.\r\n')
exit
endif
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.
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’)
if (ErrCode != 0)
Print (Logfile, ’ The file ’ + filename + ’ has not been found.\r\n’)
endif
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
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
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.
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 ()
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
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
count = 1
while (count <= limit)
path = ArchiveGetPath (handle, count)
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
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.
Example:
The following example gets the size of the first file contained in the archive.
proc main ()
archivehandle handle
int size
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
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.
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)
PackageFile = 'C:\package.pkg'
handle = ArchiveOpen (PackageFile)
if (ErrCode != 0)
Print (LogFile, 'The archive ' + PackageFile + ' is not valid.\r\n')
exit
endif
count = 1
while (count <= limit)
path = ArchiveGetPath (handle, count)
ArchiveExtract (handle, count, path)
count = count+1
wend
ArchiveClose (handle)
endproc
proc main ()
endproc
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.
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
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.
InvObjInstAttr
The InvObjInstAttr structure provides information about the inventory object.
Elements:
InvObjInst
The InvObjInst structure contains information about the inventory object instance.
Elements:
InvObjTypeAttr
The InvObjTypeAttr structure contains the information about the inventory object type attributes.
Elements:
InvObjType
The InvObjType structure contains the information about the inventory object type and is required by the
InventoryAddObjType function.
Elements:
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
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
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
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 ()
string szName
for (i=1; i<=iCount; i+=1)
szName = ContainerGetNextName (contParams, szName)
print (szName + ":\n")
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 ()
int i, iCount
iCount = ContainerCountValues (contResult, "InstanceName")
string szInstances[]
ContainerDestroy (contResult)
return szInstances
endproc
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 ()
int i, iCount
iCount = ContainerCountValues (contResult, "Values")
OpRuleEntry ruleList[]
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.
proc main ()
OpRuleEntry[] GetOpRuleList ()
int i, iCount
iCount = ContainerCountValues (contResult, "Values")
OpRuleEntry ruleList[]
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 ()
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
ContainerHandle contValues
contValues = ContainerGetContainer (contResult, "Values", 1)
ContainerDestroy (contResult)
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 ()
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
ContainerHandle contValues
contValues = ContainerGetContainer (contResult, "Values", 1)
ContainerDestroy (contResult)
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 ()
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.
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 ()
int i, iCount
iCount = ContainerCountValues (contResult, "InstanceName")
string szInstances[]
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.
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 ()
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.
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 ()
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.
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 ()
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.
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 ()
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)
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 ()
contValues = ContainerCreate ()
ContainerSetContainer (contRequest, "Values", 1, contValues)
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
endstruct
ContainerHandle contValues
contValues = ContainerGetContainer (contResult, "Values", 1)
ContainerDestroy (contResult)
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
ContainerHandle contValues
contValues = ContainerGetContainer (contResult, "Values", 1)
ContainerDestroy (contResult)
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.
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 ()
contValues = ContainerCreate ()
ContainerSetContainer (contRequest, "Values", 1, contValues)
ContainerDestroy (contResult)
return true
endproc
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.
CsvRow
The CsvRow structure represents all cells in a CSV file.
Elements:
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.
Elements:
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.
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.
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.
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).
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.
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
CurlGetInfo Get string type information about the previously performed transfer
Function OS Description
CurlResetFormFields Clear the list of form fields
CurlSendBufferAndRecv Send the buffer content to the server and store the response in the internal buffer
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.
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"
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"
CurlHandle hHttp
hHttp = CurlCreate ()
# 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
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.
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.
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.
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.
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.
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.
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.
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)
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.
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)
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
if (lResult != 0)
LogPrint (Logger, "ExecuteCmd", "An error occurred. CODE ["+ lResult +"], DESCRIPTION ["+
CurlTranslateErrorCode (hTelnet, lResult) +"] for [telnet://"+ szIpAddress +"].")
endif
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.
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)
if (lResult != 0)
// ...
endif
if (lResult != 0)
// ...
endif
CurlResetHeaderFields (hHttp)
if (lHttpReturnCode == 200)
strWholeFile = FileToString (strFileName, true)
// ...
else
// ...
endif
CurlDestroy (hHttp)
return 0
endproc
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.
Name Description
ERR_DBMBADFILE Unable to open/create DBM file
ERR_DBMBADHANDLE Invalid DBM handle
DBM
The DBM data type is a reference to the handle of an DBM file.
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
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
DbmNextKey Reads the value of the ‘next’ key from 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
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
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
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
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.
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
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
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
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
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.
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"
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"
DirDelete ("C:\\temp\\newtestdir")
endproc
DirExists
Check to see if a directory exists.
Syntax:
Bool DirFind (String DirectoryName)
string stringDir
stringDir = "C:\\temp\\testdir"
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"
DirDelete ("C:\\temp\\newtestdir")
endproc
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
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)
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 ()
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
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
DiskGetType Determine whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network
drive
DiskNetAdd Mount a redirected network drive
DiskExists
Check to see if a disk letter exists and is mapped to a valid drive.
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"
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 ()
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.
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"
endproc
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"
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:
DiskNetAdd
Redirect a drive letter to a network drive using the standard Windows networking software.
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.
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.
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
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
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
proc main ()
DiskFunctions ()
endproc
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.
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
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
EventGetFileName Get the name of an event log file given its index
Function OS Description
EventGetFilePath Get the full path of an event log file given its index
EventGetInfo Get all available information for an event in an event log file
EventGetMaxSize Get the maximum allowable size for an event log file
EventGetOldest Get the index of the oldest event entry in a log file
EventGetUser Get the login name of the user who was logged on when an event was generated
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
endproc
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
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
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 ()
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 ()
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 ()
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 ()
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 ()
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.
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 ()
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.
proc main ()
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 ()
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.
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 ()
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 ()
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.
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 ()
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 ()
endproc
EventGetTimestamp
Get the timestamp for an event in an event log file.
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
endproc
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 ()
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 ()
if (count != 0)
year = EventGetYear (1, index)
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 ()
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)
endif
endproc
proc main ()
NTEventLogFunctions ()
endproc
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.
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
Name Description
ERR_PASSWORD Server rejected user password
ERR_PUTFILE Failed to write file to destination
ERR_SHARENAME Server rejected share name
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.
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:
Example 3:
The following table shows different examples for the use of the Directory and Filename parameters.
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
FileConvertToUTF8 Convert a file which has the specified CodePage into UTF8
Function OS Description
FileDelete Delete a single file
FileFindPcre Open a binary file type with the supplied file path
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 ()
compressfile = "c:\\temp\\file.zip"
oldfile = "c:\\temp\\file1.txt"
newfile = "c:\\temp\\file2.txt"
FileCompress (oldfile, compressfile)
FileDecompress (compressfile, newfile)
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.
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 ()
compressfile = "c:\\temp\\file.zip"
oldfile = "c:\\temp\\file1.txt"
newfile = "c:\\temp\\file2.txt"
FileCompress (oldfile, compressfile)
FileDecompress (compressfile, newfile)
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)
endproc
endproc
proc main ()
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)
endproc
endproc
proc main ()
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.
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 ()
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 ()
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 ()
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.
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 ()
compressfile = "c:\\temp\\file.zip"
oldfile = "c:\\temp\\file1.txt"
newfile = "c:\\temp\\file2.txt"
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 + '\'
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 ():
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)
FileGetLineCount
Get the total number of lines in a file.
Syntax:
Int FileGetLineCount (String FilePath)
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")
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.
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
Function OS Description
FileExists Check for existence of a file
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
FileGetVersionValue Get the named file version resource value in the given language
Function OS Description
FileHasVersionInfo Check whether a given file exists and has some version information in it
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.
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
while (1)
szFileName = FileFindNext (ptrFileInfo)
if (szFileName == "")
break
else
print (szFileName + "\n")
endif
endwhile
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
while (1)
szFileName = FileFindNext (ptrFileInfo)
if (szFileName == "")
break
else
print (szFileName + "\n")
endif
endwhile
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
while (1)
szFileName = FileFindNext (ptrFileInfo)
if (szFileName == "")
break
else
print (szFileName + "\n")
endif
endwhile
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.
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:
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)
if (szExt == "")
return
endif
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.
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
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
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 ()
driveletter = 'C'
Package = 'package.pkg'
NewPkgPath = 'C:\temp\package_new.pkg'
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.
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 ()
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.
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 ()
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;
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:
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
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');
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
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.
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"
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"
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:
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"
endproc
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.
Function OS Description
FileAddLine Add a line of text to the end of a file
FileGetPath Return the path of the file associated with a given handle
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.
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 ()
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 ()
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.
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 ()
stringFile = 'c:\temp\file1.txt'
line = "new text line"
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"
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.
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 ()
stringFile = 'c:\temp\file1.txt'
line = "new text line"
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
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.
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"
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.
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 ()
stringFile = 'c:\temp\file1.txt'
line = "new text line"
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 ()
stringFile = 'c:\temp\file1.txt'
line = "new text line"
texthandle = TextFileOpen (stringfile
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.
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
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"
FileTextClose (texthandle)
endif
endproc
Function OS Description
FileGetDay Get the day part 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.
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 ()
endproc
17.8 Example
The following code sample illustrates the file functions.
proc FileFunctions ()
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
if (newline == line)
FileDeleteLine (stringFile, 1)
endif
endif
endif
FileIniClose (inihandle)
FileDeleteEntry (stringFile, section10, entry)
FileDeleteSection (stringFile, section1)
endif
endif
endproc
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.
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
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
FtpGetServerStatus Returns the last known status from the FTP server
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):
FtpHandle hFtp
hFtp = FtpConnect (szIpAddress, iPort)
if (hFtp == 0)
Print ("Failed to connect to ["+ szIpAddress +"] on port ["+ iPort +"]. Exiting...")
return
endif
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
if (hFtp == 0)
Print ("Failed to connect to ["+ szIpAddress +"] on port ["+ iPort +"]. Exiting...")
return
endif
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
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
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)
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")
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
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
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)
endproc
proc main ()
//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.
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 ()
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.
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 ()
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.
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
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)
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 ()
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
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
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.
/***********************************************************************
FtpListDirectory
Recurses through a directory structure and prints the files it finds
at each level.
***********************************************************************/
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", "")
DoFtpTests (ftp)
FtpDisconnect (ftp)
endproc
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:
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.
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:
GifPoint
The GifPoint structure represents a point in the coordinate space of a Gif image.
This structure is used by the polygon functions.
Elements:
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:
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
Function OS Description
GifDrawText Draw a text string in 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
GifSaveImage Save the image associated with the supplied handle to a file
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.
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 ()
// 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)
// Fill the button shape in the middle. Being flood fill, this
// ends up filling the whole button.
endfor
GifDestroyImage (ptrImage)
endproc
GifCreateImage
Create a Gif image.
Syntax:
GifImage GifCreateImage (Int Length, Int Height)
ImgWidth = 250
ImgHeight = 250
ptrImage = GifCreateImage (ImgWidth, ImgHeight)
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 ()
ImgWidth = 250
ImgHeight = 250
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 ()
// 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)
// Fill the button shape in the middle. Being flood fill, this
// ends up filling the whole button.
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.
ImgWidth = 250
ImgHeight = 250
ptrImage = GifCreateImage (ImgWidth, ImgHeight)
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.
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 ()
// 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)
// Fill the button shape in the middle. Being flood fill, this
// ends up filling the whole button.
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.
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 ()
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)
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 ()
ImgWidth = 250
ImgHeight = 250
ptrImage = GifCreateImage (ImgWidth, ImgHeight)
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.
Example:
The following example script writes 'Start' on a button image.
proc main ()
Height = 50
Width = 150
ptrImage = GifCreateImage (Width, Height)
Foreground = GifAllocateColour (ptrImage, 255, 255, 255)
ButtonFont = GIF_FONTSMALL
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 ()
Height = 50
Width = 150
ptrImage = GifCreateImage (Width, Height)
// Fill upper half in background color green with border color red.
GifFillToBorder (ptrImage, 5, 2, Background, Color)
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 ()
// 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)
// Fill the button shape in the middle. Being flood fill, this
// ends up filling the whole button.
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.
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.
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 ()
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)
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:
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 ()
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)
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.
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.
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 ()
ImgWidth = 250
ImgHeight = 250
ptrImage = GifCreateImage (ImgWidth, ImgHeight)
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.
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.
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 ()
Width = 150
Height = 50
ptrImage = GifCreateImage (Width, Height)
TransIndex = GifAllocateColour (ptrImage, 1, 2, 3)
GifDestroyImage (ptrImage)
endproc
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.
HtmlTag
The HtmlTag structure represents an HTML tag in a file.
Elements:
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:
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:
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
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")
endproc
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.
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
Function OS Description
FileDeleteSection Delete an entire section in an INI format file
FileGetEntryName Get the name of an entry in a section in an INI file using an integer index
FileGetSectionName Get the name of a section in an INI file using an integer index
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"
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"
endproc
FileGetEntryCount
Get the number of entries in a section of an INI format file.
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"
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 (FileGetSectionCount (inihandle) != 0)
section1 = FileGetSectionName (inihandle, 1)
section10 = FileGetSectionName (inihandle, 10)
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"
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 (FileGetSectionCount (inihandle) != 0)
section1 = FileGetSectionName (inihandle, 1)
section10 = FileGetSectionName (inihandle, 10)
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 (FileGetLineCount (inihandle)!= 0)
if (FileGetSectionCount (inihandle) != 0)
section1 = FileGetSectionName (inihandle, 1)
section10 = FileGetSectionName (inihandle, 10)
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"
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 (FileGetSectionCount (inihandle) != 0)
section1 = FileGetSectionName (inihandle, 1)
section10 = FileGetSectionName (inihandle, 10)
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"
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 (FileGetSectionCount (inihandle) != 0)
section1 = FileGetSectionName (inihandle, 1)
section10 = FileGetSectionName (inihandle, 10)
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.
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.
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 (FileGetLineCount (inihandle)!= 0)
if (FileGetSectionCount (inihandle) != 0)
section1 = FileGetSectionName (inihandle, 1)
section10 = FileGetSectionName (inihandle, 10)
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
if (FileGetLineCount (inihandle)!= 0)
if (FileGetSectionCount (inihandle) != 0)
section1 = FileGetSectionName (inihandle, 1)
section10 = FileGetSectionName (inihandle, 10)
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"
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.
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 ()
if (iCPiniFind == 1)
FileSetAttr (CPDir + '\chilli.tmp', 32)
FileRename (CPDir + '\chilli.tmp', CPDir + '\chilli.ini')
endif
endproc
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.
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.
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
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
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
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.
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.
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.
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.
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:
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.
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"
//*******************************************************************
// DoSearch
//*******************************************************************
string szAttrs[2]
int count, i, j, k;
string szValue, szValues[]
LdapMessageHandle msgg, msg[]
szAttrs[1] = "sn"
szAttrs[2] = "*"
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
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"
iError = ErrCode
if (ErrCode != ERR_SUCCESS)
print ("modifying failed: " + iError + ", " + GetErrorName (iError) + ", " +
GetErrorText (iError))
exit (0)
else
String ADD_DN
ADD_DN = "CN=lionel,CN=Users,DC=support,DC=sophia,DC=metrixsystems,DC=com"
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"
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"
//*******************************************************************
// DoSearch
//*******************************************************************
string szAttrs[2]
szAttrs[1] = "sn"
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
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
string szFilter
szFilter = "(objectclass=*)"
LdapMod LdapValues[1]
LdapValues[1].Operation = LDAP_MOD_REPLACE
LdapValues[1].Attribute = "description"
LdapValues[1].Values <<= "Just another guy"
LdapModify (ldap, MODIFY_DN, LdapValues)
LdapUnbind (ldap);
endproc
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.
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
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.
MD5Context ptrMD5Context
ptrMD5Context = MD5Start ()
MD5Update (ptrMD5Context, "my string to hash")
print ("The corresponding hashed string is " + MD5End (ptrMD5Context))
endproc
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.
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.
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.
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.
Dialog
The Dialog data type is a reference to the handle of a message dialog box.
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
MessageSetButton Set the text on one of the buttons 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 ()
While (1)
FileName = FileFindNext (PtrFileInfo)
if FileName == ""
Break
else
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)
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.
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
endproc
Example 2:
This example script creates a dialog box with one button and a warning message.
proc main ()
dialog iHandle
int iBoot
if (iBoot == 1)
MessageBox ("Warning", "Your PC is restarted now", "OK")
Reboot ()
endif
endproc
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.
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
CompileResult
The CompileResult structure contains the details of all generated compilation errors.
Elements:
IpTable
The IpTable structure contains the details of IpTable firewall rule of a UNIX device.
Elements:
OpenedPort
The OpenedPort structure contains the details of the list of open TCP or UDP port found on a device.
Elements:
SharedResource
The SharedResource structure contains the details of the shared resources found.
Elements:
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:
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:
25.5 Functions
Following you find the list of all functions of the Miscellaneous function module:
Function OS Description
AddNetworkShare Add a network share
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
GetUnixSystemInfo Retrieve information about the UNIX operating system on the local device
GetWindowsSystemInfo Retrieve information about the Windows operating system on the local device
HostNameToIPAddress Return the IP address string in the dotted notation of a specified host machine
Function OS Description
Reboot Reboot the system
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.
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=
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 ()
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 ()
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
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)
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.
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)
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
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 ()
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 ()
endproc
GetSystemDefaultLangID
Return the language ID of the device.
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)
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)
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 ()
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 ()
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.
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 ()
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 ()
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.
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”
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 ()
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.
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
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.
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 ()
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.
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 ()
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.
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 ()
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
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.
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
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_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_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_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_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
Constant Description
SQL_VARBINARY Variable length binary data of maximum length n; the maximum is set by the user
Name Description
ERR_ODBC Error ODBC
ERR_CONNECTION ODBCConnectionHandle error
ERR_STATEMENT ODBCStatementHandle error
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.
ODBCDate
The ODBCDate structure represents a list of date values conforming to the rules of the Gregorian calendar.
Elements:
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:
ODBCDataSource
The ODBCDataSource structure represents a list of available data source names and their descriptions.
Elements:
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
Function OS Description
ODBCConnect Open an ODBC connection
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.
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.
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".
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.
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.
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_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.
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.
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_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.
Function OS Description
ODBCCloseCursor Close a cursor
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
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
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.
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.
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_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.
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_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.
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)
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)
Function OS Description
ODBCGetBoolean Get a column's value as a boolean
Function OS Description
ODBCGetDouble Get a column's value as a double
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.
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.
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.
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.
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.
//*******************************************************************
if (TypeId == SQL_CHAR)
return "SQL_CHAR"
endif
return "???"
endproc
//*******************************************************************
// DumpResult
// Given a resultset handle, prints the contents.
//*******************************************************************
int i, j, iCols;
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))
else
print ("????")
endif
if (j < iCols)
print (", ")
endif
endfor
print ("\n")
endwhile
endproc
int i, j;
string szTables[], szColumns[];
endproc
proc main ()
ListDataSources ()
ODBCConnectionHandle ConnHandle
ConnHandle = ODBCConnect ("SQL Server - Northwind", "batman", "")
print ("Connected!\r\n")
ODBCStatementHandle StatementHandle
StatementHandle = ODBCCreateStatement (ConnHandle)
ODBCDisconnect (ConnHandle)
endproc
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.
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
CompletePath
Convert a relative path into a full path.
Syntax:
String CompletePath (string Path)
Path is the relative path to be completed.
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 ()
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 ()
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 ()
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"
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"
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"
endproc
PathGetFilename
Get the filename part of a path.
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"
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"
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.
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"
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 ()
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.
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 ()
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
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.
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.
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
Function OS Description
NetExtractPortCount Return the number of ports in the specified range
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)
return 0
endproc
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 ()
szOpenedPortRange = "1-4,10-12,15"
vecPort = NetExtractPortRange (szOpenedPortRange)
if (iTotal == 0)
Print ("Failed to get the port range.")
return 1
endif
return 0
endproc
NetGetDnsName
Get the DNS name of the specified device.
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 ()
szIpAddress = "87.248.113.14"
Print ("DNS name for [" + szIpAddress + "] is [" + szDnsName + "]")
return 0
endproc
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
return 0
endproc
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 ()
if (iTotal == 0)
Print ("Failed to get the network interface list.")
return 1
endif
return 0
endproc
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"
int main ()
szDescriptor = "www.yahoo.com"
Print ("IP Address for [" + szDescriptor + "] is [" + szIpAddress + "]")
return 0
endproc
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"
Print ("IP address list for [" + szDnsName + "] is [" + strIpList + "]")
return 0
endproc
Function OS Descrition
NetBind Bind to a designated port
NetConnectT
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
if (fReturn == FALSE)
Print ("Failed to create UDP connection.")
NetDeleteSocket (hSocketListen)
return FALSE
endif
if (fReturn == FALSE)
Print ("Failed to bind to local port [" + iListenPort + "].")
NetDisconnect (hSocket)
NetDeleteSocket (hSocketListen)
return 1
endif
NetDeleteSocket (hSocketListen)
return 0
endproc
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
if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif
if (fReturn == false)
Print ("Failed to connect to [" + strIpAddress + "] on port [" + iPort + "].")
return 1
endif
Print ("Successfully connected to [" + strIpAddress + "] on port [" + iPort + "].\n")
NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 0
endproc
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.
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
if (fReturn == false)
Print ("Failed to create UDP socket.")
return 1
endif
NetDeleteSocket (hSocket)
return 0
endproc
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 ()
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
if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif
if (fReturn == false)
Print ("Failed to connect to [" + strIpAddress + "] on port [" + iPort + "].")
return 1
endif
Print ("Successfully connected to [" + strIpAddress + "] on port [" + iPort + "].\n")
NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 0
endproc
NetCreateTCP
Create a TCP socket using the previously opened wrapper.
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
if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif
if (fReturn == false)
Print ("Failed to connect to [" + strIpAddress + "] on port [" + iPort + "].")
return 1
endif
Print ("Successfully connected to [" + strIpAddress + "] on port [" + iPort + "].\n")
NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 0
endproc
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
if (fReturn == false)
Print ("Failed to create UDP socket.")
return 1
endif
NetDeleteSocket (hSocket)
return 0
endproc
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
if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif
if (fReturn == false)
Print ("Failed to connect to [" + strIpAddress + "] on port [" + iPort + "].")
return 1
endif
Print ("Successfully connected to [" + strIpAddress + "] on port [" + iPort + "].\n")
NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 0
endproc
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
if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif
if (fReturn == false)
Print ("Failed to connect to [" + strIpAddress + "] on port [" + iPort + "].")
return 1
endif
Print ("Successfully connected to [" + strIpAddress + "] on port [" + iPort + "].\n")
NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 0
endproc
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"
iPort = 80
strSend = 'GET / HTTP/1.0\r\n\r\n'
hSocket = NetCreateSocket ()
if (hSocket == 0)
Print ("Failed to create socket.")
return 1
endif
if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif
if (fReturn == false)
Print ("Failed to connect to [" + strIpAddress + "] on port [" + iPort + "].")
return 1
endif
Print ("Successfully connected to [" + strIpAddress + "] on port [" + iPort + "].\n")
NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 0
endproc
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.
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
if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif
if (fReturn == false)
Print ("Failed to connect to [" + strIpAddress + "] on port [" + iPort + "].")
return 1
endif
Print ("Successfully connected to [" + strIpAddress + "] on port [" + iPort + "].\n")
NetDisconnect (hSocket)
NetDeleteSocket (hSocket)
return 0
endproc
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.
Function OS Description
NetSSLDizable Dizable SSL
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.
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)
if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif
if (fReturn == false)
Print ("Failed to connect")
NetDeleteSocket (hSocket)
return 1
endif
NetDeleteSocket (hSocket)
return 0
endproc
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 ()
NetSSLEnable (hSocket)
NetSSLEnableSSLv2 (hSocket)
NetSSLEnableSSLv3 (hSocket)
NetSSLEnableTLSv1 (hSocket)
NetSSLDizableCACheck (hSocket)
if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif
if (fReturn == false)
Print ("Failed to connect")
NetDeleteSocket (hSocket)
return 1
endif
NetDeleteSocket (hSocket)
return 0
endproc
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 ()
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)
if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif
if (fReturn == false)
Print ("Failed to connect")
NetDeleteSocket (hSocket)
return 1
endif
NetDeleteSocket (hSocket)
return 0
endproc
NetSSLEnableTLSv1
Enable TLSv1.
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)
if (fReturn == false)
Print ("Failed to create TCP socket.")
return 1
endif
if (fReturn == false)
Print ("Failed to connect")
NetDeleteSocket (hSocket)
return 1
endif
NetDeleteSocket (hSocket)
return 0
endproc
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)
NetSSLEnableTLSv1 (hSocket)
NetSSLSetCertVerif (hSocket, CERT_VERIF_NONE)
NetDisconnect (hSocket)
return 0
endproc
Function OS Description
NetToolCreate Create a new network raw tool object
NetToolGetResultEx Get the string representation of the execution result with a parameter
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.
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"
if (hNetTool == 0)
Print ("Failed to create Tcp raw network object.")
return 1
endif
NetToolDelete (hNetTool)
return 0
endproc
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"
if (hNetTool == 0)
Print ("Failed to create Tcp raw network object.")
return 1
endif
NetToolDelete (hNetTool)
return 0
endproc
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"
if (hNetTool == 0)
Print ("Failed to create Tcp raw network object.")
return 1
endif
NetToolDelete (hNetTool)
return 0
endproc
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:
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"
if (hNetTool == 0)
Print ("Failed to create Tcp raw network object.")
return 1
endif
NetToolDelete (hNetTool)
return 0
endproc
NetToolGetResult
Get the string representation of the execution result.
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"
if (hNetTool == 0)
Print ("Failed to create Tcp raw network object.")
return 1
endif
NetToolDelete (hNetTool)
return 0
endproc
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.
Function OS Description
NetPacketAlign Align the buffer content to the supplied byte count
NetPacketDumpForPrint Make a printable string out of a given Handle from the given range
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
NetPacketSendTo Function to transmit a packet on a UDP socket to a specified host and port
NetPacketWriteInt8X Write a 1 byte integer repeated X times 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)
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.
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.
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.
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.
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.
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
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
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:
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.
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
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
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
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.
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.
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:
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.
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.
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;
qhandle = NtPerfOpenQuery ()
NtPerfCollectQueryData (qhandle)
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.
#####################################################################
int i
PerfQueryHandle hQuery;
PerfCounterHandle hCount;
hQuery = NtPerfOpenQuery ()
hCount = NtPerfAddCounter (hQuery, szCounter)
NtPerfCollectQueryData (hQuery)
wait (1)
endfor
NtPerfCloseQuery (hQuery)
endproc
#####################################################################
# Main
#####################################################################
proc main ()
ErrHandler = INLINE_HANDLER
int i, j
if (ErrCode != ERR_SUCCESS)
print ("Function failed!\n")
exit
endif
endfor
endfor
string szCounter
szCounter = NtPerfMakeCounterPath ("", "System", "", "", 0, "File Control
Operations/sec")
endproc
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.
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.
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
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").
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.
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
Function OS Description
ProgressDestroy Destroy a progress bar dialog box
ProgressGetBar Get the current position of the bar on a progress dialog box
ProgressSetLine Set the text on one of the lines 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)
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.
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 ()
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 ()
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.
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
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
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 ()
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 ()
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
count = count + 1
wend
wait (10)
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
Wait (5)
ProgressDestroy (hProgress)
endproc
proc main ()
ProgressBarFunctions ()
endproc
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’
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
RegGetSubKeys Get the names of all the sub-keys under a registry key
Function OS Description
RegSetValue Add or modify a value in the registry
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 ()
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)
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 ()
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")
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 ()
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.
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 ()
if (type == REG_DWORD)
intRegValue = RegGetIntValue (RegKey, RegValue)
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:
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 ()
if (type == REG_SZ)
strRegValue = "test"
RegGetStrValue (RegKey, RegValue)
if (strRegValue == "test1")
RegDeleteValue (RegKey, RegValue)
endif
endif
RegDeleteKey (RegKey)
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 ()
endproc
RegGetValueNames
Get the names of all the values of a registry key.
Syntax:
String[] RegGetValueNames (String KeyPath)
String[] RegGetValueNames (RegKeyHandle Handle, String KeyPath)
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:
if (type == REG_SZ)
strRegValue = "test"
RegGetStrValue (RegKey, RegValue)
if (strRegValue == "test1")
RegDeleteValue (RegKey, RegValue)
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 ()
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
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:
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 ()
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 ()
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)
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"
;*******************************************************
;Procedure to create registry keys and handle any errors
;*******************************************************
RegCloseKey (hKey)
endproc
;*******************************************************
;Perform the creation of new registry keys
;*******************************************************
if (FileIsIni(szFile))
inihandle = FileIniOpen (szFile)
else
Print (LogFile, "\r\nInifile not valid INI format\r\n")
exit
endif
;*******************************************************
;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
;*******************************************************
;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
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
;*******************************************************
n = 1
iTotal = 1
while (n <= nSect)
if (CHILLI_VERH >= 3)
szKey = FileGetSectionName (inihandle, n)
nEntry = FileGetEntryCount (inihandle, szKey)
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
;********************************************************
; InstallServices
; This procedure sets the variables for the remote
; creation of the SNMP service
;********************************************************
;********************************************************
; Main
;********************************************************
Proc Main()
string szMachine, szMachineList
TextFileHandle hMachineList
int i, iNumPC
RefWinDir = 'C:\WinNT'
RefSysDir = 'C:\WinNT\System32'
ErrHandler = INLINE_HANDLER
// Loop through the list of PCs and create and configure SNMP on each one
hMachineList = FileTextOpen ("List.txt")
iNumPC = FileGetLineCount (hMachineList)
FileTextClose (hMachineList)
Endproc
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.
Name Description
ERR_SDBMOUTOFHANDLES Out of SDBM file handles (too many opened at once)
ERR_SDBMBADHANDLE Invalid SDBM handle
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
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.
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.
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.
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.
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.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
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
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.
string szRes
endproc
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
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:
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
endproc
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.
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
ServiceList List the services which satisfy the supplied type and status values
Function OS Description
ServiceStart Start 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 ()
ServiceName = "NTService"
ServiceCreate (ServiceName, "C:\\winnt\system32\\ntserv.exe",
SERVICE_WIN32_OWN_PROCESS)
DisplayName = "NT Service Test"
ServiceSetName (ServiceName, DisplayName)
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.
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)
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
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.
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 ()
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 ()
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
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 ()
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.
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)
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 ()
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.
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:
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
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 ()
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 ()
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.
Example:
The following example resets the path of a service.
proc main ()
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 ()
ServiceName = "NTService"
group = ServiceGetGroup ("SNMP")
ServiceSetGroup (ServiceName, group)
start = ServiceGetStart ("SNMP")
if (start == SERVICE_START_SYSTEM)
ServiceSetStart (ServiceName, start)
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.
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
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.
Example:
This example sets the user of a service and then checks if this value has been correctly set.
proc main ()
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.
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 (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")
exit
endif
endif
ServiceDelete (ServiceName)
endif
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
if (start == SERVICE_START_SYSTEM)
ServicesetStart (ServiceName, start)
endif
endproc
proc main ()
ServicesFunctions ()
endproc
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.3 Functions
Following you find the list of all functions of the Shortcut function module:
Function OS Description
ShortcutCreate Create a new shortcut
ShortcutGetIconIndex Get the index of the icon image used for a shortcut
Function OS Description
ShortcutGetShow Get the show status 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.
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 ()
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 ()
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.
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 ()
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 ()
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.
Example:
This example reads information of a shortcut.
proc main ()
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 ()
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.
Example:
This example reads information of a shortcut.
proc main ()
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 ()
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.
Example:
The following example sets the target and arguments of a shortcut.
proc main ()
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 ()
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 ()
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 ()
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.
Example:
The following example sets the directory, icon and show status of a shortcut.
proc main ()
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:
Example:
The following example sets the directory, icon and show status of a shortcut.
proc main ()
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.
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 ()
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
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.
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.
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:
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:
RpcDomainInfo01
The RpcDomainInfo01 structure is returned as a result for the RpcSamQueryDomain01 function. It gathers
information about a domain.
Elements:
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:
RpcServerInfo
The RpcServerInfo structure is returned as a result for the RpcSrvSvcQueryInfo function. It gathers
information about a server.
Elements:
RpcServiceInfo
The RpcServiceInfo structure is returned as a result for the RpcSvcCtlEnumServices function. It gathers
information about a service.
Elements:
RpcShareInfo
The RpcShareInfo structure is returned as a result for the RpcSrvSvcEnumNetShare function. It gathers
information about a share.
Elements:
RpcSidInfo
The RpcSidInfo structure is returned as a result for the RpcLsaQueryInfo function. It gathers information
about a domain or an account.
Elements:
RpcWinregKeyInfo
The RpcWinregKeyInfo structure is returned as a result for the RpcWinregQueryKey and RpcWinregEnumKey
functions. It gathers information about a registry key.
Elements:
RpcWinregValueInfo
The RpcWinregValueInfo structure is returned as a result for the RpcWinregQueryValue and
RpcWinregEnumValue functions. This structure gathers information about a registry value.
Elements:
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:
SmbTreeInfo
The SmbTreeInfo structure is returned as a result for the SmbTreeConnect function. This represents a handle
for any opened share (tree).
Elements:
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
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
RpcSamConnect Remote access to the SAM pipe through the RPC interface
RpcSamQueryDomain01 Open a policy handle for the supplied Domain SID with maximum allowed
security
RpcSrvSvcEnumNetShare Enumerate the network share using the SRVSVC interface
Function OS Description
RpcWinregOpenHKey Remote access to the registry through the WINREG interface
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
SmbSessionOpen Do all the required operations from TCP connection to SMB logon
SmbTreeConnectWithServerName Connect to a share and give an indication about the server name
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.
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
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.
#####################################################################
# main
#####################################################################
int main ()
SmbHandle hSmb
hSmb = SmbCreate ()
if (hSmb == 0)
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.
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
SmbTreeInfo hTree
RapShareInfo vecRapShareInfo[]
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
SmbTreeInfo hTree
RapFileInfo hFileInfo
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
SmbTreeInfo hTree
endif
SmbFileInfo hFileInfo
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
SmbTreeInfo hTree
SmbFileInfo hFileInfo
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
endif
SmbTreeInfo hTree
SmbFileInfo hFileInfo
RpcPolicyHandle hLsaHandle
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.
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
SmbTreeInfo hTree
SmbFileInfo hFileInfo
RpcPolicyHandle hLsaHandle
RpcSidInfo sidAccount
sidAccount.Sid = 'S-1-5-21-3749479926-2838610240-4085093052'
iUserCpt += 1
endif
endif
endfor
RpcLsaClose (hSmb, hTree, hFileInfo, hLsaHandle)
endif
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
SmbTreeInfo hTree
SmbFileInfo hFileInfo
RpcPolicyHandle hLsaHandle
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
#####################################################################
int main ()
SmbHandle hSmb
hSmb = SmbCreate ()
if (hSmb == 0)
return 1
endif
SmbTreeInfo hTree
SmbFileInfo hFileInfo
RpcPolicyHandle hLsaHandle
RpcSidInfo sidDomain
endproc
RpcSamClose
Remote access to the SAM pipe through the RPC interface. Close the previously opened policy handle.
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
SmbTreeInfo hTree
SmbFileInfo hFileInfo
RpcPolicyHandle hPolicyHandle
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
SmbTreeInfo hTree
return 1
endif
SmbFileInfo hFileInfo
RpcPolicyHandle hPolicyHandle
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 ()
SmbHandle hSmb
hSmb = SmbCreate ()
if (hSmb == 0)
return 1
endif
SmbTreeInfo hTree
SmbFileInfo hFileInfo
sidDomain.Sid = 'S-1-5-21-3749479926-2838610240-4085093052'
endproc
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
SmbTreeInfo hTree
SmbFileInfo hFileInfo
endif
sidDomain.Sid = 'S-1-5-21-3749479926-2838610240-4085093052'
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 ()
if (hSmb == 0)
return 1
endif
SmbTreeInfo hTree
SmbFileInfo hFileInfo
RpcShareInfo vecRpcShareInfo[]
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.
#####################################################################
# main
#####################################################################
int main ()
SmbHandle hSmb
hSmb = SmbCreate ()
if (hSmb == 0)
return 1
endif
SmbTreeInfo hTree
SmbFileInfo hFileInfo
RpcServerInfo hServerInfo
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
SmbTreeInfo hTree
SmbFileInfo hFileInfo
SmbDelete (hSmb)
return false
endif
RpcPolicyHandle hPolicyHandle
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
return 1
endif
SmbTreeInfo hTree
SmbFileInfo hFileInfo
RpcPolicyHandle hPolicyHandle
RpcServiceInfo vecRpcServiceInfo[]
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.
Returns:
The policy handle.
Example:
include "smb.chx"
#####################################################################
# main
#####################################################################
int main ()
SmbHandle hSmb
hSmb = SmbCreate ()
if (hSmb == 0)
return 1
endif
SmbTreeInfo hTree
SmbFileInfo hFileInfo
RpcPolicyHandle hPolicyHandle
endproc
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
SmbTreeInfo hTree
SmbFileInfo hFileInfo
RpcPolicyHandle hHK, hK
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
SmbTreeInfo hTree
SmbFileInfo hFileInfo
RpcPolicyHandle hHK, hK
RpcWinregKeyInfo hKeyInfo, hKeyInfo2
RpcWinregValueInfo hValueInfo, hValueInfo2
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
SmbTreeInfo hTree
SmbFileInfo hFileInfo
RpcPolicyHandle hHK, hK
RpcWinregKeyInfo hKeyInfo, hKeyInfo2
RpcWinregValueInfo hValueInfo, hValueInfo2
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)
#####################################################################
# main
#####################################################################
int main ()
SmbHandle hSmb
hSmb = SmbCreate ()
if (hSmb == 0)
return 1
endif
SmbTreeInfo hTree
SmbFileInfo hFileInfo
RpcPolicyHandle hHK, hK
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
SmbTreeInfo hTree
SmbFileInfo hFileInfo
RpcPolicyHandle hHK, hK
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 ()
SmbHandle hSmb
hSmb = SmbCreate ()
if (hSmb == 0)
return 1
endif
SmbTreeInfo hTree
SmbFileInfo hFileInfo
RpcPolicyHandle hHK, hK
RpcWinregKeyInfo hKeyInfo, hKeyInfo2
RpcWinregValueInfo hValueInfo, hValueInfo2
endif
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
SmbTreeInfo hTree
SmbDelete (hSmb)
return 1
endif
SmbFileInfo hFileInfo
RpcPolicyHandle hHK, hK
RpcWinregKeyInfo hKeyInfo, hKeyInfo2
RpcWinregValueInfo hValueInfo, hValueInfo2
endproc
SmbCreate
Create a new SMB client.
Syntax:
SmbHandle SmbCreate ()
Returns:
A handle to the newly created SMB client.
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)
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
SmbTreeInfo hTree
string szFileVersion
string szProductVersion
bool fFileExists
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 ()
if (hSmb == 0)
return 1
endif
SmbTreeInfo hTree
string szFileVersion
string szProductVersion
bool fFileExists
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.
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
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)
return 1
endif
SmbSessionInfo hSession
SmbSessionGetInfo (hSmb, hSession)
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
TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 1
endif
if (!SmbSessionNegotiate (hSmb))
NbtSessionDisconnect (hSmb)
TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 1
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
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 ()
if (hSmb == 0)
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
SmbDelete (hSmb)
return 1
endif
if (!SmbSessionNegotiate (hSmb))
NbtSessionDisconnect (hSmb)
TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 1
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
DebugContextHandle hDebug
hDebug = DebugContextCreate ()
if (hDebug == 0)
SmbDelete (hSmb)
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
endif
SmbTreeInfo hTree
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
hSmb = SmbCreate ()
if (hSmb == 0)
return 1
endif
SmbTreeInfo hTree
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 ()
if (hSmb == 0)
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
TcpDisconnect (hSmb)
SmbDelete (hSmb)
return 0
endproc
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]
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
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
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
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
Function OS Description
SmtpConnect Connect to the named SMTP server at the specified port
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
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.
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.
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.
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.
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
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.
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)
SmtpEndMail (smtp)
SmtpDisconnect (smtp)
endproc
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.
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
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.
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:
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:
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:
Value Types:
Possible value types are: SNMP_INT, SNMP_STR, SNMP_OID and SNMP_UNKNOWN
Function OS Description
SnmpCreateVars Create a variable list for SNMP operations
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
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
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.
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.
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.
The SnmpGetNext functions has two signatures, whose usage depends on the fact if the BCM agent is running or
not.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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).
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[]
SnmpGetNext
Perform a getnext operation from an SNMP agent given an array of variables containing the object to be read.
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[]
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[]
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.
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"
endproc
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[]
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.
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
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.
***************************************************************************/
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)
endproc
;*************************************************************************
; Main procedure sending the DGM code 800.
;*************************************************************************
proc main ()
SendDGMTrap (800)
endproc
Example 2:
proc PrintOid (SnmpOid Oid)
int i;
endproc
proc main ()
int error;
string szAddress, szMail
SnmpOid Oid;
SnmpVarBind VarBind[1];
// ErrHandler = INLINE_HANDLER;
endproc
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.
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:
DATATYPE
This constant defines the data type of a column in a database table. It can be one of the following values:
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
GenSqlConnection
The GenSqlConnection data type is a reference to the handle of an open sql connection.
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
GenSqlFirstRow Move the current row index within the result object to the first one
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
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
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
GenSqlSeekRow Move the current row index within the result object to the number specified
GenSqlClose
Close the connection specified by the supplied handle.
Syntax:
Bool GenSqlClose (GenSqlConnection Connection)
Connection is the handle to the connection to be closed.
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.
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.
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
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.
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)
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"
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;
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))
GenSqlClose (conn)
GenSqlFreeResult(result)
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 + ' ;'
// Select all columns for all records in MtxPC and print the
// entire result set without knowing how many rows or how many
// columns.
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
// With two nested loops we can dump the entire result from the blind query
GenSqlFirstRow(result)
For (i=0; i<GenSqlGetRowCount(result); i+=1) // Loop for each row
GenSqlSeekRow (result, i) // Goto row number i
Endfor
GenSqlFreeResult(result)
GenSqlClose (conn)
// Note: Database and data still intact: We have not cleaned up the sample
endproc
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.
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.
SshExecInfo
The SshExecInfo structure represents an array of information about a .
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
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
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
#####################################################################
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
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.
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
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"
#####################################################################
# 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
SshDelete (hSsh)
DebugContextDestroy (hDebug)
return 0
endproc
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
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:
Function OS Description
CompareVersions Compare two strings containing a version number
StrLeft Extract a substring from the left hand side (beginning) of a string
StrRight Extract a substring from the right hand side (end) of a string
StrToBinary Convert all of the characters in a string from printable ASCII to their actual binary value
StrToNumbers Convert the contents of an ASCII string value to the equivalent decimal values
StrTruncateRight Return a subset of a string by counting raw characters from the 'left' of the string.
CompareVersions
Compare two strings containing a version number.
Syntax:
Bool CompareVersions (String Version1, String Operator, String Version2)
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
DriveLetter = "T"
Server = "Coyote"
Share = "Sample"
User = "Guest"
break
else
if ((szFilename != '.') && (szFilename != '..'))
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.
Returns:
The HTML value of the character, for example a space ( ) is converted to “ ”.
Example:
proc main ()
string 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
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.
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 ()
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 ()
if (iOffset != 0)
iLen = StrLen (Value)
Right = StrRight (Value, iLen - iOffset)
Left = StrLeft (Value, iOffset - 1)
endif
endproc
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 ()
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 ()
endproc
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 ()
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 ()
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)
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.
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 ()
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 ()
endproc
StrTokenise
Tokenise a string given a separator.
Syntax:
String[] StrTokenise (String Value, String Separator)
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[]
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 ()
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 ()
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.
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, )
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:
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
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):
StrFindRegEx
Match a regular expression within a string and return an array of matching strings.
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
if ( count > 0)
print ("In the following sentence: " + MySentence)
print (" I found the word 'grey' in " + count +" places:\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"
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
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"
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)
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 ()
endproc
Example 4:
This example converts special characters in an ASCII file to be HTML ready:
proc main ()
endproc
This returns "French is cluttered with words like évident and héritage"
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
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.
Function OS Description
TimeFormat Format a value of absolute seconds using the supplied formatting string
TimeGetUTCDiff Return the difference in seconds between local time and UTC time
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
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 ()
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.
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 ()
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 ()
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 ()
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
Function OS Description
TimerCreate Create a timer object
TimerReset Reset a timer object to 0 and stops it so that it can be used for a new measurement
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.
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.
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.
if (!FileExists (szFile))
FileCreate (szFile)
FileAddLine (szFile, szTitle + "\r\n")
endif
endproc
# LogData
# Logs the supplied data string with the current timestamp.
int TimeNow;
TimeNow = TimeGetAbsSeconds ()
endproc
proc main ()
TimerHandle HandleTime;
FtpHandle HandleFtp;
ErrHandler = INLINE_HANDLER
TimerStop (HandleTime);
TimerReset (HandleTime)
FtpDisconnect (HandleFtp);
TimerDestroy (HandleTime);
endproc
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
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 ()
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.
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.
UserInfo
The UserInfo structure is returned as a result for the UserGetList function. This structure provides
information about the user.
Elements:
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.
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.
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.
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.
Returns:
TRUE if the group exists, FALSE otherwise.
Example:
include "user.chx"
proc main ()
bool fGroupExists
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.
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
Function OS Description
Defined Check that variable or constant name is defined
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
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
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))
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.
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'))
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'))
else
print ('This variable is not defined')
endif
endproc
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'))
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'))
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'))
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 ()
if (defined ('my_string_variable'))
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.
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')
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 (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.
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
endproc
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
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
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
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.
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
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.
Example:
The following example script removes duplicates from an array.
proc main ()
int IntArray[]
int i
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[]
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
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
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.
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 ()
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
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
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:
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"
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"
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
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 ()
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 ()
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.
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 ()
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 ()
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 ()
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”)
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.
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.
WindowSize
The WindowSize structure represents a list of integers defining the size of a number of windows.
Elements:
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
WindowGetClassName Get the name of the class to which the specified window belongs
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
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:
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.
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
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.
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
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.
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;
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.
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;
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 ()
endproc
WindowMove
Change the position and dimensions of the specified window.
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)
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 ()
47.5 Examples
The following code sample illustrates the window functions.
proc ListChildren (int win)
int i, iChildren[];
string szText;
proc ListWindows ()
int i, iWindow[];
string szText;
iWindow = WindowListTopLevel ()
proc main ()
window winCancel
ListWindows ()
ClickButton ("Print", "Cancel")
ClickButton ("Quick Open", "&Browse")
endproc
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.
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.
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
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.
WNET_SRVTYPE
The Wnet_SrvType constant represents all possible types that the servers found in a domain can be:
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.
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.
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.
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.
ModuleFunctions
The HtmlTag structure represents an HTML tag in a file.
Elements:
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
XMLGetAttributeValue Get an XML element attribute value using the supplied XPath key
XMLGetValue Get the value of an XML element using the supplied XPath key
Function OS Description
XMLSave Save the XML file
XMLSetAttributeValue Set an XML element attribute 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.
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.
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.
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.
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
// The second syntax also uses brackets inside which the 'position()'
// function is called and given an integer encoded as string as its argument
XMLClose (hXML_CFG_FILE)
Endproc
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
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
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
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
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
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
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
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
This appendix lists all predefined variables and constants which are used in the Chilli language.
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:
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:
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.
This following table displays a list of all existing Chilli function modules and for which platforms they are
applicable:
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
Performance ntper.chx
Monitoring
Process process.chx
process.so
Progress Dialog progress.ch
Box x
Registry registry.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.
45828309