### Initialize RulesEngine with Workflow Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Initializes the RulesEngine with a list of workflow rules. This C# code snippet demonstrates the setup required before executing any rules. ```csharp var workflowRules = //Get list of workflow rules declared in the json var re = new RulesEngine.RulesEngine(workflowRules); ``` -------------------------------- ### Implement Custom Action Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Create a class that extends ActionBase and implements the Run method for custom logic. This example shows a basic synchronous implementation. ```csharp public class MyCustomAction: ActionBase { public MyCustomAction(SomeInput someInput) { .... } public override ValueTask Run(ActionContext context, RuleParameter[] ruleParameters) { var customInput = context.GetContext("customContextInput"); //Add your custom logic here and return a ValueTask } ``` -------------------------------- ### Workflow Rules Schema Example Source: https://github.com/microsoft/rulesengine/wiki/Getting-Started This JSON defines a workflow for calculating discounts based on various input parameters. It includes multiple rules with different conditions and success events. ```json [ { "WorkflowName": "Discount", "Rules": [ { "RuleName": "GiveDiscount10", "SuccessEvent": "10", "ErrorMessage": "One or more adjust rules failed.", "ErrorType": "Error", "RuleExpressionType": "LambdaExpression", "Expression": "input1.country == \"india\" AND input1.loyalityFactor <= 2 AND input1.totalPurchasesToDate >= 5000 AND input2.totalOrders > 2 AND input3.noOfVisitsPerMonth > 2" }, { "RuleName": "GiveDiscount20", "SuccessEvent": "20", "ErrorMessage": "One or more adjust rules failed.", "ErrorType": "Error", "RuleExpressionType": "LambdaExpression", "Expression": "input1.country == \"india\" AND input1.loyalityFactor == 3 AND input1.totalPurchasesToDate >= 10000 AND input2.totalOrders > 2 AND input3.noOfVisitsPerMonth > 2" }, { "RuleName": "GiveDiscount25", "SuccessEvent": "25", "ErrorMessage": "One or more adjust rules failed.", "ErrorType": "Error", "RuleExpressionType": "LambdaExpression", "Expression": "input1.country != \"india\" AND input1.loyalityFactor >= 2 AND input1.totalPurchasesToDate >= 10000 AND input2.totalOrders > 2 AND input3.noOfVisitsPerMonth > 5" }, { "RuleName": "GiveDiscount30", "SuccessEvent": "30", "ErrorMessage": "One or more adjust rules failed.", "ErrorType": "Error", "RuleExpressionType": "LambdaExpression", "Expression": "input1.loyalityFactor > 3 AND input1.totalPurchasesToDate >= 50000 AND input1.totalPurchasesToDate <= 100000 AND input2.totalOrders > 5 AND input3.noOfVisitsPerMonth > 15" }, { "RuleName": "GiveDiscount35", "SuccessEvent": "35", "ErrorMessage": "One or more adjust rules failed.", "ErrorType": "Error", "RuleExpressionType": "LambdaExpression", "Expression": "input1.loyalityFactor > 3 AND input1.totalPurchasesToDate >= 100000 AND input2.totalOrders > 15 AND input3.noOfVisitsPerMonth > 25" } ] } ] ``` -------------------------------- ### Workflow Rules Schema Example Source: https://github.com/microsoft/rulesengine/blob/main/docs/Getting-Started.md This JSON defines a sample workflow with multiple rules for applying discounts based on various input conditions. It demonstrates the structure for 'WorkflowName', 'Rules', 'RuleName', 'SuccessEvent', 'ErrorMessage', 'RuleExpressionType', and 'Expression'. ```json [ { "WorkflowName": "Discount", "Rules": [ { "RuleName": "GiveDiscount10", "SuccessEvent": "10", "ErrorMessage": "One or more adjust rules failed.", "RuleExpressionType": "LambdaExpression", "Expression": "input1.country == \"india\" AND input1.loyalityFactor <= 2 AND input1.totalPurchasesToDate >= 5000 AND input2.totalOrders > 2 AND input3.noOfVisitsPerMonth > 2" }, { "RuleName": "GiveDiscount20", "SuccessEvent": "20", "ErrorMessage": "One or more adjust rules failed.", "RuleExpressionType": "LambdaExpression", "Expression": "input1.country == \"india\" AND input1.loyalityFactor == 3 AND input1.totalPurchasesToDate >= 10000 AND input2.totalOrders > 2 AND input3.noOfVisitsPerMonth > 2" }, { "RuleName": "GiveDiscount25", "SuccessEvent": "25", "ErrorMessage": "One or more adjust rules failed.`, "RuleExpressionType": "LambdaExpression", "Expression": "input1.country != \"india\" AND input1.loyalityFactor >= 2 AND input1.totalPurchasesToDate >= 10000 AND input2.totalOrders > 2 AND input3.noOfVisitsPerMonth > 5" }, { "RuleName": "GiveDiscount30", "SuccessEvent": "30", "ErrorMessage": "One or more adjust rules failed.", "RuleExpressionType": "LambdaExpression", "Expression": "input1.loyalityFactor > 3 AND input1.totalPurchasesToDate >= 50000 AND input1.totalPurchasesToDate <= 100000 AND input2.totalOrders > 5 AND input3.noOfVisitsPerMonth > 15" }, { "RuleName": "GiveDiscount35", "SuccessEvent": "35", "ErrorMessage": "One or more adjust rules failed.", "RuleExpressionType": "LambdaExpression", "Expression": "input1.loyalityFactor > 3 AND input1.totalPurchasesToDate >= 100000 AND input2.totalOrders > 15 AND input3.noOfVisitsPerMonth > 25" } ] } ] ``` -------------------------------- ### Example Rule Definition Source: https://github.com/microsoft/rulesengine/blob/main/README.md Defines discount rules for a workflow. Rules are expressed using lambda expressions and specify success events and error messages. ```json [ { "WorkflowName": "Discount", "Rules": [ { "RuleName": "GiveDiscount10", "SuccessEvent": "10", "ErrorMessage": "One or more adjust rules failed.", "RuleExpressionType": "LambdaExpression", "Expression": "input1.country == \"india\" AND input1.loyaltyFactor <= 2 AND input1.totalPurchasesToDate >= 5000" }, { "RuleName": "GiveDiscount20", "SuccessEvent": "20", "ErrorMessage": "One or more adjust rules failed.", "RuleExpressionType": "LambdaExpression", "Expression": "input1.country == \"india\" AND input1.loyaltyFactor >= 3 AND input1.totalPurchasesToDate >= 10000" } ] } ] ``` -------------------------------- ### Handling Success Event in Rules Engine Source: https://github.com/microsoft/rulesengine/wiki/Getting-Started Example of executing a rule and defining a success event handler to process the outcome, such as displaying a discount message. ```csharp List resultList = bre.ExecuteRule("Discount", inputs); resultList.OnSuccess((eventName) => { discountOffered = $"Discount offered is {eventName} % over MRP."; }); ``` -------------------------------- ### Define a Custom Utility Method Source: https://github.com/microsoft/rulesengine/wiki/Getting-Started Create a static class with utility methods to extend the capabilities of lambda expressions in rules. This example defines a method to check if a string exists within a comma-separated list. ```csharp using System; using System.Linq; namespace RE.HelperFunctions { public static class Utils { public static bool CheckContains(string check, string valList) { if (String.IsNullOrEmpty(check) || String.IsNullOrEmpty(valList)) return false; var list = valList.Split(',').ToList(); return list.Contains(check); } } } ``` -------------------------------- ### Initiating Rules Engine with JSON Configuration Source: https://github.com/microsoft/rulesengine/wiki/Getting-Started Shows how to create an instance of the Rules Engine using serialized JSON configuration strings. ```csharp public RulesEngine(string[] jsonConfig, ReSettings reSettings = null); ``` -------------------------------- ### Populate Rules Engine with Entity Framework Source: https://github.com/microsoft/rulesengine/blob/main/README.md Demonstrates how to retrieve workflows from a database using Entity Framework and initialize the Rules Engine. Ensure all nested rule levels are included with ThenInclude. ```csharp var wfr = db.Workflows.Include(i => i.Rules).ThenInclude(i => i.Rules).ToArray(); var bre = new RulesEngine.RulesEngine(wfr, null); ``` -------------------------------- ### Initiating Rules Engine with WorkflowRules Objects Source: https://github.com/microsoft/rulesengine/wiki/Getting-Started Illustrates creating a Rules Engine instance by directly providing workflow rules as WorkflowRules objects. ```csharp public RulesEngine(WorkflowRules[] workflowRules, ReSettings reSettings = null); ``` -------------------------------- ### Initiating the Rules Engine Source: https://github.com/microsoft/rulesengine/wiki/Getting-Started Demonstrates how to initialize the Rules Engine by injecting workflow rules, either from JSON configuration or directly as WorkflowRules objects. ```APIDOC ## Initiating the Rules Engine ### Description Initializes an instance of the Rules Engine by providing workflow rules. ### Constructors #### Constructor 1 * **Signature**: `public RulesEngine(string[] jsonConfig, ReSettings reSettings = null)` * **Description**: Initializes the Rules Engine with rules defined in serialized JSON strings. * **Parameters**: * `jsonConfig` (string[]) - An array of serialized JSON strings representing the rules schema. * `reSettings` (ReSettings, optional) - Custom settings for the Rules Engine. #### Constructor 2 * **Signature**: `public RulesEngine(WorkflowRules[] workflowRules, ReSettings reSettings = null)` * **Description**: Initializes the Rules Engine with an array of WorkflowRules objects. * **Parameters**: * `workflowRules` (WorkflowRules[]) - An array of WorkflowRules objects. * `reSettings` (ReSettings, optional) - Custom settings for the Rules Engine. ``` -------------------------------- ### Execute Workflow Rules with Input Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Executes all rules within a specified workflow ('Discount') using provided inputs. The results, including rule names and success status, are then printed to the console. ```csharp // Declare input1,input2,input3 var resultList = await re.ExecuteAllRulesAsync("Discount", input1,input2,input3); //Check success for rule foreach(var result in resultList){ Console.WriteLine($"Rule - {result.Rule.RuleName}, IsSuccess - {result.IsSuccess}"); } ``` -------------------------------- ### Implementing a Custom Action Source: https://github.com/microsoft/rulesengine/wiki/Actions Create a custom action by extending ActionBase and implementing the Run method. This method can contain synchronous or asynchronous logic and returns a ValueTask. ```csharp public class MyCustomAction: ActionBase { public MyCustomAction(SomeInput someInput) { .... } public override ValueTask Run(ActionContext context, RuleParameter[] ruleParameters) { var customInput = context.GetContext("customContextInput"); //Add your custom logic here and return a ValueTask } ``` ```csharp public class MyCustomAction: ActionBase { public MyCustomAction(SomeInput someInput) { .... } public override async ValueTask Run(ActionContext context, RuleParameter[] ruleParameters) { var customInput = context.GetContext("customContextInput"); //Add your custom logic here return await MyCustomLogicAsync(); } ``` -------------------------------- ### Define and Initialize Rules Engine Programmatically Source: https://github.com/microsoft/rulesengine/blob/main/README.md Creates a simple rule and workflow programmatically and initializes the Rules Engine. This is useful for in-code rule definitions. ```csharp List rules = new List(); Rule rule = new Rule(); rule.RuleName = "Test Rule"; rule.SuccessEvent = "Count is within tolerance."; rule.ErrorMessage = "Over expected."; rule.Expression = "count < 3"; rule.RuleExpressionType = RuleExpressionType.LambdaExpression; rules.Add(rule); var workflows = new List(); Workflow exampleWorkflow = new Workflow(); exampleWorkflow.WorkflowName = "Example Workflow"; exampleWorkflow.Rules = rules; workflows.Add(exampleWorkflow); var bre = new RulesEngine.RulesEngine(workflows.ToArray()); ``` -------------------------------- ### ExecuteRule Overloads for IRulesEngine Source: https://github.com/microsoft/rulesengine/wiki/Getting-Started Demonstrates the different overloaded methods available in the IRulesEngine interface for executing rules with various input types. ```csharp List ExecuteRule(string workflowName, IEnumerable input, object[] otherInputs); List ExecuteRule(string workflowName, object[] inputs); List ExecuteRule(string workflowName, object input); List ExecuteRule(string workflowName, RuleParameter[] ruleParams); ``` -------------------------------- ### Rules Engine Constructors Source: https://github.com/microsoft/rulesengine/blob/main/docs/Getting-Started.md Shows the two available constructors for initiating a RulesEngine instance, allowing injection of workflow rules via JSON configuration or WorkflowRules objects. ```csharp public RulesEngine(string[] jsonConfig, ILogger logger, ReSettings reSettings = null) public RulesEngine(WorkflowRules[] workflowRules, ILogger logger, ReSettings reSettings = null) ``` -------------------------------- ### Initialize Rules Engine Source: https://github.com/microsoft/rulesengine/blob/main/README.md Initializes the Rules Engine with a list of deserialized workflow objects. The workflow objects should conform to the defined schema. ```csharp var rulesEngine = new RulesEngine(workflow); ``` -------------------------------- ### Handling Success and Failure Events Source: https://github.com/microsoft/rulesengine/wiki/Getting-Started Illustrates how to define and handle success and failure events after executing rules, allowing for custom actions based on the outcome. ```APIDOC ## Success/Failure Event Handling ### Description Allows users to define actions to be triggered based on the success or failure of rule execution. ### Success Event * **Trigger**: Triggered when one or more rules pass based on the given input(s). * **Action**: Executes an event initialized as `SuccessEvent` in the Rules Schema. * **Example**: ```csharp List resultList = bre.ExecuteRule("Discount", inputs); resultList.OnSuccess((eventName) => { discountOffered = $"Discount offered is {eventName} % over MRP."; }); ``` ### Failure Event * **Trigger**: Triggered when none of the rules succeed. * **Action**: Executes a predefined failure event. * **Example**: ```csharp List resultList = bre.ExecuteRule("Discount", inputs); resultList.OnFail(() => { discountOffered = "The user is not eligible for any discount."; }); ``` ``` -------------------------------- ### Rules Engine Constructors Source: https://github.com/microsoft/rulesengine/blob/main/docs/Getting-Started.md These constructors are used to initiate an instance of the Rules Engine. You can provide workflow rules either as JSON configuration strings or as WorkflowRules objects. ```APIDOC ## Rules Engine Constructors ### Description Initiate the Rules Engine by providing workflow rules through JSON configuration or WorkflowRules objects, along with a logger and optional settings. ### Constructors #### RulesEngine (string[] jsonConfig, ILogger logger, ReSettings reSettings = null) - **jsonConfig** (string[]) - An array of serialized JSON strings following the Rules Schema. - **logger** (ILogger) - An instance of a logger. - **reSettings** (ReSettings, optional) - Custom settings for the Rules Engine. #### RulesEngine (WorkflowRules[] workflowRules, ILogger logger, ReSettings reSettings = null) - **workflowRules** (WorkflowRules[]) - An array of WorkflowRules objects. - **logger** (ILogger) - An instance of a logger. - **reSettings** (ReSettings, optional) - Custom settings for the Rules Engine. ``` -------------------------------- ### Handling Failure Event in Rules Engine Source: https://github.com/microsoft/rulesengine/wiki/Getting-Started Demonstrates how to execute a rule and define a failure event handler to be triggered when no rules succeed, such as informing the user about ineligibility. ```csharp List resultList = bre.ExecuteRule("Discount", inputs); resultList.OnFail(() => { discountOffered = "The user is not eligible for any discount."; }); ``` -------------------------------- ### Executing Rules and Accessing Action Output Source: https://github.com/microsoft/rulesengine/wiki/Actions Call the ExecuteAllRulesAsync method to run rules and then iterate through the results. The output of an action, if any, is available in the RuleResult.ActionResult.Output property. ```csharp var ruleResultList = await rulesEngine.ExecuteAllRulesAsync("inputWorkflow",ruleParameters); foreach(var ruleResult in ruleResultList){ if(ruleResult.ActionResult != null){ Console.WriteLine(ruleResult.ActionResult.Output); //ActionResult.Output contains the evaluated value of the action } } ``` -------------------------------- ### Implement Async Custom Action Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Implement an asynchronous custom action by making the Run method async and awaiting custom asynchronous logic. This allows for non-blocking operations within actions. ```csharp public class MyCustomAction: ActionBase { public MyCustomAction(SomeInput someInput) { .... } public override async ValueTask Run(ActionContext context, RuleParameter[] ruleParameters) { var customInput = context.GetContext("customContextInput"); //Add your custom logic here return await MyCustomLogicAsync(); } ``` -------------------------------- ### IRulesEngine ExecuteRule Overloads Source: https://github.com/microsoft/rulesengine/wiki/Getting-Started The IRulesEngine interface provides multiple overloaded methods to execute rules based on different input configurations. These methods allow for flexibility in how workflows and their associated inputs are processed. ```APIDOC ## IRulesEngine ExecuteRule Overloads ### Description Provides overloaded methods to execute rules with different input parameters. ### Methods #### ExecuteRule (Overload 1) * **Signature**: `List ExecuteRule(string workflowName, IEnumerable input, object[] otherInputs)` * **Description**: Executes rules for a given workflow using a collection of dynamic inputs and additional auxiliary inputs. * **Parameters**: * `workflowName` (string) - The name of the workflow to execute. * `input` (IEnumerable) - A list of dynamic inputs to be checked. * `otherInputs` (object[]) - An array of auxiliary inputs that complement the primary inputs based on the rules. #### ExecuteRule (Overload 2) * **Signature**: `List ExecuteRule(string workflowName, object[] inputs)` * **Description**: Executes rules for a given workflow using an array of inputs. * **Parameters**: * `workflowName` (string) - The name of the workflow to execute. * `inputs` (object[]) - An array of inputs to be checked. #### ExecuteRule (Overload 3) * **Signature**: `List ExecuteRule(string workflowName, object input)` * **Description**: Executes rules for a given workflow using a single input object. * **Parameters**: * `workflowName` (string) - The name of the workflow to execute. * `input` (object) - A single input object to be checked. #### ExecuteRule (Overload 4) * **Signature**: `List ExecuteRule(string workflowName, RuleParameter[] ruleParams)` * **Description**: Executes rules for a given workflow using an array of RuleParameters. * **Parameters**: * `workflowName` (string) - The name of the workflow to execute. * `ruleParams` (RuleParameter[]) - An array of RuleParameters. ``` -------------------------------- ### IRulesEngine ExecuteRule Overloads Source: https://github.com/microsoft/rulesengine/blob/main/docs/Getting-Started.md The IRulesEngine interface provides four overloaded methods to execute rules. These methods allow for flexibility in how workflows and inputs are provided. ```APIDOC ## IRulesEngine ExecuteRule Overloads ### Description These methods are used to execute rules defined in a workflow. They offer different ways to pass workflow names and inputs. ### Methods #### ExecuteRule (string workflowName, IEnumerable input, object[] otherInputs) - **workflowName** (string) - The name of the workflow to execute. - **input** (IEnumerable) - A list of dynamic inputs to be checked. - **otherInputs** (object[]) - An array of auxiliary inputs that complement the primary inputs. #### ExecuteRule (string workflowName, object[] inputs) - **workflowName** (string) - The name of the workflow to execute. - **inputs** (object[]) - An array of dynamic inputs to be checked. #### ExecuteRule (string workflowName, object input) - **workflowName** (string) - The name of the workflow to execute. - **input** (object) - A single dynamic input to be checked. #### ExecuteRule (string workflowName, RuleParameter[] ruleParams) - **workflowName** (string) - The name of the workflow to execute. - **ruleParams** (RuleParameter[]) - An array of RuleParameters. ### Returns - List - A list of RuleResultTree objects representing the results of the rule execution. ``` -------------------------------- ### Define Workflow Rules in JSON Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Defines a workflow named 'Discount' with two rules, 'GiveDiscount10' and 'GiveDiscount20', based on various input conditions. This JSON structure is used to configure the RulesEngine. ```json [{"WorkflowName": "Discount", "Rules": [{"RuleName": "GiveDiscount10", "Expression": "input1.country == \"india\" AND input1.loyalityFactor <= 2 AND input1.totalPurchasesToDate >= 5000 AND input2.totalOrders > 2 AND input3.noOfVisitsPerMonth > 2"},{"RuleName": "GiveDiscount20", "Expression": "input1.country == \"india\" AND input1.loyalityFactor == 3 AND input1.totalPurchasesToDate >= 10000 AND input2.totalOrders > 2 AND input3.noOfVisitsPerMonth > 2"}]}] ``` -------------------------------- ### Registering Custom Actions Source: https://github.com/microsoft/rulesengine/wiki/Actions Register custom actions by providing a dictionary of names to factory functions in ReSettings. This allows the RulesEngine to instantiate and use your custom actions. ```csharp var reSettings = new ReSettings{ CustomActions = new Dictionary>{ {"MyCustomAction", () => new MyCustomAction(someInput) } } }; var re = new RulesEngine(workflowRules,logger,reSettings); ``` -------------------------------- ### Define Workflow with Custom Input Names Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Defines a workflow with custom input names ('basicInfo', 'orderInfo', 'telemetryInfo') for its rules. This allows for more descriptive rule expressions compared to default 'inputX' naming. ```json [{"WorkflowName": "DiscountWithCustomInputNames", "Rules": [{"RuleName": "GiveDiscount10", "Expression": "basicInfo.country == \"india\" AND basicInfo.loyalityFactor <= 2 AND basicInfo.totalPurchasesToDate >= 5000 AND orderInfo.totalOrders > 2 AND telemetryInfo.noOfVisitsPerMonth > 2"},{"RuleName": "GiveDiscount20", "Expression": "basicInfo.country == \"india\" AND basicInfo.loyalityFactor == 3 AND basicInfo.totalPurchasesToDate >= 10000 AND orderInfo.totalOrders > 2 AND telemetryInfo.noOfVisitsPerMonth > 2"}]}] ``` -------------------------------- ### Inject Custom Static Class for Expression Evaluation Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Define a static utility class with custom methods. Add this class to ReSettings to make its methods callable within RulesEngine expressions. ```csharp using System; using System.Linq; namespace RE.HelperFunctions { public static class Utils { public static bool CheckContains(string check, string valList) { if (String.IsNullOrEmpty(check) || String.IsNullOrEmpty(valList)) return false; var list = valList.Split(',').ToList(); return list.Contains(check); } } } ``` ```csharp var reSettings = new ReSettings{ CustomTypes = new Type[] { typeof(Utils) } }; var rulesEngine = new RulesEngine.RulesEngine(workflowRules,reSettings); ``` ```json { "WorkflowName": "DiscountWithCustomInputNames", "Rules": [ { "RuleName": "GiveDiscount10", "Expression": "Utils.CheckContains(input1.country, \"india,usa,canada,France\") == true" } ] } ``` -------------------------------- ### Handling Success and Failure Events Source: https://github.com/microsoft/rulesengine/blob/main/docs/Getting-Started.md The Rules Engine allows you to define actions to be taken upon successful rule execution or upon failure when no rules are met. ```APIDOC ## Handling Success and Failure Events ### Description Define custom actions to be executed when rules succeed or fail based on the provided input. ### Success Event Triggered when one or more rules pass. The success event is based on the first rule that evaluates to true. #### Example ```csharp List resultList = bre.ExecuteRule("Discount", inputs); resultList.OnSuccess((eventName) => { discountOffered = $"Discount offered is {eventName} % over MRP."; }); ``` ### Failure Event Triggered when none of the rules succeed. #### Example ```csharp List resultList = bre.ExecuteRule("Discount", inputs); resultList.OnFail(() => { discountOffered = "The user is not eligible for any discount."; }); ``` ``` -------------------------------- ### Execute Rules with Custom Input Names Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Executes rules using custom input names by wrapping inputs in RuleParameter objects. This C# code demonstrates how to pass named inputs to the RulesEngine for execution. ```csharp var workflowRules = //Get list of workflow rules declared in the json var re = new RulesEngine.RulesEngine(workflowRules); // Declare input1,input2,input3 var rp1 = new RuleParameter("basicInfo",input1); var rp2 = new RuleParameter("orderInfo", input2); var rp3 = new RuleParameter("telemetryInfo",input3); var resultList = await re.ExecuteAllRulesAsync("DiscountWithCustomInputNames",rp1,rp2,rp3); ``` -------------------------------- ### Custom Logger Interface Implementation Source: https://github.com/microsoft/rulesengine/blob/main/docs/Getting-Started.md This C# code defines the methods for a custom logger interface. Implement these methods to integrate your preferred logging mechanism with the Rules Engine. ```csharp void LogTrace(string msg); void LogError(Exception ex); ``` -------------------------------- ### Register Custom Types with Rules Engine Source: https://github.com/microsoft/rulesengine/wiki/Getting-Started Configure the Rules Engine to recognize and use custom types by registering them during the engine's initialization. This allows custom methods to be invoked within rule expressions. ```csharp var reSettingsWithCustomTypes = new ReSettings { CustomTypes = new Type[] { typeof(Utils) } }; new RulesEngine.RulesEngine(workflowRules.ToArray(), null, reSettingsWithCustomTypes); ``` -------------------------------- ### Execute Rules Source: https://github.com/microsoft/rulesengine/blob/main/README.md Executes all rules for a given workflow name and input object. The response contains a list of RuleResultTree objects indicating rule pass/fail status. ```csharp List response = await rulesEngine.ExecuteAllRulesAsync(workflowName, input); ``` -------------------------------- ### Define Rule with Local Parameters Source: https://github.com/microsoft/rulesengine/wiki/Getting-Started Simplify complex rule logic by defining intermediate local parameters. These parameters can be reused within the main rule expression, improving readability and maintainability. ```json { "name": "allow_access_if_all_mandatory_trainings_are_done_or_access_isSecure", "errorMessage": "Please complete all your training(s) to get access to this content or access it from a secure domain/location.", "errorType": "Error", "localParams": [ { "name": "completedSecurityTrainings", "expression": "MasterSecurityComplainceTrainings.Where(Status.Equals(\"Completed\", StringComparison.InvariantCultureIgnoreCase))" }, { "name": "completedProjectTrainings", "expression": "MasterProjectComplainceTrainings.Where(Status.Equals(\"Completed\", StringComparison.InvariantCultureIgnoreCase))" }, { "name": "isRequestAccessSecured", "expression": "UserRequestDetails.Location.Country == \"India\" ? ((UserRequestDetails.Location.City == \"Bangalore\" && UserRequestDetails.Domain=\"xxxx\")? true : false):false" } ], "expression": "(completedSecurityTrainings.Any() && completedProjectTrainings.Any()) || isRequestAccessSecured " } ``` -------------------------------- ### Configure OutputExpression Action in a Rule Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Define the OutputExpression action within a rule's OnSuccess event to evaluate an expression and return its value. This is typically used to calculate a result based on input parameters. ```json { "WorkflowName": "inputWorkflow", "Rules": [ { "RuleName": "GiveDiscount10Percent", "SuccessEvent": "10", "ErrorMessage": "One or more adjust rules failed.", "RuleExpressionType": "LambdaExpression", "Expression": "input1.couy == \"india\" AND input1.loyalityFactor <= 2 AND input1.totalPurchasesToDate >= 5000 AND input2.totalOrders > 2 AND input2.noOfVisitsPerMonth > 2", "Actions": { "OnSuccess": { "Name": "OutputExpression", //Name of action you want to call "Context": { //This is passed to the action as action context "Expression": "input1.TotalBilled * 0.9" } } } } ] } ``` -------------------------------- ### Execute Chained Rules with ExecuteActionWorkflowAsync Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Call ExecuteActionWorkflowAsync to initiate a workflow and retrieve the output from the executed rule. This is used when rules are chained or when a specific rule needs to be executed. ```csharp var result = await rulesEngine.ExecuteActionWorkflowAsync("inputWorkflow","GiveDiscount20Percent",ruleParameters); Console.WriteLine(result.Output); //result.Output contains the evaluated value of the action ``` -------------------------------- ### Using a Registered Custom Action in Rule Definition Source: https://github.com/microsoft/rulesengine/wiki/Actions Reference your registered custom action by its name in the rule's OnSuccess or OnFailure block. Pass any necessary context data through the 'Context' property. ```json { "WorkflowName": "inputWorkflow", "Rules": [ { "RuleName": "GiveDiscount10Percent", "SuccessEvent": "10", "ErrorMessage": "One or more adjust rules failed.", "ErrorType": "Error", "RuleExpressionType": "LambdaExpression", "Expression": "input1.couy == \"india\" AND input1.loyalityFactor <= 2 AND input1.totalPurchasesToDate >= 5000 AND input2.totalOrders > 2 AND input2.noOfVisitsPerMonth > 2", "Actions": { "OnSuccess": { "Name": "MyCustomAction", //Name context "Context": { //This is passed to the action as action context "customContextInput": "input1.TotalBilled * 0.9" } } } } ] } ``` -------------------------------- ### Register Custom Action in ReSettings Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Register your custom action by providing a factory function within the CustomActions dictionary in ReSettings. This makes the action available to the RulesEngine. ```csharp var reSettings = new ReSettings{ CustomActions = new Dictionary>{ {"MyCustomAction", () => new MyCustomAction(someInput) } } }; var re = new RulesEngine(workflowRules,reSettings); ``` -------------------------------- ### Standalone Expression Evaluation Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Utilize RuleExpressionParser for evaluating expressions without the full RulesEngine. This is useful for simpler parsing and evaluation needs. ```csharp using System; using RulesEngine.Models; using RulesEngine.ExpressionBuilders; public class Program { public static void Main() { var reParser = new RuleExpressionParser(new ReSettings()); var result = reParser.Evaluate("a+b", new RuleParameter[]{ new RuleParameter("a","Hello "), new RuleParameter("b","World") }); Console.WriteLine(result); } ``` -------------------------------- ### Configure EvaluateRule Action for Rule Chaining Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Use the EvaluateRule action within a rule's OnFailure event to chain another rule. This allows for conditional execution of rules based on the success or failure of the preceding rule. ```json { "WorkflowName": "inputWorkflow", "Rules": [ { "RuleName": "GiveDiscount20Percent", "Expression": "input1.couy == \"india\" AND input1.loyalityFactor <= 5 AND input1.totalPurchasesToDate >= 20000", "Actions": { "OnSuccess": { "Name": "OutputExpression", //Name of action you want to call "Context": { "Expression": "input1.TotalBilled * 0.8" } }, "OnFailure": { // This will execute if the Rule evaluates to failure "Name": "EvaluateRule", "Context": { "workflowName": "inputWorkflow", "ruleName": "GiveDiscount10Percent" } } } }, { "RuleName": "GiveDiscount10Percent", "SuccessEvent": "10", "ErrorMessage": "One or more adjust rules failed.", "RuleExpressionType": "LambdaExpression", "Expression": "input1.couy == \"india\" AND input1.loyalityFactor <= 2 AND input1.totalPurchasesToDate >= 5000 AND input2.totalOrders > 2 AND input2.noOfVisitsPerMonth > 2", "Actions": { "OnSuccess": { "Name": "OutputExpression", //Name of action you want to call "Context": { "Expression": "input1.TotalBilled * 0.9" } } } } ] } ``` -------------------------------- ### Configure EvaluateRule with Input Filtering and Additional Inputs Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Customize the inputs passed to a chained rule using EvaluateRule's 'inputFilter' and 'additionalInputs' context properties. This allows for selective input passing and computed input generation for the chained rule. ```json "Actions": { "OnSuccess": { "Name": "EvaluateRule", "Context": { "workflowName": "inputWorkflow", "ruleName": "GiveDiscount10Percent", "inputFilter": ["input2"], //will only pass input2 from existing inputs,scopedparams to the chained rule "additionalInputs":[ { "Name": "currentDiscount", "Expression": "input1.TotalBilled * 0.9" } ] } } } ``` -------------------------------- ### Register Custom Type for Rule Evaluation Source: https://github.com/microsoft/rulesengine/blob/main/docs/Getting-Started.md Define a static utility class with custom methods to extend the capabilities of lambda expressions within the Rules Engine. This allows for more complex logic than what is directly supported by the .Net framework's System namespace. ```csharp using System; using System.Linq; namespace RE.HelperFunctions { public static class Utils { public static bool CheckContains(string check, string valList) { if (String.IsNullOrEmpty(check) || String.IsNullOrEmpty(valList)) return false; var list = valList.Split(',').ToList(); return list.Contains(check); } } } ``` ```json "Expression": "Utils.CheckContains(input1.country, \"india,usa,canada,France\") == true" ``` ```csharp var reSettingsWithCustomTypes = new ReSettings { CustomTypes = new Type[] { typeof(Utils) } }; new RulesEngine.RulesEngine(workflowRules.ToArray(), null, reSettingsWithCustomTypes); ``` -------------------------------- ### GlobalParams for Workflow-Level Aliases Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Define GlobalParams at the workflow level to create reusable aliases for expressions. These can be referenced in any rule within the workflow. ```json //Rule.json { "WorkflowName": "workflowWithGlobalParam", "GlobalParams":[ { "Name":"myglobal1", "Expression":"myInput.hello.ToLower()" } ], "Rules":[ { "RuleName": "checkGlobalEqualsHello", "Expression":"myglobal1 == \"hello\"" }, { "RuleName": "checkGlobalEqualsInputHello", "Expression":"myInput.hello.ToLower() == myglobal1" } ] } ``` ```csharp var input = new RuleParameter("myInput",new { hello = "HELLO" }); var resultList = await re.ExecuteAllRulesAsync("workflowWithGlobalParam",rp); ``` -------------------------------- ### OutputExpression Action in Rule Definition Source: https://github.com/microsoft/rulesengine/wiki/Actions Define the OutputExpression action within a rule's OnSuccess or OnFailure block to evaluate an expression and return its value. The evaluated output is accessible via ActionResult.Output. ```json { "WorkflowName": "inputWorkflow", "Rules": [ { "RuleName": "GiveDiscount10Percent", "SuccessEvent": "10", "ErrorMessage": "One or more adjust rules failed.", "ErrorType": "Error", "RuleExpressionType": "LambdaExpression", "Expression": "input1.couy == \"india\" AND input1.loyalityFactor <= 2 AND input1.totalPurchasesToDate >= 5000 AND input2.totalOrders > 2 AND input2.noOfVisitsPerMonth > 2", "Actions": { "OnSuccess": { "Name": "OutputExpression", //Name of action you want to call "Context": { //This is passed to the action as action context "Expression": "input1.TotalBilled * 0.9" } } } } ] } ``` -------------------------------- ### LocalParams for Rule-Level Aliases Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md Define LocalParams within a specific rule to create aliases for expressions scoped to that rule and its nested rules. LocalParams can be redefined in nested rules. ```json //Rule.json { "WorkflowName": "workflowWithLocalParam", "Rules":[ { "RuleName": "checkLocalEqualsHello", "LocalParams":[ { "Name":"mylocal1", "Expression":"myInput.hello.ToLower()" } ], "Expression":"mylocal1 == \"hello\"" }, { "RuleName": "checkLocalEqualsInputHelloInNested", "LocalParams":[ { "Name":"mylocal1", //redefined here as it is scoped at rule level "Expression":"myInput.hello.ToLower()" } ], "Operator": "And", "Rules":[ { "RuleName": "nestedRule", "Expression":"myInput.hello.ToLower() == mylocal1" //mylocal1 can be used here since it is nested to Rule where mylocal1 is defined } ] } ] } ``` ```csharp var rp = new RuleParameter("myInput",new { hello = "HELLO" }); var resultList = await re.ExecuteAllRulesAsync("workflowWithLocalParam",rp); ``` -------------------------------- ### Referencing ScopedParams in Other ScopedParams Source: https://github.com/microsoft/rulesengine/blob/main/docs/index.md ScopedParams can reference other ScopedParams defined earlier in the workflow or rule definition. This enables multi-step calculations and improved readability. ```json //Rule.json { "WorkflowName": "workflowWithReferencedRule", "GlobalParams":[ { "Name":"myglobal1", "Expression":"myInput.hello" } ], "Rules":[ { "RuleName": "checkGlobalAndLocalEqualsHello", "LocalParams":[ { "Name": "mylocal1", "Expression": "myglobal1.ToLower()" } ], "Expression":"mylocal1 == \"hello\"" }, { "RuleName": "checklocalEqualsInputHello", "LocalParams":[ { "Name": "mylocal1", "Expression": "myglobal1.ToLower()" }, { "Name": "mylocal2", "Expression": "myInput.hello.ToLower() == mylocal1" } ], "Expression":"mylocal2 == true" } ] } ``` ```csharp var input = new RuleParameter("myInput",new { hello = "HELLO" }); var resultList = await re.ExecuteAllRulesAsync("workflowWithReferencedRule",rp); ``` -------------------------------- ### Use Custom Type in Rule Expression Source: https://github.com/microsoft/rulesengine/wiki/Getting-Started Integrate a custom utility method into a rule's expression. The custom method is called directly within the JSON rule definition. ```json "Expression": "Utils.CheckContains(input1.country, \"india,usa,canada,France\") == true" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.