Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate the expression in Microsoft RulesEngine

I have been using the Microsoft RulesEngine nuget package in my .NET Core-based project. I wonder if there is a way to validate the format of the expression before running RulesEngine.Execute. According to the README file, the expression is a lambda expression. Also, there is a schema definition that can be used to validate the schema of the root object (WorkflowRules) but that wouldn't validate the expressions used under the Rules. enter image description here

like image 320
Mar Chal Avatar asked Jun 16 '26 06:06

Mar Chal


1 Answers

I found a way to make sure the expression is valid. In the below code, if an exception occurs, it means the expression has an invalid format:

    using System.Linq.Dynamic.Core;
    using System.Linq.Expressions;
    ...
    private bool Evaluate<TParameterType>(TParameterType fact, string rule)
    {
        var parameter = Expression.Parameter(typeof(TParameterType));
        try
        {
            var lambdaExpression = DynamicExpressionParser.ParseLambda(new[] { parameter }, null, rule);
            return (bool) lambdaExpression.Compile().DynamicInvoke(fact);
        }
        catch
        {
            return false;
        }
    }
like image 175
Mar Chal Avatar answered Jun 18 '26 00:06

Mar Chal