DEV Community

Cover image for Understanding MS Rules Engine In-Built Post Rule Actions — Part 4
vamsi dogiparthi
vamsi dogiparthi

Posted on • Originally published at Medium

Understanding MS Rules Engine In-Built Post Rule Actions — Part 4

Evaluate Rule JSON syntax

Hi Buddy! Welcome back to the part 4 of the MS Rules Engine series. In this article we will be concentrating on how to use different in-built post rule action to create a chain of rule executions.

So, lets dive into the next steps.

Configuring EvaluateRule built-in action

In this section, let’s explore how to configure EvaluateRule built-in action to create a chain of rule executions where you want to execute set of rules one after the other during OnSuccess or OnFailure of the parent rule.

Use Case:

To demonstrate this functionality, let’s take a use case we used in the previous article. which is in arcade business where we have to check the inventory of certain genre games belonging to a platform

When the inventory falls below a threshold, we want to calculate the quantity of games that we need to reorder for the genre and platform in question.

In this article we will try to create two level nested rule for quantity falling below 10 and 5.

Step by Step Implementation:

  • Download the base code from Github Repo.
  • Add a class named RestockingChainRulesExample.cs into your project root folder.
  • Add a new JSON rule named RestockingChainRules.json to your RulesFiles folder.
  • Add below content to the above created Json file.
[
  {
    "WorkflowName": "RestockingChainRules",
    "Rules": [
      {
        "RuleName": "ActionPlaystationGameRestock1",
        "ErrorMessage": "The action game stocks for the playstation are low. Restock by 5 units",
        "ErrorType": "Error",
        "SuccessEvent": "5",
        "RuleExpressionType": "LambdaExpression",
        "Expression": "input1.Where(x => x.Genre == \"Action\" AND x.Platform == \"PlayStation\").Sum(x => x.Quantity) < 5",
        "Actions": {
          "OnSuccess": {
            "Name": "OutputExpression",
            "Context": {
              "Expression": "input1.Where(x => x.Genre == \"Action\" AND x.Platform == \"PlayStation\").Sum(x => x.Quantity) * 5"
            }
          },
          "OnFailure": {
            "Name": "EvaluateRule",
            "Context": {
              "workflowName": "RestockingChainRules",
              "ruleName": "ActionPlaystationGameRestock2"
            }
          }
        }
      },
      {
        "RuleName": "ActionPlaystationGameRestock2",
        "ErrorMessage": "The action game stocks for the playstation are low. Restock by 10 units",
        "ErrorType": "Error",
        "SuccessEvent": "10",
        "RuleExpressionType": "LambdaExpression",
        "Expression": "input1.Where(x => x.Genre == \"Action\" AND x.Platform == \"PlayStation\").Sum(x => x.Quantity) < 10",
        "Actions": {
          "OnSuccess": {
            "Name": "OutputExpression",
            "Context": {
              "Expression": "input1.Where(x => x.Genre == \"Action\" AND x.Platform == \"PlayStation\").Sum(x => x.Quantity) * 10"
            }
          }
        }
      }
    ]
  }
]
Enter fullscreen mode Exit fullscreen mode
  • Modify the Game.cs model class under model's folder to include a new property called Quantity of type integer as show below.
namespace MsRulesEngine.Models;
public class Game {
    public string Title { get; set; } = string.Empty;
    public string Genre { get; set; } = string.Empty;
    public long Id { get; set; }
    public string Platform { get; set; } = string.Empty;    
    public string GamingStudio { get; set; } = string.Empty;
    public decimal Price { get; set; }
    public int Quantity { get; set; }
}
Enter fullscreen mode Exit fullscreen mode
  • Lets now add some code to our new RestockingChainRulesExample.cs class file as shown below.
using RE = RulesEngine;

namespace MsRulesEngine;
public class RestockingChainRulesExample
{
    public static async Task Run()
    {

        string filePath = Path.Combine(Environment.CurrentDirectory, "RulesFiles", "RestockingChainRules.json");
        Console.WriteLine(filePath);
        string jsonString = File.ReadAllText(filePath);

        var workflows = JsonSerializer.Deserialize<Workflow[]>(jsonString);


        var gamesInventory = new List<Game>
        {
            new() {
                Title = "Halo",
                Genre = "Action",
                Id = 1,
                Platform = "PlayStation",
                GamingStudio = "Sony",
                Price = 59.99m,
                Quantity = 5
            },
            new() {
                Title = "Yakuza",
                Genre = "Action",
                Id = 2,
                Platform = "PlayStation",
                GamingStudio = "EA",
                Price = 49.99m,
                Quantity = 2
            },
        };

        var ruleParameters = new RuleParameter[] {
        new ("input1", gamesInventory),
      };


        RE.RulesEngine rulesEngine = new(workflows);

        var result = await rulesEngine.ExecuteActionWorkflowAsync("RestockingChainRules", "ActionPlaystationGameRestock1", ruleParameters);


        Console.WriteLine($"Rule: {result.Output}");
    }

}
Enter fullscreen mode Exit fullscreen mode
  • Modify the program.cs as shown below and execute the application.
// See https://aka.ms/new-console-template for more information

using MsRulesEngine;

await RestockingChainRulesExample.Run();
Enter fullscreen mode Exit fullscreen mode
  • You will observe the below output. It calculates 10 as restock quantity for PlayStation Action games and 50 for Xbox RPG games.

Restocking Chain Rules Output

Advantages of EvaluateRule:

  • You execute chain of rules to find the matching one.
  • Easy to change the rule chaining process.
  • Can be mixed with OutputExpression action to stop the chain execution and terminal condition.

Conclusion:

In our day-to-day business, we come across many scenarios where we want to perform various calculations or return different outputs out of a rule execution based on its OnSuccess and OnFailure we want to usually check if there are any sub rules it satisfies as shown in the current article.

This dynamic behavior helps us perform appropriate chaining process. Also, because of its dynamic nature we can easily change the chaining process as the business changes.

Hope this article will help you understand the use of built-in EvaluateRule Action and provide you guidance to use it for your needs.

To access my source code. Please go to my Github Link. In my next article I will explain about Nested Rules. Please don’t forget to check it out.

To get more articles like this, please follow me to get notification when it is available.

Until then see ya soon! 😁

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay