Custom Code Snippets

Some scripts require more complexity than Studio actions alone can provide. Studio allows you to add custom code to your scripts. This allows you to customize your scripts to meet your organization's needs.

Custom coding requires some scripting or programming knowledge. Studio uses a custom programming language called Snippet. NICE CXone developed this language for use in Studio. A complete technical reference guide is available in the online help so you can learn to use this language.

Key Facts About Snippets

  • Code snippets can help improve the organization and efficiency of your scripts. They increase your control over the processes that execute, as well as when and how they execute. You can create your own variables and objects and add programming logic using statements such as IF, FOR, FOREACH, and others.
  • Some products and features require snippets, but you can use them in your scripts even when they're not required.
  • When a product or feature requires code snippets, the online help provides detailed information about the snippets you need to include. Examples of scripts are provided to show how to use the code snippets in scripts. Additional scripting may be required to implement the products or features.
  • The Snippet scripting language is built on the .NET framework. It executes server-side and compiles into MSIL (Microsoft Intermediate Language) just as C# and Visual Basic .NET do.

Snippet Action

To add custom code to your scripts, you need a Snippet action. You can double-click this action to open an editor window where you can add your custom code. You can also debug the code in the editor window. You may need more than one Snippet action in your script. If you use multiple actions, update the Caption field of each one with a phrase that helps identify its purpose.

Placement of a Snippet action matters. If a Snippet assigns a value to a variable, it must be placed before the action that needs the value. On the other hand, if a Snippet contains decision-making code that acts based on a value passed to it, the Snippet must be placed after the action that provides the value.

Snippets Compared to Actions

Some of what you can do in snippets can also be done using Studio actions. For example, there are actions for IF and FOR statements. There's also the ASSIGN action, which you can use to create a custom variable and assign it a value. Using these actions is an acceptable way to add these capabilities to your script. However, using snippets is more efficient.

By placing code in snippets, your script is cleaner, more organized, and easier to navigate. This makes your job as a scripter easier and more efficient. If you make it a habit to always declare variables in snippets, then in the future if you need to locate a particular declaration, you have fewer places to look.

Add Custom Code to a Script

The Snippet action allows you to add custom code to your scripts. This action is located in the Advanced section of the default palette on the Tools tab.

  1. In Studio, open your script.
  2. Place a Snippet action in your script wherever you need the code and connect it to the other actions.
  3. Double-click the action to open the editor window. This is where you can add your code.
  4. Click the tab you want to use to add your code. Each tab provides a different method of adding code. The tabs are:

  5. Debug your code, if you want to.

  6. Click Apply at any time to save your changes without closing the editor window.
  7. Click OK when you're finished editing the code.

Code with Text View

The Text View tab in the Snippet window allows you to write your Snippet code by hand. A complete reference guide is available in the online help so you can learn to use this language.

  1. In Studio, open your script.
  2. Add the Snippet action to your script and double-click on it to open the Snippet window.
  3. On the left side of the Tree View tab, enter your code. You can type the code in or copy and paste it from another source, such as this help site or another script.
  4. Click the Tree View tab at any time to add code from the predefined keywords. You can use the up and down arrow buttons to move code related to a keyword to a different spot in the script.
  5. Click the Check Syntax icon The Check Syntax icon, three small green circles with a triangle pointing to the right. to verify that your syntax for the current code is correct. The status field in the toolbar at the bottom of the Text View tab displays the status Okay if there are no errors. If there are errors, a pop-up message about the error appears and the status field in the toolbar displays a message. For example, the message might read Error at line 4.
  6. Click the Comment icon The Comment icon, an open angle bracket and a closed angle bracket with a blue forward slash in between them.  to convert the line where the cursor currently sites into a comment.
  7. Click the Uncomment icon The Uncomment icon,  a large red forward slash superimposed over an open angle bracket and a closed angle bracket with a forward slash between them. to remove the comment characters from the line where the cursor currently sits.
  8. Click Apply at any time to save your changes without closing the editor window.
  9. Click OK when you're finished editing the code.

Code with Tree View

The Tree View tab in the Snippet Properties window guides you through the process of creating custom code. A predefined set of keywords is available for you to choose from.

  1. In Studio, open your script.
  2. Add the Snippet action to your script and double-click on it to open the Snippet window.
  3. Click the plus icon A plus sign with an arrow next to it pointing down. at the bottom of the Tree View tab.
  4. Select the keyword you want to add to your code.
  5. Click the keyword that appears in the list on the left side of the window to view its properties.
  6. Configure the keyword's properties in the list on the right side of the window. You can: 

    • Select each property to view a definition of the property in the space below the right pane.
    • Refer to the Snippet Keywords section on this page for details about configuring each command.
  7. Add more keywords as needed.
  8. Click the Text View tab at any time to view the code written out in traditional coding format.
  9. Click Apply at any time to save your changes without closing the editor window.
  10. Click OK when you're finished editing the code.

Debug Snippet Code

The Snippet action has its own debugger that you can use to check the code. You can only debug code from the Text View tab.

If you created your code on the Tree View tab, you can use the debugger if you switch to the Text View tab. If the debugger finds any issues, use the specified line number to determine which part of the code contains the issue. You can then return to the Tree View tab to correct the problem.

More debugging options are available, including stepping through the code line by line and using breakpoints. You can also use TRACE statements in snippet code to output text during debugging. This output can be useful when solving problems in your script.

  1. In Studio, open a script containing a Snippet action.
  2. Double-click on the Snippet action.
  3. Add Snippet code on the Text View tab, if it doesn't already contain some.
  4. On the right side of the Snippet editor window, click the Debugger tab.
  5. Click the down-arrow button on the right side of the Debug icon An icon of a window with a green right-facing triangle. On the right side of the icon is a down-facing black triangle that opens a drop-down menu. and select StartAn icon of a green play button triangle. .
  6. If there are any syntax errors in the code, the Snippet editor window expands. All errors in the code appear in a pane at the bottom of the window. If there are no errors, skip to the next step.

    1. Correct the errors.
    2. When the errors have been corrected, click the Close or Clear Trace Output icons An X. to close the error pane.
    3. Start the debugger again.
  7. View the contents of the Variables as Text tab. The tab shows the variables and their values when all of the code has been executed if you didn't set a breakpoint.
  8. You can select one or more lines in the snippet code and click the Comment out selected lines icon An icon with open and closed angle brackets next to each other with a blue forward slash between them. . This is helpful if you want to remove some code to see how the outcome of the debugging changes.
  9. You can select one or more lines of commented-out code and click the Uncomment the selected lines icon An icon with open and closed angle brackets next to each other with a forward slash between them. A large red forward slash crosses the other characters. to add those lines back into the snippet.

Snippet Keywords in Tree View

Keywords, or commands, are part of the syntax of statements in the Snippet language. They're pre-defined terms that are reserved for specific uses in scripts. The compiler recognizes the keyword and performs the behavior associated with it. For example, when the compiler sees the ASSIGN keyword, it creates a new variable with the name and value specified after the keyword. For example: ASSIGN varName = 1

Because keywords are reserved terms, these words cannot be used as identifiers for objects or variables in your scripts.

Many of the keywords also have Studio actionsClosed Performs a process within a Studio script, such as collecting customer data, playing a message or music, or routing a contact to an agent. with the same name. For example, there is an IF keyword and an IF action. Both accomplish the same behavior in your script. You can use Snippet actions with custom code to reduce the number of actions in your scripts.

The following sections cover the keyword options available in the Tree View tab. These options include most of the keywords that you can use in snippets. A complete list of all supported keywords is available in the reference section.

Assign

Description: ASSIGN statements create a variable with the name and value you specify.

Studio Action: Assign

Naming Guidelines: Follow these guidelines when naming variables:

  • Use alpha-numeric characters (a-z, A-Z, 0-9).

  • The first character in the name must be a letter.
  • Use the underscore character ( _ ) and the dollar sign ( $ ) anywhere in the name.
  • If the last character in a variable name is a dollar sign, the value is treated as text.
  • Do not use the names of pre-defined variables or reserved words.

Learn More: More information about variables is available on the Variables help page. More information about the ASSIGN keyword is available on the Declaration Statements page.

Tree View Properties

On the Tree View tab, ASSIGN appears as newvar="". It has the following properties to configure:

Example

To see this example in Tree View, copy and paste into the Text View tab, then click the Tree View tab.

ASSIGN varName = value1
varName2 = value2

//Including the ASSIGN keyword is optional. 
//It's best practice to use this keyword every time you create a variable.
//When you use advanced search, you can quickly locate where a variable 
//is created if it includes this keyword. 

Break

Description: Immediately ends a loop.

Syntax: BREAK

Details: When the BREAK statement is reached, the current loop ends immediately. The script continues executing the snippet code below the loop until complete.

BREAK is optional. If it's not included, the loop continues until the defined stop condition is met.

Call Function

Calls a previously-defined function.

Tree View Properties

On the Tree View tab, Call Function appears as newcall().

It has the following properties to configure:

  • Arguments: Enter the arguments that you need to pass into the function. The arguments appear between the parentheses in the function name. For example, functionA (var1, var2).
  • Comment: Add a comment about the variable.
  • Line Number: The line number the command is on in the editor.
  • Name: Enter the name of the function you want to call.

Case

Description: Defines one of a set of possible statements to be executed. Used with SWITCH or SELECT.

Syntax: varies; see SWITCH or SELECT

Studio Action: Case

Details:  CASE must be used in the conditional code block of a SWITCH or SELECT statement. Add one or more CASE statements to define the possible blocks for the script to execute. At least one CASE is required.

Related: Include a DEFAULT statement to define the case that's used if none of the specified CASE statements apply.

Comment

Hides text in the script so the compiler doesn't process it.

Use comments to document your script. You can provide explanations and descriptions of each part of your script so that it's easy to understand later.

Tree View Properties

On the Tree View tab, Comment appears as //.

It has the following properties to configure:

  • Comment: Add a comment.
  • Line Number: The line number the command is on in the editor.

Each of the keywords available in Tree View has a Comment property. This allows you to add a comment about that specific instance of the keyword. Use the Comment option on the Tree View tab to add a general comment about the snippet.

Declare Function

Description: Creates a custom function.

Details: Declare a function by giving it a <name> with a set of open and closed parentheses at the end. For example, FUNCTION functionName(). Add optional [parameters] between the parentheses. Parameters allow you to pass data, called arguments, into and out of the function.

Naming Guidelines: When naming functions, follow these guidelines:

  • Use alpha-numeric characters (a-z, A-Z, 0-9).

  • The first character in the name must be a letter.
  • Use the underscore character ( _ ) and the dollar sign ( $ ) anywhere in the name.
  • Do not use reserved words or the names of built-in functions.

Learn More: More information about functions is available on the Functions help page.

Tree View Properties

On the Tree View tab, FUNCTION appears as FUNCTION newfunc().

It has the following properties to configure:

  • Arguments: Enter the arguments that you want passed into the function. The arguments appear between the parentheses in the function name. For example, newfunc(var1, var2).
  • Comment: Add a comment about the variable.
  • Line Number: The line number the command is on in the editor.
  • Name: Enter the name of the function.

To complete FUNCTION, right-click on SWITCH 0 and add the CASE keyword for each condition you want the script to evaluate. Add a DEFAULT condition to define what the script does when none of the defined CASE options apply. Configure each CASEand the DEFAULT keyword.

Example

To see this example in Tree View, copy and paste into the Text View tab, then click the Tree View tab.

