Server-side Scripting Flashcards
The following are examples of what kind of scripting:
- Update record fields when a database query runs
- Set field values on related records when a record is saved
- Manage failed log in attempts
- Determine if a user has a specific role
- Send email
- Generate and respond to events
- Compare two dates to determine which comes first chronologically
- Determine if today is a weekend or weekday
- Calculate the date when the next quarter starts
- Log messages
- Initiate integration and API calls to other systems
- Send REST messages and retrieve results
Server-side Scripting
Business Rules are server-side logic that execute when?
When database records are queried, updated, inserted, or deleted
When would a “Before” business rule be used?
Before Business Rules execute their logic before a database operation occurs. Use before Business Rules when field values on a record need to be modified before the database access occurs. Before Business Rules run before the database operation so no extra operations are required. For example, concatenate two fields values and write the concatenated values to the Description field.
When would an “After” business rule be used?
After Business Rules execute their logic immediately after a database operation occurs and before the resulting form is rendered for the user. Use after Business Rules when no changes are needed to the record being accessed in the database. For example, use an after Business Rule when updates need to be made to a record related to the record accessed. If a record has child records use an after Business Rules to propagate a change from the parent record to the children.
When would an “Async” business rule be used?
Like after Business Rules, async Business Rules execute their logic after a database operation occurs. Unlike after Business Rules, async Business Rules execute asynchronously.
Async Business Rules execute on a different processing thread than before or after Business Rules. They are queued by a scheduler to be run as soon as possible. This allows the current transaction to complete without waiting for the Business Rules execution to finish and prevents freezing a user’s screen.
Use Async Business Rules when the logic can be executed in near real-time as opposed to real-time (after Business Rules). For example use async Business Rules to invoke web services through the REST API. Service level agreement (SLA) calculations are also typically done as async Business Rules.
Developer Tip:
Use async Business Rules instead of after Business Rules whenever possible to benefit from executing on the scheduler thread.
When would a “Display” business rule be used?
Display Business Rules execute their logic when a form loads and a record is loaded from the database. They must complete execution before control of the form is given to a user. The purpose of a display Business Rule is to populate an automatically instantiated object, g_scratchpad.
The g_scratchpad object is passed from the display Business Rule to the client-side for use by client-side scripts. Recall that when scripting on the client-side, scripts only have access to fields and field values for fields on the form and not all of the fields from the database.
Use the g_scratchpad object to pass data to the client-side without modifying the form. The g_scratchpad object has no default properties.
what are two objects that can be used in business rules script logic?
Hint: one of them can’t be used in “Async” Business Rules
Current and Previous
The syntax for using the current or previous object in a script is:
.
An example script using current and previous:
// If the current value of the description field is the same as when the // record was loaded from the database, stop executing the script
if(current.description == previous.description){
return;
}
What is the purpose of the “Condition” field and what is the correct syntax for it
- Use the Condition field to write Javascript to specify when the Business Rule script should execute.
- Using the Condition field rather than writing condition logic directly in the Script field avoids loading unnecessary script logic.
- The Business Rule script logic only executes when the Condition field returns true. If the Condition field is empty, the field returns true.
This is CORRECT syntax for a condition script:
current.short_description == “Hello world”
This is INCORRECT syntax for a condition script:
if(current.short_description == “Hello world”){}
Here are some excellent examples of condition scripts
- The value of the State field changed from anything else to 6:
- current.state.changesTo(6)
- The Short description field has a value:
- !current.short_description.nil()
- The value of the Short description field is different than when the record was loaded:
- current.short_description != previous.short_description
- The examples use methods from the server-side API.
- The changesTo() method checks if a field value has changed from something else to a hardcoded value
- The nil() method checks if a field value is either NULL or the empty string
- Notice that condition logic is a single JavaScript statement and does not require a semicolon at the end of the statement.
What kind of function is the “executeRule()” function in business rules?
- The function syntax is known in JavaScript as a self-invoking function or an Immediately Invoked Function Expression (IIFE).
- The function is immediately invoked after it is defined.
- ServiceNow manages the function and when it is invoked; developers do not explicitly call Business Rule scripts.
What is the purpose of dot walking?
What is an example of dot walking?
- Dot-walking allows direct scripting access to fields and field values on related records.
- For example, the NeedIt table has a reference field called Requested for.
- The Requested for field references records from the User [sys_user] table. Reference fields contain the sys_id of the record from the related table.
When scripting, use dot-walking to retrieve or set field values on related records. The syntax is:
..
For example:
if(current.u_requested_for.email == “beth.anglin@example.com”){
//logic here
}
The example script determines if the NeedIt record’s Requested for person’s email address is beth.anglin@example.com.
What is the script tree?
This is a new feature that displays as a > on the top of business rule scripts. It quickly creates the path to get to an object in the script
What are some common types of APIs and where can more information about them be found?
- GlideSystem
- GlideRecord
- GlideDateTime
Go into the ServiceNow learning then reference for the APIs available:
https://developer.servicenow.com/dev.do#!/reference
What are some common uses for the GlideSystem API?
Find information about the currently logged in user
log messages (debug, error, warning, info)
Add messages to pages
Generate events
Execute scheduled jobs
…
For Glide Record queries, what are the operators that can be used?
- Numbers:
- =
- !=
- >
- >=
- <
- <=
- Strings:
- =
- !=
- STARTSWITH
- ENDSWITH
- CONTAINS
- DOES NOT CONTAIN
- IN
- NOT IN
- INSTANCEOF
The next() method and a while loop iterates through all returned records to process script logic:
// iterate through all records in the GlideRecord and set the Priority field value to 4 (low priority).
// update the record in the database
while(myObj.next()){
myObj.priority = 4;
myObj.update();
}
The next() method and an if processes only the first record returned.
// Set the Priority field value to 4 (low priority) for the first record in the GlideRecord
// update the record in the database
if(myObj.next()){ myObj.priority = 4; myObj.update(); }
if(myObj.next()){
myObj.priority = 4;
myObj.update();
}
Use the updateMultiple() method to update all records in a GlideRecord.
To ensure expected results with the updateMultiple() method, set field values with the the setValue() method rather than direct assignment.
// When using updateMultiple(), use the setValue() method.
// Using myObj.priority = 4 may return unexpected results.
myObj.setValue(‘priority’,4);
myObj.updateMultiple();
How can i count rows returned in a GlideRecord query and what is the main caveot?
The GlideRecord API has a method for counting the number of records returned by a query: getRowCount().
Do not use the getRowCount() method on a production instance as there could be a negative performance impact on the database.
To determine the number of rows returned by a query on a production instance, use GlideAggregate.
// If you need to know the row count for a query on a production instance do this
var count = new GlideAggregate(‘x_snc_needit_needit’); count.addAggregate(‘COUNT’); count.query(); var recs = 0; if (count.next()){ recs = count.getAggregate(‘COUNT’); } gs.info(“Returned number of rows = “ +recs); // Do not do this on a production instance. var myObj = new GlideRecord(‘x_snc_needit_needit’); myObj.query(); gs.info(“Returned record count = “ + myObj.getRowCount());
What are the scoped GlideSystem API logging methods that get passed to system logs?
gs. info()
gs. warn()
gs. error()
gs. debug() (must be enabled)
All of the logging methods write to the System Log. Pass strings, variables that resolve to strings, or methods that resolve to strings into the logging methods.
The following is how to log messages in a business rule:
Flip to see results
Results attached
The scoped GlideSystem API has a gs.debug() method. By default, the scoped GlideSystem debug() method does not write to the Application log when the gs.debug() method is used in a script.
How can you enable the gs.debug() method
create or modify the application property with the name syntax .logging.verbosity.
Set the Value field in the .logging.verbosity property to debug to log debug messages from the gs.debug() method to the Application Log.
For all other log levels, set the Value field to a comma-separated list of desired log levels. Do not use spaces in the Value field.
How can a Business Rule “Condition” field script be debugged?
Enable detailed Business Rule Debugging (System Diagnostics > Session Debug > Debug Business Rule (Details))
Open the form that contains the business rule and trigger the business rule to run
Logging information is written to the Session Log
What is Script Tracer and what does it display?
debugs synchronous, server-side scripts which are executed as part of an application’s logic.
Return to the form being debugged and make whatever change is needed to trigger the scripts being debugged. The Script Tracer begins tracing when a UI Action, such as the Save or Update button is clicked, or some other transaction occurs.
The Script Tracer table displays a list of server-side scripts and UI Actions that executed during the tracing period. Errors are indicated by a red circle with a white X to the left of the table row.
What is the “Script Debugger”
Primary debugging strategy for Business Rules and other synchronous server side scripts
- Set, remove, and pause at breakpoints
- Step through code line-by-line
- Step into and out of functions and method calls
- View the values of local, global, and private variables
- View the call stack
What are “Breakpoints”?
To whom do they apply?
Breakpoints pause script execution to give developers the chance to examine variables and their values.
The script debugger status bar indicates whether scripts are paused at breakpoints or waiting for breakpoints to be reached.
Breakpoints are session-specific. Setting breakpoints affects script execution only for the developer who set the breakpoint.
How do you set a breakpoint?
how are breakpoints indicated in a script once set?
click in the gutter for the line of interest (the number on the left of the line of script).
They are shown by highlighting the number in the gutter in purple (yellow for conditional breakpoints), and a gray background on the line of script
What is a conditional breakpoint?
This is simply a breakpoint that will only pause the script if the condtion returns true. To set such a breakpoint simply click in the gutter, add condition and type in a server side condition script to validate
EX:
current.short_description != “”
Note: a semi colon can be used to end the condition but is not required