Exemplo n.º 1
0
 public TheConstructor()
 {
     _scriptPackMock = new Mock<IScriptPack>();
     _contextMock = new Mock<IScriptPackContext>();
     _scriptPackMock.Setup(p => p.GetContext()).Returns(_contextMock.Object);
     _scriptPackSession = new ScriptPackSession(new List<IScriptPack>{_scriptPackMock.Object}, new string[0]);
 }
Exemplo n.º 2
0
        public ScriptResult Execute(string code, string[] scriptArgs, AssemblyReferences references, IEnumerable<string> namespaces,
            ScriptPackSession scriptPackSession)
        {
            Guard.AgainstNullArgument("references", references);
            Guard.AgainstNullArgument("scriptPackSession", scriptPackSession);

            references.PathReferences.UnionWith(scriptPackSession.References);

            SessionState<Evaluator> sessionState;
            if (!scriptPackSession.State.ContainsKey(SessionKey))
            {
                Logger.Debug("Creating session");
                var context = new CompilerContext(new CompilerSettings
                {
                    AssemblyReferences = references.PathReferences.ToList()
                }, new ConsoleReportPrinter());

                var evaluator = new Evaluator(context);
                var allNamespaces = namespaces.Union(scriptPackSession.Namespaces).Distinct();

                var host = _scriptHostFactory.CreateScriptHost(new ScriptPackManager(scriptPackSession.Contexts), scriptArgs);
                MonoHost.SetHost((ScriptHost)host);

                evaluator.ReferenceAssembly(typeof(MonoHost).Assembly);
                evaluator.InteractiveBaseClass = typeof(MonoHost);

                sessionState = new SessionState<Evaluator>
                {
                    References = new AssemblyReferences(references.PathReferences, references.Assemblies),
                    Namespaces = new HashSet<string>(),
                    Session = evaluator
                };

                ImportNamespaces(allNamespaces, sessionState);

                scriptPackSession.State[SessionKey] = sessionState;
            }
            else
            {
                Logger.Debug("Reusing existing session");
                sessionState = (SessionState<Evaluator>)scriptPackSession.State[SessionKey];

                var newReferences = sessionState.References == null ? references : references.Except(sessionState.References);
                foreach (var reference in newReferences.PathReferences)
                {
                    Logger.DebugFormat("Adding reference to {0}", reference);
                    sessionState.Session.LoadAssembly(reference);
                }

                sessionState.References = new AssemblyReferences(references.PathReferences, references.Assemblies);

                var newNamespaces = sessionState.Namespaces == null ? namespaces : namespaces.Except(sessionState.Namespaces);
                ImportNamespaces(newNamespaces, sessionState);
            }

            Logger.Debug("Starting execution");
            var result = Execute(code, sessionState.Session);
            Logger.Debug("Finished execution");
            return result;
        }
            public void ShouldThrowExceptionThrownByScriptWhenErrorOccurs(
                [NoAutoProperties] RoslynScriptDebuggerEngine 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>());

                // Act
                var exception = Assert.Throws<ScriptExecutionException>(() =>
                    scriptEngine.Execute(
                        code,
                        new string[0],
                        Enumerable.Empty<string>(),
                        Enumerable.Empty<string>(),
                        session));

                // Assert
                exception.Message.ShouldContain("at Submission#0");
                exception.Message.ShouldContain("Exception Message: InvalidOperationExceptionMessage.");
            }
        public ScriptResult Execute(string code, string[] scriptArgs, AssemblyReferences references, IEnumerable<string> namespaces,
            ScriptPackSession scriptPackSession)
        {
            var debugLine = code.Substring(0, code.IndexOf(".lol\"") + 5);
            code = code.Replace(debugLine, string.Empty).TrimStart();

            var compiler = new LOLCodeCodeProvider();
            var cparam = new CompilerParameters
            {
                GenerateInMemory = true,
                MainClass = "Program",
                OutputAssembly = "lolcode.dll"
            };
            cparam.ReferencedAssemblies.AddRange(references.PathReferences != null ? references.PathReferences.ToArray() : new string[0]);
            var results = compiler.CompileAssemblyFromSource(cparam, code);

            var x = results.CompiledAssembly.GetReferencedAssemblies();

            var startupType = results.CompiledAssembly.GetType("Program", true, true);
            var instance = Activator.CreateInstance(startupType, false);
            var entryPoint = results.CompiledAssembly.EntryPoint;

            var result = entryPoint.Invoke(instance, new object[] { });

            return new ScriptResult(result);
        }
Exemplo n.º 5
0
            public void ShouldReturnOnlyLastValueOfVariablesDeclaredManyTimes([NoAutoProperties]RoslynReplEngine engine, ScriptPackSession scriptPackSession)
            {
                var session = new SessionState<Session> { Session = new ScriptEngine().CreateSession() };
                scriptPackSession.State[RoslynScriptEngine.SessionKey] = session;

                engine.Execute("int x = 1;", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(), scriptPackSession);
                engine.Execute("int x = 2;", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(), scriptPackSession);

                engine.GetLocalVariables(scriptPackSession).ShouldEqual(new Collection<string> { "System.Int32 x = 2" });
            }
Exemplo n.º 6
0
            public void ShouldReturnOnlyLastValueOfVariablesDeclaredManyTimes([NoAutoProperties]MonoScriptEngine engine, ScriptPackSession scriptPackSession)
            {
                var session = new SessionState<Evaluator> { Session = new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter())) };
                scriptPackSession.State[MonoScriptEngine.SessionKey] = session;

                engine.Execute("int x = 1;", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(), scriptPackSession);
                engine.Execute("int x = 2;", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(), scriptPackSession);

                engine.GetLocalVariables(scriptPackSession).ShouldEqual(new Collection<string> { "int x = 2" });
            }
        public ScriptResult Execute(string code, string[] scriptArgs, IEnumerable<string> references, IEnumerable<string> namespaces, ScriptPackSession scriptPackSession)
        {
            Guard.AgainstNullArgument("scriptPackSession", scriptPackSession);

            Logger.Debug("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())
                {
                    if (@namespace.Contains("ScriptCs.ReplCommand.Pack")) continue;
                    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.Debug("Starting execution");
            var result = Execute(code, sessionState.Session);
            Logger.Debug("Finished execution");
            return result;
        }
Exemplo n.º 8
0
 public TheInitializeMethod()
 {
     _contextMock1 = new Mock<IScriptPackContext>();
     _contextMock2 = new Mock<IScriptPackContext>();
     _scriptPackMock1 = new Mock<IScriptPack>();
     _scriptPackMock1.Setup(p => p.GetContext()).Returns(_contextMock1.Object);
     _scriptPackMock2 = new Mock<IScriptPack>();
     _scriptPackMock2.Setup(p => p.GetContext()).Returns(_contextMock2.Object);
     _scriptPackSession = new ScriptPackSession(new List<IScriptPack> { _scriptPackMock1.Object, _scriptPackMock2.Object }, new string[0]);
     _scriptPackSession.InitializePacks();
 }
        public static ICollection<string> GetLocalVariables(this IReplEngine replEngine, string sessionKey,
            ScriptPackSession scriptPackSession)
        {
            if (scriptPackSession != null && scriptPackSession.State.ContainsKey(sessionKey))
            {
                var sessionState = (SessionState<ScriptState>)scriptPackSession.State[sessionKey];
                return sessionState.Session.Variables.Select(x => string.Format("{0} {1}", x.Type, x.Name)).ToArray();
            }

            return new string[0];
        }
Exemplo n.º 10
0
            public void ShouldReturnDeclaredVariables([NoAutoProperties]CSharpReplEngine engine, ScriptPackSession scriptPackSession)
            {
                var session = new SessionState<ScriptState> { Session = CSharpScript.Run("") };
                scriptPackSession.State[CommonScriptEngine.SessionKey] = session;

                engine.Execute("int x = 1;", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(),
                    scriptPackSession);
                engine.Execute(@"var y = ""www"";", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(),
                scriptPackSession);

                engine.GetLocalVariables(scriptPackSession).ShouldEqual(new Collection<string> { "System.Int32 x", "System.String y" });
            }
Exemplo n.º 11
0
            public void ShouldReturn0VariablesAfterReset([NoAutoProperties]RoslynReplEngine engine, ScriptPackSession scriptPackSession)
            {
                var session = new SessionState<Session> { Session = new ScriptEngine().CreateSession() };
                scriptPackSession.State[RoslynScriptEngine.SessionKey] = session;

                engine.Execute("int x = 1;", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(),
                    scriptPackSession);
                engine.Execute(@"var y = ""www"";", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(),
                scriptPackSession);

                scriptPackSession.State[RoslynScriptEngine.SessionKey] = new SessionState<Session> { Session = new ScriptEngine().CreateSession() };

                engine.GetLocalVariables(scriptPackSession).ShouldBeEmpty();
            }
Exemplo n.º 12
0
        public ICollection<string> GetLocalVariables(ScriptPackSession scriptPackSession)
        {
            if (scriptPackSession != null && scriptPackSession.State.ContainsKey(SessionKey))
            {
                var sessionState = (SessionState<Evaluator>)scriptPackSession.State[SessionKey];
                var vars = sessionState.Session.GetVars();
                if (!string.IsNullOrWhiteSpace(vars) && vars.Contains(Environment.NewLine))
                {
                    return vars.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                }
            }

            return new Collection<string>();
        }
Exemplo n.º 13
0
            public void ShouldReturn0VariablesAfterReset([NoAutoProperties]MonoScriptEngine engine, ScriptPackSession scriptPackSession)
            {
                var session = new SessionState<Evaluator> { Session = new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter())) };
                scriptPackSession.State[MonoScriptEngine.SessionKey] = session;

                engine.Execute("int x = 1;", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(),
                    scriptPackSession);
                engine.Execute(@"var y = ""www"";", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(),
    scriptPackSession);

                scriptPackSession.State[MonoScriptEngine.SessionKey] = new SessionState<Evaluator> { Session = new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter())) };

                engine.GetLocalVariables(scriptPackSession).ShouldBeEmpty();
            }
Exemplo n.º 14
0
            public void ShouldSetIsCompleteSubmissionToFalseIfCodeIsMissingCurlyBracket(
                [NoAutoProperties] CSharpReplEngine engine, ScriptPackSession scriptPackSession)
            {
                // Arrange
                const string Code = "class test {";

                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.IsCompleteSubmission.ShouldBeFalse();
            }
Exemplo n.º 15
0
            public void ShouldSetIsCompleteSubmissionToFalseIfCodeIsMissingParenthesis(
                [NoAutoProperties] RoslynReplEngine engine,
                ScriptPackSession scriptPackSession)
            {
                // Arrange
                const string Code = "System.Diagnostics.Debug.WriteLine(\"a\"";

                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.IsCompleteSubmission.ShouldBeFalse();
            }
Exemplo n.º 16
0
        public ICollection<string> GetLocalVariables(ScriptPackSession scriptPackSession)
        {
            var variables = new Collection<string>();
            if (scriptPackSession != null && scriptPackSession.State.ContainsKey(SessionKey))
            {
                var sessionState = (SessionState<Session>)scriptPackSession.State[SessionKey];
                var submissionObjectField = sessionState.Session.GetType()
                    .GetField("submissions", BindingFlags.Instance | BindingFlags.NonPublic);

                if (submissionObjectField != null)
                {
                    var submissionObjectFieldValue = submissionObjectField.GetValue(sessionState.Session);
                    if (submissionObjectFieldValue != null)
                    {
                        var submissionObjects = submissionObjectFieldValue as object[];

                        if (submissionObjects != null && submissionObjects.Any(x => x != null))
                        {
                            var processedFields = new Collection<string>();

                            // reversing to get the latest submission first
                            foreach (var submissionObject in submissionObjects.Where(x => x != null).Reverse())
                            {
                                foreach (var field in submissionObject.GetType().GetFields()
                                    .Where(x => x.Name.ToLowerInvariant() != "<host-object>")
                                    .Where(field => !processedFields.Contains(field.Name)))
                                {
                                    var variable = string.Format(
                                        CultureInfo.InvariantCulture,
                                        "{0} {1} = {2}",
                                        field.FieldType,
                                        field.Name,
                                        field.GetValue(submissionObject));

                                    variables.Add(variable);
                                    processedFields.Add(field.Name);
                                }
                            }
                        }
                    }

                }
            }

            return variables;
        }
Exemplo n.º 17
0
            public void ShouldCreateNewSessionIfNotProvided(
                [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)));

                // Act
                engine.Execute(Code, new string[0], new AssemblyReferences(), Enumerable.Empty<string>(), scriptPackSession);

                // Assert
                engine.Session.ShouldNotBeNull();
            }
Exemplo n.º 18
0
            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();
            }
Exemplo n.º 19
0
            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);
            }
Exemplo n.º 20
0
            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 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");
            }