FUNCTION TimerRound(Timer)
{
  IF Timer = "-1"
  {
    ASSIGN Timer = Timer
  }
  ELSE
  {
    ASSIGN PeriodLocation = Timer.indexof('.')
	IF PeriodLocation = 0
	{
	  ASSIGN Timer = Timer
	}
	ELSE
	{
	    ASSIGN DataLength = Timer.length
	    IF DataLength - PeriodLocation <= 2
	        {
	          ASSIGN Timer = Timer
            }   
	    ELSE
	     {
            ASSIGN DigitCheck = Timer.substr(PeriodLocation + 3, PeriodLocation + 3)
            IF DigitCheck >=5 && DigitCheck <= 9
               {
                  ASSIGN Timer = Timer + .01
               }
            ELSE
              {
                 ASSIGN Timer = Timer
              }
		
            ASSIGN Timer = Timer.substr(1, PeriodLocation + 2)
         }
      }
   }
  
   TRACE "{Timer}"
   RETURN Timer
}

IF TEST = 1
   {
      ASSIGN DC1 = "1.931876668494874"
   }   

   ASSIGN DC1 = TimerRound(DC1)

Default

Description: Defines the CASE block that's used if none of the specified CASEs, apply. Used with SWITCH and SELECT.

Syntax: Varies; see SWITCH or SELECT

Details: DEFAULT must be used with SWITCH or SELECT blocks, and there must be at least one CASE statement present. DEFAULT cannot be used on its own. DEFAULT is always optional. It must be the last clause in the list of CASE statements.

For

Description: Repeats a statement or series of statements a specific number of times.

Tree View Properties

On the Tree View tab, FOR appears as FOR i = 1 to 10.

It has the following properties to configure:

  • Comment: Add a comment about the FOR loop.
  • EndValue: Enter the ending index value. The default is 10.

  • Iterator: Enter the name of the variable that holds the current loop index.

  • Line Number: The line number the command is on in the editor.
  • StartValue: Enter the starting index value. The default is 1.

To complete FOR, right-click on FOR i = 1 to 10 and add the keywords and behaviors that you want the script to perform.

Examples

To see these examples in Tree View, copy and paste into the Text View tab, then click the Tree View tab.

IF TEST = 1
{
  ASSIGN Names = "Wes|Nate|Dan|Clay"
  ASSIGN EyeColors = "Blue|Blue|Brown|Brown"
  ASSIGN Signs = "Aquarius|Aries|Pisces|Leo"
  ASSIGN Foods = "Spagetti|Pizza|Sushi|Deep Fried Twinkies"
}

DYNAMIC Persons

ASSIGN PeopleCount = Names.size

FOR i = 1 TO PeopleCount
{
  ASSIGN Persons[i].Name = "{Names[i]}"
  ASSIGN Persons[i].Eyecolor = "{EyeColors[i]}"
  ASSIGN Persons[i].Sign = "{Signs[i]}"
  ASSIGN Persons[i].Food = "{Foods[i]}"
}
FOR i=1 TO 9
{
	a = "{a}{i}"
}
//Result: a="123456789"


FOR i=9 TO 1
{
	b = "{b}{i}"
}
//Result: b="987654321"

ForEach

Description: Repeats a loop once for each element in the specified string array.

Tree View Properties

On the Tree View tab, FOREACH appears as FOREACH i in array.

It has the following properties to configure:

  • ArrayName: The name of the variable containing the array you want the script to apply the defined behaviors to.
  • Comment: Add a comment about the FOREACH loop.
  • Iterator: Enter the name of the variable that holds the current array element.

  • Line Number: The line number the command is on in the editor.

To complete FOREACH, right-click on FOREACH i in array and add the keywords and behaviors to define what you want the script to do with each element in the specified array.

Example

To see this example in Tree View, copy and paste into the Text View tab, then click the Tree View tab.



IF TEST = 1 
{
	ASSIGN Names="Odin|Freya|Thor|Loki"
}
ASSIGN SubCounter=1
FOREACH Name IN Names
{
	IF Name = "Odin" |  Name = "Freya"
	{
		ASSIGN NewNames[SubCounter]= "{Name}"

		ASSIGN SubCounter=SubCounter + 1

	}
}

If

Description: Evaluates an expression and takes a branch based on the results of the evaluation.

Studio Action: If

Tree View Properties

On the Tree View tab, IF appears as >IF 0 with >True and False below it. >IF defines the expression to be evaluated. >True defines what happens if the expression evaluates as true. >False defines what happens if the expression evaluates as false.

