public static ISessionFactory Compile(this INRulesRepository repository, IEnumerable <RuleGroup> groups)
        {
            var             compiler = new RuleCompiler();
            ISessionFactory factory  = compiler.Compile(repository.GetRuleSets(groups));

            return(factory);
        }
Пример #2
0
        public void Compile_CancellationRequested()
        {
            using (var cancellationSource = new CancellationTokenSource())
            {
                // Arrange
                var ruleCompiler = new RuleCompiler();

                var rule1 = CreateRuleDefinitionMock();
                var rule2 = CreateRuleDefinitionMock();
                rule2.Setup(r => r.LeftHandSide).Returns(() =>
                {
                    cancellationSource.Cancel();
                    return(new AndElement(Enumerable.Empty <RuleElement>()));
                });

                var rule3 = CreateRuleDefinitionMock();
                var rules = new[] { rule1.Object, rule2.Object, rule3.Object };

                // Act
                ruleCompiler.Compile(rules, cancellationSource.Token);

                // Assert
                rule1.Verify(r => r.LeftHandSide, Times.AtLeastOnce);
                rule2.Verify(r => r.LeftHandSide, Times.AtLeastOnce);
                rule3.Verify(r => r.LeftHandSide, Times.Never);
            }
        }
Пример #3
0
        private static void RunNrules()
        {
            //Load rules
            RuleRepository repository = new RuleRepository();

            repository.Load(x => x.From(typeof(DiscountRule).Assembly));

            //Compile rules
            RuleCompiler compiler       = new RuleCompiler();
            var          sessionFactory = compiler.Compile(repository.GetRuleSets());

            //Create a working session
            var session = sessionFactory.CreateSession();

            //Load domain model
            var customer = new Customer("John Doe")
            {
                IsPreferred = true
            };
            var order1 = new Order(123456, customer, 2, 25.0);
            var order2 = new Order(123457, customer, 1, 100.0);

            //Insert facts into rules engine's memory
            //session.Insert(customer);
            //session.Insert(order1);
            //session.Insert(order2);

            //Start match/resolve/act cycle
            var rulesExecuted = session.Fire();

            Console.WriteLine("Rules executed: {0}", rulesExecuted.ToString());

            //Insert facts into rules engine's memory
            session.InsertAll(new List <object> {
                customer, order2, order1
            });

            var customer2 = new Customer("Test customer")
            {
                IsPreferred = true
            };

            //var order3 = new Order(1234, customer2, 2, 25.0);

            //Insert facts into rules engine's memory
            session.InsertAll(new List <object> {
                customer2
            });

            rulesExecuted = session.Fire();
            Console.WriteLine("Rules executed: {0}", rulesExecuted.ToString());


            rulesExecuted = session.Fire();
            Console.WriteLine("Rules executed: {0}", rulesExecuted.ToString());
        }
Пример #4
0
        protected override ISessionFactory Compile()
        {
            var compiler = new RuleCompiler();

            compiler.AggregatorRegistry.RegisterFactory("CustomSelect", typeof(CustomSelectAggregateFactory));

            var factory = compiler.Compile(Repository.GetRules());

            return(factory);
        }
Пример #5
0
        private static void Main(string[] args)
        {
            var dwelling = new Dwelling {
                Address = "1 Main Street, New York, NY", Type = DwellingTypes.SingleHouse
            };
            var dwelling2 = new Dwelling {
                Address = "2 Main Street, New York, NY", Type = DwellingTypes.SingleHouse
            };
            var policy1 = new Policy {
                Name = "Silver", PolicyType = PolicyTypes.Home, Price = 1200, Dwelling = dwelling
            };
            var policy2 = new Policy {
                Name = "Gold", PolicyType = PolicyTypes.Home, Price = 2300, Dwelling = dwelling2
            };
            var customer1 = new Customer {
                Name = "John Do", Age = 22, Sex = SexTypes.Male, Policy = policy1
            };
            var customer2 = new Customer {
                Name = "Emily Brown", Age = 32, Sex = SexTypes.Female, Policy = policy2
            };

            var repository = new RuleRepository();

            repository.Load("Test", x => x.From(typeof(Program).Assembly));
            var ruleSets = repository.GetRuleSets();

            IRuleCompiler   compiler = new RuleCompiler();
            ISessionFactory factory  = compiler.Compile(ruleSets);
            ISession        session  = factory.CreateSession();

            session.Insert(policy1);
            session.Insert(policy2);
            session.Insert(customer1);
            session.Insert(customer2);
            session.Insert(dwelling);
            session.Insert(dwelling2);

            customer1.Age = 10;
            session.Update(customer1);

            session.Retract(customer2);

            session.Fire();

            session.Insert(customer2);

            session.Fire();

            customer1.Age = 30;
            session.Update(customer1);

            session.Fire();
        }