Exemplo n.º 22
0
            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, new ScriptEnvironment(q)));

                scriptPack.Setup(p => p.Initialize(It.IsAny<IScriptPackSession>()));
                scriptPack.Setup(p => p.GetContext()).Returns((IScriptPackContext)null);

                // Act
                engine.Execute(Code, new string[0], new AssemblyReferences(), Enumerable.Empty<string>(), scriptPackSession);

                // Assert
                scriptHostFactory.Verify(f => f.CreateScriptHost(It.IsAny<IScriptPackManager>(), It.IsAny<string[]>()));
            }
Exemplo n.º 23
0
        public void ShouldInitializeScriptLibraryWrapperHost(
            [Frozen] Mock<IScriptHostFactory> scriptHostFactory,
            Mock<IScriptPackManager> manager,
            [NoAutoProperties] RoslynScriptEngine 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 ShouldExposeExceptionThrownByCompilation()
            {
                var scriptEngine = new CSharpScriptInMemoryEngine(new ScriptHostFactory(), 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 ShouldExposeExceptionThrownByScriptWhenErrorOccurs()
            {
                var scriptEngine = new RoslynScriptInMemoryEngine(new ScriptHostFactory(), 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");
            }
Exemplo n.º 26
0
        public void ShouldCompileWhenUsingClassesFromAPassedAssemblyInstance(
            [Frozen] Mock<IScriptHostFactory> scriptHostFactory,
            [NoAutoProperties] RoslynScriptEngine engine,
            ScriptPackSession scriptPackSession)
        {
            // Arrange
            const string Code = "var x = new ScriptCs.Tests.TestMarkerClass();";

            scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny<IScriptPackManager>(), It.IsAny<string[]>()))
                .Returns<IScriptPackManager, ScriptEnvironment>((p, q) => new ScriptHost(p, q));

            var session = new SessionState<Session> { Session = new ScriptEngine().CreateSession() };
            scriptPackSession.State[RoslynScriptEngine.SessionKey] = session;
            var refs = new AssemblyReferences(new[] { Assembly.GetExecutingAssembly() }, new[] { "System" });

            // Act
            var result = engine.Execute(Code, new string[0], refs, Enumerable.Empty<string>(), scriptPackSession);

            // Assert
            result.CompileExceptionInfo.ShouldBeNull();
            result.ExecuteExceptionInfo.ShouldBeNull();
        }
        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();
        }
Exemplo n.º 28
0
            public void ShouldCreateScriptHostWithContexts()
            {
                var fileSystem = new Mock<IFileSystem>();
                fileSystem.Setup(f => f.GetWorkingDirectory(It.IsAny<string>())).Returns(@"c:\my_script");
                fileSystem.Setup(f => f.CurrentDirectory).Returns(@"c:\my_script");

                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>()));
            }
Exemplo n.º 29
0
            public void ShouldCreateNewSessionIfNotProvided()
            {
                var scriptHostFactory = new Mock<IScriptHostFactory>();
                scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny<IScriptPackManager>(), It.IsAny<string[]>())).Returns((IScriptPackManager p, string[] q) => new ScriptHost(p, q));

                var code = "var a = 0;";

                var engine = CreateTestScriptEngine(scriptHostFactory: scriptHostFactory);
                var scriptPackSession = new ScriptPackSession(new List<IScriptPack>());
                engine.Execute(code, new string[0], Enumerable.Empty<string>(), Enumerable.Empty<string>(), scriptPackSession);
                engine.Session.ShouldNotBeNull();
            }
Exemplo n.º 30
0
            public void ShouldAddNewReferencesIfTheyAreProvided()
            {
                var scriptHostFactory = new Mock<IScriptHostFactory>();
                scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny<IScriptPackManager>(), It.IsAny<string[]>())).Returns((IScriptPackManager p, string[] q) => new ScriptHost(p, q));

                var code = "var a = 0;";

                var engine = CreateTestScriptEngine(scriptHostFactory: scriptHostFactory);
                var scriptPackSession = new ScriptPackSession(new List<IScriptPack>());
                var roslynEngine = new ScriptEngine();
                var session = new SessionState<Session> { Session = roslynEngine.CreateSession()};
                scriptPackSession.State[RoslynScriptEngine.SessionKey] = session;
                engine.Execute(code, new string[0], new[] {"System"}, Enumerable.Empty<string>(), scriptPackSession);

                ((SessionState<Session>)scriptPackSession.State[RoslynScriptEngine.SessionKey]).References.Count().ShouldEqual(1);
            }