コード例 #1
0
        public void V8ScriptEngine_ValueTaskPromiseConversion_NoResult()
        {
            engine.Script.value = new ValueTask(Task.CompletedTask);
            Assert.AreEqual("HostObject", engine.Evaluate("value.constructor.name"));
            Assert.IsInstanceOfType(engine.Evaluate("Promise.resolve(123)"), typeof(ScriptObject));

            engine.Dispose();
            engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging | V8ScriptEngineFlags.EnableTaskPromiseConversion | V8ScriptEngineFlags.EnableValueTaskPromiseConversion);

            engine.Script.value = new ValueTask(Task.CompletedTask);
            Assert.AreEqual("Promise", engine.Evaluate("value.constructor.name"));
            Assert.IsInstanceOfType(engine.Evaluate("Promise.resolve(123)"), typeof(Task));

            var task = new Func <Task <object> >(async() => await(Task <object>) engine.Evaluate("Promise.resolve(123)"))();

            Assert.AreEqual(123, task.Result);

            engine.Script.promise = new ValueTask(Task.CompletedTask);
            engine.Execute("promise.then(value => result = value);");
            Assert.IsInstanceOfType(engine.Script.result, typeof(Undefined));

            var cancelSource = new CancellationTokenSource();

            cancelSource.Cancel();
            engine.Script.promise = new ValueTask(Task.Factory.StartNew(() => { }, cancelSource.Token));
            engine.Execute("promise.then(value => result = value, value => error = value);");
            Assert.IsInstanceOfType(engine.Script.error.hostException.GetBaseException(), typeof(TaskCanceledException));

            cancelSource          = new CancellationTokenSource();
            engine.Script.promise = new ValueTask(Task.Factory.StartNew(() => throw new AmbiguousImplementationException(), cancelSource.Token));
            Thread.Sleep(250);
            engine.Execute("promise.then(value => result = value, value => error = value);");
            Assert.IsInstanceOfType(engine.Script.error.hostException.GetBaseException(), typeof(AmbiguousImplementationException));
        }
コード例 #2
0
        public void Clear()
        {
            _context.Execute("Handlebars.templates = []; " +
                             "Handlebars.partials = []; ");

            // a good opportunity to return ram to it's rightful owner
            _context.CollectGarbage(true);
        }
コード例 #3
0
 private dynamic Merge(Product site, Product user)
 {
     var engine = new V8ScriptEngine();
     var underscore = File.ReadAllText("scripts/underscore.min.js");
     engine.Execute(underscore);
     engine.Execute("function extend(thing1, thing2) { return _.extend({}, thing1, thing2) }");
     var product = engine.Script.extend(site, user);
     return product;
 }
コード例 #4
0
ファイル: ScriptReader.cs プロジェクト: zxyxz/GDX-RPG
 public ScriptReader()
 {
     engine.AddHostObject("prototype__________", this);
     engine.AddHostType("MsgType", typeof(MsgType));
     engine.AddHostType("RPGObject", typeof(RPGObject));
     engine.AddHostType("BalloonType", typeof(BalloonType));
     engine.AddHostObject("CG", CG);
     engine.Execute("this.__proto__ = prototype__________");
 }
コード例 #5
0
 protected override void Prepare()
 {
     _engine = new V8ScriptEngine();
     _engine.AddHostObject("log", new Action <object>(Console.WriteLine));
     _engine.Execute("const window = this;");
     _engine.Execute("const exports = {};");
     _engine.Execute(Compiler);
     _compiler = _engine.Script.transform ?? throw new InvalidOperationException("Missing compiler");
 }
コード例 #6
0
ファイル: Main.cs プロジェクト: diennttlu/Graduation-Project
        private List <string> ExecuteMainScript(MainScript mainScript)
        {
            using (var engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging))
            {
                engine.AccessContext = typeof(Program);
                engine.AddHostObject("host", new HostFunctions());
                engine.AddHostObject("xHost", new ExtendedHostFunctions());
                engine.AddHostObject("lib", new HostTypeCollection("mscorlib", "System", "System.Core"));
                engine.AddHostType("Console", typeof(Console));
                engine.AddHostType("File", typeof(File));
                engine.AddHostType("Directory", typeof(Directory));
                engine.AddHostType("Path", typeof(Path));
                engine.AddHostType("Process", typeof(Process));
                engine.AddHostType("WebClient", typeof(WebClient));
                engine.AddHostType("Uri", typeof(Uri));

                //engine.AddHostType("object", typeof(object));

                try
                {
                    _loadScript.ExecuteLibraries(engine);
                    if (_mainScript.Dependencies.Count > 0)
                    {
                        var funcIncluded = _loadScript.CreateFuncIncluded(mainScript.Dependencies, engine);
                        engine.Execute(funcIncluded);
                    }
                    if (mainScript.Available)
                    {
                        var jsonResult = engine.Script.getFunctionInfo((mainScript.Content));
                        List <FunctionDeclaration> functionDeclarations = JsonConvert.DeserializeObject <List <FunctionDeclaration> >(jsonResult);

                        var excludeStatement = _loadScript.ExcludeStatement(mainScript.Content, functionDeclarations);
                        engine.Execute(excludeStatement);
                        if (functionDeclarations.Where(x => x.Name == "main").Any())
                        {
                            engine.Execute("main();");
                        }
                    }
                    else
                    {
                        engine.Execute(mainScript.Content);
                    }

                    if (Console.Result.Count == 0)
                    {
                        Console.Log($"Done");
                    }
                }
                catch (ScriptEngineException ex)
                {
                    Console.Log($"<span class='error-result'>{ex.Message}<br>{ex.ErrorDetails}</span>");
                    _logger.Error(ex);
                }
                return(Console.Result);
            }
        }
