Esempio n. 1
0
        public void BuildExpressionForRuleTest()
        {
            var reSettings        = new ReSettings();
            var objBuilderFactory = new RuleExpressionBuilderFactory(reSettings, new RuleExpressionParser(reSettings));
            var builder           = objBuilderFactory.RuleGetExpressionBuilder(RuleExpressionType.LambdaExpression);

            var ruleParameters = new RuleParameter[] {
                new RuleParameter("RequestType", "Sales"),
                new RuleParameter("RequestStatus", "Active"),
                new RuleParameter("RegistrationStatus", "InProcess")
            };


            Rule mainRule = new Rule();

            mainRule.RuleName = "rule1";
            mainRule.Operator = "And";
            mainRule.Rules    = new List <Rule>();

            Rule dummyRule = new Rule();

            dummyRule.RuleName           = "testRule1";
            dummyRule.RuleExpressionType = RuleExpressionType.LambdaExpression;
            dummyRule.Expression         = "RequestType == \"vod\"";

            mainRule.Rules.Add(dummyRule);
            var func = builder.BuildDelegateForRule(dummyRule, ruleParameters);

            Assert.NotNull(func);
            Assert.Equal(typeof(RuleResultTree), func.Method.ReturnType);
        }
Esempio n. 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RuleCompiler"/> class.
        /// </summary>
        /// <param name="expressionBuilderFactory">The expression builder factory.</param>
        /// <exception cref="ArgumentNullException">expressionBuilderFactory</exception>
        internal RuleCompiler(RuleExpressionBuilderFactory expressionBuilderFactory, ReSettings reSettings, ILogger logger)
        {
            _logger = logger ?? throw new ArgumentNullException($"{nameof(logger)} can't be null.");

            _expressionBuilderFactory = expressionBuilderFactory ?? throw new ArgumentNullException($"{nameof(expressionBuilderFactory)} can't be null.");
            _reSettings = reSettings;
        }
Esempio n. 3
0
        internal static RuleFunc <RuleResultTree> ToResultTree(ReSettings reSettings, Rule rule, IEnumerable <RuleResultTree> childRuleResults, Func <object[], bool> isSuccessFunc, string exceptionMessage = "")
        {
            return((inputs) => {
                var isSuccess = false;
                var inputsDict = new Dictionary <string, object>();
                try
                {
                    inputsDict = inputs.ToDictionary(c => c.Name, c => c.Value);
                    isSuccess = isSuccessFunc(inputs.Select(c => c.Value).ToArray());
                }
                catch (Exception ex)
                {
                    exceptionMessage = GetExceptionMessage($"Error while executing rule : {rule?.RuleName} - {ex.Message}", reSettings);
                    HandleRuleException(new RuleException(exceptionMessage, ex), rule, reSettings);
                    isSuccess = false;
                }

                return new RuleResultTree {
                    Rule = rule,
                    Inputs = inputsDict,
                    IsSuccess = isSuccess,
                    ChildResults = childRuleResults,
                    ExceptionMessage = exceptionMessage
                };
            });
        }
Esempio n. 4
0
 public RuleExpressionParser(ReSettings reSettings)
 {
     _reSettings  = reSettings;
     _memoryCache = new MemoryCache(new MemoryCacheOptions {
         SizeLimit = 1000
     });
 }
Esempio n. 5
0
        public void RuleCompiler_NullCheck()
        {
            Assert.Throws <ArgumentNullException>(() => new RuleCompiler(null, null));
            var reSettings = new ReSettings();
            var parser     = new RuleExpressionParser(reSettings);

            Assert.Throws <ArgumentNullException>(() => new RuleCompiler(new RuleExpressionBuilderFactory(reSettings, parser), null));
        }
Esempio n. 6
0
 public RulesEngine(ILogger logger = null, ReSettings reSettings = null)
 {
     _logger               = logger ?? new NullLogger <RulesEngine>();
     _reSettings           = reSettings ?? new ReSettings();
     _ruleExpressionParser = new RuleExpressionParser(_reSettings);
     _ruleCompiler         = new RuleCompiler(new RuleExpressionBuilderFactory(_reSettings, _ruleExpressionParser), _reSettings, _logger);
     _actionFactory        = new ActionFactory(GetActionRegistry(_reSettings));
 }
Esempio n. 7
0
        private RulesEngine.RulesEngine GetRuleEngine()
        {
            var reSettingsWithCustomTypes = new ReSettings {
                CustomTypes = new Type[] { typeof(RulePipePayloadParser) }
            };
            var result = new RulesEngine.RulesEngine(new Workflow[] { _ruleWorkflow.GetWorkflow() }, null, reSettingsWithCustomTypes);

            return(result);
        }
Esempio n. 8
0
        public void RuleCompiler_CompileRule_ThrowsException()
        {
            var reSettings = new ReSettings();
            var parser     = new RuleExpressionParser(reSettings);
            var compiler   = new RuleCompiler(new RuleExpressionBuilderFactory(reSettings, parser), new NullLogger <RuleCompiler>());

            Assert.Throws <ArgumentNullException>(() => compiler.CompileRule(null, null));
            Assert.Throws <ArgumentNullException>(() => compiler.CompileRule(null, new RuleParameter[] { null }));
        }
Esempio n. 9
0
        /// <summary>
        /// 重写自行构建规则引擎
        /// </summary>
        /// <returns></returns>
        protected virtual Engine CreateRulesEngine()
        {
            var reSetting = new ReSettings
            {
                NestedRuleExecutionMode = NestedRuleExecutionMode.Performance
            };

            return(new Engine(Logger, reSetting));
        }
Esempio n. 10
0
 public RuleExpressionParser(ReSettings reSettings)
 {
     _reSettings  = reSettings;
     _memoryCache = _memoryCache ?? new MemoryCache(new MemoryCacheOptions {
         SizeLimit = 1000
     });
     _methodInfo = new Dictionary <string, MethodInfo>();
     PopulateMethodInfo();
 }
Esempio n. 11
0
        internal static void HandleRuleException(Exception ex, Rule rule, ReSettings reSettings)
        {
            ex.Data.Add(nameof(rule.RuleName), rule.RuleName);
            ex.Data.Add(nameof(rule.Expression), rule.Expression);

            if (!reSettings.EnableExceptionAsErrorMessage)
            {
                throw ex;
            }
        }
        public void RuleGetExpressionBuilderTest(RuleExpressionType expressionType, Type expectedExpressionBuilderType)
        {
            var reSettings        = new ReSettings();
            var parser            = new RuleExpressionParser(reSettings);
            var objBuilderFactory = new RuleExpressionBuilderFactory(reSettings, parser);
            var builder           = objBuilderFactory.RuleGetExpressionBuilder(expressionType);

            var builderType = builder.GetType();

            Assert.Equal(expectedExpressionBuilderType.ToString(), builderType.ToString());
        }
Esempio n. 13
0
        private IDictionary <string, Func <ActionBase> > GetActionRegistry(ReSettings reSettings)
        {
            var actionDictionary = GetDefaultActionRegistry();
            var customActions    = reSettings.CustomActions ?? new Dictionary <string, Func <ActionBase> >();

            foreach (var customAction in customActions)
            {
                actionDictionary.Add(customAction);
            }
            return(actionDictionary);
        }
        private RulesEngine GetRulesEngine(string filename, ReSettings reSettings = null)
        {
            var filePath = Path.Combine(Directory.GetCurrentDirectory() as string, "TestData", filename);
            var data = File.ReadAllText(filePath);

            var injectWorkflow = new WorkflowRules
            {
                WorkflowName = "inputWorkflowReference",
                WorkflowRulesToInject = new List<string> { "inputWorkflow" }
            };

            var injectWorkflowStr = JsonConvert.SerializeObject(injectWorkflow);
            var mockLogger = new Mock<ILogger>();
            return new RulesEngine(new string[] { data, injectWorkflowStr }, mockLogger.Object, reSettings);
        }
Esempio n. 15
0
        private RulesEngine GetRulesEngine(string filename, ReSettings reSettings = null)
        {
            var data = GetFileContent(filename);

            var injectWorkflow = new WorkflowRules {
                WorkflowName          = "inputWorkflowReference",
                WorkflowRulesToInject = new List <string> {
                    "inputWorkflow"
                }
            };

            var injectWorkflowStr = JsonConvert.SerializeObject(injectWorkflow);
            var mockLogger        = new Mock <ILogger>();

            return(new RulesEngine(new string[] { data, injectWorkflowStr }, mockLogger.Object, reSettings));
        }
Esempio n. 16
0
        public async Task NestedRulesShouldFollowExecutionMode(NestedRuleExecutionMode mode)
        {
            var workflows  = GetWorkflows();
            var reSettings = new ReSettings {
                NestedRuleExecutionMode = mode
            };
            var     rulesEngine = new RulesEngine(workflows, reSettings: reSettings);
            dynamic input1      = new ExpandoObject();

            input1.trueValue = true;

            List <RuleResultTree> result = await rulesEngine.ExecuteAllRulesAsync("NestedRulesTest", input1);

            var andResults = result.Where(c => c.Rule.Operator == "And").ToList();
            var orResults  = result.Where(c => c.Rule.Operator == "Or").ToList();

            Assert.All(andResults,
                       c => Assert.False(c.IsSuccess)
                       );
            Assert.All(orResults,
                       c => Assert.True(c.IsSuccess));

            if (mode == NestedRuleExecutionMode.All)
            {
                Assert.All(andResults,
                           c => Assert.Equal(c.Rule.Rules.Count(), c.ChildResults.Count()));
                Assert.All(orResults,
                           c => Assert.Equal(c.Rule.Rules.Count(), c.ChildResults.Count()));
            }
            else if (mode == NestedRuleExecutionMode.Performance)
            {
                Assert.All(andResults,
                           c => {
                    Assert.Equal(c.IsSuccess, c.ChildResults.Last().IsSuccess);
                    Assert.Single(c.ChildResults.Where(d => c.IsSuccess == d.IsSuccess));
                    Assert.True(c.ChildResults.SkipLast(1).All(d => d.IsSuccess == true));
                });

                Assert.All(orResults,
                           c => {
                    Assert.Equal(c.IsSuccess, c.ChildResults.Last().IsSuccess);
                    Assert.Single(c.ChildResults.Where(d => c.IsSuccess == d.IsSuccess));
                    Assert.True(c.ChildResults.SkipLast(1).All(d => d.IsSuccess == false));
                });
            }
        }
        public override async Task <AutoAllocateResponse> ExecuteAsync(AutoAllocateRequest request, CancellationToken cancellationToken)
        {
            var basicInfo     = "{\"name\": \"hello\",\"email\": \"[email protected]\",\"creditHistory\": \"good\",\"country\": \"canada\",\"loyalityFactor\": 3,\"totalPurchasesToDate\": 10000}";
            var orderInfo     = "{\"totalOrders\": 5,\"recurringItems\": 2}";
            var telemetryInfo = "{\"noOfVisitsPerMonth\": 10,\"percentageOfBuyingToVisit\": 15}";

            var converter = new ExpandoObjectConverter();

            dynamic input1 = JsonConvert.DeserializeObject <ExpandoObject>(basicInfo, converter);
            dynamic input2 = JsonConvert.DeserializeObject <ExpandoObject>(orderInfo, converter);
            dynamic input3 = JsonConvert.DeserializeObject <ExpandoObject>(telemetryInfo, converter);

            var inputs = new dynamic[]
            {
                input1,
                input2,
                input3
            };

            var workflowRules             = JsonConvert.DeserializeObject <List <WorkflowRules> >(await GetRulesAsync());
            var reSettingsWithCustomTypes = new ReSettings {
                CustomTypes = new [] { typeof(Utils) }
            };

            var bre = new RulesEngine.RulesEngine(workflowRules.ToArray(), null, reSettingsWithCustomTypes);

            string discountOffered = "No discount offered.";

            List <RuleResultTree> resultList = await bre.ExecuteAllRulesAsync("Discount", inputs);

            resultList.OnSuccess((eventName) => {
                discountOffered = $"Discount offered is {eventName} % over MRP.";
                var bbb         = resultList.ToArray();
            });

            resultList.OnFail(() => {
                discountOffered = "The user is not eligible for any discount.";
            });

            return(new AutoAllocateResponse {
                Result = discountOffered
            });
        }
Esempio n. 18
0
        public void EvaluateRule(IMessage <ICRMMessage> message)
        {
            var settings = new ReSettings()
            {
                NestedRuleExecutionMode = NestedRuleExecutionMode.Performance
            };

            var wflw = repo.GetWorkflow(message);

            foreach (var stp in wflw.Steps)
            {
                //var lst = JsonConvert.DeserializeObject<List<WorkflowRules>>(stp.JsonRules);
                var bre = new RulesEngine.RulesEngine(stp.Rules, null, settings);

                var result = bre.ExecuteAllRulesAsync("NewLead-Immediate", message.Payload.Opportunity, message.Payload.Opportunity.Leads[0], message.Payload.Opportunity.VehicleOfInterest).Result;

                result.OnSuccess((eventName) => {
                    Console.WriteLine($"NewLead-Immediate evaluation resulted in succees - {eventName}");
                }).OnFail(() => {
                    Console.WriteLine($"NewLead-Immediate evaluation resulted in failure");
                });
            }
        }
Esempio n. 19
0
 public RulesEngine(ILogger logger, ReSettings reSettings = null)
 {
     _logger           = logger ?? new NullLogger <RulesEngine>();
     _reSettings       = reSettings ?? new ReSettings();
     ruleParamCompiler = new ParamCompiler(new RuleExpressionBuilderFactory(_reSettings), _logger);
 }
Esempio n. 20
0
 public RulesEngine(WorkflowRules[] workflowRules, ILogger logger, ReSettings reSettings = null) : this(logger, reSettings)
 {
     AddWorkflow(workflowRules);
 }
Esempio n. 21
0
        public RulesEngine(string[] jsonConfig, ILogger logger, ReSettings reSettings = null) : this(logger, reSettings)
        {
            var workflowRules = jsonConfig.Select(item => JsonConvert.DeserializeObject <WorkflowRules>(item)).ToArray();

            AddWorkflow(workflowRules);
        }
Esempio n. 22
0
 internal LambdaExpressionBuilder(ReSettings reSettings)
 {
     _reSettings = reSettings;
 }
 public RuleExpressionBuilderFactory(ReSettings reSettings, RuleExpressionParser expressionParser)
 {
     _reSettings = reSettings;
     _lambdaExpressionBuilder = new LambdaExpressionBuilder(_reSettings, expressionParser);
 }
 internal LambdaExpressionBuilder(ReSettings reSettings, RuleExpressionParser ruleExpressionParser)
 {
     _reSettings           = reSettings;
     _ruleExpressionParser = ruleExpressionParser;
 }
Esempio n. 25
0
 internal ParamCompiler(ReSettings reSettings, RuleExpressionParser ruleExpressionParser)
 {
     _reSettings           = reSettings;
     _ruleExpressionParser = ruleExpressionParser;
 }
 public RuleExpressionBuilderFactory(ReSettings reSettings)
 {
     _reSettings = reSettings;
 }
Esempio n. 27
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="ex"></param>
 /// <param name="message"></param>
 /// <param name="rule"></param>
 /// <param name="reSettings"></param>
 /// <returns></returns>
 internal static string GetExceptionMessage(string message, ReSettings reSettings)
 {
     return(reSettings.IgnoreException ? "" : message);
 }
Esempio n. 28
0
 internal static RuleFunc <RuleResultTree> ToRuleExceptionResult(ReSettings reSettings, Rule rule, Exception ex)
 {
     HandleRuleException(ex, rule, reSettings);
     return(ToResultTree(reSettings, rule, null, (args) => false, ex.Message));
 }
Esempio n. 29
0
 public RulesEngine(ILogger logger, ReSettings reSettings = null)
 {
     _logger     = logger ?? new NullLogger();
     _reSettings = reSettings ?? new ReSettings();
     InitializeVariables();
 }
Esempio n. 30
0
 public RulesEngine(ILogger logger, ReSettings reSettings = null)
 {
     _logger     = logger ?? new NullLogger <RulesEngine>();
     _reSettings = reSettings ?? new ReSettings();
 }