0% found this document useful (0 votes)
189 views

Script Lab

This document contains code snippets and descriptions for 8 exercises demonstrating advanced scripting and debugging techniques in ServiceNow. It includes examples of business rules, client scripts, background scripts, script includes, and making AJAX requests to check inventory and notify users. The exercises cover topics like adding comments when closing an incident, setting priority based on category, displaying info to users, updating fields on change, disabling users, extending script includes, and checking laptop capacity before allowing an order.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
189 views

Script Lab

This document contains code snippets and descriptions for 8 exercises demonstrating advanced scripting and debugging techniques in ServiceNow. It includes examples of business rules, client scripts, background scripts, script includes, and making AJAX requests to check inventory and notify users. The exercises cover topics like adding comments when closing an incident, setting priority based on category, displaying info to users, updating fields on change, disabling users, extending script includes, and checking laptop capacity before allowing an order.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Script Lab 1

Script Lab
Temporary Page for Knowledge 11 Advanced Scripting & Debugging Lab

Business Rules

Exercise 1: Incident Close Comment


/*
* Business rule - incident, before update
* k11 Exercise 1 - Incident Close Comment
* condition: current.incident_state.changesTo("Closed")
* description: add a comment on close
*/

//add comment when closing


current.comments = "Closed by " + gs.getUserName() + " at " +
gs.nowDateTime();
gs.addInfoMessage("Close comment added");

// Debug info
//gs.addInfoMessage("(InfoMessage) Incident state = " +
current.incident_state); //output to app
//gs.log("(Log) Incident state = " + current.incident_state); //output
to system log
//gs.print("(debug print) Incident state = " + current.incident_state);
//output to debug console

Exercise 2: Incident Priority Change


/*
* Business rule - incident, before insert/update
* k11 Exercise 2 - Incident Priority Change
* condition - current.category == "hardware"
* description: set hardware incidents to P1
*/

current.priority = 1;

Exercise 3: Display Info


/*
* Business rule - incident, after insert/update
* k11 Exercise 3 - Display Info
* condition - current.category == "software"
* description - display some information to the user
*/

try {
Script Lab 2

//output current number


gs.addInfoMessage("Current number: " + current.number);

//output current short_description


gs.addInfoMessage("Current Short Description: " +
currrent.short_description);

//output current category


gs.addInfoMessage("Current Category: " + current.category);
}
catch(err) {
gs.log("Error in k11 Exercise 3 business rule: " + err);
}

Client Scripts

Exercise 4: Category onChange


/*
* Client script - incident, onChange of category
* k11 Exercise 4 Request Category
* Description: set urgency to low for request category, add jslog
comment
*/

function onChange(control, oldValue, newValue, isLoading, isTemplate) {


if (isLoading || newValue == '')
return;

if (newValue == "request") {
g_form.setValue("urgency", 3);
jslog("k11 Exercise 5 Request Category client script: Setting
urgency to low for requests");
}
}

Background Scripts

Exercise 6: Disable Users


disableUsers();

function disableUsers() {

//query active user records with first name b*


var users = new GlideRecord("sys_user");
users.addQuery("first_name", "STARTSWITH", "b");
users.addActiveQuery();
Script Lab 3

users.query();
gs.print("User query: " + users.getEncodedQuery() + " = " +
users.getRowCount());

while (users.next()) {
//deactivate user
users.active = false;
//users.update();
gs.print(users.getDisplayValue() + " was disabled");
}
}

Script Includes

Exercise 7: Extending TableUtils Script Include


/*
* Testing TableUtils getTables from background script
* enumerate java array list
*/
var util = new TableUtils("cmdb_ci_server");
//get tables returns a java array list object, not array
var tables = util.getTables();
gs.print("Java list: " + tables);
JSUtil.logObject(tables, "tables");

//enumerate java list


for (var i=0; i < tables.size(); i++) {
gs.print(tables.get(i));
}

/*
* new script include that extends TableUtils so we can add our own
logic
*/
var MyTableUtils = Class.create();

MyTableUtils.prototype = Object.extendsObject(TableUtils, {
getTablesArray: function() {
var tables = this.getTables();
return j2js(tables);
},

type: "MyTableUtils"
});

/*
* Testing MyTableUtils getTablesArray from background script
* enumerate javascript array instead of java array list
Script Lab 4

*/
var util = new MyTableUtils("cmdb_ci_server");
//call our new method
var tables = util.getTables();
gs.print("Java list: " + tables);
JSUtil.logObject(tables, "tables");
gs.print("");
var tablesArray = util.getTablesArray();
gs.print(tablesArray);
JSUtil.logObject(tablesArray, "tablesArray");
//what is util object
JSUtil.logObject(util, "util");

AJAX

Exercise 8 Catalog Capacity Check


/*
* Catalog client script - onLoad Development Laptop
* Description - AJAX request to check laptop inventory and notify user
*/

function onLoad() {
// new GlideAjax object
var gajax = new GlideAjax("CapacityCheckAjax");
// add parameter to call function we need
gajax.addParam("sysparm_name", "checkDevCapacity");
// submit to server, call ajaxResponse function with server response
gajax.getXML(ajaxResponse);

function ajaxResponse(serverResponse) {
var result = serverResponse.responseXML.getElementsByTagName("result");
var inStock = result[0].getAttribute("found_one");
var stockCount = result[0].getAttribute("stock_count");
var reservedComputer = result[0].getAttribute("reserved_computer");
if (inStock != "true") {
alert("We currently don't have any in stock so you order may be
delayed");
return;
}
if (reservedComputer) {
alert("There are currently " + stockCount +
" in stock, we have reserved device " + reservedComputer +
" for you");
} else {
alert("There are currently " + stockCount + " in stock");
Script Lab 5

}
}

/*
* k11 CatalogCapacityCheck script include
* Description - handle catalog client script AJAX request to check
laptop inventory
*/

var CapacityCheckAjax = Class.create();


CapacityCheckAjax.prototype =
Object.extendsObject(AbstractAjaxProcessor, {

// set come global properties so we only have to update them in


one
// place
DEBUG_ENABLED : true,
FOUND_ONE : "found_one",
COMPUTER : "cmdb_ci_computer",
DEV_MODEL_ID : "d9d7f2c54655645600d356aab990865f",
IN_STOCK : 6,
RESERVED : 9,
STOCK_COUNT : "stock_count",
RESERVED_COMPUTER : "reserved_computer",

ajaxFunction_checkDevCapacity : function() {
// add some error handling
gs.log("RUNNING checkDevCapacity");
try {
this._debug("_checkDevCapacity starting");

// build new response xml element


var result = this.newItem("result");

// set result to false just in case we fail somewhere


result.setAttribute(this.FOUND_ONE, "false");

// query dev type computers for in stock


var comp = new GlideRecord(this.COMPUTER);
comp.addQuery("install_status", this.IN_STOCK); // in
stock
// status
comp.addQuery("model_id", this.DEV_MODEL_ID);
comp.query();

// get the count of available computers


var stockCount = comp.getRowCount();
this._debug("_checkDevCapacity query: " +
Script Lab 6

comp.getEncodedQuery()
+ " returned " + stockCount);

// out of stock, exit


if (stockCount == 0) {
return;
}

// we have some so keep going


// get the first available computer
var computerToHold = comp.next();

// place one on hold for the current user


// pass computer object to the allocate function
if (this._allocateComputer(comp)) {
result.setAttribute(this.RESERVED_COMPUTER,
comp
.getDisplayValue());

// populate result payload for the client


processing
result.setAttribute(this.FOUND_ONE, "true");
result.setAttribute(this.STOCK_COUNT,
stockCount);
}
} catch (err) {
gs.log("ERROR - " + this.type + "(" + err + ")");
}
},

/*
* Hold this computer for this user in case they order should
have job to
* cleanup reserved but never ordered
*/
_allocateComputer : function(/* GlideRecord */computer) {
try {
computer.setValue("install_status", this.RESERVED);
computer.setValue("assigned_to", gs.getUserID());
computer.update();
this._debug("_allocateComputer: reserved "
+ computer.getDisplayValue() + " for " +
gs.getUserName());
return true;
} catch (err) {
gs.log("ERROR - " + this.type + "(" + err + ")");
}
Script Lab 7

},

/*
* Centralized debug logging
*/
_debug : function(msg) {
// exit early if not debugging
if (!this.DEBUG_ENABLED) {
return;
}
gs.log(this.type + ": " + msg);
},

type : "CapacityCheckAjax"

});

/*
* testing AJAX call and response from javascript executor
*/

var gajax = new GlideAjax("CapacityCheckAjax");


gajax.addParam("sysparm_name", "checkDevCapacity");
gajax.getXML(ajaxResponse);

function ajaxResponse(serverResponse) {
alert(serverResponse.responseText);
}

Jelly

Exercise 9: Jelly Debugging


<!-- k11_test UI Page -->

<?xml version="1.0" encoding="utf-8"?>


<j:jelly trim="false" xmlns:j="jelly:core" xmlns:g="glide" xmlns:j2="null" xmlns:g2="null">

<table style="padding-left:2px" class="wide" cellspacing="0">


<tr class="header">
<td class="column_head" align="left">
Title: ${sysparm_title}
</td>
</tr>
</table>

<!-- set a variable -->


<j:set var="jvar_p1_test" value="Cached Value From Phase 1" />
Script Lab 8

<j2:set var="jvar_p2_test" value="My Phase 2 Value" />

<g2:evaluate var="jvar_session" >


var session = new GlideRecord("v_user_session");
session.addQuery("user", gs.getUserName());
session.query();
session.next();
session;
</g2:evaluate>

<g2:evaluate var="jvar_session_query_debug">
session.getEncodedQuery() + " = " + session.getRowCount();
</g2:evaluate>

<g2:evaluate var="jvar_session_total_transactions">
session.total_transactions;
</g2:evaluate>

<j2:set var="jvar_last_transaction" value="${session.last_transaction}" />

<!-- include a macro -->


<g:inline template="k11_macro_test.xml"/>
</j:jelly>

<!-- k11_macro_test ui macro -->


<?xml version="1.0" encoding="utf-8" ?>
<j:jelly trim="false" xmlns:j="jelly:core" xmlns:g="glide" xmlns:j2="null" xmlns:g2="null">

<g:breakpoint id="phase 1 k11_macro_test"/>


<g2:breakpoint id="phase 2 k11_macro_test"/>
User: $[gs.getUserName()]<br/>

Phase 1 Test Message {}: ${jvar_p1_test}<br/>


Phase 1 Test Message []: $[jvar_p1_test]<br/>

Phase 2 Test Message {}: ${jvar_p2_test}<br/>


Phase 2 Test Message []: $[jvar_p2_test]<br/>
</j:jelly>

Display Business Rules

Exercise 10 Problem Client Script


/*
* k11 Exercise 10 Send data to the client
* Business rule - problem, display
* Desciption - send data to client for use in client script k11 notify
Script Lab 9

on old problems
*/

//display business rule on problem


//get the record sys_created_by value and add to the client scratchpad
g_scratchpad.created_by = current.sys_created_by;
gs.print("SCRATCH Createdby = " + g_scratchpad.created_by);

//calculate the age of this record


var age = gs.dateDiff(current.sys_created_on, gs.nowDateTime(), true);
var daysOld = Math.round(age / 3600 / 24);
g_scratchpad.days_old = daysOld;
gs.print("SCRATCH age = " + g_scratchpad.days_old);

/*
* Client Script k11 Exercise 10 - notify on old problems
* problem onLoad
* Description - get data from display business rule and alert user on
old problems
*/

function onLoad() {
//get data from display rule scratchpad
var createdBy = g_scratchpad.created_by;
var daysOld = g_scratchpad.days_old;

if (parseInt(daysOld) > 30) {


alert("This is an old record created by " + createdBy);
}
}
Article Sources and Contributors 10

Article Sources and Contributors


Script Lab Source: http://wiki.servicenow.com/index.php?title=Script_Lab Contributors: G.yedwab, John.roberts, Neola, Steven.wood

You might also like