Пример #6
0
        public static void RunRestockRules(Item item)
        {
            RuleRepository repository = new RuleRepository();

            repository.Load(x => x.From(typeof(RestockRule).Assembly));

            RuleCompiler compiler       = new RuleCompiler();
            var          sessionFactory = compiler.Compile(repository.GetRuleSets());

            //Create a working session
            var session = sessionFactory.CreateSession();

            session.Insert(item);
            session.Fire();
        }
Пример #7
0
        public Processor()
        {
            repository = new RuleRepository();
            sessions   = new Dictionary <string, Lazy <ISessionFactory> >();

            var rc = new RuleCompiler();

            var addFactory = new Lazy <ISessionFactory>(() =>
            {
                repository.Load(x => x.To("add").From(typeof(AddRule <T>)));
                var addRuleset = repository.GetRuleSets().Single(r => r.Name == "add");
                return(rc.Compile(addRuleset.Rules) /*.Log()*/);
            });

            sessions.Add("add", addFactory);
        }
Пример #8
0
        public static void RunDiscountRulesForItems(List <OrderItem> items)
        {
            RuleRepository repository = new RuleRepository();

            repository.Load(x => x.From(typeof(AddAllItemDiscountsRule).Assembly));

            RuleCompiler compiler       = new RuleCompiler();
            var          sessionFactory = compiler.Compile(repository.GetRuleSets());

            //Create a working session
            var session = sessionFactory.CreateSession();

            session.InsertAll(items);


            session.Fire();
        }
Пример #9
0
        public static void Run(string[] args)
        {
            Console.WriteLine("Parse Rules Compiler");
            Console.WriteLine();

            if (args.Length < 2)
            {
                Console.WriteLine("Usage: cprc <inputfile> <outputfile>");
                return;
            }

            using (TextReader r = File.OpenText(args[0]))
            {
                RuleCompiler compiler = new RuleCompiler(r);
                compiler.Compile(args[1]);
            }
        }
Пример #10
0
        public static void RunCreditsRules(Order order)
        {
            RuleRepository repository = new RuleRepository();

            repository.Load(x => x.From(Assembly.GetExecutingAssembly()));

            RuleCompiler compiler       = new RuleCompiler();
            var          sessionFactory = compiler.Compile(repository.GetRuleSets());

            //Create a working session
            var session = sessionFactory.CreateSession();

            System.Diagnostics.Debug.WriteLine("After: " + order.Customer.BonusCredits);

            session.Insert(order);
            session.Fire();

            System.Diagnostics.Debug.WriteLine("After: " + order.Customer.BonusCredits);
        }
Пример #11
0
        public void Setup()
        {
            var rules = new List <IRuleDefinition>();

            for (int i = 1; i <= RuleCount; i++)
            {
                var rule = BuildRule(i);
                rules.Add(rule);
            }

            var compiler = new RuleCompiler();

            Factory = compiler.Compile(rules);

            _facts1 = new TestFact1[FactCount];
            for (int i = 0; i < FactCount; i++)
            {
                _facts1[i] = new TestFact1 {
                    IntProperty = i
                };
            }
        }
Пример #12
0
        public string Run()
        {
            //Load rules
            var repository = new RuleRepository();

            repository.Load(x => x.From(typeof(PreferredCustomerDiscountRule).Assembly).To("testRuleSet"));

            var ruleSets = repository.GetRuleSets();
            var compiler = new RuleCompiler();
            //Compile rules
            ISessionFactory factory = compiler.Compile(ruleSets.Where(x => x.Name == "testRuleSet"));

            //Create a working session
            var session = factory.CreateSession();

            //Load domain model
            var customer = new Customer("John Doe")
            {
                IsPreferred = true
            };
            var order1 = new Order(123456, customer, 2, 25.0);
            var order2 = new Order(123457, customer, 1, 100.0);

            //Insert facts into rules engine's memory
            session.Insert(customer);
            session.Insert(order1);
            session.Insert(order2);

            //Start match/resolve/act cycle
            session.Fire();

            Order ret = session.Query <Order>().Where(x => x.Id == 123456).FirstOrDefault();

            Order ret1 = session.Query <Order>().Where(x => x.Id == 123457).FirstOrDefault();

            return("true");
        }
        /// <summary>
        /// Constructor to create logger and tasks and queue parametrization
        /// </summary>
        public ExecutionDataflowEngineProcessing()
        {
            BagTMLog.LogDebug("BagTM Engine Processing Constructor", this);

            config = ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None) as Configuration;

            hub = this.GetAppSetting(config, "hub");
            if (hub == null)
            {
                throw new EngineProcessingException("No hub defined to process TTY messages");
            }

            airline = this.GetAppSetting(config, "airline");
            if (airline == null)
            {
                throw new EngineProcessingException("No airline defined to process TTY messages");
            }

            BagTMLog.LogDebug("BagTM Engine Processing hub ", hub);

            String timeSpanParameter = this.GetAppSetting(config, "timeSpan");
            int    timeSpanNumber    = 0;

            if (!int.TryParse(timeSpanParameter, out timeSpanNumber))
            {
                throw new EngineProcessingException("Parameter TimeSpan incorrectly configured");
            }

            this.timeSpan = new TimeSpan((Int64)(timeSpanNumber * TimeSpan.TicksPerMillisecond));

            BagTMLog.LogDebug("BagTM Engine Processing Constructor timeSpanNumber", this.timeSpan);

            String parallelismCounterParameter = this.GetAppSetting(config, "parallelismCounter");

            if (!int.TryParse(parallelismCounterParameter, out this.parallelismCounter))
            {
                throw new EngineProcessingException("Parameter ParallelismCounter incorrectly configured");
            }

            BagTMLog.LogDebug("BagTM Engine Processing Constructor parallelismCounterParameter", parallelismCounterParameter);

            queueEngine       = this.CreateMessageQueue(QUEUEENGINE);
            queueEngineSucess = this.CreateMessageQueue(QUEUESUCESS);
            queueEngineError  = this.CreateMessageQueue(QUEUEERROR);

            BagTMLog.LogDebug("BagTM Engine Processing Constructor queueEngine", queueEngine);
            BagTMLog.LogDebug("BagTM Engine Processing Constructor queueEngineSucess", queueEngineSucess);
            BagTMLog.LogDebug("BagTM Engine Processing Constructor queueEngineError", queueEngineError);

            baggageTerminalCode = this.GetAppSetting(config, "baggageTerminal");
            if (baggageTerminalCode == null)
            {
                throw new EngineProcessingException("No baggage terminal configured");
            }

            String sorterTimeParameter = this.GetAppSetting(config, "sorterTime");

            if (!int.TryParse(sorterTimeParameter, out sorterTime))
            {
                throw new EngineProcessingException("Parameter sorter time incorrectly configured");
            }

            String etcgParameter = this.GetAppSetting(config, "etcg");

            if (!int.TryParse(sorterTimeParameter, out etcg))
            {
                throw new EngineProcessingException("Parameter estimated time to close gate incorrectly configured");
            }

            defaultEquipment = this.GetAppSetting(config, "defaultEquipment");
            if (!int.TryParse(defaultEquipment, out int aux))
            {
                throw new EngineProcessingException("Parameter default equipment incorrectly configured");
            }

            defaultStandFrom = this.GetAppSetting(config, "defaultStandFrom");
            if (defaultStandFrom == null)
            {
                throw new EngineProcessingException("No default stand from configured");
            }

            defaultGateTo = this.GetAppSetting(config, "defaultGateTo");
            if (defaultGateTo == null)
            {
                throw new EngineProcessingException("No default stand to configured");
            }

            String maxPaxTurnaroundParameter = this.GetAppSetting(config, "maxPaxTurnaround");

            if (!int.TryParse(maxPaxTurnaroundParameter, out this.maxPaxTurnaround))
            {
                throw new EngineProcessingException("No max pax turnaround configured");
            }

            String maxBaggageTurnaroundParameter = this.GetAppSetting(config, "maxBaggageTurnaround");

            if (!int.TryParse(maxBaggageTurnaroundParameter, out this.maxBaggageTurnaround))
            {
                throw new EngineProcessingException("No max baggage turnaround configured");
            }

            String maxSorterThroughPutParameter = this.GetAppSetting(config, "maxSorterThroughPut");

            if (!int.TryParse(maxSorterThroughPutParameter, out this.maxSorterThroughPut))
            {
                throw new EngineProcessingException("No max sorter through put configured");
            }

            String minLoadUnloadTimeParameter = this.GetAppSetting(config, "minLoadUnloadTime");

            if (!int.TryParse(minLoadUnloadTimeParameter, out this.minLoadUnloadTime))
            {
                throw new EngineProcessingException("No min load / unload configured");
            }

            String maxLoadUnloadTimeParameter = this.GetAppSetting(config, "maxLoadUnloadTime");

            if (!int.TryParse(maxLoadUnloadTimeParameter, out this.maxLoadUnloadTime))
            {
                throw new EngineProcessingException("No max load / unload configured");
            }

            //Load rules
            var repository = new RuleRepository();

            Type[] ruleTypes = new Type[13];
            repository.Load(x => x
                            .From(Assembly.GetExecutingAssembly()).To("BagTMRuleSet")
                            .Where(r => r.IsTagged("BagIntegrity")));

            BagTMLog.LogDebug("BagTM Engine Processing Constructor repository", repository);

            //Compile rules
            var ruleSets = repository.GetRuleSets();
            var compiler = new RuleCompiler();

            factory = compiler.Compile(ruleSets);

            //Create a working session
            factory.Events.FactInsertedEvent      += BagRulesEventMonitorization.OnFactInsertedEvent;
            factory.Events.FactUpdatedEvent       += BagRulesEventMonitorization.OnFactUpdatedEvent;
            factory.Events.FactRetractedEvent     += BagRulesEventMonitorization.OnFactRetractedEvent;
            factory.Events.ActivationCreatedEvent += BagRulesEventMonitorization.OnActivationCreatedEvent;
            factory.Events.ActivationUpdatedEvent += BagRulesEventMonitorization.OnActivationUpdatedEvent;
            factory.Events.ActivationDeletedEvent += BagRulesEventMonitorization.OnActivationDeletedEvent;
            factory.Events.RuleFiringEvent        += BagRulesEventMonitorization.OnRuleFiringEvent;
            factory.Events.RuleFiredEvent         += BagRulesEventMonitorization.OnRuleFireEvent;
            factory.Events.ActionFailedEvent      += BagRulesEventMonitorization.OnActionFailedEvent;
            factory.Events.ConditionFailedEvent   += BagRulesEventMonitorization.OnConditionFailedEvent;

            this.sorterVolumeMap = new SorterProcessingVolumeMap();

            BagTMLog.LogDebug("BagTM Engine Processing Constructor factory", factory);

            this.RefreshRefLists();

            BagTMLog.LogDebug(
                String.Format("BagTM Engine Processing Task Process Message Define Dataflow Block Parallelism Counter {0}", parallelismCounter)
                , this);

            BagTMLog.LogDebug("BagTM Engine Processing Constructor Ending", this);
        }