public void BugFix_VBScriptItemArgsByRef() { engine.Dispose(); engine = new VBScriptEngine(); var a = new object(); var b = new object(); var c = new object(); var x = new object(); var y = new object(); var z = new object(); engine.Script.a = a; engine.Script.b = b; engine.Script.c = c; engine.Script.x = x; engine.Script.y = y; engine.Script.z = z; engine.Execute("sub test(i, j, k) : i = x : j = y : k = z : end sub"); engine.Script.test(ref a, out b, ref c); Assert.AreSame(x, a); Assert.AreSame(y, b); Assert.AreSame(z, c); }
/// <summary> /// 获取函数 /// </summary> /// <param name="file">文件名</param> /// <returns>返回函数</returns> public dynamic GetClass(string file) { if (string.IsNullOrEmpty(file)) { Ex = "脚本文件名不能为空"; return(null); } file = Cache.ToFullName(file, _Dir); if (!File.Exists(file)) { Ex = "脚本不存在!请确认脚本:“" + file + "”是否存在。"; return(null); } try { var Eng = new VBScriptEngine { EnableAutoHostVariables = true }; Eng.AddHostType("Console", typeof(Console)); Eng.AddHostObject("Cache", new Cache()); var Engine = new EngineHelper { 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); }
public void BugFix_VBScriptItemArgsByRef_Struct() { engine.Dispose(); engine = new VBScriptEngine(); var random = new Random(); var a = TimeSpan.FromMilliseconds(random.NextDouble() * 1000); var b = TimeSpan.FromMilliseconds(random.NextDouble() * 1000); var c = TimeSpan.FromMilliseconds(random.NextDouble() * 1000); var x = TimeSpan.FromMilliseconds(random.NextDouble() * 1000); var y = TimeSpan.FromMilliseconds(random.NextDouble() * 1000); var z = TimeSpan.FromMilliseconds(random.NextDouble() * 1000); engine.Script.a = a; engine.Script.b = b; engine.Script.c = c; engine.Script.x = x; engine.Script.y = y; engine.Script.z = z; engine.Execute("sub test(i, j, k) : i = x : j = y : k = z : end sub"); engine.Script.test(ref a, out b, ref c); Assert.AreEqual(x, a); Assert.AreEqual(y, b); Assert.AreEqual(z, c); }
public void BugFix_IDispatchExArgLeak_GetProperty_VBScript() { engine.Dispose(); engine = new VBScriptEngine(); WeakReference wr1 = null; WeakReference wr2 = null; new Action(() => { object x1 = Guid.NewGuid(); wr1 = new WeakReference(x1); object x2 = Guid.NewGuid(); wr2 = new WeakReference(x2); engine.Execute(@" class MyClass public property get foo(x1, x2) foo = x1.ToString() & x2.ToString() end property end class set bar = new MyClass "); var bar = (DynamicObject)engine.Script.bar; var args = new[] { "foo", HostItem.Wrap(engine, x1), HostItem.Wrap(engine, x2) }; Assert.IsTrue(bar.GetMetaObject(Expression.Constant(bar)).TryGetIndex(args, out var result)); Assert.AreEqual(x1.ToString() + x2, result); })(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); Assert.IsFalse(wr1.IsAlive); Assert.IsFalse(wr2.IsAlive); }
public void BugFix_IDispatchExArgLeak_InvokeMethod_VBScript() { engine.Dispose(); engine = new VBScriptEngine(); WeakReference wr1 = null; WeakReference wr2 = null; new Action(() => { object x1 = Guid.NewGuid(); wr1 = new WeakReference(x1); object x2 = Guid.NewGuid(); wr2 = new WeakReference(x2); engine.Execute("function foo(x1, x2):foo = x1.ToString() & x2.ToString():end function"); Assert.AreEqual(x1.ToString() + x2, engine.Script.foo(x1, x2)); engine.CollectGarbage(true); })(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); Assert.IsFalse(wr1.IsAlive); Assert.IsFalse(wr2.IsAlive); }
public void BugFix_PropertyBag_NativeEnumerator_VBScript() { engine.Dispose(); engine = new VBScriptEngine(); var x = new PropertyBag { ["foo"] = 123, ["bar"] = "blah" }; engine.Script.x = x; engine.Execute(@" function getResult(arg) dim result result = """" for each item in arg result = result & item.Value next getResult = result end function "); var result = (string)engine.Evaluate("getResult(x)"); Assert.AreEqual(7, result.Length); Assert.IsTrue(result.IndexOf("123", StringComparison.Ordinal) >= 0); Assert.IsTrue(result.IndexOf("blah", StringComparison.Ordinal) >= 0); }
public void BugFix_IDispatchExArgLeak_SetProperty_VBScript() { // ReSharper disable RedundantAssignment engine.Dispose(); engine = new VBScriptEngine(); WeakReference wr = null; new Action(() => { object x = Guid.NewGuid(); wr = new WeakReference(x); var result = x.ToString(); engine.Script.x = x; x = null; GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); Assert.AreEqual(result, engine.Evaluate("x.ToString()")); engine.Script.x = null; engine.CollectGarbage(true); })(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); Assert.IsFalse(wr.IsAlive); // ReSharper restore RedundantAssignment }
public void BugFix_VBScript_PropertyPut_CrossEngine() { using (var vbEngine = new VBScriptEngine()) { vbEngine.Execute(@" class Test private myFoo public property get foo foo = myFoo end property public property let foo(value) myFoo = value end property end class set myTest = new Test myTest.foo = 123 "); engine.Script.test = vbEngine.Script.myTest; Assert.AreEqual(123, Convert.ToInt32(engine.Evaluate("test.foo"))); engine.Execute("test.foo = 456"); Assert.AreEqual(456, Convert.ToInt32(engine.Evaluate("test.foo"))); engine.Execute("test.foo = \"blah\""); Assert.AreEqual("blah", engine.Evaluate("test.foo")); engine.AddHostObject("bar", new DateTime(2007, 5, 22)); engine.Execute("test.foo = bar"); Assert.AreEqual(new DateTime(2007, 5, 22), engine.Evaluate("test.foo")); } }
public void BugFix_VBScript_PropertyPut() { using (var vbEngine = new VBScriptEngine()) { vbEngine.Execute(@" class Test private myFoo public property get foo foo = myFoo end property public property let foo(value) myFoo = value end property end class set myTest = new Test myTest.foo = 123 "); Assert.AreEqual(123, Convert.ToInt32(vbEngine.Script.myTest.foo)); vbEngine.Script.myTest.foo = 456; Assert.AreEqual(456, Convert.ToInt32(vbEngine.Script.myTest.foo)); vbEngine.Script.myTest.foo = "blah"; Assert.AreEqual("blah", vbEngine.Script.myTest.foo); vbEngine.Script.myTest.foo = new DateTime(2007, 5, 22); Assert.AreEqual(new DateTime(2007, 5, 22), vbEngine.Script.myTest.foo); } }
public FluentJScript() { this._engine = new VBScriptEngine(WindowsScriptEngineFlags.None); this._engine.AddHostObject("host", new HostFunctions()); this._engine.AddHostObject("xHost", new ExtendedHostFunctions()); this._withDebug = false; }
private static void AddHostSymbols(ref VBScriptEngine vbscriptEngine) { vbscriptEngine.AddHostObject("CSExtendedHost", new ExtendedHostFunctions()); vbscriptEngine.AddHostObject("CSHost", new HostFunctions()); var htc = new HostTypeCollection(); foreach (var assembly in new string[] { "mscorlib", "System", "System.Core", "System.Data" /*, "RestSharp", "WebDriver", "WebDriver.Support" */ }) { htc.AddAssembly(assembly); } if (Settings.ContainsKey("/ASSEMBLIES")) { var assemblies = Settings["/ASSEMBLIES"].ToString().Split(','); foreach (var assembly in assemblies) { System.Reflection.Assembly assem; try { assem = System.Reflection.Assembly.LoadFrom(assembly); htc.AddAssembly(assem); } catch (Exception e) { Console.WriteLine(e.Message); } } } vbscriptEngine.AddHostObject("CS", htc); }
public FluentJScript(bool debug) { this._engine = new VBScriptEngine(debug ? WindowsScriptEngineFlags.EnableDebugging | WindowsScriptEngineFlags.EnableJITDebugging : WindowsScriptEngineFlags.None); this._engine.AddHostObject("host", new HostFunctions()); this._engine.AddHostObject("xHost", new ExtendedHostFunctions()); this._withDebug = debug; }
private static void AddInternalSymbols(ref VBScriptEngine vbscriptEngine) { vbscriptEngine.AddHostObject("VBS", vbscriptEngine); vbscriptEngine.AddHostType("CSINI", typeof(INI)); vbscriptEngine.AddHostObject("CSSettings", Settings); vbscriptEngine.AddHostType("CSLychen", typeof(Program)); // Experimental. No idea if useful or dangerous. }
public void BugFix_VBScriptItemArgsByRef_Enum() { engine.Dispose(); engine = new VBScriptEngine(); var a = DayOfWeek.Monday; var b = DayOfWeek.Tuesday; var c = DayOfWeek.Wednesday; const DayOfWeek x = DayOfWeek.Sunday; const DayOfWeek y = DayOfWeek.Saturday; const DayOfWeek z = DayOfWeek.Friday; engine.Script.a = a; engine.Script.b = b; engine.Script.c = c; engine.Script.x = x; engine.Script.y = y; engine.Script.z = z; engine.Execute("sub test(i, j, k) : i = x : j = y : k = z : end sub"); engine.Script.test(ref a, out b, ref c); Assert.AreEqual(x, a); Assert.AreEqual(y, b); Assert.AreEqual(z, c); }
public void BugFix_VBScriptItemArgsByRef_Scalar() { engine.Dispose(); engine = new VBScriptEngine(); var a = 123; var b = 456; var c = 789; const int x = 987; const int y = 654; const int z = 321; engine.Script.a = a; engine.Script.b = b; engine.Script.c = c; engine.Script.x = x; engine.Script.y = y; engine.Script.z = z; engine.Execute("sub test(i, j, k) : i = x : j = y : k = z : end sub"); engine.Script.test(ref a, out b, ref c); Assert.AreEqual(x, a); Assert.AreEqual(y, b); Assert.AreEqual(z, c); }
public void VBScriptCoreEngine_AddCOMType_XMLHTTP() { var status = 0; string data = null; var thread = new Thread(() => { using (var testEngine = new VBScriptEngine(Windows.WindowsScriptEngineFlags.EnableDebugging, NullSyncInvoker.Instance)) { using (var helperEngine = new JScriptEngine(Windows.WindowsScriptEngineFlags.EnableStandardsMode, NullSyncInvoker.Instance)) { // ReSharper disable AccessToDisposedClosure testEngine.Script.onComplete = new Action <int, string>((xhrStatus, xhrData) => { status = xhrStatus; data = xhrData; Dispatcher.ExitAllFrames(); }); testEngine.Script.getData = new Func <string, string>(responseText => helperEngine.Script.JSON.parse(responseText).data ); Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => { testEngine.AddCOMType("XMLHttpRequest", "MSXML2.XMLHTTP"); testEngine.Script.host = new HostFunctions(); testEngine.Execute(@" sub onreadystatechange if xhr.readyState = 4 then call onComplete(xhr.status, getData(xhr.responseText)) end if end sub xhr = host.newObj(XMLHttpRequest) call xhr.open(""POST"", ""http://httpbin.org/post"", true) xhr.onreadystatechange = GetRef(""onreadystatechange"") call xhr.send(""Hello, world!"") "); })); Dispatcher.Run(); // ReSharper restore AccessToDisposedClosure } } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); if (!thread.Join(TimeSpan.FromSeconds(5))) { Assert.Inconclusive("The Httpbin service request timed out"); } Assert.AreEqual(200, status); Assert.AreEqual("Hello, world!", data); }
public void Initialize(IDictionary <string, string> expressions) { _expressions = expressions; string script = GetExpressionScript(_expressions, EXPRESSION_TEMPLATE); _engine = new VBScriptEngine(); _engine.Execute(script); _engine.Execute(EXTRA_FUNCTIONS); }
public void VBScriptEngine_StandardsMode() { engine.Dispose(); engine = new VBScriptEngine(WindowsScriptEngineFlags.EnableDebugging | WindowsScriptEngineFlags.EnableStandardsMode); // Standards Mode shouldn't affect VBScriptEngine at all engine.Execute("function pi : pi = 4 * atn(1) : end function"); engine.Execute("function e : e = exp(1) : end function"); VBScriptEngine_Execute(); }
public void BugFix_NestedType_VBScript() { engine.Dispose(); engine = new VBScriptEngine(); engine.AddHostType(typeof(NestedTypeTest)); Assert.AreEqual(NestedTypeTest.NestedType.Foo, engine.Evaluate("NestedTypeTest.NestedType.Foo")); Assert.AreEqual(NestedTypeTest.NestedType.Bar, engine.Evaluate("NestedTypeTest.NestedType.Bar")); Assert.AreEqual(NestedTypeTest.NestedType.Baz, engine.Evaluate("NestedTypeTest.NestedType.Baz")); Assert.AreEqual(NestedTypeTest.NestedType.Qux, engine.Evaluate("NestedTypeTest.NestedType.Qux")); }
private static void AddSystemSymbols(ref VBScriptEngine vbscriptEngine) { vbscriptEngine.AddHostType("CSFile", typeof(System.IO.File)); vbscriptEngine.AddHostType("CSConsole", typeof(System.Console)); vbscriptEngine.AddHostType("CSPath", typeof(System.IO.Path)); vbscriptEngine.AddHostType("CSDirectory", typeof(System.IO.Directory)); vbscriptEngine.AddHostType("CSDirectoryInfo", typeof(System.IO.DirectoryInfo)); vbscriptEngine.AddHostType("CSEnvironment", typeof(System.Environment)); vbscriptEngine.AddHostType("CSString", typeof(System.String)); vbscriptEngine.AddHostType("CSDateTime", typeof(System.DateTime)); vbscriptEngine.AddHostType("CSDebugger", typeof(System.Diagnostics.Debugger)); }
public void PropertyBag_MultiEngine_HostFunctions() { var bag = new PropertyBag { { "host", new HostFunctions() } }; engine.AddHostObject("bag", bag); using (var scriptEngine = new VBScriptEngine(WindowsScriptEngineFlags.EnableDebugging)) { scriptEngine.AddHostObject("bag", bag); } }
/// <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 = Cache.ToFullName(file, _Dir); if (!File.Exists(file)) { Ex = "脚本不存在!请确认脚本:“" + file + "”是否存在。"; return(null); } try { var Eng = new VBScriptEngine { EnableAutoHostVariables = true }; Eng.AddHostType("Console", typeof(Console)); Eng.AddHostObject("Cache", new Cache()); var Engine = new EngineHelper { 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); }
private void ScriptFunc() { _scriptEngineObject = new VBScriptEngine(); _scriptEngine = (IActiveScript)_scriptEngineObject; _scriptParser = new ActiveScriptParseWrapper(_scriptEngine); _scriptParser.InitNew(); _scriptEngine.SetScriptSite(this); _scriptEngine.SetScriptState(ScriptState.Started); _scriptEngine.SetScriptState(ScriptState.Connected); while (true) { if (_running == 0) { break; } string code = ""; lock (_runnables) { _runnables.ForEach(snippet => code += snippet + "\n"); _runnables.Clear(); } if (code.Trim().Length > 0) { try { /*_scriptEngine.GetScriptThreadState(SCRIPTTHREADID_BASE, out ScriptThreadState state); * Console.WriteLine(string.Format("Scipt thread state for thread '{0}' is {1}", _processThread.Name, state)); * _scriptEngine.GetScriptState(out ScriptState sciptState); * Console.WriteLine(string.Format("Scipt state for thread '{0}' is {1}", _processThread.Name, sciptState));*/ _scriptParser.ParseScriptText(code, null, null, null, IntPtr.Zero, 0, ScriptText.IsVisible, out object result, out EXCEPINFO ei); } catch (Exception e) { Console.WriteLine(string.Format("Exception while parsing following code for thread '{0}'\nException: {1}\nCode:\n{2}", _processThread.Name, e, code)); } } else if (_running == 2) { break; } Thread.Sleep(100); } _scriptEngine.Close(); Marshal.ReleaseComObject(_scriptEngine); Marshal.ReleaseComObject(_scriptEngineObject); _scriptParser.ReleaseComObject(); _scriptEngine = null; _scriptParser = null; }
public void BugFix_VBScript_TargetInvocationException() { engine.Dispose(); engine = new VBScriptEngine(WindowsScriptEngineFlags.EnableDebugging); engine.Script.foo = new Action(() => throw new Exception("bar")); engine.Execute("sub test\nfoo\nend sub"); try { engine.Invoke("test"); } catch (ScriptEngineException exception) { Assert.IsTrue(exception.ErrorDetails.Contains("bar\n at test (Script:1:0) -> foo")); } }
public void Evaluating4000Records_ExpectedTime_100ms() { // Arrange var vbengines = new VBScriptEngine[Environment.ProcessorCount]; var checkPoint = new ManualResetEventSlim(); var exprected_time = TimeSpan.FromMilliseconds(100); var exprected_count = Environment.ProcessorCount; var actual_time = new TimeSpan(); // Act for (var index = 0; index < vbengines.Length; ++index) { var thread = new Thread(indexArg => { using (var engine = new VBScriptEngine()) { vbengines[(int)indexArg] = engine; checkPoint.Set(); Dispatcher.Run(); } }); thread.Start(index); checkPoint.Wait(); checkPoint.Reset(); } Parallel.ForEach(Enumerable.Range(0, 4000), item => { var engine = vbengines[item % vbengines.Length]; engine.Dispatcher.Invoke(() => { ThreadedFunc(new Myobj() { Vbengine = engine, Index = item }); }); }); Array.ForEach(vbengines, engine => engine.Dispatcher.InvokeShutdown()); // Expect Assert.AreEqual(exprected_count, vbengines.Length); Assert.That(actual_time, Is.LessThanOrEqualTo(exprected_time)); }
/// <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 VBScriptEngine { EnableAutoHostVariables = true }; Eng.AddHostType("Console", typeof(Console)); Eng.AddHostObject("Cache", new Cache()); var Engine = new EngineHelper { 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 void BugFix_VBScript_ErrorDetails_DirectAccess_ReadOnlyProperty() { engine.Dispose(); engine = new VBScriptEngine(WindowsScriptEngineFlags.EnableDebugging); engine.AddHostObject("foo", HostItemFlags.DirectAccess, new Variable()); engine.Execute("sub test\nfoo.Description = \"bogus\"\nend sub"); try { engine.Invoke("test"); Assert.Fail(); } catch (ScriptEngineException exception) { Assert.IsTrue(exception.ErrorDetails.Contains("at test (Script:1:0) -> foo.Description = \"bogus\"")); } }
public void BugFix_VBScript_ErrorDetails() { engine.Dispose(); engine = new VBScriptEngine(WindowsScriptEngineFlags.EnableDebugging); engine.AddHostObject("foo", new Variable()); engine.Execute("sub test\nfoo = \"xyz\"\nend sub"); try { engine.Invoke("test"); Assert.Fail(); } catch (ScriptEngineException exception) { Assert.IsTrue(exception.ErrorDetails.Contains("at test (Script:1:0) -> foo = \"xyz\"")); } }
public void BugFix_VBScript_ErrorDetails_DirectAccess_NoDebugger() { engine.Dispose(); engine = new VBScriptEngine(); engine.AddHostObject("foo", HostItemFlags.DirectAccess, new Variable()); engine.Execute("sub test\nfoo = \"xyz\"\nend sub"); try { engine.Invoke("test"); Assert.Fail(); } catch (ScriptEngineException exception) { Assert.IsTrue(exception.ErrorDetails.Contains("at ([unknown]:1:0)")); } }
public void BugFix_AmbiguousIndexer_ADODB() { engine.Dispose(); engine = new VBScriptEngine(WindowsScriptEngineFlags.EnableDebugging); var recordSet = new ADODB.Recordset(); recordSet.Fields.Append("foo", ADODB.DataTypeEnum.adVarChar, 20); recordSet.Open(Missing.Value, Missing.Value, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic, 0); recordSet.AddNew(Missing.Value, Missing.Value); recordSet.Fields["foo"].Value = "bar"; engine.AddHostObject("recordSet", recordSet); Assert.AreEqual("bar", engine.Evaluate("recordSet.Fields.Item(\"foo\").Value")); engine.Execute("recordSet.Fields.Item(\"foo\").Value = \"qux\""); Assert.AreEqual("qux", engine.Evaluate("recordSet.Fields.Item(\"foo\").Value")); TestUtil.AssertException <ScriptEngineException>(() => engine.Evaluate("recordSet.Fields.Item(\"baz\")")); }