C# Corner

Using The Roslyn Scripting API in C#

Learn how to utilize the Roslyn Scripting API to host a C# scripting engine in your applications.

I first learned about the C# compiler as a service workings way back in 2008 at PDC. At that time, Anders Hejlsberg gave a brief preview of what was to come by showing off a C# Read-Evaluate-Print-Loop (REPL) demo. Since then the project has progressed to include powerful code analysis and compiler APIs as well. In this column I'll  demonstrate how to utilize the C# Roslyn Scripting API to execute expressions , code blocks and classes from a string or file.

Getting Started

The first step is to procure and install the Roslyn CTP bits from bit.ly/rThx5k. Once Roslyn is set up, open up Visual Studio and you should see the Roslyn templates available for both C# and VB.NET, as shown in Figure 1.


[Click on image for larger view.]
Figure 1. Roslyn Visual Studio Templates.

Figure 1: Roslyn Visual Studio Templates

Next create a new Console Application, open up Program.cs and add the following using statements.

using Roslyn.Scripting;
using Roslyn.Scripting.CSharp;

You're now set up to run any of the code examples in the remainder of the article.

Executing a C# Expression

One of the most basic scripting needs is the ability to execute a given expression. Accomplishing this task with Roslyn is very similar to using the Dynamic Language Runtime (DLR) . First create a  ScriptEngine instance for your target language, in this case C#:

 ScriptEngine  scriptEngine = new ScriptEngine();

Then use the Execute method to run the given expression:

 scriptEngine.Execute("1+1");

The expression above would return an object with a value of 2.

If you know the return type, you can also use the generic Execute<T> method. For example, to get an integer value from a numeric expression, run the following:

 int result =  scriptEngine.Execute<int>("20+22");

Executing a Code Block and Classes

The Execute method can also be used to execute code blocks, including control statements and even an entire class. To execute a foreach script block to increment each item in a collection, for example, you would call:

scriptEngine.Execute("foreach(int  item in numbers) { item += 1;    };");

To execute an entire class, you can simply pass it to the Execute method. For example, to execute a custom class named DemoClass that contains one method named Test you would run:

scriptEngine.Execute("Public  class DemoClass() {" +
"public string Test { return "Test Method"; } +
"}"

Maintaining an Execution Context

The Execute method contains an overloaded signature for passing a Session object. The Session object is used for maintaining an execution context. To create a context, use the Session.Create() method:

 Session  mySession = Session.Create();

After a session's been created, pass it to the ScriptEngine Execute method whenever you call it. For example, you can create a variable in one Execute invocation and then access it in a succeeding Execute invocation:

scriptEngine.Execute("int number = 40;", mySession);
scriptEngine.Execute("number += 2;", mySession);

Executing a File

The SciptEngine  also allows for execution of a given C# code file. You can execute either a standard  .cs C# file or a .csx C# script with the ScriptEngine's ExecuteFile method. To execute a standard C# file, run the following:

 scriptEngine.ExecuteFile("DemoClass.cs");
Running a C# script file is just as easy:
scriptEngine.ExecuteFile("DemoScript.csx");

Creating a Read Evaluate Print Loop (REPL)

This is just the tip of the iceberg; with a little work, you can create a REPL quite easily. For the sake of clarity and clean code, I'll encapsulate the Scripting API access into a new class named ScriptHost. The ScriptHost class exposes the Execute, Execute<T>, and ExecuteFile methods of the Roslyn C# ScriptEngine.

In addition, I used an overloaded ScriptEngine constructor to pass in the assemblies and namespaces that will be available to the consumer of the ScriptHost. The ExecuteFile method is not used in the demo application, but could come in quite handy for loading utility classes for use by the scripting engine. See Listing 1 for the full contents of the ScriptHost class.

In the console application, I make use of the ScriptHost class to execute the user's given C# expressions in a loop. If the user enters the word "quit", the program silently exits.  I opted to catch any Exceptions that might occur and display them to the user. See Listing 2 for the full REPL application code, and Figure 2 for the resulting output.


[Click on image for larger view.]
Figure 2. C# REPL in action.

Looking Forward

The Roslyn project is looking very promising, and already has a lot of powerful APIs available for developers to wield. Today I've shown only the Scripting API, which can be used to host C# or VB.NET in a .NET application. Stay tuned for the next installment, covering how to use the Compiler APIs to analyze C# syntax and semantics and compile code.

About the Author

Eric Vogel is a Senior Software Developer for Red Cedar Solutions Group in Okemos, Michigan. He is the president of the Greater Lansing User Group for .NET. Eric enjoys learning about software architecture and craftsmanship, and is always looking for ways to create more robust and testable applications. Contact him at [email protected].

comments powered by Disqus

Featured

Subscribe on YouTube