Esempio n. 1
0
        public void ProcessNumber_Should_Bypass_Default_Rules_If_Apply_Default_Rules_IsFalse()
        {
            var fizzBuzz = new RulesEngine();
            const string textForMatches = "FOUR!";

            var result = fizzBuzz.ProcessNumber(4, ((x) => x == 4), textForMatches, false);
            Assert.AreEqual(textForMatches, result);
        }
        public static StatefulSession New(RulesEngine rulesEngine, Action<StatefulSessionConfigurator> configureCallback)
        {
            var configurator = new StatefulSessionConfiguratorImpl();

            configureCallback(configurator);

            return configurator.Create(rulesEngine);
        }
Esempio n. 3
0
        public void ProcessNumber_Should_Evaluate_Custom_Rule()
        {
            var fizzBuzz = new RulesEngine();
            const string textForMatches = "FOUR!";

            var result = fizzBuzz.ProcessNumber(4, ((x) => x == 4), textForMatches);
            Assert.AreEqual("even " + textForMatches, result);
        }
 public void Setup()
 {
     _engine = RulesEngineFactory.New(x =>
         {
             // add our rule
             x.Rule<SingleFactRule>();
             x.Rule<ViolationRule>();
         });
 }
 public RulesEngine GetRulesEngine()
 {
     Console.WriteLine("Create Rule Engine");
     XElement engineElement = GetRulesEngineElement();
     GetRuleTypesElement(engineElement);
     GetParser(engineElement);
     RulesEngine engine = new RulesEngine(parser);
     return engine;
 }
Esempio n. 6
0
 public void ProcessNumbers_Should_Display_Output()
 {
     var fizzBuzz = new RulesEngine();
     var output = fizzBuzz.ProcessRange();
     foreach (var item in output)
     {
         Console.WriteLine(item);
     }
 }
Esempio n. 7
0
 public override BrokenRule Validate(object value, RulesEngine.ValidationContext context)
 {
     BrokenRule rule = new BrokenRule();
     if (value.ToString().Length > MaxLength)
     {
         rule.IsBroken = true;
         rule.Name = this.Name;
         rule.ErrorMessage = this.Message;
     }
     return rule;
 }
        public override BrokenRule Validate(object value, RulesEngine.ValidationContext context)
        {
            BrokenRule rule = new BrokenRule();
            if(value == null || string.IsNullOrWhiteSpace(value.ToString()))
            {
                rule.IsBroken = true;
                rule.ErrorMessage = this.Message;
                rule.Name = this.Name;
            }

            return rule;
        }
Esempio n. 9
0
        public void SaveGraphToFile(RulesEngine engine, int width, int height, string filename)
        {
            Graph gleeGraph = CreateGraph(engine);

            var renderer = new GraphRenderer(gleeGraph);
            renderer.CalculateLayout();

            var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            renderer.Render(bitmap);

            Trace.WriteLine("Saving graph to " + filename);

            bitmap.Save(filename, ImageFormat.Png);
        }
Esempio n. 10
0
        public void ProcessNumber_Should_Evaluate_Multiple_Custom_Rules_And_Bypass_Default_Rules()
        {
            var fizzBuzz = new RulesEngine();
            const string textForMatches4 = "FOUR!";
            const string textForGreaterThan3 = "GREATER_THAN_THREE";

            var rules = new Dictionary<NumberRule, string>()
            {
                {(x) => x == 4, textForMatches4},
                {(x) => x > 3, textForGreaterThan3}
            };

            var result = fizzBuzz.ProcessNumber(4, rules, false);
            Assert.AreEqual(textForMatches4 + " " + textForGreaterThan3, result);
        }
Esempio n. 11
0
        public void Define_rule()
        {
            var conditions = new[]
                {
                    Conditions.NotNull((Order x) => x.Customer),
                };

            var consequences = new[]
                {
                    Consequences.Delegate((Order o) => _result = o),
                };

            Rule rule = new SemanticRule("RuleA", conditions, consequences);

            _engine = RulesEngineFactory.New(x => x.Add(rule));
        }
Esempio n. 12
0
        public void Define_rule()
        {
            var conditions = new[]
                {
                    Conditions.NotEqual((Order x) => x.Name, "BOB"),
                };

            var consequences = new[]
                {
                    Consequences.Delegate((Order o) => _result = o),
                };

            Rule rule = new OdoyuleRule("RuleA", conditions, consequences);

            _engine = RulesEngineFactory.New(x => x.Add(rule));
        }
        public void Define_rule()
        {
            var conditions = new RuleCondition[]
                {
                    Conditions.GreaterThanOrEqual((Order x) => x.Amount, 10000.0m),
                };

            var consequences = new RuleConsequence[]
                {
                    Consequences.Delegate<Order>((session,x) => { _result = x; }),
                };

            Rule rule = new OdoyuleRule("RuleA", conditions, consequences);

            _engine = RulesEngineFactory.New(x => x.Add(rule));
        }
Esempio n. 14
0
        public void Define_rule()
        {
            var conditions = new[]
                {
                    Conditions.GreaterThan((Order x) => x.Amount, 10000.0m),
                };

            var consequences = new[]
                {
                    Consequences.Delegate((Order o) => _result = o),
                };

            Rule rule = new SemanticRule("RuleA", conditions, consequences);

            _engine = RulesEngineFactory.New(x => x.Add(rule));
        }
Esempio n. 15
0
        public void Define_rule()
        {
            var conditions = new RuleCondition[]
                {
                    Conditions.NotNull((Order x) => x.Customer),
                };

            var consequences = new RuleConsequence[]
                {
                    Consequences.Delegate<Order>((session,x) => { _result = x; }),
                };

            Rule rule = new OdoyuleRule("RuleA", conditions, consequences);

            _engine = RulesEngineFactory.New(x => x.Add(rule));
        }
