Friday, 8 May 2020

Important ServiceNow Script or Reference

ServiceNow Best Practice :




Attachment script Attachment Mandatory --- 




function onSubmit() {

    if (g_form.getValue('non_tracked_devices') == 'Yes') {
        var cat_id = g_form.getValue('sysparm_item_guid');
        var gr = new GlideRecord("sys_attachment");
        gr.addQuery("table_name", "sc_cart_item");
        gr.addQuery("table_sys_id", cat_id);
        gr.query();
        if (!gr.next()) {
            alert("You must add an attachment before submitting this request.");
            return false;
        }
    }

}

//Script to Delete multiple record 

var psc = new GlideRecord('<table_name>'); //Make sure table name is correct
psc.addEncodedQuery('sourceISNOTEMPTY');// Encoded Query or Filter if any required 
psc.addQuery('sourceISNOTEMPTY');//Query or Filter if any required 
psc.setLimit('10'); //Limit number of records 
psc.setWorkflow(false); //Turn off business rule or notifications
psc.deleteMultiple();



//On Change Client script Example ...   Disable or Enable the form 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
   if (isLoading || newValue == '') {
      return;
   }
    var u1 = g_form.getValue('sitescope_manager'); //optional
g_form.addInfoMessage('Please wait while fetching Server Name');
g_form.getFormElement().disable();
var links = g_form.getFormElement().getElementsByTagName("a");
for ( i=0;i<links.length;i++)
{
links[i].hide();
}
var ga = new GlideAjax('Sitescope');
ga.addParam('sysparm_name','sitescope'); 
ga.addParam('sysparm_sitescope_manager',u1); //optional
ga.getXML(FolderFetch);
}
function FolderFetch(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
if (answer == "start")
{
g_form.showFieldMsg('remote_server_name','There is some Congestion in the Network. Please try again Later','error');
}
else
{
var outputval=answer;
var arr=outputval.split("\n");
var k=0;
while(k!=arr.length)
{
g_form.addOption('remote_server_name', arr[k],arr[k]);
k++;
}
}
g_form.clearMessages();
g_form.getFormElement().enable();
var links1 = g_form.getFormElement().getElementsByTagName("a");
for ( i=0;i<links1.length;i++)
{
links1[i].show();
}
}

   //How to setup OAuth2 authentication for RESTMessageV2 integrations



//Find Duplicate record in table with filed value :

var dupRecords = [];
var gaDupCheck1 = new GlideAggregate('cmdb_ci_hardware');
gaDupCheck1.addAggregate('COUNT', 'serial_number');
gaDupCheck1.groupBy('serial_number');
gaDupCheck1.addHaving('COUNT', '>', 1);
gaDupCheck1.query();
while (gaDupCheck1.next()) {
    dupRecords.push(gaDupCheck1.serial_number.toString());
}
gs.print(dupRecords);


//Script to delete duplicate records: 


var dup = new GlideAggregate('dscy_router_interface');
dup.groupBy('mac_address');
dup.query();
while(dup.next()) {
var dup1 = new GlideRecord('dscy_router_interface');
dup1.addQuery('mac_address', dup.mac_address);
dup1.query();
dup1.next();
while(dup1.next())
dup1.deleteRecord();
}


//CI Asset Synchronization useful scripts 

var serialNum = [”SE415WS47”, ”VMware-42 26 87 93 04 f8 e6 15-9c 43 e6 c2 0e 76 4f 55”,];
for (var i = 0; i < serialNum.length; i++) {
    var grCI = new GlideRecord("cmdb_ci_hardware");
    grCI.addEncodedQuery('sys_class_name=cmdb_ci_computer');
    grCI.addQuery("discovery_source", "MS SMS");
    grCI.addQuery("serial_number", serialNum[i]);
    grCI.query();
    while (grCI.next()) {
        var grAlm = new GlideRecord("alm_hardware");
        grAlm.addQuery("serial_number", serialNum[i]);
        grAlm.query();
        while (grAlm.next()) {
            grAlm.ci = grCI.sys_id.toString();
            grAlm.setWorkflow(false);
            grAlm.update();
        }

    }
}

var serialNum = ["1N44FW2", "1PR8YW2", "1QDKGP2"];
for (var i = 0; i < serialNum.length; i++) {
var grCI = new GlideRecord("cmdb_ci_hardware");
grCI.addEncodedQuery('sys_class_name=cmdb_ci_computer');
grCI.addQuery("discovery_source", "NULL");
grCI.addQuery("serial_number",serialNum[i]);
grCI.query();
while (grCI.next()) {

    var grCI1 = new GlideRecord("cmdb_ci_hardware");
    grCI1.addEncodedQuery('sys_class_name=cmdb_ci_computer');
    grCI1.addQuery("discovery_source", "MS SMS");
    grCI1.addQuery("serial_number", serialNum[i]);
    grCI1.query();
    while (grCI1.next()) {
        grCI1.asset = grCI.asset;
        grCI1.update();

    }
}
}


// Manually Create record in windows Server or any other class using script 

var payload = {
   "items": [
      {
         "className": "u_cmdb_ci_mongoose_web_server",
         "lookup": [],
         "values": {
            "name": "Mongoose@owa-sd-01",            
            "version": “5.5”,
            "running_process_command": "c:\\clouddimensions\\mongoose.exe",
            "sys_class_name": "u_cmdb_ci_mongoose_web_server"
         }
      },
      {
         "className": "cmdb_ci_win_server",
         "lookup": [],
         "values": {
            "name": "OWA-SD-01"
         }
      }
   ],
   "relations": [
      {
         "type": "Runs on::Runs",
         "parent": 0,
         "child": 1
      }
   ]
};

var jsonUtil = new JSON();
var input = jsonUtil.encode(payload);
var output = SNC.IdentificationEngineScriptableApi.createOrUpdateCI(‘ServiceNow’, input);
gs.print(output);


//Azure Fundamental :   -



Remove Middle name from a name in Excel Sheet .

Using formula may be a very easy way for most of Excel users.

Select a blank cell next to the name list, and type this formula =TRIM(LEFT(A1,FIND(" ",LOWER(A1),1))) & " " & TRIM(MID(A1,FIND(" ",LOWER(A1),FIND(" ",LOWER(A1),1)+1)+1,LEN(A1)-FIND(" ",LOWER(A1),1)+1)) into it, then press Enter button on the keyboard and drag the Auto Fill handle to fill the range needed to apply the formula. Now you can see all the name of the list are shown in the new column without middle initials.

// Get all the incidents updated 3 days before

var dupRecords = [];
var count = '';
var gr = new GlideRecord('incident');
gr.addQuery('sys_updated_onRELATIVEGE@dayofweek@ago@3');
gr.query();
while(gr.next()){
dupRecords.push(gr.number);
}
gs.print(dupRecords);

   

ServiceNow Asset Data Load Pre checks or procedure


Pre-Checks
·         Look at the below attribute for data provided in Excel/Data sheet
Acquisition method
Asset tag
Assigned
Assigned to
Comments
Manufacturer
Cost
Cost center
Depreciation
Depreciation effective date
Disposal reason
Due
Installed
 Retired date
State
Invoice number
Managed by
Model
Model Category
Ordered
Purchased
Quantity
Request line
Resale price
Salvage value
Serial number
Stockroom
Substate
DR Option
Part Number
Room
Shared Workstation Reason
Vendor
Warranty expiration
Building
Support group
Beneficiary
Checked in
Checked out
Supported by
Order received
Department
Name
Workstation Classification
Due in
Expenditure type
GL account
Window
Justification
Lease contract
Location
Wave
Owned by
Parent
PO number
Scheduled retirement
Reserved for



·         Check for all the reference or choice field value is available in ServiceNow or Now
o   Assigned To
o   Supported By
o   Support Group
o   State
o   Sub State
o   Manufacturer
o   Model Category
o   Model
o   Location
o   DR Option
o   Name (Configuration Item)
·         Confirm that if any of the above attribute value is not available in ServiceNow, Should you create new value of it or not.
·         When you have proper data in hand start loading the data into ServiceNow using below steps
o   Create a Data load
§  System Import Set à Load Data
§  Create new Staging table to load the data
o   Create Transform Map
§  Map all the attribute from Source Table (Newly created Staging table) to target table (alm_hardware or alm_asset)
§  Select coalesces field to remove duplication
§  Select choice action properly
§  Create a transform map script if required
·         On Start
·         On Complete
·         On Before
·         On After
·         On choice Create
·         On Reject etc.
o   Run the data load
§  Select the transform map created above.

Transform used to load data in LYB ServiceNow


Post-Checks
·         Check for the below attribute whether data loaded properly or now.
o   Assigned To
o   Supported By
o   Support Group
o   State
o   Sub State
o   Manufacturer
o   Model Category
o   Model
o   Location
o   DR Option
o   Name (Configuration Item)
·         Check for the below table whether any unnecessary value created because of data load
o   User
o   Group
o   Location
o   Hardware CI
o   State Choice
o   Substate Choice etc.
·         Run Below script on alm_hardware and cmdb_ci_hardware table for duplicate CI using Serial Number

var dupRecords = [];
var gaDupCheck1 = new GlideAggregate('cmdb_ci_hardware');
gaDupCheck1.addAggregate('COUNT', 'serial_number');
gaDupCheck1.groupBy('serial_number');
gaDupCheck1.addHaving('COUNT', '>', 1);
gaDupCheck1.query();
while (gaDupCheck1.next()) {
               
    dupRecords.push(gaDupCheck1.serial_number.toString());
}
gs.print(dupRecords);

·         Delete all duplicate value created because of transform map.
·         If required use below script to delete duplicate value :  ( Run with high precautions)

var dup = new GlideAggregate(‘alm_hardware’);
dup.groupBy('serial_number');
dup.query();
while(dup.next()) {
                var dup1 = new GlideRecord('alm_ hardware’');
                dup1.addQuery('serial_number', dup.serial_number);
                dup1.query();
                dup1.next();
                while(dup1.next())
                                dup1.deleteRecord();
}
Further Reference for Data load or transform Maps.

Tuesday, 21 April 2020

Agent Workspace in ServiceNow




Today I had a chance to go through the Agent Workspace thought of sharing the learnings.
Agent workspace is New UI from ServiceNow for a Support engineer or developer to work on. It is as we have Studio for building an Application in ServiceNow.
Agent Workspace allows agents to work on multiple records without having to switch browser tabs.

Features:
  • It has the entire feature as we have in platform, For Example:
    • Sorting columns from A-Z or Z-A
    • The ability to show or filter out matching records (based on a specific column value)
    • Changing the number of rows displayed per page
    • List editing
    • Multi-list editing etc.
It also Include below:
  • Altogether separate form view which provide single screen
    • Form header contain all the information we need related to record like
      • Related records
      • Form Layout
      • Activity streams etc
    • It has option to order from catalog item on the same workspace.
    • Agent Assist is having a contextual search option, which provides
      • Provide similar records and trends using Predictive Intelligence
      • Search and attach knowledge articles
      • Search social Q&A entries
      • Order catalog items
      • Manage attachments
      • Apply Templates
    • If Organization has configured Agent Chat1 and Advanced Work Assignment, We can have Inbox icon in the fixed navigation bar. 
      • View the pending work items that are assigned to him (can include chat requests)
      • Accept or reject work
    • During chat, end user can transfer the chat to some other person .
    • Organization has integrated a telephony system with Agent Workspace,
      • A phone icon becomes visible in the fixed navigation bar.
      • He can make inbound and outbound calls.
    • We can personalize the list with set of work, like Incident assigned to me etc.
Configurations /Plugins / Roles

Plugins:
Any user with the admin role can activate the Agent Workspace [com.agent_workspace] plugin by navigating to System Definition > Plugins.

Roles:
  1. workspace_admin
    1. The workspace_admin role provides the ability to configure Agent Workspace. This role contains the following roles:
      1. form_admin, chat_admin, template_editor,ui_action_admin,personalize_form,interaction_admin
    2. workspace_list_admin -- This is an elevated role.

      The [workspace_list_admin] role provides the ability to create list categories and filtered lists in Agent Workspace. This role contains the [agent_workspace_user] role.
    3. agent_workspace_user

      The agent_workspace_user role provides access to Agent Workspace UI. The itil (ITSM) and sn_esm_agent (CSM) roles contain this role. Assign the agent_workspace_user role to agents who need to work in Agent Workspace.
    4. workspace_user

      The workspace_user role provides access to workspace_core. This role is for internal use only.


ServiceNow provides preconfigured workspaces for other ServiceNow applications.
Below is a list of plugins you can install for additional workspaces:
  • CMDB
    • cmdb-workspace
  • Customer Service Management
    • snc.agent_workspace.csm
  • HR Services
    • sn_hr_agent_workspace
  • IT Service Management
    • snc.agent_workspace.itsm
  • Operational Intelligence
    • oi-scoped-app
  • Security Incident Response
    • sn_app_secops_ui

