Platinum Partner
dotnet,microsoft,tools,framework,c#,visual studio,c-sharp,net

FastSharp – Building A Fast C# Prototyping Tool Using Roslyn And AvalonEdit

FastSharp in action

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.

To install Roslyn, make sure that you already have installed Visual Studio SDK SP1. If you don’t have it, you can grab it here. You can install the latest version of Roslyn from here.

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.

Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}