Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

what is the simplest and fastest way to support simple scripting in a .Net application? I search a lot but only find many things with practical no documentation or outdated since years. I only need to transfer a simple .Net Object to the script and get a bool result from it.

share|improve this question

closed as too broad by gnat, MichaelT, GlenH7, Corbin March, TZHX Sep 13 '13 at 15:00

There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.If this question can be reworded to fit the rules in the help center, please edit the question.

    
You want to allow others to write scripts for your application, or do you want to call a script from your application? –  R0MANARMY Sep 9 '13 at 13:20
    
nothing that involves custom scripts is ever simple. –  Mathew Foscarini Sep 9 '13 at 16:37
    
allow users to interact with objects from the program –  Sebastian Sep 10 '13 at 8:24
1  
Then expose your types as com objects, and let people use vbs, and call it a day. –  whatsisname Sep 10 '13 at 16:40
    
@whatsisname Once it's COM, doesn't necessarily have to be VBA, pretty much anything that can consume COM can use it. –  R0MANARMY Sep 10 '13 at 18:32

5 Answers 5

up vote 5 down vote accepted

It depends on your precise needs. Two ways I can think of:

  • Use a language like Python which is interoperable with C#, and call the Python script from C#. Actually, you can even make things simpler by just calling an executable, passing to it an XML or JSON data, and wait for XML or JSON response.

  • If you need to use C#, then compile C# on the fly, just like LINQPad does. Is it possible to dynamically compile and execute C# code fragments? is a good starting point. Loading the code in a sandbox (in a different AppDomain) is also a good idea if you need to provide enough security and don't trust the code which can be written by the user.

share|improve this answer
    
+1 for Python, by far the easiest way –  RMalke Sep 9 '13 at 13:32

I think the simplest way would be to use one of the .Net scripting languages that already exist, like IronPython or IronRuby.

For example, with IronPython you can write your script code in Python, execute it from your C# application and then process the results from the script.

The code could look like this:

var engine = Python.CreateEngine();
var scope = engine.CreateScope();
scope.SetVariable("value", 43);

var code = @"
# overcomplicated just to show it's really Python
def areEqual (value1, value2):
    return value1 == value2

areEqual(value, 42)";

Console.WriteLine(engine.Execute<bool>(code, scope));

Another option would be to use the scripting capabilities of Roslyn, but that's not production ready yet.

share|improve this answer

Another scripting language you should consider is PowerShell. There's a fully working example of an application that exposes some of its internal objects to a script environment here.

This is the description of the application from the book (emphasis mine):

The reference application for this chapter, Beaver Music, is a very simple music album management system. It supports create, read, update, and delete (CRUD) actions for albums. Beaver Music has the functionality you’d expect—a couple of dialogs for adding and changing album information, and you can delete albums as well. What we want to focus on is the PowerShell Console button (shown in Figure 5-1), a WPF application that has the PowerShell engine embedded in it. As noted earlier, PowerShell is surfaced as a console, a scripting language, and an API; the custom PowerShell console uses this surfaced API in conjunction with the Beaver Music application so it can be scripted and automated. This works similarly to the way Microsoft Excel can be automated with the embedded Visual Basic for Applications (VBA) scripting language.

share|improve this answer

You could build a temp class and invoke a method on that

var template = @"public static class Temp
{{
  public static bool Run()
  {{
      return {0};
  }}
}}";

var script = "1 < 2";

var source = string.Format(template, script);

var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll" }, "temp.dll", true);
parameters.GenerateExecutable = false;
var results = csc.CompileAssemblyFromSource(parameters, source);
var type = results.CompiledAssembly.GetType("Temp");
var method = type.GetMethod("Run");
var result = (bool)method.Invoke(null, null);
Console.WriteLine(result);

But you really have to trust people who write the scripts. Just add parameters to the Run method to pass your object.

share|improve this answer

Fastest and simplest? I really hope this isn't that, but as a really last resort, you can use the .NET Emit method to create hand crafted CIL code that you generate dynamically in your program.

If your scripting requirement is really trivial, then this is probably a month or two's work. You can work out the CIL instruction set from using a reflector to look at how the compiler translates your C# code into CIL, and then 'borrow' these code fragments.

share|improve this answer
    
I hoped there is something out there I didn't find... –  Sebastian Sep 9 '13 at 13:19
    
I had to use CIL about 2 years ago for dynamically implementing a proxy class that implements a supplied interface marked with attributes to identify the key parts of the interface we needed to proxy. It was some fairly intense work, and not to be undertaken lightly, but it was effective. –  Ptolemy Sep 9 '13 at 13:26
    
Using CIL is practically the opposite of simple scripting. –  svick Sep 9 '13 at 13:39
    
True, but as a real last resort but it does allow you to present a script window to your user, to convert their script (in what ever script language to allow them to use) into CIL and then to load that into your process and execute it. –  Ptolemy Sep 9 '13 at 13:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.