Is possible to parse a string as function and reference runtime variables?

42 Views Asked by At

I'm trying ExpandoObjects to accomplish custom calculations on some customer data.

For example, there exists some class as (short version):

public class Seller
{
    public Guid Id { get; set; }
    public decimal MonthlyAmount { get; set; }
}

In some process, we need to dynamically create some properties, whose formulas are defined as literals in a dictionary. For example:

var formulas = new Dictionary<string, string>
{
    { "Bonus", "Seller.MonthlyAmount > 1000 ? Seller.MonthlyAmount * 3/100 : 0" },
    { "AmountPlusBonus", "Seller.MonthlyAmount + Bonus" }
}

I would need to create a dynamic class, which allows to have to parse the literal as a custom function.

I have tried the following, without success:

var seller = new Seller();

var sellerEx = new ExpandoObject() as IDictionary<string, object>;
sellerEx["Seller"] = seller;

foreach (var formula in formulas)
{
    sellerEx[formula.Key] = DynamicExpressionParser.ParseLambda(
    ParsingConfig.Default, false, typeof(object), formula.Value);
}

During execution, it complains with "Unknown identifier 'Seller'". How it is Seller unknown, if the expando already has this assignment?: sellerEx["Seller"] = seller?

What would be a working approach for this?

Apart from "Seller", I would like to have other objects as source for calculations, like:

sellerEx["Seller"] = seller;
sellerEx["Schedule"] = schedule;
sellerEx["ProductList"] = productList;

I mean, I expect the Parse to define functions on the expando and take other expando properties as part of its context. Is it possible?

0

There are 0 best solutions below