コード例 #7
0
ファイル: Markdownify.cs プロジェクト: hyrmn/Strike
        public Markdownify(Options options, RenderMethods rendereMethods, V8ScriptEngine engine)
        {
            this.engine = engine;

            var markedJsText = GetMarkedJsText();
            engine.Execute(markedJsText);

            var js = GetContructionJs(options, rendereMethods);
            engine.Execute(js);
        }
コード例 #8
0
        public static HtmlDocumentFacade ProcessServerSideScripts(this HtmlDocumentFacade doc)
        {
            var scripts = doc.getElementsByTagName("script");
            var noSideScripts = scripts
                .Where(_TestForNoSide);
            var noSideScriptsList = noSideScripts.ToList();
            noSideScriptsList.ForEach(node =>
            {
                node.parentNode.removeChild(node);
            });
            var serverSideScripts = scripts
                .Where(_TestForServerSide)
                .Where(_TestForRealScript)
            ;
            var sb = new StringBuilder();
            //serverSideScripts = serverSideScripts.Where(node => string.IsNullOrEmpty(node.getAttribute(ModelAttribute)));
            var serverSideScriptsList = serverSideScripts.ToList();
            serverSideScriptsList.ForEach(node =>
            {
                string src = node.getAttribute("src");
                if (string.IsNullOrEmpty(src))
                {
                    sb.AppendLine(node.innerHTML);
                }
                else
                {
                    sb.AppendLine(doc.GetHostContent(src));
                }
                if (!_TestForClientSide(node))
                {
                    node.parentNode.removeChild(node);
                }
            });
            string script = sb.ToString();
            if (script.Length > 0)
            {
                // Initialize a context
                script = sb.ToString();
                using (var engine = new V8ScriptEngine())
                {
                    var jqueryFacade = new JQueryFacade(doc);
                    engine.AddHostObject("console", new Console());
                    engine.AddHostObject("document", doc);
                    engine.AddHostObject("jQueryServerSideFacade", jqueryFacade);
                    engine.Execute("var " + modeParameter + "='server'");
                    if (doc.ProcessContext.Model != null)
                    {
                        engine.AddHostObject("model", doc.ProcessContext.Model);
                    }
                    engine.Execute(script);
                }
            }

            return doc;
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: AdamSobieski/Logic
        public static void Main(string[] args)
        {
            var swi_settings = new SwiPrologInitializationSettings
            {
                HomeDirectory = @"C:\Program Files\swipl",
                SetHomeDirectoryEnvironmentVariable = true,
                BinaryDirectory = @"C:\Program Files\swipl\bin",
                PrependBinaryDirectoryToPath = true
            };

            var xsb_settings = new XsbPrologInitializationSettings
            {
                HomeDirectory   = @"C:\Program Files (x86)\XSB",
                BinaryDirectory = @"C:\Program Files (x86)\XSB\config\x64-pc-windows\bin",
                PrependBinaryDirectoryToPath = true
            };

            using (var engine = new V8ScriptEngine())
            {
                engine.AddHostType("Console", typeof(Console));

                if (Directory.Exists(swi_settings.HomeDirectory))
                {
                    using (var swi = new SwiPrologEngine(swi_settings))
                    {
                        Console.WriteLine("SWI Prolog " + swi.Version);

                        engine.AddHostObject("swi", swi);

                        string script1 = File.OpenText("script1.js").ReadToEnd();

                        engine.Execute(script1);

                        Console.WriteLine();
                    }
                }

                if (Directory.Exists(xsb_settings.HomeDirectory))
                {
                    using (var xsb = new XsbPrologEngine(xsb_settings))
                    {
                        Console.WriteLine("XSB Prolog " + xsb.Version);

                        engine.AddHostObject("xsb", xsb);

                        string script2 = File.OpenText("script2.js").ReadToEnd();

                        engine.Execute(script2);

                        Console.WriteLine();
                    }
                }
            }
        }
コード例 #10
0
ファイル: Markdownify.cs プロジェクト: jongalloway/Strike
        public Markdownify(Options options, RenderMethods rendereMethods, V8ScriptEngine engine)
        {
            this.engine = engine;

            var markedJsText = GetMarkedJsText();

            engine.Execute(markedJsText);

            var js = GetContructionJs(options, rendereMethods);

            engine.Execute(js);
        }
コード例 #11
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hi");
            V8ScriptEngine eng = new V8ScriptEngine();
            Map            map = new Map();

            eng.AddHostObject("calculator", new Calculator());
            eng.AddHostObject("map", map);
            eng.Execute("let result = calculator.Sum(1, 2);");
            eng.Execute("map.Put('#ref', {r: result});");
            Console.WriteLine(eng.Evaluate("map.Get('#ref').r.Response"));
            Console.Read();
        }
