ScriptCSSession( IScriptEngine engine, ScriptPackSession scriptPackSession, CurrentCmdletScriptPack currentCmdletScriptPack, CurrentLogger logger) { _engine = engine; _scriptPackSession = scriptPackSession; _currentCmdletScriptPack = currentCmdletScriptPack; _logger = logger; }
public ScriptResult Execute(string code, string[] scriptArgs, IEnumerable<string> references, IEnumerable<string> namespaces, ScriptPackSession scriptPackSession) { Guard.AgainstNullArgument("scriptPackSession", scriptPackSession); _logger.Info("Starting to create execution components"); _logger.Debug("Creating script host"); var distinctReferences = references.Union(scriptPackSession.References).Distinct().ToList(); SessionState<Session> sessionState; if (!scriptPackSession.State.ContainsKey(SessionKey)) { var host = _scriptHostFactory.CreateScriptHost(new ScriptPackManager(scriptPackSession.Contexts), scriptArgs); _logger.Debug("Creating session"); var session = _scriptEngine.CreateSession(host); foreach (var reference in distinctReferences) { _logger.DebugFormat("Adding reference to {0}", reference); session.AddReference(reference); } foreach (var @namespace in namespaces.Union(scriptPackSession.Namespaces).Distinct()) { _logger.DebugFormat("Importing namespace {0}", @namespace); session.ImportNamespace(@namespace); } sessionState = new SessionState<Session> {References = distinctReferences, Session = session}; scriptPackSession.State[SessionKey] = sessionState; } else { _logger.Debug("Reusing existing session"); sessionState = (SessionState<Session>) scriptPackSession.State[SessionKey]; var newReferences = sessionState.References == null || !sessionState.References.Any() ? distinctReferences : distinctReferences.Except(sessionState.References); if (newReferences.Any()) { foreach (var reference in newReferences) { _logger.DebugFormat("Adding reference to {0}", reference); sessionState.Session.AddReference(reference); } sessionState.References = newReferences; } } _logger.Info("Starting execution"); var result = Execute(code, sessionState.Session); _logger.Info("Finished execution"); return result; }
public void Execute(string code, IEnumerable<string> references, IEnumerable<string> namespaces, ScriptPackSession scriptPackSession) { var host = _scriptHostFactory.CreateScriptHost(new ScriptPackManager(scriptPackSession.Contexts)); var session = _scriptEngine.CreateSession(host); foreach (var reference in references.Union(scriptPackSession.References).Distinct()) session.AddReference(reference); foreach (var @namespace in namespaces.Union(scriptPackSession.Namespaces).Distinct()) session.ImportNamespace(@namespace); Execute(code, session); }
public static ScriptCSSession Create(Cmdlet cmdlet) { ScriptCSSession session = null; var logger = new CurrentLogger(); using (logger.CreateActiveLoggerSession(new CmdletLogger(cmdlet))) { IScriptHostFactory factory = new ScriptHostFactory(); var engine = new RoslynScriptEngine(factory, logger); engine.BaseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var currentCmdletScriptPack = new CurrentCmdletScriptPack(); var scriptPackSession = new ScriptPackSession(new IScriptPack[] { currentCmdletScriptPack }); scriptPackSession.InitializePacks(); session = new ScriptCSSession( engine, scriptPackSession, currentCmdletScriptPack, logger ); } return session; }
public void Execute(string script, IEnumerable<string> paths, IEnumerable<IScriptPack> scriptPacks) { var bin = Path.Combine(_fileSystem.GetWorkingDirectory(script), "bin"); var references = DefaultReferences.Union(paths); _scriptEngine.BaseDirectory = bin; var scriptPackSession = new ScriptPackSession(scriptPacks); scriptPackSession.InitializePacks(); var path = Path.IsPathRooted(script) ? script : Path.Combine(_fileSystem.CurrentDirectory, script); var code = _filePreProcessor.ProcessFile(path); _scriptEngine.Execute(code, references, DefaultNamespaces, scriptPackSession); scriptPackSession.TerminatePacks(); }
public virtual ScriptResult ProcessCommand(string command, ScriptPackSession scriptPackSession) { _logger.Debug("Processing REPL Command [" + command + "] >>"); var scriptResult = new ScriptResult(); if (_replCommands.Count.Equals(0)) { if (scriptPackSession.ReplCommands != null && scriptPackSession.ReplCommands.Count > 0) { foreach (var scriptPackReplCommand in scriptPackSession.ReplCommands) { _replCommands.Add(scriptPackReplCommand.Key, scriptPackReplCommand.Value); } } } var script = ParseArguments(command); if (!string.IsNullOrWhiteSpace(script)) { script = NormaliseScript(script); if (_scriptEngine != null) scriptResult = _scriptEngine.Execute(script, new string[0], scriptPackSession.References, scriptPackSession.Namespaces, scriptPackSession); _logger.Debug("<< REPL Command executed."); } else { scriptResult.ReturnValue = "REPL Command not found"; _logger.Debug("<< REPL Command not defined."); } return scriptResult; }
public void ShouldNotReturnExecuteExceptionIfCodeExecutionDoesNotThrowAnException( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] RoslynScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "var theNumber = 42; //this should not throw an Exception"; var session = new SessionState <Session> { Session = new ScriptEngine().CreateSession() }; scriptPackSession.State[RoslynScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(new[] { "System" }); // Act var result = engine.Execute(Code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert result.ExecuteExceptionInfo.ShouldBeNull(); }
public void ShouldAddNewReferencesIfTheyAreProvided( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] CSharpTestScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "var a = 0;"; var session = new SessionState <ScriptState> { Session = CSharpScript.Run("") }; scriptPackSession.State[CommonScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(new[] { "System" }); // Act engine.Execute(Code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert ((SessionState <ScriptState>)scriptPackSession.State[CommonScriptEngine.SessionKey]).References.Paths.Count().ShouldEqual(1); }
public void ShouldCreateScriptHostWithContexts( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [Frozen] Mock <IScriptPack> scriptPack, ScriptPackSession scriptPackSession, [NoAutoProperties] RoslynScriptEngine engine) { // Arrange const string Code = "var a = 0;"; scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>(), It.IsAny <string[]>())) .Returns <IScriptPackManager, string[]>((p, q) => new ScriptHost(p, q)); scriptPack.Setup(p => p.Initialize(It.IsAny <IScriptPackSession>())); scriptPack.Setup(p => p.GetContext()).Returns((IScriptPackContext)null); // Act engine.Execute(Code, new string[0], Enumerable.Empty <string>(), Enumerable.Empty <string>(), scriptPackSession); // Assert scriptHostFactory.Verify(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>(), It.IsAny <string[]>())); }
public void ShouldNotReturnReturnValueIfCodeExecutionDoesNotReturnValue( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] CSharpScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "var theNumber = 42; //this should not return a value"; var session = new SessionState <ScriptState> { Session = CSharpScript.Run("") }; scriptPackSession.State[CommonScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(new[] { "System" }); // Act var result = engine.Execute(Code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert result.ReturnValue.ShouldBeNull(); }
public void ShouldInitializeScriptLibraryWrapperHost( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, Mock <IScriptPackManager> manager, [NoAutoProperties] CSharpScriptEngine engine, ScriptPackSession scriptPackSession ) { // Arrange const string Code = "var theNumber = 42; //this should compile"; var refs = new AssemblyReferences(new[] { "System" }); scriptHostFactory.Setup(s => s.CreateScriptHost(It.IsAny <IScriptPackManager>(), It.IsAny <string[]>())) .Returns(new ScriptHost(manager.Object, null)); // Act engine.Execute(Code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert ScriptLibraryWrapper.ScriptHost.ShouldNotEqual(null); }
public void ShouldReturnAScriptResult( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] CSharpTestScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange var code = string.Empty; var session = new SessionState <ScriptState> { Session = CSharpScript.Run("") }; scriptPackSession.State[CommonScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(new[] { "System" }); // Act var result = engine.Execute(code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert result.ShouldBeType <ScriptResult>(); }
public void ShouldReturnExecuteExceptionIfCodeExecutionThrowsException( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] CSharpScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "throw new System.Exception(); //this should throw an Exception"; var session = new SessionState <ScriptState> { Session = CSharpScript.Run("") }; scriptPackSession.State[CommonScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(new[] { "System" }); // Act var result = engine.Execute(Code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert result.ExecuteExceptionInfo.ShouldNotBeNull(); }
public void ShouldCreateScriptHostWithContexts() { var scriptHostFactory = new Mock <IScriptHostFactory>(); scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>())).Returns((IScriptPackManager p) => new ScriptHost(p)); var code = "var a = 0;"; var engine = CreateScriptEngine(scriptHostFactory: scriptHostFactory); var scriptPack1 = new Mock <IScriptPack>(); scriptPack1.Setup(p => p.Initialize(It.IsAny <IScriptPackSession>())); scriptPack1.Setup(p => p.GetContext()).Returns((IScriptPackContext)null); var scriptPackSession = new ScriptPackSession(new[] { scriptPack1.Object }); engine.Execute(code, Enumerable.Empty <string>(), Enumerable.Empty <string>(), scriptPackSession); scriptHostFactory.Verify(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>())); }
public void ShouldReturnReturnValueIfCodeExecutionReturnsValue( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] RoslynScriptEngine engine, ScriptPackSession scriptPackSession) { const string Code = "\"Hello\" //this should return \"Hello\""; var session = new SessionState <Session> { Session = new ScriptEngine().CreateSession() }; scriptPackSession.State[RoslynScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(); refs.PathReferences.Add("System"); // Act var result = engine.Execute(Code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert result.ReturnValue.ShouldEqual("Hello"); }
public ScriptResult Execute(string code, string[] scriptArgs, AssemblyReferences references, IEnumerable <string> namespaces, ScriptPackSession scriptPackSession) { try { var def = Compiler.Compile("code", code, false, false, false); using (var exeStream = new MemoryStream()) { AssemblyFactory.SaveAssembly(def, exeStream); var exeBytes = exeStream.ToArray(); var assembly = Assembly.Load(exeBytes); assembly.EntryPoint.Invoke(null, new object[] { new string[0] }); } } catch (CompilerException e) { throw new Exception("Error compiling", e); } return(new ScriptResult()); }
public void ShouldSetIsCompleteSubmissionToFalseIfCodeIsMissingCurlyBracket( [NoAutoProperties] RoslynReplEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "class test {"; var session = new SessionState <Session> { Session = new ScriptEngine().CreateSession() }; scriptPackSession.State[RoslynScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(); refs.PathReferences.Add("System"); // Act var result = engine.Execute( Code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert result.IsCompleteSubmission.ShouldBeFalse(); }
public void ShouldExposeExceptionThrownByCompilation( [NoAutoProperties] RoslynScriptInMemoryEngine scriptEngine) { // Arrange var lines = new List <string> { "using Sysasdasdasdtem;" }; var code = string.Join(Environment.NewLine, lines); var session = new ScriptPackSession(Enumerable.Empty <IScriptPack>(), new string[0]); // Act var result = scriptEngine.Execute(code, new string[0], Enumerable.Empty <string>(), Enumerable.Empty <string>(), session); // Assert var exception = Assert.Throws <ScriptCompilationException>(() => result.CompileExceptionInfo.Throw()); exception.InnerException.ShouldBeType <CompilationErrorException>(); exception.Message.ShouldContain("The type or namespace name 'Sysasdasdasdtem' could not be found"); }
public void ShouldExposeExceptionThrownByCompilation() { var scriptEngine = new CSharpScriptInMemoryEngine(new ScriptHostFactory(_console, _printers), new TestLogProvider()); // Arrange var lines = new List <string> { "Sysasdasdasdtem;" }; var code = string.Join(Environment.NewLine, lines); var session = new ScriptPackSession(Enumerable.Empty <IScriptPack>(), new string[0]); // Act var result = scriptEngine.Execute(code, new string[0], new AssemblyReferences(), Enumerable.Empty <string>(), session); // Assert var exception = Assert.Throws <ScriptCompilationException>(() => result.CompileExceptionInfo.Throw()); exception.Message.ShouldContain("error CS0103: The name 'Sysasdasdasdtem' does not exist in the current context"); }
public void ShouldReturnAScriptResult( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] RoslynTestScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange var code = string.Empty; scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>(), It.IsAny <string[]>())) .Returns <IScriptPackManager, string[]>((p, q) => new ScriptHost(p, q)); var session = new SessionState <Session> { Session = new ScriptEngine().CreateSession() }; scriptPackSession.State[RoslynScriptEngine.SessionKey] = session; // Act var result = engine.Execute(code, new string[0], new[] { "System" }, Enumerable.Empty <string>(), scriptPackSession); // Assert result.ShouldBeType <ScriptResult>(); }
public void ShouldReuseExistingSessionIfProvided( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] MonoTestScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "var a = 0;"; scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>(), It.IsAny <string[]>())) .Returns <IScriptPackManager, string[]>((p, q) => new ScriptHost(p, new ScriptEnvironment(q, _console, _printers))); var session = new SessionState <Evaluator> { Session = new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter())) }; scriptPackSession.State[MonoScriptEngine.SessionKey] = session; // Act engine.Execute(Code, new string[0], new AssemblyReferences(), Enumerable.Empty <string>(), scriptPackSession); // Assert engine.Session.ShouldEqual(session.Session); }
public void ShouldReturnExecuteExceptionIfCodeExecutionThrowsException( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] RoslynScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "throw new System.Exception(); //this should throw an Exception"; scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>(), It.IsAny <string[]>())) .Returns <IScriptPackManager, string[]>((p, q) => new ScriptHost(p, q)); var session = new SessionState <Session> { Session = new ScriptEngine().CreateSession() }; scriptPackSession.State[RoslynScriptEngine.SessionKey] = session; // Act var result = engine.Execute(Code, new string[0], new[] { "System" }, Enumerable.Empty <string>(), scriptPackSession); // Assert result.ExecuteExceptionInfo.ShouldNotBeNull(); }
public void ShouldNotReturnReturnValueIfCodeExecutionDoesNotReturnValue( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] RoslynScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "var theNumber = 42; //this should not return a value"; scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>(), It.IsAny <string[]>())) .Returns <IScriptPackManager, string[]>((p, q) => new ScriptHost(p, q)); var session = new SessionState <Session> { Session = new ScriptEngine().CreateSession() }; scriptPackSession.State[RoslynScriptEngine.SessionKey] = session; // Act var result = engine.Execute(Code, new string[0], new[] { "System" }, Enumerable.Empty <string>(), scriptPackSession); // Assert result.ReturnValue.ShouldBeNull(); }
public void ShouldAddNewReferencesIfTheyAreProvided( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] RoslynTestScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "var a = 0;"; var session = new SessionState <Session> { Session = new ScriptEngine().CreateSession() }; scriptPackSession.State[RoslynScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(); refs.PathReferences.Add("System"); // Act engine.Execute(Code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert ((SessionState <Session>)scriptPackSession.State[RoslynScriptEngine.SessionKey]).References.PathReferences.Count().ShouldEqual(1); }
public void ShouldExposeExceptionThrownByScriptWhenErrorOccurs() { var scriptEngine = new CSharpScriptInMemoryEngine(new ScriptHostFactory(_console, _printers), new TestLogProvider()); // Arrange var lines = new List <string> { "using System;", @"throw new InvalidOperationException(""InvalidOperationExceptionMessage."");" }; var code = string.Join(Environment.NewLine, lines); var session = new ScriptPackSession(Enumerable.Empty <IScriptPack>(), new string[0]); // Act var result = scriptEngine.Execute(code, new string[0], new AssemblyReferences(), Enumerable.Empty <string>(), session); // Assert var exception = Assert.Throws <InvalidOperationException>(() => result.ExecuteExceptionInfo.Throw()); exception.StackTrace.ShouldContain("Submission#0"); exception.Message.ShouldContain("InvalidOperationExceptionMessage"); }
public void ShouldAddNewReferencesIfTheyAreProvided( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] RoslynTestScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "var a = 0;"; scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>(), It.IsAny <string[]>())) .Returns <IScriptPackManager, string[]>((p, q) => new ScriptHost(p, q)); var session = new SessionState <Session> { Session = new ScriptEngine().CreateSession() }; scriptPackSession.State[RoslynScriptEngine.SessionKey] = session; // Act engine.Execute(Code, new string[0], new[] { "System" }, Enumerable.Empty <string>(), scriptPackSession); // Assert ((SessionState <Session>)scriptPackSession.State[RoslynScriptEngine.SessionKey]).References.Count().ShouldEqual(1); }
public void ShouldReturnAScriptResult( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] RoslynTestScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange var code = string.Empty; var session = new SessionState <Session> { Session = new ScriptEngine().CreateSession() }; scriptPackSession.State[RoslynScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(); refs.PathReferences.Add("System"); // Act var result = engine.Execute(code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert result.ShouldBeType <ScriptResult>(); }
public void ShouldExposeExceptionThrownByScriptWhenErrorOccurs( [NoAutoProperties] RoslynScriptInMemoryEngine scriptEngine) { // Arrange var lines = new List <string> { "using System;", @"throw new InvalidOperationException(""InvalidOperationExceptionMessage."");" }; var code = string.Join(Environment.NewLine, lines); var session = new ScriptPackSession(Enumerable.Empty <IScriptPack>(), new string[0]); // Act var result = scriptEngine.Execute(code, new string[0], Enumerable.Empty <string>(), Enumerable.Empty <string>(), session); // Assert var exception = Assert.Throws <InvalidOperationException>(() => result.ExecuteExceptionInfo.Throw()); exception.StackTrace.ShouldContain("at Submission#0"); exception.Message.ShouldContain("InvalidOperationExceptionMessage"); }
public void ShouldRemoveInvalidNamespacesFromSessionStateAndEngine( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] RoslynScriptEngine engine, ScriptPackSession scriptPackSession) { var session = new SessionState <Session> { Session = new ScriptEngine().CreateSession() }; scriptPackSession.State[RoslynScriptEngine.SessionKey] = session; // Act engine.Execute(string.Empty, new string[0], new AssemblyReferences(), new[] { "System", "foo" }, scriptPackSession); // Assert session.Namespaces.ShouldNotBeEmpty(); session.Namespaces.ShouldNotContain("foo"); var pendingNamespacesField = session.Session.GetType().GetField("pendingNamespaces", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); var pendingNamespacesValue = (ReadOnlyArray <string>)pendingNamespacesField.GetValue(session.Session); pendingNamespacesValue.AsEnumerable().ShouldNotBeEmpty(); pendingNamespacesValue.AsEnumerable().ShouldNotContain("foo"); }
public void ShouldReturnCompileExceptionIfCodeDoesNotCompile( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] RoslynScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "this shold not compile"; var session = new SessionState <Session> { Session = new ScriptEngine().CreateSession() }; scriptPackSession.State[RoslynScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(); refs.PathReferences.Add("System"); // Act var result = engine.Execute(Code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert result.CompileExceptionInfo.ShouldNotBeNull(); }
public void ShouldReuseExistingSessionIfProvided( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] RoslynTestScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "var a = 0;"; scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>(), It.IsAny <string[]>())) .Returns <IScriptPackManager, string[]>((p, q) => new ScriptHost(p, new ScriptEnvironment(q))); var session = new SessionState <Session> { Session = new ScriptEngine().CreateSession() }; scriptPackSession.State[RoslynScriptEngine.SessionKey] = session; // Act engine.Execute(Code, new string[0], new AssemblyReferences(), Enumerable.Empty <string>(), scriptPackSession); // Assert engine.Session.ShouldEqual(session.Session); }
public void ShouldReuseExistingSessionIfProvided( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] CSharpTestScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "var a = 0;"; scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>(), It.IsAny <string[]>())) .Returns <IScriptPackManager, string[]>((p, q) => new ScriptHost(p, new ScriptEnvironment(q, _console, _printers))); var session = new SessionState <ScriptState> { Session = CSharpScript.RunAsync("").GetAwaiter().GetResult() }; scriptPackSession.State[CommonScriptEngine.SessionKey] = session; // Act engine.Execute(Code, new string[0], new AssemblyReferences(), Enumerable.Empty <string>(), scriptPackSession); // Assert engine.Session.ShouldEqual(session.Session); }
public void ShouldReturnAScriptResult( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] MonoScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange var code = string.Empty; scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>(), It.IsAny <string[]>())) .Returns <IScriptPackManager, string[]>((p, q) => new ScriptHost(p, new ScriptEnvironment(q, _console, _printers))); var session = new SessionState <Evaluator> { Session = new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter())) }; scriptPackSession.State[MonoScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(new[] { "System" }); // Act var result = engine.Execute(code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert result.ShouldBeType <ScriptResult>(); }
public void ShouldNotReturnReturnValueIfCodeExecutionDoesNotReturnValue( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] MonoScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "var theNumber = 42; //this should not return a value"; scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>(), It.IsAny <string[]>())) .Returns <IScriptPackManager, string[]>((p, q) => new ScriptHost(p, new ScriptEnvironment(q, _console, _printers))); var session = new SessionState <Evaluator> { Session = new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter())) }; scriptPackSession.State[MonoScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(new[] { "System" }); // Act var result = engine.Execute(Code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert result.ReturnValue.ShouldBeNull(); }
public void ShouldAddNewReferencesIfTheyAreProvided( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] MonoTestScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "var a = 0;"; scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>(), It.IsAny <string[]>())) .Returns <IScriptPackManager, string[]>((p, q) => new ScriptHost(p, new ScriptEnvironment(q))); var session = new SessionState <Evaluator> { Session = new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter())) }; scriptPackSession.State[MonoScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(new[] { "System" }); // Act engine.Execute(Code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert ((SessionState <Evaluator>)scriptPackSession.State[MonoScriptEngine.SessionKey]).References.Paths.Count().ShouldEqual(1); }
public void ShouldSetIsPendingClosingCharToTrueIfCodeIsMissingParenthesis( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] RoslynScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "System.Diagnostics.Debug.WriteLine(\"a\""; scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>(), It.IsAny <string[]>())) .Returns <IScriptPackManager, string[]>((p, q) => new ScriptHost(p, q)); var session = new SessionState <Session> { Session = new ScriptEngine().CreateSession() }; scriptPackSession.State[RoslynScriptEngine.SessionKey] = session; // Act var result = engine.Execute(Code, new string[0], new[] { "System" }, Enumerable.Empty <string>(), scriptPackSession); // Assert result.IsPendingClosingChar.ShouldBeTrue(); result.ExpectingClosingChar.ShouldEqual(')'); }
public virtual void Initialize( IEnumerable<string> paths, IEnumerable<IScriptPack> scriptPacks, params string[] scriptArgs) { AddReferences(paths.ToArray()); var bin = Path.Combine(FileSystem.CurrentDirectory, FileSystem.BinFolder); var cache = Path.Combine(FileSystem.CurrentDirectory, FileSystem.DllCacheFolder); ScriptEngine.BaseDirectory = bin; ScriptEngine.CacheDirectory = cache; _log.Debug("Initializing script packs"); var scriptPackSession = new ScriptPackSession(scriptPacks, scriptArgs); ScriptPackSession = scriptPackSession; scriptPackSession.InitializePacks(); }
public void Initalize(IConfiguration configuration) { _logger.LogInformation($"Detecting CSX files in '{_env.Path}'."); var allCsxFiles = Directory.GetFiles(_env.Path, "*.csx", SearchOption.TopDirectoryOnly); if (allCsxFiles.Length == 0) { _logger.LogInformation("Could not find any CSX files"); return; } _scriptCsContext.Path = _env.Path; _logger.LogInformation($"Found {allCsxFiles.Length} CSX files."); //script name is added here as a fake one (dir path not even a real file); this is OK though -> it forces MEF initialization var scriptServicesBuilder = new ScriptServicesBuilder(new ScriptConsole(), LogManager.GetCurrentClassLogger()). LogLevel(LogLevel.Info).Cache(false).Repl(false).ScriptName(_env.Path).ScriptEngine<NullScriptEngine>(); _scriptServices = scriptServicesBuilder.Build(); var mscorlib = MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location); var systemCore = MetadataReference.CreateFromFile(typeof(Enumerable).GetTypeInfo().Assembly.Location); var scriptcsContracts = MetadataReference.CreateFromFile(typeof(IScriptHost).Assembly.Location); var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp6, DocumentationMode.Parse, SourceCodeKind.Script); var scriptPacks = _scriptServices.ScriptPackResolver.GetPacks().ToList(); var assemblyPaths = _scriptServices.AssemblyResolver.GetAssemblyPaths(_env.Path); foreach (var csxPath in allCsxFiles) { try { _scriptCsContext.CsxFiles.Add(csxPath); var processResult = _scriptServices.FilePreProcessor.ProcessFile(csxPath); var references = new List<MetadataReference> { mscorlib, systemCore, scriptcsContracts }; var usings = new List<string>(ScriptExecutor.DefaultNamespaces); //default references ImportReferences(references, ScriptExecutor.DefaultReferences); //file usings usings.AddRange(processResult.Namespaces); //#r references ImportReferences(references, processResult.References); //nuget references ImportReferences(references, assemblyPaths); //script packs if (scriptPacks != null && scriptPacks.Any()) { var scriptPackSession = new ScriptPackSession(scriptPacks, new string[0]); scriptPackSession.InitializePacks(); //script pack references ImportReferences(references, scriptPackSession.References); //script pack usings usings.AddRange(scriptPackSession.Namespaces); _scriptCsContext.ScriptPacks.UnionWith(scriptPackSession.Contexts.Select(pack => pack.GetType().ToString())); } _scriptCsContext.References.UnionWith(references.Select(x => x.Display)); _scriptCsContext.Usings.UnionWith(usings); var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: usings.Distinct()); var fileName = Path.GetFileName(csxPath); var projectId = ProjectId.CreateNewId(Guid.NewGuid().ToString()); var project = ProjectInfo.Create(projectId, VersionStamp.Create(), fileName, $"{fileName}.dll", LanguageNames.CSharp, null, null, compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost)); _workspace.AddProject(project); AddFile(csxPath, projectId); foreach (var filePath in processResult.LoadedScripts.Distinct().Except(new[] { csxPath })) { _scriptCsContext.CsxFiles.Add(filePath); var loadedFileName = Path.GetFileName(filePath); var loadedFileProjectId = ProjectId.CreateNewId(Guid.NewGuid().ToString()); var loadedFileSubmissionProject = ProjectInfo.Create(loadedFileProjectId, VersionStamp.Create(), $"{loadedFileName}-LoadedFrom-{fileName}", $"{loadedFileName}-LoadedFrom-{fileName}.dll", LanguageNames.CSharp, null, null, compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost)); _workspace.AddProject(loadedFileSubmissionProject); AddFile(filePath, loadedFileProjectId); _workspace.AddProjectReference(projectId, new ProjectReference(loadedFileProjectId)); } } catch (Exception ex) { _logger.LogError($"{csxPath} will be ignored due to the following error:", ex); } } }
public virtual void Initialize(IEnumerable<string> paths, IEnumerable<IScriptPack> scriptPacks, params string[] scriptArgs) { AddReferences(paths.ToArray()); var bin = Path.Combine(FileSystem.CurrentDirectory, "bin"); ScriptEngine.BaseDirectory = bin; Logger.Debug("Initializing script packs"); var scriptPackSession = new ScriptPackSession(scriptPacks, scriptArgs); scriptPackSession.InitializePacks(); ScriptPackSession = scriptPackSession; }
protected override void ProcessRecord() { var currentCmdletScriptPack = new CurrentCmdletScriptPack(this); var scriptPackSession = new ScriptPackSession(new IScriptPack[] { currentCmdletScriptPack }); scriptPackSession.InitializePacks(); var result = _engine.Execute(Script, References, Namespaces, scriptPackSession); WriteObject(result); currentCmdletScriptPack.Terminate(); }
public virtual void Initialize(IEnumerable<string> paths, IEnumerable<IScriptPack> scriptPacks) { References = DefaultReferences.Union(paths); var bin = Path.Combine(FileSystem.CurrentDirectory, "bin"); ScriptEngine.BaseDirectory = bin; Logger.Debug("Initializing script packs"); var scriptPackSession = new ScriptPackSession(scriptPacks); scriptPackSession.InitializePacks(); ScriptPackSession = scriptPackSession; }