TargetInvocationException

Nov 7, 2013 at 4:29 AM
First of all.. .Kudos for this amazing library. I tried this simple test and got an exception and was wondering what I did wrong:
JScriptEngine engine = new JScriptEngine();
dynamic sum = engine.Evaluate(@"
                 (function (num1, num2) {
                        return num1+num2;
                  })
 ");
Calling, say, sum(1,2) triggers a System.Reflection.TargetInvocationException error for me. (.net 4.0, 32-bit).

My 2nd question: is there a way to enumerate through all properties of a dynamic object returned by the engine?

Any suggestions would be greatly appreciated!

Regards
Coordinator
Nov 7, 2013 at 10:04 AM
Edited Nov 7, 2013 at 3:35 PM
Hello jvillegas! Thank you for your questions.

There seems to be a bug in the underlying script engine. When invoked to evaluate a stand-alone anonymous function expression, JScript misinterprets it as a function statement and returns undefined. You can work around the bug by expanding the expression slightly:
dynamic sum = engine.Evaluate(@"
    (function (num1, num2) {
        return num1 + num2;
    }).valueOf()
");
Note that V8 does not have this bug.

As for your second question, there are several ways to enumerate the properties of a script object. One way is to use DynamicObject.GetDynamicMemberNames():
var obj = (DynamicObject)engine.Evaluate("({ foo: 123, bar: 'qux' })");
foreach (var name in obj.GetDynamicMemberNames()) {
    Console.WriteLine(name);
}
You can also use script code to enumerate object properties. The host and script engine can work together:
dynamic getNames = engine.Evaluate(@"
    (function (obj) {
        var names = [];
        for (var name in obj) {
            names.push(name);
        }
        return names;
    }).valueOf()
");

dynamic names = getNames(obj);
for (var i = 0; i < names.length; i++) {
    Console.WriteLine(names[i]);
}
Good luck!
Nov 9, 2013 at 4:45 AM
Thank you!!... Awesome library.