Jun 29, 2023

Create Text file and send to MID Server in ServiceNow

ServiceNow Export Set offers to export data in a limited format, as shown below. This article will discuss how to create a .txt file and export it to MID Server.

To create a text file and send it to a MID Server in ServiceNow, you can combine the file creation and MID Server file transfer steps

Create a text file and attach to the MID Server Attachments (ecc_agent_attachment) record.

Below is the Script Include to create the .txt file and transfer to the MID Server. The Script Include have some functions.
/* esline no-undef:error,no-unused-vars:warning */
var FileTransferUtil = Class.create();
FileTransferUtil.prototype = {
    initialize: function() {},
    CreateTextFilefunction() {
        var fileContent = "This is a sample text file";
        fileName = 'CustomeText.txt';

        var eccAttachment = new GlideRecord('ecc_agent_attachment');
        eccAttachment.initialize();
        eccAttachment.name = 'Export Set Attachment';
        eccAttachment.short_description = 'Exporting Custom Text File:' + fileName;
        var eccAtt_sys_id = eccAttachment.insert();

        var attachment = new GlideSysAttachment();
        var attachmentRec = attachment.write(eccAttachment, fileName, "text", fileContent);
        if (!gs.nil(attachmentRec)) {
            var xmlString = '<?xml version="1.0" encoding="UTF-8"?>' +
                '<parameters>' +
                '<parameter name=\"stream_relay_response_topic\" value=\"ExportSetResult\"/>' +
                '<stream_relay_source attachment_sys_id=\"' + attachmentRec + '\" type=\"AttachmentSource\"/>' +
                '<stream_relay_transform attachment.table_sys_id=\"' + eccAtt_sys_id + '\" order=\"0\" stream_relay_transfer_progress_interval=\"150\" type=\"AttachmentProgressTransformer\"/>' +
                '<stream_relay_sink path="\/' + fileName + '\" type=\"FileSink\"/>' +
                '</parameters>';
            //stream_relay_sink path update as per requirement
            // agent/export/ is base folder
            // Create ECC Record
            var eccQueue = new GlideRecord('ecc_queue');
            eccQueue.initialize();
            eccQueue.agent = 'mid.server.XXXXXXXXX';//MID Server Name
            eccQueue.topic = 'StreamPipeline';
            eccQueue.queue = 'output';
            eccQueue.state = 'ready';
            eccQueue.payload = xmlString;
            eccQueue.insert();
        }
    },
    type: 'FileTransferUtil'
};
Below is how to consume the Script Include

var util=new FileTransferUtil();
util.CreateTextFile();

May 28, 2023

Async Business Rules in ServiceNow

 There are four types of Business Rules in ServiceNow

  1. Before business rules
  2. After business rules
  3. Display business rules
  4. Async business rules

    Business rules in ServiceNow are executed synchronously, meaning they run in the same order as they are defined and block the execution until they complete. However, ServiceNow provides other mechanisms for asynchronous processing and handling long-running tasks. Async Business Rules are best used when you don't want the result to be immediately displayed and do not want to halter the user experience since the control is with the client and in background it is processing. 

    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. 

    When the record is modified and the async rule is triggered, a record is inserted to the sys_trigger table. That record holds a reference to the business rule that we need to run, and to the particular record to use as current within that business rule. 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. When the worker picks up the job, a scripting environment is created. The record is loaded from the database as it is at the time the script runs and is put into the scripting environment as the variable current. You can then interact with that variable as you normally would.

    To see async Business Rules queued up for execution, use the All menu in the main ServiceNow window (not Studio) to open System Scheduler > Scheduled Jobs > Scheduled Jobs. Look for Scheduled Job names starting with ASYNC. They go in and out of the queue very quickly and can be hard to catch on the schedule.


Here are some key points about "async" business rules in ServiceNow:

  •  Asynchronous business rules do not have access to the previous version of a record. 
  • Therefore, the changes(), changesTo(), and changesFrom() GlideElement methods do not work with async rule script. However, the condition builder and condition field (advanced view) both support the changes(), changesTo(), and changesFrom() methods.




 

 

Display Business Rules in ServiceNow

 There are four types of Business Rules in ServiceNow

  1. Before business rules
  2. After business rules
  3. Display business rules
  4. Async business rules

In ServiceNow, Display Business Rules are a type of business rule that allows you to control the visibility and behavior of form elements (fields, sections, related lists, etc.) on a form in the user interface.

Display Business Rules run when a user requests a record/load a form, data has been retrieved from the database, and before the form is presented back to the user.

Display Business Rules use g_scratchpad object to store server-side script results and send them to the client-side. 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.

Client-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.

How to use Display Business Rules:

  • Create a display business rule as per your requirement (conditions).
  • Use g_scratchpad object to store data from server-side and send to the client-side.
  • Use g_scratchpad object properties to manipulate/process form-level data.
// From client script 
if(g_scratchpad.someName == "someValue") { 
  //do something special 
}


After Business Rules in ServiceNow

 There are four types of Business Rules in ServiceNow

  1. Before business rules
  2. After business rules
  3. Display business rules
  4. Async business rules
In ServiceNow, an "after" Business Rule is a customization mechanism used to perform automated actions or logic after a record is inserted, updated, or deleted in a specific table. It is a server-side script that executes after the database transaction has occurred.

