Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debug script code that is being executed with Roslyn CSharpScript

Tags:

roslyn

I created this test console application to run some C# code with the Roslyn scripting engine (in the Microsoft.CodeAnalysis.CSharp.Scripting nuget package).

     string code = "int test = 123;\r\nConsole.WriteLine(\"hello, world!\");";
     var options = ScriptOptions.Default.WithImports("System");
     var script = CSharpScript.Create(code, options);
     await script.RunAsync();

This works, but now I would also like the option of somehow debugging into the script that is being executed. Is there a way to do that?

like image 359
Wim Coenen Avatar asked Jun 26 '18 13:06

Wim Coenen


1 Answers

Figured out a way to do it by writing the code to a temporary file, and adding debugging information pointing to that file. Then I can step into the RunAsync call, and visual studio will load the temporary file, show an execution pointer, and will let me inspect variables.

using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using System;
using System.IO;
using System.Text;

namespace RoslynScriptingTest
{
   class Program
   {
      static async Task Main(string[] args)
      {
         string code = "int test = 123;\r\nConsole.WriteLine(\"hello, world!\");";
         string tmpFile = Path.GetTempFileName();
         var encoding = Encoding.UTF8;
         File.WriteAllText(tmpFile, code, encoding);
         try
         {
            var options = ScriptOptions.Default
               .WithImports("System")
               .WithEmitDebugInformation(true)
               .WithFilePath(tmpFile)
               .WithFileEncoding(encoding);
            var script = CSharpScript.Create(code, options);
            await script.RunAsync();   
         }
         finally
         {
            File.Delete(tmpFile);
         }
         Console.ReadKey();
      }
   }
}

The debugging only seems to work when "just my code" is enabled in the visual studio debugger settings.

In my actual use case, I'm actually loading the code from an XML file, so it would be better if I could point to that original file and map the line numbers somehow. But this is already a good start.

like image 197
Wim Coenen Avatar answered Nov 07 '22 15:11

Wim Coenen