コード例 #12
0
        public static Tuple <int, string> Run(string code, string inputs, string output)
        {
            //Jeśli input jest pusty przypisz do niego pusty literał
            if (inputs == null)
            {
                inputs = " ";
            }

            //Inicjalizacja silnika Javascript
            using (V8ScriptEngine v8 = new V8ScriptEngine()) {
                //inicjalizacja zmiennych
                //długie nazwy by nie kolidowały z nazwami zmiennych użytkownika
                v8.Script.hiddenVariableStdinString = inputs;
                v8.Execute(@"
                    var hiddenVariableStdinArray = hiddenVariableStdinString.split("","");
                    hiddenVariableStdoutArray = [];
                    function readline(){ 
                        var temp = hiddenVariableStdinArray[0];
                        hiddenVariableStdinArray.shift();
                        return temp;
                    }
                    function print(content){
                        var temp = content.toString();
                        hiddenVariableStdoutArray.push(temp);
                        return temp;
                    }");
                try
                {
                    v8.Execute(code);
                    String strOutput = "";
                    foreach (String line in v8.Script.hiddenVariableStdoutArray)
                    {
                        strOutput += line + " ";
                    }
                    strOutput = strOutput.Trim();
                    if (strOutput.Equals(output))
                    {
                        return(Tuple.Create(0, "Prawidłowy wynik: " + output + " = " + strOutput));
                    }
                    else
                    {
                        return(Tuple.Create(1, "Błędny wynik: " + output + " != " + strOutput));
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Exception: " + e.Message);
                    return(Tuple.Create(2, "Błąd: " + e.Message));
                }
            }
        }
コード例 #13
0
        static V8ScriptEngine CreateScriptEngine()
        {
            var scriptEngine = new V8ScriptEngine();

            scriptEngine.AddHostObject("lib", new HostTypeCollection("mscorlib", "System.Core"));
            scriptEngine.AddHostObject("debug", new DebugModule());
            scriptEngine.AddHostObject("log", new LoggerModule());
            scriptEngine.AddHostObject("http", new HttpModule());
            scriptEngine.AddHostType("Array", typeof(JSArray));
            scriptEngine.Execute(ResourceManager.ReadResource("Snail.Collector.JsExtends.stringExtend.js"));
            scriptEngine.Execute(ResourceManager.ReadResource("Snail.Collector.JsExtends.unity.js"));

            return(scriptEngine);
        }
コード例 #14
0
 private void ExecuteWrapped(string code)
 {
     engine.Execute($@"
         (function () {{
             {code}
         }})()");
 }
コード例 #15
0
        public void Verify(ExpressionScriptProvided expressionScript)
        {
            try
            {
                using (var engine = new V8ScriptEngine())
                {
                    ExposeTypesToEngine(engine);

                    engine.AddHostObject("host", new XHostFunctions());
                    engine.AddHostObject("debug", new DebugFunctions(this));

                    var writer = new StringWriter();
                    WritePolyfills(writer);
                    writer.WriteLine("var __result = function() {");
                    writer.WriteLine(expressionScript.Expression);
                    writer.WriteLine("};");

                    engine.Execute(writer.ToString());
                }
            }
            catch (ScriptEngineException ex)
            {
                throw new ExprValidationException(ex.Message, ex);
            }
        }
コード例 #16
0
        private void LoadSharedScripts(V8ScriptEngine context, bool precompileOnly)
        {
            if (SharedScripts == null)
            {
                return;
            }

            foreach (var script in SharedScripts)
            {
                try
                {
                    if (precompileOnly)
                    {
                        context.Compile(script.Content, V8CacheKind.Code, out byte[] cache);
                        script.CompiledCache = cache;
                    }
                    else
                    {
                        V8Script v8Script = context.Compile(script.Content, V8CacheKind.Code, script.CompiledCache, out bool accepted);
                        context.Execute(v8Script);
                    }
                }
                catch (Exception ex)
                {
                    logger.ErrorFormat("Script: Shared script failed to run. {0}.  {1}", script.Name, ex.Message);
                    throw;
                }
            }
        }
コード例 #17
0
ファイル: JSPlayer.cs プロジェクト: newmind/GoldMine
 public IJSPlayer(string fileFullPath, ILog iLog)
 {
     this.iLog = iLog;
     engin     = new V8ScriptEngine();
     engin.Execute(File.ReadAllText(fileFullPath));
     engin.AddHostObject("Console", iLog);
 }
コード例 #18
0
ファイル: main.cs プロジェクト: staherianYMCA/test
        static void Main(string[] args)
        {
            try
            {
                using (var engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging))
                {
                    engine.Execute(JS);

                    var returnedVal = engine.Script.calculation();
                    WriteLine(returnedVal);

                    returnedVal = engine.Script.add(3, 5);
                    WriteLine(returnedVal);

                    returnedVal = engine.Script.testObjectI();
                    WriteLine(returnedVal);

                    returnedVal = engine.Script.testObjectII();
                    WriteLine(returnedVal);
                }
            }
            catch (Exception eException)
            {
                WriteLine(eException.GetType().FullName + Environment.NewLine + "Message: " + eException.Message + Environment.NewLine + (eException.InnerException != null && !string.IsNullOrEmpty(eException.InnerException.Message) ? "InnerException.Message" + eException.InnerException.Message + Environment.NewLine : string.Empty) + "StackTrace:" + Environment.NewLine + eException.StackTrace);
            }
        }
コード例 #19
0
        private Scene CreateScene(string scriptPath)
        {
            var scene = new Scene();

            // Set up sensible defaults
            scene.Size = new ImageSize(picture.Width, picture.Height);
            // Cosmic background radiation!
            scene.Background = new Colour(0.0);
            // Render shadows
            scene.Shadow = true;
            // Ambient light
            scene.Ambient = new Colour(0.1);
            // Reflection recursion depth
            scene.TraceMax = 20;
            // Light level threshold for recursion
            scene.MinWeight = 0.004;
            // Enable antialiasing
            scene.Antialias = true;

            var script = System.IO.File.ReadAllText(scriptPath);

            using (var engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging, 9222))
            {
                InjectTypes(engine);
                InjectFunctions(engine);
                engine.Execute(script);
                engine.Script.Build(scene);
                return(scene);
            }
        }
コード例 #20
0
        /// <summary>
        /// 加载模块
        /// </summary>
        /// <param name="v8"></param>
        /// <param name="module"></param>
        internal static object LoadModule(this V8ScriptEngine v8, ModuleInfo module)
        {
            var ass = Assembly.LoadFile(Path.Combine(module.ExecutePath, module.Assembly));

            if (ass == null)
            {
                throw new Exception("the path is not found,'" + module.Assembly + "'.");
            }
            var type = ass.GetType(module.Type);

            if (type == null)
            {
                throw new Exception("the type is not found,'" + module.Type + "'.");
            }
            var refType = string.Format("_ref_module_type_{0}", type.Name);

            v8.AddHostType(refType, type);
            var funcName = string.Format("_init_module_func_{0}", module.Name);
            var script   = new StringBuilder("function ");

            script.Append(funcName + "() {\r\n");
            script.AppendFormat("var {0} = new {1}();\r\n", module.Name, refType);
            if (module.ProxyScript?.Length > 0)
            {
                script.Append(module.ProxyScript);
            }
            script.AppendFormat("\r\nreturn {0};", module.Name);
            script.Append("\r\n}");
            v8.Execute(script.ToString());
            return(v8.Invoke(funcName));
        }
コード例 #21
0
ファイル: JS.cs プロジェクト: Boyka-wang/MM
 /// <summary>
 /// 获取函数
 /// </summary>
 /// <param name="file">文件名</param>
 /// <returns>返回函数</returns>
 public dynamic GetClass(string file)
 {
     if (string.IsNullOrEmpty(file))
     {
         Ex = "脚本文件名不能为空";
         return(null);
     }
     file = file.ToFullName(_Dir);
     if (!File.Exists(file))
     {
         Ex = "脚本不存在!请确认脚本:“" + file + "”是否存在。";
         return(null);
     }
     try
     {
         var Eng = new V8ScriptEngine
         {
             EnableAutoHostVariables = true
         };
         Eng.AddHostType("Console", typeof(Console));
         Eng.AddHostObject("Cache", new Cache());
         var Engine = new Index
         {
             Dir = Path.GetDirectoryName(file) + "\\"
         };
         Eng.AddHostObject("Engine", Engine);
         Eng.Execute(File.ReadAllText(file, Encoding.UTF8));
         return(Eng.Script);
     }
     catch (Exception ex)
     {
         Ex = ex.ToString();
     }
     return(null);
 }
コード例 #22
0
ファイル: JSPlayer.cs プロジェクト: elrha/GoldMine
 public IJSPlayer(string fileFullPath, ILog iLog)
 {
     this.iLog = iLog;
     engin = new V8ScriptEngine();
     engin.Execute(File.ReadAllText(fileFullPath));
     engin.AddHostObject("Console", iLog);
 }
コード例 #23
0
ファイル: Program.cs プロジェクト: surya-rakanta/EPJsDeOb
        static void ProcessScript(String sFunc, String sHdrFile, String sDtlFile)
        {
            String sFileResult = Path.GetFileNameWithoutExtension(sDtlFile) + "-result.js";
            String sHdrScript  = File.ReadAllText(sHdrFile);
            String sRScript    = File.ReadAllText(sDtlFile);

            V8ScriptEngine v8       = new V8ScriptEngine();
            V8Script       myScript = v8.Compile(sHdrScript);

            v8.Execute(myScript);

            String          sRegex    = "(" + sFunc + @"\(\'0[xX][0-9A-Fa-f]+\'\))";
            MatchCollection arMatches = Regex.Matches(sRScript, sRegex);
            int             nI;
            String          sMatchVal, sRes;

            for (nI = 0; nI < arMatches.Count; nI++)
            {
                sMatchVal = arMatches[nI].Value;
                Console.WriteLine("Processing " + sMatchVal + " ...");
                sRes     = v8.ExecuteCommand(sMatchVal);
                sRScript = sRScript.Replace(arMatches[nI].Value, "\"" + sRes + "\"");
            }
            v8.Dispose();
            File.WriteAllText(sFileResult, sRScript);
            return;
        }
コード例 #24
0
        public String V8Build(String view, object modal)
        {
            String result = String.Empty;

            using (var engine = new V8ScriptEngine())
            {
                engine.Execute(Juicer);

                engine.Script.view = "hi , id: ${ID}";
                //	engine.Script.modal = modal;
                //var modal_script = "modal = " + JsonConvert.SerializeObject(modal);

                var modal_script = JsonConvert.SerializeObject(modal);

                //engine.Execute(modal_script);
                //string tpl = "${subTpl}";
                //result = engine.Invoke("juicer", engine.Script.view, engine.Script.modal);
                //	var result1 = engine.Invoke("juicer", engine.Script.view);
                result = engine.Invoke("juicer", engine.Script.view, modal_script);
                string tpl = "Hi, {@include subTpl, subData}, End.";

                string data = "{\"subTpl\":\"I\'m sub content, ${name}\",\"subData\":{\"name\": \"juicer\"}}";

                //engine.Execute(data);
                var result1 = engine.Invoke("juicer", tpl, data);
            }

            return(result.ToString());
        }
コード例 #25
0
        public void StartUp()
        {
            MainForm.WriteLine("加载脚本...");
            V8.Execute(Code); //加载代码

            try
            {
                Proxy.系统.Img = () =>
                {
                    CaptureImage screen = Capture.Screen(V8.Script.屏幕());
                    var          当前工作区域 = 工作区域 == System.Drawing.Rectangle.Empty ?
                                          new System.Drawing.Rectangle(System.Drawing.Point.Empty, screen.Bitmap.Size) : 工作区域;
                    return(screen.Bitmap.Clone(当前工作区域, screen.Bitmap.PixelFormat));
                };
                MainForm.WriteLine("脚本执行中...");
                V8.Script.运行();
                MainForm.WriteLine("脚本执行结束");
            }
            catch (Exception exception)
            {
                MainForm.WriteLine($@"ERROR runner caller : {exception}");
            }
            finally
            {
                Proxy.系统.Img = null;
            }
        }
コード例 #26
0
        // Full doc: https://github.com/Microsoft/ClearScript
        static void Main(string[] args)
        {
            var taskA = new Task("TaskA", 54, 0.74m, 0.24m);
            var taskB = new Task("TaskB", 72, 0.74m, 0.24m);

            // create a script engine
            using (var engine = new V8ScriptEngine())
            {
                const string evaluateSetupJsFunction = @"
                function getSetup(previousTask, currentTask) {
                    var previousTaskSetup = previousTask.Quantity * previousTask.BeeingFirstPenaltyFactor;
                    var currentTaskSetup = currentTask.Quantity * currentTask.BeeingSecondPenaltyFactor;

                    return {
                        previousTaskSetup: previousTaskSetup,
                        currentTaskSetup: currentTaskSetup
                    }
                }";

                // call a script function
                engine.Execute(evaluateSetupJsFunction);
                var setupTimes = engine.Script.getSetup(taskA, taskB);

                Console.WriteLine($"{ taskA.Number } setup time: {setupTimes.previousTaskSetup}h");
                Console.WriteLine($"{ taskB.Number } setup time: {setupTimes.currentTaskSetup}h");
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
コード例 #27
0
ファイル: Main.cs プロジェクト: nicoriff/NinoJS
        /// <summary>
        /// Method to use for running Javascript Files.
        /// </summary>
        /// <param name="filePath">Path to JS or JSE File</param>
        public void RunScript(object filePath)
        {
            try
            {
                /* CODIGO JINTENGINE VIEJO
                Engine engine = new Engine(cfg => cfg.AllowClr(typeof(NinoJS.Resources.SQL).Assembly))
                    .SetValue("log", new Action<object>(Console.WriteLine));
                engine.Execute(fileContent);
                */

                string fileContent = new StreamReader(filePath.ToString()).ReadToEnd();

                var engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging);
                var typeCollection = new HostTypeCollection("mscorlib", "System", "System.Core", "NinoJS.Resources");
                engine.AddHostObject("clr", typeCollection);
                engine.AddHostObject("host", new HostFunctions());
                engine.AddHostObject("extendedHost", new ExtendedHostFunctions());
                engine.AddHostObject("console", new NinoJS.Core.Helpers.Console());

                engine.Execute(fileContent);
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.ToString());
                log.LogError(ex.ToString());
            }
        }
コード例 #28
0
        static string v8_get_raw(object p)
        {
            if (p == null || string.IsNullOrWhiteSpace(p.ToString()))
            {
                return(string.Empty);
            }
            string url = p.ToString();

            V8ScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging, 9393);

            //engine.Execute(Script_Text);
            //engine.AddCOMType("XMLHttpRequest", "MSXML2.XMLHTTP");
            //object returnedVal = _v8Engine.Script.Execute();

            engine.AddCOMType("XMLHttpRequest", "MSXML2.XMLHTTP");
            engine.Execute(@"
    function get(url) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, false);
        xhr.send();

        if (xhr.status == 200) return xhr.responseText;
        else return 'ERR: Request failed: ' + xhr.status;
    }
");

            string v = engine.Script.get(url);

            return(v);
        }
コード例 #29
0
ファイル: Connector.cs プロジェクト: numlck/gtmp-javascript
        public V8ScriptEngine ExposeAPI(V8ScriptEngine engine)
        {
            var connector = this;

            engine.AddHostObject("API", HostItemFlags.DirectAccess, API);
            engine.AddHostObject("host", new ExtendedHostFunctions());
            engine.AddHostObject("lib", new HostTypeCollection("mscorlib", "System.IO", "MySql.Data"));


            engine.AddHostType("Vector3", typeof(GrandTheftMultiplayer.Shared.Math.Vector3));
            engine.AddHostType("Quaternion", typeof(GrandTheftMultiplayer.Shared.Math.Quaternion));
            engine.AddHostType("Matrix4", typeof(GrandTheftMultiplayer.Shared.Math.Matrix4));
            engine.AddHostType("WeaponHash", typeof(WeaponHash));
            engine.AddHostType("VehicleHash", typeof(VehicleHash));
            engine.AddHostType("PedHash", typeof(PedHash));
            engine.Script.host_typeof = new Action <dynamic>(arg => {
                API.consoleOutput("TYPE =" + engine);
            });
            engine.Script.require = new Func <dynamic, ScriptObject>(arg =>
            {
                return(Import(arg));
            });
            engine.Execute("var modules = {};");
            return(engine);
        }
