private void CustomStartup()
 {
     // Execute a basic script to load roslyn successfully.
     var result = CSharpScript.EvaluateAsync <int>("1 + 2").Result;
 }
Beispiel #2
0
        public async Task <DiscordCommandResult> EvalAsync([Remainder] string code = null)
        {
            if (code == null)
            {
                var messageRef = Context.Message.ReferencedMessage.GetValueOrDefault();
                if (messageRef is not null)
                {
                    code = messageRef.Content;
                }
                else
                {
                    return(Response("More code needed, sir."));
                }
            }
            code = EvalUtils.ValidateCode(code);
            var scriptOptions = ScriptOptions.Default
                                .WithImports(EvalUtils.EvalNamespaces)
                                .WithReferences(AppDomain.CurrentDomain.GetAssemblies().Where(x => !x.IsDynamic && !string.IsNullOrWhiteSpace(x.Location)));

            var script = CSharpScript.Create(code, scriptOptions, Context is DiscordGuildCommandContext ? typeof(EvalGuildGlobals) : typeof(EvalGlobals));

            try
            {
                using (Context.Bot.BeginTyping(Context.ChannelId))
                {
                    var stopwatch   = Stopwatch.StartNew();
                    var diagnostics = script.Compile();
                    stopwatch.Stop();
                    if (diagnostics.Any(x => x.Severity == DiagnosticSeverity.Error))
                    {
                        var e = new LocalEmbed()
                                .WithTitle("Compilation Failure")
                                .WithDescription($"{diagnostics.Length} {(diagnostics.Length > 1 ? "errors" : "error")}")
                                .WithColor(Color.Red)
                                .WithFooter($"{stopwatch.Elapsed.TotalMilliseconds}ms");
                        for (var i = 0; i < diagnostics.Length; i++)
                        {
                            if (i > 3)
                            {
                                break;
                            }
                            var diagnostic = diagnostics[i];
                            var lineSpan   = diagnostic.Location.GetLineSpan().Span;
                            e.AddField($"Error `{diagnostic.Id}` at {lineSpan.Start} - {lineSpan.End}", diagnostic.GetMessage());
                        }

                        if (diagnostics.Length > 4)
                        {
                            e.AddField($"Skipped {diagnostics.Length - 4} {(diagnostics.Length - 4 > 1 ? "errors" : "error")}", "You should be able to fix it.");
                        }
                        return(Response(e));
                    }
                    var globals = Context is DiscordGuildCommandContext guildContext ? new EvalGuildGlobals(guildContext) : new EvalGlobals(Context);
                    var state   = await script.RunAsync(globals, _ => true);

                    if (state.Exception != null)
                    {
                        var e = new LocalEmbed()
                                .WithTitle("Execution Failure")
                                .WithDescription(state.Exception.ToString().SplitInParts(LocalEmbed.MaxDescriptionLength).First())
                                .WithColor(Color.Red)
                                .WithFooter($"{stopwatch.Elapsed.TotalMilliseconds}ms");
                        return(Response(e));
                    }

                    switch (state.ReturnValue)
                    {
                    case null:
                    case string value when string.IsNullOrWhiteSpace(value):
                        return(Reaction(new LocalEmoji("✅")));

                    case DiscordCommandResult commandResult:
                        return(commandResult);

                    default:
                        return(Response(state.ReturnValue.ToString()));
                    }
                }
            }
            catch (Exception ex)
            {
                Context.Bot.Logger.LogError(ex, "An unexpected exception occurred when evaluating code.");
                return(Response($"An unexpected exception occurred: {ex.Message}."));
            }
        }
 public abstract void Handle(CSharpScript script);
 public Task <object> Evaluate([FromBody] ExpressionModel expressionModel)
 {
     return(CSharpScript.EvaluateAsync(expressionModel.Expression));
 }
        public async Task SharedLibCopy_DifferentVersion_Strong()
        {
            string libBaseName = "LibBase_" + Guid.NewGuid();
            string lib1Name    = "Lib1_" + Guid.NewGuid();
            string lib2Name    = "Lib2_" + Guid.NewGuid();

            var libBase1 = CreateCSharpCompilation(@"
[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")]
public class LibBase
{
    public readonly int X = 1;
}
", new[] { Net451.mscorlib }, libBaseName, s_signedDll);

            var libBase2 = CreateCSharpCompilation(@"
[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")]
public class LibBase
{
    public readonly int X = 2;
}
", new[] { Net451.mscorlib }, libBaseName, s_signedDll);

            var lib1 = CreateCSharpCompilation(@"
public class Lib1
{
    public LibBase libBase = new LibBase();
}
", new MetadataReference[] { Net451.mscorlib, libBase1.ToMetadataReference() }, lib1Name);

            var lib2 = CreateCSharpCompilation(@"
public class Lib2
{
    public LibBase libBase = new LibBase();
}
", new MetadataReference[] { Net451.mscorlib, libBase2.ToMetadataReference() }, lib2Name);

            var libBase1Image = libBase1.EmitToArray();
            var libBase2Image = libBase2.EmitToArray();
            var lib1Image     = lib1.EmitToArray();
            var lib2Image     = lib2.EmitToArray();

            var root      = Temp.CreateDirectory();
            var dir1      = root.CreateDirectory("1");
            var file1     = dir1.CreateFile(lib1Name + ".dll").WriteAllBytes(lib1Image);
            var fileBase1 = dir1.CreateFile(libBaseName + ".dll").WriteAllBytes(libBase1Image);

            var dir2      = root.CreateDirectory("2");
            var file2     = dir2.CreateFile(lib2Name + ".dll").WriteAllBytes(lib2Image);
            var fileBase2 = dir2.CreateFile(libBaseName + ".dll").WriteAllBytes(libBase2Image);

            var s0 = await CSharpScript.RunAsync($@"#r ""{file1.Path}""");

            var s1 = await s0.ContinueWithAsync($@"new Lib1().libBase.X");

            Assert.Equal(1, s1.ReturnValue);
            var s2 = await s1.ContinueWithAsync($@"#r ""{file2.Path}""");

            var s3 = await s2.ContinueWithAsync($@"new Lib2().libBase.X");

            Assert.Equal(2, s3.ReturnValue);
        }
        public async Task SharedLibCopy_Identical_Strong()
        {
            string libBaseName = "LibBase_" + Guid.NewGuid();
            string lib1Name    = "Lib1_" + Guid.NewGuid();
            string lib2Name    = "Lib2_" + Guid.NewGuid();

            var libBase = CreateCSharpCompilation(@"
public class LibBase
{
    public readonly int X = 1;
}
", new[] { Net451.mscorlib }, libBaseName, s_signedDll);

            var lib1 = CreateCSharpCompilation(@"
public class Lib1
{
    public LibBase libBase = new LibBase();
}
", new MetadataReference[] { Net451.mscorlib, libBase.ToMetadataReference() }, lib1Name);

            var lib2 = CreateCSharpCompilation(@"
public class Lib2
{
    public LibBase libBase = new LibBase();
}
", new MetadataReference[] { Net451.mscorlib, libBase.ToMetadataReference() }, lib2Name);

            var libBaseImage = libBase.EmitToArray();
            var lib1Image    = lib1.EmitToArray();
            var lib2Image    = lib2.EmitToArray();

            var root      = Temp.CreateDirectory();
            var dir1      = root.CreateDirectory("1");
            var file1     = dir1.CreateFile(lib1Name + ".dll").WriteAllBytes(lib1Image);
            var fileBase1 = dir1.CreateFile(libBaseName + ".dll").WriteAllBytes(libBaseImage);

            var dir2      = root.CreateDirectory("2");
            var file2     = dir2.CreateFile(lib2Name + ".dll").WriteAllBytes(lib2Image);
            var fileBase2 = dir2.CreateFile(libBaseName + ".dll").WriteAllBytes(libBaseImage);

            var s0 = await CSharpScript.RunAsync($@"#r ""{file1.Path}""");

            var s1 = await s0.ContinueWithAsync($@"var l1 = new Lib1();");

            var s2 = await s1.ContinueWithAsync($@"#r ""{file2.Path}""");

            var s3 = await s2.ContinueWithAsync($@"var l2 = new Lib2();");

            var s4 = await s3.ContinueWithAsync($@"l2.libBase.X");

            var c4 = s4.Script.GetCompilation();

            c4.VerifyAssemblyAliases(
                lib2Name,
                lib1Name,
                "mscorlib",
                libBaseName + ": <implicit>,global");

            var libBaseRefAndSymbol = c4.GetBoundReferenceManager().GetReferencedAssemblies().ToArray()[3];

            Assert.Equal(fileBase1.Path, ((PortableExecutableReference)libBaseRefAndSymbol.Key).FilePath);
        }
 public override Script <T> CreateScript <T>(string code, ScriptOptions options, Type globalsTypeOpt, InteractiveAssemblyLoader assemblyLoader)
 {
     return(CSharpScript.Create <T>(code, options, globalsTypeOpt, assemblyLoader));
 }
Beispiel #8
0
 public void TestEvalScript()
 {
     var value = CSharpScript.Eval("1 + 2");
     Assert.Equal(3, value);
 }
Beispiel #9
0
        public async Task EvalCs(CommandContext ctx, [RemainingText] string code)
        {
            /////////////////////////////////////////////////////////////
            //Code provided by i forgot                               ///
            // If you are the owner the of the code below please pm at///
            // - ̗̀Hera ̖́-#0002 on discord                               ///
            /////////////////////////////////////////////////////////////

            DiscordMessage msg;

            var cs1 = code.IndexOf("```", StringComparison.Ordinal) + 3;

            cs1 = code.IndexOf('\n', cs1) + 1;
            var cs2 = code.LastIndexOf("```", StringComparison.Ordinal);

            if (cs1 == -1 || cs2 == -1)
            {
                var erorr = new DiscordEmbedBuilder()
                            .WithColor(new DiscordColor(0xF4FF81))
                            .WithDescription("`You need to wrap the code into a code block. ```codehere ```  `");

                await ctx.RespondAsync(embed : erorr);

                throw new ArgumentException("You need to wrap the code into a code block.");
            }

            var cs = code.Substring(cs1, cs2 - cs1);

            msg = await ctx.RespondAsync("", embed : new DiscordEmbedBuilder()
                                         .WithColor(new DiscordColor(0xCCFF90))
                                         .WithDescription("Evaluating...")
                                         .Build()).ConfigureAwait(false);

            try
            {
                var globals = new TestVariables(ctx.Message, ctx.Client, ctx);

                var sopts = ScriptOptions.Default;
                sopts = sopts.WithImports("System", "System.Collections.Generic", "System.Linq", "System.Net.Http",
                                          "System.Net.Http.Headers", "System.Reflection", "System.Text", "System.Threading.Tasks",
                                          "DSharpPlus", "DSharpPlus.CommandsNext", "DSharpPlus.Interactivity");
                sopts = sopts.WithReferences(AppDomain.CurrentDomain.GetAssemblies()
                                             .Where(xa => !xa.IsDynamic && !string.IsNullOrWhiteSpace(xa.Location)));

                var script = CSharpScript.Create(cs, sopts, typeof(TestVariables));
                script.Compile();
                var result = await script.RunAsync(globals).ConfigureAwait(false);

                if (result != null && result.ReturnValue != null &&
                    !string.IsNullOrWhiteSpace(result.ReturnValue.ToString()))
                {
                    var results = new DiscordEmbedBuilder()
                                  .WithTitle($"{ctx.Member.Username}: Result")
                                  .AddField("Results", $"{result.ReturnValue}")
                                  .AddField("Return Type", $"{result.ReturnValue.GetType()}")
                                  .WithColor(new DiscordColor(0xB9F6CA));
                    await msg.ModifyAsync(embed : new DSharpPlus.Entities.Optional <DiscordEmbed>(results))
                    .ConfigureAwait(false);
                }

                else
                {
                    var successful = new DiscordEmbedBuilder()
                                     .WithTitle($"{ctx.Member.Username}: Successful")
                                     .AddField("Results = False",
                                               $"No result was returned. To have a results please make sure you use `return`")
                                     .WithColor(new DiscordColor(0xB9F6CA));
                    await msg.ModifyAsync(embed : new DSharpPlus.Entities.Optional <DiscordEmbed>(successful))
                    .ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                var failure = new DiscordEmbedBuilder()
                              .WithTitle($"{ctx.Member.Username}: Failure")
                              .AddField($"{ex.GetType()}", $"**{ex.Message}**")
                              .WithColor(new DiscordColor(0xFF8A80));

                await msg.ModifyAsync(embed : new DSharpPlus.Entities.Optional <DiscordEmbed>(failure))
                .ConfigureAwait(false);
            }
        }
Beispiel #10
0
        public static async Task <ApplicationWrapper?> RunCustomizationScriptAsync(OutputContext output, FileInfo solutionFile, SolutionFile solution)
        {
            if (output is null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            if (solutionFile is null)
            {
                throw new ArgumentNullException(nameof(solutionFile));
            }

            if (solution is null)
            {
                throw new ArgumentNullException(nameof(solution));
            }

            using (var step = output.BeginStep("Applying Application Customizations..."))
            {
                var scriptFilePath = Path.Combine(solutionFile.DirectoryName, "Opulence.csx");
                output.WriteDebugLine($"Looking for customization script at '{scriptFilePath}'.");
                if (!File.Exists(scriptFilePath))
                {
                    output.WriteDebugLine($"No customization script found.");
                    step.MarkComplete("Skipping...");
                    return(null);
                }

                output.WriteInfoLine($"Configuring application using '{Path.GetFileName(scriptFilePath)}'.");

                var code   = File.ReadAllText(scriptFilePath);
                var script = CSharpScript.Create <object>(
                    code,
                    options: ScriptOptions.Default.WithImports(new [] { "System", "System.Collections.Generic", }),
                    globalsType: typeof(PipelineHolder),
                    assemblyLoader: null);
                script = script.ContinueWith <object>(@"return await Pipeline.ExecuteAsync(__Pipeline);", options: ScriptOptions.Default);

                output.WriteDebugLine($"Compiling {Path.GetFileName(scriptFilePath)}'.");
                script.Compile();
                var diagnostics = script.Compile();
                if (diagnostics.Length > 0)
                {
                    var builder = new StringBuilder();
                    output.WriteDebugLine($"Script '{scriptFilePath}' had compilation errors.");
                    builder.AppendLine($"Script '{scriptFilePath}' had compilation errors.");
                    foreach (var diagnostic in diagnostics)
                    {
                        output.WriteDebugLine(CSharpDiagnosticFormatter.Instance.Format(diagnostic));
                        builder.AppendLine(CSharpDiagnosticFormatter.Instance.Format(diagnostic));
                    }

                    throw new CommandException(builder.ToString());
                }
                output.WriteDebugLine($"Done compiling {Path.GetFileName(scriptFilePath)}'.");

                var pipeline = new CustomizationPipeline(
                    output,
                    rootDirectory: Path.GetDirectoryName(scriptFilePath) !,
                    name: Names.NormalizeToDns(Path.GetFileNameWithoutExtension(solutionFile.Name)),
                    solution,
                    projectFile: null);
                var holder = new PipelineHolder(pipeline);

                output.WriteDebugLine($"Running {Path.GetFileName(scriptFilePath)}'.");
                object obj;
                try
                {
                    var result = await script.RunAsync(holder);

                    obj = result.ReturnValue;
                }
                catch (Exception ex)
                {
                    throw new CommandException($"Failed executing {Path.GetFileName(scriptFilePath)}'.", ex);
                }

                step.MarkComplete();
                return(new ApplicationWrapper(obj, Path.GetDirectoryName(scriptFilePath) !));
            }
        }
 public void RunNonExistingExpressionNumber_Failure()
 {
     using (var expression = new CSharpScript())
         expression.Execute(2);
 }
 public void ExpressionWithSyntaxError_Failure()
 {
     using (var expression = new CSharpScript("1 + obj.int_Field"))
         expression.Compile();
 }
 public void BasicExpression_Success()
 {
     using (var expression = new CSharpScript("1 + 1"))
         Assert.AreEqual(2, expression.Execute());
 }
 private Task CompileAndRunAsync(string sourceCode)
 {
     Assert.Equal(0, stringList.Count);
     return(CSharpScript.RunAsync(sourceCode, globals: this));
 }
Beispiel #15
0
 public void TestCreateScript_CodeIsNull()
 {
     Assert.Throws <ArgumentNullException>(() => CSharpScript.Create((string)null));
 }
Beispiel #16
0
 public void TestCreateScript()
 {
     var script = CSharpScript.Create("1 + 2");
     Assert.Equal("1 + 2", script.Code);
 }
Beispiel #17
0
        public void TestCreateFromStreamScript()
        {
            var script = CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("1 + 2")));

            Assert.Equal("1 + 2", script.Code);
        }
Beispiel #18
0
 public void TestGetCompilation()
 {
     var script = CSharpScript.Create("1 + 2");
     var compilation = script.GetCompilation();
     Assert.Equal(script.Code, compilation.SyntaxTrees.First().GetText().ToString());
 }
Beispiel #19
0
 public void TestCreateFromStreamScript_StreamIsNull()
 {
     Assert.Throws <ArgumentNullException>(() => CSharpScript.Create((Stream)null));
 }
        public void References_Versioning_FxUnification2()
        {
            if (!s_isSystemV2AndV4Available.Value)
            {
                return;
            }

            var script0 = CSharpScript.Create($@"
#r ""System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089""
");
            var script1 = script0.ContinueWith($@"
#r ""System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089""
");
            var script2 = script1.ContinueWith(@"
System.Diagnostics.Process.GetCurrentProcess()
");

            script0.GetCompilation().VerifyAssemblyVersionsAndAliases(
                "System, Version=2.0.0.0",
                "mscorlib, Version=4.0.0.0",
                "System.Configuration, Version=2.0.0.0: <implicit>,global",
                "System.Xml, Version=2.0.0.0: <implicit>,global",
                "System.Data.SqlXml, Version=2.0.0.0: <implicit>,global",
                "System.Security, Version=2.0.0.0: <implicit>,global");

            // TODO (https://github.com/dotnet/roslyn/issues/6456):
            // This is not correct. "global" alias should be recursively applied on all
            // dependencies of System, V4. The problem is in ResolveReferencedAssembly which considers
            // System, V2 equivalent to System, V4 and immediately returns, instead of checking if a better match exists.
            // This is not a problem in csc since it can't have both System, V2 and System, V4 among definitions.
            script1.GetCompilation().VerifyAssemblyVersionsAndAliases(
                "System, Version=4.0.0.0",
                "System, Version=2.0.0.0: <superseded>",
                "mscorlib, Version=4.0.0.0",
                "System.Configuration, Version=2.0.0.0: <superseded>",
                "System.Xml, Version=2.0.0.0: <superseded>",
                "System.Data.SqlXml, Version=2.0.0.0: <superseded>",
                "System.Security, Version=2.0.0.0: <superseded>",
                "System.Configuration, Version=4.0.0.0: <implicit>",
                "System.Xml, Version=4.0.0.0: <implicit>",
                "System.Data.SqlXml, Version=4.0.0.0: <implicit>",
                "System.Security, Version=4.0.0.0: <implicit>",
                "System.Core, Version=4.0.0.0: <implicit>",
                "System.Numerics, Version=4.0.0.0: <implicit>");

            // TODO (https://github.com/dotnet/roslyn/issues/6456):
            // "global" alias should be recursively applied on all
            script2.GetCompilation().VerifyAssemblyVersionsAndAliases(
                "System, Version=4.0.0.0",
                "System, Version=2.0.0.0: <superseded>",
                "mscorlib, Version=4.0.0.0",
                "System.Configuration, Version=2.0.0.0: <superseded>",
                "System.Xml, Version=2.0.0.0: <superseded>",
                "System.Data.SqlXml, Version=2.0.0.0: <superseded>",
                "System.Security, Version=2.0.0.0: <superseded>",
                "System.Configuration, Version=4.0.0.0: <implicit>",
                "System.Xml, Version=4.0.0.0: <implicit>",
                "System.Data.SqlXml, Version=4.0.0.0: <implicit>",
                "System.Security, Version=4.0.0.0: <implicit>",
                "System.Core, Version=4.0.0.0: <implicit>",
                "System.Numerics, Version=4.0.0.0: <implicit>");

            Assert.NotNull(script2.EvaluateAsync().Result);
        }
Beispiel #21
0
        public async Task <object> EvalExpressionTask(string expression)
        {
            var rc = await CSharpScript.EvaluateAsync(expression);

            return(rc);
        }
        public async Task SharedLibCopy_SameVersion_StrongDifferentPKT_DifferentContent()
        {
            string libBaseName = "LibBase_" + Guid.NewGuid();
            string lib1Name    = "Lib1_" + Guid.NewGuid();
            string lib2Name    = "Lib2_" + Guid.NewGuid();

            var libBase1 = CreateCSharpCompilation(@"
[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")]
public class LibBase
{
    public readonly int X = 1;
}
", new[] { Net451.mscorlib }, libBaseName, s_signedDll);

            var libBase2 = CreateCSharpCompilation(@"
[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")]
public class LibBase
{
    public readonly int X = 2;
}
", new[] { Net451.mscorlib }, libBaseName, s_signedDll2);

            var lib1 = CreateCSharpCompilation(@"
public class Lib1
{
    public LibBase libBase = new LibBase();
}
", new MetadataReference[] { Net451.mscorlib, libBase1.ToMetadataReference() }, lib1Name);

            var lib2 = CreateCSharpCompilation(@"
public class Lib2
{
    public LibBase libBase = new LibBase();
}
", new MetadataReference[] { Net451.mscorlib, libBase1.ToMetadataReference() }, lib2Name);

            var libBase1Image = libBase1.EmitToArray();
            var libBase2Image = libBase2.EmitToArray();
            var lib1Image     = lib1.EmitToArray();
            var lib2Image     = lib2.EmitToArray();

            var root      = Temp.CreateDirectory();
            var dir1      = root.CreateDirectory("1");
            var file1     = dir1.CreateFile(lib1Name + ".dll").WriteAllBytes(lib1Image);
            var fileBase1 = dir1.CreateFile(libBaseName + ".dll").WriteAllBytes(libBase1Image);

            var dir2      = root.CreateDirectory("2");
            var file2     = dir2.CreateFile(lib2Name + ".dll").WriteAllBytes(lib2Image);
            var fileBase2 = dir2.CreateFile(libBaseName + ".dll").WriteAllBytes(libBase2Image);

            var s0 = await CSharpScript.RunAsync($@"#r ""{file1.Path}""");

            var s1 = await s0.ContinueWithAsync($@"new Lib1().libBase.X");

            var s2 = await s1.ContinueWithAsync($@"#r ""{file2.Path}""");

            bool exceptionSeen = false;

            try
            {
                await s2.ContinueWithAsync($@"new Lib2().libBase.X");
            }
            catch (FileLoadException fileLoadEx) when(fileLoadEx.InnerException is InteractiveAssemblyLoaderException)
            {
                exceptionSeen = true;
            }

            Assert.True(exceptionSeen);
        }
Beispiel #23
0
 public void TestRunScript()
 {
     var result = CSharpScript.Run("1 + 2");
     Assert.Equal(3, result.ReturnValue);
 }
        async Task interpret(string statement)
        {
            object result = await CSharpScript.EvaluateAsync(statement);

            logger.WriteLine($"eval result({result.ToString()})");
        }
Beispiel #25
0
 public void TestRunScriptWithGlobals()
 {
     var result = CSharpScript.Run("X + Y", new Globals { X = 1, Y = 2 });
     Assert.Equal(3, result.ReturnValue);
 }
Beispiel #26
0
 public Roslyn(string code)
 {
     _code   = code;
     _script = CSharpScript.Create <int>(code, ScriptOptions.Default);
     _runner = _script.CreateDelegate();
 }
Beispiel #27
0
 public void TestRunScriptWithSpecifiedReturnType()
 {
     var result = CSharpScript.Create("1 + 2").WithReturnType(typeof(int)).Run();
     Assert.Equal(3, result.ReturnValue);
 }
Beispiel #28
0
        private async Task HandleSubmitCode(
            SubmitCode submitCode,
            KernelInvocationContext context)
        {
            CancellationTokenSource cancellationSource;

            lock (_cancellationSourceLock)
            {
                cancellationSource = _cancellationSource;
            }

            var codeSubmissionReceived = new CodeSubmissionReceived(submitCode);

            context.Publish(codeSubmissionReceived);

            var code       = submitCode.Code;
            var isComplete = await IsCompleteSubmissionAsync(submitCode.Code);

            if (isComplete)
            {
                context.Publish(new CompleteCodeSubmissionReceived(submitCode));
            }
            else
            {
                context.Publish(new IncompleteCodeSubmissionReceived(submitCode));
            }

            if (submitCode.SubmissionType == SubmissionType.Diagnose)
            {
                return;
            }

            Exception exception = null;

            using var console = await ConsoleOutput.Capture();

            using (console.SubscribeToStandardOutput(std => PublishOutput(std, context, submitCode)))
                using (console.SubscribeToStandardError(std => PublishError(std, context, submitCode)))
                {
                    if (!cancellationSource.IsCancellationRequested)
                    {
                        ScriptOptions = ScriptOptions.WithMetadataResolver(
                            ScriptMetadataResolver.Default.WithBaseDirectory(
                                Directory.GetCurrentDirectory()));

                        try
                        {
                            if (ScriptState == null)
                            {
                                ScriptState = await CSharpScript.RunAsync(
                                    code,
                                    ScriptOptions,
                                    cancellationToken : cancellationSource.Token)
                                              .UntilCancelled(cancellationSource.Token);
                            }
                            else
                            {
                                ScriptState = await ScriptState.ContinueWithAsync(
                                    code,
                                    ScriptOptions,
                                    catchException : e =>
                                {
                                    exception = e;
                                    return(true);
                                },
                                    cancellationToken : cancellationSource.Token)
                                              .UntilCancelled(cancellationSource.Token);
                            }
                        }
                        catch (CompilationErrorException cpe)
                        {
                            exception = new CodeSubmissionCompilationErrorException(cpe);
                        }
                        catch (Exception e)
                        {
                            exception = e;
                        }
                    }
                }

            if (!cancellationSource.IsCancellationRequested)
            {
                if (exception != null)
                {
                    string message = null;

                    if (exception is CodeSubmissionCompilationErrorException compilationError)
                    {
                        message =
                            string.Join(Environment.NewLine,
                                        (compilationError.InnerException as CompilationErrorException)?.Diagnostics.Select(d => d.ToString()) ?? Enumerable.Empty <string>());
                    }

                    context.Fail(exception, message);
                }
                else
                {
                    if (ScriptState != null && HasReturnValue)
                    {
                        var formattedValues = FormattedValue.FromObject(ScriptState.ReturnValue);
                        context.Publish(
                            new ReturnValueProduced(
                                ScriptState.ReturnValue,
                                submitCode,
                                formattedValues));
                    }
                }
            }
            else
            {
                context.Fail(null, "Command cancelled");
            }
        }
Beispiel #29
0
 public void TestRunVoidScript()
 {
     var result = CSharpScript.Run("Console.WriteLine(0);");
 }
Beispiel #30
0
 protected override Script <T> Create <T>(string code, ScriptOptions options, Type globalsType, InteractiveAssemblyLoader assemblyLoader) =>
 CSharpScript.Create <T>(code, options, globalsType, assemblyLoader);
Beispiel #31
0
 static void cSharpScriptCompiler_WarningOccured( object sender, CSharpScript.NotificationDetails e )
 {
     Console.WriteLine( e.ToString() );
 }