コード例 #1
0
 protected override ElementString TranslateToElementString(string sRawString, int nCardIndex, DeckLine zDeckLine, ProjectLayoutElement zElement)
 {
     using (var engine = new V8ScriptEngine())
     {
         var sScript = GetJavaScript(nCardIndex, zDeckLine, sRawString);
         try
         {
             var sValue = engine.Evaluate(sScript);
             if (sValue is string || sValue is int)
             {
                 return new ElementString()
                 {
                     String = sValue.ToString()
                 };
             }
             else
             {
                 Logger.AddLogLine(sValue.GetType().ToString());
             }
         }
         catch (Exception e)
         {
             Logger.AddLogLine(e.Message);
         }
     }
     return new ElementString()
     {
         String = string.Empty
     };
 }
コード例 #2
0
        public IActionResult Index()
        {
            string result = "Ok";

            try
            {
                var engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDateTimeConversion);
                engine.AddHostObject("host", new HostFunctions());
                engine.AddHostType("LoggerConsole", typeof(LoggerConsole));
                // engine.Execute(@" var o=new LoggerConsole();   o.Log(2+3+''); ");
                result = engine.Evaluate(@" 2+3 ") + "";
            }
            catch (Exception ex)
            {
                result = "Error " + ex.Message;
            }
            return(View("Index", result));
        }
コード例 #3
0
        private static void Execute(Context context)
        {
            try
            {
                using var engine = new V8ScriptEngine
                      {
                          AllowReflection = true
                      };

                engine.AddHostObject("context", context);

                Console.WriteLine(engine.Evaluate("context.Value.ToString()"));
            }
            catch (Exception exception)
            {
                Console.WriteLine($"{exception.Message} Error testing {context.Value} [{context.Value.GetType().Name}]");
            }
        }
コード例 #4
0
        private object ProcessIf(V8ScriptEngine scriptEngine, Dictionary <object, object> parameters)
        {
            object value      = null;
            var    testResult = scriptEngine.Evaluate(parameters["test"] as string);

            if (testResult is bool && (bool)testResult)
            {
                if (parameters.TryGetValue("then", out value))
                {
                    return(ApplyYamlExpressions(scriptEngine, value));
                }
            }
            else if (parameters.TryGetValue("else", out value))
            {
                return(ApplyYamlExpressions(scriptEngine, value));
            }

            return(value);
        }
コード例 #5
0
        private object ProcessEach(V8ScriptEngine scriptEngine, Dictionary <object, object> parameters)
        {
            var    list = new List <object>();
            object variableNameObj;

            if (parameters.TryGetValue("var", out variableNameObj))
            {
                if (variableNameObj is string)
                {
                    var    variableName = variableNameObj as string;
                    object inListTextObj;
                    if (parameters.TryGetValue("in", out inListTextObj))
                    {
                        if (inListTextObj is string)
                        {
                            object doObj;
                            if (parameters.TryGetValue("do", out doObj))
                            {
                                object inListObj = scriptEngine.Evaluate(inListTextObj as string);
                                if (inListObj is IEnumerable)
                                {
                                    foreach (var itemObj in (IEnumerable)inListObj)
                                    {
                                        scriptEngine.AddHostObject(variableName, itemObj);
                                        var itemResult = ApplyYamlExpressions(scriptEngine, doObj);
                                        list.Add(itemResult);
                                    }
                                }
                                else
                                {
                                    scriptEngine.AddHostObject(variableName, inListObj);
                                    var itemResult = ApplyYamlExpressions(scriptEngine, doObj);
                                    list.Add(itemResult);
                                }
                            }
                            return(list);
                        }
                    }
                }
            }
            throw new Exception("Invalid $each");
        }
コード例 #6
0
        public void Evaluated_ExpectedResult_2()
        {
            // Arrange
            var engine   = new V8ScriptEngine();
            int actual   = 0;
            int expected = 2;

            // Act
            try
            {
                actual = (int)engine.Evaluate("1+1");
            }
            finally
            {
                engine.Dispose();
            }

            // Expect
            Assert.AreEqual(expected, actual);
        }
コード例 #7
0
        protected override object InnerEvaluate(string expression)
        {
            object result;

            lock (_executionSynchronizer)
            {
                try
                {
                    result = _jsEngine.Evaluate(expression);
                }
                catch (OriginalJsException e)
                {
                    throw ConvertScriptEngineExceptionToJsRuntimeException(e);
                }
            }

            result = MapToHostType(result);

            return(result);
        }
コード例 #8
0
        public void PropertyBag_MultiEngine_HostFunctions()
        {
            using (var scriptEngine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging))
            {
                const string code = "bag.host.func(0, function () { return bag.func(); })";
                var          bag  = new PropertyBag
                {
                    { "host", new HostFunctions() },
                    { "func", new Func <object>(() => ScriptEngine.Current) }
                };

                engine.AddHostObject("bag", bag);
                scriptEngine.AddHostObject("bag", bag);

                var func = (Func <object>)engine.Evaluate(code);
                Assert.AreSame(engine, func());

                func = (Func <object>)scriptEngine.Evaluate(code);
                Assert.AreSame(scriptEngine, func());
            }
        }
コード例 #9
0
        public T Execute <T>(string script, IEnumerable <KeyValuePair <string, object> > parameters)
        {
            var engine = new V8ScriptEngine();

            engine.AddHostType("Action", typeof(Action));
            engine.AddHostObject("console", _console);

            foreach (var kvp in parameters)
            {
                engine.AddHostObject(kvp.Key, kvp.Value);
            }

            var toReturn = engine.Evaluate(script);

            if (toReturn is T)
            {
                return((T)toReturn);
            }

            throw new ArgumentException("Expected " + typeof(T).FullName + " but got " + toReturn.GetType().FullName);
        }
コード例 #10
0
        private static void Execute(object context, string script)
        {
            try
            {
                using var engine = new V8ScriptEngine
                      {
                          AllowReflection = true
                      };

                engine.AddHostType(typeof(Enumerable));
                engine.AddHostObject("context", context);
                engine.AddHostObject("host", new HostFunctions());
                engine.AddHostType("func", typeof(Func <Object, int>));

                Console.WriteLine(engine.Evaluate(script));
            }
            catch (Exception exception)
            {
                Console.WriteLine($"{exception.Message} Error testing {context} [{context.GetType().Name}]");
            }
        }
コード例 #11
0
 /// <summary>
 /// process and apply any expression found inside double << >>
 /// i.e. "<" "<" (javascript expression) ">" ">"
 /// </summary>
 /// <param name="scriptEngine"></param>
 /// <param name="textWithExpressions"></param>
 /// <param name="outputYaml">When true the yaml representation of the expression is injected</param>
 /// <returns></returns>
 private string ApplyExpressions(V8ScriptEngine scriptEngine, string textWithExpressions, bool outputYaml)
 {
     return(_expressionMatcher.Replace(textWithExpressions, (match) =>
     {
         var expression = match.Groups[1].Value;
         if (string.IsNullOrWhiteSpace(expression))
         {
             return outputYaml ? "~" : "";
         }
         else
         {
             try
             {
                 var result = scriptEngine.Evaluate(expression);
                 if (result == null)
                 {
                     return outputYaml ? "~" : "";
                 }
                 else
                 {
                     var text = result.ToString();
                     if (outputYaml)
                     {
                         if (result is string)
                         {
                             return "\"" + text.Replace("\"", "\"\"") + "\"";
                         }
                     }
                     return text;
                 }
             }
             catch (Exception e)
             {
                 _logProvider.Warning("Error processing expression <<{expression}>>: {reason}", match.Value, e.Message);
                 return outputYaml ? "~" : "";
             }
         }
     }));
 }
コード例 #12
0
ファイル: XFADOM.cs プロジェクト: msavidg/XFAForms
        public void Test(XDPFile xdp, XDocument form)
        {
            _configDom.Initialize(_form);

            _connectionSetDom.Initialize(_form);

            _connectionDataDom.Initialize(_form);

            _xmlDataDom.Initialize(_formData);

            //xfa.record
            _xfaDataDom.Initialize(_xfaObject, _formData);

            //xfa.template
            _templateDom.Initialize(_xfaObject, _xdp, _form);

            _dataDescriptionDom.Initialize(_form);

            //xfa.form
            _formDom.Initialize(_form);

            _layoutDom.Initialize(_form);

            _engine.AddHostObject("xfa", _xfaObject);

            var a1 = _engine.Evaluate("xfa.record.CurrentRisk.Options.nodes.length");
            var a2 = _engine.Evaluate("xfa.record.CurrentRisk.Options.nodes.item(0)");
            var a3 = _engine.Evaluate("xfa.record.CurrentRisk.Options.nodes.item(0).OptionId.value");

            _engine.Execute("xfa.record.CurrentRisk.Options.nodes.item(0).OptionId.value=99");
            var a5 = _engine.Evaluate("xfa.record.CurrentRisk.Options.nodes.item(0).OptionId.value");
            var a6 = _engine.Evaluate("xfa.record.CurrentRisk.Options.nodes.item(0).OptionDetailECP.OptionDetailECPId.value");

            if (_xdp.Filename.Contains("Sample_001"))
            {
                var x = _xfaObject.template.GetDynamicMemberNames();

                var b1 = _engine.Evaluate("xfa.template.form1.minH");
                var b2 = _engine.Evaluate("xfa.template.form1.layout");
            }
        }
コード例 #13
0
        public void Run(string script, ViewModels.LogStream log, CancellationToken cancel)
        {
            var utils = new ScriptUtils(log, cancel);

            try
            {
                engine?.Interrupt();

                engine = new V8ScriptEngine();
                engine.AddHostObject("utils", utils);
                engine.AddHostObject("client", this.client);

                var evalResult = engine.Evaluate("script", script);
            }
            catch (ScriptEngineException e)
            {
                utils.WriteLine(e.ErrorDetails);
            }
            catch (ScriptInterruptedException e)
            {
                utils.WriteLine(e.ErrorDetails);
            }
        }
