5

I just download the Iron JS and after doing some 2/3 simple programs using the Execute method, I am looking into the ExecuteFile method.

I have a Test.js file whose content is as under

function Add(a,b)
{
    var result = a+b;
    return result;
}

I want to invoke the same from C# using Iron JS. How can I do so? My code so far

var o = new IronJS.Hosting.CSharp.Context();
dynamic loadFile = o.ExecuteFile(@"d:\test.js");
var result = loadFile.Add(10, 20);

But loadfile variable is null (path is correct)..

How to invoke JS function ,please help... Also searching in google yielded no help.

Thanks

John Saunders
  • 160,644
  • 26
  • 247
  • 397
learner123
  • 243
  • 1
  • 4
  • 10
  • I have revised my answer to work with the NuGet package. My previous answer was based on our current master branch. I had forgotten that the dynamic stuff was not in NuGet yet. – John Gietzen Aug 31 '11 at 02:15
  • Your edit completely changed the question, and also made the question worthless. I've rolled back to the original version. If you want to go back to your version, it's your choice, but I, for one, will then vote to close the question as "Not a real question". – John Saunders Aug 31 '11 at 03:00
  • Yes, it happened by mistake.. thanks for rolling it back. – learner123 Aug 31 '11 at 03:03

1 Answers1

6

The result of the execution is going to be null, because your script does not return anything.

However, you can access the "globals" object after the script has run to grab the function.

var o = new IronJS.Hosting.CSharp.Context();
o.ExecuteFile(@"d:\test.js");
dynamic globals = o.Globals;

var result = globals.Add(10, 20);

EDIT: That particular version will work with the current master branch, and in an up-coming release, but is not quite what we have working with the NuGet package. The slightly more verbose version that works with IronJS version 0.2.0.1 is:

var o = new IronJS.Hosting.CSharp.Context();
o.ExecuteFile(@"d:\test.js");
var add = o.Globals.GetT<FunctionObject>("Add");

var result = add.Call(o.Globals, 10D, 20D).Unbox<double>();
John Gietzen
  • 48,783
  • 32
  • 145
  • 190
  • Sir, 1 question(i don't know if it is relevant to ask), when will Iron JS be release officially? – learner123 Aug 31 '11 at 04:58
  • Fredrik Holmstrom would be the person to ask, but you can consider the releases up on NuGet as "supported", in that we try to be very active in fixing issues and publishing updates. – John Gietzen Aug 31 '11 at 20:16