static void IRuleExample() { // Create an input object (component) var customer = new Customer { ID = 1, Name = "Amitabh" }; // Create an output object (discount) var discount = new CustomerDiscount(); // Create a new rule for xmas seasson SeasonDiscount seasonal = new SeasonDiscount(new DateTime(2019, 12, 15), new DateTime(2019, 12, 25), 5); // Populate the engine var engine = new RulesEngine(component: customer, output: discount); engine.AddRule(new Rule(seasonal)); // Run the rule var result = engine.RunAllRules(); // Check if we got the discount Console.WriteLine($"Seasonal discount {discount.Discount}"); // Let's inspect the result Console.WriteLine(result); }
public bool RuleMethod(object component, object output) { CustomerDiscount discountObj = (CustomerDiscount)output; if (DateTime.Today >= SeasonStart && DateTime.Today <= SeasonEnd) { discountObj.Discount += this.Discount; } return(true); }
static bool seniorCitizenDiscount(Customer customer, CustomerDiscount discount) { var span = (DateTime.Today - customer.Birthdate); int age = span.Days / 365; if (age > 60) { discount.Discount = Math.Max(discount.Discount, 20); } return(true); }
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()); }