Esempio n. 16
0
        public void Define_rule()
        {
            _results = new List<Tuple<OrderLine, int>>();

            var conditions = new[]
                {
                    Conditions.Each<Order, IList<OrderLine>, OrderLine>(x => x.Lines),
                };

            var consequences = new[]
                {
                    Consequences.Delegate((Token<Token<Order, IList<OrderLine>>, Tuple<OrderLine, int>> x) => _results.Add(x.Item2))
                };

            Rule rule = new OdoyuleRule("RuleA", conditions, consequences);

            _engine = RulesEngineFactory.New(x => x.Add(rule));
        }
Esempio n. 17
0
        public void Define_rule()
        {
            _results = new List<Order>();

            var conditions = new[]
                {
                    Conditions.Exists((Order x) => x.Lines),
                };

            var consequences = new[]
                {
                    Consequences.Delegate((Order o) => _results.Add(o)),
                };

            Rule rule = new OdoyuleRule("RuleA", conditions, consequences);

            _engine = RulesEngineFactory.New(x => x.Add(rule));
        }
Esempio n. 18
0
    void Start()
    {
        combatNumber = GameObject.FindWithTag("CombatNumber");
        combatNumber.SetActive(false);
        combatNumberText = combatNumber.transform.GetChild(0).transform.GetChild(0).gameObject.GetComponent <Text>();

        _rulesEngine = GetComponent <RulesEngine>();

        GameObject LevelUpUI = GameObject.FindWithTag("LevelUpUI");

        experiencePanel = LevelUpUI.transform.GetChild(0).gameObject.GetComponent <ExperienceUI>();
        experiencePanel.gameObject.SetActive(false);
        levelUpScreen = LevelUpUI.transform.GetChild(1).gameObject.GetComponent <LevelUpScreen>();
        foreach (GameObject stat in levelUpScreen._statLine)
        {
            stat.transform.GetChild(2).gameObject.SetActive(false);
        }
        levelUpScreen.gameObject.SetActive(false);
    }
        public async Task GetCarInsuranceAdvice_SearchForRulesWithRepairCostsGreaterThan1000_Returns2Rules()
        {
            // Arrange
            const ContentTypes expectedContent   = ContentTypes.CarInsuranceAdvice;
            DateTime           expectedMatchDate = new DateTime(2018, 06, 01);
            SearchArgs <ContentTypes, ConditionTypes> searchArgs = new SearchArgs <ContentTypes, ConditionTypes>
            {
                Conditions = new Condition <ConditionTypes>[]
                {
                    new Condition <ConditionTypes>
                    {
                        Type  = ConditionTypes.RepairCosts,
                        Value = 1200.00000m
                    }
                },
                ContentType = expectedContent,
                DateBegin   = expectedMatchDate,
                DateEnd     = expectedMatchDate,
                ExcludeRulesWithoutSearchConditions = false
            };

            IRulesDataSource <ContentTypes, ConditionTypes> rulesDataSource = await RulesFromJsonFile.Load
                                                                              .FromJsonFileAsync <ContentTypes, ConditionTypes>(DataSourceFilePath, serializedContent : false);

            RulesEngine <ContentTypes, ConditionTypes> rulesEngine = RulesEngineBuilder.CreateRulesEngine()
                                                                     .WithContentType <ContentTypes>()
                                                                     .WithConditionType <ConditionTypes>()
                                                                     .SetDataSource(rulesDataSource)
                                                                     .Configure(reo =>
            {
                reo.PriotityCriteria = PriorityCriterias.BottommostRuleWins;
            })
                                                                     .Build();

            // Act
            IEnumerable <Rule <ContentTypes, ConditionTypes> > actual = await rulesEngine.SearchAsync(searchArgs);

            // Assert
            actual.Should().NotBeNull();
            actual.Should().HaveCount(2);
            actual.Should().Contain(r => r.Name == "Car Insurance Advise on repair costs greater than 80% of commercial value");
            actual.Should().Contain(r => r.Name == "Car Insurance Advise on repair costs lesser than 80% of commercial value");
        }
Esempio n. 20
0
        public void Define_rule()
        {
            _results = new List<Order>();

            var conditions = new RuleCondition[]
                {
                    Conditions.Exists((Order x) => x.Lines), //,
                    //Conditions.Equal((OrderLine x) => x.ItemNumber == "123"));
                };

            var consequences = new RuleConsequence[]
                {
                    Consequences.Delegate<Order>((session,x) => _results.Add(x)),
                };

            Rule rule = new OdoyuleRule("RuleA", conditions, consequences);

            _engine = RulesEngineFactory.New(x => x.Add(rule));
        }
Esempio n. 21
0
        public ChessApp(IConsoleIO console, IFileIO fileIO)
        {
            // TODO: How to replace this boilerplate code with auto-generated?
            // Maybe, classical DI infrastructure could be used here in a local scope?

            Console = console ?? throw new ArgumentNullException(nameof(console));
            FileIO  = fileIO ?? throw new ArgumentNullException(nameof(fileIO));

            RulesEngine = new RulesEngine();
            AiPlayer    = new AiPlayer(RulesEngine);
            FileStorage = new FileStorage(FileIO);

            var lazyConsolePlayer = new LateBindingPlayerAdapter();

            GameFlow  = new GameFlow(lazyConsolePlayer, AiPlayer, RulesEngine);
            ConsoleUI = new ConsoleUI(GameFlow, Console, FileStorage, RulesEngine);

            lazyConsolePlayer.Bind(ConsoleUI);
        }
Esempio n. 22
0
        private RulesEngine GetRulesEngine()
        {
            var rulesEngine = new RulesEngine(_settings);

            rulesEngine.PlayWindowsAudio += RulesEnginePlayWindowsAudio;
            rulesEngine.UpdateStatusBar  += RulesEngineUpdateStatusBar;
            rulesEngine.RefreshStatus    += RulesEngineRefreshRefreshStatus;
            rulesEngine.TrayNotify       += RulesEngineTrayNotify;
            rulesEngine.ModalDialog      += RulesEngineModalDialog;
            rulesEngine.SetAudio         += RulesEngineSetAudio;
            rulesEngine.SetLights        += RulesEngineSetLights;
            rulesEngine.SetTrayIcon      += RulesEngineSetTrayIcon;
            rulesEngine.StatsChanged     += RulesEngineStatsChanged;
            rulesEngine.NewAlert         += RulesEngineNewAlert;
            rulesEngine.NewAchievement   += RulesEngineNewAchievement;
            rulesEngine.NewNewsItem      += RulesEngineNewNewsItem;
            rulesEngine.NewUser          += RulesEngineNewUser;
            return(rulesEngine);
        }
        public async Task GetCarInsuranceAdvice_RepairCostsNotWorthIt_ReturnsRefusePaymentPerFranchise()
        {
            // Arrange
            CarInsuranceAdvices expected          = CarInsuranceAdvices.RefusePaymentPerFranchise;
            const ContentTypes  expectedContent   = ContentTypes.CarInsuranceAdvice;
            DateTime            expectedMatchDate = new DateTime(2018, 06, 01);

            Condition <ConditionTypes>[] expectedConditions = new Condition <ConditionTypes>[]
            {
                new Condition <ConditionTypes>
                {
                    Type  = ConditionTypes.RepairCosts,
                    Value = 800.00000m
                },
                new Condition <ConditionTypes>
                {
                    Type  = ConditionTypes.RepairCostsCommercialValueRate,
                    Value = 23.45602m
                }
            };

            IRulesDataSource <ContentTypes, ConditionTypes> rulesDataSource = await RulesFromJsonFile.Load
                                                                              .FromJsonFileAsync <ContentTypes, ConditionTypes>(DataSourceFilePath, serializedContent : false);

            RulesEngine <ContentTypes, ConditionTypes> rulesEngine = RulesEngineBuilder.CreateRulesEngine()
                                                                     .WithContentType <ContentTypes>()
                                                                     .WithConditionType <ConditionTypes>()
                                                                     .SetDataSource(rulesDataSource)
                                                                     .Configure(reo =>
            {
                reo.PriotityCriteria = PriorityCriterias.BottommostRuleWins;
            })
                                                                     .Build();

            // Act
            Rule <ContentTypes, ConditionTypes> actual = await rulesEngine.MatchOneAsync(expectedContent, expectedMatchDate, expectedConditions);

            // Assert
            actual.Should().NotBeNull();
            CarInsuranceAdvices actualContent = actual.ContentContainer.GetContentAs <CarInsuranceAdvices>();

            actualContent.Should().Be(expected);
        }
Esempio n. 24
0
        public void RulesEngine_PickCard_Valid2()
        {
            // 1: blue | 2: green, white | 3: red, yellow
            var startingPositions = TestHelper.ConvertToStartingPositions("1,0 2,1 2,2 3,3 3,4");
            var gamestate         = new ImplementedGameState(2, startingPositions);

            gamestate.BettingCards.RemoveAll(x => x.CamelColor == CamelColor.Red && x.Value != 2);

            var engine = new RulesEngine(gamestate, seed: 2);
            var change = engine.Getchange(0, new PlayerAction()
            {
                CamelAction = CamelAction.PickCard, Color = CamelColor.Red
            }) as PickCardStateChange;

            Assert.IsTrue(change != null, "is pick card");
            Assert.AreEqual(CamelColor.Red, change.Color, "card color");
            Assert.AreEqual(0, change.Player, "player");
            Assert.AreEqual(2, change.Value, "card value");
        }
Esempio n. 25
0
        public async Task BasicWorkflowRules_ReturnsTrue(string workflowName)
        {
            var workflows = GetWorkflowRulesList();

            var engine = new RulesEngine(null, null);

            engine.AddWorkflow(workflows);

            var input1 = new {
                trueValue  = true,
                falseValue = false
            };

            var result = await engine.ExecuteAllRulesAsync(workflowName, input1);

            Assert.True(result.All(c => c.IsSuccess));

            CheckResultTreeContainsAllInputs(workflowName, result);
        }
Esempio n. 26
0
        public void RulesEngine_ScoreGame_WrongBets()
        {
            // 1: blue | 2: green, white | 3: red, yellow
            var startingPositions = TestHelper.ConvertToStartingPositions("1,0 2,1 2,2 3,3 3,4");
            var gamestate         = new ImplementedGameState(4, startingPositions);

            gamestate.LoserBets.Add(new GameEndBet()
            {
                Player = 0, CamelColor = CamelColor.Green
            });
            gamestate.LoserBets.Add(new GameEndBet()
            {
                Player = 0, CamelColor = CamelColor.White
            });
            gamestate.LoserBets.Add(new GameEndBet()
            {
                Player = 0, CamelColor = CamelColor.Red
            });

            gamestate.LoserBets.Add(new GameEndBet()
            {
                Player = 1, CamelColor = CamelColor.White
            });
            gamestate.LoserBets.Add(new GameEndBet()
            {
                Player = 1, CamelColor = CamelColor.Red
            });

            gamestate.LoserBets.Add(new GameEndBet()
            {
                Player = 2, CamelColor = CamelColor.Red
            });

            var engine = new RulesEngine(gamestate, seed: 1);

            engine.ScoreGame();

            Assert.AreEqual(0, gamestate.Money[0], "money p0");
            Assert.AreEqual(1, gamestate.Money[1], "money p1");
            Assert.AreEqual(2, gamestate.Money[2], "money p2");
            Assert.AreEqual(3, gamestate.Money[3], "money p3");
        }
