Servicenow – encrypt a field using encryption context

I wanted to encrypt a field by using encryption context and de-encrypt it. Below are the setups and scripts to test it. I am using ‘admin’ rights.

UI Macro:

ui macro



At Table structure:


At the form, I can view field (cipher) as string, showing encryption context table sys_id. This can update and sys_id over there.

Below will be the script:

   var contextGR = new GlideRecord("sys_encryption_context");
   gs.addInfoMessage("encrypt context id:"+contextGR.sys_id+'');

   var person= new GlideRecord("x_person");
   person.addQuery('ciphers', contextGR.sys_id+'');
   while ( {

   gs.addInfoMessage("person sys id:"+person.sys_id+'');

   gs.addInfoMessage('decrypted val: '+person.ciphers.getDisplayValue());




Hope this can help!


Basic REST Api – Client Request Data From Server

Below is the example of a client getting data from server through REST Api. Gzip encode header was used in this example, therefore the stream received on the client side will have to decode back. Content type pass from server will be application/json.

 public static void Main(string[] args)
                var req = Create("", "POST");
                var w = Base64Encode("username:password");
                req.Headers.Add("Authorization", "Basic " + w);
                var res = req.GetResponse();
                using (Stream ReceiveStream = res.GetResponseStream())
                using (var gzipStream = new GZipStream(ReceiveStream, CompressionMode.Decompress))
                using (StreamReader reader = new StreamReader(gzipStream, Encoding.UTF8))
                    String responseString = reader.ReadToEnd();

            catch(Exception ex)

public static HttpWebRequest Create(string uri, string method)
            var rq = (HttpWebRequest)WebRequest.Create(uri);
            rq.Method = method;
            rq.MaximumAutomaticRedirections = 4;
            rq.MaximumResponseHeadersLength = 4;
            rq.Headers.Add(new NameValueCollection() {
                {"Accept-Encoding", "gzip, deflate"},
                {"Accept-Language", "en-US,en;q=0.5"},
                {"Cache-Control", "no-cache"},
                {"Pragma", "no-cache"}
            rq.Accept = "application/json";
            rq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0";
            rq.KeepAlive = true;
            rq.AllowAutoRedirect = true;
            return rq;

Basic Authorization is being used in this case. There are many more authentication scheme can be use as below.

The most common authentication scheme is the “Basic” authentication scheme which is introduced in more details below. IANA maintains a list of authentication schemes, but there are other schemes offered by host services, such as Amazon AWS. Common authentication schemes include:

  • Basic (base64-encoded credentials)
  • Bearer (bearer tokens to access OAuth 2.0-protected resources)
  • Digest (only md5 hashing is supported in Firefox, see bug 472823 for SHA encryption support)
  • HOBA (HTTP Origin-Bound Authentication, digital-signature-based)
  • Mutual 

To Read More: HTTP authentication

How to Use Window.onload() Event

Any DOM manipulation code which depends on the DOM elements located at the head section of the html page, this code will be executed first before the DOM is fully ready. However error may occurs. Therefore, it is required to put the codes inside a callback function which will be fire when the DOM is fully loaded. If the code is place after the body element, the code will be executed smoothly after the DOM is fully loaded. No wrapping of code in the special callback function is require anymore.

Window.onload()  or window.load() is Javascript pure load event. The purpose of this event is to ensure that the page and its resources which include images, css, script, files are being loaded. This may take more time than $(document).ready().

window.onload = function() {


What is the different between Window.onload() and $(document).ready()

  • Time contraints – Window.onload() may take longer time to check the DOM is ready or not
  • Window.onload() are created to check the page and resources load complete. Whereas for $(document).ready() is just to check Javascript, Jquery code is ready to execute or not.


Window.onload() is well supported widely from old to new browser.

Why does jQuery or a DOM method could not find the element?

As script executed line by line, they are only executed when they are added into the DOM. The order matters. This mean the script cant find the element which written later below as it is not added into the DOM yet. Example:


<div id="fname">test</div>


The result for first document.getElementById is null. However, there is value for the second one.

What should you do?

There are few option to solve this.

        1. Move your script to where your action will be fire
              document.getElementById("fname").addEventListener("focusout", function() {
        2. Use $(document).ready()
          This will parse all the codes into the DOM first before executing them.

        3. Use Delegated Events .On()
          Delegated events can process events from descendant elements that are added to the document at a later time.

            $(document).on("click", {val: "test"}, display);
            function display( event ) {
            alert( "display: " + );
          click me


Either way can solve the problem.

Is best to use the $(document).ready(), this will ensure all events will be registered in DOM before executing them.

$(document).ready(function() {
   // do stuff when DOM is ready


$(function() {
    // do stuff when DOM is ready


For more information of this, refer here.


How to POST an array of objects with $.ajax

Base on earlier post which I talk about JSON. Here is the application part. Imagine you have an array of objects from client side need post back to server side for processing. JSON.stringify can do the trick of sending the array back to server side. Remember to put it before sending it.

objs = [
   {name: abc, age: 20, id: 123},
   {name: def, age: 23, id: 456, pet: dog},
   {name: efg, age: 30, id: 678, pet: {id: animal1, animal: cat, color: black}}


    url: postbackUrl,
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(objs);


JSON Method

I came across a scenario in my work place where I need to use client script WebService REST message to call a MID server to get result from the actual server which is behind the firewall. However, this time I will just share how I use client script to get the results and assigned them to object using JSON (JavaScript Object Notation) method in Servicenow.

try {
		 var r = new sn_ws.RESTMessageV2('NAT DNS API', 'dns_zone');

		 var response = r.execute();
		 var responseBody = response.getBody() ;
		var obj = JSON.parse(responseBody);
		obj.httpStatus = response.getStatusCode();
		var oj = JSON.stringify(obj);

		 gs.setRedirect(""+  encodeURI(oj));
		catch(ex) {
		var message = ex.getMessage();


How to use JSON?

From above example. I used two JSON method which is JSON.parse and JSON.stringify. ‘response’ variable will contain the result in string format after executed.

JSON.parse = Convert string to object. As I need to add a message element  to contain message and assigning the status code to  the existing element.

JSON.stringify = Convert object to string. In order for me to be able to post back the values, I have to convert back to string before I postback.

Below are some helpful sites for your better understanding:

  1. JSON
  2. Mozzila Web Doc


Here is how to use it for posting back from client side to server side for processing in my post.

There you go. Hope you have a better understanding on this.


How about get some insight about window.onload() event


Converting An Object to String in JavaScript

There are three ways to convert an object to string in Javascript will be as below:

1. value.toString()
2. value+""
3. String(value) 

Limitation to Use

value.toString() can only be use when the value is not null or undefine.

value+”” can only be use when the value is non empty string.

String(value) this way looks like a function call which can be confusing especially to those who are coming from Java. For this case, String will be a constructor instead of a function. Output of this will be different from a  function.

For value.toString(), .toString() will convert primitive to string as below:

Argument Result
undefined "undefined"
null "null"
boolean value either "true" or "false"
number value the number as a string, e.g. "1.765"
string value no conversion necessary


Which approaches do you prefer to use?

If you know that value is not null or undefine, you can use  value.toString(). Otherwise,  ""+value and String(value) are mostly equivalent.

For more related information, please click here.

How to use C# LinQ similar method in JavaScript

Below is a simple example to help understand the usage of the code:

var arr = [
 {name: 'a', val:1},
 {name:'b', val:2},
 {name:'c', val:3},
 {name:'d', val:4},
 {name:'e', val:5},
 {name:'f', val:6},

//jquery map
 var nm = $.map(arr,function(v){
 return v.val;

$("#box").html("jquery map: "+nm);

//array map
 var nm ={
 return v.val;
 $("#box2").html("array map: "+nm);

 var fName = $.grep(arr, function (p) { return == 'f'; })
 .map(function (p) { return p.val; });
 $("#box3").html("grep map: "+fName);

var result = arr.some(function (p) { return p.val>6; });
 $("#box4").html("some: "+result);

var result2 = arr.filter(function (p) { return (p.val<5); })
 .filter(function (q) { return ('a'); });
 $("#box5").html("filter: "+ JSON.stringify(result2));

var result3 = arr.find(function (p) { return'e'; });
 $("#box6").html("find: "+ JSON.stringify(result3));

Result can be seen here or test it out yourself:

Map – Translate array/object into new array of items. This is something similar to c# ( var value = listofobject.where(x=>;). Getting a list of particular items which you need. It can be use either jquery map ($.map()) or array map (

Grep – Finds the elements of an array which satisfy a filter function. The original array is not affected. This command is similar to .Where() in c# and it will return an array of result base on your criteria.

Some – Return a Boolean as an when your requirement met or not. something similar to c# (.Any()).

Filter – Reduce the set of matched elements to those that match the selector or pass the function’s test. You can add multiple filter as you need to meet your requirements. Is similar to .Where() as well. And it will return you an object instead of an array.

Find – Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. Similar to .Where() and .First() in C#. It will return the object you search for.

12 Tools to Replace Google Adwords

Well, if you haven’t heard the news yet, the word on the street is Google has shut down their widely popular keyword tool for public use. Now if you want access to Google sanctioned keyword data you have to sign up for an Adwords account. Of course there are a ton of theories surrounding why Google would make this decision, some are more obvious than others. But to many of us Google’s motivations seem pointless when we still have work to do! Luckily we exist in a vibrant industry where innovation is at the core of most of what we do. As such we have a slew of different tools available to replace Google’s tool.

  1. Ninja Search Combination Tool: With this great tool you can develop a giant list of different search queries. Then each query is linked to a Google query. It is great for developing strategies on the fly.
  2. MajesticSEO: Our friends over at Majestic SEO have a great tool for keyword research. They pull from their giant index to provide many metrics that you can’t find anywhere else.
  3. SEO Book Keyword Tools: Aaron Wall has offered these tools on his site for quite a long time, and to be honest as time goes on, they continue to deliver!
  4. Bing Webmaster Toolbox: Oh yeah, remember that other search engine? Yes that’s right Bing has a whole collection of tools of their own, including keyword tools. The data will be taken from Bing itself, which means that you should be able to make relative assumptions about keyword popularity. because lets face it, Bing users aren’t that different than Google’s.
  5. WordTracker: WordTracker is a commercial application that offers a free tool on their front end. I will admit that this free tool looks like it is mostly intended for you to sign up for the not free version, but it still provides a quick and clean interface for fast analysis.
  6. Keyword Discovery: This is a cool little tool in that it presents it’s data set in a very large easy to read table. Though their could improve a bit on the UI with better color scheme.
  7. WordPot: wordpot is an interesting little tool in that somehow it is able to provide daily search volume. This data point isn’t often provided by tools vendors, so this could be useful when correlating various metrics.
  8. Ubersuggest: Ubersuggest has long been a favorite of many SEOs that need keyword suggestion data. I personally love this tool not only for keyword research, but also just to learn more about a topic. Some of my favorite queries to run on this tool is “How do I” or “What does a”.
  9. KeywordSpy: This is another commercial option with a free front end. With this tool you can search for not only word variations, but also similar words, and spelling mistakes. It is designed mostly for PPC, but can still be useful for just getting your lists started.
  10. SEMRush: I am not sure I can talk enough about SEMRush. I use it often here at IMN. With this amazing tool set you can pretty much do any amount of reasearch that is needed. It is great for competitive research as well as individual keywords.
  11. SpyFu: While I mention competitive research, I need to mention Spyfu. With Spyfu you can do some searious damage to your competitors, as well as get a great overview of a keyword’s value.
  12. KGen: KGen is a bit unique in that it is a browser plugin that analyzes the keywords found on a page. It may not be a substitute for Google keyword tool, but it is a great place to start when needing to understand which keywords need targeting.


See, We still have great tools to do almost all of our keyword research without Google!

Basic Meeting Bot

I just created a simple room booking console app platform with ApiAi NLP. Room booking appointment will be added to the Outlook365 calendar after the appointment was done. There is still room for better improvement.


I’m using ApiAiSDK which you can get from GitHub.

Setup in Dialogflow:

        1. Create a new Agent
        2. Create a new Intents
          I have added room.reservation intent. In the action, parameters were set to capture the require info for room booking.intentsagentagent2
        3. Create Entities for the Intent
          Define the @Rooms entities by listing all the rooms available.entities

Code in C#:

Ensure that AIConfiguration & ApiAi is declared once for the entire flow else it will loss context as session Id will change if it re-declare again.


In the main function: Accept input value and display the response.



Method to submit to ApiAI: