Home > Uncategorized > Evaluate C# with C# using #Roslyn

Evaluate C# with C# using #Roslyn

Having code that evaluates code is a bit of an unusual ask, but perhaps, you want to have a super-configurable system, where you can dynamically execute user code, giving full flexibility over the functionality of your system. Obviously this opens security issues, but let’s imagine you are in a secure, trusted environment

So, this is where Roslyn comes in, Which you can load by grabbing the NuGet package using “Install-Package Microsoft.CodeAnalysis.CSharp.Scripting”. Then, you can run a very simple command such as;

var result = CSharpScript.EvaluateAsync("1 + 3").Result;

All very simple, however, let’s say you want to run more complex code. Here, for example, to run some code to get the user’s IP address. I’ve moved this out to a seperate file, called Sample.txt, and set the build option to copy always, so I can write the user code in a different location to the interpreting code.

var wc = new WebClient();
return wc.DownloadString("http://www.icanhazip.com");

If you try to run this as a script, it borks, because it can’t locate WebClient, and fully qualifying it, by saying System.Net.WebClient doesn’t work either, because it can’t locate System.Net either, so you need to add a bit more as follows –

var scriptOptions = ScriptOptions.Default;
var asmWebClient = typeof(WebClient).Assembly;
scriptOptions = scriptOptions.AddReferences(asmWebClient);
scriptOptions = scriptOptions.AddImports("System.Net");
var sample = File.ReadAllText("sample.txt");
var result = CSharpScript.EvaluateAsync(sample, scriptOptions).Result;
Console.WriteLine(result);

This grabs the relevant assembly for WebClient, and then adds both the reference, and the import to the script. Once it executes, it can find the WebClient class, and the code runs.

GitHub Repo here: https://github.com/infiniteloopltd/RoslynDemo

Advertisement
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: