Thursday, September 29, 2022

ServiceNow script to retrieve oAuth token programatically

var instance = 'https://test.service-now.com';

var username = 'testadmin1'; 

var password = 'testadmin1'; 

var clientId = '539decb2e5968b00f5ac882d078e787d'; 

var clientSecret = 'test123'; 

  

// Request a token 

var getTokenRM = new sn_ws.RESTMessageV2(); 

getTokenRM.setEndpoint(instance + '/oauth_token.do'); 

getTokenRM.setHttpMethod("post"); 

getTokenRM.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 

getTokenRM.setRequestBody('grant_type=password&client_id=' + clientId + '&client_secret=' + clientSecret + '&username=' + username + '&password=' + password); 

var responseToken = getTokenRM.execute(); 

gs.print('response..'+ responseToken.getBody());

var token = new JSONParser().parse(responseToken.getBody()); 

Thursday, February 3, 2022

ServiceNow business rule to print the list of columns changed

For Global Scope Applications

 (function executeRule(current, previous /*null when async*/ ) {
    var gru = GlideScriptRecordUtil.get(current);
    var changedFields = gru.getChangedFields();
    var changedFieldNames = gru.getChangedFieldNames();

    //Convert to JavaScript Arrays
    gs.include('j2js');

    changedFields = j2js(changedFields);
    changedFieldNames = j2js(changedFieldNames);

    var arrayLength = changedFields.length;
    gs.log(arrayLength);


    for (var i = 0; i < arrayLength; i++) {
        gs.addErrorMessage(changedFields[i]);
    }

    var arrayLength1 = changedFieldNames.length;
    gs.log(arrayLength);

    for (var i = 0; i < arrayLength1; i++) {
        gs.addErrorMessage(changedFieldNames[i]);
    }
})(current, previous);

For Scoped application tables

 (function executeRule(current, previous /*null when async*/ ) {
    var result = [];
    var elements = current.getElements();
    var size = elements.length;
    for (var i = 0; i < size; i++) {
     var ge = elements[i];
     if (ge.changes()) {
      gs.addErrorMessage(ge.getName());
     }
    }
   })(current, previous);

Monday, January 10, 2022

ServiceNow backend script to wait for a few milliseconds

 function waitForTime(time){  

  var t1 = new GlideDateTime().getNumericValue();  

  var t2 = new GlideDateTime().getNumericValue();  

  var duration = t2 - t1;  

  while(duration < time){  

  t2 = new GlideDateTime().getNumericValue();  

  duration = t2 - t1;  

  }  

}

Wednesday, June 2, 2021

Parse attached CSV file in ServiceNow using script in UI Action

The following is a sample script to parse a CSV file in UI Action.


var gr = new GlideRecord('sys_attachment');

gr.addQuery("table_name", "incident");

gr.addQuery("table_sys_id", current.sys_id); // sys_id of attachment record

gr.query();


if (gr.next()) {

    var gsa = new GlideSysAttachment();

    var bytesInFile = gsa.getBytes('incident', current.sys_id);

    var fileContent = Packages.java.lang.String(bytesInFile); 

    gs.log("Contents of CSV:  " + fileContent);

    fileContent = String(fileContent);

    var delimiter = ',';

    var quoteChar = '"';


    var x = new sn_impex.CSVParser().parseLineToArray(fileContent, delimiter, quoteChar);

gs.log("line 0 content" + x[0]);

}

Thursday, July 25, 2019

Reset Button or Clear Values button widget to clear catalog item variable values

Step 1: Create a widget as shown below

Body HTML Template:


<button type="button" class="btn btn-danger btn-block" ng-click="c.setFieldValue(inputValue)">Reset Values</button>


Client Controller script


function($scope) {
var c = this;
c.setFieldValue = function(uploadname) {
var g_form = $scope.page.g_form;
g_form.clearValue("acrobat");
g_form.setValue("Additional_software_requirements", "");
g_form.setValue("test","");
g_form.setValue("photoshop", "");
};
}


Step-2: Create a variable of type Macro and in the default section give this widget name.

Thursday, June 27, 2019

ServiceNow parseInt() is returning NaN all the times

This is a common issue and the resolution is to pass both the parameters to the parseInt() method. It accepts the second parameter, which is the base

var testString = "10101"
var number = parseInt(testString, 10) + 100


The second parameter indicates that this integer has to be generated in base10

-------------------------------------------------------------------------------------------------------------
Are you looking to implement custom solutions in ServiceNow?

You are at the right place. Reach us at

Conyx IT Solutions | ServiceNow experts
partners@conyxit.com

Monday, December 17, 2018

Parse the CSV file upload in ServiceNow Service Portal


Body HTML template


<div class="text-center m">
      <span class="file-upload-input">
        <input type="file" style="display: none" multiple="true" ng-file-select="attachmentHandler.onFileSelect($files); filePicked($files);" class="sp-attachments-input">
        <button title="Add attachment"
                ng-click="attachmentHandler.openSelector($event)"
                class="btn btn-primary sp-attachment-add"
                aria-label="Add attachment" role="button">${Upload the custim file}
        </button>
      </span>
</div>


Client Controller Code


$scope.filePicked = function (oEvent) {
docArr = [];

// Get The File From The Input
var oFile = oEvent[0];
var sFilename = oFile.name;

// Create A File Reader HTML5
var reader = new FileReader();

// Ready The Event For When A File Gets Selected
reader.onload = function(e) {
try {
setTimeout(function(){
$rootScope.$broadcast('file-attached',null);
},1000);

var data = e.target.result;
var cfb = XLS.CFB.read(data, {type: 'binary'});

var wb = XLS.parse_xlscfb(cfb);

// Loop Over Each Sheet
wb.SheetNames.forEach(function(sheetName) {
// Obtain The Current Row As CSV
var sCSV = XLS.utils.make_csv(wb.Sheets[sheetName]);
var oJS = XLS.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);
var theanswer = sCSV.split(',');
docArr.push(theanswer);

console.log(theanswer.filter(String)[0]);
$scope.data.output = theanswer.filter(String);
$scope.data.doc_date = theanswer.filter(String)[0];
$scope.data.doc_date_val = theanswer.filter(String)[1];
$scope.data.post_date = theanswer.filter(String)[2];
$scope.data.post_date_val = theanswer.filter(String)[3];
}
}
}
}