The purpose of an "after" business rule is to extend and customize the behavior of the platform by defining additional actions or validations based on changes made to records. It allows you to automate processes, enforce business rules, perform calculations, update related records, send notifications, or integrate with other systems after the record has been saved in ServiceNow. It gives you the ability to write server-side scripts using JavaScript to interact with the ServiceNow platform and perform various operations on the affected record or related records.

By utilizing "after" business rules effectively, you can enhance the functionality and automation capabilities of ServiceNow, aligning it with your organization's unique requirements and processes.

Here are some key points about "after" business rules in ServiceNow:
  • Event Trigger: An "after" business rule is triggered after a specific database operation, such as "insert", "update", or "delete", is performed on a record in the associated table.
  • Execution Timing: The script associated with the "after" business rule executes after the database transaction has completed. This means that the record changes have already been committed to the database.
  • Server-Side Execution: "After" business rules run on the server-side of the ServiceNow platform. They are implemented using server-side JavaScript and have access to the Glide API, which provides a wide range of functionalities for interacting with the platform's data and services.
  • Context and Conditions: You can define conditions or criteria for the business rule to execute. These conditions can be based on the values of specific fields, the user who made the changes, or any other relevant data in the record.
  • Script Logic: The script associated with the "after" business rule can perform a variety of operations, such as querying and updating other records, calculating values, validating data, sending notifications, logging information, or triggering workflows.
  • Extension and Customization: "After" business rules allow you to extend and customize the behavior of ServiceNow beyond the out-of-the-box functionality. They provide a way to implement specific business logic or automate actions based on changes to records.


Some common use cases for "after" business rules include:

  • Field calculations or derivations: You can use the business rule to compute values for certain fields based on the values of other fields. For example, you can automatically calculate the total cost of an order based on the quantity and unit price.
  • Data validation: You can validate the data entered in the record against certain criteria or business rules. For instance, you can check if a user is eligible for a specific service based on their department or role.
  • Sending notifications or alerts: The business rule can trigger notifications or alerts to relevant stakeholders based on the changes made to the record. This can include sending emails, generating notifications within the ServiceNow platform, or triggering external integrations.
  • Updating related records: You can use the business rule to update other records that are related to the changed record. For example, when an incident is resolved, you can automatically update the associated change request or notify the requester.
  • Logging or auditing: The business rule can log the changes made to the record or generate audit records for tracking purposes. This can help in maintaining a record of data modifications and monitoring system activity.


May 26, 2023

Before Business Rules in ServiceNow

There are four types of Business Rules in ServiceNow

  1. Before business rules
  2. After business rules
  3. Display business rules
  4. Async business rules

In ServiceNow, "Before" Business rules are a type of business rule that executes before a record is inserted or updated in the database. These rules allow you to perform actions and validations on the record data before it is saved.

Before business rules are defined with the condition "Before Insert" or "Before Update" and are executed in the order specified by their execution order values. They are typically used to enforce data integrity, perform calculations, set default values, or apply business logic before the record is saved.

Before business rules have the following characteristics:

  • Execution Order: Before business rules are executed in the order specified by their numeric values. Lower numeric values are executed first, while higher values are executed later. This order is important when multiple before business rules are defined for the same table and event.
  • Condition Evaluation: Before business rules evaluate conditions defined in their scripts to determine whether to execute the associated actions. Conditions typically involve checking field values, record state, or other criteria before proceeding with the desired actions.
  • Actions: When the conditions of a before business rule are met, the specified actions are executed. These actions can include modifying field values, performing calculations, displaying messages, or running additional scripts. Before business rules allow you to modify the record data before it is saved to the database.
  • Advance: This section allows to add additional execution condition and logic to manipulate and validate data before storing the data into the database.

Here are some key aspects of before business rules in ServiceNow:

  • Before Insert: A before business rule with the "Before Insert" condition is executed before a new record is inserted into the database. It allows you to perform actions and validations based on the values being inserted.
  • Before Update: A before business rule with the "Before Update" condition is executed before an existing record is updated in the database. It enables you to perform actions and validations based on the updated values.
  • Data Manipulation: Before business rules provide the ability to modify or manipulate record data before it is saved. You can set field values, validate data, perform calculations, or apply complex business logic to ensure data consistency and accuracy.
  • Field Validations: These rules can enforce data integrity by validating field values. You can check if required fields are populated, verify data formats, or validate against predefined criteria to ensure that only valid data is stored in the database.
  • Default Values: Before business rules can set default values for fields if they are not provided by the user. This feature allows you to automate the population of certain fields with predefined values, reducing manual effort and ensuring consistency.
  • Execution Order: The order of execution of before business rules is determined by their execution order values. Lower execution order values are executed first, while higher values are executed later. This order is crucial when multiple before business rules are defined for the same event or condition.

Before business rules play a vital role in manipulating and validating data before it is saved in ServiceNow. They allow you to enforce business rules, maintain data integrity, and ensure consistent data quality within the platform.

Before Business Rules provide flexibility and control over the data being saved to the database. They allow you to enforce data integrity, apply custom business rules, and modify data as necessary before it is persisted. By leveraging Before Business Rules effectively, you can ensure that data is accurate, consistent, and meets the desired criteria within your ServiceNow instance.


Example:

If the incident description is empty, the incident should not be submitted and display an information message.

Steps:

  • Create a before insert and update business rule on the incident table.
  • Add the condition "Description is empty".
  • In Action section check box the checkboxes and in the message textbox provide your message text.