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; }
public Engine() { engine = new V8ScriptEngine (V8ScriptEngineFlags.EnableDebugging); engine.AddHostObject ("dotnet", new Microsoft.ClearScript.HostTypeCollection ("mscorlib", "System.Core")); engine.AddHostType ("WinJS_KeyUtil", typeof (KeyUtil)); engine.AddHostType ("WinJS_FileUtils", typeof (FileUtils)); engine.AddHostObject ("WinJS_host", new Microsoft.ClearScript.HostFunctions ()); }
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__________"); }
public void RunScript(string script) { Console.WriteLine("[{0}] {1} clicked Run Script", DateTime.Now, Context.ConnectionId); if (jContext == null) { jContext = new V8ScriptEngine(); jContext.AddHostObject("map", map); jContext.AddHostType("Console", typeof(Console)); } try { jContext.Evaluate(script); } catch (ScriptEngineException ex) { Clients.All.receiveMessage("JavaScript Engine:" + ex.Message + "<br>"); } foreach (var token in map.GetTokenList()) { Clients.All.onTokenMoved(token.Id, token.X, token.Y, "nobody"); } }
public Task <T> Execute <T>(string script, IDictionary <string, object> variables) { using (var engine = new V8ScriptEngine()) { if (variables != null) { foreach (var kv in variables) { if (kv.Value != null) { var inputJson = JsonConvert.SerializeObject(kv.Value); var inputJs = engine.Script.JSON.parse(inputJson); engine.Script[kv.Key] = inputJs; } } } engine.AddHostType("Console", typeof(Console)); var outputJs = engine.Evaluate(script); if (outputJs == null) { return(Task.FromResult(default(T))); } var outputJson = engine.Script.JSON.stringify(outputJs) as string; if (outputJson == null) { return(Task.FromResult(default(T))); } var output = JsonConvert.DeserializeObject <T>(outputJson); return(Task.FromResult(output)); } }
public Engine(V8ScriptEngine V8Engine = null) { if (V8Engine == null) { V8Engine = new V8ScriptEngine(); } this.V8Engine = V8Engine; globalSetInteropClasses.ForEach(x => { V8Engine.AddHostType(x.Attribute.Name, x.Type); }); V8Engine.AddHostObject("require", new Func <string, object>((string requirePath) => { HelperClass helper = requireInteropClasses.FirstOrDefault(x => x.Attribute.Name == requirePath); if (helper != null) { return(helper.Type.GetConstructor(new Type[] { }).Invoke(new object[] { })); } if (requirePath.Length > 2 && requirePath.Substring(0, 2) == "./") { //TODO: check if file doesnt exist return(Evaluate(File.ReadAllText(Path.Combine(dirname, requirePath)))); } return(null); //TODO: require package.json stuff })); V8Engine.Evaluate("const __dirname = '" + dirname + "';"); V8Engine.Evaluate("const __filename = '" + filename + "';"); }
public static object RunJS_V8() { using (var engine = new V8ScriptEngine()) { var f = "test.js"; var code = File.ReadAllText(f); engine.Compile(code); engine.AddHostType("Console", typeof(Console)); engine.Execute("Console.WriteLine('{0} is an interesting number.', Math.PI)"); engine.AddHostType("Console", typeof(Console)); engine.Evaluate("Console.debug('faasfafa')"); var res = engine.Evaluate("test(fsfs)"); Console.WriteLine(res); } return(null); }
/// <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); }
/// <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)); }
public ScriptRunner() { V8 = new V8ScriptEngine("script code runner"); V8.AddHostObject("host", new HostFunctions()); V8.AddHostObject("代理", Proxy); V8.AddHostObject("库", new HostTypeCollection("mscorlib", "System.Core")); V8.AddHostType("键盘", typeof(VirtualKeyShort)); UiTimer = new System.Threading.Timer(new TimerCallback((state => { lock (this) { if (IsExecuting) { MainForm.WriteLine("上一任务未执行完成,此次轮空"); return; } IsExecuting = true; } try { StartUp(); IsExecuting = false; } catch (Exception exception) { MainForm.WriteLine($@"ERROR runner script:{exception}"); IsExecuting = false; IsRun = false; } })), null, 0, 300); }
private void AddHostTypeToATMB(string name, Type type) { string bindingName = $"___atmb_binding__{name}"; engine.AddHostType(bindingName, type); engine.ExecuteCommand($"atmb.{name} = {bindingName}"); }
public override bool Initialize(Action <Exception> FailedCallback) { try { Engine = new V8ScriptEngine(); FileHelper fh = new FileHelper(); //创建脚本数据库 读取所有脚本 if (!Directory.Exists("joyScripts")) { Directory.CreateDirectory("joyScripts"); } foreach (var file in Directory.GetFiles("joyScripts")) { var name = System.IO.Path.GetFileNameWithoutExtension(file); var nameHash = name.GetHashCode(); var scriptStr = fh.readFile(file); if (!this.Scripts.ContainsKey(nameHash)) { scriptStr = Regex.Replace(scriptStr, "var.*?onJoyKey.*?\\=", $"var onJoyKey_{nameHash.ToString()}="); Engine.Execute(scriptStr); this.Scripts.Add(nameHash, scriptStr); } } this.KeyBoardJoyMap = new KeyBoardJoyMap(this.KeyBoardConfig); this.XinputJoyMap = new VitualXinputJoyMap(this.XinputConfig); this.KeyBoardJoyMap.Initialize(FailedCallback); this.XinputJoyMap.Initialize(FailedCallback); Engine.AddHostObject("keyBoard", this.KeyBoardJoyMap); Engine.AddHostObject("xinput", this.XinputJoyMap); Engine.AddHostType("Xbox360Report", typeof(Xbox360Report)); Engine.AddHostType("Xbox360ReportExtensions", typeof(Xbox360ReportExtensions)); Engine.AddHostType("Xbox360Axes", typeof(Xbox360Axes)); Engine.AddHostType("Xbox360Buttons", typeof(Xbox360Buttons)); ////TODO 读取脚本文件加载 //Engine.Execute(this.Scripts["default".GetHashCode()]); return(true); } catch (Exception e) { FailedCallback(e); return(false); } }
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())"); } }
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(); } } } }
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); } }
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}]"); } }
/// <summary> /// 加载系统扩展模块 /// </summary> internal static void LoadSystemModules(this V8ScriptEngine v8) { v8.AddHostObject("lib", new HostTypeCollection("mscorlib", "System.Core")); v8.AddHostObject("host", new HostModuleExtend()); v8.AddHostType("Array", typeof(JSArray)); v8.AddHostObject("http", new HttpModule()); var unityJs = Unity.ReadResource("Snail.Collector.Core.SystemModules.Unity.js"); if (!string.IsNullOrEmpty(unityJs)) { v8.Execute(unityJs); } var httpProxy = Unity.ReadResource("Snail.Collector.Http.HttpModule.js", Assembly.GetAssembly(typeof(HttpModule))); if (!string.IsNullOrEmpty(httpProxy)) { v8.Execute(httpProxy); } v8.AddHostType(typeof(HttpModuleExtend)); v8.AddHostObject("storage", new StorageDataModuleExtend()); var storageProxy = Unity.ReadResource("Snail.Collector.Storage.StorageDataModule.js", Assembly.GetAssembly(typeof(StorageDataModule))); if (!string.IsNullOrEmpty(storageProxy)) { v8.Execute(storageProxy); } var moduleProxy = Unity.ReadResource("Snail.Collector.Core.SystemModules.SystemModule.js"); if (!string.IsNullOrEmpty(moduleProxy)) { v8.Execute(moduleProxy); } var stringExt = Unity.ReadResource("Snail.Collector.Core.SystemModules.StringExtend.js"); if (!string.IsNullOrEmpty(stringExt)) { v8.Execute(stringExt); } v8.AddHostType(typeof(HttpResultExtend)); }
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); }
/// <summary> /// 加载系统扩展模块 /// </summary> internal static void LoadSystemModules(this V8ScriptEngine v8) { v8.AddHostObject("lib", new HostTypeCollection("mscorlib", "System.Core")); v8.AddHostObject("host", new HostModuleExtend()); v8.AddHostType("Array", typeof(JSArray)); v8.AddHostObject("http", new HttpModuleExtend()); var moduleProxy = Unity.ReadResource("Snail.Collector.Core.SystemModules.SystemModule.js"); if (!string.IsNullOrEmpty(moduleProxy)) { v8.Execute(moduleProxy); } }
public ContentLoader() { engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging); engine.AddHostType(typeof(Job)); engine.AddHostType(typeof(Ecosystem)); engine.AddHostType(typeof(Archetypes)); engine.AddHostType(typeof(ContentLoader)); Directories.Add(ContentDirectory); #if DEVELOPER watcher = new FileSystemWatcher(ContentDirectory); watcher.NotifyFilter = NotifyFilters.LastWrite; watcher.Filter = "*.js"; watcher.IncludeSubdirectories = true; watcher.Changed += new FileSystemEventHandler(OneFileChanged); watcher.Created += new FileSystemEventHandler(OneFileChanged); watcher.Deleted += new FileSystemEventHandler(OneFileChanged); watcher.Renamed += new RenamedEventHandler(OnFileRenamed); watcher.EnableRaisingEvents = true; #endif }
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())"); } }
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())"); } }
/// <summary> /// 执行脚本文件 /// </summary> /// <param name="file">文件名</param> /// <param name="fun">函数名</param> /// <param name="param1">参数1</param> /// <param name="param2">参数2</param> /// <param name="param3">参数3</param> /// <returns>返回执行结果</returns> public object RunFile(string file, object fun, object param1 = null, object param2 = null, object param3 = null) { 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)); var dyn = Eng.Script; if (param1 == null) { return(dyn.Main(fun)); } else if (param2 == null) { return(dyn.Main(fun, param1)); } else if (param3 == null) { return(dyn.Main(fun, param1, param2)); } else { return(dyn.Main(fun, param1, param2, param3)); } } catch (Exception ex) { Ex = ex.ToString(); } return(null); }
public TestRunner() { Engine = new V8ScriptEngine(); Engine.AddHostType("Terminal", typeof(Terminal)); Engine.AddHostObject("host", new HostFunctions()); Engine.AddHostObject("log", new Log()); foreach (string file in Directory.EnumerateFiles("Libraries", "*.js", SearchOption.AllDirectories)) { Console.WriteLine($"Found library: {file}"); var scriptText = File.ReadAllText(file); Engine.Execute(scriptText); } }
protected override void InnerEmbedHostType(string itemName, Type type) { lock (_executionSynchronizer) { try { _jsEngine.AddHostType(itemName, type); } catch (OriginalJsException e) { throw ConvertScriptEngineExceptionToJsRuntimeException(e); } } }
public static void Initialize(TestContext context) { var settings = new XsbPrologInitializationSettings { HomeDirectory = @"C:\Program Files (x86)\XSB", BinaryDirectory = @"C:\Program Files (x86)\XSB\config\x64-pc-windows\bin", PrependBinaryDirectoryToPath = true }; v8 = new V8ScriptEngine(); prolog = new XsbPrologEngine(settings); v8.AddHostType("Console", typeof(Console)); v8.AddHostObject("prolog", prolog); }
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); }
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; } }
public void Execute(SaveFile saveFile, string folderPath, bool debuggingEnabled, int debuggingPort) { V8ScriptEngineFlags flag; if (debuggingEnabled) { flag = V8ScriptEngineFlags.EnableDebugging; } else { flag = V8ScriptEngineFlags.None; } if (_engine == null) { _engine = new V8ScriptEngine(flag, debuggingPort); } _engine.DocumentSettings.AccessFlags = DocumentAccessFlags.EnableFileLoading; _engine.AddHostObject("lib", new HostTypeCollection(typeof(SaveFile).Assembly)); _engine.AddHostObject("nodes", saveFile.Nodes); _engine.AddHostObject("host", new HostFunctions()); _engine.AddHostType(typeof(Enumerable)); _engine.AddHostType(typeof(EnumerableExtensions)); _engine.ExecuteDocument(Path.Combine(folderPath, "script.js")); }
public static void Initialize(TestContext context) { var settings = new SwiPrologInitializationSettings { HomeDirectory = @"C:\Program Files\swipl", SetHomeDirectoryEnvironmentVariable = true, BinaryDirectory = @"C:\Program Files\swipl\bin", PrependBinaryDirectoryToPath = true }; v8 = new V8ScriptEngine(); prolog = new SwiPrologEngine(settings); v8.AddHostType("Console", typeof(Console)); v8.AddHostObject("prolog", prolog); }
/// <summary> /// 执行脚本代码 /// </summary> /// <param name="code">代码</param> /// <param name="fun">函数名</param> /// <param name="param1">参数1</param> /// <param name="param2">参数2</param> /// <param name="param3">参数3</param> /// <returns>返回执行结果</returns> public object RunCode(string code, object fun, object param1 = null, object param2 = null, object param3 = null) { if (string.IsNullOrEmpty(code)) { Ex = "脚本不能为空"; return(null); } try { var Eng = new V8ScriptEngine { EnableAutoHostVariables = true }; Eng.AddHostType("Console", typeof(Console)); Eng.AddHostObject("Cache", new Cache()); var Engine = new Index { Dir = _Dir }; Eng.AddHostObject("Engine", Engine); Eng.Execute(code); var dyn = Eng.Script; if (param1 == null) { return(dyn.Main(fun)); } else if (param2 == null) { return(dyn.Main(fun, param1)); } else if (param3 == null) { return(dyn.Main(fun, param1, param2)); } else { return(dyn.Main(fun, param1, param2, param3)); } } catch (Exception ex) { Ex = ex.ToString(); } return(null); }
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)); }
public static void Main() { //var application = new System.Windows.Application(); //var window = new System.Windows.Window(); //application.Run(window); var applicationPath = AppDomain.CurrentDomain.BaseDirectory; string fileName = Path.Combine(applicationPath, "app", "app.js"); var sourceCode = File.ReadAllText(fileName); //var engine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging); var engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging); engine.AddHostType("Console", typeof(Console)); var typeCollection = new HostTypeCollection("mscorlib", "System", "System.Core", "PresentationCore", "PresentationFramework", "WindowsBase"); engine.AddHostObject("clr", typeCollection); engine.AddHostObject("xHost", new ExtendedHostFunctions()); engine.Execute(fileName, sourceCode); }
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); }
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); }
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); }