Answer the question
In order to leave comments, you need to log in
How to implement inline code debugging in C#?
Good afternoon!
I have a code (c#) that I generate dynamically. For example, the following code was generated:
NetOffice.ExcelApi.Application excel = new NetOffice.ExcelApi.Application();
excel.Visible = true;
excel.Workbooks.Open(@"C:\mail.xml");
while (true)
{
System.Threading.Thread.Sleep(5 * 1000);
break;
}
Answer the question
In order to leave comments, you need to log in
Kirill Serov , this is one of the reasons why you should not engage in metaprogramming unless it is absolutely necessary. Actually, you don’t really have any options, or pile up a test bench, which, at the moment of transition to the execution of your generated text, will stop the program, throw your code into a file, you will load it into the debugger, initialize all variables and objects, and debug.
Second, since you're integrating with Excel, consider VBA as your scripting language.
The third is file input-output and step-by-step logging at the moment of execution of your code with all the information you are interested in.
And again, consider refusing to generate compiled code, use at least any scripting language (vbs, js, ps1, python, etc.).
Actually, nothing complicated. You just need to tell the script to generate DebugInformation and specify the path to a temporary file with the source code (the studio cannot debug sources from memory).
Here is an example:
class Program
{
static void Main(string[] args)
{
string scriptFileName = Path.GetTempFileName() + ".cs";
var scriptBody = GenerateScript(scriptFileName);
var script = CSharpScript.Create(
scriptBody,
globalsType: typeof(Globals),
options: ScriptOptions
.Default
.WithEmitDebugInformation(true)
.WithFilePath(scriptFileName)
.WithFileEncoding(Encoding.UTF8));
var sum = script.RunAsync(new Globals {X = 56, Y = 42}).Result.ReturnValue;
Console.Out.WriteLine(sum);
Console.ReadKey();
File.Delete(scriptFileName);
}
private static string GenerateScript(string fileName)
{
var body =
@"var result = X + Y;
return result;
";
File.WriteAllText(fileName, body, Encoding.UTF8);
return body;
}
}
public class Globals
{
public int X { get; set; }
public int Y { get; set; }
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question