Using Roslyn to build a simple C # interactive script engine,
(This article is also published in my public account "dotNET daily excellent article". Welcome to the QR code on the right to follow it .)
Microsoft's next-generation compiler technology, Roslyn, is a milestone technology that can bring unlimited imagination to the. NET platform. As mentioned in the recommendation article today, develop an interactive Script Engine for C.
Roslyn (that is. NET Compiler Platform) is a Microsoft open-source C # and Visual Basic Compiler. It contains a wide range of code analysis APIs, allowing you to build code analysis tools using familiar languages and tools.
With the release of VS 2015 RC, Roslyn also enters Go Live (that is, the function has been frozen, and some bugs will be fixed ), then we can start to apply it to some actual products. In the article recommended today, Christian Jacob bsen showed you a small trick: How to Use the features of Roslyn to implement a C # interactive window similar to F # interactive window.
First, implement a very simple script execution engine:
public class CSharpScriptEngine{ private static Script _previousInput; private static Lazy<object> _nextInputState = new Lazy<object>(); public static object Execute(string code) { var script = CSharpScript.Create(code, ScriptOptions.Default).WithPrevious(_previousInput); var endState = script.Run(_nextInputState.Value); _previousInput = endState.Script; _nextInputState = new Lazy<object>(() => endState); return endState.ReturnValue; }}
The above Code only references the two Nuget: Microsoft. CodeAnalysis. CSharp and Microsoft. CodeAnalysis. Scripting.
The C/S architecture can be used to implement the interactive window. The Server is a Web Api of SelfHost, as follows:
public class CodeController : ApiController{ // POST api/code public void Post([FromBody]string code) { Console.WriteLine(CSharpScriptEngine.Execute(code)); }}static void Main(string[] args){ string baseAddress = "http://localhost:9000/"; // Start OWIN host using (WebApp.Start<Startup>(url: baseAddress)) { while (true) { var str = Console.ReadLine(); Console.WriteLine(CSharpScriptEngine.Execute(str)); } }}
The Client is a standard Windows Forms. During Alt + Enter, the entered code is sent to the Server for execution and the execution result is displayed on the Server:
private void CodeEdit_KeyDown(object sender, KeyEventArgs e){ if (CodeEdit.SelectedText.Length > 0 && e.KeyCode == Keys.Enter && e.Alt) { string baseAddress = "http://localhost:9000/"; using (var client = new HttpClient()) { var response = client.PostAsJsonAsync(baseAddress + "api/code", CodeEdit.SelectedText).Result; } }}
Although the sample code is simple, it shows the powerful idea of Roslyn and the basic idea of implementing the interactive window. You can find the complete source code address by reading the original text.
Address: http://www.jayway.com/2015/05/09/using-roslyn-to-build-a-simple-c-interactive-script-engine/