Esempio n. 27
0
        public string GetOrderOutput(string[] orderParams)
        {
            OrderDomain order = BuildOrder(orderParams);

            _rules = RulesEngine.GetRules(order);

            foreach (var rule in _rules)
            {
                rule.GetOrder(order);

                if (!string.IsNullOrWhiteSpace(order.ErrorMessage))
                {
                    break;
                }
            }

            var orderOutput = GenerateFormattedOutput(order);

            return(orderOutput);
        }
Esempio n. 28
0
        /// <summary>
        /// Registers the services used by serialization.
        /// </summary>
        /// <param name="registration">The <see cref="IServiceRegistration"/> to register with.</param>
        public void RegisterDefaultServices(IServiceRegistration registration)
        {
            registration.RegisterSingleton <IReflectionHelper>(
                new ReflectionHelper());
            registration.Register <IConfigurationBuilder, ConfigurationBuilder>();
            registration.RegisterSingleton <IDefaultConfiguration>(new DefaultConfiguration());
            var rules = new RulesEngine
            {
                LoadingDefaults = true,
            };

            registration.RegisterSingleton <IRulesEngine>(rules);
            registration.RegisterSingleton <IRulesConfiguration>(rules);
            registration.RegisterSingleton <IAnonymousTypeAdapter>(
                new AnonymousTypeAdapter());
            registration.RegisterSingleton <ITypesCompressor>(
                new TypesCompressor());
            registration.RegisterSingleton <ISerializationWrapper <string, JsonSerializerOptions, JsonSerializerOptions> >(
                new JsonWrapper());
        }
Esempio n. 29
0
        public Graph CreateGraph(RulesEngine engine)
        {
            var visitor = new GraphRulesEngineVisitor();
            engine.Visit(visitor);

            var graph = new AdjacencyGraph<Vertex, Edge<Vertex>>();

            visitor.Vertices.Each(x => graph.AddVertex(x));
            visitor.Edges.Each(x => graph.AddEdge(new Edge<Vertex>(x.From, x.To)));

            GleeGraphPopulator<Vertex, Edge<Vertex>> glee = graph.CreateGleePopulator();

            glee.NodeAdded += NodeStyler;
            glee.EdgeAdded += EdgeStyler;
            glee.Compute();

            Graph gleeGraph = glee.GleeGraph;

            return gleeGraph;
        }
Esempio n. 30
0
        static void DelegateExample()
        {
            // Create EngineAttributes with Name
            var engineOptions = new EngineAttributes {
                Name = "MyEngine"
            };

            // Instantiate the RulesEngine with option
            var myEngine = new RulesEngine(engineOptions);

            // Now add Lambda rule
            myEngine.AddRule(new Rule((c, o) => { Console.WriteLine("Hello, world"); return(true); }));

            // Next, add a delegate method
            myEngine.AddRule(new Rule(ruleDelegate));

            myEngine.RunAllRules();
            // Output:
            // Hello, world
            // ruleDelegate called
        }
Esempio n. 31
0
        public void RulesEngine_BetOnWinner_Valid_Other()
        {
            // 1: blue | 2: green, white | 3: red, yellow
            var startingPositions = TestHelper.ConvertToStartingPositions("1,0 2,1 2,2 3,3 3,4");
            var gamestate         = new ImplementedGameState(2, startingPositions);

            gamestate.LoserBets.Add(new GameEndBet()
            {
                Player = 0, CamelColor = CamelColor.Green
            });
            var engine = new RulesEngine(gamestate, seed: 2);

            var change = engine.Getchange(1, new PlayerAction()
            {
                CamelAction = CamelAction.SecretBetOnWinner, Color = CamelColor.Green
            }) as WinnerBetStateChange;

            Assert.IsTrue(change != null, "is valid");
            Assert.AreEqual(1, change.Player, "player");
            Assert.AreEqual(CamelColor.Green, change.Color, "bet on green");
        }
Esempio n. 32
0
        public async Task ExecuteRule_RuntimeError_ThrowsException()
        {
            var workflow = new WorkflowRules {
                WorkflowName = "TestWorkflow",
                Rules        = new[] {
                    new Rule {
                        RuleName   = "ruleWithRuntimeError",
                        Expression = "input1.Country.ToLower() == \"india\""
                    }
                }
            };

            var re = new RulesEngine(new[] { workflow }, null, new ReSettings {
                EnableExceptionAsErrorMessage = false
            });
            var input = new RuleTestClass {
                Country = null
            };

            _ = await Assert.ThrowsAsync <RuleException>(async() => await re.ExecuteAllRulesAsync("TestWorkflow", input));
        }
Esempio n. 33
0
        private static void processColdTemperature()
        {
            Console.WriteLine("Process Cold temperature");
            Console.WriteLine();
            String       type     = "COLD";
            String       commands = string.Empty;
            IRulesEngine iRules   = new RulesEngine();

            Console.WriteLine("SUCCESS: ");

            commands = "8,6,3,4,2,5,1,7";
            Console.WriteLine(iRules.processRules(type, commands));

            Console.WriteLine("FAILURE:");
            commands = "8,6,3,4,2,5,7";
            Console.WriteLine(iRules.processRules(type, commands));

            commands = "6";
            Console.WriteLine(iRules.processRules(type, commands));
            Console.WriteLine();
        }
Esempio n. 34
0
        public void Should_return_instances_that_implement_said_fact()
        {
            RulesEngine engine = RulesEngineFactory.New(x =>
            {
                x.Rules(r => r.Add <FirstRule>());
            });

            using (Session session = engine.CreateSession())
            {
                session.Add((IA) new A {
                    Name = "Chris"
                });

                session.Run();

                IEnumerable <FactHandle <IA> > ass = session.Facts <IA>();

                Assert.AreEqual(1, ass.Count());
                Assert.AreEqual("Chris", ass.First().Fact.Name);
            }
        }
Esempio n. 35
0
        private static void executeHotTemperatureProcess()
        {
            Console.WriteLine();
            Console.WriteLine("Hot temperature processing start");
            String temperatureType = string.Empty;
            String commandList     = string.Empty;

            IRulesEngine iRules = new RulesEngine();

            Console.WriteLine(iRules.processRules(temperatureType, commandList));

            Console.WriteLine("****SUCCESS****");
            temperatureType = "HOT";
            commandList     = "8,6,4,2,1,7";

            Console.WriteLine(iRules.processRules(temperatureType, commandList));
            Console.WriteLine();

            Console.WriteLine("****FAILURE****");
            temperatureType = "HOT";
            commandList     = "8,6,6";

            Console.WriteLine(iRules.processRules(temperatureType, commandList));

            temperatureType = "HOT";
            commandList     = "8,6,3";
            Console.WriteLine(iRules.processRules(temperatureType, commandList));


            temperatureType = "HOT";
            commandList     = "8,6,6,20";
            Console.WriteLine(iRules.processRules(temperatureType, commandList));


            temperatureType = "HOT";
            commandList     = "8,6,4,3,5,2,1,7";
            Console.WriteLine(iRules.processRules(temperatureType, commandList));
            Console.WriteLine("Hot temperature processing end");
            Console.WriteLine();
        }
Esempio n. 36
0
        /// <summary>
        /// Use the rules engine to process a range from 0 to 100 using the default rules and 
        /// 2 custom rules and associated strings:
        ///   - Custom Rule 1: if the number equals 4, display "FOUR"
        ///   - Custom Rule 2: if the number is > 50 and a multiple of 6, display "GREATER_THAN_FIFTY_AND_MULTIPLE_OF_6"
        /// </summary>
        static void Main(string[] args)
        {
            var fizzBuzz = new RulesEngine();
            int upperBound;

            //Define custom rules to pass to rules engine
            var rules = new Dictionary<NumberRule, string>()
            {
                {x => x == 4, "FOUR"},
                {x => x > 50 && x%6 == 0, "GREATER_THAN_FIFTY_AND_MULTIPLE_OF_6"}
            };

            if (args.Length == 0)
            {
                //Process the range, storing the results in a collection
                var result = fizzBuzz.ProcessRange(rules);

                //Iterate over the results collection, writing the results for each
                //number in the range to the console
                foreach (var item in result)
                {
                    var number = item.Key;
                    var output = item.Value;

                    Console.WriteLine("{0}: {1}", number, output);
                }
            }
            else if (args.Length == 1 && Int32.TryParse(args[0], out upperBound))
            {
                fizzBuzz.ProcessRange(upperBound, WriteOutput, rules);
            }
            else
            {
                Console.WriteLine("Incorrect arguments supplied. Please pass either no arguments, or an integer < {0}", int.MaxValue);
            }

            //Allow the user to press any key to terminate the console app
            Console.WriteLine("\n\nPress any key to continue...");
            Console.ReadKey();
        }
Esempio n. 37
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        // gets a rule engine
        RulesEngine rulesEngine = RuleEngineProvider.RulesEngines["DataCollectorAssignment"];
        // gets a ticket entity and fill his fields
        Entity ent = EntityNodeProvider.GetEntityNodeType(new Guid("00000000-0000-0000-0000-000000000003"));

        ent.Fields["Square"].Value = 40000;
        ent.Fields["Status"].Value = 3;
        //ent.Fields["Address"].Value = 3;
        //EntityNodeProvider.GetEntityNode(
        Entity orgStruct = EntityFieldProvider.Entities["4cda22f3-4f01-4768-8608-938dc6a06825"];

        if (orgStruct != null)
        {
            ent.Fields["Address"].Value = orgStruct;
        }
        // add entity as input parameter
        rulesEngine.AddInputEntity(ent);
        // gets a output RuleId
        Label1.Text = rulesEngine.Execute().ToString();
    }
Esempio n. 38
0
    public static string updateRow(string id, string columnName, string newValue)
    {
        // Check rules
        var rules = new RulesEngine(newValue, columnName);

        rules.checkColumn("enddemd")
        .number()
        .greaterThanOrEqual(0);
        rules.checkColumn("lotsiz")
        .number()
        .greaterThan(0);
        rules.checkColumn("varbility")
        .number()
        .greaterThanOrEqual(0);

        if (rules.HasError)
        {
            return(MpxTableUtil.CreateError(rules.Error));
        }

        return(MpxTableUtil.UpdateRow(getSource(), TableName, IdColumn, id, columnName, newValue));
    }
Esempio n. 39
0
        public void Should_not_activate_for_only_other_side()
        {
            _result = null;

            RulesEngine rulesEngine = RulesEngineFactory.New(x => { x.Add(_rule); });

            using (Session session = rulesEngine.CreateSession())
            {
                session.Add(new Order {
                    Name = "MAMA", Amount = 10001.0m
                });
                session.Run();
            }

            var visitor = new TextRuntimeVisitor();

            rulesEngine.Accept(visitor);

            Console.WriteLine(visitor);

            Assert.IsNull(_result);
        }
        public void RebuildSince(DateTime?since, Action <string> reportProgress)
        {
            try
            {
                var buildStatuses       = _sosDb.ReadAll();
                var sortedBuildStatuses = buildStatuses
                                          .Where(buildStatus => since == null || buildStatus.StartedTime > since)
                                          .OrderByDescending(buildStatus => buildStatus.LocalStartTime)
                                          .ToList();

                var totalBuilds = sortedBuildStatuses.Count;

                var rulesEngine = new RulesEngine(_settings)
                {
                    DisableSosOnline      = true,
                    DisableWritingToSosDb = true
                };
                int i = 0;
                foreach (var buildStatus in sortedBuildStatuses)
                {
                    rulesEngine.ExecuteNewBuilds(new List <BuildStatus> {
                        buildStatus
                    });
                    if (i % 10 == 0)
                    {
                        reportProgress(string.Format("Processing {0}/{1}", i, totalBuilds));
                    }
                    i++;
                }
                _settings.Save();
                reportProgress("Completed reset successfully");
            }
            catch (Exception ex)
            {
                _log.Error("Error in sync", ex);
                reportProgress("Error, check the logs. " + ex.Message);
            }
        }
Esempio n. 41
0
        static void RuleClassExample()
        {
            /**
             * Create the component to initialize the RulesEngine
             * We don't HAVE to have a component, the rules can still run
             */
            var bigB = new Customer
            {
                ID            = 1,
                Name          = "Amitabh",
                Birthdate     = new DateTime(1942, 10, 11),
                FirstPurchase = new DateTime(2005, 1, 2),
            };

            /**
             * Create an output object for Rules Engine
             * We don't HAVE to have an output object
             */
            var discount = new CustomerDiscount();

            // Create Engine Attributes
            var engineAttributes = new EngineAttributes {
                Component = bigB, Output = discount
            };

            // We can add individual rules or an array of rules
            var rulesArray = new Rule[] { new Rule(seniorCitizenDiscount, ruleName: "Senior") };

            // Start the engine with attributes and initial rules list
            var engine = new RulesEngine(engineAttributes, rulesArray);

            // We are adding multiple rules based on the same class, so we must name them explicitly
            engine.AddRule(new Rule(new LoyaltyDiscount(1, 5), ruleName: "L1"));
            engine.AddRule(new Rule(new LoyaltyDiscount(5, 8), ruleName: "L2"));
            engine.AddRule(new Rule(new LoyaltyDiscount(10, 10), ruleName: "L3"));

            Console.WriteLine(engine.RunAllRules());
        }
        public async Task RulesEngine_Execute_Rule_For_Nested_Rule_Params_Returns_Success(string ruleFileName)
        {
            dynamic[] inputs = GetInputs4();

            var ruleParams = new List<RuleParameter>();

            for (int i = 0; i < inputs.Length; i++)
            {
                var input = inputs[i];
                var obj = Utils.GetTypedObject(input);
                ruleParams.Add(new RuleParameter($"input{i + 1}", obj));
            }

            var files = Directory.GetFiles(Directory.GetCurrentDirectory(), ruleFileName, SearchOption.AllDirectories);
            if (files == null || files.Length == 0)
                throw new Exception("Rules not found.");

            var fileData = File.ReadAllText(files[0]);
            var bre = new RulesEngine(JsonConvert.DeserializeObject<WorkflowRules[]>(fileData), null);
            var result = await bre.ExecuteAllRulesAsync("inputWorkflow", ruleParams?.ToArray());
            var ruleResult = result?.FirstOrDefault(r => string.Equals(r.Rule.RuleName, "GiveDiscount10", StringComparison.OrdinalIgnoreCase));
            Assert.True(ruleResult.IsSuccess);
        }
Esempio n. 43
0
        public void RulesEngine_ScoreRound_Bets_Loser()
        {
            // 1: blue | 2: green, white | 3: red, yellow
            var startingPositions = TestHelper.ConvertToStartingPositions("1,0 2,1 2,2 3,3 3,4");
            var gamestate         = new ImplementedGameState(4, startingPositions);

            gamestate.BettingCards.First(x => x.CamelColor == CamelColor.White && x.Value == 5).Owner = 0;
            gamestate.BettingCards.First(x => x.CamelColor == CamelColor.Green && x.Value == 5).Owner = 0;

            gamestate.BettingCards.First(x => x.CamelColor == CamelColor.White && x.Value == 3).Owner = 1;
            gamestate.BettingCards.First(x => x.CamelColor == CamelColor.Blue && x.Value == 5).Owner  = 1;

            gamestate.BettingCards.First(x => x.CamelColor == CamelColor.White && x.Value == 2).Owner = 2;

            var engine = new RulesEngine(gamestate, seed: 1);

            engine.ScoreRound();

            Assert.AreEqual(1, gamestate.Money[0], "money p0");
            Assert.AreEqual(1, gamestate.Money[1], "money p1");
            Assert.AreEqual(2, gamestate.Money[2], "money p2");
            Assert.AreEqual(3, gamestate.Money[3], "money p3");
        }
Esempio n. 44
0
        public void Should_compile_and_execute()
        {
            _result = null;

            RulesEngine rulesEngine = RulesEngineFactory.New(x => { x.Add(_rule); });

            using (Session session = rulesEngine.CreateSession())
            {
                session.Add(new Order {
                    Name = "JOE", Amount = 10001.0m
                });
                session.Run();
            }

            var visitor = new TextRuntimeVisitor();

            rulesEngine.Accept(visitor);

            Console.WriteLine(visitor);

            Assert.IsNotNull(_result);
            Assert.IsNotNull(_resultB);
        }
Esempio n. 45
0
        public async Task ExecuteRule_RuntimeError_ShouldReturnAsErrorMessage()
        {
            var workflow = new WorkflowRules {
                WorkflowName = "TestWorkflow",
                Rules        = new[] {
                    new Rule {
                        RuleName   = "ruleWithRuntimeError",
                        Expression = "input1.Country.ToLower() == \"india\""
                    }
                }
            };

            var re    = new RulesEngine(new[] { workflow }, null, null);
            var input = new RuleTestClass {
                Country = null
            };

            var result = await re.ExecuteAllRulesAsync("TestWorkflow", input);

            Assert.NotNull(result);
            Assert.All(result, rule => Assert.False(rule.IsSuccess));
            Assert.All(result, rule => Assert.StartsWith("Error while executing rule :", rule.ExceptionMessage));
        }
Esempio n. 46
0
 /// <summary>
 /// Read the file line-by-line until EOF
 /// </summary>
 /// <returns>True, if the read was successful; False, otherwise</returns>
 public bool ReadLinesToEOF()
 {
     try
     {
         string temp;
         while ((temp = fileStream.ReadLine()) != null)
         {
             if (string.IsNullOrWhiteSpace(temp))
             {
                 continue;
             }
             temp        = temp.Replace("\t", "    ");
             LongestLine = (LongestLine.Length < temp.Length ? temp : LongestLine);
             rawLogEntries.Add(new LogEntry(temp));
         }
     }
     catch (Exception)
     {
         return(false);
     }
     filteredLogEntries = RulesEngine.FilterLogEntries(rawLogEntries);
     return(true);
 }
        private static void Main()
        {
            var rulesEngine = new RulesEngine<TicketHolder>();
            var ruleSet = rulesEngine.LoadRuleSetFromFile();

            Console.WriteLine("Press space to modify rules, otherwise press any key to execute the rules...");

            if (Console.ReadKey().Key == ConsoleKey.Spacebar)
            {
                ruleSet = rulesEngine.LaunchRulesDialog(ruleSet);
            }

            var ticketHolders = GetTicketHolders();

            Console.WriteLine("Before the rules are applied");
            DisplayTicketHolders(ticketHolders);

            ticketHolders.ForEach(ticketHolder => rulesEngine.ProcessRuleSet(ticketHolder, ruleSet));

            Console.WriteLine("After the rules are applied");
            DisplayTicketHolders(ticketHolders);

            Console.ReadKey();
        }
Esempio n. 48
0
        public async Task ExecuteRule_WithNullInput_ShouldNotThrowException()
        {
            var workflow = new WorkflowRules {
                WorkflowName = "Test",
                Rules        = new Rule[] {
                    new Rule {
                        RuleName = "RuleWithLocalParam",

                        RuleExpressionType = RuleExpressionType.LambdaExpression,
                        Expression         = "input1 == null || input1.hello.world = \"wow\""
                    }
                }
            };

            var re = new RulesEngine();

            re.AddWorkflow(workflow);

            var result1 = await re.ExecuteAllRulesAsync("Test", new RuleParameter("input1", value : null));

            Assert.True(result1.All(c => c.IsSuccess));


            var result2 = await re.ExecuteAllRulesAsync("Test", new object[] { null });

            Assert.True(result2.All(c => c.IsSuccess));

            dynamic input1 = new ExpandoObject();

            input1.hello       = new ExpandoObject();
            input1.hello.world = "wow";

            List <RuleResultTree> result3 = await re.ExecuteAllRulesAsync("Test", input1);

            Assert.True(result3.All(c => c.IsSuccess));
        }
Esempio n. 49
0
        /// <summary>
        /// Configures and creates a new rules engine instance
        /// </summary>
        /// <param name="configureCallback">The callback to perform the configuration</param>
        /// <returns>The new rules engine instance</returns>
        public static RulesEngine New(Action <EngineConfigurator> configureCallback)
        {
            if (configureCallback == null)
            {
                throw new ArgumentNullException("configureCallback");
            }

            var configurator = new OdoyuleEngineConfigurator();

            configureCallback(configurator);

            ConfigurationResult result = configurator.Validate();

            try
            {
                RulesEngine engine = configurator.Create();

                return(engine);
            }
            catch (Exception ex)
            {
                throw new RulesEngineConfigurationException(result, ex);
            }
        }
Esempio n. 50
0
        public void Execute(string psOrchestrationTestAddress = null, bool pbValidateWithinTransaction = false)
        {
            WonkaRefEnvironment RefEnv = WonkaRefEnvironment.GetInstance();

            Dictionary <string, WonkaBre.RuleTree.WonkaBreSource> SourceMap =
                new Dictionary <string, WonkaBre.RuleTree.WonkaBreSource>();

            string sDefaultSource    = "S";
            string sContractSourceId = sDefaultSource;
            string sContractAddress  = "";
            string sContractAbi      = "";
            string sOrchGetterMethod = "";
            string sOrchSetterMethod = "";

            // If a 'psOrchestrationTestAddress' value has been provided, it indicates that the user wishes
            // to use Orchestration
            if (!String.IsNullOrEmpty(psOrchestrationTestAddress))
            {
                // Here we set the values for Orchestration (like the target contract) and the implemented
                // methods that have the expected function signatures for getting/setting Attribute values
                sContractAddress  = psOrchestrationTestAddress;
                sContractAbi      = msAbiOrchTest;
                sOrchGetterMethod = "getAttrValueBytes32";
                sOrchSetterMethod = "setAttrValueBytes32";
            }
            else
            {
                sContractAddress  = msContractAddress;
                sContractAbi      = msAbiWonka;
                sOrchGetterMethod = "getValueOnRecord";
                sOrchSetterMethod = "";
            }

            // Here a mapping is created, where each Attribute points to a specific contract and its "accessor" methods
            // - the class that contains this information (contract, accessors, etc.) is of the WonkaBreSource type
            foreach (WonkaRefAttr TempAttr in moTargetAttrList)
            {
                WonkaBreSource TempSource =
                    new WonkaBreSource(sContractSourceId, msSenderAddress, msPassword, sContractAddress, sContractAbi, sOrchGetterMethod, sOrchSetterMethod, RetrieveValueMethod);

                SourceMap[TempAttr.AttrName] = TempSource;
            }

            // Creating an instance of the rules engine using our rules and the metadata
            WonkaBreRulesEngine RulesEngine = null;

            if (psOrchestrationTestAddress == null)
            {
                RulesEngine = new WonkaBreRulesEngine(new StringBuilder(msRulesContents), moMetadataSource);
            }
            else
            {
                RulesEngine = new WonkaBreRulesEngine(new StringBuilder(msRulesContents), SourceMap, moMetadataSource);
                RulesEngine.DefaultSource = sDefaultSource;
            }

            RulesEngine.SetDefaultStdOps(msPassword);

            // The contract dictates that the RuleTree (and its other info, like the Source mapping) is serialized
            // to the blockchain before interacting with it
            SerializeRulesEngineToBlockchain(RulesEngine);

            WonkaRefAttr AccountStsAttr = RefEnv.GetAttributeByAttrName("AccountStatus");
            WonkaRefAttr RvwFlagAttr    = RefEnv.GetAttributeByAttrName("AuditReviewFlag");

            // Gets a predefined data record that will be our analog for new data coming into the system
            // We are only using this record to test the .NET implementation
            WonkaProduct NewProduct = GetNewProduct();

            string sStatusValueBefore = GetAttributeValue(NewProduct, AccountStsAttr);
            string sFlagValueBefore   = GetAttributeValue(NewProduct, RvwFlagAttr);

            // SerializeProductToBlockchain(NewProduct);

            // Validate that the .NET implementation and the rules markup are both working properly
            WonkaBre.Reporting.WonkaBreRuleTreeReport Report = RulesEngine.Validate(NewProduct);

            string sStatusValueAfter = GetAttributeValue(NewProduct, AccountStsAttr);
            string sFlagValueAfter   = GetAttributeValue(NewProduct, RvwFlagAttr);

            if (Report.OverallRuleTreeResult == ERR_CD.CD_SUCCESS)
            {
                // NOTE: This should only be used for further testing
                // Serialize(NewProduct);
            }
            else if (Report.GetRuleSetFailureCount() > 0)
            {
                System.Console.WriteLine(".NET Engine says \"Oh heavens to Betsy! Something bad happened!\"");
            }
            else
            {
                System.Console.WriteLine(".NET Engine says \"What in the world is happening?\"");
            }

            // If a 'psOrchestrationTestAddress' value has been provided, it indicates that the user wishes
            // to use Orchestration
            if (!String.IsNullOrEmpty(psOrchestrationTestAddress))
            {
                /**
                ** Now execute the rules engine on the blockchain.
                **
                ** NOTE: Based on the value of the argument 'pbValidateWithinTransaction', we will act accordingly -
                **       If set to 'true', we issue a call() when we execute the rules engine, since we are only
                **       looking to validate here.  However, if the value if 'false', we issue a sendTransaction()
                **       so that we can attempts to set values (i.e., change the blockchain) will take effect.
                **       In that case, we might want to pull back the record afterwards with a subsequent function
                **       call, in order to examine the record here.
                **
                **/
                var BlockchainReport = ExecuteWithReport(RulesEngine, pbValidateWithinTransaction, SourceMap[RvwFlagAttr.AttrName]);

                if (BlockchainReport.NumberOfRuleFailures == 0)
                {
                    // Indication of a success
                }
                else if (BlockchainReport.NumberOfRuleFailures > 0)
                {
                    throw new Exception("Oh heavens to Betsy! Something bad happened!");
                }
                else
                {
                    throw new Exception("Seriously, what in the world is happening?!");
                }
            }
        }
Esempio n. 51
0
 public void Setup()
 {
     _engine = RulesEngineFactory.New(x => { });
 }
Esempio n. 52
0
 private static void InitCache()
 {
     string configKey = @"TestRule3.Config";
     RulesEngineConfigurationXmlProvider provider = new RulesEngineConfigurationXmlProvider(configKey);
     _engine = provider.GetRulesEngine();
 }
Esempio n. 53
0
        public override bool Visit(RulesEngine rulesEngine, Func <RuntimeVisitor, bool> next)
        {
            Append("Rules Engine");

            return(Indent(next));
        }
Esempio n. 54
0
 public GameView()
 {
     board = new ChessBoard(playerwhite, playerblack);
     rules = new RulesEngine(board);
 }
 public StatelessSession Create(RulesEngine rulesEngine)
 {
     return new StatelessSessionImpl(rulesEngine, ObjectCache);
 }
Esempio n. 56
0
 public void ProcessNumber_Should_Return_Even_For_4()
 {
     var fizzBuzz = new RulesEngine();
     var result = fizzBuzz.ProcessNumber(4);
     Assert.AreEqual("even", result);
 }
 public void Setup()
 {
     rulesEngine = new RulesEngine();
     var rule = new MeetsTheMinimumRequiredAccountBalance(100);
     RulesInitializer.RegisterRule<IAccountBalanceRules, decimal>(typeof(Account), () => rule);
 }
Esempio n. 58
0
        public void ProcessNumber_Should_Handle_Large_Input()
        {
            var fizzBuzz = new RulesEngine();
            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream);
            StreamReader reader = new StreamReader(stream);

            fizzBuzz.ProcessRange(999999, WriteOutput);
        }
Esempio n. 59
0
 public void ProcessNumber_Should_Return_Odd_For_1()
 {
     var fizzBuzz = new RulesEngine();
     var result = fizzBuzz.ProcessNumber(1);
     Assert.AreEqual("odd", result);
 }
Esempio n. 60
0
 public void ProcessNumbers_Should_Throw_Exception_For_Negative_Numbers()
 {
     var fizzBuzz = new RulesEngine();
     Assert.Throws<ArgumentOutOfRangeException>(() => fizzBuzz.ProcessRange(-1));
 }