コード例 #14
0
ファイル: BugFixTest.cs プロジェクト: eswann/MyClearScript
        public void BugFix_V8CachedObjectLeak()
        {
            object        x  = null;
            WeakReference wr = null;

            new Action(() =>
            {
                using (var tempEngine = new V8ScriptEngine())
                {
                    tempEngine.AddHostType("Action", typeof(Action));
                    x  = tempEngine.Evaluate("action = new Action(function () {})");
                    wr = new WeakReference(tempEngine);
                }
            })();

            Assert.IsInstanceOfType(x, typeof(Action));
            TestUtil.AssertException <ObjectDisposedException>((Action)x);

            x = null;
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            GC.WaitForPendingFinalizers();
            Assert.IsFalse(wr.IsAlive);
        }
コード例 #15
0
        public static oResult Execute(string file___api, Dictionary <string, object> parameters = null, Dictionary <string, object> request = null)
        {
            if (request == null)
            {
                request = new Dictionary <string, object>();
            }
            if (parameters == null)
            {
                parameters = new Dictionary <string, object>();
            }

            oResult r = new oResult()
            {
                ok      = false,
                name    = file___api,
                input   = parameters,
                request = request
            };

            string file = Path.Combine(_CONFIG.PATH_ROOT, "_api\\" + file___api + ".js");

            if (File.Exists(file) == false)
            {
                r.error = "ERROR[clsEngineJS.Execute] Cannot found file: " + file;
                return(r);
            }

            if (!file.Contains("___"))
            {
                r.error = "ERROR[clsEngineJS.Execute] file___api: " + file___api + " must be format cache_name___api_name ";
                return(r);
            }

            string[] a = file___api.Split(new string[] { "___" }, StringSplitOptions.None);
            string   cache_name = a[0], api_name = a[1];

            try
            {
                string js = string.Empty;
                js = @"
                (function() {
                    'use strict';
                    try {
                        var ___log_text = function(text){ log___.write('" + file___api + @"', '_', text); };
                        var ___log_key = function(key, text){ log___.write('" + file___api + @"', key, text); };
                        var ___api_call = function(api_name, paramenter, request, result_type){ var v = ___api.js_call(api_name, JSON.stringify(paramenter), JSON.stringify(request)); if(result_type == 'text') return v; else return JSON.parse(v); };

                        var ___request = " + JsonConvert.SerializeObject(request) + @";
                        var ___parameters = " + JsonConvert.SerializeObject(parameters) + @";

                        ___log_text('This is from JavaScript...');

                        " + File.ReadAllText(file) + @"

                    } catch(e) {
                        return { ok: false, name: '" + file___api + @"', error: e.message };
                    }
                })();
                ";

                var toReturn = m_engine.Evaluate(js);
                if (toReturn is Microsoft.ClearScript.Undefined)
                {
                    r.ok = true;
                }
                else if (toReturn is string)
                {
                    string json = toReturn.ToString();
                    try
                    {
                        r = JsonConvert.DeserializeObject <oResult>(json);
                    }
                    catch (Exception ejs)
                    {
                        r.error = ejs.Message;
                        r.data  = json;
                    }
                }

                //////else
                //////{
                //////    try
                //////    {
                //////        dynamic dynamicResult = toReturn;
                //////        foreach (string name in dynamicResult.GetDynamicMemberNames())
                //////        {
                //////            switch (name)
                //////            {
                //////                case "ok":
                //////                    r.ok = Convert.ToBoolean(dynamicResult[name]);
                //////                    break;
                //////                case "request":
                //////                    break;
                //////                case "input":
                //////                    break;
                //////                case "name":
                //////                    r.name = Convert.ToString(dynamicResult[name]);
                //////                    break;
                //////                case "error":
                //////                    r.error = Convert.ToString(dynamicResult[name]);
                //////                    break;
                //////            }
                //////        }
                //////    }
                //////    catch (Exception ejs)
                //////    {
                //////        r.error = ejs.Message;
                //////    }
                //////}
            }
            catch (Exception e)
            {
                r.error = "ERROR_THROW: " + e.Message;
            }
            return(r);
        }
