Вы находитесь на странице: 1из 165

BML Scripting Cookbook

Best practices for BML language use and advanced functionality 1st Edition

Author Toni Pastorino

BigMachines BML Scripting Cookbook 1st Edition (September 2009) Copyright 2009 BigMachines, Inc. All rights reserved. Any technical documentation that is made available by BigMachines, Inc. is the copyrighted work of BigMachines, Inc. and is owned by BigMachines, Inc. The technical documentation is being delivered to you AS-IS. BigMachines, Inc. makes every effort to provide the most accurate and relevant information available to date. Any use of technical documentation or the information contained therein is at the risk of the user. No part of the contents of this book may be reproduced or transmitted in any form or by any means without the written permission of BigMachines, Inc. The examples companies, organizations, products, people and events depicted herein are fictitious. No association with any real company, organization, product, person or event is intended or should be inferred.

THIS DOCUMENT IS CONFIDENTIAL


Definition of Confidential Information. Confidential Information means any information which the Discloser keeps secret from its business competitors and the public, and includes information disclosed in writing, verbally, electronically, or any tangible form. The Recipient shall have a duty to protect only that Confidential Information which (a) is disclosed in writing or any tangible form and is marked Confidential at the time of disclosure, or (b) is disclosed by the Discloser in any other manner and is designated as confidential at the time of disclosure and in a written memorandum delivered to the Recipient within thirty (30) days of the disclosure. Use, Non-Disclosure. Recipient shall not disclose Confidential Information to any third parties or employees of Recipient, except for those with a good faith need to know of this information. Recipient shall not reverse engineer, disassemble or decompile any prototypes, software or other tangible objects which embody a Disclosers Confidential Information. Recipient agrees to use the same level of care, but no less than a reasonable degree of care, as Recipient uses to protect its own Confidential Information of a similar nature, and shall immediately notify the Discloser in the event of any unauthorized use or disclosure.

Retail Value: $49.95

ACKNOWLEDGEMENTS I give much appreciation and thanks for the editing support and constructive feedback provided by Tim Handorf throughout the evolution of this project. Thank you to Jared Toporek for proofreading and feedback. Many thanks to Debbie Maher and Will Weigler for talking me into using a better design program! I have to thank my husband for putting up with long nights and weekends where I had my head buried in my laptop. Last, but certainly not least, this book would not have been completed without the help of Richard Jones. His feedback, patience and extensive knowledge of BML and the BigMachines application has been invaluable.

TABLE OF CONTENTS
11
12 12 13 13 14 14 14 17

PROGRAMMING CONCEPTS

1.1 - PROGRAMMING LANGUAGE 1.2 - PROGRAMMING STRUCTURE 1.3 BASIC DATA TYPES 1.4 COMMON ELEMENTS OF STATEMENTS 1.5 WHAT IS A FUNCTION? 1.6 - BASIC SYNTAX OF BML 1.7 - VARIABLE DECLARATION 1.8 STRING VS. NUMBER

19
20 21 22 22 25 28

BML FUNCTION EDITOR

2.1 - FUNCTION EDITOR BASICS 2.2 SCRIPT DEFINITION AREA 2.3 ATTRIBUTES AND ACTIONS 2.4 - FUNCTION WIZARD 2.5 VARIATIONS OF THE DEBUGGER 2.6 LIBRARY FUNCTIONS

33
34 35 36 37 38 39 41 42 44 46

STRING FUNCTIONS

3.1 UPPER(str) AND LOWER(str) 3.2 ATOF(str) AND ATOI(str) 3.3 STARTSWITH(str, substring) 3.4 LEN(str) 3.5 ISNUMBER(str) 3.6 TRIM(str) 3.7 REPLACE(str, old, new, [n]) 3.8 FIND(str, substring, [start], [end]) 3.9 SUBSTRING(str, start, [end]) USE CASE STRING FUNCTIONS

49
50 50 51 52 53 54 55 57 59 62 65

NUMERIC FUNCTIONS

4.1 INTEGER (x) 4.2 ROUND(x) 4.3 CEIL(x) 4.4 FABS(x) 4.5 POWER FUNCTIONS POW (x,y) AND EXP (x) 4.6 FMOD(x,y) 4.7 LOG(x) AND LN(x) 4.8 SQRT(x) AND HYPOT(x,y) 4.9 SIN(x), COS(x) AND TAN(x) 4.10 ASIN(x), ACOS(x), AND ATAN(x) 4.11 - SINH(x), COSH(x), TANH(x)

CONFIDENTIAL

69
70 70 71 72 72 74 75 76 77

DATE FUNCTIONS

5.1 GETDATE()/GETSTRDATE() 5.2 ISWEEKEND(date) 5.3 ISLEAP(year_num) 5.4 DATETOSTR(date) 5.5 STRTODATE(str, format) 5.6 STRTOJAVADATE(str, format) 5.7 MINUSDAYS(date, num_of_days) 5.8 - ADDDAYS (date, num_of_days) 5.9 GETDIFFINDAYS(date 1, date 2)

79
80 81 82 84 85

CONDITIONAL FUNCTIONS
6.1 - USING AN IF...STATEMENT 6.2 - USING AN IF...ELSE STATEMENT 6.3 - FOR...LOOP 6.4 - BREAK 6.5 - CONTINUE

87

88 90 93 97 99 100 101 102 103 104 105 106 107 109 110

ARRAYS AND ARRAY FUNCTIONS

7.1 - ARRAY ATTRIBUTES 7.2 - 1-D ARRAYS 7.3 - 2-D ARRAYS 7.4 - POPULATING ARRAYS 7.5 - RANGE(x) 7.6 - APPEND(arrayID, newArrayElem) 7.7 - REMOVE(arrayidentifier, removePos) 7.8 SORT(arrayID,[sortOrder],[sortType]) 7.9 MAX(arrayIdentifier) AND MIN(arrayIdentifier) 7.10 FINDINARRAY(arrayID, element) 7.12 ISEMPTY(arrayIdentifier) 7.13 SIZEOFARRAY(arrayIdentifier) 7.14 SPLIT(str, separator) 7.15 JOIN(str_Array, delimiter) ARRAY FUNCTIONS USE CASE

115
116 116 117 118 119 120 121

ADVANCED FUNCTIONS

8.1 DICT(dictType) 8.2 PUT(dictIdentifier, key, value) 8.3 GET(dictIdentifier, key) 8.4 - CONTAINSKEY(dictIdentifier, key) 8.5 MAKEURLPARAM({name 1:value 1}) 8.6 URLDATABYget() 8.7 URLDATABYpost()

CONFIDENTIAL

122 130 131 132

8.8 BMQL() 8.9 - INVOKE () 8.10 - GETARRAYSTR() 8.11 - GETCONFIGATTRVALUE()

135
136 137 138 140

LIBRARY FUNCTIONS

9.1 - ADD A UTIL LIBRARY F(X) 9.2 - ADD A COMMERCE LIBRARY F(X) 9.3 - USE CASE: FIND AN AVERAGE 9.4 - USE CASE: LINEAR INTERPOLATION

145
146 148 151 152

ADVANCED USE CASES

10.1 - RECOMMENDED ITEM RULE 10.2 - LOOPING THROUGH LINE ITEMS 10.3 - SOAP CALLS IN BML 10.3 - SOAP CALLS IN BML

155
156 158 158

TROUBLESHOOTING

11.1 - COMMON ERROR MESSAGES 11.2 - TIPS AND REMINDERS 11.3 - BEST PRACTICES FOR BML

CONFIDENTIAL

CONFIDENTIAL

INTRODUCTION

BML (BigMachines Extension Language) is a scripting tool that is used to define advanced logic within configuration and commerce. ABOUT THIS BOOK This book has been written with BigMachines Administrators in mind. The purpose of this book is not only to provide readers with a basic understanding of programming concepts, but also offers different examples, exercises, use cases and Best Practice Tips. Once you have finished this book, you will understand: * * * * * * The History and Function of BML Basic programming concepts Pre-defined functions, data types, basic and advanced functionality. Most Common Use Cases and Applications Avoiding common errors How to Debug the Code

INTENDED AUDIENCE Novice BigMachines Administrators that have little to no programming experience will find this book helpful in learning how to master using the BML scripting language for basic and advanced rules. Advanced BigMachines Administrators who are already familiar with BML should be able to skim the basics and move to the more advanced recipes and use cases. You will quickly be able to formulate your own solutions for any unique use case that you may have. HISTORY OF BML BML is a scripting language that was built on the JavaTM platform. It is a scripting language that was provided to administrators to capture the companys complex business logic in BigMachines. It has evolved since its inception and now offers more advanced capabilities, including complex data structures like arrays, dictionaries, and the ability to query data table and parts data. It is built on a robust platform of Java.

CONFIDENTIAL

PROGRAMMING CONCEPTS
In this chapter: Programming language Programming structure Data Tables Variable initialization Language Samples Basic syntax of BML If Statements Examples Practices Exercises

basic definition of computer programming is that it creates a sequence of instructions to enable a computer to perform a certain action. In order to enable the computer to perform the desired action, you must determine the instructions that must be performed, the order in which they are executed, and the fixed data that is required. These instructions or statements are written in a particular programming language that makes up the source code.

There are thousands of programming languages, but we only refer to the most common and how BML compares to them. BML is language that wasnt really based off of one specific language. Which language it is most similar to is often debated in the BigMachines home office, but nobody really has a good answer. The answer is simple: there isnt one. You will see syntax that is familiar in Java, Basic, Python, and C++, but they arent exactly the same. By the end of this chapter, you should have a good understanding of what programming language is and how its used and structured. You should also understand the syntax of BML and have generated some very basic and functional code.

Highlights of BML JavaTM Based High Performance Environment for Speed and Scalability Infrastructural Changes do not affect Business Logic Leverages same syntax as prior version of BigMachines scripts Written through a user friendly administration tool Enhanced Debugger Additional functions such as direct data table calls and arrays

CONFIDENTIAL

11

1.1 - PROGRAMMING LANGUAGE


1.1 - PROGRAMMING LANGUAGE
A programming language is an artificial language that is used to write instructions that a computer can understand. Programming languages can be broken down into two groups Compiled and Interpretive. Compiled programming language is a language which must be converted into machine language, after its been written by the programmer, so that a computer can understand and execute the instructions. These languages require the use of special software called a compiler prior to being executed.

Language C C++ JAVA

Source Code Write general instructions

Compiler Compiles instructions into machine language.

Computer executes machine language

Many programming languages are considered Interpretive. Interpretive programming languages do not have to be compiled. The computer understands and executes the instructions while the program is running. See examples below:

Language Visual Basic Perl

Source Code Write general instructions

Computer executes instructions as its running.

BML has characteristics of both. Its a Java based mark-up language, so it does need to be compiled, but that is done within the application.

1.2 - PROGRAMMING STRUCTURE


There are two separate models for computer programming: Structured and Object-Oriented programming. Structured programming uses blocks of code that are executed one after the other. They include control statements which dictate the flow, or when these statements are executed. Almost all structured programming, including BML, share a similar overall structure. They include: Statements to establish the start of the program Variable declarations Source code (blocks of programming statements) In BML, a return statement is always required

BML follows a Structured programming model, so object-oriented programming will not be introduced. 12 CONFIDENTIAL

1.3 BASIC DATA TYPES


Almost all programming languages include the use of data types. A data type determines the values that a variable can contain and how it is executed. A data type also represents a constraint placed upon the interpretation of data. There are four basic types that you should know Integer Float String Boolean

The integer data type allows data to be stored and returned as a whole number. When trying to assign any value that contains a decimal or a different character, will either round the decimal or throw an error. The float data type is also commonly referred to as decimal. This only allows data to be returned with a decimal. The string data type will allow text output of any kind to be returned. In BML, string variables will always be in double quotations ( ). Boolean data types return either a True or False based on your inputs.

1.4 COMMON ELEMENTS OF STATEMENTS


Element ; // return Description Represents and end statement. This is required on each line of code. Indicates a comment line. This is the beginning of the return statement which is required at the end of your code. BML will not process instructions without it. This function displays all data types in the console to make debugging easier. You can give it direct inputs or have it print variables and results from other functions. It displays as purple in the Debugger

PROGRAMMING CONCEPTS

print

You may also see the element return ;. This is going to return an empty string if there isnt anything to return. It will not return an integer, float, boolean or array, it will return only a string as signified by the double-quotation marks.

CONFIDENTIAL

13

1.5 WHAT IS A FUNCTION?


A function is usually defined as a rule that relates one variable value to another. In programming, it also represents a series of commands that perform an action or calculates a value depending upon certain parameters. Parameters are the values that the function uses. Not all functions require parameters, as you will see throughout this cookbook.

1.5 WHAT IS A FUNCTION?

1.6 - BASIC SYNTAX OF BML


In Recipe 1.2 we discussed the structure of programming language. To review, the basic structure includes statements that make up the source code and finish with a return statement. The example below shows a comment, a variable and a return statement. We will cover the importance of declaring variables in Recipe 1.8.

1. The [//] indicates that the line is a comment and describes the code to the user, without sending it to the computer as an action. 2. You are declaring your variable in line 3. 3. Line 5 is your return statement. You are letting the computer know that the instructions are complete and ready to be executed. Anything that occurs after a return statement is executed will be ignored. Note It is considered a Best Practice to add spaces and comments to your code. You probably noticed that lines 2 and 4 were left blank. This is done to make the code more readable.

1.7 - VARIABLE DECLARATION


Variables are placeholders for the data a program may use or manipulate. They are given unique names so that they can be assigned values and referred to throughout the source code. In order to use a variable, you must declare it by giving it a unique name. In many programming languages, once a variable is declared, it must be initialized. However, in BML, these two steps occur at the same time. The following example shows what your code will look like when a variable is declared and initialized. For this example, we will be showing string variables only. EXAMPLES String Data Type Lets assume this is a configuration rule message you have written. Lines 1-3 declare the variables age, salary, and first_inital. 14 CONFIDENTIAL

The following will returned in the Debugger, which we will cover in the next chapter

Integer Data Type We are going to try to determine the average of three people using the integer data type.

PROGRAMMING CONCEPTS

CONFIDENTIAL

15

Float Data Type Now we will perform a similar formula but with numbers that contain decimals. Again, we are performing a simple equation , but this time it returns a float

1.5 WHAT IS A FUNCTION?


Boolean Data Type In this last example, we are going to ask the computer a true or false question.

16

CONFIDENTIAL

1.8 STRING VS. NUMBER


As was explained in the Recipe 1.3, string, integer and float are three separate data types. Lets go into a little more detail as to the difference between strings and numbers. Lets say you put the following variable into BML

If the required return type is Integer, this will return a 6, as it is processed as a regular math equation. If its a Float return type, it will return a 6.0. However, should your required return type be a String, the following error message will be returned

This is because all string variables need to be in double quotations. So, lets see what happens if we put the numbers in quotes

While in use with integers and floats, the + sign is meant for addition, however when being used with strings, it is meant to concatenate, meaning it will combine the strings. Therefore, the code above returns the following

PROGRAMMING CONCEPTS

CONFIDENTIAL

17

1.8 STRING VS. NUMBER

18

CONFIDENTIAL

2
BML FUNCTION EDITOR
In this chapter: Script Definition Area Attributes Function Wizard Debugger Library Functions BML Library

he BML scripting language is used to define advanced functions in the BigMachines application. Basically anywhere you see a button that is labeled define function, you will open the BML function editor. The Function Editor is basically the same throughout the software, however there are slight differences based on the section of BigMachines you are in (ie Commerce, Configuration, Itemsetc). Editors are customized for each component of BigMachines to provide the best functionality for the selected section.

We are using the function editor from Configuration throughout this chapter. In addition, the Function Editor allows you to compile your BML code and check the syntax by running it through the Debugger. BML FUNCTION EDITOR USED IN CONFIGURATION

CONFIDENTIAL

19

2.1 - FUNCTION EDITOR BASICS


2.1 - FUNCTION EDITOR BASICS
While there are notable differences between the function editors that are found throughout the BigMachines application, there are some common characteristics as well. Definition of Button You will run across a few buttons located at the bottom of the editor pane: The Validate or Check button checks your code for errors. The Save button allows you to save your code and continue editing. The Save and Close button saves your code and closes the function editor.

Color of Syntax You will notice that the code below is displayed in different colors

Color
Black Pink Aqua Blue Green

Definition
Variable names, float variables and integer variables Numeric Operators Literals or data types (string, float, integer, boolean) Functions and string variables Conditional functions

20

CONFIDENTIAL

2.2 SCRIPT DEFINITION AREA


BML can be directly typed into the Script Definition Area. You will want to save the changes you make after writing/editing the script. EXAMPLE

If we zoom in on the bar across the bottom, you should see the bar that represents the character position in the code as well as the total number of characters.

The box on the left defines the Position of the character based on its line and index. (Remember that the character index begins with 0. The box to the right gives you the actual number of characters in each line.

Use the toolbar above to undo/redo changes, change the font or jump to a specific line in the script.

BML FUNCTION EDITOR

Clicking on the the script

will call a search and replace pop-up if you need to find and/or replace part of

You can also click on

in order to jump to a specific line in the script.

CONFIDENTIAL

21

2.3 ATTRIBUTES AND ACTIONS


2.3 ATTRIBUTES AND ACTIONS
In the function editor, you can select attributes to include within your code. These attributes are specific to the product family that you are working in. For example, when you are in Configuration you can select from standard product line, model, account, user or configurable attributes. To add an attribute or attribute values as an input

1. Click Add Attributes in the Attributes tab. This adds an editable row to the Attributes list. In the first column, click the drop-down list and navigate through the attribute list to find the desired attribute, or click and start typing and the attribute list will be filtered for you. The proper Variable Name will automatically populate. You can click on the blue arrow to insert the variable name into the code. 2. Click the drop-down list and navigate to find the desired value for the attribute you selected. 3. Click on the blue arrow in order to insert your selected attribute value into the script definition area below. 4. The return type of the your code will be displayed in between the section with header tabs and the script definition area. The action attribute values you select will determine the return type of your code.

2.4 - FUNCTION WIZARD


The Function Wizard contains a list of pre-defined functions that are available for use in advanced scripting. We will be covering these functions in the chapters that follow. There are some variations in the Function Editor depending on where you are within the application, Commerce, Configuration, Commerce Library or the Util Library.

22

CONFIDENTIAL

Configuration/Util Library Function Editor Note The only difference between the Configuration Function Editor and that of the Util Library is that the latter doesnt have a tab labeled Library Functions. This is because your library functions are created in the Util Library. This will be covered in more depth in Chapter 9. To use the Function Wizard in Configuration, first click on the Function Wizard tab, then 1. Select a Function Category and a Function Name. You will see some help with syntax appear just below the tool bar.

2. To insert the function in your BML function Script Definition Area, click Insert into BML.

BML FUNCTION EDITOR

3. As you can see, the function populates in the script definition area.

CONFIDENTIAL

23

2.3 ATTRIBUTES AND ACTIONS

Commerce Library Function Editor The Commerce Library looks similar to the one in Configuration, however you will notice that the Attributes section is quite different. It allows you to select attributes for the main document, subdocument as well as system attributes.

Commerce Function Editor You may also come across a BML Editor in Commerce that looks like this Using this editor, you will have select your attributes on a previous screen. Your operators are all located on a tool bar across the top and you can select your functions from a drop-down menu on the right side of the editor.

24

CONFIDENTIAL

2.5 VARIATIONS OF THE DEBUGGER


The Debugger tab allows the users to debug the advanced function. You can test the code by providing different values of the attributes/parameters as inputs in the debugger. The Debugger varies quite a bit depending on where you are in the application. Configuration

You will start in the Input Section, in the upper left-hand corner for the Function Editor. You should have already added your attributes/parameters under the Attributes tab. Those will show up in the input section under Action Inputs. 1. Click on the corresponding cell in the Value column to select a value for the attribute using the drop-down list or by simply typing a value into the cell. 2. Click Run to run the function. The result can be seen in the Console section. 3. Click Clear to remove the Value(s) for your attribute(s) as well as clearing the Console. 4. Clicking Expand Console will hide the Input Section of the Debugger. If there is an error in the syntax, an error message will appear ABOVE the tabs. Errors will be discussed in detail in Chapter 11. You may have also noticed that there are a couple of different colors in the Debugger. In Recipe 1.4, we introduced the print function and also return statements. Anything that is sent to the console using the print function will show up in PURPLE. What you return using the return statement will show up highlighted in yellow. In the previous example we return an empty string (using return ), which is why you just see what appears to be a small yellow box.

BML FUNCTION EDITOR

CONFIDENTIAL

25

2.5 VARIATIONS OF THE DEBUGGER

Commerce Debugger This is eventually going to be phased out, but there are still many applications and versions out there that use this. This Debugger requires that you select at least one variable and then use a Transaction ID number to import the Values for each attribute you selected. You could also manually enter these values.

Where to find the transaction ID In order to use the Debugger in Commerce, you will have to reference a quote. 1. 2. 3. 4. 5. Go to the Quote Manager. Choose a pending quote and click on its quote number. Click View>Source in under your address bar Click CTR+F to open a Find box. You will want to search for id and you will find the transaction ID.

Depending on your implementation, you may be able to find it under a tab titled Integration. Click on the Integration tab and the Transaction ID will be in a text box towards the right of the screen. Commerce Library Debugger There are a number of sub-headings that can be used under the Commerce Library Debugger tab.

26

CONFIDENTIAL

Test Script: Test Script provides a way to test a BML Library function when array type attributes are input parameters. Within the Test Script, you can populate your own complex data objects and pass it to the library functions to analyze the results. Test Scripts can also be used to compute multiple iterations of the library function and print each. Example of Test Script: 1. Created values for the parameters used in this function. 2. The return statement is written as follows: return.util.function_name(parameters).

BML FUNCTION EDITOR

CONFIDENTIAL

27

Param: If you defined parameters in the header section, they will appear here for Debugging. System: This section lists the attributes you added under the System Attribute section. They will appear here so you can populate/change the parameter values when debugging You can populate values by double-clicking the Value section next to the attribute(s) of your choice.

2.6 LIBRARY FUNCTIONS

Header: This section lists the attributes you added under the Main Document Attribute section. You can add values by double-clicking the Value section next to the attribute(s) of your choice. Line Item: This sections lists the attributes you added under the Sub-Document Attribute section. You can populate values for debugging values by double-clicking the Value section next to the attribute(s) of your choice. Common: In the Common Attribute section, click Add to access the common attributes that are available across the system. For example, suppose your function requires to check the user type of the logged in user, choose the user type Common Attribute in this section and reference it in your function. Util Library The Util Library Debugger is similar to that of the one shown above in the Commerce Library, however it contains only the tabs labeled Test Script, Params and Common.

2.6 LIBRARY FUNCTIONS


This section allows the users to input Library Functions to the script. Library functions can be created if there isnt a pre-defined function for what youre trying to accomplish. Keep in mind that library functions need to be created before they can be added. More details regarding libraries will be provided in Chapter 9.

To add a library function 1. Click Add Functions. 2. In the Function column, click the drop-down list and navigate through the list to find the desired function. 3. Click on to preview the function in the pane to the right. 4. Click the blue arrow to insert the function in the Script Definition Area.

28

CONFIDENTIAL

2.7 BEFORE YOU BEGIN


There are some things to note before you begin reading the rest of this book and attempting to write BML code. SHORTCUTS If you click on the question mark in the tool bar above the script definition area, you will see the following menu of commands Shortcut Tab Shift+Tab CTRL+F CTRL+R CTRL+H CTRL+G CTRL+Z CTRL+Y CTRL+E CTRL+Q Access Key E STANDARD SYNTAX You will see some standard syntax through this cookbook and the function editor function(param 1, param 2, param 3, [optional param]) For example substring(str, start, [end]) Data Type String Integer Integer Definition This is the given string for... This represents the index... This represents the index... What does it do? Add tabulation to text Remove tabulation from text Search next/open search area Replace/open search area Toggle syntax highlight on/off Go to line Undo Redo About Close popup Toggle Editor

BML FUNCTION EDITOR

Parameter str start [end]

CONFIDENTIAL

29

Here is a list of operators that will be used throughout the book. For a list of all operators and functions, please refer to Appendix A. Operator Looks like == <number> == <number> <string> == <string> <boolean> == <boolean> <> <number> <> <number> <string> <> <string> <boolean> <> <boolean < <number> < <number> <string> < <string> > <number> > <number> <string> > <string> <= <number> <= <number> <string> <= <string> >= <number> >= <number> <string> >= <string> <boolean> and <boolean> <boolean> not <boolean> <boolean> or <boolean>

2.6 LIBRARY FUNCTIONS

equals

not equal

less than

greater than

less than or equal to

greater than or equal to and not or NUMERIC OPERATORS

Numeric operators always return a numeric data type. The following table shows the numeric operators that can be used in functions. Numeric Operator + * / % Meaning Addition (binary) Subtraction (binary) Multiplication Division Modulus Looks like <number> + <number> <number> - <number> <number> * <number> <number> / <number> <number> % <number>

30

CONFIDENTIAL

All numeric operators take numeric values as input and return numeric values as output. Input can come from numeric literals, numeric identifiers, and numeric functions. Numeric operators can also be used wherever a numeric value can be plugged in, such as in other functions, relational operators and expressions. For example: sqrt (45 + 45) STRING OPERATORS There is one string operator that can be used to return a string as output. The string operator + is meant for concatenation and its formation is <string> + <string> LITERALS Literals can be added to scripts following these conventions: Literal Integer Floating point number Data Type Numeric Numeric Examples 12345 123.45 12345 .345 volume 23 psi 100 True False (3 * 3) + (4 * 4) (3 + 4) == (4 + 3)

String True False

String Boolean Boolean

BML FUNCTION EDITOR

CONFIDENTIAL

31

2.6 LIBRARY FUNCTIONS

32

CONFIDENTIAL

STRING FUNCTIONS
In this chapter: find() substring() len() lower () upper () trim() isnumber() replace() atof() atoi() startwith() endswith()

ow that you have a basic understanding of programming language, BML structure and using the function editor, its time to start scripting. In this chapter, you will be learning how to use string functions in BML. As was introduced in Chapter 1, string data types allow any type of text character to be returned. However, be aware that not all string functions have return values of string type.

At the end of this chapter you will find a sample use case. Try to practice creating the code on your own and check it against the solution provided.

CONFIDENTIAL

33

3.1 UPPER(str) AND LOWER(str)


3.1 UPPER(str) AND LOWER(str)
These functions convert all characters in the text into either all lowercase or all uppercase letters. Example Use Cases: Used in table comparison to make sure you have clean data Ignore case for searching Correcting mistakes made from not following Best Practices during Implementation.

Parameters: # 1 Parameter str Data Type String Description Given input string that must be converted to uppercase

Return Type: String Notes: If the string is empty, then the function will return an empty string This function is case-sensitive.

Example of upper(str) or lower(str)

The code above will print three different examples. The first is applying the upper() function to at typical input string. The second is applying the same function to an empty string. The third one applies the lower() function to the same string. You will notice a blank space in between the upper() and lower() functions. This represents the return that will occur if you use an empty string.

34

CONFIDENTIAL

3.2 ATOF(str) AND ATOI(str)


The atof and atoi functions convert text that represents a number into either a float (atof) or an integer (atoi). The syntax is exactly the same. Example Use Case: Create a string table value into a float/integer value

Parameters: # 1 Parameters str Data Type String Description Given input string that is to be parsed into a float or an integer

Return Type: Integer Notes: An empty string will throw an exception error. You can not parse a string with a decimal point into an integer.

STRING FUNCTIONS

Example of atof (str)/atoi(str) error messages If you attempt to pass an empty string or a string with letters into either atoi() or atof(), you will see:

CONFIDENTIAL

35

If you try to pass a string with a decimal point (like 123.456) through the atoi() function, you will see

3.3 STARTSWITH(str, substring)

Example of atof(str) and atoi(str)

3.3 STARTSWITH(str, substring)


This function, as well as endswith(str, substring) checks whether a string starts or ends with a particular substring. For example, if you wanted to see if the value abc starts with a or if that same string ends in c, you would use these functions. Example Use Cases: Determine if a part number starts with a certain text or, Determine if a part number contains a specific suffix

36

CONFIDENTIAL

Parameters: # 1 2 Parameter str substring Data Type String String Description Represents the given input string Endswith() determines if the given input string ends with this substring and startswith() determines if this string begins with this substring.

Return Type: Boolean (True or False) Notes: These functions are case-sensitive. An empty string will return as true.

Example of startswith(str, substring)/endwith(str, substring)

We know that the return of endResults will be true because the string I like this string, ends with the substring string.

STRING FUNCTIONS

3.4 LEN(str)
The len() function will return the length of a string. Example Use Case: To constrain the length of an input text field

Parameters: # 1 Parameter str Data Type String Description Represents the given input string 37

CONFIDENTIAL

Return Type: Integer

3.3 STARTSWITH(str, substring)

Notes: If str is an empty string, then the function returns a 0. If a string with spaces is passed as an input, then the spaces are counted in the length of the string. For example, len (The cat in the hat) returns 18.

Example of len(str)

3.5 ISNUMBER(str)
isnumber() is a Boolean function that returns true when the string is a number and false if it contains other characters. Example Use Case: Check if a table cell contains a number. This check needs to be performed to prevent system errors when converting that value to a number.

38

CONFIDENTIAL

Parameters: # 1 Parameter str Data Type String Description Represents the given input string

Return Type: Boolean Notes: If str is an empty string, then the function returns false. If no string is passed into the function, then a compile time error is thrown.

Example of isnumber(str)

STRING FUNCTIONS

3.6 TRIM(str)
This function removes white space from both edges of strings. Example Use Case: Compare strings with leading or trailing white space CONFIDENTIAL 39

Parameters:

3.3 STARTSWITH(str, substring)

# 1

Parameter str

Data Type String

Description Represents the given input string

Return Type: String Notes: This function is case sensitive If str is empty, then the function returns an empty string.

Example of trim(str)

You should notice that the string variable contains white space on both ends.

40

CONFIDENTIAL

3.7 REPLACE(str, old, new, [n])


You will use this function if you want to return a copy of a string, with all occurances of the old parameter replaced with the new parameter. All occurrences of the old substring are replaced by new. If the optional integer argument n is given, only the first n occurrences are replaced. Example Use Cases: You must replace multiple subsets of a string.

Parameters: # 1 2 3 4 Parameter str old new [n] Data Type String String String Integer Description Represents the given input string Specifies the substring that is being replaced Specifies the substring that is replacing the old substring Optional: Specifies the number of occurrences of the old that must be replaced

Return Type: Copy of String with replacements made Notes: This function is case-sensitive. Replace(, , ) throws an exception. Replace(abc, , ) throws an exception. Replace(abc, , 1) throws an exception.

Example of replace(str, old, new, [n])

STRING FUNCTIONS

CONFIDENTIAL

41

3.8 FIND(str, substring, [start], [end])

3.8 FIND(str, substring, [start], [end])


The find() function returns the position of a substring within a string. Example Use Cases: Multi-select menu checking Find a value or where a value exists within a string Powerful when used with a substring function

Parameters: # 1 2 Parameters str substring [start] [end] Data Type String String Description Represents given input string Required string parameter that specifies the substring, the position of which this function will return. Optional: Can be used to specify the index at which to begin the search for the substring. Optional: Can be used to specify the index at which to end the search for the substring.

3 4

Integer Integer

Return Type: Integer Notes: This function is case-sensitive. If not specified, start is 0 and end is length(Str). Find(, ) or find(,, num>0) returns 0. Find(str, substring, start>length(str)) returns -1

42

CONFIDENTIAL

Example of find(str, substring, [start], [end]) You will notice that in the example we are performing four different variations of the find() function. emptyTest: We are trying to see what will be returned if we pass two empty strings through the find() function. test_2: what will happen if you try to pass the same two empty strings but also define the optional start index for the substring. longTest: shows what is returned when we pass through a string and substring but begin searching for the substring at an index that is outside of the length of the string. result: shows what happens if find() is looking for a substring and contains both a start and end index.

STRING FUNCTIONS

CONFIDENTIAL

43

3.9 SUBSTRING(str, start, [end])


3.9 SUBSTRING(str, start, [end])
This function is used to pull a subset of string. Example Use Cases : Break a large string down into smaller strings Test characters of dynamic part numbers Determine which characters are at what index

Parameters: # 1 2 3 Parameter str start [end] Data Type String Integer Integer Description Represents the original string you are going to parse. The index where you will begin parsing the string. Optional: The index where you will stop parsing.

Return Type: String Notes: This function is case-sensitive. If start is given an index value that is greater than the length of the string, an empty string will be returned. Start and End can be negative index value.

Example of substring(str, start, [end]) Once again, we are performing a number of actions with the substring() function. subStr: The first thing you should notice is that substring is being populated by using the str, start index and optional [end] index. test_1: This is using the find function with the substring we just defined. negIndResults Here we are giving you and example of what happens when you use a negative start :and [end] index. longStartInd: Finally, this last example shows you what to expect if start is given an index value that is greater than the length of the string,.

44

CONFIDENTIAL

STRING FUNCTIONS

CONFIDENTIAL

45

USE CASE STRING FUNCTIONS


USE CASE STRING FUNCTIONS
You work for Jenson Computer Company. Your company has a product line for configured servers. Your management team wants to have two options when configuring a server. They either want to be able to configure a server from the base up or they want to be able to enter a part number of pre-configured servers. The configuration has the following inputs: Qty input integer box OS input single-select menu Version Number input float box Enterprise System input multi-select check box or single-select menu

Examples: Part numbers PN1200-Win-VN7.1E PN120-Linux-VN2.1S PN12-Mac-E Syntax Breakdown: PN The identifier that determines if it is a part number lookup For a part number: Number Numeric value that represents quantity of the order. - - separator Operating System (OS) = Win or Linux or Mac - - separator VN - Prefix for the version number of the software Version a float value for version number of software E or S - Enterprise System or standard? Your job is to write a script to parse out each of section of the part number and print them in the debugger. It is recommended that you open up your practice session in the BML Library Function Editor. Because this is practice, you can leave all of the code in the same script editor. Lets get started. 1. 2. 3. 4. 5. 6. 7. 8. 9. Assume your first variable is a part number PN35434-Linux-VN4.3S First trim the input string so that we can accurately use startswith(), endswith() Find length of string to see if we can get any useful information Determine if len > 2 Use upper to make the string uniform for comparisons Use startswith() to find if the number begins with a PN Use endswith() to see if it is an enterprise system Find first separator (-) Use index of first dash as a reference point for substrings

46

CONFIDENTIAL

9. 10. 11. 12. 13. 14. 15.

Substring out Number of elements Use atoi() to determine the number of elements Find index of second separator (-) Substring out OS and recommend accordingly Find if last section contains VN and then substring version number Compare version number with a standard version number (atof first) Recommend latest if version number is <

You should see the following results in the console. Dont forget to use the print function for Debugging!

The following is the code you will see when you have completed this exercise. You will be creating variables as you go along. Good luck!

STRING FUNCTIONS

CONFIDENTIAL

47

4
NUMERIC FUNCTIONS
In this chapter: integer() ceil() pow() fmod() ln() hypot() cos() asin() atan() round() fabs() exp() log() sqrt() sin() tan() acos()

umeric functions serve many purposes throughout the BigMachines application. Many of them represent some basic mathematical and trigonometric functions. Time to brush up on your junior high math skills! You will find some refreshers throughout this chapter if you find yourself getting stuck on how to find the arcsine of an angle.

CONFIDENTIAL

49

4.1 INTEGER (x)


This function returns the integer portion of a float number. For example, this function would return 14 for the number 14.3345324. Example Use Case: Returning an attribute as an integer, without rounding.

4.1 INTEGER (x)

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

Return Type: Integer Example of integer(x)

4.2 ROUND(x)
This function returns the rounded value of a number up to a certain decimal point.

50

CONFIDENTIAL

Example Use Case: For returning float values that represent currency. You may want to round to a certain decimal place.

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

Return Type: Float Example of round(x)

NUMERIC FUNCTIONS

4.3 CEIL(x)
This function converts a float into the next highest whole number. Example Use Case: Rounding up to the next highest whole number.

CONFIDENTIAL

51

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

Return Type: Float Notes:

4.4 FABS(x)

Ceil(num), if num is less than zero but greater than -1.0, then the result is negative zero.

Example of ceil(x)

4.4 FABS(x)
This function returns the absolute value of a number. Example Use Case: Finding the distance of the quantity from zero.

52

CONFIDENTIAL

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

Return Type: Float Example of fabs(x)

4.5 POWER FUNCTIONS POW (x,y) AND EXP (x)


pow(x, y) This function returns the value of the first argument raised to the power of the second argument. Example Use Case: Finding the product obtained from multiplying a quantity by itself one or more times.

NUMERIC FUNCTIONS

Parameters: # 1 2 Parameter x y Data Type Float Float Description Represents the value of the input float Represents the power to which you raise the input float

Return Type: Float CONFIDENTIAL 53

Example of pow(x,y)

The results in the console will read 1024.0.

4.6 FMOD(x,y)

exp(x) This function returns Eulers number e raised to the power of the number passed through the function, also known as the exponential function. Example Use Case: Find whether a quantity grows or decays at a rate proportional to its current value, such as compound interest.

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

Return Type: Float Example of exp(x)

Since we are asking to return e1, Eulers number is returned 2.7182818284590455

4.6 FMOD(x,y)
This function returns the remainder after division.

54

CONFIDENTIAL

Parameters: # 1 2 Parameter x y Data Type Float Float Description Represents the dividend Represents the divisor

Return Type: Float Example of fmod(x,y)

The answer is 5 with a remainder of 2. If you plug this operation into your calculator, you will see the answer is 5.66667. That is because the remainder is being divided by the divisor.

NUMERIC FUNCTIONS

4.7 LOG(x) AND LN(x)


log(x) This function returns the base ten logarithm of the number. Remember: if x = by, then y=logb(x). Example: If 1000=103, then 3=log10(1000). The logarithm of 1000 would be 3 because that is how many times you must multiply 10 to get 1000.

CONFIDENTIAL

55

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

Return Type: Float Notes: log(0) or log(-0) is negative infinity. log(infinity) is infinity.

4.6 FMOD(x,y)

Example of log(x)

ln(x) This function returns the natural logarithm (base e) of the number. Remember: if e3=x, then ln(x)=3. Special rules: ln(1.0)=0 ln(0) or ln(-0)=infinity ln(infinity)=infinity

56

CONFIDENTIAL

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

Return Type: Float Notes: ln0) or ln(-0) is negative infinity. ln(infinity) is infinity.

Example of ln(x)

NUMERIC FUNCTIONS

4.8 SQRT(x) AND HYPOT(x,y)


sqrt(x) This function returns the positive square root of a number. CONFIDENTIAL 57

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

4.8 SQRT(x) AND HYPOT(x,y)

Return Type: Float Example of sqrt(x) In this example, we will look for the square root of 49, which we already know to be 7.

hypot(x.y) This function returns the sqrt(x2+y2) without intermediaries. Example: sqrt(32+42)=sqrt=(9+16)=sqrt(25)=5.0 or -5.0 Parameters: # 1 2 Parameter x y Data Type Float Float Description Represents the x in sqrt(x2+y2) Represents the y in sqrt(x2+y2)

Return Type: Float Notes: Negative numbers can be passed as parameters to this function.

Example of hypot(x,y)

58

CONFIDENTIAL

As you can see, we have declared three variables. The two that were required for this function to work, as well as a third variable so we can round the results of the hypot() function.

The result of this function returned a rather large number. Using the round() function we were able to round to the third decimal place.

4.9 SIN(x), COS(x) AND TAN(x)


Remember B sin A = opposite/hypotenuse = a/h cos A = adjacent/hypotenuse = b/h tan A = opposite/adjacent = a/b
h (hypotenuse) a

NUMERIC FUNCTIONS

(opposite)

b (adjacent)

sin(x) This function returns the trigonometric sine of the number/angle. Example Use Case: Finding the ratio of the side opposite the given angle and the hypotenuse. CONFIDENTIAL 59

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

4.9 SIN(x), COS(x) AND TAN(x)

Return Type: Float Example of sin(x)

cos(x) This function returns the trigonometric cosine of the number/angle. Example Use Case: Find the ratio of the side adjacent the given angle and the hypotenuse.

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

Return Type: Float Example of cos(x)

60

CONFIDENTIAL

tan(x) This function returns the trigonometric tangent of the number/angle. Example Use Case: Find the ratio of the side opposite the given angle to the adjacent side.

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

NUMERIC FUNCTIONS

Return Type: Float Example of tan(x)

The result of the function above is -1.995200412208242 CONFIDENTIAL 61

4.10 ASIN(x), ACOS(x), AND ATAN(x)

4.10 ASIN(x), ACOS(x), AND ATAN(x)


Remember The usual notation of the inverse trig function arcsine is, y=arcsin(x), which is defined as x=sin(y). This notation is the same for arccosine and arctangent. asin(x) This function returns the arcsine of a number or angle, the range of which is -/2 y /2 or -90 y 90 and the domain is -1 x 1 Example Use Case: Find the inverse function of the sine of an angle.

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

Return Type: Float Notes: Float variable > 1 will return NaN

Example of asin(x) If you enter your float variable as (-1), which is the lowest number in the domain, it will return the lowest number in the range, which is /2.

62

CONFIDENTIAL

acos(x) This function returns the arccosine of the number/angle in the range of 0.0 through . Example Use Case: Find the inverse function of the cosine of an angle.

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

Return Type: Float Notes: Float variable > 1 returns NaN

Example of acos(x)

NUMERIC FUNCTIONS

You should recognize that the number returned is pi.

CONFIDENTIAL

63

4.10 ASIN(x), ACOS(x), AND ATAN(x)

atan(x) This function returns the arc tangent of the number/angle, the range of which is -/2 y /2 Example Use Case: Find the inverse function of the tangent of an angle.

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

Return Type: Float Example of atan(x)

64

CONFIDENTIAL

4.11 - SINH(x), COSH(x),TANH(x)


sinh x = 1/2 (ex - e-x) cosh x = 1/2 (ex + e-x) tanh x = (e2x - 1) / (e2x + 1)

sinh(x) This function returns the hyperbolic sine of the number or angle. Example Use Case: Find the hyperbolic sine of a number/angle.

NUMERIC FUNCTIONS

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

Return Type: Float

CONFIDENTIAL

65

Example of sinh(x)

4.11 - SINH(x), COSH(x),TANH(x)


cosh(x) This function returns the hyperbolic cosine of the number or angle. Example Use Case: Find the hyperbolic cosine of a number/angle. Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter Return Type: Float Example of cosh(x)

66

CONFIDENTIAL

tanh(x) This function returns the hyperbolic tangent of the number or angle. Example Use Case: Find the hyperbolic tangent of a number/angle

Parameters: # 1 Parameter x Data Type Float Description Represents a given float parameter

Return Type: Float Example of tanh(x)

NUMERIC FUNCTIONS

CONFIDENTIAL

67

4.11 - SINH(x), COSH(x),TANH(x)

68

CONFIDENTIAL

5
DATE FUNCTIONS
In this chapter: getdate() isweekend() isleap() datetostr() strtodate() strtojavadate() minusdays() adddays() getdiffindate() ate functions are often used when evaluating and calculating quotes in Commerce. As an example, they are used to set quote expiration dates. Dates are always saved as strings in commerce, but can be converted to dates using the functions included in this chapter.

Remember: dates always need to be returned as strings to commerce as well.

CONFIDENTIAL

69

5.1 GETDATE()/GETSTRDATE()
5.1 GETDATE()/GETSTRDATE()
This function returns the current date/time based on the base time zone you have set-up. Example Use Case: Find current date

Parameters: This function does not take parameters

Return Type: Date Example of getdate()

5.2 ISWEEKEND(date)
This will determine whether a date falls within a weekend. Example Use Case: Can also determine if the date entered by a user is a valid date..

Parameters: # 1 Parameter date Data Type Date Description Mandatory date parameter

Return: Boolean Example of isweekend (date) 70 CONFIDENTIAL

5.3 ISLEAP(year_num)
Using this function will determine whether the date falls within a leap year. The function will return true if the year provided as a parameter is a leap year. Example Use Cases: Can determine if the date entered by a user is a vaild date. Can be used when trying to calculate the total number of days in a given year.

Parameters: # 1 Parameter year_num Data Type Integer Description 4-digit Integer that represents the year in question.

DATE FUNCTIONS

Return Type: Boolean Example of isleap(year_num) Since the year 2008 was a leap year, the function returns True.

CONFIDENTIAL

71

5.4 DATETOSTR(date)
This function converts a date to a string. Example Use Case: Date fields in commerce are considered string fields so to return a date to a commerce attribute, you need to convert it to a string first.

5.4 DATETOSTR(date)

Parameters: # 1 Parameter date Data Type Date Description Mandatory date parameter

Return Type: String Example of datetostr(date) In this example, you will need to take a function of a function. So, you will first be determining the current date with the getdate() function, and then using datetostr() to convert the date format to a string data type.

The format of the return text is MM/DD/YYYY HH:MM:SS.

5.5 STRTODATE(str, format)


This function does the opposite of datetostr() by converting a string to a date.

72

CONFIDENTIAL

Example Use Case: Date variables are stored as strings in commerce. To convert it to a date type and use data functions in BML, strtodate() must be used on the variable first.

Parameters: # 1 2 Date Format: Day Month Year Hour in Day(0-23) Minute Second %d %m %y %H %M %S Parameter str format Data Type String Date Format Description String format of a date Specifies the format that the date is in.

For example MM/DD/YYYY will be represented as %m/%d/%y Return Type: Date Notes: If the str value is empty string then strtodate() returns ERROR_DATE which in 01/01/0001 (MM/DD/YYYY). If there is a parsing error due to mismatch of str value and the format string passed to strtodate() function then the same ERROR_DATE is returned.

Example of strtodate(str, format)

DATE FUNCTIONS

The format of the return text is YYYY-MM-DD HH:MM:SS.

CONFIDENTIAL

73

5.6 STRTOJAVADATE(str, format)

5.6 STRTOJAVADATE(str, format)


The function converts a string to a date and replicates Java behavior. This function is preferred over strtodate(). Strtodate() is a deprecated function that will no longer be supported. Parameters: # 1 2 Date Format: Day Month Year Hour in Day (0-23) Hour in Day (1-24) Hour in am/pm (0 - 11) Hour in am/pm(1-12) Minute Second dd MM YY HH Kk KK Hh mm ss Parameter str format Data Type String Date Format Description String format of a date Specifies the format that the date is in.

Return Type: Date Notes: If str is empty string, then this method throws an exception, unlike strtodate() method. The format strings supported are different from the ones supported by strtodate() function.

74

CONFIDENTIAL

Example of strtojavadate(str, format)

The format of the return text is YYYY-MM-DD HH:MM:SS, the same as the strtodate() function.

5.7 MINUSDAYS(date, num_of_days)


This function returns a date that is x days before the base date. Example Use Case: Can be used to set an expiration date of a quote.

Parameters: # 1 2 Parameter date num_of_days Data Type Date Integer Description Represents the given date. How many days you want to subtract from given date.

Return Type: Date Example of minusdays(date, num_of_days)

DATE FUNCTIONS

CONFIDENTIAL

75

5.8 - ADDDAYS (date, num_of_days)


5.8 - ADDDAYS (date, num_of_days)
This function returns the date which is obtained after adding x number of days to a particular date. Example Use Case: Often used in commerce to set the time a quote is valid, or when it expires.

Parameters: # 1 2 Parameter date num_of_days Data Type Date Integer Description Represents the given date. How many days you want to subtract from given date.

Return Type: Date Example of addDays(date, num_of_days) For this example, we are going to use multiple functions that will accomplish the following Add 60 days to the current date Convert that date to a string format Remove the hours:minutes:seconds from the return

76

CONFIDENTIAL

5.9 GETDIFFINDAYS(date 1, date 2)


This function calculates the number of days between two different dates. Example Use Case: Check to see if a quote is expired.

Parameters: # 1 2 Parameter date 1 date 2 Data Type Date Date Description Mandatory Date Parameter Mandatory Date Parameter

Return Type: Integer or Float Example of getdiffindays(date 1, date 2) Note the inputs must be in Date format.

TIP: You must use strtojavadate()to change otherDate from a string format to date format.

DATE FUNCTIONS

CONFIDENTIAL

77

5.8 - ADDDAYS (date, num_of_days)

78

CONFIDENTIAL

6
CONDITIONAL FUNCTIONS
In this chapter: if ifelse forloop break continue

onditional functions are commands that run only when specific criteria is met. Each conditional statement requires a boolean expression that may or may not be visible to you. To put it more plainly, a conditional function must evaluate a true or false.

CONFIDENTIAL

79

6.1 - USING AN IF...STATEMENT


6.1 - USING AN IF...STATEMENT
An if...statement is the most basic conditional function in programming. The basic syntax is: if (condition){ statement; } What this is saying in plain language is If (condition) is true, then perform the statement. If that condition is false, then no action is taken. Example of if... This is a very basic example, saying that if the variable string is a number, then we want to convert it to a float.

In this case, 25 is a number, so we used function atof() to convert the string to a float.

80

CONFIDENTIAL

6.2 - USING AN IF...ELSE STATEMENT


An if...else statement as essentially the same as an if...statement, except that instead of doing nothing if the condition isnt met, a different statement is run. The basic syntax is: if (condition){ statement; }else{ statement; ) So, its saying, Do something if the condition is met. If not, do something else. You can also have multiple else statements nested within on another. Example of if...else

We are saying, if the var=25 is a number, then convert the string to a float. If its not an number, print NaN (which represents not a number).

CONDITIONAL FUNCTIONS

CONFIDENTIAL

81

6.3 - FOR...LOOP
A for...loop is a popular function that is used in programming. A for...loop statement is meant to loop through a block of code until a specific condition is met. The basic syntax is: for (variable) in (system_array){ statement(s) }

6.3 - FOR...LOOP

The variable represents the element, but you can label however you want. You can call it each or element or even your name if you wanted to. Lets think of a table of values that we will name: Table_Array Column 1 1 Column 2 2 Column 3 3

Row 1

Now, lets use the same syntax as above: for (row element) in Table_Array{ print row element; ) So, what we are really saying is: For Row 1 in Table_Array, print each element in the row Example of for...loop in a 1-D Array In the following example, we are setting up a 1-D integer array. What this code is saying is, for whatever array element is in myArray, print that array element. We will cover arrays in Chapter 7.

So, the code is going to loop through the integer array we have defined and print every element that is in this 1-D array.

82

CONFIDENTIAL

Example of for...loop in a 2-D Array Now, lets say we had a table that had more than one row Column 1 Row 1 Row 2 Row 3 0 1 2 Column 2 3 4 5

We are going to cover 2-D arrays in extensive detail in Chapter 7, but this is for your reference. You will have use a loop within a loop in order to return the row values and the column values.

CONDITIONAL FUNCTIONS

So, what we will see is that for each row, it will print a row (Row 1 will return [0,3]), after it loops through and pulls the value for the row, its going to loop through the row and pull the values for the columns, returning to you the individual values of 0 and 3.

CONFIDENTIAL

83

6.4 - BREAK

6.4 - BREAK
Using this function will break a forloop at the element that you ask it to. Example of break We are going to use a simple 1-D string array. As it is being looped through, we would like it to stop if and when it reaches the element ccc.

As you can see, we are still using the same string array and for loop in the first two lines. However, we have added an if statement to the third line, which says that if the loop approaches the element ccc in the array, that it should break.

84

CONFIDENTIAL

6.5 - CONTINUE
The continue action calls out an element from an array, and essentially skips it, but continues looping through the rest of the array. Example of continue

In Recipe 6.4, the break stopped the loop, but in this case the loop continues through the rest of the array, it just skips over the element ccc.

CONDITIONAL FUNCTIONS

CONFIDENTIAL

85

6.4 - BREAK

86

CONFIDENTIAL

ARRAYS AND ARRAY FUNCTIONS


In this chapter

row, column x, y color, shape

Variable Name

Value 1
Index 0

Value 2
Index 1

Value 3
Index 2

Value 4
Index 3

Value 5
Index 4

Value 6
Index 5

The index indicates the position of the value within the array. So, if we were looking for Value 7 within the array, its location is Index 6. Indexes are zero-based in BML, meaning that the first element will always have an index of zero and the last element or value will have an index of 1(number of element). The maximum size of a 1-D array is 1000. There are also 2-dimensional arrays. These arrays can be though of as a grid or a table with multiple rows and columns. The convention for defining and accessing these arrays is [row, column].
Col 1 Variable 1 Variable 2 Variable 3 2 7 8 Col 2 6 5 4 Col 3 5 1 3

We can see that for the data set {Variable 2, Col 3}, the value is 1 and the index for this would be index[1][2].

CONFIDENTIAL

{
Value 7
Index 6

Overview of arrays range sizeOfArryay append() remove() sort() max() min() findinarray() reverse() isempty() replace() split() join()

B {

igMachines provides the ability to declare, initialize, populate and manipulate arrays using BML. An array is an ordered collection of values referenced by a single variable name. You could think of an array as a table. With values in rows and columns. Another way to think of arrays is in relation to an x-y axis. If you recall, data sets are formatted as (x,y). Data in arrays is similar

Value 8
Index 7

Value 9
Index 8

87

7.1 - ARRAY ATTRIBUTES


What are array attributes? Array attributes are used to allow users to easily group multiple, scalar attributes using a single data structure, and are available both for the selection and configuration process. Similar to other configurable attributes, you can create array attributes at all levels in the configuration hierarchy, but can delete them only at the level of the hierarchy in which they were created. You can create Array attributes for all the available data types (Float, Integer, String). Example of an array attribute (Users View)

7.1 - ARRAY ATTRIBUTES

What you see above would be a typical array configuration. In this example, the user had selected that 3 floors needed to have their elevators configured. From this one screen, you can individually configure each elevator. As you can see, each one has a different combination of door type, door trim and buttons. Control Attribute The size of arrays are defined by the control attribute. When creating a control attribute, the attribute itself must have a Data Type of integer and you must make sure that the Array Type box is not checked. In the case below, the user wants to configure 27 floors. Number of Floors is the control attribute for the array.

88

CONFIDENTIAL

Before You Begin Here is some general information regarding arrays that you should know before you get started. As we introduced, another way to think of an array is as a 1-D or 2-D table. A one-dimensional table of the above array would like this: Elevator # Door_Type 1 Stone 2 Blue 3 Red

A two-dimensional table representing this array should look pretty familiar: Elevator # Door_Type Door Trim Buttons BML syntax used with arrays Element [] [n] {x,y} Limits Indexes In a 1-D array, the following represents your index values: ROW 1 Index 0 Index 1 Index 2 Index 3 Index 4 Index 5 Index 6 Index 7 For a 1-D array, the maximum number of columns that you can have in an array is 1000. For a 2-D array, the maximum number of rows an array is 1000 and columns is 50. Meaning Indicates a 1-D array 1-D array with a defined size Element within a 1-D array Element [][] [n][n] {{x,y},{z,r}} Meaning Indicates a 2-D Array 2-D array with defined size Elements within a 2-D array 1 Stone Painted Shiny 2 Blue White Easy 3 Red Stained Plastic

ARRAYS AND ARRAY FUNCTIONS

In a 2-D array, your index values will represent both the row index and the column index, so the basic syntax will be index[row][column]. A simple 3x3 table will have the following index values: COL 1 ROW 1 ROW 2 ROW 3 Index [0][0] Index [1][0] Index [2][0] COL 2 Index [0][1] Index [1][1] Index [2][1] COL 3 Index [0][2] Index [1][2] Index [2][2] 89

CONFIDENTIAL

7.2 - 1-D ARRAYS


These functions initialize arrays without specifying the size. At a later time, when they values are assigned in different array indexes, the system expands the array into the appropriate size automatically. string[n] Parameters:

7.2 - 1-D ARRAYS

# 1 2

Parameter string[] [n]

Data Type String Array Integer

Description Used to declare an array Optional: use number n if you need to declare an array of a specific size.

Return Typ:e String Array Notes: Negative number (including NaN, which is equal to -999999) specified for array size throws a runtime exception. For example, arr = string[-9]; throws a RuntimeException. The maximum number of rows supported is 1000. For string array, the value in each field of the array after array declaration (example, arr = string[10];) is equal to null, if the array fields are not initialized. These arrays are dynamic in nature and the length can be increased. For example strArray = String [2]; // This will create a string array of length 2 strArray [4] = a; // This will automatically extend the length of strArray to 5

Example of string[n]

90

CONFIDENTIAL

Unitialized arrays In order to show you the different ways to declare arrays, we will display two separate arrays below. myArray is going to show you what to expect if you define an array size without initializing array fields. yourArray will show you what is returned when you define the size of an array as well as initialize the fields.

ARRAYS AND ARRAY FUNCTIONS

As you can see, myArray returned a string with four null values because array fields were not initialized after the array was declared.

CONFIDENTIAL

91

integer[n] Just as you do for string arrays, in order to initialize an array of a particular size, use the function integer[n]. Parameters: # 1 2 Parameter integer[] [n] Data Type String Array Integer Description Used to declare an array Optional: use number n if you need to declare an array of a specific size.

7.2 - 1-D ARRAYS

Return Type: Integer Array Notes: For integer array, the value in each field of the array after array declaration (example, arr = integer[10];) is equal to 0, if the array fields are not initialized.

Example of integer[n]

In contrast to the string[] function, if you define an array size without initializing array fieilds, you will see 0 instead of null.

92

CONFIDENTIAL

float[n] Parameters: # 1 2 Parameter integer[] [n] Data Type String Array Integer Description Used to declare an array Optional use number n if you need to declare an array of a specific size.

Return Type: Float Array Example of float[n]

ARRAYS AND ARRAY FUNCTIONS

7.3 - 2-D ARRAYS


These functions initialize 2-D arrays without specifying the size. At a later time, when the values are assigned in a different array index, the system expands the array into the appropriate size automatically. string[n][n]

CONFIDENTIAL

93

Parameters: # 1 2 3 Parameter string[][] [n] [n] Data Type String Array Integer Integer Description Used to declare an 2-D string array Optional: use number n if you need to declare an array of a specific size. Optional: use number n if you need to declare an array of a specific size.

7.3 - 2-D ARRAYS

Return Type: String[][] Notes: For string array, the value in each field of the array after array declaration (example, arr = string[10][2];) is equal to null, if the array fields are not initialized.

Example of string [n][n]

integer[n][n] To initialize a 2-D integer array of a specific size, use the function integer[n][n].

94

CONFIDENTIAL

Parameters: # 1 2 3 Parameter integer[][] [n] [n] Data Type Integer Array Integer Integer Description Used to declare an 2-D integer array Optional: use number n if you need to declare an array of a specific size. Optional: use number n if you need to declare an array of a specific size.

Return Type: Integer[][] Notes: For integer array, the value in each field of the array after array declaration (example, arr = integer[10][2];) is equal to 0, if the array fields are not initialized. These arrays are dynamic in nature and the length can be increased. intArray = Integer[2] [2]; // Creates an integer array with two rows and two columns intArray [2][3] // Automatically extends the length of intArray to include an extra column

Example of integer[n][n]

ARRAYS AND ARRAY FUNCTIONS

Notice the multiple print statements being used in the code above. We are printing a specific element index and value index. Since there are two elements, then element indexes are 0 and 1 respectively. Each element has two values, so the value indexes are also 0 an 1. The syntax used in the code will print each value in the console.

CONFIDENTIAL

95

float[n][n] To initialize a 2-D float array of a specific size, use the function float[n][n]. Parameters: # 1 2 Parameter float[][] [n] [n] Data Type Integer Array Integer Integer Description Used to declare an 2-D float array Optional: use number n if you need to declare an array of a specific size. Optional: use number n if you need to declare an array of a specific size.

7.3 - 2-D ARRAYS

Return Type: Float[][] Notes: For float array, the value in each field of the array after array declaration (example, arr = float[10][2];) is equal to 0.0, if the array fields are not initialized. These arrays are dynamic in nature and the length can be increased.

Example of float[n][n]

96

CONFIDENTIAL

7.4 - POPULATING ARRAYS


Examples of how to populate 1-D and 2-D arrays using a for...loop. 1-D Arrays Create an 1-D array of values equal to the sum of each array element.

ARRAYS AND ARRAY FUNCTIONS

CONFIDENTIAL

97

2-D Arrays In this example, we are going to combine two 2-D arrays by adding together their values and placing them in a new 2-D array. Remember that range() creates an integer array of indexes. We will be using two here.

7.4 - POPULATING ARRAYS


What we are going to do here is add together the values of the two arrays based on their indexes. colRange and rowRange are initializing integer arrays. So, both colRange and rowRange=[0,1,2] respectively. Next, we have to declare and initialize the 2D array that we are going to populate. Next comes the for...loop. As you learned in Chapter 6, the second loop will loop through a row and pull out the column values.

98

CONFIDENTIAL

7.5 - RANGE(x)
Declares an integer array with specified size and initializes it to its index value. Parameters: # 1 Parameter x Date Type Integer Description Denotes the size of the integer array

Return Type: Integer[] Notes: This function is case-sensitive. If x is 0, then the function returns an integer[0]. Example intArray = range(2) returns an integer array of size 2 where, intArray [0] = 0, intArray [1] = 1

Example of range(x) In this example, we are populating a 1-D array. Since range declares an array of indexes, we can loop through the variable that range is equal to in order to populate a new array.

ARRAYS AND ARRAY FUNCTIONS

We are using the example from Recipe 7.1. Lets just say you wanted to concatenate the first two arrays based on their index values and populate the results in a new array. So for example, newArray[0]=doorTypeArray[0] + doorTrimArray[0] or newArray[0] = Stone + Painted = [StonePainted] Using range allows you to loop through the index values and use those to pull information out of the old arrays and input those values into the new array.

CONFIDENTIAL

99

7.6 - APPEND(arrayID, newArrayElem)

7.6 - APPEND(arrayID, newArrayElem)


Parameters: # 1 2 PARAMETERS arrayIdentifier newArrayElem

The function append() will attach a new element to the end of an array and can be used with initialized and un-initialized arrays. Append only works with 1-D arrays.

DATA TYPE DESCRIPTION string[], integer[] or This is the given array that you are float[] going to add an element to. float, float[], integer, This represents the new element that integer[], string, string[], you are appending to the array. boolean, boolean[]

Return Type: Integer (denotes the size of the new array) Notes: If array max size is reached and you try to append a new element, it will fail. If a null element is added to an array, it should be allowed to be added and the value of the element in the array should be null.

Example of append(arrayIdentifier, newArrayElem)

100

CONFIDENTIAL

7.7 - REMOVE(arrayidentifier, removePos)


Parameters: # 1 2 PARAMETERS arrayIdentifier removePos DATA TYPE string[], integer[] or float[] Integer

The function remove() removes an element from an existing array based on a given index.

DESCRIPTION This is the given array from which you will remove an element. This represents the index of the element that you are removing.

Return Type: Integer (denotes the size of the new array) Notes:

ARRAYS AND ARRAY FUNCTIONS

If the array is empty, the remove will fail. Only integers are allowed to be passed in for the index of the element to be removed.

Example of remove(arrayIdentifier, removePos)

CONFIDENTIAL

101

7.8 SORT(arrayID,[sortOrder],[sortType])

Here you can see the new array that is being returned once the element at index[2] was removed.

7.8 SORT(arrayID,[sortOrder],[sortType])
Sorts array elements based on your standard sort method. You can sort in ascending or descending order. Sort() can only be used with 1-D arrays. Parameters: # 1 2 Parameter arrayIdentifier [sortOrder] Data Type string[], integer[], float[] String Description This is the given array you will sort Takes in the string values desc or asc. If it is not specified, the default is asc or ascending. It also can not be a variable containing the string value; this will throw an error. Takes in the sting values as text or numeric

[sortType]

String

Return Type: String Array newly sorted

Example of sort(arrayIdentifier, [sortOrder], [sortType]) What we will find returned in the debugger is the values in this array rearranged into descending order by value.

102

CONFIDENTIAL

7.9 MAX(arrayIdentifier) AND MIN(arrayIdentifier)


max(arrayIdentifier) Returns the largest element of an integer or float array. This function can only be used with a 1-D array. Parameters: # 1 Parameter arrayIdentifier Data Type integer[], float[] Description This is the given array you will use to find the max value

Return Type: Returns an Integer or Float depending on the type of array. Example of max(arrayIdentifier)

ARRAYS AND ARRAY FUNCTIONS

CONFIDENTIAL

103

7.10 FINDINARRAY(arrayID, element)

min(arrayIdentifier) Returns the smallest element of an integer or float array. Min() can only be used with a 1-D array. Using the same example as above, 123 would be returned in the Console.

7.10 FINDINARRAY(arrayID, element)


This function is used to check whether a certain element exists in an array. If it does, the index is returned, otherwise a -1 is returned. Findinarray() can only be used with 1-D arrays. Parameters: # 1 2 Parameter arrayIdentifier element Data Type string[], integer[], float[] String, Integer, Float Description This is the given array. Represents the element you are looking for in the given array.

Return type: Integer that denotes the index of the element in the array. Example of findinarray(arrayIdentifier, element)

This example is asking to find the element (or value) 123.65. Because it is not found in the array, a -1 is what is returned.

104

CONFIDENTIAL

7.11 REVERSE(arrayIdentifier)
The function is used to reverse all elements in the array. Reverse() can only be used with 1-D arrays. Parameters: # 1 Parameter arrayIdentifier Data Type string[], integer[], float[] Description This is the given array.

Return Type: Returns the array with all of the elements in reverse order. Example of reverse(arrayIdentifier)

ARRAYS AND ARRAY FUNCTIONS

7.12 ISEMPTY(arrayIdentifier)
This function determines if the array is empty. Isempty() can only be used with 1-D arrays. Parameters: # 1 Parameter arrayIdentifier Data Type string[], integer[], float[] Description This is the given array.

Return Type: Boolean (True if array is empty and False if it is not)

CONFIDENTIAL

105

7.13 SIZEOFARRAY(arrayIdentifier)

Example of isempty(arrayIdentifier)

The string array above is empty, therefore TRUE is returned.

7.13 SIZEOFARRAY(arrayIdentifier)
This function returns the length of the array for a 1-D array and the number of rows for a 2-D array. Parameters: # 1 Parameter arrayIdentifier Data Type string[], integer[], float[] Description This is the given array.

Return Type: Integer Example of sizeofarray() for a 1-D array

Because there are seven separate elements in the integer array, the Console returns 7.

106

CONFIDENTIAL

Example of sizeOfArray(arrayIdentifier) for a 2-D array

While there are 6 separate values in this array, there are only three elements. Remember that sizeOfArray for a 2-D array will return the number of rows.

7.14 SPLIT(str, separator)


Split() is a string function that returns as a 1-D string array. The function splits a string with respect to a specific separator and populates it into a string array. Parameters: # 1 2 Parameter str separator Data Type String String Description This is the given input string. Represents a variety of separators, however they all must be enclosed in double-quotes, including spaces.

ARRAYS AND ARRAY FUNCTIONS

Return Type: String [] (1-D string array)

CONFIDENTIAL

107

7.13 SIZEOFARRAY(arrayIdentifier)

Notes: This function is case-sensitive. If str is empty string then function returns empty array of size 1. If both str and separator is empty, then function returns empty array of size 1. If separator is empty, then every character in the passed string str is split. Example strArray = split(a.b.c, ); will return an array with every character split, that is sa will be [a,., b, ., c] with size 5.

Example of split(str, separator) This example is going to show you what happens when you try to pass through an empty string or separator as well as what happens when you try to split a string that contains values with the separator that is being used.

108

CONFIDENTIAL

7.15 JOIN(str_Array, delimiter)


Concatenates a string array into a string with a specified identifier. Parameters: # 1 2 Parameter str_Array delimiter Data Type string[] String Description This is the given array. Represents a delimiter to use when concatenating string elements.

Return Type: String Notes: This function is case-sensitive. If str array is empty, then function returns empty string. If both str and delimiter are empty, then function returns empty string. If delimiter is empty, then function returns all the array entries concatenated. Example strArr1 = string[]{1, 2, 3}; strArr2 = join(strArr1, ); will set the value of strArr2 to 123.

Example of join(str_Array, delimiter) The following example will be similar to what we saw with split(). You will see what happens when either the str_Array or delimiter are empty or if one is and one is not. The last example shows what happens when both the st_Array and delimiter have values.

ARRAYS AND ARRAY FUNCTIONS

CONFIDENTIAL

109

ARRAY FUNCTIONS USE CASE

ARRAY FUNCTIONS USE CASE


In this example, you are given User Information that contains a users name, e-mail address and regional revenue. This was set-up as a Util Library Function. It is recommended that you do the same in order to test this. Make sure to create the parameters listed below and select the proper return type. For information on how to create a Util Library Function, please see Chapter 9. arrayFunctionTest(UserInfo, SortDirection, MaxValue, MinValue, UseZero) Parameters: # 1 Parameter UserInfo Data Type string[]][] Description Each row contains the following info {Name, Email, RegionalRevenues} where RegionRevenues is a comma delimited string of sales revenues for the Region the User is responsible for. I.E. - 1200, 0 320, 456 Represents sort direction where 0 is alphabetical, 1 is reverse alphabetical Represents the maximum revenue allowed in the return data Represents the minimum revenue allowed in the return data Boolean flag used to determine if 0 valued revenue should count in the Min constraint

2 3 4 5

SortDirection MaxValue MinValue UseZero

Integer Integer Integer Boolean

Return Type: String[][] containing all the elements sorted and narrowed

110

CONFIDENTIAL

This code is an example of BML Best Practices. It is commented very well and you will need to use a wide variety of functions to accomplish your goal. Here is what you need to do in order for this code to work. It is recommended that these comments are what you put in your code to explain what is happening. You will need to use a wide variety of functions to accomplish your goal. The use of dictionaries will be covered in Chapter 8. 1. Setup initial arrays of data: Given UserName = string[]; QueriedInfo = dict(string[]); 2. Loop through User Info. Within the loop: Find and split region revenue Remove spaces from string Split the data on comma, creating an array of revenues If zero is not allowed in the min constraint Create an integer array the same size as the array you created with the split. Find the location in the array of zero revenue values Declare a 1-D array Check if each is a number and append to the array you just created. Compare min and max values with acceptable min and max values Add user info to a dictionary value Using the username as the key Append the username to a separate array. These will be used as our list of keys to use in the return value 3. Sort data accordingly 4. Retrieve data from dictionary for output 5. Create an index array to build the number of rows of output 6. Create an index array for number of columns of output 7. In this example it is fixed so no need for a variable size 8. Get info from the dictionary 9. Loop through and assign to the output Use Test Script in the Debugger to test the function. The results are on the next page. Chapter 2 explains how to use the Test Script within the Debugger.

ARRAYS AND ARRAY FUNCTIONS

CONFIDENTIAL

111

The code below represents the start of your code. In lines 1-29, you could comment out what the parameters are, similar to what you see on page 110.

ARRAY FUNCTIONS USE CASE

112

CONFIDENTIAL

Example of Test Script Enter the following code into your Test Script: UserInfo = string[][]{{Mick Guyfur, McGuy@quickonfeet.com, 0,1200, 450, 100}, {Clark Kent, SuperGuy@quickonfeet.com, 75.5, -100}, {Bruce Wayne, BatGuy@quickonfeet.com, None, 40, 100000}}; SortDirection = 0; MinValues = 0; MaxValues = 9999999; AllowZero = true; print util.arrayFunctionsTest(UserInfo, SortDirection, MinValues, MaxValues, AllowZero); return util.arrayFunctionsTest(UserInfo, SortDirection, MinValues, MaxValues, AllowZero);

ARRAYS AND ARRAY FUNCTIONS

The following should be returned to you in the console

CONFIDENTIAL

113

ARRAY FUNCTIONS USE CASE

114

CONFIDENTIAL

ADVANCED FUNCTIONS
This chapter includes: dict() put() get() makeurlparam() urldatabyget() urldatabypost bmql() invoke() getarrayattrstr() getconfigattrvalue()

ow that we have mastered many of the standard functions use in BML, its time to introduce some advanced functions. We will start by introducing dictionaries and their purpose and move into pulling external information from other resources, using data tables and a couple of functions that are specific to either configuration or commerce. Dictionaries are a useful tool to store key value pairs. They serve a purpose similar to that of an array or a data table. A dictionary key is what you use to look up a value.

Dictionaries make it very quick to store and retrieve data. You can make them on the fly and append to them as well. After you have created a dictionary, you store values in it using a key. You can attach a value with any data type to a dictionary (except dictionary). When you declare a dictionary you need to make sure to declare what data type you need. A highlight of using dictionaries is that it has better speed and performance than performing table calls. (Recipe 8.6). As an example of the functionality of a dictionary: In your line items, if you wanted to retrieve a list price for a line item you could say that key is the line number and key is the list price.

CONFIDENTIAL

115

8.1 DICT(dictType)
This function creates a dictionary of a specific data type. Parameters: # 1 Parameter dictType Data Type Description string, integer, float, string[], Specify the data type of the integer[], float[], sting[][], integer[][], dictionary. float[][], boolean or date

8.1 DICT(dictType)

Return Type: Dictionary Example of dict()

8.2 PUT(dictIdentifier, key, value)


Once your dictionary has been created, you can define keys and values to put into the dictionary. Example of put(dictIdentifier, key, value) When you return the dictionary, your key is set equal to your value. Parameters: # 1 2 3 Parameter dictIdentifier key value Data Type Dictionary String, Integer or Float String, Integer or Float Description Identifies the dictionary you are adding values to Unique identifier for the value parameter Data value that relates to the unique key identifier

116

CONFIDENTIAL

8.3 GET(dictIdentifier, key)


This function will retrieve from the dictionary, the value of the key provided. Parameters: # 1 2 Parameters dictIdentifier key Data Type Dictionary String, Integer, Float Description Identifies the dictionary you are retrieving values from United identifier for the value parameter

Return Type: The return type is based upon the data type of the dictionary. Example of get(dictIdentifier, key) As you can see, we have defined three separate keys and values and put them all in the same dictionary.

ADVANCED FUNCTIONS

Keep in mind that we have created a dictionary with a data type of string. Using the print function, we can see all of the keys and values in the dictionary. If we ask to receive the value of auto color, the following will be returned

CONFIDENTIAL

117

8.4 - CONTAINSKEY(dictIdentifier, key)

8.4 - CONTAINSKEY(dictIdentifier, key)


This is a Dictionary lookup function that checks to see if the key is found in the dictionary. Parameters: # 1 Parameter dictIdentifier key Data Type Dictionary Description Identifies the Dictionary you are looking through to find if it contains the key you have identified Unique identifier for the value parameter

2 Return Type: Boolean

String, Integer, Float

Example of containskey(dictIdentifier, key) In this example we are going to try to see if the dictionary contains two different keys auto color and purple.

118

CONFIDENTIAL

8.5 MAKEURLPARAM({name 1:value 1})


It is equivalent to creating an ampersand delimited string. URL Functions can be used to extract real-time data from an external system. To build a URL that returns relevant data, use a URL variable to define the parameters the URL expects. The makeurlparam() function constructs the parameters which are used by other URL access functions. Parameters: # 1 2 Parameter name value Data Type String String Description

Return Type: Dictionary Example of makeurlparam()

ADVANCED FUNCTIONS

Notice that this code has comments explaining what it is doing. It is considered best practice to comment your code as much as possible.

You will see all of your parameters and their values returned in the console.

CONFIDENTIAL

119

8.6 URLDATABYget()

8.6 URLDATABYGET()
The function retrieves data from a URL address by the HTTP Get method. Parameters: # 1 2 3 Parameter URL url_param default_ value Data Type N/A Dictionary String Description The location of the data you are trying to access. This represents the markurlparam()parameters you created. This is the default value (or error message) displayed if the data cannot be accessed

Return Type: String Example of urldatabypost(URL, url_param, default_value)

120

CONFIDENTIAL

We are going to see that just as the function suggests, this information is Not Available.

8.7 URLDATABYPOST()
The function retrieves data from a URL address by the HTTP Post method. Parameters: # 1 2 3 Parameter URL url_param default_ value Data Type N/A Dictionary String Description The location of the data you are trying to access. This represents the markurlparam()parameters you created. This is the default value (or error message) displayed if the data cannot be accessed

Return Type: String Example of urldatabypost(URL, url_param, default_value)

ADVANCED FUNCTIONS

CONFIDENTIAL

121

We are going to see that just as the function suggests, this information is Not Available.

8.8 BMQL()

8.8 BMQL()
BigMachines now provides the ability to query system tables and user-created data tables from within BML by using a SQL-like syntax. This functionality is replacing the deprecated gettabledata() and getpartsdata() functions. BMQL is a new function that returns a new data type: Record Set, that contains the results of an SQL query. Highlights: BMQL does not cap the size of the results set at 1,000 records. A query can return all results unless it uses either DISTINCT or ORDER BY, in which case, the result set can contain a maximum of 1,000 records. Can access the parts database or user-defined tables. BMQL is context-sensitive and will pick up the language, currency and selected price book depending on where the function is involved.

The Basics Syntax: RecordSet bmql(String sqlQuery) As mentioned above, the new bmql function is based on SQL syntax. In SQL, most actions you need to perform on a database are done with a statement like: SELECT + FROM. For Example: Similar to SQL, in bmql, your statement would essentially read: select(fields you want to return) from (which database you will be searching through).

122

CONFIDENTIAL

So, when its written that the function syntax is: bmql(String sqlQuery), the sqlQuery is really the statement, similar to the example above. NOTE: The sqlQuery MUST be written as a STRING. For Example:

Statement Keywords: There are a few statement keywords that can use while querying your results. Description This is the keyword used to select the column(s) of data you wish to retrieve. FROM This is where you select the database object from which to retrieve the data. [DISTINCT] This keyword can be used with SELECT to return distinct values, removing duplicates. [ORDER BY] This is used to sort the data returned. Be default, the fields will be returned in ascending order. Use desc to reverse the sort order to descending and use asc to reverse the order to ascending. Keyword SELECT Example bmql(SELECT part_number FROM _parts);

bmql(SELECT part_number FROM _parts);

bmql(SELECT DISTINCT price FROM _parts);

bmql(SELECT price FROM _parts ORDER BY desc);

ADVANCED FUNCTIONS

Parameters: When using BMQL, your WHERE clause will be your parameters. For example:

CONFIDENTIAL

123

When using the WHERE clause: BML Variables can be used in the WHERE clause conditions. The $ symbol must be prepended to the BML variable name when used in the query string. See image under Parameters on page 423. The variable data types that can be used are: string, integer and float. For the IN condition, the variables should be of data type: string[], integer[], or float[]. Line item variables cannot be used directly in the query string. However, you can assign line item variables to variables in BML and then use them in the query string. WHERE Condition The condition is field operation <field|value>. For Example: part_number = BL-5C NOTE: String values should be inclosed in single quotations marks when being used in the WHERE condition. Float and Integer values should be used without them (i.e. valve_pressure = 1.235). Logical operators can be used to group the conditions:

8.8 BMQL()

Parentheses can be used to change the precedence:

This is a conditional evaluation where a boolean value can be used with the AND operator to conditionally evaluate the predicate in the WHERE clause. Where eval is a boolean variable in the script. When eval is TRUE, the predicate field = value is used in the criteria and when eval is FALSE, the predicate field = value is ignored. NOTE: The condition MUST come before the predicate. See Use Case 3 for more details. Operators Relational Operators: =, <>, <, >, <=, >=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL Logical Operators: AND and OR The table on the following page gives the definition and an example of some of the new operators that can be used in BMQL.

124

CONFIDENTIAL

OPERATOR
LIKE NOT LIKE

DESCRIPTION
This is used to mean contains. This is used as does not contain.

EXAMPLE
SELECT part_number FROM _parts WHERE part_number LIKE $var_1 SELECT part_number FROM _parts WHERE part_number IS NOT LIKE $var_1 SELECT part_number FROM _parts WHERE part_number LIKE $var_1 IN $lead_time.

IN

Used to find a value within an array.

NOT IN

Used to find values outside of an array. SELECT part_number FROM _parts WHERE part_number LIKE $var_1 NOT IN $lead_time. Used to find null values in a field or array. Used to find values that are not null within a field or an array. SELECT part_number FROM _parts WHERE part_number LIKE $var_1 IS NULL. SELECT part_number FROM _parts WHERE part_number LIKE $var_1 IS NOT NULL.

IS NULL

IS NOT NULL

Return Type: RecordSet Notes: For security purposes, the query cannot be built dynamically and passed into BMQL. Dynamic values can be passed in the WHERE clause of the query by assigning it to a BML variable and prefixing the variable name with $. EXAMPLE: $var_1 = _quote_line_item The BMQL query is parsed at compile time. Three functions are available to retrieve data from the results set, depending on the data type of the values being returned: get(string); getInt, and getFloat. See Recipe 8.3 for details. ORDER BY and DISTINCT cannot be grouped together using AND or OR. The order of operations can be changed using parentheses. % is the wild card option.

ADVANCED FUNCTIONS

CONFIDENTIAL

125

SAMPLE USE CASES


For all of the use cases below, well be using a user created data table named sammie. Click on a Sample Use Case below to see an example.

8.8 BMQL()
Sample Use Case 1: Using the BMQL Function In this example, lets say youd like to run a query to return the Price and Type from the sammie table shown above. Step 1: Using the information from the sammie data table,, we can create a new script using BMQL that will return Price and Type. Remember that you use select to choose your columns and from to choose your database object. Step 2: Create a for...loop to loop through your record set created using the bmql function. Step 3: In this example, we are using the print statement to show the results of the query. Now, you can compare the results of the query to what is on the table and see that it pulled the correct Type and Price from the table.

126

CONFIDENTIAL

In this example, we are using the same sample case, but adding the distinct keyword. Remember, using distinct will only return distinct values, essentially removing any duplicates.

As you can see, where there were multiple sets that were the same in the first example, now those have been removed:

Sample Use Case 2: Using the get() function and WHERE clause This example takes Sample Use Case 1 a step further by adding a WHERE clause to the select statement. We also add the get function. Step 1: Using the information from the sammie data table,, we can create a new script using BMQL that will return Part, Description and Price when the Type in the data table is Hot. Remember that you use select to choose your columns and from to choose your database object. Step 2: Create a for...loop to go through your record set created using the bmql function. See Recipe 6.3 for more information on for...loops.

ADVANCED FUNCTIONS

Step 3: Use the get function with record being used like a dictionary and Price being the data to be returned. See Recipe 8.3 for more information on the get() function.

CONFIDENTIAL

127

As you can see below, record acts like a dictionary and returns the columns and data you requested. You should also notice the get function at work, returning the price for each of the records.

8.8 BMQL()
Sample Use Case 3: Using a WHERE condition In this example, we are going to add a condition. So, the first screen show well say that if the condition is true, that the predicate will query for the part number HS001. Remember that when adding a where condition, the syntax is $eval AND field = value. In this case, we are searching for part number HS001 when the condition is true. In the console, youll notice that when the part number is HS001, the price and type have been returned.

128

CONFIDENTIAL

Next well evaluate what happens if the condition is FALSE.

In the console, youll notice that when the condition is false, the predicate (Part = HS001) is ignored and all other results are returned.

Sample Use Case 4: Errors The user can retrieve errors or warnings using the new getMessage function.

ADVANCED FUNCTIONS

CONFIDENTIAL

129

Sample Use Case 5: Recommended Item Rule Lets use the table sammie to create a recommended item rule. The goal is to recommend all hot sandwiches when a user selects Hot Sandwiches from a certain attribute.

8.9 - INVOKE ()

8.9 - INVOKE ()
The invoke function is a method to call a global (python) function. You can call a global function from anywhere you can write BML. Although global functions are being phased out in BigMachines, we mention the invoke function in the cookbook because many existing BigMachines customers use this function. Python functions are a method of creating advanced functionality and a method to call data tables. However, in the past two years BML has evolved and most of the functionality you could do with a global function can now be done directly in BML. Also, BML performs better then a global function. This is why we recommend you use BML instead of a global function if possible. Parameters: # 1 2 3 Parameter globalTableFunction delimitedData defaultData Data Type String String String Description Specifies the table function that will be used Specifies the inputs to the global function Specifies the string returned when the result cannot be obtained from the globalTableFunction

130

CONFIDENTIAL

Return Type: String Example of invoke()


Product Line Model Appication Horsepower Lubrication Method Min Cut-In PSIG Max CutOut PSIG

QR-25 QR-25 QR-25

210 210 210

Industrial Industrial Industrial

1 1.5 2

Pressure Pressure Pressure

40 40 40

100 100 100

Note: Only one parameter is allowed to be passed to the global function, which is why we usually pass in a delimited argument string.

8.10 - GETARRAYSTR()
This function returns the delimited string for array attributes with $,$ as the delimiter. This function is only used for configurable attributes. Parameters: # 1 Parameter arrayIdentifier Data Type String[] Description This is the given input array

ADVANCED FUNCTIONS

Return Type: String

CONFIDENTIAL

131

8.11 - GETCONFIGATTRVALUE()

8.11 - GETCONFIGATTRVALUE()
This function retrieves the values of configurable attributes in Commerce. Parameters: # 1 2 Parameter documentNumber configAttrVarName Data Type Integer String Description Represents the Variable name of the configurable attribute from which you are retrieving data

Return Type: String Notes: System attribute _config_attr_info has to be selected as rule input. If the _config_attr_ info is not selected as rule input, and getConfigAttrValue is used, a compile error should be shown to the user. In case of menu attributes, the returned value is the menu item variable name. Always returns a String

132

CONFIDENTIAL

Example of getconfigattrvalue()

ADVANCED FUNCTIONS

CONFIDENTIAL

133

8.11 - GETCONFIGATTRVALUE()

134

CONFIDENTIAL

LIBRARY FUNCTIONS
In this chapter:

Overview of Library Functions Adding a Util Library Adding a Commerce Library Use Case

he BML Function Library enables the user to write efficient and reusable custom BML functions. The user can write and store BML functions in a central library and call these functions from different areas in BigMachines. In the Util BML Library, the functions can be accessed and called throughout BigMachines. However, in the commerce BML Library The functions in this library are accessible only to a main document-sub document pair. Each commerce BML library is a 1:1 relationship with a

main document and sub-document pair. There can be as many commerce BML libraries as there are document pairs in commerce.

CONFIDENTIAL

135

9.1 - ADD A UTIL LIBRARY F(X)


9.1 - ADD A UTIL LIBRARY F(X)
As we discussed Recipe 2.6, you can create your own function to be used throughout BML. In order to add or edit a library function, you will need to navigate to the BML Library.

1. Create a Name,Variable Name, Description and make sure to select the Return Type. 2. At this point, you can begin to add any necessary parameters.

3. Next, create your script, adding any attributes as necessary. 4. Click Add to add your new library function to make it available for use.

136

CONFIDENTIAL

9.2 - ADD A COMMERCE LIBRARY F(X)


Too add a commerce library function, you will need to navigate to: Process Definition > select the Process you wish to modify > choose the appropriate document>Library Functions>List.

1. Click Add to create a new commerce library function. 2. Create a Name,Variable Name, Description, select a Return Type. 3. If the function takes parameters, click Add in the Parameter(s) section. Give a name for the parameter and choose a data type of the parameter. You will be referencing the parameter in the library function with the name that you specify here.

4. In the Main Document Attribute section, click Add to access the main document attributes.

LIBRARY FUNCTIONS

5. Similarly, in the Sub-Document Attribute section and System Attributes section, click Add to access the sub-document and the system attributes respectively. Note: The Main Document, Sub-Document, and System Attributes sections are only available in the Commerce Library Editor. It is not available in Util Library Function.

CONFIDENTIAL

137

9.3 - USE CASE: FIND AN AVERAGE


Finding an Average

9.3 - USE CASE: find an average

You would like to know what your average monthly sales revenue is for the first six months of the year. You have already checked the Function Wizard and havent found a function that will serve this purpose, so you will need to create one. Monthly Sales Revenue 1,651 65,165 1,321 561 521,321 65,161 Parameters: # 1 Parameter valuesArray Data Type Float Description Represents the sales revenue by month.

Return Type: Integer Example of average

138

CONFIDENTIAL

Dont forget to test your new function in the Debugger. Here is what your test script should look like:

Make sure you create an integer array with the sales values found in the table. Then you will need to return your table. The syntax is: return util.libraryfunctionvariablename(parameters)

LIBRARY FUNCTIONS

What we have returned in the Console are the values of the index+1. Remember that indexes start at 0, so in order to find out how many elements we need to divide by, we need to make sure you add one so it counts from there. The next object that printed was a total of all of the array elements added together. Finally, we return the average.

CONFIDENTIAL

139

9.4 - USE CASE: LINEAR INTERPOLATION


9.4 - USE CASE: linear interpolation
Linear Interpolation Lets assume your sales team works on a commission curve. You have the following table set of defined commissions earned based on the amount of a sale Sales ($) Under 10,000 10,000 30,000 50,000 80,000 100,000 120,000 150,000 250,000 500,000 and Up Commission (%) .5 .6 .7 .8 .9 1.0 1.2 1.5 2.25 3.5

So, you need to be able to determine how much commission a sales team member will earn if they make a sale that falls somewhere in between your defined values. This is done by creating a straight line between two sets of data, a process called linear interpolation. It will essentially fill in the gaps in your table. Your BigMachines application doesnt provide a pre-defined function for linear interpolation, so you need to create one. While this will be used in Commerce, it is better to create it as a Util Library Function in case another administrator finds another use for it. Parameters: # 1 Parameter valueOfSale Data Type Float Description Represents the value of the sale, which will be used to find the relative commission.

Return Type: Float (represents the percentage of commission associated with the sale). What you need to do: Call table and get the sales values that are below the sales amount that was input Find the maximum sales value from the table and store both it and the commission % Call table and get the sales values that are above the sales amount that was input Find the minimum sales value from the table and store both it and the commission % After finding values closest to the sale value, plug the values into the formula to estimate the relative commission

140

CONFIDENTIAL

LIBRARY FUNCTIONS

CONFIDENTIAL

141

9.4 - USE CASE: linear interpolation

142

CONFIDENTIAL

LIBRARY FUNCTIONS

CONFIDENTIAL

143

9.4 - USE CASE: linear interpolation

144

CONFIDENTIAL

ADVANCED USE CASES


In this chapter:

10

Recommended Items Rules Looping Through Line Items Soap Calls in BML

ncluded in this chapter are some of the more common advanced use cases. You will see examples of how to manipulate and populate arrays, loop through line items in commerce and dynamically populate dictionaries with parts data.

CONFIDENTIAL

145

10.1 - RECOMMENDED ITEM RULE


10.1 - RECOMMENDED ITEM RULE
One of the most common uses cases is creating a rule that looks up recommended items from a table . Sample Case You work for an automotive company. You have been tasked with creating a configurator for mid-sized SUVs. There is a configurable attribute named Accessories that has a multi-select menu. Users will select if they would like Exterior, Interior or Outdoor Living accessories for their vehicle. You have decided to save your accessories in a table titled Exterior that contains all of the accessories that are available if the Exterior box is selected. Part Number F25X0001 F25X0002 F25X0003 F25X0004 F25X0005 F25X0006 F25X0007 F25X0008 F25X0009 F25X0010 F25X0011 F25X0012 F25X0013 F25X0014 F25X0015 F25X0016 F25X0017 F25X0018 F25X0019 Type Exterior Exterior Exterior Exterior Exterior Exterior Exterior Exterior Exterior Exterior Exterior Exterior Exterior Exterior Exterior Exterior Exterior Exterior Exterior Name Tail Pipe Cover - Dual Bumper Corner Molding Front Underspoiler Sports Grille Kit Spoiler Fog Lamp Kit Wheel Arch Kit Rear Bumper Underguard Trailer Hitch Hood Protector Rear Bumper Cover Engine Block Healer Front Bumper Underguard Shock Sensor Splash Guard Kit Car Cover Body Side Molding Wheel Locks Bag - Car Cover Price 79.5 60 369.95 277 335 325 399.95 239.95 389.95 72.95 59.95 39.95 289.95 99.95 89.95 99.95 219.95 23.95 9.95

146

CONFIDENTIAL

Just as you are getting started, your manager sends you an email and says management only wants to display items that are more than $100.00 each. The first thing you will want to do is set-up a table call.

ADVANCED USE CASES

CONFIDENTIAL

147

10.2 - LOOPING THROUGH LINE ITEMS

1. Dont forget to click Apply and then Update and Back in the rule. Your code will not be saved if you fail to do so. 2. Next, you will need to deploy your configuration via QuickLinks. 3. Click on Admin>Home Page and refresh your product family. 4. Click on Deployment Center and Deploy your homepage. Now, test your configuration rule. Go to Home> YourProductFamily.

10.2 - LOOPING THROUGH LINE ITEMS


This example is going to cover multiple use cases in one: Looping over line items in commerce Using a table call with getpartsdata() Dynamically populating a dictionary

Continuing along the same lines as Recipe 10.1, we are going to assume that a quote has been created and that you would like to return the price. Go to your Commerce Library to create a new library function. It would be advantageous to select your sub-document attributes before you begin writing your code. You will need to select: _document_number _part_number _part_base_price _price_quantity

148

CONFIDENTIAL

This is the code that you will need to complete this task:

ADVANCED USE CASES

CONFIDENTIAL

149

10.2 - LOOPING THROUGH LINE ITEMS

After you have written your code, you will want to run it through the Debugger. In order for it to work, you will need to have created a quote and obtained the transaction ID.

You will need to put the transaction ID into the Data Import text area and click Import. If you notice, under the Line Item tab, it has listed the values for the Sub-Document attributes you selected before writing your code. You can see that Line Item 2 contains part F25X0035 with a price of $229.95. Once this is done, you can run your code in the Debugger.

To breakdown what you see in the Console: The first line represents the partsArray that was created when you looped through the line items. The second line shows the DocumentNumbers that were appended in that same loop. The third line shows the array that you created using getpartsdata(). Next we have a print of the partsDict. You should have created a loop through the array of those values and put them in the dictionary where the part number is the key and the price is the value. The last line is the return string.

150

CONFIDENTIAL

10.3 - SOAP CALLS IN BML


Please see code below for using SOAP calls in BML. Along with the comments in the code, this is what is being accomplished: 1. Upload an XML template to the file manager, But first put in variables that can be replaced using BML 2. Post the XML in BML using urldatabypost 3. Replace the variables in the XML with the ones required 4. Post the new XML to the BigMachines SOAP receiver XML 5. Receive the response and parse it as required

ADVANCED USE CASES

CONFIDENTIAL

151

10.3 - SOAP CALLS IN BML

10.3 - SOAP CALLS IN BML

152

CONFIDENTIAL

Here is a sample of the XML that is being used in the soap call.

ADVANCED USE CASES

CONFIDENTIAL

153

10.3 - SOAP CALLS IN BML

154

CONFIDENTIAL

11
TROUBLESHOOTING
In this chapter:

Common Error Messages Tips Best Practices

t takes time, patience and utilisation to become very proficient in scripting with BML. You will only get better with time. A very effective way to learn is to start troubleshooting your own code. if you receive the same error message a few times in a row, its likely that you wont continue to make that mistake as you move forward. This chapter illustrates some of the most common error messages and provides tips for BigMachines Best Practices when using BML.

CONFIDENTIAL

155

11.1 - COMMON ERROR MESSAGES


11.1 - COMMON ERROR MESSAGES
There are number of error messages that you may come across while using BML. This recipe provides a comprehensive list of those you might find and how to correct them. Compilation Errors

One of the most common error message is the one shown above and you will see it if you forget to close a statement with a semi-colon (;). As you can see, the message tells you what line and index your error occured so that you can correct it. Notice that the errors will display above the tabs in the function editor.

The error message about is quite self-explanatory. You are missing a return statement. Remember that BML will not being compiling your code without one.

Notice that this error message is saying it has come across a semi-colon, which ends a statement, but it should have encountered something else first. It was either expecting a curly bracket, which are used with conditional functions and arrays, or it was looking for an operator. Use the line and index to double-check your code.

156

CONFIDENTIAL

You will see this error message any time you have a variable that is not intialized. This can be caused by a number of errors. In order to fix the issue, try doing one of the following Make sure that your variable in question is spelled the same way wherever it is being used. Verify that your string variable are in double-quotations.

This error message can be slightly confusing. In this is example, the message is telling us that the data type of the return value should be a string. What it is really saying is, the wrong return data type is being used for the code you have written. Lets say you have just written a code in the Util Library using the getpartsdata() function. We know that the return type for that function is a 2-D string array. However, we have accidently selected String from the Return Type drop-down menu. This is the exact message that you will see. You do not need to re-write your code in order to change the value to string, you can simply change the Return Value to String[][] and the message will disappear.

TROUBLESHOOTING

This is a message similar to the first one we discussed. Make sure that you have a a semi-colon at the end of each statement. If you dont, the compiler will think that you meant to use an operator to combine two lines of code.

CONFIDENTIAL

157

11.2 - TIPS AND REMINDERS


Here are some general tips and Best Practice pointers to help troubleshoot the most common errors that they come across. Our world-class Customer Services technicians provided us with some common errors and fixes that you may come across when working within BigMachines. For all functions that are compatible in 1-D arrays only, you can loop through a 2-D array to populate a 1-D array and then use those functions. Use $BM_UNCHANGED_NUM$ or $BM_UNCHANGED_STR$ to keep the value of an array unchanged or constant. When creating a constraint rule, make sure to use the syntax A |^| B. Take advantage of the function wizard!! As this cookbook shows, there are many predefined functions that can help you. Create your attributes at the highest level possible in the hierarchy. For example, if you try to make changes to a model when the attribute and all rules that are associated with that attribute is actually at the Product Line level, your rule will not reflect the changes you made at the model level. A rule will not work if your chosen condition attribute or action input attribute is not in the configuration flow or if that attribute is inactive. Pay attention to the expected format of return value. Look at the example below and you will see the return will be (item1~quantity1~comment1~price|^|item2~quantity2~comment2~price2)

11.2 - TIPS AND REMINDERS

11.3 - BEST PRACTICES FOR BML


General Always put the name of the rule and location in the first line of code (say what it is and where it is). This aids in global script searches. For example // Update Line Items Advanced Modify Function // Commerce Quote Header Update Line Items action Us if elif, else structures, not if, if,if Keep variable name and attribute name similar. Menu values and variable names to match where possible (illegal characters and integration)

158

CONFIDENTIAL

General (continued) Do not use special characters in attribute or variable names (Cant have , &). Do NOT use the following delimiters in any data ~ or , or | or ^ or |^|. |^| is only used when you need to constrain and/or in Recommended Item rules. If delimiters are needed, we suggest ** or or && or $,$. Using items listed as DO NOT USE can cause unforeseen issues and create major problems, such as preventing site upgrades. Always use new format instead of legacy where the choice is available (Recommended Items as shown in the image on the previous page. )

Commerce Keep in mind the order of operations Defaults (Advanced Default / Attribute Level) Modify (Advanced Modify / Modify Tab) Put all commerce BML in libraries (9.0+) Comment the library function Comment the calling function Looping No nested loops Select variables carefully at the line level Keep in mind the difference between document number and sequence number Dont modify system generated attributes (any attributes that start with _) Be aware of and use system generated actions (Update Lines, Add Line, Reconfigure, Autofill)

TROUBLESHOOTING

Line item looping always on the advanced modify / default Return format [docNo]~variableName~variableValue| Never use summation attributes Never use _config_attributes or _config_attr_text, use _config_attr_info instead Make sure to transition document out of start step When defining attributes use _quote and _line suffixes as well as camelCase Do not use the Line sub-tab on the Modify tab of the _update_line_items Commmerce Header action. Ensure to keep the default settings of Save to Form. This will prevent performance issues.

CONFIDENTIAL

159

11.2 - TIPS AND REMINDERS

160

CONFIDENTIAL

CONFIDENTIAL

161

INDEX
1-D Arrays 97 2-D Arrays 98 acos(x) 63 arrayFunctionTest(UserInfo, SortDirection, MaxValue, MinValue, UseZero) asin(x) 62 atan(x) 64 Before You Begin 89 Color of Syntax 20 Commerce 155 Commerce Debugger 26 Commerce Function Editor 24 Commerce Library Debugger 26 Commerce Library Function Editor 24 Commission (%) 136 Compilation Errors 152 Configuration 25 Configuration/Util Library Function Editor 23 Control Attribute 88 cos(x) 60 Definition of Button 20 Example of acos(x) 63 Example of addDays(date, num_of_days) 76 Example of an array attribute (buyside) 88 Example of append( 100 Example of asin(x) 62 Example of atan(x) 64 Example of atof(str) and atoi(str) 36 Example of atof (str)/atoi(str) error messages 35 Example of average 134 Example of break 84 Example of ceil(x) 52 Example of containskey(dictIdentifier, key) 118 Example of continue 85 Example of cosh(x) 66 Example of cos(x) 60 Example of datetostr(date) 72 Example of dict() 116 Example of exp(x) 54 Example of fabs(x) 53 Example of findinarray(arrayIdentifier, element) 104 Example of find(str, substring, [start], [end]) 42 Example of find(str, substring, [start], [end]) 43 Example of float[n] 93 Example of float[n][n] 96 Example of fmod(x,y) 55 162 CONFIDENTIAL

110

INDEX

Example of for...loop in a 1-D Array 82 Example of for...loop in a 2-D Array 83 Example of getarraystr() 127 Example of getconfigattrvalue() 128 Example of getdate() 70 Example of get(dictIdentifier, key) 117 Example of getdiffindays(date 1, date 2) 77 Example of getpartsdata() 125 Example of gettabledata() 123 Example of hypot(x,y) 58 Example of if... 80 Example of if...else 81 Example of integer[n] 92 Example of integer[n][n] 95 Example of integer(x) 50 Example of invoke() 126 Example of isempty(arrayIdentifier) 106 Example of isleap(year_num) 71 Example of isnumber(str) 39 Example of isweekend (date) 70 Example of join(str_Array, delimiter) 109 Example of len(str) 38 Example of ln(x) 57 Example of log(x) 56 Example of makeurlparam() 119 Example of max(arrayIdentifier) 103 Example of minusdays(date, num_of_days); 75 Example of pow(x,y) 54 Example of put(dictIdentifier, key, value) 116 Example of range(x) 99 Example of remove(arrayIdentifier, removePos) 101 Example of replace(str, old, new, [n]) 41 Example of reverse(arrayIdentifier) 105 Example of round(x) 51 Example of sinh(x) 66 Example of sin(x) 60 Example of sizeofarray() for a 1-D array 106 Example of sort(arrayIdentifier, [sortOrder], [sortType]) Example of split(str, separator) 108 Example of sqrt(x) 58 Example of string[n] 90 Example of string [n][n] 94 Example of strtodate(str, format) 73 Example of strtojavadate(str, format) 75 Example of substring(str, start, [end]) 44 Example of tanh(x) 67 Example of tan(x) 61

102

CONFIDENTIAL

163

Example of Test Script 113 Example of trim(str) 40 Example of upper(str) or lower(str) 34 Example of urldatabypost(URL, url_param, default_value) 120 Example of urldatabypost(URL, url_param, default_value) 121 EXAMPLES 14 Example Use Case 76 exp(x) 54 Finding an Average 134 float[n] 93 float[n][n] 96 General 154 General (continued) 155 Highlights of BML 11 hypot(x.y) 58 integer[n] 92 integer[n][n] 94 Linear Interpolation 136 LITERALS 31 ln(x) 56 log(x) 55 max(arrayIdentifier) 103 min(arrayIdentifier) 104 Notes 52 NUMERIC OPERATORS 30 pow(x, y) 53 Remember 59 Remember 62 Return Type Date 74 Return Type Date 75 Sales ($) 136 Sample Case 142 Shortcut 29 SHORTCUTS 29 Since the year 2008 was a leap year, the function returns True. 71 sinh(x) 65 sqrt(x) 57 STANDARD SYNTAX 29 string[n] 90 string[n][n] 93 STRING OPERATORS 31 tanh(x) 67 tan(x) 61 Unitialized arrays 91 USE CASE STRING FUNCTIONS 46 Util Library 28 What are array attributes? 88 What does it do? 29 Where to find the transaction ID 26 164 CONFIDENTIAL

INDEX

CONFIDENTIAL

165

Вам также может понравиться