-1

I get a exception if I try to use GetCompletionValue with Invoker.
How can i execute the run function with IIFE lexical scope?

Javascript:

(function(){
  function run() {
    logger('teste logger');

    var file = new System.IO.StreamWriter('log.txt');
        file.WriteLine('Write file test');
        file.Dispose();
  }

  return {
    'run': run
  }
})();

My Invoker:

public void Execute(string code, string functionName)
{
  _engine.Execute(code).GetCompletionValue();
  _engine.Invoke(functionName); // -- run function
}

Error:

Exception has occurred: CLR/System.ArgumentException
An exception of type 'System.ArgumentException' occurred in Jint.dll but was not handled in user code: 'Can only invoke functions'
   at Jint.Engine.Invoke(JsValue value, Object thisObj, Object[] arguments)
   at Jint.Engine.Invoke(String propertyName, Object thisObj, Object[] arguments)
   at Jint.Engine.Invoke(String propertyName, Object[] arguments)

1 Answers1

1

How can i execute the run function with IIFE lexical scope?

The reason why causes 'System.ArgumentException' is the codes in Javascript. Function codes of format are invalid. Change it like codes below:

          function run() {
            logger('teste logger');

            var file = new System.IO.StreamWriter('log.txt');
                file.WriteLine('Write file test');
                file.Dispose();
          }

As for lexical scope, you could also try these codes below:

        String code = @"

          function go(){
                function run() {
                logger('teste logger');

                var file = new System.IO.StreamWriter('log.txt');
                    file.WriteLine('Write file test');
                    file.Dispose();
                }

                return run();
            }

        ";
        Execute(code, "go");



ConsoleApplication Examples of using Jint in .NET Core 3.1

class Program
{

    public static Engine _engine = new Engine(cfg => cfg.AllowClr());


    static void Main(string[] args)
    {
        _engine.SetValue("logger", new Action<object>(Console.WriteLine));

        String code = @"

          function run() {
            logger('teste logger');

            var file = new System.IO.StreamWriter('log.txt');
                file.WriteLine('Write file test');
                file.Dispose();
          }

        ";
        Execute(code, "run");
    }

    public static void Execute(string code, string functionName)
    {
        _engine.Execute(code).GetCompletionValue();
        _engine.Invoke(functionName); // -- run function
    }
}

Test

It works as run function expected.

enter image description here

Michael Wang
  • 3,782
  • 1
  • 5
  • 15