コード例 #30
0
        public static void Main()
        {
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

            using (engine = new V8ScriptEngine(typeof(ClearScriptConsole).Name, V8ScriptEngineFlags.EnableDebugging))
            {
                engine.AddHostObject("host", new ExtendedHostFunctions());
                engine.AddHostObject("clr", HostItemFlags.GlobalMembers, new HostTypeCollection("mscorlib", "System", "System.Core", "ClearScript"));

                hm = new Hidemaru();
                engine.AddHostType("hm", typeof(Hidemaru));
                console = new hmV8Console();
                engine.AddHostType("console", typeof(hmV8Console));

                engine.AllowReflection = true;

                // 特別にR関数を追加
                String expression = @"
                function R(text){
                    return text.toString().split(""\n"").slice(1,-1).join(""\n"");
                }
                ";
                engine.Execute(expression);


                RunStartupFile(engine);
                RunConsole(engine);
            }

            AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
        }
コード例 #31
0
        /// <summary>
        /// Assumes layout has been already applied
        /// Note: method mutates graph and graphLayout
        /// </summary>
        public void ImproveAppliedLayout(SigmaGraphModel graph, GraphLayout graphLayout, LayoutSettings layoutSettings, TimeSpan duration)
        {
            using (var engine = new V8ScriptEngine())
            {
                try
                {
                    var v8Graph = new V8GraphModel();
                    v8Graph.LoadSigma(graph);
                    engine.AddHostObject("log", _log);

                    engine.Execute("var graph = " + JsonConvention.SerializeObject(v8Graph) + ";");
                    engine.Execute("var settings = " + JsonConvention.SerializeObject(layoutSettings) + ";");
                    engine.Execute("var duration = " + JsonConvention.SerializeObject(duration.TotalMilliseconds) + ";");

                    var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

                    var forceAtlas2   = engine.Compile(File.ReadAllText($@"{baseDirectory}\App\Graph\Layout\ForceAtlas2.js"));
                    var serviceScript = engine.Compile(File.ReadAllText($@"{baseDirectory}\App\Graph\Layout\GraphLayoutService.js"));
                    engine.Execute(forceAtlas2);
                    engine.Execute(serviceScript);

                    var nodesJson = engine.Evaluate("JSON.stringify(nodes)").ToString();
                    var nodes     = JsonConvention.DeserializeObject <V8NodeModel[]>(nodesJson);
                    for (int i = 0; i < nodes.Length; i++)
                    {
                        var node = graph.Nodes[i];
                        node.X = nodes[i].x;
                        node.Y = nodes[i].y;

                        var id = node.Entity;
                        if (id.HasValue)
                        {
                            graphLayout[id.Value] = new GraphLayout.Coords()
                            {
                                X = nodes[i].x,
                                Y = nodes[i].y
                            };
                        }
                    }
                }
                catch (ScriptEngineException e)
                {
                    _log.Error("V8 exception: " + e.ErrorDetails);
                    throw;
                }
            }
        }
