Create a gist now

Instantly share code, notes, and snippets.

@akimboyko /Howto.md
Last active Dec 17, 2015

Scripting: `eval()`-like for C# using Roslyn and ScriptCS
  • Install Chocolatey
  • Reopen console application (for example cmd.exe) to update %PATH% and other environment variables
  • Install ScriptCs using chocolatey
  • Save both Roslyn-EvalSample.csx and packages.config
  • Install dependencies using scriptcs -install
  • Run scriptcs .\Roslyn-EvalSample.csx
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Roslyn" version="1.2.20906.2" targetFramework="net45" />
<package id="Roslyn.Compilers" version="1.2.20906.2" targetFramework="net45" />
<package id="Roslyn.Compilers.Common" version="1.2.20906.2" targetFramework="net45" />
<package id="Roslyn.Compilers.CSharp" version="1.2.20906.2" targetFramework="net45" />
<package id="Roslyn.Services.Common" version="1.2.20906.2" targetFramework="net45" />
<package id="Roslyn.Services.CSharp" version="1.2.20906.2" targetFramework="net45" />
</packages>
// Steps:
// * Get NuGet packages: `scriptcs -install`
// * Run scriptcs: `scriptcs .\Roslyn-EvalSample.csx`
using System;
using Roslyn.Services.Interactive;
using Roslyn.Scripting;
using Roslyn.Scripting.CSharp;
// limitations of scripts:
// * no `dynamic` keyword allowed
// * no async/await allowed
System.Console.WriteLine("Enter two commands to execute");
System.Console.WriteLine("For example:");
System.Console.WriteLine("var x = 6;");
System.Console.WriteLine("System.Math.Sqrt(x * 7)");
System.Console.WriteLine();
var scripts = new []
{
System.Console.ReadLine(), //fromValue:
System.Console.ReadLine() //formula:
};
var engine = new ScriptEngine(); // create script engine
Array.ForEach( // add references to assembiles
new[] { typeof(object).Assembly, GetType().Assembly },
@assembly => engine.AddReference(@assembly));
Array.ForEach( // import namespaces
new[] { "System" },
@namespace => engine.ImportNamespace(@namespace));
var session = engine.CreateSession();// create session
object resultModel = null;
// INFO: scripts are using same session
foreach(var script in scripts)
{
resultModel = session // process scripts
.CompileSubmission<object>(script)
.Execute();
}
Console.WriteLine(resultModel);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment