This project has moved. For the latest updates, please go here.

Expressions in expressions

Dec 12, 2014 at 8:08 AM
Edited Dec 12, 2014 at 9:05 AM
Hi, I'm having some trouble doing this:
I dinamically fill a Context object containing some parameters and some db data, to use in evaluation. Something like this: Context.Parameters and Context.Datasets...
In example
{"Value1" , "Hallo "},
{"Value2" , @"Context.Parameters.Value1 + "" world :-)"""},
If I evaluate Value1, obviously I get "Hallo ", if I evaluate Value2, i get "Hallo world :-)". It's OK!!!
The problem is when I try to do this:
{"IsTypeA" , @"Context.DataSets.Table1.MyField == 0"},
{"IsTypeB" , @"Context.DataSets.Table1.MyField == 1"},
{"IsAorBType", "Context.Parameters.IsTypeA || Context.Parameters.IsTypeB"},
If I run Context.Parameters.IsTypeA, i get "False".
If I run Context.Parameters.IsTypeB, i get "True".
If I run Context.Parameters.IsAorBType, I get "Context.Parameters.IsTypeA || Context.Parameters.IsTypeB".
I expect "True" from that expression, but seems that it isn't able to evaluate it.

MyField is a numeric Db's Table1 field.
I use theese methods to evaluate the expression:
private object EvaluateExpression(string expression)
{
    var exp = new CompiledExpression(expression);
    exp.TypeRegistry = _registry;
    try
    {
        var result = exp.Eval();
        return result;
    }
    catch (Exception e)
    {
        //If here's some error, i return the expression
        return expression;
    }
}
and this
public object EvaluateExpressionRecursive(string expression, int deepLevel=0)
{
    if (deepLevel == 10) return expression; //Temp protection from loops
    
    var result = EvaluateExpression(expression);

    if (Convert.ToString(result) != expression)
        return EvaluateExpressionRecursive(Convert.ToString(result), deepLevel++);
    else
        return result;
    
}
Debugging, first execution of EvaluateExpression method, I get the expression correctly expanded.
Instead in second execution, i get an exception: invalid cast.
Any idea??

tnx so much in advance
Developer
May 16, 2015 at 1:32 AM
Sorry I took so long to answer this.

Hi, with the latest version I get the exception "OrElse is not defined for types string and string"

The problem with this approach is that your Parameters are inherently strings, and ExpressionEvaluator is resolving them as the strings themselves, not as the expressions they represent.

The first two work because they store the expressions, but with the third one what is actually happening is:
"Context.DataSets.Table1.MyField == 0" || "Context.DataSets.Table1.MyField == 1",
You would need to write some sort of parser that would detect if a part of the expression needs to be resolved, evaluate that value, then replace it into the original string before finally parsing again.

There was some talk about this on this thread and an implementation of it here