コード例 #32
0
 public PropertyGraphModel Calculate(PropertyGraphModel graph)
 {
     using (var engine = new V8ScriptEngine())
     {
         engine.AddHostObject("graph", graph);
         engine.Execute(Script);
         return(engine.Script.graph);
     }
 }
コード例 #33
0
        private MockEngineResponse ExecuteAction(V8ScriptEngine scriptEngine, string scenarioName, MockAction action)
        {
            _logProvider.Information("executing action: {action}", action);
            var response = new MockEngineResponse()
            {
                Success = true
            };

            if (action.Before != null)
            {
                try
                {
                    scriptEngine.Execute(action.Before);
                }
                catch (Exception e)
                {
                    throw new MockEngineException(this.Name, scenarioName, $"error executing Before code: {e.Message}", e);
                }
            }
            if (action.Response != null)
            {
                response = BuildResponse(scriptEngine, scenarioName, action);
                if (response != null)
                {
                    scriptEngine.AddHostObject("response", response);
                }
            }
            if (action.After != null)
            {
                try
                {
                    scriptEngine.Execute(action.After);
                }
                catch (Exception e)
                {
                    throw new MockEngineException(this.Name, scenarioName, $"error executing After code: {e.Message}", e);
                }
            }
            if (action.Log != null)
            {
                _logProvider.Information(ApplyExpressions(scriptEngine, action.Log, false));
            }
            return(response);
        }
コード例 #34
0
 public ManticoreEngine Start()
 {
     v8 = new V8ScriptEngine();
     v8.AccessContext = typeof(ManticoreEngine);
     v8.Execute("var manticore = {platform:{name:\"win\"}};");
     ManticoreJsObject = v8.Script.manticore;
     v8.Script.global  = v8.Script;
     nativeServices.Register(this);
     return(this);
 }
コード例 #35
0
        public void Can_Perform_JS_ToLower_On_A_Passed_String()
        {
            using (var engine = new V8ScriptEngine(V8ScriptEngineFlags.DisableGlobalMembers))
            {
                engine.Script.MyString = "Just a test string";
                engine.AddHostType("Console", typeof(Console));

                engine.Execute("Console.WriteLine ('Length of MyString = {0}', MyString.toLowerCase())");
            }
        }
コード例 #36
0
        public void Can_Perform_JS_ToLower_On_A_Passed_String()
        {
            using (var engine = new V8ScriptEngine(V8ScriptEngineFlags.DisableGlobalMembers))
            {
                engine.Script.MyString = "Just a test string";
                engine.AddHostType("Console", typeof(Console));

                engine.Execute("Console.WriteLine ('Length of MyString = {0}', MyString.toLowerCase())");
            }
        }
コード例 #37
0
        public void Can_Perform_JS_ToLower_On_An_Object_Property()
        {
            using (var engine = new V8ScriptEngine(V8ScriptEngineFlags.DisableGlobalMembers))
            {
                var myObject = new {MyString = "Just a test string"};

                engine.Script.MyString = "Just a test string";
                engine.AddHostType("Console", typeof(Console));
                engine.AddHostObject("myObject", myObject);

                engine.Execute("Console.WriteLine ('Length of MyString = {0}', myObject.MyString.toLowerCase())");
            }
        }
コード例 #38
0
        public ClearScriptEngine(IHandlebarsResourceProvider resourceProvider)
        {
            Console.Out.WriteLine("ClearScriptEngine Loaded");

            _resourceProvider = resourceProvider;

            _context = new V8ScriptEngine();
            _context.AddHostObject("clearScriptBridge", 
                                   HostItemFlags.GlobalMembers,
                                   new ClearScriptBridgeFunctions(_context, _resourceProvider));

            // _context.Script.moduleLoader = new ModuleLoader(_context);
            // _context.Execute(File.ReadAllText("require.js"));
            // _context.Execute(@"require.load = function(context, name, url) { moduleLoader.LoadModuleAsync(context, name, url); };");
                
            _context.Execute("var raw = [];");
            _context.Execute("require('./Script/handlebars-1.0.0.js');");
            foreach (var script in HandlebarsConfiguration.Instance.Include)
            {
                _context.Execute("require('./" + script.Source + "');"); 
            }

        }
コード例 #39
0
ファイル: JadeRunner.cs プロジェクト: hallipr/NJade
        public string Render(string path)
        {
            using (var engine = new V8ScriptEngine())
            {
                Environment.CurrentDirectory = Path.GetDirectoryName(path);

                engine.AddHostType("externalFS", typeof(FsModule));

                engine.Execute("jade.js", Resources.jade);

                var result = (string)engine.Script.jade.renderFile(path);

                return result;
            }
        }
コード例 #40
0
        public void V8ScriptEngine_ResourceConstraints_Dual()
        {
            const int limit = 4 * 1024 * 1024;
            const string code = @"x = []; for (i = 0; i < 1024 * 1024; i++) { x.push(x); }";

            engine.Execute(code);
            engine.CollectGarbage(true);
            var usedHeapSize = engine.GetRuntimeHeapInfo().UsedHeapSize;

            var constraints = new V8RuntimeConstraints
            {
                MaxYoungSpaceSize = limit,
                MaxOldSpaceSize = limit,
                MaxExecutableSize = limit
            };

            engine.Dispose();
            engine = new V8ScriptEngine(constraints);

            TestUtil.AssertException<ScriptEngineException>(() =>
            {
                try
                {
                    engine.Execute(code);
                }
                catch (ScriptEngineException exception)
                {
                    Assert.IsTrue(exception.IsFatal);
                    throw;
                }
            });

            engine.CollectGarbage(true);
            Assert.IsTrue(usedHeapSize > engine.GetRuntimeHeapInfo().UsedHeapSize);
        }
コード例 #41
0
        private static void Cleanup(V8ScriptEngine engine)
        {
            var data = engine.Script as DynamicObject;
            var cleanup = new StringBuilder();

            foreach (var item in data.GetDynamicMemberNames())
            {
                if (item != "EngineInternal")
                {
                    cleanup.Append("delete " + item + ";");
                }
            }
            
            engine.Execute(cleanup.ToString());
            engine.CollectGarbage(true);
        }