Additional Plugins for Agent Workspace
  • Route work items to agents so that they can access their work item assignments from their Agent Workspace inboxes by activating the 
    • Advanced Work Assignment [com.glide.awa] plugin.
  • Activate quick actions, response templates, Agent Chat, and the Chat service channel in Advanced Work Assignment by activating the 
    • Agent Chat [com.glide.interaction.awa] plugin.
  • Openframe and CTI enable third-party phone integrations for phone use by activating the
Openframe [com.sn_openframe] plugin

Reference: 
ServiceNow Docs
Now Learning

Happy Learning !!

Tuesday, 3 March 2020

ServiceNow OOB Regex Validation for Currency || Email || IP address || Letter || Mac address || Number || URL




As we are using Madrid version of ServiceNow. I have come across one OOB feature of ServiceNow in Madrid for validating  below
Currency || Email || IP address || Letter || Mac address || Number || URL

We have a table in ServiceNow called  Questions Regular Expression “question_regex”. Which store the regular expression in record format. See below.

OOB we only three validation but we can create as many as we want with the help of  Regex.


Once we create a record in Questions Regular Expression “question_regex” table we can put that validation while creating variable in Catalog item.
See below: This works on Single line text field.







No more writing lengthy script for validation.
Below are the Regex validation we can utilize  

- Currency ($)
^\$[0-9]*\.[0-9]{2}$
- Currency (€)
^\€[0-9]*\.[0-9]{2}$
- Email address
^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$
- IBAN
^[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}$
- IP address
^\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b$
- Letter (A-z)
^[A-Za-z]*$
- Mac address
^[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}$
- Zip Code (NL)
^[1-9][0-9]{3}[\s]?[A-Za-z]{2}$

Reference : 


More details on similar topic I have kept in portal  - https://www.servicenowpreparation.com/ you can visit.

Bel
Happy Learning

Regards
Sandeep Kumar


Monday, 2 March 2020

Custom Currency field Validation

Use Below script on change of field value

This script will help you to restrict end user to provide currency value in "$0.00" format


function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    //Type appropriate comment here, and begin script below
    var cost_field = g_form.getValue('cost_field');
    cost_field = cost_field.trim();
    // first character should be dollar sign
    var firstChar = cost_field.substring(0, 1);
    if (firstChar != '$') {
        alert("Please enter cost_field in $0.00 format");
        g_form.setValue("cost_field", oldValue);
        return;
    }
    // characters after the $ sign should be numerics
    var cost_fieldType = isNaN(cost_field.substring(1));
    if (cost_fieldType == true) {
        alert("Please enter cost_field in $0.00 format");
        g_form.setValue("cost_field", oldValue);
        return;
    }
    // entered value should have a decimal point
    var num = cost_field.substring(1);
    if (num.indexOf('.') == -1) {
        alert("Please enter cost_field in $0.00 format");
        g_form.setValue("cost_field", oldValue);
        return;
    }
    // there must be 2 digits only after the decimal
    var decNum = num.substring(num.indexOf('.') + 1, num.length);
    if (decNum.length != 2) {
        alert("Please enter cost_field in $0.00 format");
        g_form.setValue("cost_field", oldValue);
        return;
    }
}

Start and End Data validation according to Data format ServiceNow



Start Date Validation :
On Change Client Script :

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


    if (isLoading || newValue == '') {

        return;

    }

    if (g_form.getValue('start_date') != '') {

        var dFormat = g_user_date_format;

        var tFormat = g_user_date_time_format;

        var today = getDateFromFormat(formatDate(new Date(), dFormat), dFormat);

        var sDate = getDateFromFormat(g_form.getValue('start_date'), dFormat);

        if (today > sDate) {

            alert(getMessage("Select date in the future"));

            g_form.setValue('start_date', '');

        }

    }

}



End Date Validation :
On Change Client Script :
 


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

    if (isLoading || newValue == '') {

        return;

    }

    if (g_form.getValue('start_date') != '') {

        var dFormat = g_user_date_format;

        var tFormat = g_user_date_time_format;

        var end = getDateFromFormat(g_form.getValue('end_date'), dFormat);

        var today = getDateFromFormat(formatDate(new Date(), dFormat), dFormat);

        var sDate = getDateFromFormat(g_form.getValue('start_date'), dFormat);

        if (today > end) {

            alert(getMessage("Desired End Date has to be a date in the future"));

           g_form.setValue('end_date', '');

        } else if (sDate != '' && end < sDate) {

            alert(getMessage("End date should not be before Start date"));

            g_form.setValue('end_date', '');

        }

    } else {

        g_form.setValue('end_date', '');

        alert(getMessage('First please select Start Date Of Limit Change'));

    }

}