Пример #1
0
 public ServerHandler(TcpServerProperties tcpServerProperties, RulesEngine.RulesEngine engine, TcpRuleWorkflow ruleWorkflow, ILogger logger)
 {
     _tcpServerProperties = tcpServerProperties;
     _engine       = engine;
     _ruleWorkflow = ruleWorkflow;
     _logger       = logger;
 }
        public WeatherForecastMapper()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            List <Workflow>?workflow = JsonConvert.DeserializeObject <List <Workflow> >(GetFileText());

            _rulesEngine = new RulesEngine.RulesEngine(workflow?.ToArray());
        }
Пример #3
0
 public DotNettyTcpServerMessageListener(ILogger logger, string id, TcpServerProperties properties)
 {
     _logger = logger;
     Id      = id;
     _tcpServerProperties = properties;
     _ruleWorkflow        = GetTcpRuleWorkflow();
     _engine = GetRuleEngine();
 }
Пример #4
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);
        }
Пример #5
0
        public Task SaveAsync(WorkflowRules[] rules, CancellationToken cancellationToken)
        {
            var engine = new re(null);

            // provides with workflow validation
            engine.AddWorkflow(rules);

            return(Task.CompletedTask);
        }
Пример #6
0
        internal void Do(Report report)
        {
            int pages = 0;
            var rulesEngine = new RulesEngine.RulesEngine();

            foreach (var urlDto in _sqlRepository.GetWebPages())
            {
                rulesEngine.ProcessPage(_sqlRepository, urlDto, report);
                pages++;
            }

            _log.Info("Pages analyzed: " + pages);
        }
        /// <summary>
        /// 适配优惠券
        /// </summary>
        /// <returns></returns>
        public async Task <string> SelectCouponAsync()
        {
            var workRules = new RulesEngine.Models.WorkflowRules();

            workRules.WorkflowName = "优惠券";
            var rules = new List <Rule>();

            foreach (var coupon in _userCoupons.Where(s => s.BeginTime <DateTime.Now && s.EndTime> DateTime.Now))
            {
                var rule = new Rule
                {
                    RuleName     = coupon.Name,
                    SuccessEvent = coupon.Code,
                    //ErrorMessage = "规则应用失败",
                    ErrorType          = ErrorType.Error,
                    RuleExpressionType = RuleExpressionType.LambdaExpression,
                    Expression         = coupon.Expression
                };
                rules.Add(rule);
            }
            workRules.Rules = rules;
            var rulesEngine = new RulesEngine.RulesEngine(new WorkflowRules[] { workRules }, _logger, new ReSettings());
            var ruleResults = await rulesEngine.ExecuteAllRulesAsync("优惠券", _order, _user, _goodses);

            // var valueCoupons = new List<string>();
            //处理结果
            var discountCoupons = new StringBuilder();

            foreach (var ruleResult in ruleResults)
            {
                if (ruleResult.IsSuccess)
                {
                    discountCoupons.AppendLine($"可以使用的优惠券 “{_userCoupons.SingleOrDefault(s => s.Code == ruleResult.Rule.SuccessEvent)?.Name}”, Code是:{ruleResult.Rule.SuccessEvent}");
                    //valueCoupons.Add(ruleResult.Rule.SuccessEvent);
                }
                else
                {
                    Console.WriteLine(ruleResult.ExceptionMessage);
                }
            }
            //resultList.OnSuccess((eventName) =>
            //{
            //    discountOffered += $"可以使用的优惠券“{userCoupons.SingleOrDefault(s => s.Code == eventName)?.Name}”,Code是:{eventName} ";
            //});
            ruleResults.OnFail(() =>
            {
                discountCoupons.AppendLine("您没有适合的优惠券!");
            });
            return(discountCoupons.ToString());
        }
Пример #8
0
        public static void Main(string[] args)
        {
            var nestedInput = new
            {
                SimpleProp = "simpleProp",
                NestedProp = new
                {
                    SimpleProp = "nestedSimpleProp",
                    ListProp   = new List <ListItem>
                    {
                        new ListItem
                        {
                            Id    = 1,
                            Value = "first"
                        },
                        new ListItem
                        {
                            Id    = 2,
                            Value = "second"
                        }
                    }
                }
            };

            var files = Directory.GetFiles(Directory.GetCurrentDirectory(), "NestedInputDemo.json", SearchOption.AllDirectories);

            if (files == null || files.Length == 0)
            {
                throw new Exception("Rules not found.");
            }

            var fileData      = File.ReadAllText(files[0]);
            var workflowRules = JsonConvert.DeserializeObject <List <WorkflowRules> >(fileData);

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

            foreach (var workflow in workflowRules)
            {
                List <RuleResultTree> resultList = bre.ExecuteRule(workflow.WorkflowName, nestedInput);

                resultList.OnSuccess((eventName) =>
                {
                    Console.WriteLine($"{workflow.WorkflowName} evaluation resulted in succees - {eventName}");
                }).OnFail(() =>
                {
                    Console.WriteLine($"{workflow.WorkflowName} evaluation resulted in failure");
                })
                ;
            }
        }
Пример #9
0
        public void Run()
        {
            Console.WriteLine($"Running {nameof(BasicDemo)}....");
            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 files = Directory.GetFiles(Directory.GetCurrentDirectory(), "Discount.json", SearchOption.AllDirectories);

            if (files == null || files.Length == 0)
            {
                throw new Exception("Rules not found.");
            }

            var fileData      = File.ReadAllText(files[0]);
            var workflowRules = JsonConvert.DeserializeObject <List <WorkflowRules> >(fileData);

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

            string discountOffered = "No discount offered.";

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

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

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

            Console.WriteLine(discountOffered);
        }
Пример #10
0
        public async Task <List <RuleResultTree> > Excute(FlowExcuteEntity Input)
        {
            var mainRules = new Workflow
            {
                WorkflowName = Input.Task.id,
            };

            foreach (var item in Input.Task.outgoing)
            {
                item.Rule.Operator = item.id;
            }
            mainRules.Rules = Input.Task.outgoing.Select(c => c.Rule).ToList();
            var bre = new RulesEngine.RulesEngine(new[] { mainRules }, null);

            return(await bre.ExecuteAllRulesAsync(Input.Task.id, Input.Params));
        }
Пример #11
0
        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
            });
        }
Пример #12
0
        public REBenchmark()
        {
            var files = Directory.GetFiles(Directory.GetCurrentDirectory(), "NestedInputDemo.json", SearchOption.AllDirectories);

            if (files == null || files.Length == 0)
            {
                throw new Exception("Rules not found.");
            }

            var fileData = File.ReadAllText(files[0]);

            workflows = JsonConvert.DeserializeObject <List <WorkflowRules> >(fileData);

            rulesEngine = new RulesEngine.RulesEngine(workflows.ToArray(), null, new ReSettings {
                EnableFormattedErrorMessage = false,
                EnableLocalParams           = false
            });

            ruleInput = new
            {
                SimpleProp = "simpleProp",
                NestedProp = new
                {
                    SimpleProp = "nestedSimpleProp",
                    ListProp   = new List <ListItem>
                    {
                        new ListItem
                        {
                            Id    = 1,
                            Value = "first"
                        },
                        new ListItem
                        {
                            Id    = 2,
                            Value = "second"
                        }
                    }
                }
            };
        }
Пример #13
0
        public async Task Can_Get_Rules()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            List <Workflow>?workflow = JsonConvert.DeserializeObject <List <Workflow> >(GetFileText());

            RulesEngine.RulesEngine bre = new RulesEngine.RulesEngine(workflow.ToArray());

            var rp1 = new RuleParameter("todayInfo", new WeatherInfo("Klart vejr", 25));
            var rp2 = new RuleParameter("yesterdayInfo", new WeatherInfo("Regn", 10));

            var location = "Kolding";

            RuleResultTree?result = (await bre.ExecuteAllRulesAsync("WeatherForecast", rp1, rp2)).FirstOrDefault(r => r.IsSuccess);

            if (result != null && result.Rule.SuccessEvent != null)
            {
                var text = string.Format(result.Rule.SuccessEvent, location, "0");
                Assert.NotNull(text);
            }
        }
Пример #14
0
        static async Task Main(string[] args)
        {
            //定义规则
            var rulesStr = @"[{
                    ""WorkflowName"": ""UserInputWorkflow"",
                    ""Rules"": [
                      {
                        ""RuleName"": ""CheckNestedSimpleProp"",
                        ""ErrorMessage"": ""年龄必须小于18岁."",
                        ""ErrorType"": ""Error"",
                        ""RuleExpressionType"": ""LambdaExpression"",
                        ""Expression"": ""IdNo.GetAgeByIdCard() < 18""
                      },
                       {
                        ""RuleName"": ""CheckNestedSimpleProp1"",
                        ""ErrorMessage"": ""身份证号不可以为空."",
                         ""ErrorType"": ""Error"",
                        ""RuleExpressionType"": ""LambdaExpression"",
                        ""Expression"": ""IdNo != null""
                      }
                    ]
                  }] ";

            //规则JSON架构
            //RuleName规则名称
            //Properties 规则属性,获取或设置规则的自定义属性或标记。
            //Operator 操作符
            //ErrorMessage 错误消息
            //Enabled 获取和设置规则是否已启用
            //RuleExpressionType 默认RuleExpressionType.LambdaExpression
            //WorkflowRulesToInject 注入工作规则
            //Rules 规则
            //LocalParams
            //Expression 表达树
            //Actions
            //SuccessEvent 完成事件,默认为规则名称



            var userInput = new UserInput
            {
                IdNo = "11010519491230002X",
                Age  = 18
            };

            //反序列化Json格式规则字符串
            var workflowRules = JsonConvert.DeserializeObject <List <WorkflowRules> >(rulesStr);



            var rulesEngine = new RulesEngine.RulesEngine(workflowRules.ToArray(), null, reSettings: reSettings);

            List <RuleResultTree> resultList = await rulesEngine.ExecuteAllRulesAsync("UserInputWorkflow", userInput);

            //foreach (var item in resultList)
            //{
            //    //{ "Rule":{ "RuleName":"CheckNestedSimpleProp","Properties":null,"Operator":null,"ErrorMessage":"年龄必须大于18岁.",
            //    //"ErrorType":"Error","RuleExpressionType":"LambdaExpression","WorkflowRulesToInject":null,"Rules":null,"LocalParams":null,"Expression":"Age > 18","Actions":null,"SuccessEvent":null},"IsSuccess":false,"ChildResults":null,"Inputs":{ "input1":{ "IdNo":null,"Age":18} },
            //    //"ActionResult":{ "Output":null,"Exception":null},"ExceptionMessage":"年龄必须大于18岁.","RuleEvaluatedParams":[]}


            //    Console.WriteLine("验证成功:{0},消息:{1}", item.IsSuccess, item.ExceptionMessage);
            //}

            var discountOffered = "";

            resultList.OnSuccess((eventName) =>
            {
                discountOffered = $"成功事件:{eventName}.";
            });


            resultList.OnFail(() =>
            {
                discountOffered = "失败事件.";
            });

            Console.WriteLine(discountOffered);
            Console.ReadLine();
        }
 public RulesEngineBasedProcessor(WorkflowRules[] workflows)
 {
     mWorkflows   = workflows;
     mRulesEngine = new RulesEngine.RulesEngine(mWorkflows, null);
 }