コード例 #42
0
        public void ExecutarTestesDoMomentSemHelper()
        {
            var sw = new Stopwatch();
            var engine = new V8ScriptEngine();

            var quintCode = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Moment", "Qunit.js"));
            var codigoIndividuo = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Moment", "global.js"));
            var codigoTestes = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Moment", "core-test.js"));

            engine.AddHostType("Console", typeof(Console));

            engine.Execute("var GLOBAL = this;");

            sw.Start();
            engine.Execute(quintCode);
            engine.Execute(codigoIndividuo);
            engine.Execute(codigoTestes);

            #region Configura Retorno de erros
            engine.Execute(@"
                                    var total, sucesso, falha;

                                    QUnit.done(function( details ) {
                                    Console.WriteLine('=============================================');
                                    Console.WriteLine('Total:' + details.total);
                                    Console.WriteLine('Falha:' + details.failed);
                                    Console.WriteLine('Sucesso:' + details.passed);
                                    Console.WriteLine('Tempo:' + details.runtime);

                                });

                                QUnit.log(function( details ) {
                                  if ( details.result ) {
                                    return;
                                  }
                                  var loc = details.module + ': ' + details.name + ': ',
                                    output = 'FAILED: ' + loc + ( details.message ? details.message + ', ' : '' );

                                  if ( details.actual ) {
                                    output += 'expected: ' + details.expected + ', actual: ' + details.actual;
                                  }
                                  if ( details.source ) {
                                    output += ', ' + details.source;
                                  }

                                    Console.WriteLine('=============================================');
                                    Console.WriteLine( output );
                                });

                                QUnit.config.autostart = false;
                                QUnit.config.ignoreGlobalErrors = true;
                        ");
            #endregion

            engine.Execute(@"   QUnit.load();
                                QUnit.start();
                ");

            sw.Stop();
            Console.WriteLine(sw.Elapsed.ToString(@"hh\:mm\:ss\,ffff"));
            //Assert.AreEqual(0, 57982);
        }
コード例 #43
0
        public void V8ScriptEngine_ResourceConstraints()
        {
            const int limit = 4 * 1024 * 1024;
            const string code = @"x = []; while (true) { x.push(x); }";

            var constraints = new V8RuntimeConstraints
            {
                MaxYoungSpaceSize = limit,
                MaxOldSpaceSize = limit,
                MaxExecutableSize = limit
            };

            engine.Dispose();
            engine = new V8ScriptEngine(constraints);

            TestUtil.AssertException<ScriptEngineException>(() =>
            {
                try
                {
                    engine.Execute(code);
                }
                catch (ScriptEngineException exception)
                {
                    Assert.IsTrue(exception.IsFatal);
                    throw;
                }
            });

            TestUtil.AssertException<ScriptEngineException>(() =>
            {
                try
                {
                    engine.CollectGarbage(true);
                    engine.Execute("x = 5");
                }
                catch (ScriptEngineException exception)
                {
                    Assert.IsTrue(exception.IsFatal);
                    throw;
                }
            });
        }
コード例 #44
0
ファイル: PageBuilder.cs プロジェクト: seven1276/yycms
        public String V8Build(String view, object modal)
        {
            String result = String.Empty;

            using (var engine = new V8ScriptEngine())
            {
                engine.Execute(Juicer);

                engine.Script.view = view;

                var modal_script = "modal = " + JsonConvert.SerializeObject(modal);

                engine.Execute(modal_script);

                result = engine.Invoke("juicer", engine.Script.view, engine.Script.modal);
            }

            return result.ToString();
        }
コード例 #45
0
        /// <summary>
        /// configura o Helper para posterior execuçao
        /// </summary>
        /// <param name="diretorioJavascripts">Diretório onde estão os arquivos em js</param>
        /// <param name="setTimeout">Habilitar a função global setTimeout</param>
        /// <param name="setInterval">Habilitar a função global setInterval</param>
        private void Carregar(string diretorioJavascripts, bool setTimeout, bool setInterval)
        {
            TimedOuts = new List<IDisposable>();
            _diretorioExecucao = diretorioJavascripts;
            _timeoutTestes = int.MaxValue;
            ExecutouTestesAteFinal = false;

            SetTimeOutLigado = setTimeout;

            //O manager vai compilar e cachear as bibliotecas
            _manager = new RuntimeManager(new ManualManagerSettings() { MaxExecutableBytes = (1000000000 * 2), RuntimeMaxCount = int.MaxValue});
            _engine = _manager.GetEngine();

            //RequireManager.ClearPackages(); //garantir uma execução limpa

            #region Ler arquivos Js

            _cacheCodigos = new Dictionary<string, string>();

            foreach (var enumerateFile in Directory.EnumerateFiles(diretorioJavascripts, "*.js"))
            {
                _cacheCodigos.Add(Path.GetFileNameWithoutExtension(enumerateFile), File.ReadAllText(enumerateFile));
                //_manager.Compile(Path.GetFileNameWithoutExtension(enumerateFile), File.ReadAllText(enumerateFile), true, int.MaxValue);
            }

            #endregion

            #region Configura a Engine com o JavascriptHelper e Console, Settimeout e etc

            FalhasDosTestes = new List<string>();
            _timers = new Dictionary<int, bool>();

            _engine.AddHostObject("javascriptHelper", this);

            _engine.Execute(@"'use strict';
                        function console() {
                          if (!(this instanceof console)) {
                            return new Console();
                          }
                        }

                        console.prototype.log = function(args, args1, args2) {
                          javascriptHelper.Escrever(args, args1, args2);
                        };");

            _engine.Execute("var console = new console();");
            _engine.Execute("var GLOBAL = this;");

            _engine.Execute(@"var stFunctionsCallBack = new Array();");

            if (setTimeout)
            {
                _engine.Execute(@"var setTimeout = function (funcToCall, millis) {
                                                var textoId = javascriptHelper.CurrentThreadId;
                                                var idlocal = javascriptHelper.SetTimeout(millis);
                                                stFunctionsCallBack.push(funcToCall);
                                                return idlocal;
                            };");

                _engine.Execute(@"var clearTimeout = function(id) { javascriptHelper.ClearTimeout(id);};");
            }

            if (setInterval)
            {
                _engine.Execute(@"var setInterval = function (funcToCall, millis) {

                                                var idlocal = javascriptHelper.SetTimeout(millis);
                                                var funcaoTimeout = function() { funcToCall(); setTimeout(funcToCall, millis); };
                                                stFunctionsCallBack.push(funcaoTimeout);
                                                return idlocal;
                            };");

                _engine.Execute(@"var clearInterval = function(id) { javascriptHelper.ClearTimeout(id);};");
            }
            #endregion
        }