FastSharp – Building A Fast C# Prototyping Tool Using Roslyn And AvalonEdit
I’ve had this idea about building a fast code prototyping tool for a while now. You can use LINQPad to test LINQ queries against lots of data sources, but it cannot provide fast code prototyping. The obvious solution was to go and build a custom tool. Open source to the rescue.
For such tool I needed two parts: visual editor for displaying source code and an interpreter to actually compile and execute that code. I wanted to use WPF for building UI and there is an excellent control that offers syntax highlighting – AvalonEdit. As for the code compiling and execution, I use Roslyn – a great project from Microsoft.
You can install AvalonEdit quickly via Nuget by executing the following command: Install-Package AvalonEdit. Now you can add it to your XAML window using the following fragment:
// namespace xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit" // somewhere else <avalonEdit:TextEditor Grid.Row="1" FontFamily="Consolas" SyntaxHighlighting="C#" FontSize="14pt" Name="editor" Margin="3" ShowLineNumbers="True" WordWrap="True" KeyDown="editor_KeyDown"> <avalonEdit:TextEditor.Options> <avalonEdit:TextEditorOptions ShowEndOfLine="True" ShowSpaces="True" ShowTabs="True" /> </avalonEdit:TextEditor.Options> </avalonEdit:TextEditor>
And now the fun part – executing code. First add the necessary references to Roslyn.Compilers and Roslyn.Compilers.CSharp. The quick and dirty way is to create an instance of ScriptEngine and call the Execute method. Here is the code fragment:
var engine = new ScriptEngine(); var session = Session.Create(); engine.Execute(editor.SelectedText, session);
That serves as a basic foundation for the project. Now comes the hard part, defining requirements and building features. You can grab this project over at github, although at this stage it isn’t much.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)