コード例 #16
0
        public IMockEngineResponse Invoke(string scenarioName, object dynamicProperties = null)
        {
            if (scenarioName == null)
            {
                throw new ArgumentNullException(nameof(scenarioName));
            }

            _logProvider.Verbose("Invoking scenario {scenarioName}", scenarioName);

            var scenario = _scenarioManager.GetScenario(scenarioName);

            if (scenario == null)
            {
                throw new ArgumentOutOfRangeException(nameof(scenarioName), $"scenario \"{scenarioName}\" was not found.");
            }

            using (var scriptEngine = new V8ScriptEngine())
            {
                scriptEngine.AllowReflection = true;

                scriptEngine.Script["scenarioName"] = scenarioName;

                SetInputParameters(scriptEngine, dynamicProperties);

                SetGlobals(scriptEngine, scenario);

                if (scenario.Global != null && !string.IsNullOrWhiteSpace(scenario.Global.Before))
                {
                    try
                    {
                        scriptEngine.Execute(scenario.Global.Before);
                    }
                    catch (Exception e)
                    {
                        throw new MockEngineException(this.Name, scenarioName, $"error executing global Before code: {e.Message}", e);
                    }
                }

                MockEngineResponse response = null;

                foreach (var action in scenario.Actions)
                {
                    try
                    {
                        if (action.When == null)
                        {
                            response = ExecuteAction(scriptEngine, scenarioName, action);
                            break;
                        }
                        else
                        {
                            var caseResult = scriptEngine.Evaluate(action.When);
                            if (caseResult is bool)
                            {
                                if ((bool)caseResult)
                                {
                                    response = ExecuteAction(scriptEngine, scenarioName, action);
                                    break;
                                }
                            }
                            else
                            {
                                _logProvider.Warning("action: {action} case expression did not return a boolean result", action);
                            }
                        }
                    }
                    catch (MockEngineException e)
                    {
                        var message = $"action: {action} exception: {e.Message}";
                        _logProvider.Error(e, "action: {action} exception: {message}", action, e.Message);
                        throw new MockEngineException(this.Name, scenarioName, message, e);
                    }
                    catch (Exception e)
                    {
                        _logProvider.Error(e, "action: {action} exception: {message}", action, e.Message);
                        throw new MockEngineException(this.Name, scenarioName, $"action: {action} exception: {e.Message}", e);
                    }
                }
                if (scenario.Global != null && !string.IsNullOrWhiteSpace(scenario.Global.After))
                {
                    try
                    {
                        scriptEngine.Execute(scenario.Global.After);
                    }
                    catch (Exception e)
                    {
                        throw new MockEngineException(this.Name, scenarioName, $"error executing global After code: {e.Message}", e);
                    }
                }

                if (response != null)
                {
                    return(response);
                }
            }

            var reasonPhrase = $"scenario: \"{scenarioName}\" did not contain any matching actions for this request.";

            _logProvider.Error("scenario: {scenarioName} did not contain any matching actions for this request.", scenarioName);

            return(new MockEngineResponse()
            {
                ReasonPhrase = reasonPhrase
            });
        }
コード例 #17
0
ファイル: BugFixTest.cs プロジェクト: dirkelfman/ClearScript
        public void BugFix_V8CachedObjectLeak()
        {
            object x = null;
            WeakReference wr = null;

            new Action(() =>
            {
                using (var tempEngine = new V8ScriptEngine())
                {
                    tempEngine.AddHostType("Action", typeof(Action));
                    x = tempEngine.Evaluate("action = new Action(function () {})");
                    wr = new WeakReference(tempEngine);
                }
            })();

            Assert.IsInstanceOfType(x, typeof(Action));
            TestUtil.AssertException<ObjectDisposedException>((Action)x);

            x = null;
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            GC.WaitForPendingFinalizers();
            Assert.IsFalse(wr.IsAlive);
        }
コード例 #18
0
        public void PropertyBag_MultiEngine_HostFunctions()
        {
            using (var scriptEngine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging))
            {
                const string code = "bag.host.func(0, function () { return bag.func(); })";
                var bag = new PropertyBag
                {
                    { "host", new HostFunctions() },
                    { "func", new Func<object>(() => ScriptEngine.Current) }
                };

                engine.AddHostObject("bag", bag);
                scriptEngine.AddHostObject("bag", bag);

                var func = (Func<object>)engine.Evaluate(code);
                Assert.AreSame(engine, func());

                func = (Func<object>)scriptEngine.Evaluate(code);
                Assert.AreSame(scriptEngine, func());
            }
        }
コード例 #19
0
 public bool Exists(string name)
 {
     return((bool)_context.Evaluate("typeof Handlebars.templates['" + name + "'] == 'function';"));
 }
コード例 #20
0
        public void V8ScriptEngine_General_Precompiled_Dual()
        {
            engine.Dispose();
            using (var runtime = new V8Runtime())
            {
                using (var script = runtime.Compile(generalScript))
                {
                    engine = runtime.CreateScriptEngine();
                    using (var console = new StringWriter())
                    {
                        var clr = new HostTypeCollection(type => type != typeof(Console), "mscorlib", "System", "System.Core");
                        clr.GetNamespaceNode("System").SetPropertyNoCheck("Console", console);

                        engine.AddHostObject("host", new ExtendedHostFunctions());
                        engine.AddHostObject("clr", clr);

                        engine.Evaluate(script);
                        Assert.AreEqual(MiscHelpers.FormatCode(generalScriptOutput), console.ToString().Replace("\r\n", "\n"));

                        console.GetStringBuilder().Clear();
                        Assert.AreEqual(string.Empty, console.ToString());

                        engine.Evaluate(script);
                        Assert.AreEqual(MiscHelpers.FormatCode(generalScriptOutput), console.ToString().Replace("\r\n", "\n"));
                    }

                    engine.Dispose();
                    engine = runtime.CreateScriptEngine();
                    using (var console = new StringWriter())
                    {
                        var clr = new HostTypeCollection(type => type != typeof(Console), "mscorlib", "System", "System.Core");
                        clr.GetNamespaceNode("System").SetPropertyNoCheck("Console", console);

                        engine.AddHostObject("host", new ExtendedHostFunctions());
                        engine.AddHostObject("clr", clr);

                        engine.Evaluate(script);
                        Assert.AreEqual(MiscHelpers.FormatCode(generalScriptOutput), console.ToString().Replace("\r\n", "\n"));

                        console.GetStringBuilder().Clear();
                        Assert.AreEqual(string.Empty, console.ToString());

                        engine.Evaluate(script);
                        Assert.AreEqual(MiscHelpers.FormatCode(generalScriptOutput), console.ToString().Replace("\r\n", "\n"));
                    }
                }
            }
        }
コード例 #21
0
ファイル: BugFixTest.cs プロジェクト: dirkelfman/ClearScript
        public void BugFix_V8CompiledScriptDispose()
        {
            V8Script script1;
            using (var tempEngine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging))
            {
                script1 = tempEngine.Compile("(function () { return 123; })()");
                Assert.AreEqual(123, tempEngine.Evaluate(script1));

                V8Script script2 = tempEngine.Compile("(function () { return 456; })()");
                using (script2)
                {
                    Assert.AreEqual(456, tempEngine.Evaluate(script2));

                }
            }

            using (script1)
            {
            }
        }
コード例 #22
0
ファイル: BugFixTest.cs プロジェクト: dirkelfman/ClearScript
        public void BugFix_V8RuntimeConstraintScale()
        {
            const int maxNewSpaceSize = 16;
            const int maxOldSpaceSize = 512;

            var constraints = new V8RuntimeConstraints
            {
                MaxNewSpaceSize = maxNewSpaceSize,
                MaxOldSpaceSize = maxOldSpaceSize
            };

            using (var tempEngine = new V8ScriptEngine(constraints))
            {
                Assert.AreEqual(Math.PI, tempEngine.Evaluate("Math.PI"));
                Assert.AreEqual(Convert.ToUInt64(maxNewSpaceSize * 4 + maxOldSpaceSize), tempEngine.GetRuntimeHeapInfo().HeapSizeLimit / (1024 * 1024));
            }

            constraints = new V8RuntimeConstraints
            {
                MaxNewSpaceSize = maxNewSpaceSize * 1024 * 1024,
                MaxOldSpaceSize = maxOldSpaceSize * 1024 * 1024
            };

            using (var tempEngine = new V8ScriptEngine(constraints))
            {
                Assert.AreEqual(Math.E, tempEngine.Evaluate("Math.E"));
                Assert.AreEqual(Convert.ToUInt64(maxNewSpaceSize * 4 + maxOldSpaceSize), tempEngine.GetRuntimeHeapInfo().HeapSizeLimit / (1024 * 1024));
            }
        }
コード例 #23
0
ファイル: BugFixTest.cs プロジェクト: dirkelfman/ClearScript
        public void BugFix_V8ScriptItemWeakBinding()
        {
            // This test verifies that V8 script items no longer prevent their isolates from being
            // destroyed. Previously it exhausted address space and crashed in 32-bit mode.

            for (var i = 0; i < 128; i++)
            {
                using (var tempEngine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging))
                {
                    tempEngine.Evaluate("(function () {}).valueOf()");
                }
            }
        }
