Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make my application scriptable in C#?

I have a desktop application written in C# I'd like to make scriptable on C#/VB. Ideally, the user would open a side pane and write things like

foreach (var item in myApplication.Items)
   item.DoSomething();

Having syntax highlighting and code completion would be awesome, but I could live without it. I would not want to require users to have Visual Studio 2010 installed.

I am thinking about invoking the compiler, loading and running the output assembly.

Is there a better way?

Is Microsoft.CSharp the answer?

like image 439
tom greene Avatar asked Mar 02 '10 23:03

tom greene


3 Answers

Have you thought about IronPython or IronRuby?

like image 81
Jared Updike Avatar answered Oct 10 '22 02:10

Jared Updike


Use a scripting language. Tcl, LUA or even JavaScript comes to mind.

Using Tcl is really easy:

using System.Runtime.InteropServices;
using System;

namespace TclWrap {
    public class TclAPI {
         [DllImport("tcl84.DLL")]
         public static extern IntPtr Tcl_CreateInterp();
         [DllImport("tcl84.Dll")]
         public static extern int Tcl_Eval(IntPtr interp,string skript);
         [DllImport("tcl84.Dll")]
         public static extern IntPtr Tcl_GetObjResult(IntPtr interp);
         [DllImport("tcl84.Dll")]
         public static extern string Tcl_GetStringFromObj(IntPtr tclObj,IntPtr length);
    }
    public class TclInterpreter {
        private IntPtr interp;
        public TclInterpreter() {
            interp = TclAPI.Tcl_CreateInterp();
            if (interp == IntPtr.Zero) {
                throw new SystemException("can not initialize Tcl interpreter");
            }
        }
        public int evalScript(string script) {
            return TclAPI.Tcl_Eval(interp,script);        
        }
        public string Result {
            get { 
                IntPtr obj = TclAPI.Tcl_GetObjResult(interp);
                if (obj == IntPtr.Zero) {
                    return "";
                } else {
                    return TclAPI.Tcl_GetStringFromObj(obj,IntPtr.Zero);
                }
            }
        }
    }
}

Then use it like:

TclInterpreter interp = new TclInterpreter();
string result;
if (interp.evalScript("set a 3; {exp $a + 2}")) {
    result = interp.Result;
}
like image 1
Byron Whitlock Avatar answered Oct 10 '22 02:10

Byron Whitlock


I would use PowerShell or MEF. It really depends on what you mean by scritable and what type of application you have. The best part about PowerShell is it's directly hostable and directly designed to use .NET interfaces in a scripting manner.

like image 1
rerun Avatar answered Oct 10 '22 03:10

rerun