Exemplo n.º 1
0
        public async Task <Result> ExecuteScriptAsync(string script, CancellationToken cancellationToken)
        {
            using (var context = new ZvsContext(EntityContextConnection))
            {
                JintEngine.SetValue("zvsContext", context);

                JintEngine.SetValue("logInfo", new Action <object>(LogInfo));
                JintEngine.SetValue("logWarn", new Action <object>(LogWarn));
                JintEngine.SetValue("logError", new Action <object>(LogError));
                JintEngine.SetValue("setTimeout", new Action <string, double>(SetTimeout));
                JintEngine.SetValue("shell", new Func <string, string, Process>(Shell));

                JintEngine.SetValue("runDeviceNameCommandName", new Func <string, string, string, Result>(RunDeviceNameCommandName));
                JintEngine.SetValue("runCommand", new Func <int, string, string, Result>(RunCommand));

                JintEngine.SetValue("require", new Action <string>(Require));

                JintEngine.SetValue("mappath", new Func <string, string>(MapPath));
                try
                {
                    //pull out import statements
                    //import them into the JintEngine by running each script
                    //then run the JintEngine as normal

                    var result = await Task.Run(() => JintEngine.Execute(script), cancellationToken);

                    return(Result.ReportSuccessFormat("JavaScript execution complete. {0}", result));
                }
                catch (Exception ex)
                {
                    return(Result.ReportErrorFormat("JavaScript execution error. {0}", ex.Message));
                }
            }
        }
Exemplo n.º 2
0
        public void Require(string script)
        {
            var path = script;

            if (!File.Exists(path))
            {
                path = $"scripts\\{script}";
                if (!File.Exists(path))
                {
                    return;
                }

                script = path;
            }

            var s = File.ReadAllText(script);

            try
            {
                JintEngine.Execute(s);
            }
            catch (Exception e)
            {
                Log.ReportErrorFormatAsync(CancellationToken.None, "Error in required file {0}. {1}", script, e.Message).Wait();
            }
        }
Exemplo n.º 3
0
        public void ShouldNotRunInRun()
        {
            var filename = Path.GetTempFileName();
            File.WriteAllText(filename, "a='bar'");

            var engine = new JintEngine().AddPermission(new FileIOPermission(PermissionState.None));
            engine.AllowClr();
            engine.SetFunction("load", new Action<string>(p => engine.ExecuteFile(p)));
            engine.SetFunction("print", new Action<string>(Console.WriteLine));
            engine.Execute("var a='foo'; load('" + EscapeStringLiteral(filename) + "'); print(a);");
        }
Exemplo n.º 4
0
        public void ShouldRunInRun()
        {
            var filename = Path.GetTempFileName();
            File.WriteAllText(filename, "a='bar'");

            var engine = new JintEngine().AddPermission(new FileIOPermission(PermissionState.Unrestricted));
            engine.AllowClr();

            // The DLR compiler won't compile with permissions set
            engine.DisableSecurity();

            engine.SetFunction("load", new Action<string>(p => engine.ExecuteFile(p)));
            engine.SetFunction("print", new Action<string>(Console.WriteLine));
            engine.Execute("var a='foo'; load('" + EscapeStringLiteral(filename) + "'); print(a);");

            File.Delete(filename);
        }
Exemplo n.º 5
0
 protected virtual object RunScript(JintEngine ctx, string script)
 {
     return ctx.Execute(script);
 }
Exemplo n.º 6
0
        private static void ExecuteV8()
        {
            const string fileName = @"..\..\..\Jint.Benchmarks\Suites\V8\raytrace.js";

            var jint = new JintEngine();

            jint.DisableSecurity();

            jint.ExecuteFile(@"..\..\..\Jint.Benchmarks\Suites\V8\base.js");

            jint.SetFunction(
                "NotifyResult",
                new Action<string, string>((name, result) => { })
            );
            jint.SetFunction(
                "NotifyError",
                new Action<string, object>((name, error) => { })
            );

            string score = null;

            jint.SetFunction(
                "NotifyScore",
                new Action<string>(p => { score = p; })
            );

            jint.ExecuteFile(fileName);

            Console.WriteLine("Attach");
            Console.ReadLine();

            jint.Execute(@"
                BenchmarkSuite.RunSuites({
                    NotifyResult: NotifyResult,
                    NotifyError: NotifyError,
                    NotifyScore: NotifyScore,
                    Runs: 1
            });");

            Console.WriteLine("Score: " + score);
        }
Exemplo n.º 7
0
        protected override void RunInclude(JintEngine engine, string fileName)
        {
            string source;

            if (!_includeCache.TryGetValue(fileName, out source))
            {
                source =
                    GetSpecialInclude(fileName) ??
                    File.ReadAllText(Path.Combine(_libPath, fileName));

                _includeCache.Add(fileName, source);
            }

            engine.Execute(source, fileName);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Evaluate a code and return a value
        /// </summary>
        /// <param name="discardFromDebugView">true to discard from Debug View, in Debug mode (used to prevent pollution of executed modules in Visual Studio Code)</param>
        public object Evaluate(string script, bool discardFromDebugView = false)
        {
            if (script is null)
            {
                throw new ArgumentNullException(nameof(script));
            }
            switch (Type)
            {
            case JsScriptRunnerType.Jint:
            {
                try
                {
                    return(JintEngine.Execute(script) // from https://github.com/sebastienros/jint
                           .GetCompletionValue()      // get the latest statement completion value
                           .ToObject());              // converts the value to .NET
                }
                catch (Esprima.ParserException ex)
                {
                    throw new ApplicationException($"{ex.Error} (Line {ex.LineNumber}, Column {ex.Column}), -> {ReadLine(script, ex.LineNumber)}", ex);
                }
                catch (Jint.Runtime.JavaScriptException ex)          // from https://github.com/sebastienros/jint/issues/112
                {
                    throw new ApplicationException($"{ex.Error} (Line {ex.LineNumber}, Column {ex.Column}), -> {ReadLine(script, ex.LineNumber)}", ex);
                }
            }

            case JsScriptRunnerType.ClearScriptDebugMode:
            {
                try
                {
                    if (discardFromDebugView)
                    {
                        return(ClearScriptEngine.Evaluate(string.Empty, true, script));
                    }
                    else
                    {
                        // see https://microsoft.github.io/ClearScript/Reference/html/M_Microsoft_ClearScript_ScriptEngine_Evaluate_2.htm
                        return(ClearScriptEngine.Evaluate(ReadAndNormalizeFirstNonEmptyLineOfAScript(script), false, script));
                    }
                }
                catch (Microsoft.ClearScript.ScriptEngineException ex)          // from https://github.com/microsoft/ClearScript/issues/16
                {
                    throw new ApplicationException($"{ex.ErrorDetails}", ex);
                }
            }

            case JsScriptRunnerType.ClearScript:
            {
                try
                {
                    // see https://microsoft.github.io/ClearScript/Reference/html/M_Microsoft_ClearScript_ScriptEngine_Evaluate_2.htm
                    return(ClearScriptEngine.Evaluate(script));
                }
                catch (Microsoft.ClearScript.ScriptEngineException ex)          // from https://github.com/microsoft/ClearScript/issues/16
                {
                    throw new ApplicationException($"{ex.ErrorDetails}", ex);
                }
            }
            }
            throw new InvalidOperationException("unexpected case");
        }
Exemplo n.º 9
0
        public void Run(string script, bool discardFromDebugView = false)
        {
            if (script is null)
            {
                throw new ArgumentNullException(nameof(script));
            }
            switch (Type)
            {
            case JsScriptRunnerType.Jint:
            {
                try
                {
                    JintEngine.Execute(script);
                    break;
                }
                catch (Esprima.ParserException ex)
                {
                    throw new ApplicationException($"{ex.Error} (Line {ex.LineNumber}, Column {ex.Column}), -> {ReadLine(script, ex.LineNumber)}", ex);
                }
                catch (Jint.Runtime.JavaScriptException ex)          // from https://github.com/sebastienros/jint/issues/112
                {
                    throw new ApplicationException($"{ex.Error} (Line {ex.LineNumber}, Column {ex.Column}), -> {ReadLine(script, ex.LineNumber)}", ex);
                }
            }

            case JsScriptRunnerType.ClearScriptDebugMode:
            {
                try
                {
                    if (discardFromDebugView)
                    {
                        // see https://microsoft.github.io/ClearScript/Reference/html/M_Microsoft_ClearScript_ScriptEngine_Execute_2.htm
                        ClearScriptEngine.Execute(string.Empty, true, script);
                    }
                    else
                    {
                        ClearScriptEngine.Execute(ReadAndNormalizeFirstNonEmptyLineOfAScript(script), false, script);
                    }
                    break;
                }
                catch (Microsoft.ClearScript.ScriptEngineException ex)          // from https://github.com/microsoft/ClearScript/issues/16
                {
                    throw new ApplicationException($"{ex.ErrorDetails}", ex);
                }
            }

            case JsScriptRunnerType.ClearScript:
            {
                try
                {
                    // see https://microsoft.github.io/ClearScript/Reference/html/M_Microsoft_ClearScript_ScriptEngine_Execute_2.htm
                    ClearScriptEngine.Execute(script);
                    break;
                }
                catch (Microsoft.ClearScript.ScriptEngineException ex)          // from https://github.com/microsoft/ClearScript/issues/16
                {
                    throw new ApplicationException($"{ex.ErrorDetails}", ex);
                }
            }
            }
        }
Exemplo n.º 10
0
 public void ShouldNotReproduceBug85418()
 {
     var engine = new JintEngine();
     engine.SetParameter("a", 4);
     Assert.AreEqual(4, engine.Execute("return a"));
     Assert.AreEqual(4d, engine.Execute("return 4"));
     Assert.AreEqual(true, engine.Execute("return a == 4"));
     Assert.AreEqual(true, engine.Execute("return 4 == 4"));
     Assert.AreEqual(true, engine.Execute("return a == a"));
 }
Exemplo n.º 11
0
        public void ShouldHandleClrArrays()
        {
            var values = new int[] { 2, 3, 4, 5, 6, 7 };
            var jint = new JintEngine()
            .SetParameter("a", values)
            .AllowClr();

            Assert.AreEqual(3, jint.Execute("a[1];"));
            jint.Execute("a[1] = 4");
            Assert.AreEqual(4, jint.Execute("a[1];"));
            Assert.AreEqual(4, values[1]);

        }
Exemplo n.º 12
0
        public void ShouldRetainGlobalsThroughRuns()
        {
            var jint = new JintEngine();

            jint.Execute("i = 3; function square(x) { return x*x; }");

            Assert.AreEqual(3d, jint.Execute("return i;"));
            Assert.AreEqual(9d, jint.Execute("return square(i);"));
        }
Exemplo n.º 13
0
 public void ShouldReturnDelegateForFunctions()
 {
     const string script = "ccat=function (arg1,arg2){ return arg1+' '+arg2; }";
     JintEngine engine = new JintEngine().SetFunction("print", new Action<string>(Console.WriteLine));
     engine.Execute(script);
     Assert.AreEqual("Nicolas Penin", engine.CallFunction("ccat", "Nicolas", "Penin"));
 }
Exemplo n.º 14
0
 public void SetTimeout(string function, double millisecondsDelay)
 {
     Task.Delay((int)millisecondsDelay).Wait();
     JintEngine.Execute(function);
 }