コード例 #24
0
        public static void Init(V8ScriptEngine engine)
        {
            _createJsArray = engine.Evaluate(@"
                (function (list) {
                    var array = [];
                    for (var i = 0; i < list.Length; i++){
                        array.push(list[i]);
                    }
                    return array;
                }).valueOf()
            ");

            _createJsByteArray = engine.Evaluate(@"
                (function (length) {
                    var array = new Uint8Array(length);
                    return array;
                }).valueOf()
            ");

            _createJSPromise = engine.Evaluate(@"
                (function (action) {
                    return new Promise((resolve, reject) => {
                        action(resolve, reject);
                    });
                }).valueOf()
            ");

            _createJSObject = engine.Evaluate(@"
                (function (list) {
                    var obj = {};
                    for (var i = 0; i < list.Count; i++){
                        obj[list[i].Key] = list[i].Value;
                    }
                    return obj;
                }).valueOf()
            ");

            _createJSObjectArray = engine.Evaluate(@"
                (function (json) {
                    return JSON.parse(json);
                }).valueOf()
            ");

            _fillDictionary = engine.Evaluate(@"
                (function (obj, dict) {
                    for(var key in obj){
                        dict.Add(key, obj[key]);
                    }
                }).valueOf()
            ");

            _getStack = engine.Evaluate(@"
                (function() {
                  // Save original Error.prepareStackTrace
                  var origPrepareStackTrace = Error.prepareStackTrace

                  // Override with function that just returns `stack`
                  Error.prepareStackTrace = function (_, stack) {
                    return stack
                  }

                  // Create a new `Error`, which automatically gets `stack`
                  var err = new Error()

                  // Evaluate `err.stack`, which calls our new `Error.prepareStackTrace`
                  var stack = err.stack

                  // Restore original `Error.prepareStackTrace`
                  Error.prepareStackTrace = origPrepareStackTrace

                  // Remove superfluous function call on stack
                  stack.shift() // getStack --> Error

                  return stack
                }).valueOf()
            ");
        }
コード例 #25
0
ファイル: clsEngineJS.cs プロジェクト: git-thinh/test
        public static oResult Execute(string file___api, object parameters = null, Dictionary <string, object> request = null)
        {
            if (request == null)
            {
                request = new Dictionary <string, object>();
            }
            if (parameters == null)
            {
                parameters = new Dictionary <string, object>();
            }
            oResult r = new oResult()
            {
                ok = false, name = file___api, request = request
            };
            string file = Path.Combine(_CONFIG.PATH_ROOT, "_api\\" + file___api + ".js");

            if (File.Exists(file) == false)
            {
                r.error = "ERROR[clsEngineJS.Execute] Cannot found file: " + file;
                return(r);
            }

            if (!file.Contains("___"))
            {
                r.error = "ERROR[clsEngineJS.Execute] file___api: " + file___api + " must be format cache_name___api_name ";
                return(r);
            }

            string[] a = file___api.Split(new string[] { "___" }, StringSplitOptions.None);
            string   cache_name = a[0], api_name = a[1];

            try
            {
                string js = string.Empty;
                js = @"
                (function() {
                    'use strict';
                    try {
                        var ___log_text = function(text){ log___.write('" + file___api + @"', '_', text); };
                        var ___log_key = function(key, text){ log___.write('" + file___api + @"', key, text); };

                        var ___request = " + JsonConvert.SerializeObject(request) + @";
                        var ___parameters = " + JsonConvert.SerializeObject(parameters) + @";

                        ___log_text('This is from JavaScript...');

                        " + File.ReadAllText(file) + @"

                    } catch(e) {
                        return { ok: false, name: '" + file___api + @"', error: e.message };
                    }
                })();
                ";

                var toReturn = m_engine.Evaluate(js);
                if (toReturn is Microsoft.ClearScript.Undefined)
                {
                    r.ok = true;
                }
                else if (toReturn is oResult)
                {
                    r         = (oResult)toReturn;
                    r.request = request;
                    r.name    = file___api;
                }
                else
                {
                    r.error = "ERROR: Expected TYPE of result but got " + toReturn.GetType().FullName;
                }
            }
            catch (Exception e)
            {
                r.error = "ERROR_THROW: " + e.Message;
            }
            return(r);
        }
コード例 #26
0
        public static string Execute(string file___api, Dictionary <string, object> parameters = null, Dictionary <string, object> request = null)
        {
            if (request == null)
            {
                request = new Dictionary <string, object>();
            }
            if (parameters == null)
            {
                parameters = new Dictionary <string, object>();
            }

            oResult r = new oResult()
            {
                ok      = false,
                name    = file___api,
                input   = parameters,
                request = request
            };

            string file_main = Path.Combine(_CONFIG.PATH_ROOT, "_api\\main.js");

            if (File.Exists(file_main) == false)
            {
                r.error = "ERROR[clsEngineJS.Execute] Cannot found file: main.js ";
                return(JsonConvert.SerializeObject(r));
            }

            string file_api = Path.Combine(_CONFIG.PATH_ROOT, "_api\\" + file___api + ".js");

            if (File.Exists(file_api) == false)
            {
                r.error = "ERROR[clsEngineJS.Execute] Cannot found file: " + file_api;
                return(JsonConvert.SerializeObject(r));
            }

            try
            {
                string js_main = File.ReadAllText(file_main);
                string js_api  = File.ReadAllText(file_api);

                js_main = js_main.Replace("[FILE___API]", file___api)
                          .Replace("[TEXT_REQUEST]", JsonConvert.SerializeObject(request))
                          .Replace("[TEXT_PARAMETER]", JsonConvert.SerializeObject(parameters))
                          .Replace("[EXECUTE_TEXT_JS]", js_api);

                var toReturn = m_engine.Evaluate(js_main);
                if (toReturn is Microsoft.ClearScript.Undefined)
                {
                    r.ok = true;
                }
                else
                {
                    string json = toReturn.ToString();
                    return(json);
                }
            }
            catch (Exception e)
            {
                r.error = "ERROR_THROW: " + e.Message;
            }
            return(JsonConvert.SerializeObject(r));
        }
コード例 #27
0
 public dynamic Evaluate(string code) => _engine.Evaluate("", code);
コード例 #28
0
        public object call(string functionName, params object[] arguments)
        {
            if (!CefUtil.DISABLE_CEF)
            {
                if (!_wrapper._localMode)
                {
                    return(null);
                }

                object objToReturn = null;
                bool   hasValue    = false;

                lock (JavascriptHook.ThreadJumper)
                    JavascriptHook.ThreadJumper.Add(() =>
                    {
                        try
                        {
                            string callString = functionName + "(";

                            if (arguments != null)
                            {
                                for (int i = 0; i < arguments.Length; i++)
                                {
                                    string comma = ", ";

                                    if (i == arguments.Length - 1)
                                    {
                                        comma = "";
                                    }

                                    if (arguments[i] is string)
                                    {
                                        callString += System.Web.HttpUtility.JavaScriptStringEncode(arguments[i].ToString(), true) + comma;
                                    }
                                    else if (arguments[i] is bool)
                                    {
                                        callString += arguments[i].ToString().ToLower() + comma;
                                    }
                                    else
                                    {
                                        callString += arguments[i] + comma;
                                    }
                                }
                            }

                            callString += ");";

                            objToReturn = _parent.Evaluate(callString);
                        }
                        finally
                        {
                            hasValue = true;
                        }
                    });

                while (!hasValue)
                {
                    Thread.Sleep(10);
                }

                return(objToReturn);
            }
            else
            {
                return(null);
            }
        }
コード例 #29
0
        public async Task <GenerateResult> GenerateDocumentAsync(string code, object model, IResourceManager resourceManager = null, CancellationToken cancellationToken = default)
        {
            using var engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDynamicModuleImports);
            engine.Execute(PolyfillScripts.Get("ImageData"));

            engine.DocumentSettings.Loader = new CustomLoader(engine.DocumentSettings.Loader, _resourceScriptFactory, resourceManager);
            engine.DocumentSettings.AddSystemDocument("main", ModuleCategory.Standard, code);

            dynamic setModel = engine.Evaluate(@"
let model;
const setModel = m => model = JSON.parse(m);
setModel");

            setModel(JsonSerializer.Serialize(model));

            dynamic contentTypePromise = engine.Evaluate(new DocumentInfo()
            {
                Category = ModuleCategory.Standard
            }, @"
async function getContentType() {
    const { contentType } = await import('main');
    return contentType;
}
getContentType()");
            var contentType = await ToTask(contentTypePromise);

            if (contentType is Undefined)
            {
                contentType = null;
            }

            dynamic resultPromise = engine.Evaluate(new DocumentInfo()
            {
                Category = ModuleCategory.Standard
            }, @"
import Builder from 'main';
let builder = new Builder();
Promise.resolve(builder.build(model));");

            var result = await ToTask(resultPromise);

            switch (result)
            {
            case string @string: return(new GenerateResult()
                {
                    Content = Encoding.UTF8.GetBytes(@string), ContentType = contentType ?? "text/plain"
                });

            case ITypedArray <byte> typedArray: return(new GenerateResult()
                {
                    Content = typedArray.ToArray(), ContentType = contentType ?? "application/octet-stream"
                });

            case IList list:
            {
                var array = new byte[list.Count];
                for (var i = 0; i < list.Count; i++)
                {
                    array[i] = Convert.ToByte(list[i]);
                }

                return(new GenerateResult()
                    {
                        Content = array, ContentType = contentType ?? "application/octet-stream"
                    });
            }

            default: throw new NotSupportedException("Build did not produce a supported result");
            }
        }
コード例 #30
0
        public override float[][] Do(float[][] buffer)
        {
            // TODO: ステレオの両方のチャンネルに対して処理する

            using (var engine = new V8ScriptEngine())
            {
                int BLOCK_SIZE = 8192;

                engine.Execute("__mapper = (" + ExpressionCode + ")");

                // アルファベットにエンコードすることにより更に約4倍の高速化
                var code1 = engine.Compile(
                    "(function(){" +
#if EXPRESSION_USE_ENCODING_IN
                    "var __byteArray = new Array(__inputStr.length / 2);\n" +
                    "for(__i = 0; __i < __inputStr.length / 8; __i++) {\n" +
                    "  __byteArray[__i * 4 + 3] = (__inputStr.charCodeAt(__i * 8 + 0) - 65) * 16 + (__inputStr.charCodeAt(__i * 8 + 1) - 65);\n" +
                    "  __byteArray[__i * 4 + 2] = (__inputStr.charCodeAt(__i * 8 + 2) - 65) * 16 + (__inputStr.charCodeAt(__i * 8 + 3) - 65);\n" +
                    "  __byteArray[__i * 4 + 1] = (__inputStr.charCodeAt(__i * 8 + 4) - 65) * 16 + (__inputStr.charCodeAt(__i * 8 + 5) - 65);\n" +
                    "  __byteArray[__i * 4 + 0] = (__inputStr.charCodeAt(__i * 8 + 6) - 65) * 16 + (__inputStr.charCodeAt(__i * 8 + 7) - 65);\n" +
                    "}\n" +
                    "var __inputArray = new Float32Array((new Uint8Array(__byteArray)).buffer);\n" +
#endif
                    "var __result = new Array(__inputArray.length);\n" +
                    "for(__j=0;__j<__inputArray.length;__j++){__result[__j]=__mapper(__inputArray[__j]);}\n" +
#if EXPRESSION_USE_ENCODING_OUT
                    "__byteArray = new Uint8Array((new Float32Array(__result)).buffer);\n" +
                    "var __outputStr = \"\";\n" +
                    "for(__i = 0; __i < __result.length; __i++) {\n" +
                    "  __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 3] >> 4) & 0x0F) + 65);\n" +
                    "  __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 3]     ) & 0x0F) + 65);\n" +
                    "  __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 2] >> 4) & 0x0F) + 65);\n" +
                    "  __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 2]     ) & 0x0F) + 65);\n" +
                    "  __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 1] >> 4) & 0x0F) + 65);\n" +
                    "  __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 1]     ) & 0x0F) + 65);\n" +
                    "  __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 0] >> 4) & 0x0F) + 65);\n" +
                    "  __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 0]     ) & 0x0F) + 65);\n" +
                    "}\n" +
                    "return __outputStr;\n" +
#else
                    "return __result.join(',');\n" +
#endif
                    "})()"
                    );

                List <float[]> ret = new List <float[]>();

                foreach (var channelOfBuffer in buffer)
                {
                    List <float> wholeResult = new List <float>();

                    for (int blockId = 0; blockId < (channelOfBuffer.Length - 1) / BLOCK_SIZE + 1; blockId++)
                    {
                        int fromInclusive = BLOCK_SIZE * blockId;
                        int toExclusive   = Math.Min(BLOCK_SIZE * (blockId + 1), channelOfBuffer.Length);

                        var s = new StringBuilder();

#if EXPRESSION_USE_ENCODING_IN
                        s.Append("__inputStr = \"");

                        var charbuf = new byte[(toExclusive - fromInclusive) * 8];

                        for (int i = 0, i4 = 0, i8 = 0; i < toExclusive - fromInclusive; i++, i4 += 4, i8 += 8)
                        {
                            var x = channelOfBuffer[i + fromInclusive];

                            var floatbits = BitConverter.GetBytes(x);

                            charbuf[i8 + 0] = (byte)(((floatbits[3] >> 4) & 0x0F) + 65);
                            charbuf[i8 + 1] = (byte)(((floatbits[3] >> 0) & 0x0F) + 65);
                            charbuf[i8 + 2] = (byte)(((floatbits[2] >> 4) & 0x0F) + 65);
                            charbuf[i8 + 3] = (byte)(((floatbits[2] >> 0) & 0x0F) + 65);
                            charbuf[i8 + 4] = (byte)(((floatbits[1] >> 4) & 0x0F) + 65);
                            charbuf[i8 + 5] = (byte)(((floatbits[1] >> 0) & 0x0F) + 65);
                            charbuf[i8 + 6] = (byte)(((floatbits[0] >> 4) & 0x0F) + 65);
                            charbuf[i8 + 7] = (byte)(((floatbits[0] >> 0) & 0x0F) + 65);
                        }

                        s.Append(Encoding.ASCII.GetString(charbuf));

                        s.Append("\";");
#else
                        s.Append("__inputArray = [");

                        // 配列ではなく文字列に変換して渡すことにより大幅に高速化
                        s.Append(string.Join(",", Enumerable.Range(fromInclusive, toExclusive - fromInclusive).Select(i =>
                        {
                            var x = channelOfBuffer[i];

                            if (float.IsNaN(x))
                            {
                                return("NaN");
                            }                                      // ここいる??
                            else if (float.IsNegativeInfinity(x))
                            {
                                return("-Infinity");
                            }
                            else if (float.IsPositiveInfinity(x))
                            {
                                return("Infinity");
                            }

                            return(x.ToString());
                        })));

                        s.Append("];");
#endif

                        // コンパイルしてもコンパイルしなくてもほとんど同じ時間でした
                        engine.Execute(engine.Compile(s.ToString()));

                        dynamic result = engine.Evaluate(code1);

#if EXPRESSION_USE_ENCODING_OUT
                        string result_s = (string)result;

                        float[] result3 = new float[toExclusive - fromInclusive];

                        for (int i = 0; i < toExclusive - fromInclusive; i++)
                        {
                            result3[i] = BitConverter.ToSingle(new byte[] {
                                (byte)((result_s[i * 8 + 6] - 65) * 16 + (result_s[i * 8 + 7] - 65)),
                                (byte)((result_s[i * 8 + 4] - 65) * 16 + (result_s[i * 8 + 5] - 65)),
                                (byte)((result_s[i * 8 + 2] - 65) * 16 + (result_s[i * 8 + 3] - 65)),
                                (byte)((result_s[i * 8 + 0] - 65) * 16 + (result_s[i * 8 + 1] - 65)),
                            }, 0);
                        }
#else
                        float[] result3 = ((string)result).Split(',').Select(x =>
                        {
                            if (x == "Infinity")
                            {
                                return(float.PositiveInfinity);
                            }
                            if (x == "-Infinity")
                            {
                                return(float.NegativeInfinity);
                            }
                            if (x == "NaN")
                            {
                                return(float.NaN);
                            }
                            // NaNやInfinityは残さない方が良い気もします・・・

                            return(float.Parse(x));
                        }).ToArray();
#endif

                        wholeResult.AddRange(result3);
                    }

                    ret.Add(wholeResult.ToArray());
                }

                return(ret.ToArray());
            }
        }
コード例 #31
0
ファイル: BugFixTest.cs プロジェクト: dirkelfman/ClearScript
        public void BugFix_V8ScriptItemDispose()
        {
            dynamic item1;
            using (var tempEngine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging))
            {
                item1 = tempEngine.Evaluate("(function () { return 123; }).valueOf()");
                Assert.AreEqual(123, item1());

                dynamic item2 = tempEngine.Evaluate("(function () { return 456; }).valueOf()");
                using (item2 as IDisposable)
                {
                    Assert.AreEqual(456, item2());

                }
            }

            using (item1 as IDisposable)
            {
            }
        }