Day 6

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 96

Service-now.

com
Scripting and API
Overview
APIs 
Application Programming Interfaces are JavaScript classes

Scripting 
Scripting means creating scripts in JavaScript that will run inside or outside the
ServiceNow platform. Jelly scripts are also used in some modules.
Client APIs

 GlideForm (g_form)
GlideForm.js is the Javascript class used to customize forms. g_form is a global
object in the GlideForm class. It is only used on the client (i.e. the web browser).

 GlideUser (g_user)
g_user is a global object in GlideUser (the Javascript class). It can only be used in
client scripts. g_user typically used in Client Scripts and UI Policies but is also
found in UI Actions which run on the client it cannot be used in Business Rules
or UI Actions which run on the server.
GlideForm (g_form)

g_form accesses:
 Display Settings: hideRelatedList(), showRelatedList(), setDisplay(), setvisible()
 Field Information: getValue(), isMandatory()
 Change Field: setMandatory(), setReadOnly()
 Change Choice List: addOption(), removeOption(), clearOptions()
 Form Information: getSections(), getTableName()
 Form Action: save(), submit(), disableAttachments(), enableAttachments()
GlideUser (g_user)

GlideUser contains name and role information about the current user.
Server APIs

 GlideRecord
 GlideElement
 GlideSystem
GlideRecord

 Overview
 GlideRecord is used for database operations . It is an object that contains zero or more
records from one table.
 The field names in a GlideRecord are the same as the underlying database column
names.
 Following APIs is used for database operations :
 Query
 Update
 Insert
 Delete
GlideRecord (Cont.)

 Insert Record
