Nested Loop From A Folder to Get Files In Servers

Nested loop to do whatever you need to do with the files and folders in the server remotely using ManagementScope. This function will loop the first layer or loop nested until the end.

public static IEnumerable queryByFolder(ManagementScope scope, string path, bool withSecurity, bool recursive) {
        if (String.isNullOrEmpty(path)) throw new Exception("Please specified folder.");

          if (recursive) {
            foreach (var subdir in dir.GetSubDirectories(scope, path, true)) {
              foreach (var f in queryByFolder(scope, subdir, withSecurity)) yield return f;
          foreach (var f in queryByFolder(scope, path, withSecurity)) yield return f;

        yield break;

Disable a Textbox when Text Change In WinForm Textbox

When text changed method being trigger, getting the updated value from ‘sender’ to execute requirements.

private void _onTxtPrefix_TextChanged(object sender, EventArgs e) {
   var t = (Control)sender;
   if (t.Text == "abc") { txtFqdn.Text = "12345"; txtFqdn.Enabled = false; }
   else { txtFqdn.Text = ""; txtFqdn.ReadOnly = false; txtFqdn.Enabled = true; }

List All Files and Directories in a Directory

Getting all files and directories within a directory:

input parameter: string directory path and empty list string to add file paths

public static void DirectorySearch(string dir, Listlst) {
      try {
        string[] fl = Directory.GetFiles(dir);
        string[] dl = Directory.GetDirectories(dir);
        if (fl.Length > 0 || dl.Length > 0) {
          foreach (string f in fl) {
            lst.Add("f: " + Path.GetFileName(f));
          foreach (string d in dl) {
            //lst.Add("d: " + Path.GetFileName(d));
            DirectorySearch(d, lst);
      } catch (System.Exception ex) {

Calling the method:

var lst = new List();
DirectorySearch("C:\\testfolder", lst);

Updated way to do the same process: Here

Build a Lambda Expression Dynamically For Sort Acs/Desc

I have tried writing my own basic dynamic lambda expression for sorting the columns in grid panel. There are columns with different property type, and a few link to other object.

In this example Branch column (in computer object as a property) is link to Lookup object. I want to order by display field in Lookup object.

example of lambda expression:




Below code will generate the lambda expression dynamically to sort asc/desc.

public static IQueryable SortComputers(this IQueryable source, string Field, bool desc) {
      var elType = typeof(Computer);
      var fp = elType.GetProperty(Field);

      var method = desc ? "OrderByDescending" : "OrderBy";

      var ep = Expression.Parameter(elType, "x");      // x =>
      var member = Expression.MakeMemberAccess(ep, fp); // x.field
      Expression exprSelector;
      var tyLookup = typeof(Lookup);
      if (member.Type == tyLookup) {
        MemberInfo miDisplay = tyLookup.GetProperty("display");
        member = Expression.MakeMemberAccess(member, miDisplay); //x.field.display
      exprSelector = Expression.Lambda(member, ep);    // x => x.field || x.field.display
      var exprResult = Expression.Call(typeof(Queryable), method, new Type[] { elType, member.Type },
                       source.Expression, Expression.Quote(exprSelector));

      return source.Provider.CreateQuery(exprResult);


To call the function:

if (model.Sort.Length > 0) {
            results = mylinq.SortComputers(d, model.SimpleSort,
            (model.SimpleSortDirection == SortDirection.DESC)).ToArray();


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

Connect to WMI remotely to Copy File from Server to Local Computer

Below a function which remote to server to copy a file to local pc through Windows Management Infrastructure (WMI).

public static void copyfiletolocal(ManagementScope scope)

            ObjectQuery oq = new ObjectQuery(@"Select * from CIM_Datafile WHERE Extension = 'txt' AND FileName = 'FileName'");

            ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(scope, oq);

            using (ManagementObjectCollection oReturns = oSearcher.Get())
                foreach(ManagementObject oReturn in oReturns)
                    oReturn.Scope = scope;
                    ManagementBaseObject inputArgs = oReturn.GetMethodParameters("Copy");
                    inputArgs["FileName"] = @"C:\\";
                    ManagementBaseObject outParams = oReturn.InvokeMethod("Copy",inputArgs,null);
                    uint ret = (uint)(outParams.Properties["ReturnValue"].Value);
                    if (ret == 0)
                        Console.WriteLine("Failed with error code: {0}", ret);



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);