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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With