var gr = new GlideRecord(‘incident');
gr.initialize();
gr. short_description = 'first to do item';
gr.description = 'learn about GlideRecord';
gr.insert();
 Update Record
var rec= new GlideRecord('u_samplelab');
rec.addQuery('u_state',"New");
rec.query();
while (rec.next())
{
rec.u_short_description = "Via Business Rule";
rec.u_description = "Via Business Rule";
rec.update();
}
GlideRecord (Cont.)

 Delete Record
var rec = new GlideRecord('incident');
rec.addQuery('active',false);
rec.query();
while (rec.next())
{
rec.deleteRecord();
}
GlideElement

Overview

GlideElement provides a number of convenient script methods for dealing with fields and
their values.
GlideSystem

Overview
The GlideSystem (referred to by the variable name 'gs' in Business Rules)
provides a number of convenient methods to get information about the system,
the current logged in user, etc.

Many of the GlideSystem methods facilitate the easy inclusion of dates in query
ranges and are most often used in filters and reporting. The method Detail is in
three sections:
 General functions: print(), getProperty()
 Date and Time functions: now(), nowDateTime()
 User Session functions: hasRole(), setRedirect(), getUser(), getUserID(),
getUserName()
Client Script
Overview
Client scripts are shipped to the client (the browser), and they run there instead
of on the server. Three types of scripts are supported:
 onLoad(): Runs when a form is loaded
 onChange(): Runs when a particular widget changes value
 onSubmit(): Runs when a form is submitted
Client Script (Cont.)
Field Overview
Client Script (Cont.)
Limitations on Client Script
 Client scripts do not have "current". They don't know what it is. Instead of using
current.incident_state, use g_form.getValue('incident_state'). The field must be on your
form to access it this way.
 If you're using the advanced techniques (described above) to add your own custom event
handlers, please do not overwrite our out of box onChange(), onSubmit(), or onLoad()
handlers. Doing so will have predictably unpredictable results. Feel free to add additional
handlers in this manner however.
 It's important to recognize the order of operations of client side scripts as opposed to
server side business rules. All client scripts execute before any server side business rule is
executed. This means, for example, that if you click the "close ticket" button on an
incident, when your client side script runs, the ticket will not yet be closed. The client
side script, after all, is running before the business rule that actually closes the ticket.
 All onChange() scripts will run when loading a form (because all fields within a form
technically "change" when you load them). This confuses some people, because they
assume that an onChange() script will only run when someone changes the field
manually. In order to prevent a script from running every time a form loads, you need to
add the following lines of code to the top of the script.
if (isLoading) { return; }
UI Policy
Overview
 UI Policy offers an alternative to client scripts for dynamically changing
information on a form. Organizations may use UI Policy to define custom
process flows for tasks.
 Administrators and users with the personalize_rules or ui_policy_admin role can
create UI Policies.
UI Policy (Cont.)
To create a UI Policy, navigate to System UI > UI Policies and click New.
Populate the following fields:
UI Policy (Cont.)
UI Policy (Cont.)
UI Script
Overview
 UI Scripts are client-side JavaScript, as opposed to Script Includes which are
server-side JavaScript.
 UI Scripts provide a way to package JavaScript into a re-useable form. They can
be called from Client Scripts.
UI Script (Cont.)
A UI script consists of the following parts:
 Name - Name of the UI script.
 Active - Indicates whether the script is active. Note that the UI script must
be marked "active" to actually be included by any JavaScripts which may
invoke it. If the UI script is marked "inactive", it will not be included even if
you attempt to do so.
 Description - Describes the purpose of the script.
 Script - The actual script.
UI Script (Cont.)
You can create a UI script and designate it as Global, which makes the script
available on any form in the system.

For example, you can create a UI script that has a function helloWorld(), and
has the Global field checked:

After you create this global UI script, you can call the helloWorld() function
from any client script or UI policy you write.

function helloworld()
{
alert(‘Welcome’);
}
UI Action
Overview
 UI Actions are an easy way to put buttons, links, and context menu items on
forms and lists, making the UI more interactive, customizable, and specific to
user activities.
 These buttons, links, and context menu items can be scripted, making them
more powerful.
UI Actions include:
 Form buttons
 Form context menu items (right-click the header)
 Form links (Related Links in a form)
 List buttons
 List context menu items (right-click a record)
 List choices (at the bottom of a list)
 List links (Related Links at the bottom of a list)
UI Action (Cont.)
A single UI Action can provide any or all of these. UI Actions are found by
navigating to System Definition > UI Actions
UI Action
UI Action field descriptions:
 Show insert: shows a button on new records that have not been inserted
 Show update: shows a button on existing records
 Show multiple update: shows the button on Multiple Record Update forms
 Show query: shows the button on Search forms
 Form button: puts a button on a form
 Form context menu: puts a context menu action on a form (right-click the form header)
 Form link: puts a link in the Related Links section of a form
 List button: puts a button on a list
 List choice: puts a choice in the dropdown at the bottom of a list
 List context menu: puts a context menu action on list rows (right-click a row in a list)
 List link: puts a link in the Related Links section at the bottom of a list
 Name: the label of the UI Action (text on the button, link or context menu item)
 Table: where the UI Action will appear. An extended table also gets its base table's actions (e.g., Incidents get Task actions).
"Global" means all tables
 View: used to restrict UI Actions to a specific view
 Order: defines the display order of UI Actions (buttons left to right, menu actions top to bottom)
 Action name: name by which a UI Action can be referred to in script
 Client: the UI Action will execute its script in the user's browser, not on the server
 Condition: used to restrict when a UI Action will appear
 Script: run when a UI Action is executed
UI Action (Cont.)
Business Rule
Overview
 A Business Rule is a piece of JavaScript configured to run when a record is
displayed, inserted, updated, deleted, or when a table is queried.
 A Business Rule can be set to run before or after the database action has
occurred.
 In the case of a query, the business rule runs before the database operation, so
that the data returned to the user is appropriate to his system privileges (user
roles).
 Note that business rules apply consistently to records regardless of how they are
accessed--through forms, lists, or Web Services. This is one major difference
between Business Rules and Client Scripts, which only apply when editing
through the form.
Business Rule (Cont.)
Business Rule (Cont.)
To create a Business Rule, navigate to System Definition > Business
Rules and click New. Populate the following fields:
Business Rule Scripting
You create scripts in business rules with JavaScript. The following are the
predefined variables that help reference the system:
 current: The current record being referenced
 previous: The record before any changes were made, available on update and delete
operations
 system (or gs): References to GlideSystem functions.
Global Business Rule
 Business Rules marked as running on table Global are loaded and initialized at
the beginning of each interaction between a user and the platform.
 Global business rules ignore the Condition field. Therefore, unless the script is
wrapped in a function, it will run on every interaction between the user and the
platform.
 Global Business Rules that have script wrapped in a function can be called upon
by any script running elsewhere.
 Client scripts and business rules can reference any function defined in a global
business rule.
 Global business rules are useful in defining functions to be used repeatedly by a
variety of scripts.
Glide Ajax
Overview
 The GlideAjax class allows the execution of server-side code from the client.
GlideAjax calls pass parameters to the script includes, and, using naming
conventions, allows the use of these parameters.
Using Glide Ajax
 Initialize GlideAjax with the name of the Script Include that you want to use.
 When creating the Script Include, you must set the name field to be exactly the
same as the class name.
 Specify the parameter sysparm_name. GlideAjax uses sysparm_name to find which
function to use.
 Any extra parameters may be passed in, all of which must begin with sysparm_.
 Avoid using predefined parameter names.
 sysparm_name

 sysparm_function

 sysparm_value

 sysparm_type

 Code is then executed with the getXML() or getXMLWait() functions.


Asynchronous Glide Ajax
There are two parts to this script: client side and server side code.
This code runs on the client (the web browser). Create a Client Script as normal.
This sends the parameters to server, which then does the processing. So that
the client does not wait for the result, a callback function is used to return the
result, passed to the getXML() function.

Client Side Code:


Asynchronous Glide Ajax
Server Side Code:
 The server side code for the above function. Don't make a business rule, but
instead navigate to System Definition > Script Include and create a new script.
Paste in the code below.
 Note: you must set the name of the Script Include to be HelloWorld
 The sys_script_include code must extend the AbstractAjaxProcessor class and be
client callable.
 Function names starting with "_" are considered private and are not callable
from the client.
Synchronous Glide Ajax
 If you prefer to slow down your code you can use getXMLWait(), although it is
recommended that you use getXML with a callback function.
 This code results in a client side alert that says "The Server Says Hello Bob!“
Client Side Code:

Server Side Code


Script Include
Overview
 Script Includes have a name, description and script. They also specify whether
they are active or not, and whether they can be called from a Client Script.
 Script Includes are used to store JavaScript that runs on the server. If a script will
be used multiple times, or if it is particularly complicated, it should be stored as
a Script Include.
 Script Includes only run when they are called by another script. They are
commonly used to extend classes or to create functions.
How do we use Script Include?
 Script Includes are found under System Definition or System UI. You can call
existing Script Includes from a script.
 It is usually best not to modify an existing Script Include. If you want a Script
Include that does something similar to an existing one, copy it and make
changes to the copy.
 In the example, the name of your Script Include is 'NewInclude' and there is a
single function called 'myFunction.
Service-Now Export and Import
Export Data from Service-Now

Data can be extracted in the variety of ways:


 Manually exported by right clicking
 Scheduling a regular or one-time export using Scheduled jobs
 Using Web Services
 Basic Authentication based on direct URL access
 Downloading the entire Database or certain subsets from our system via
HTTPS
We can export (Lower Threshold) 10,000-50,000 (Upper Threshold) records
simultaneously in one time.
When the user has to export more than 50,000 records then break the export into
smaller chunks that does not affect the performance of the platform.
Manually exported by right clicking

Right click on the header


bar

Choose any Format


 Now selecting Export, and choosing the export format (CSV, Excel, PDF,
XML) from a list. Then following pop-up will appear on screen

Download

Now click “Download” option and save it.

Save
Scheduling a regular or one-time export using Scheduled
jobs
Scheduled Jobs are automated pieces of work that can be performed at either
a particular time, or on a recurring schedules. Three kinds of tasks can be
automated:
 Run and distribute a report
 Generate a record (incident, change, configuration item, etc.) from a template
 Run a business rule and do whatever the rule contains
To create a scheduled job navigate to System Definition > Scheduled Jobs
and click New.

To create new
 Now select the appropriate type of Scheduled jobs:

The fields presented will depend on the type of scheduled job required.
Scheduling Reports
 Scheduled Reports are distributed via email. The scheduled reports are
created by an individual whose user account is deactivated might not display
any data.
Scheduling Entity Generation
 To schedule the generation of an entity
Scheduling Script Execution
 This form can include the script field where we can write scripting scheduling. The
form is
Scheduling Special Cases
 We can also schedule reports in daily, weekly, monthly and periodic
schedule.
 To view the scheduled jobs which will run today navigate to System
Scheduler > Today's Scheduled Jobs. As given
Using Web Services

To create web service, navigate to System Web Services > Create New.

Click to create new


Web Service
 When we submit the Web Service record it produce the wsdl url which can be
used by other application to extract data.

wsdl url
Basic Authentication based on direct URL access
 It is based on the model that the user agent must authenticate itself by the
user id and password for each realm. The realm can be considered as the
opaque string that must be compared for equality with the other realms on
that server.
 The server will authorize the request only if it can validate the user-ID and
password.
 The basic authentication scheme is a non-secure method of filtering
unauthorized access to resources on an HTTP server.
Downloading the entire Database or certain subsets from
our system via HTTPS
 HTTPS is Hyper Text Transfer Protocol Secure is a combination of HTTP and
(Secure Socket Layer)SSL/(Transport Layer Security)TLS protocol to provide
secure communication and identification of a network web server.
 It is based on a request /response paradigm
Import Data in Service-Now
Data can be imported in following ways:
 System Import set
 CMDB import
System Import Set
 System Import set is the powerful tool which is used to import data from
various data sources and then map that data into Service-Now tables. To
import set navigate to System Import Set > Load data

Click to import
Data
Load Data
 When user click on the Load Data option then this form will be appear

Enter the address


of file to import
The progress form display:
 State: Complete
 Completion code: Success

To create New
Transform Map
Fill The form and click “Mapping Assist” form link

Click to Map
The mapping form will appear where we have to map the fields

Mapping Field
Click Save to
continue
Then Transform Map form will appear as:

Click Transform
link
Then after importing the progress form will appear with following options as
 State: Complete
 Completion code: Success

See Transform
History and
Import log
Now check out the target table. The data must be available in it as:
Administration
This module can include:
 Data Source
 Transform map
 Scheduled Imports
Data Sources
A data source is a module of Import Set application. It can include a file or a
JDBC connection. The form of Data Source is:

For example we can link files as:


Transform Maps
 This map is a set of fields which determines the relationship between fields in
an import set and the fields in an existing Service-Now table. The form is

As in the above example:


Scheduled Imports
 Scheduled Imports make it is possible to specify that certain import
operations should occur at some regular interval.
Advanced

This module can include following sub-modules:


 Import Sets
 Progress
 Transform History
 Transform Errors
 Import Log
Import Sets
 Table of all import sets. "An import set" is a set of records imported from a
Data source
Progress
 Show the progress of scheduled import set jobs that are running in the
background.

For example in the above import


Transform History
 Log of completed import operations
Transform Errors
 Log of all errors encountered during any import operations.
Import Log
 Log of all Import Set application operations.
Import Set Tables
This module can include following sub-modules:
 Cleanup
 Schedule Cleanup
 Import Set Test
Cleanup
 Graphical tool used for deleting old data or removing no longer needed
import set tables.
Scheduled Cleanup
 Schedule regular deletion of import set data older than a set number of days.
Only data is removed, not the import table itself.
 We can activate this job to ensure that our import tables do not get extremely
large.  Deleting records older than 7 days should be sufficient.
Import Set Test Tables
 Expandable list of previous Import Set will contain references to the most
recent Import Set records that have been uploaded from a data source.
CMDB Import
 Using Discovery application
 A class of integrations with existing configuration management databases
(CMDB) that imports CI's into ServiceNow's CMDB. It is achieved using
Import Sets and JDBC data sources defined and executed via the MID server
(JDBC Probes)
JDBC Probes
 JDBC probes are run on the MID server to query an external database
 These are in XML format stored in the ECC Queue as input
 Probes are used as data collection which are used to collect data from the
machines available in the enterprise network
 JDBC probes are executed via a JDBC data source when an import is running
against the data source. A JDBC data source JDBC probe is described by the
JDBCProbe Topic and the sys_id of the data source in the Source field of the
ECC Queue output record.
We have to activate the plugin Integration - Altiris 2.0, then following
application are get activated
 Integration-Altiris
 Integration-Microsoft SMS/SCCM

After installing the plugin we need to install the MID server in our company
environment
Following modules are available under these applications:
 Setup
 Scheduled Import
 Data Sources
 Progress
 Transform History
Setup
 The Setup module allows the administrator to configure the JDBC data
sources for the external CMDB tables.
Scheduled Import
 Schedule the execution of the import or import immediately
Data Sources

 A list of the pre-configured data sources defining the external CMDB database
Progress
 A historical list of progress on scheduled imports
Transform History
 A historical list of transformations performed during scheduled imports
Reporting
ITSM Platform Reporting
Overview
 Reports allow users to generate charts from any data in the database. Reports
can be used as homepage or content gauges, published to a visible URL, or
scheduled to be run and distributed at regular intervals. Generate reports
from Reports > View / Run.
 You can generate pie and bar charts directly from a list by right-clicking a
column header. For example, in the Incident list, right-click Category and
select Bar Chart. A chart displaying the distribution of categories for incidents
in the list appears.
ITSM Platform Reporting (Cont.)

 ServiceNow puts the power of report creation in the hands of every user of the
system.
 Administrators can create reports that are viewable by specific groups, or by
everybody. Individual users can create custom reports that they can access at
any time.
 Reports can be scheduled for email delivery at specific times of the day, week or
month, internally and externally.
 Any report can be made into a gauge which can be added to a ServiceNow
homepage.
Getting Started with Reporting

View/Run module contains list of available reports. This list will be based on
the role the logged in user has to access individual reports. From this list users
can either create a new report or click on any available report to run it.

To create custom report

List of
available
reports
Getting Started with Reporting (Cont.)

 Existing reports can be modified by an administrator using the


Administration module. This module is not enabled by default, and must be
activated.
 Global reports cannot be edited by non-admin roles; if a non-admin user edits a
global report, it will create a personalized version belonging to them.

List of existing Reports


Getting Started with Reporting (Cont.)

 Published Report module contains all published reports.


 Published report visible to anyone - without requiring a login.
 Users need the report_publisher role to see the Publish button. Select the
report you want to publish click Publish.
 Copy the link and paste it where you want to distribute it.

URL of published
report
Getting Started with Reporting (Cont.)

 Chart Color module to change the color to the values you want. Colors that are
used in Bar and Pie charts for a particular choice field value are consistently used
across all charts created. For example, priority 1 incidents in a chart will always
have the same color and will not change color based on their relative position
within the chart.
 For choice type fields the colors are automatically assigned to each value
automatically the first time the field is used in a chart.
Color value

Element Value
Getting Started with Reporting (Cont.)

 Color Definition will display the current colors that are defined in your system.
These colors can be referenced from Chart Colors instances. You can add your
own colors if the ones provided are insufficient for your task.
 Fields that are not choice lists will not have the color permanently assigned
automatically by the system and will pick from the default set of colors as the
field is used in a chart. Thus they will NOT have a constant color.
Getting Started with Reporting (Cont.)

Scheduled Reports module is a powerful way to automate distribution of the


current status of your database tables. Instead of spending time creating Access
or Excel reports and emailing them to team members or executives, you can
create a report and let ServiceNow periodically run it and email the output to
the appropriate parties automatically.

Attached Report
Getting Started with Reporting (Cont.)

Summary Sets module contains data from all reports, custom and standard, to
be stored in the sys_report_summary table and separates the data from the
rendering process for all reports.
Report data is periodically purged from the sys_report_summary  table
(approximately every two hours).
Getting Started with Reporting (Cont.)

You might also like