Your first workflow
In this tutorial you will define a few rules for an e-commerce discount, run them against three inputs and read the results. It takes about ten minutes. You need the .NET SDK and the RulesEngine package:
dotnet new console -n DiscountDemo
cd DiscountDemo
dotnet add package RulesEngine
The scenario
A customer gets a discount when conditions on three kinds of information are met:
| Input | Contains |
|---|---|
| Customer | country, loyaltyFactor, totalPurchasesToDate |
| Orders | totalOrders |
| Telemetry | noOfVisitsPerMonth |
| Discount | Conditions |
|---|---|
| 10% | India, loyalty factor 2 or less, at least 5,000 purchased, more than 2 orders, more than 2 visits a month |
| 20% | India, loyalty factor exactly 3, at least 10,000 purchased, more than 2 orders, more than 2 visits a month |
| 25% | Not India, loyalty factor 2 or more, at least 10,000 purchased, more than 2 orders, more than 5 visits a month |
1. Write the rules
Create discount.json. A workflow has a name and a list of rules. Each rule has a name and an Expression that evaluates to true or false. SuccessEvent is the value you read back when the rule passes, and ErrorMessage explains a failure.
[
{
"WorkflowName": "Discount",
"Rules": [
{
"RuleName": "GiveDiscount10",
"SuccessEvent": "10",
"ErrorMessage": "Not eligible for 10%: country is $(customer.country), loyalty factor is $(customer.loyaltyFactor).",
"Expression": "customer.country == \"india\" AND customer.loyaltyFactor <= 2 AND customer.totalPurchasesToDate >= 5000 AND orders.totalOrders > 2 AND telemetry.noOfVisitsPerMonth > 2"
},
{
"RuleName": "GiveDiscount20",
"SuccessEvent": "20",
"ErrorMessage": "Not eligible for 20%.",
"Expression": "customer.country == \"india\" AND customer.loyaltyFactor == 3 AND customer.totalPurchasesToDate >= 10000 AND orders.totalOrders > 2 AND telemetry.noOfVisitsPerMonth > 2"
},
{
"RuleName": "GiveDiscount25",
"SuccessEvent": "25",
"ErrorMessage": "Not eligible for 25%.",
"Expression": "customer.country != \"india\" AND customer.loyaltyFactor >= 2 AND customer.totalPurchasesToDate >= 10000 AND orders.totalOrders > 2 AND telemetry.noOfVisitsPerMonth > 5"
}
]
}
]
The rules refer to the inputs by the names customer, orders and telemetry. You choose those names in the next step. The $(customer.country) placeholders in an ErrorMessage are filled in with the real values when the rule fails.
Make sure the file is copied to the output folder, for example by adding this to the .csproj:
<ItemGroup>
<None Update="discount.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
2. Load the workflow and run it
Replace Program.cs:
using System.Text.Json;
using RulesEngine.Extensions;
using RulesEngine.Models;
var workflows = JsonSerializer.Deserialize<Workflow[]>(File.ReadAllText("discount.json"));
var engine = new RulesEngine.RulesEngine(workflows);
var customer = new { country = "india", loyaltyFactor = 3, totalPurchasesToDate = 10000 };
var orders = new { totalOrders = 5 };
var telemetry = new { noOfVisitsPerMonth = 10 };
List<RuleResultTree> results = await engine.ExecuteAllRulesAsync(
"Discount",
new RuleParameter("customer", customer),
new RuleParameter("orders", orders),
new RuleParameter("telemetry", telemetry));
foreach (var result in results)
{
Console.WriteLine($"{result.Rule.RuleName}: {(result.IsSuccess ? "pass" : "fail")} {result.ExceptionMessage}");
}
results.OnSuccess(eventName => Console.WriteLine($"Discount offered: {eventName}%"));
results.OnFail(() => Console.WriteLine("No discount."));
Run it with dotnet run. You should see:
GiveDiscount10: fail Not eligible for 10%: country is india, loyalty factor is 3.
GiveDiscount20: pass
GiveDiscount25: fail Not eligible for 25%.
Discount offered: 20%
What happened
new RulesEngine.RulesEngine(workflows)validated the workflows and stored them. Nothing was compiled yet.ExecuteAllRulesAsynccompiled the three expressions the first time (and caches them for the next call), then evaluated every rule and returned oneRuleResultTreeper rule.IsSuccesstells you whether the rule passed. For a failed rule,ExceptionMessageholds the formattedErrorMessage; for a passing rule it is empty.OnSuccesscalls your callback for the first rule that passed, with itsSuccessEvent(or the rule name when there is none).OnFailcalls its callback only when all rules failed.
Try it
- Change
loyaltyFactorto1and run again: nowGiveDiscount10passes, andOnSuccessreports the first passing rule in the list. - Pass plain inputs instead of named ones:
engine.ExecuteAllRulesAsync("Discount", customer, orders, telemetry)names theminput1,input2andinput3, so the expressions would have to use those names. - Make an expression invalid, for example
customer.countri == "india", and read theExceptionMessage. By default errors are reported as messages instead of exceptions; see Error handling.