Posts

C# scripting in .NET

Based on a couple of days of experimenting it seems that I now have C# scripting working in my application to a level that I am satisfied.  Because I couldn’t have achieved this without looking at other people’s examples I thought it was only fair that I share what I now have.  Firstly I want to say that my purpose was to give the user the ability to write procedural code rather than object code.  Although it is still possible for the user to write OOP source code my requirement was to let the user define a function which returned a specific return type. public interface ICompiledFunction < T > { T Execute(Dictionary < string , object > variables); } A typical script might look something like this public decimal string Main() { return " Bob Monkhouse " ; } To create an instance of the ICompiledFunction<T> I use ICompilerService, which is defined like so public interface ICompilerService { bool Compile < T > ( string [] scripts,

Why I dislike DLR

It took me hours last night to work out why I was getting a null result from the Value property in the following code when accessed via IronPython public interface ISomeInterface { decimal Value { get ; } } How could a non nullable type possibly return a null (or “None”)?  It turns out that when I set my variable using the .NET scripting API ScriptScope.SetVariable(variableName, (ISomeInterface)value); The scripting engine still works on the implementing object rather than the interface.  This means that if my object has a method “DoSomethingThatScriptingShouldNotHaveAccessTo()” then scripting has access to it! In my case this bit me because I had a Nullable<decimal> property called “Value”, and the Value property implemented explicitly for the interface looked like this decimal ISomeInterface.Value { get { if ( this .Value == null ) CalculateValue(); return this .Value; } } In this case I expected the script to access the variable’s “Value” propert