public void Core_sleep_Exists() { using (var engine = new JsEngine()) { engine.AddCoreLibrary(); engine.Execute("Core = lib('Core');"); engine.Execute("Core.sleep(100)"); } }
public void Engine_AddLibrary_Core() { using (var engine = new JsEngine()) { engine.AddCoreLibrary(); engine.Execute("Core = lib('AudioSwitcher');"); Assert.Equal(true, engine.InternalEngine.HasGlobalValue("Core")); } }
public void Engine_AddLibrary_Dynamic() { using (var engine = new JsEngine()) { engine.AddLibrary("Dynamic", new TestLibrary()); engine.Execute("Dynamic = lib('Dynamic');"); Assert.Equal(true, engine.InternalEngine.HasGlobalValue("Dynamic")); } }
public void Engine_WithArgs() { string[] test = new string[] { "One", "Two" }; var engine = new JsEngine(); Assert.NotNull(engine.Evaluate<string[]>("args", test)); }
public void AudioSwitcher_AudioDevice_getName() { using (var engine = new JsEngine()) { engine.AddAudioSwitcherLibrary(GetAudioController()); engine.Execute("AudioSwitcher = lib('AudioSwitcher');"); const string js = @"AudioSwitcher.getAudioDevices()[0].name"; var result = engine.Execute(js); Assert.NotNull(result); Assert.Null(result.ExecutionException); Assert.True(result.Success); } }
public void Engine_Dynamic_Method_Func_Returns() { using (var engine = new JsEngine()) { var testLib = new TestLibrary(); engine.AddLibrary("Dynamic", testLib); engine.Execute("Dynamic = lib('Dynamic');"); Assert.Equal(true, engine.InternalEngine.HasGlobalValue("Dynamic")); var result = engine.Evaluate<string>("Dynamic.MethodFunc()"); Assert.NotNull(result.ExecutionException); //Assert.Equal(testLib.MethodFunc()(), result.Value); } }
public void Engine_Dynamic_Delegate_Func_Fail() { using (var engine = new JsEngine()) { var testLib = new TestLibrary(); engine.AddLibrary("Dynamic", testLib); engine.Execute("Dynamic = lib('Dynamic');"); Assert.True(engine.InternalEngine.HasGlobalValue("Dynamic")); var result = engine.Evaluate<string>("Dynamic.DelegateWithArguments('Hello')"); Assert.NotNull(result.ExecutionException); //Assert.Equal(testLib.DelegateWithArguments(), result.Value); } }
public void AudioSwitcher_AudioDevice_Exists() { using (var engine = new JsEngine()) { engine.AddAudioSwitcherLibrary(GetAudioController()); engine.Execute("AudioSwitcher = lib('AudioSwitcher');"); const string js = @"AudioSwitcher.getAudioDevices()[0];"; var result = engine.Execute(js); Assert.NotNull(result); Assert.Null(result.ExecutionException); Assert.True(result.Success); Assert.NotEqual(null, engine.Evaluate<JavaScriptAudioDevice>(js)); Assert.IsType<JavaScriptAudioDevice>(engine.Evaluate<JavaScriptAudioDevice>(js).Value); } }
public void Engine_Dynamic_Delegate_Returns() { using (var engine = new JsEngine()) { var testLib = new TestLibrary(); engine.AddLibrary("Dynamic", testLib); engine.Execute("import('Dyanmic');"); engine.Execute("Dynamic = lib('Dynamic');"); Assert.Equal(true, engine.InternalEngine.HasGlobalValue("Dynamic")); var result = engine.Evaluate<int>("Dynamic.Delegate()"); Assert.Equal(testLib.Property, result.Value); } }
public void Engine_Dynamic_Method_WithArg_Returns() { using (var engine = new JsEngine()) { var testLib = new TestLibrary(); engine.AddLibrary("Dynamic", testLib); engine.Execute("Dynamic = lib('Dynamic');"); Assert.Equal(true, engine.InternalEngine.HasGlobalValue("Dynamic")); var result = engine.Evaluate<string>("Dynamic.MethodWithArg('Hello')"); Assert.Equal("Hello", result.Value); } }
public void AudioSwitcher_getAudioDevices_Playback_IsPlayback_Enum() { using (var engine = new JsEngine()) { engine.AddAudioSwitcherLibrary(GetAudioController()); engine.Execute("AudioSwitcher = lib('AudioSwitcher');"); var device = engine.Evaluate<JavaScriptAudioDevice>("AudioSwitcher.getAudioDevices(AudioSwitcher.DeviceType.PLAYBACK)[0]").Value; var devices = engine.Evaluate<IEnumerable<JavaScriptAudioDevice>>("AudioSwitcher.getAudioDevices(AudioSwitcher.DeviceType.PLAYBACK)").Value; Assert.True(devices.All(x => x.IsPlayback)); Assert.True(device.IsPlayback); } }
public void AudioSwitcher_getAudioDevices_Capture_IsCapture_List() { using (var engine = new JsEngine()) { engine.AddAudioSwitcherLibrary(GetAudioController()); engine.Execute("AudioSwitcher = lib('AudioSwitcher');"); var device = engine.Evaluate<JavaScriptAudioDevice>("AudioSwitcher.getAudioDevices(AudioSwitcher.DeviceType.CAPTURE)[0]").Value; var devices = engine.Evaluate<List<JavaScriptAudioDevice>>("AudioSwitcher.getAudioDevices(AudioSwitcher.DeviceType.CAPTURE)").Value; Assert.IsAssignableFrom<IEnumerable<JavaScriptAudioDevice>>(devices); Assert.IsAssignableFrom<IList<JavaScriptAudioDevice>>(devices); Assert.IsType<List<JavaScriptAudioDevice>>(devices); Assert.True(devices.All(x => x.IsCapture)); Assert.True(device.IsCapture); } }
public void AudioSwitcher_AudioDevice_toggleMute() { using (var engine = new JsEngine()) { engine.AddAudioSwitcherLibrary(GetAudioController()); engine.Execute("AudioSwitcher = lib('AudioSwitcher');"); const string js = @"AudioSwitcher.getAudioDevices()[0].toggleMute()"; //Toggles the mute and tests non equality of state var isMuted = engine.Evaluate<bool>(js).Value; Assert.NotEqual(isMuted, engine.Evaluate<bool>(js).Value); } }
public void AudioSwitcher_AudioDevice_setMute_false() { using (var engine = new JsEngine()) { const string js = @"AudioSwitcher.getAudioDevices()[0].mute(false)"; Assert.Equal(false, engine.Evaluate<bool>(js).Value); } }
public void Setup() { jsEngine = new JsEngine(); }
public void Setup() { jsEngine = new JsEngine(); js = jsEngine.CreateContext(); }
public void Engine_Dynamic_Value_Exists() { using (var engine = new JsEngine()) { var testLib = new TestLibrary(); engine.AddLibrary("Dynamic", testLib); engine.Execute("Dynamic = lib('Dynamic');"); Assert.Equal(true, engine.InternalEngine.HasGlobalValue("Dynamic")); Assert.Equal(testLib.Property, engine.Evaluate<int>("Dyanmic.Property").Value); } }
static void Main() { //----------------------------------- //1. //after we build nodejs in dll version //we will get node.dll //then just copy it to another name 'libespr' string currentdir = System.IO.Directory.GetCurrentDirectory(); string libEspr = @"../../../node-v8.9.3/Release/libespr.dll"; //previous version 8.4.0 if (File.Exists(libEspr)) { //delete the old one File.Delete(libEspr); } File.Copy( @"../../../node-v8.9.3/Release/node.dll", // //previous version 8.4.0 libEspr); //----------------------------------- //2. load libespr.dll (node.dll) //----------------------------------- //2. load libespr.dll (node.dll) IntPtr intptr = LoadLibrary(libEspr); int errCode = GetLastError(); int libesprVer = JsBridge.LibVersion; //change working dir to target app and run //test with socket.io's chat sample System.IO.Directory.SetCurrentDirectory(@"../../../socket.io/examples/chat"); #if DEBUG JsBridge.dbugTestCallbacks(); #endif //------------ JsEngine.RunJsEngine((IntPtr nativeEngine, IntPtr nativeContext) => { JsEngine eng = new JsEngine(nativeEngine); JsContext ctx = eng.CreateContext(nativeContext); //------------- //this LibEspressoClass object is need, //so node can talk with us, //------------- JsTypeDefinition jstypedef = new JsTypeDefinition("LibEspressoClass"); jstypedef.AddMember(new JsMethodDefinition("LoadMainSrcFile", args => { //since this is sample socket io app string filedata = File.ReadAllText("index.js"); args.SetResult(filedata); })); jstypedef.AddMember(new JsMethodDefinition("C", args => { args.SetResult(true); })); jstypedef.AddMember(new JsMethodDefinition("E", args => { args.SetResult(true); })); if (!jstypedef.IsRegisterd) { ctx.RegisterTypeDefinition(jstypedef); } //---------- //then register this as x*** //this object is just an instance for reference ctx.SetVariableFromAny("LibEspresso", ctx.CreateWrapper(new object(), jstypedef)); }); string userInput = Console.ReadLine(); }
private static int Main(string[] args) { if (args.Length > 2 || args.Length < 1) return PrintUsage(); //Process CLI Arguments for (var i = 0; i < args.Length - 1; i++) { switch (args[i]) { case "--debug": _isDebug = true; break; } } //Process file name string fName = args[args.Length - 1]; if (!fName.EndsWith(".js")) { Console.WriteLine("Invalid input file"); Console.WriteLine(); return PrintUsage(); } IAudioController controller; if (_isDebug) controller = new SandboxAudioController(new CoreAudioController()); else controller = new CoreAudioController(); using (var engine = new JsEngine()) { engine.AddCoreLibrary(); engine.AddAudioSwitcherLibrary(controller); //Enable to log to CLI //engine.SetGlobalValue("console", new ConsoleOutput(engine)); //engine.InternalEngine.SetGlobalValue("console", new FirebugConsole(engine.InternalEngine)); engine.SetOutput(new ConsoleScriptOutput()); try { Console.WriteLine("Executing {0}...", fName); var result = engine.Execute(new Scripting.FileScriptSource(fName)); if (!result.Success) throw result.ExecutionException; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } #if DEBUG Console.ReadKey(); #endif return 0; }
public void Setup() { js = new JsEngine(); }
public void AudioSwitcher_AudioDevice_setDefault_Playback_Comm() { using (var engine = new JsEngine()) { engine.AddAudioSwitcherLibrary(GetAudioController()); engine.Execute("AudioSwitcher = lib('AudioSwitcher');"); const string setDefault = @"AudioSwitcher.getAudioDevices(AudioSwitcher.DeviceType.PLAYBACK)[0].setAsDefaultComm()"; const string checkDefault = @"AudioSwitcher.getAudioDevices(AudioSwitcher.DeviceType.PLAYBACK)[0].isDefaultComm"; engine.Execute(setDefault); Assert.Equal(true, engine.Evaluate<bool>(checkDefault).Value); } }
public string BuildJs(string content) { var buffer = new StringBuilder(); int offset = 0; while (offset < content.Length) { int beginIndex = content.IndexOf('$', offset); if (beginIndex < 0) { buffer.Append(content.Substring(offset, content.Length - offset)); break; } if (beginIndex > 0 && content[beginIndex - 1] == '\\') { if (beginIndex > offset + 1) { buffer.Append(content.Substring(offset, beginIndex - offset - 1)); } buffer.Append('$'); offset = beginIndex + 1; continue; } int delimiterEnd = content.IndexOf('{', beginIndex + 1); if (delimiterEnd < beginIndex + 1) { buffer.Append(content.Substring(offset, content.Length - offset)); break; } string delimiter = content.Substring(beginIndex + 1, delimiterEnd - beginIndex - 1); int endIndex = content.IndexOf("}" + delimiter, delimiterEnd + 1); if (endIndex < 0) { buffer.Append(content.Substring(offset, delimiterEnd - offset + 1)); offset = delimiterEnd + 1; continue; } string code = content.Substring(delimiterEnd + 1, endIndex - delimiterEnd - 1); string result = JsEngine.Evaluate(code, TimeSpan.FromSeconds(3)); buffer.Append(content.Substring(offset, beginIndex - offset)); buffer.Append(result); offset = endIndex + delimiter.Length + 1; } return(buffer.ToString()); }
public void AudioSwitcher_AudioDevice_setMute_true() { using (var engine = new JsEngine()) { engine.AddAudioSwitcherLibrary(GetAudioController()); engine.Execute("AudioSwitcher = lib('AudioSwitcher');"); const string js = @"AudioSwitcher.getAudioDevices()[0].mute(true)"; //Sets to muted Assert.Equal(true, engine.Evaluate<bool>(js).Value); } }
/// <summary> /// Runs a script with a different language inside the LoliScript. /// </summary> /// <param name="script">The script as a string with linebreaks</param> /// <param name="language">The language of the script</param> /// <param name="outputs">The variables that should be extracted from the script's scope and set into the BotData local variables</param> /// <param name="data">The BotData needed for variable replacement</param> private void RunScript(string script, ScriptingLanguage language, string outputs, BotData data, string jsFilePath = "") { // Set the console output to stringwriter var sw = new StringWriter(); Console.SetOut(sw); Console.SetError(sw); jsFilePath = BlockBase.ReplaceValues(jsFilePath, data); if (jsFilePath != string.Empty && File.Exists(jsFilePath)) { script += File.ReadAllText(jsFilePath); } // Parse variables to get out List <string> outVarList = new List <string>(); if (outputs != string.Empty) { try { outVarList = outputs.Split(',').Select(x => x.Trim()).ToList(); } catch { } } var start = DateTime.Now; try { switch (language) { case ScriptingLanguage.JavaScript: switch (jsEngine.ToLower()) { case "jint": InvokeJint(); break; case "noesis": InvokeNoesis(); break; default: InvokeJint(); break; } void InvokeNoesis() { var taskExecuteJs = Task.Run(() => { object jsRetValue = null; bool disposeEngine = false; JavascriptContext context = null; if (disposeEngine = data.JsEngine == null) { context = new JavascriptContext(); JsEngine.SetParameter(context, data); } else { context = data.JsEngine.GetOrCreateEngine(data); } // Execute JS try { jsRetValue = context.Run(script); } catch (JavascriptException ex) { throw new Exception($"Executing js error {ex.Message}\nline: {ex.Line}\nStart column:{ex.StartColumn}"); } // Print results to log data.Log(new LogEntry($"DEBUG LOG: {sw}", Colors.White)); // Get variables out data.Log(new LogEntry($"Parsing {outVarList.Count} variables", Colors.White)); foreach (var name in outVarList) { try { //Add it to the variables and print info var value = context.GetParameter(name); var isArray = value.GetType().IsArray || value is string[] || value.GetType().Name.Contains("Dictionary"); if (isArray) { try { data.Variables.Set(new CVar(name, CVar.VarType.List, (List <string>)value)); } catch (Exception ex) { data.Log(new LogEntry("[SET VARS] ERROR: " + ex.Message, Colors.Yellow)); } } else { data.Variables.Set(new CVar(name, CVar.VarType.Single, value.ToString())); } data.Log(new LogEntry($"SET VARIABLE {name} WITH VALUE {value}", Colors.Yellow)); } catch { data.Log(new LogEntry($"COULD NOT FIND VARIABLE {name}", Colors.Tomato)); } } if (disposeEngine) { context.Dispose(); } //Print other info if (jsRetValue != null && !jsRetValue.GetType().Name.Contains("Dictionary")) { data.Log(new LogEntry($"Return value: {jsRetValue}", Colors.White)); } }); taskExecuteJs.Wait(); taskExecuteJs.Dispose(); } void InvokeJint() { // Redefine log() function var jsEngine = new Jint.Engine().SetValue("log", new Action <object>(Console.WriteLine)); // Add in all the variables foreach (var variable in data.Variables.All) { try { switch (variable.Type) { case CVar.VarType.List: jsEngine.SetValue(variable.Name, (variable.Value as List <string>).ToArray()); break; default: jsEngine.SetValue(variable.Name, variable.Value.ToString()); break; } } catch { } } // Execute JS jsEngine.Execute(script); // Print results to log data.Log(new LogEntry($"DEBUG LOG: {sw.ToString()}", Colors.White)); // Get variables out data.Log(new LogEntry($"Parsing {outVarList.Count} variables", Colors.White)); foreach (var name in outVarList) { try { // Add it to the variables and print info var value = jsEngine.Global.GetProperty(name).Value; var isArray = value.IsArray(); if (isArray) { data.Variables.Set(new CVar(name, CVar.VarType.List, value.TryCast <List <string> >())); } else { data.Variables.Set(new CVar(name, CVar.VarType.Single, value.ToString())); } data.Log(new LogEntry($"SET VARIABLE {name} WITH VALUE {value.ToString()}", Colors.Yellow)); } catch { data.Log(new LogEntry($"COULD NOT FIND VARIABLE {name}", Colors.Tomato)); } } // Print other info if (jsEngine.GetCompletionValue() != null) { data.Log(new LogEntry($"Completion value: {jsEngine.GetCompletionValue()}", Colors.White)); } } break; case ScriptingLanguage.IronPython: // Initialize the engine var runtime = Python.CreateRuntime(); var pyengine = runtime.GetEngine("py"); PythonCompilerOptions pco = (PythonCompilerOptions)pyengine.GetCompilerOptions(); pco.Module &= ~ModuleOptions.Optimized; //var pyengine = Python.CreateEngine(); var scope = pyengine.CreateScope(); var code = pyengine.CreateScriptSourceFromString(script); // Add in all the variables foreach (var variable in data.Variables.All) { try { scope.SetVariable(variable.Name, variable.Value); } catch { } } // Execute it var result = code.Execute(scope); //var result = pyengine.Execute(script, scope); // Print the logs data.Log(new LogEntry($"DEBUG LOG: {sw}", Colors.White)); // Get variables out data.Log(new LogEntry($"Parsing {outVarList.Count} variables", Colors.White)); foreach (var name in outVarList) { try { // Add it to the variables and print info var value = scope.GetVariable(name); data.Variables.Set(new CVar(name, (value.GetType() == typeof(string[])) ? CVar.VarType.List : CVar.VarType.Single, value.ToString())); data.Log(new LogEntry($"SET VARIABLE {name} WITH VALUE {value}", Colors.Yellow)); } catch { data.Log(new LogEntry($"COULD NOT FIND VARIABLE {name}", Colors.Tomato)); } } // Print other info if (result != null) { data.Log(new LogEntry($"Completion value: {result}", Colors.White)); } break; default: break; } data.Log(new LogEntry($"Execution completed in {(DateTime.Now - start).TotalSeconds} seconds", Colors.GreenYellow)); } catch (Exception e) { data.Log(new LogEntry($"[ERROR] INFO: {e.Message}", Colors.White)); } finally { var standardOutput = new StreamWriter(Console.OpenStandardOutput()); var standardError = new StreamWriter(Console.OpenStandardError()); standardOutput.AutoFlush = true; standardError.AutoFlush = true; Console.SetOut(standardOutput); Console.SetError(standardError); } }
public void AudioSwitcher_AudioDevice_setVolume() { using (var engine = new JsEngine()) { engine.AddAudioSwitcherLibrary(GetAudioController()); engine.Execute("AudioSwitcher = lib('AudioSwitcher');"); const string setTo10 = @"AudioSwitcher.getAudioDevices()[0].volume(10)"; const string getVolume = @"AudioSwitcher.getAudioDevices()[0].volume()"; var orignalVol = engine.Evaluate<int>(getVolume).Value; string setToOriginal = @"AudioSwitcher.getAudioDevices()[0].volume(" + orignalVol + ")"; Assert.Equal(10, engine.Evaluate<int>(setTo10).Value); Assert.Equal(10, engine.Evaluate<int>(getVolume).Value); Assert.Equal(orignalVol, engine.Evaluate<int>(setToOriginal).Value); } }
public static void Main(string[] args) { // string lodash = File.ReadAllText(@"c:\lodash.js"); using (JsEngine engine = new JsEngine()) { //Stopwatch watch = new Stopwatch(); // watch.Start(); JsScript script = engine.CompileScript("3+3"); using (JsContext ctx = engine.CreateContext()) { ctx.Execute(script); } } debugtest dbg = new debugtest(); // Delegate.CreateDelegate() //Dictionary<string, object> values = new Dictionary<string, object>(); //values["test"] = 333; while (true) { using (JsEngine js = new JsEngine(4, 32)) { using (JsContext context = js.CreateContext()) { //context.SetVariable("dbg", dbg); //object result = context.Execute("dbg.Write(dbg.valueOf());"); context.SetVariableFromAny("Debug", typeof(debugtest)); object result = context.Execute("Debug.BoolTest(3,4);"); } GC.Collect(); js.DumpHeapStats(); } } //context.SetVariable("values", values); //object result = context.Execute("dbg.runFunc(); values.test ? true : false;"); // object result = // context.Execute("var obj = { test: 0 }; obj.ft = function (v) { dbg.Write(v); return 'from JS'; }; dbg.runFunc(obj.ft); dbg.write(obj.test);"); //int a = 1; // context.SetFunction("runfunc", new Func<int, bool>(Activate)); //object result = context.Execute("runfunc(2);"); // } // } //} /*using (JsEngine js = new JsEngine()) { * using (JsContext context = js.CreateContext()) { * using (JsScript script = js.CompileScript("3 * 4")) { * object result = context.Execute(script, TimeSpan.FromHours(200)); * Console.WriteLine(result); * } * } * }*/ //return; /* * using (JsEngine js = new JsEngine()) { * using (JsContext context = js.CreateContext()) { * for (int i = 0; i < 10; i++) { * context.SetVariable("a", new Simple { N = i, S = (i * 10).ToString() }); * Console.WriteLine(context.Execute("a.N+' '+a.S")); * } * Console.WriteLine(context.Execute("a.N+' '+a.X")); * } * }*/ }
public void AudioSwitcher_getAudioDeviceByName_Playback_Flags() { using (var engine = new JsEngine()) { engine.AddAudioSwitcherLibrary(GetAudioController()); engine.Execute("AudioSwitcher = lib('AudioSwitcher');"); const string js = @"AudioSwitcher.getAudioDevice(AudioSwitcher.getAudioDevices(AudioSwitcher.DeviceType.PLAYBACK)[0].name, AudioSwitcher.DeviceType.PLAYBACK);"; var result = engine.Execute(js); Assert.NotNull(result); Assert.Null(result.ExecutionException); Assert.True(result.Success); var audioDevice = engine.Evaluate<JavaScriptAudioDevice>("AudioSwitcher.getAudioDevices(AudioSwitcher.DeviceType.PLAYBACK)[0]").Value; var resolvedAudioDevice = engine.Evaluate<JavaScriptAudioDevice>(js).Value; Assert.NotEqual(null, resolvedAudioDevice); Assert.Equal(audioDevice.Id, resolvedAudioDevice.Id); Assert.IsType<JavaScriptAudioDevice>(resolvedAudioDevice); Assert.True(resolvedAudioDevice.IsPlayback); } }
static void Main() { //----------------------------------- //1. //after we build nodejs in dll version //we will get node.dll //then just copy it to another name 'libespr' string libEspr = @"C:\projects\node-v7.4.0\Release\libespr.dll"; if (File.Exists(libEspr)) { //delete the old one File.Delete(libEspr); } File.Copy( @"C:\projects\node-v7.4.0\Release\node.dll", //from libEspr); //----------------------------------- //2. load libespr.dll (node.dll) IntPtr intptr = LoadLibrary(libEspr); int errCode = GetLastError(); #if DEBUG JsBridge.dbugTestCallbacks(); #endif //------------ JsEngine.RunJsEngine((IntPtr nativeEngine, IntPtr nativeContext) => { JsEngine eng = new JsEngine(nativeEngine); JsContext ctx = eng.CreateContext(nativeContext); //------------- //this LibEspressoClass object is need, //so node can talk with us, //------------- JsTypeDefinition jstypedef = new JsTypeDefinition("LibEspressoClass"); jstypedef.AddMember(new JsMethodDefinition("LoadMainSrcFile", args => { string filedata = @"var http = require('http'); (function t(){ console.log('hello from EspressoCup'); var server = http.createServer(function(req, res) { res.writeHead(200); res.end('Hello! from EspressoCup'); }); server.listen(8080,'localhost'); })();"; args.SetResult(filedata); })); jstypedef.AddMember(new JsMethodDefinition("C", args => { args.SetResult(true); })); jstypedef.AddMember(new JsMethodDefinition("E", args => { args.SetResult(true); })); if (!jstypedef.IsRegisterd) { ctx.RegisterTypeDefinition(jstypedef); } //---------- //then register this as x*** //this object is just an instance for reference ctx.SetVariableFromAny("LibEspresso", ctx.CreateWrapper(new object(), jstypedef)); }); }
public void AudioSwitcher_getAudioDevices_Playback() { using (var engine = new JsEngine()) { engine.AddAudioSwitcherLibrary(GetAudioController()); engine.Execute("AudioSwitcher = lib('AudioSwitcher');"); engine.Execute("AudioSwitcher.getAudioDevices(AudioSwitcher.DeviceType.PLAYBACK)"); Assert.Equal(2, engine.Evaluate<int>("AudioSwitcher.getAudioDevices(AudioSwitcher.DeviceType.PLAYBACK).length").Value); } }
private void button3_Click(object sender, EventArgs e) { #if DEBUG JsBridge.dbugTestCallbacks(); #endif JsTypeDefinition jstypedef = new JsTypeDefinition("AA"); jstypedef.AddMember(new JsMethodDefinition("B", args => { args.SetResult(100); })); jstypedef.AddMember(new JsMethodDefinition("C", args => { args.SetResult(true); })); jstypedef.AddMember(new JsPropertyDefinition("D", args => { //getter args.SetResult(true); }, args => { //setter })); jstypedef.AddMember(new JsPropertyDefinition("E", args => { //getter args.SetResult(250); }, args => { //setter })); //=============================================================== //create js engine and context using (JsEngine engine = new JsEngine()) using (JsContext ctx = engine.CreateContext()) { ctx.RegisterTypeDefinition(jstypedef); GC.Collect(); System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch(); stwatch.Reset(); stwatch.Start(); TestMe1 t1 = new TestMe1(); var proxy = ctx.CreateWrapper(t1, jstypedef); //for (int i = 2000; i >= 0; --i) //{ ctx.SetVariableFromAny("x", proxy); //object result = ctx.Execute("(function(){if(x.C()){return x.B();}else{return 0;}})()"); object result = ctx.Execute("(function(){if(x.D){ x.E=300; return x.B();}else{return 0;}})()"); //} stwatch.Stop(); Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString()); //Assert.That(result, Is.EqualTo(100)); } }
public void Engine_AddLibrary_AudioSwitcher() { using (var engine = new JsEngine()) { engine.AddAudioSwitcherLibrary(GetAudioController()); engine.Execute("AudioSwitcher = lib('AudioSwitcher');"); Assert.Equal(true, engine.InternalEngine.HasGlobalValue("AudioSwitcher")); } }
private void button5_Click(object sender, EventArgs e) { #if DEBUG JsBridge.dbugTestCallbacks(); #endif JsTypeDefinition jstypedef = new JsTypeDefinition("AA"); jstypedef.AddMember(new JsMethodDefinition("B", args => { var argCount = args.ArgCount; var thisArg = args.GetThisArg(); var arg0 = args.GetArgAsObject(0); args.SetResult((bool)arg0); })); jstypedef.AddMember(new JsMethodDefinition("C", args => { args.SetResult(true); })); //----------------------------------------------------- jstypedef.AddMember(new JsPropertyDefinition("D", args => { var ab = new AboutMe(); args.SetResultAutoWrap(ab); }, args => { //setter })); jstypedef.AddMember(new JsPropertyDefinition("E", args => { //getter args.SetResult(250); }, args => { //setter })); //=============================================================== //create js engine and context using (JsEngine engine = new JsEngine()) using (JsContext ctx = engine.CreateContext()) { ctx.RegisterTypeDefinition(jstypedef); GC.Collect(); System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch(); stwatch.Reset(); stwatch.Start(); TestMe1 t1 = new TestMe1(); INativeScriptable proxy = ctx.CreateWrapper(t1, jstypedef); ctx.SetVariable("x", proxy); string testsrc = "x.B(x.D.IsOK);"; object result = ctx.Execute(testsrc); stwatch.Stop(); Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString()); } }
public void AudioSwitcher_AudioDevice_getVolume() { using (var engine = new JsEngine()) { engine.AddAudioSwitcherLibrary(GetAudioController()); engine.Execute("AudioSwitcher = lib('AudioSwitcher');"); const string js = @"AudioSwitcher.getAudioDevices()[0].volume()"; //don't care what it returns, just that it exists var result = engine.Execute(js); Assert.NotNull(result); Assert.Null(result.ExecutionException); Assert.True(result.Success); } }
public void Engine_Dynamic_Method_Returns_ClrArray() { using (var engine = new JsEngine()) { var testLib = new TestLibrary(); engine.AddLibrary("Dynamic", testLib); engine.Execute("Dynamic = lib('Dynamic');"); Assert.Equal(true, engine.InternalEngine.HasGlobalValue("Dynamic")); var result = engine.Evaluate<int>("Dynamic.MethodReturnClrArray().Length"); Assert.Equal(2, result.Value); } }