It has the following properties to configure:

  • Comment: Add a comment about the If statement.
  • Expression: Enter the condition that you want the script to evaluate.
  • Line Number: The line number the command is on in the editor.

To complete your IF statement, right-click on True and False and select the keyword or behavior you want the script to perform depending on how the Expression evaluates. You don't need to provide options for both True and False. You can add more than one keyword or behavior. Configure the selected keywords or behaviors as required.

Example

To see this example in Tree View, copy and paste into the Text View tab, then click the Tree View tab.

IF TEST = 1
   {
      ASSIGN contactID = "123456780"
      ASSIGN customerName = "XYZ International"
      ASSIGN CBWindowStart = #"{date} 8:00 AM"
      ASSIGN CBWindowEnd = #"{date} 4:30 PM"
   }

//String Comparison

IF customerName = "ABC Corporation"
   {
      ASSIGN contractLevel = "Gold"
   }
   ELSE
      {
         ASSIGN contractLevel = "Silver"
      }

//Numeric Comparision

IF contactID % 10 = 0
   {
      ASSIGN logCall = 1
   }
   ELSE
      {
         ASSIGN logCall = 0
      }

//DateTime Comparison

ASSIGN myTime = #"{time}"

IF myTime >= CBWindowStart && myTime  <= CBWindowEnd
   {
      ASSIGN offerCallback = "True"
   }
   ELSE
      {
         ASSIGN offerCallback = "False"
      }

Repeat

Description: Performs the designated commands a specified number of times.

Tree View Properties

On the Tree View tab, REPEAT appears as REPEAT 0.

It has the following properties to configure:

  • Comment: Add a comment about the repeat.
  • Line Number: The line number the command is on in the editor.
  • Repeat: Enter an expression that evaluates to a numeric value to define the number of times you want the specified behaviors to repeat.

To complete REPEAT, right-click on REPEAT 0 and select the behavior you want the script to repeat. You can add more than one behavior. Configure each selected behavior or behaviors.

Example

To see this example in Tree View, copy and paste into the Text View tab, then click the Tree View tab.


REPEAT 10
{
	phone = "{phone}{random(10)}"
}	

Return

Description: Terminates a function and optionally passes a variable from the function to the script. Use with FUNCTION statements.

Syntax: RETURN or RETURN <var>

Studio Action: Return 

Details: Must be used in the code of a function declaration. Add a variable name <var> after the RETURN keyword to pass information back into the script.

Select

Description: Performs a set of commands based the first expression to evaluate to true.

Tree View Properties

On the Tree View tab, SELECT appears as SELECT 0.

It has the following properties to configure:

  • Comment: Add a comment about the SELECT.
  • Line Number: The line number the command is on in the editor.

To complete SELECT, right-click on SELECT 0 and add the CASE keyword for each expression you want the script to evaluate. Add a DEFAULT condition to define what the script does when none of the defined CASE options apply. Configure each CASE and the DEFAULT keyword.

Example

To see this example in Tree View, copy and paste into the Text View tab, then click the Tree View tab.

SELECT
{
	CASE name="Odin" { agentid = 123 }
	CASE name="Frigg" { agentid = 345 }
	CASE name.length = 0
	 {
	   ASSIGN agentid = -1
	   ASSIGN error = "Invalid name"
	 }
	DEFAULT { ASSIGN agentid = 999 }
} 

Switch

Description: Evaluates the specified variable and takes the action defined by the matching CASE.

Details:  SWITCH compares the value of a variable to the literal value of each CASE. When a matching CASE is found, SWITCH executes and branches to the code in curly braces { ... } associated with the matching CASE.

SWITCH can only evaluate a variable. It cannot evaluate an expression. If you use an expression, your script will not work.

At least one CASE is expected. All CASE statements must have the same type of literal. The first CASE determines the type for the remaining CASE statements . If any CASE statement has a different type from the first CASE, a compiler error occurs. The following are all valid literal types:

  • CASE "john"
  • CASE 512
  • CASE #"5/15/2050"
  • CASE #"6/1/2050 7:00am"
  • CASE #"7am"

For example:

IF TEST = 1
{
  ASSIGN MyDate = "07/03/2023" //This date falls on a Monday
}
ASSIGN MyDow = MyDate.asdatedow
SWITCH MyDow
{
  CASE 0   { ASSIGN NewToday = "Sunday"  }
  CASE 1   { ASSIGN NewToday = "Monday"  }
  CASE 2   { ASSIGN NewToday = "Tuesday" }
  CASE 3   { ASSIGN NewToday = "Wednesday" }
  CASE 4   { ASSIGN NewToday = "Thursday" }
  CASE 5   { ASSIGN NewToday = "Friday"  }
  CASE 6   { ASSIGN NewToday = "Saturday"   }
}

Use Case: SWITCH allows you to have specific outcomes depending on what the specified variable contains. For example, you can have the script evaluate a variable containing area codes. You can define a CASE for each possible area code and have the script add a value to the state variable that matches the state the area code is assigned to. For example:

SWITCH areaCode
{
	CASE 603 { state =  "New Hampshire" }
	CASE 614 { state =  "Ohio" }
	CASE 628 { state =  "California" }
	CASE 646 { state =  "New York" }
	CASE 667 { state =  "Maryland" }
}

To see this example in Tree View, copy and paste into the Text View tab, then click the Tree View tab.

Tree View Properties

On the Tree View tab, SWITCH appears as SWITCH 0.

It has the following properties to configure:

  • Comment: Add a comment about the SWITCH.
  • Expression:

  • Line Number: The line number the command is on in the editor.

To complete SWITCH, right-click on SWITCH 0 and add the CASE keyword for each condition you want the script to evaluate. Add a DEFAULT condition to define what the script does when none of the defined CASE options apply. Configure each CASE and the DEFAULT keyword.

Trace

Description: Outputs text to the result panel of the Snippet editor window when you use the debugger on the Text View tab.

Syntax: TRACE "<value>"

Details: Add a TRACE keyword with any"<value>" that you want to appear in the result panel of the Snippet editor window when you use the debugger. The <value> can be a variable name. TRACE is a helpful tool to use when troubleshooting problems with your code or to help you see what's happening in the script.

This keyword is only for use in Snippet actions. You can safely leave TRACE keywords in your snippets. At runtime they are ignored outside of the debugger tool in the Snippet editor window.

Tree View Properties

On the Tree View tab, TRACE has the following properties to configure: 

  • AllowEscapes: When set to true, you can embed an escape sequence beginning with backslash character (\). The default is false.
  • Comment: Add a comment about the trace.
  • Expression: The text you want to output to the results pane. You can include variables by enclosing them in curly braces { }. For example, {agentId}.
  • Line Number: The line number the command is on in the editor.
Example

To see this example in Tree View, copy and paste into the Text View tab, then click the Tree View tab.

TRACE "this is trace text"
//The text you specify with TRACE appears 
//In the results window when you use the 
//Debugger on the Text View tab. 

Description: Allows you to include a SOAP web service proxy DLL for use within the snippet. The DLL must be compiled by WISDL by NICE CXone.

Syntax: USES "<proxy>.dll"

Studio actionUses

Details: To use a USES statement, the proxy DLL must be located in the root folder of your business unit'sClosed High-level organizational grouping used to manage technical support, billing, and global settings for your CXone environment file server. You can view the files in your business unit on the Browse ACD Files page in CXone.

Learn More: You can learn more about using web service proxies with Studio scripts on the API Calls from SNIPPET Actions help page.

Tree View Properties

On the Tree View tab, Uses appears as USES "".

It has the following properties to configure:

  • Comment: Add a comment about this keyword.
  • FileName: Add the name of the proxy DLL file you want to use within the snippet.
  • Line Number: The line number the command is on in the editor.

Each of the keywords has a Comment property. This allows you to add a comment about that keyword. Use the Comment option to add a comment that's not connected to a specific property.