Tuesday, February 19, 2013

Convert javascript array to .NET List when using HtmlDocument.InvokeScript method

When you return an string array from a call to HtmlDocument.InvokeScript it returns it with the type "Object". Below I propose a solution to convert the array to a List in C#.

First of all we will define a class that will help us. It exposes 2 methods: length and getValue. length return the number of elements in the array and getValue(index) returns the value at index "index".

function mgArray(array){
 this.links = array;
 this.length = function(){
  return this.links.length;
 };
 this.getValue = function(index){
  return this.links[index];
 };
};

When we return an array "arrayName" we will use: return new mgArray(arrayName);

And below is the code that habdles the conversion in C#

private static List mgArrayToStringList(object comObject)
        {
            Type comObjectType = comObject.GetType();

            int count = (int)comObjectType.InvokeMember("length", BindingFlags.InvokeMethod, null, comObject, null);
            var result = new List(count);

            var indexArgs = new object[1];
            for (int i = 0; i < count; i++)
            {
                indexArgs[0] = i;
                object valueAtIndex = comObjectType.InvokeMember("getValue", BindingFlags.InvokeMethod, null, comObject, indexArgs);
                result.Add(valueAtIndex.ToString());
            }

            return result;
        }

The above code can be tweaked and used not only for List but for any oter base type of object.

No comments: