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) {
        Throw(ex.Message);
      }
    }

Calling the method:

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

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:

db.Computers.OrderBy(x=>x.Location);

db.Computers.OrderBy(x=>x.Branch.display)

grid.JPG

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

Plugin:

plugin

At Table structure:

field

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");
   contextGR.initialize();
   contextGR.get("encrypt_sys_id");
   gs.addInfoMessage("encrypt context id:"+contextGR.sys_id+'');

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

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

   person.setDisplayValue('ciphers','abcde');
   person.setContextID(contextGR.sys_id+'');
   gs.addInfoMessage('decrypted val: '+person.ciphers.getDisplayValue());

 

Result:

result

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)
        {
            try
            {
                var req = Create("http://www.abc.com/api/inboundtest/Inbound", "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)
            {
                Console.WriteLine(ex.Message);
            }
}

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() {
  init();
  doSomethingElse();
};

 

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:


alert(document.getElementById("fname"));

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

alert(document.getElementById("fname")); 


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() {
                alert(this.value);
              });
          
          
        2. Use $(document).ready()
          This will parse all the codes into the DOM first before executing them.

          
              $(document).ready(function(){
              $("#fname").focusout(function(){
                alert(document.getElementById("fname").value);
                });
              });
          
          
        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: " + event.data.val );
          }
          
          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
});

or

$(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}}
]

 

$.ajax({
    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.message='Message';
		obj.httpStatus = response.getStatusCode();
		var oj = JSON.stringify(obj);

		 gs.setRedirect("x_person.do?x_person="+  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

Conclusion

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.