Saturday, 18 January 2025

Script Includes

                                                          ServiceNow Interview Questions

                                                                  Script Includes

1. What is a Script Include in ServiceNow?

A Script Include is a reusable server-side script written in JavaScript that can be called from other server-side scripts, such as Business Rules, or from client-side scripts using GlideAjax.


2. How do you call a Script Include from a Client Script using GlideAjax?

You can call a Script Include from a Client Script using GlideAjax. Here’s an example:

JavaScript

var ga = new GlideAjax('YourScriptIncludeName');

ga.addParam('sysparm_name', 'yourFunctionName');

ga.addParam('param1', 'value1');

ga.getXMLAnswer(function(response) {

    var answer = response.responseXML.documentElement.getAttribute('answer');

    // Use the answer as needed

});


3. What are the different types of Script Includes?

There are three types of Script Includes:

On-demand: Loaded and executed when called.

Extendable: Used to create reusable code that can be extended by other Script Includes.

Global: Available globally across the instance without needing to be explicitly called.


4. How do you use Script Include in a Business Rule?

You can call a Script Include from a Business Rule by creating an instance of the Script Include and calling its methods. For example:

JavaScript

var si = new YourScriptIncludeName();

si.yourFunctionName(param1, param2);


5. Explain the purpose of the initialize() function in a Script Include.

The initialize() function is a constructor function that runs automatically when an instance of the Script Include is created. It is used to set up initial values or perform setup tasks.

JavaScript

var MyScriptInclude = Class.create();

MyScriptInclude.prototype = {

    initialize: function() {

        this.someProperty = 'initial value';

    },

    someFunction: function() {

        // Function logic

    }

};

6. How can you call one function of a Script Include from another function within the same Script Include?

You can call another function within the same Script Include using this. For example:

JavaScript

var YourScriptIncludeName = Class.create();

YourScriptIncludeName.prototype = {

    initialize: function() {},

    functionOne: function() {

        this.functionTwo();

    },

    functionTwo: function() {

        // Function logic

    }

};


7. What is gs.include() in Script Include and how is it used?

gs.include() is used to include another Script Include within the current Script Include. This allows you to reuse code from other Script Includes. For example:

JavaScript

gs.include('OtherScriptIncludeName');

var otherSI = new OtherScriptIncludeName();

otherSI.someFunction();


8. Can you provide a scenario where you would use a Script Include with GlideAjax?

A common scenario is when you need to fetch data from the server based on user input in a form. For example, you might use GlideAjax to call a Script Include that retrieves user details based on a user ID entered in a form field.


9. How do you use Script Include in an advanced and dynamic reference qualifier?

You can use a Script Include to create a dynamic reference qualifier by returning a query string. For example:

JavaScript

var YourScriptIncludeName = Class.create();

YourScriptIncludeName.prototype = {

    initialize: function() {},

    getReferenceQualifier: function() {

        return 'active=true^category=hardware';

    }

};


10. Describe a real-world scenario where you used Script Include to solve a problem.

In a real-world scenario, I used a Script Include to automate the assignment of incidents based on the user’s department. The Script Include fetched the user’s department and assigned the incident to the appropriate support group, streamlining the incident management process.


11. How do you call a Script Include from another Script Include?

You can call a Script Include from another Script Include using the new keyword. For example:

JavaScript

var otherScriptInclude = new OtherScriptIncludeName();

otherScriptInclude.someFunction();


12. How do you extend a Script Include in ServiceNow?

To extend a Script Include, create a new Script Include that inherits from the base Script Include using the Class.create() method. For example:

JavaScript

var ExtendedScriptInclude = Class.create();

ExtendedScriptInclude.prototype = Object.extendsObject(BaseScriptInclude, {

    initialize: function() {

        BaseScriptInclude.prototype.initialize.call(this);

        // Additional initialization

    },

    extendedFunction: function() {

        // Extended function logic

    }

});


13. How do you use GlideRecord in a Script Include to query records?

You can use GlideRecord in a Script Include to query records from a table. For example:

JavaScript

var MyScriptInclude = Class.create();

MyScriptInclude.prototype = {

    initialize: function() {},

    getRecords: function() {

        var gr = new GlideRecord('incident');

        gr.addQuery('priority', 1);

        gr.query();

        var results = [];

        while (gr.next()) {

            results.push(gr.number.toString());

        }

        return results;

    }

};


14. How do you handle errors in a Script Include?

Use try-catch blocks to handle errors and log them using gs.logError(). For example:

JavaScript

var MyScriptInclude = Class.create();

MyScriptInclude.prototype = {

    initialize: function() {},

    someFunction: function() {

        try {

            // Function logic

        } catch (e) {

            gs.logError('Error in MyScriptInclude: ' + e.message);

        }

    }

};


15. How do you use the gs.include() method in a Script Include?

The gs.include() method is used to include another Script Include within the current Script Include. For example:

JavaScript

gs.include('OtherScriptIncludeName');

var otherSI = new OtherScriptIncludeName();

otherSI.someFunction();


16. How do you create a Script Include that can be called from both server-side and client-side scripts?

Set the Accessible from field to All application scopes and use GlideAjax for client-side calls. For example:

JavaScript

var MyScriptInclude = Class.create();

MyScriptInclude.prototype = {

    initialize: function() {},

    myFunction: function(param1) {

        return 'Hello, ' + param1;

    }

};


17. Scenario: You need to create a Script Include that returns the number of open incidents assigned to a specific user. How would you implement this?

Create a Script Include with a function that uses GlideRecord to query the Incident table and count the number of open incidents assigned to the specified user.

JavaScript

var IncidentUtils = Class.create();

IncidentUtils.prototype = {

    initialize: function() {},

    getOpenIncidentsCount: function(userId) {

        var gr = new GlideRecord('incident');

        gr.addQuery('assigned_to', userId);

        gr.addQuery('state', '!=', 'closed');

        gr.query();

        return gr.getRowCount();

    },

    type: 'IncidentUtils'

};


18. Scenario: You want to create a Script Include that returns a list of users in a specific group. How would you achieve this?

Create a Script Include with a function that uses GlideRecord to query the sys_user_grmember table and return a list of users in the specified group.

JavaScript

var GroupUtils = Class.create();

GroupUtils.prototype = {

    initialize: function() {},

    getUsersInGroup: function(groupId) {

        var users = [];

        var gr = new GlideRecord('sys_user_grmember');

        gr.addQuery('group', groupId);

        gr.query();

        while (gr.next()) {

            users.push(gr.user.toString());

        }

        return users;

    },

    type: 'GroupUtils'

};


19. Scenario: You need to create a Script Include that calculates the difference in days between two dates. How would you implement this?

Create a Script Include with a function that calculates the difference in days between two dates using GlideDateTime.

JavaScript

var DateUtils = Class.create();

DateUtils.prototype = {

    initialize: function() {},

    getDaysDifference: function(startDate, endDate) {

        var start = new GlideDateTime(startDate);

        var end = new GlideDateTime(endDate);

        var diff = GlideDateTime.subtract(start, end);

        return diff.getNumericValue() / (1000 * 60 * 60 * 24); // Convert milliseconds to days

    },

    type: 'DateUtils'

};


20. Scenario: You want to create a Script Include that sends an email notification to a user. How would you achieve this?

Create a Script Include with a function that uses the GlideEmailOutbound API to send an email notification to the specified user.

JavaScript

var NotificationUtils = Class.create();

NotificationUtils.prototype = {

    initialize: function() {},

    sendEmail: function(userId, subject, body) {

        var email = new GlideEmailOutbound();

        email.setFrom('no-reply@example.com');

        email.setTo(userId);

        email.setSubject(subject);

        email.setBody(body);

        email.send();

    },

    type: 'NotificationUtils'

};


21. Scenario: You need to create a Script Include that retrieves the details of a specific catalog item. How would you implement this?

Create a Script Include with a function that uses GlideRecord to query the sc_cat_item table and retrieve the details of the specified catalog item.

JavaScript

var CatalogUtils = Class.create();

CatalogUtils.prototype = {

    initialize: function() {},

    getCatalogItemDetails: function(itemId) {

        var gr = new GlideRecord('sc_cat_item');

        if (gr.get(itemId)) {

            return {

                name: gr.getValue('name'),

                description: gr.getValue('description'),

                price: gr.getValue('price')

            };

        }

        return null;

    },

    type: 'CatalogUtils'

};


22. Scenario: You want to create a Script Include that updates the priority of an incident based on its impact and urgency. How would you achieve this?

Create a Script Include with a function that updates the priority of an incident based on its impact and urgency using GlideRecord.

JavaScript

var IncidentPriorityUtils = Class.create();

IncidentPriorityUtils.prototype = {

    initialize: function() {},

    updateIncidentPriority: function(incidentId) {

        var gr = new GlideRecord('incident');

        if (gr.get(incidentId)) {

            var impact = gr.getValue('impact');

            var urgency = gr.getValue('urgency');

            if (impact == 1 && urgency == 1) {

                gr.setValue('priority', 1); // High priority

            } else if (impact == 2 || urgency == 2) {

                gr.setValue('priority', 2); // Medium priority

            } else {

                gr.setValue('priority', 3); // Low priority

            }

            gr.update();

        }

    },

    type: 'IncidentPriorityUtils'

};


23. Scenario: You need to create a Script Include that returns the total number of records in a custom table. How would you implement this?

Create a Script Include with a function that uses GlideRecord to count the total number of records in the specified custom table.

JavaScript

var TableUtils = Class.create();

TableUtils.prototype = {

    initialize: function() {},

    getTotalRecords: function(tableName) {

        var gr = new GlideRecord(tableName);

        gr.query();

        return gr.getRowCount();

    },

    type: 'TableUtils'

};


24. Scenario: You need to create a Script Include that calculates the total number of open incidents for a specific user. How would you implement this?

Create a Script Include that uses GlideRecord to query the Incident table and count the number of open incidents for the specified user.

JavaScript

var IncidentUtils = Class.create();

IncidentUtils.prototype = {

    initialize: function() {},

    getOpenIncidentsCount: function(userId) {

        var gr = new GlideRecord('incident');

        gr.addQuery('assigned_to', userId);

        gr.addQuery('state', '!=', 'closed');

        gr.query();

        return gr.getRowCount();

    }

};


25. Scenario: You want to create a Script Include that returns a list of incidents assigned to a specific group. How would you achieve this?

Create a Script Include that uses GlideRecord to query the Incident table and return a list of incidents assigned to the specified group.

JavaScript

var IncidentUtils = Class.create();

IncidentUtils.prototype = {

    initialize: function() {},

    getIncidentsByGroup: function(groupId) {

        var gr = new GlideRecord('incident');

        gr.addQuery('assignment_group', groupId);

        gr.query();

        var incidents = [];

        while (gr.next()) {

            incidents.push(gr.number.toString());

        }

        return incidents;

    }

};


26. Scenario: You need to create a Script Include that updates the priority of all incidents assigned to a specific user. How would you implement this?

Create a Script Include that uses GlideRecord to query the Incident table and update the priority of incidents assigned to the specified user.

JavaScript

var IncidentUtils = Class.create();

IncidentUtils.prototype = {

    initialize: function() {},

    updateIncidentPriority: function(userId, newPriority) {

        var gr = new GlideRecord('incident');

        gr.addQuery('assigned_to', userId);

        gr.query();

        while (gr.next()) {

            gr.priority = newPriority;

            gr.update();

        }

    }

};


27. Scenario: You want to create a Script Include that sends a notification to the manager of a user when an incident is assigned to them. How would you achieve this?

Create a Script Include that uses GlideRecord to get the manager of the assigned user and then use gs.eventQueue() to trigger a notification event.

JavaScript

var IncidentUtils = Class.create();

IncidentUtils.prototype = {

    initialize: function() {},

    notifyManagerOnAssignment: function(incidentId) {

        var gr = new GlideRecord('incident');

        if (gr.get(incidentId)) {

            var userId = gr.assigned_to;

            var userGr = new GlideRecord('sys_user');

            if (userGr.get(userId)) {

                var managerId = userGr.manager;

                gs.eventQueue('incident.assigned', gr, managerId, gs.getUserID());

            }

        }

    }

};


28. Scenario: You need to create a Script Include that retrieves the details of a specific incident and formats them as a JSON object. How would you implement this?

Create a Script Include that uses GlideRecord to retrieve the incident details and format them as a JSON object.

JavaScript

var IncidentUtils = Class.create();

IncidentUtils.prototype = {

    initialize: function() {},

    getIncidentDetailsAsJSON: function(incidentId) {

        var gr = new GlideRecord('incident');

        if (gr.get(incidentId)) {

            var incidentDetails = {

                number: gr.number.toString(),

                short_description: gr.short_description.toString(),

                priority: gr.priority.toString(),

                state: gr.state.toString(),

                assigned_to: gr.assigned_to.getDisplayValue()

            };

            return JSON.stringify(incidentDetails);

        }

        return null;

    }

};

No comments:

Post a Comment

Featured post

Common Service Data Model (CSDM)

                                                ServiceNow Interview Questions                                             Common Service Da...

Popular Posts