Last active
August 29, 2015 14:18
-
-
Save bitbonk/9cf6169a4163449573a1 to your computer and use it in GitHub Desktop.
Debugging dynmically created scriptcs source code string in a hosted environment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace DebugStringConsoleHosted | |
{ | |
using System.IO; | |
using System.Linq; | |
using Common.Logging.Simple; | |
using ScriptCs.Contracts; | |
using ScriptCs.Engine.Roslyn; | |
using ScriptCs.Hosting; | |
internal class Program | |
{ | |
// The string we want to debug comes form the args, but it could of course | |
// as well come form a textbox of an app with a GUI. | |
// Example args: | |
// "for (var i = 0; i < 10; i++) { System.Console.WriteLine(i); System.Threading.Thread.Sleep(1000); }" | |
private static void Main(string[] args) | |
{ | |
var scriptcs = new ScriptServicesBuilder(new ScriptConsole(), new NoOpLogger()) | |
.Debug() | |
// We have to explictly set the RoslynScriptInMemoryEngine, so PDBs get created. | |
.ScriptEngine<RoslynScriptInMemoryEngine>() | |
.Build(); | |
// Read the oneliner from the args as a singe string. | |
var script = args[0].Trim('"', ' '); | |
// Prepend a "breakpoint" so visual studio will switch to that file. | |
// Debugger.Break() crashes the application if VS is not already attached, | |
// so we use Debugger.Launch() instead. | |
script = "System.Diagnostics.Debugger.Launch();\r\n" + script; | |
// Write that script string to a file so visual studio can pick it up. | |
var scriptFile = Path.GetTempFileName(); | |
using (var w = new StreamWriter(scriptFile)) | |
{ | |
w.WriteLine(script); | |
} | |
scriptcs.Executor.Initialize(Enumerable.Empty<string>(), Enumerable.Empty<IScriptPack>()); | |
// Eecute that file. | |
// If we break execution with the dubgger while the script is executing, | |
// we will see the source code of the script that was passed as the argument. | |
scriptcs.Executor.Execute(scriptFile); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment