0

I have an ASP.net (C#) application (.net 3.5) using Ciloci.Flee by Muhammet Parlak (specifically Trove.Flee by Alan Dean through NuGet) that allows the user to enter a formula into an interface, and that formula is later used for calculations, based on input values gathered by a different set of users. The formula includes up to 9 possible variables they have to pull from. For example, they could define Tt-((Lt/Vc)*(Th-Vi)). The app knows how to populate all those variables, but what I want to do is protect them against bad syntax or even unsupported variables when they enter the formula on the admin screen. Tt-((Lt/Vc)*(Th-Vi))+Aa should cause a validation error when they enter the formula because Aa is not a supported variable.

At the time the enter the formula I don't have actual values to try to Evaluate it. I haven't been able to find a way to tell the context what variables are ok and then have it tell me if it's syntactically correct or not.

PS - the actual evaluation of the formulas do work fine when formatted correctly and contain no invalid variables. It's just the validation piece for the users I'm trying to nail down.

If anyone has experience with this and can share their discoveries I would most appreciate it :-) Thank you!

LBW
  • 111
  • 4

1 Answers1

0

For now, I'm achieving the results I'm after by catching an exception. This code is inside an ASP CustomValidator control:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            try
            {
                ExpressionContext context = new ExpressionContext();
                context.Imports.AddType(typeof(Math));
                context.Variables["A"] = 1;
                context.Variables["Ll"] = 1;
                context.Variables["Lt"] = 1;
                context.Variables["Lh"] = 1;
                context.Variables["Th"] = 1;
                context.Variables["Tgi"] = 1;
                context.Variables["Tt"] = 1;
                context.Variables["Vi"] = 1;
                context.Variables["Vc"] = 1;

                IGenericExpression<double> eGeneric = context.CompileGeneric<double>(args.Value);
                args.IsValid = true;
            } catch (ExpressionCompileException ece)
            {
                args.IsValid = false;
            }    
        }

If the formula has bad syntax or invalid variables, it throws the ExpressionCompileException exception and invalidates the control. If the formula contains valid variables, the exception is not thrown.

LBW
  • 111
  • 4