Data Filter Rule Engine using Expression

Introduction

 
Architecture has an elegance and a purpose. For a given set of data, consider rows of a table consisting of meaningful data. Like in a loan, a financial product, there can be a number of different types of rules, like the total amount should be greater than 10000, the total amount should be greater than the balance amount, client name should not be blank and so on. Architecture in this article assumes that assorted such rules can be classified in classes and can be reused many times later, and if the need arises, the new type of rules can be created and integrated into the application. In this article, I will discuss only two types of rules: validation of a field and comparison of any two fields of the same dataset.
 

Approach

 
There are mainly 4 classes in this small application.
  1. FpProduct, representing a financial product, this represents entity.
  2. FpProductsEntities, this represents the collection of financial product ie. FpProduct. 
  3. ClassVisitValidateField to validate the fields of FpProduct in collection named FpProductsEntities 
  4. ClassVisitCompareFields to compare between two fields of FpProduct in FpProductsEntities.
The 3 and 4 Classes are rules based upon the FpProductsEntities that will be filtered.
The desire is to keep rules unknowledgeable to fields of entity upon which it will apply, and that made the reason to leverage the expression tree to achieve the same.
 
Code
 
Below is the implementation of Classes and Interfaces used in the application.
  1. // FpProduct: this is our entity.For simplicity sake i have taken only few columns from 
  2. // table Financial Product to represent the entity. 
  3. class FpProduct   
  4.     {  
  5.         public string ProductiD { getset; }  
  6.         public string ProductName { getset; }  
  7.         public string ProductType { getset; }  
  8.         public double ProductTotalAmount { getset; }  
  9.         public double ProductBalanceAmount { getset; }  
  10.         public int ProductTenure { getset; }  
  11.   
  12.         public FpProduct(string Productid, string ProdName, string ProdType, double ProdTotalAmount,   
  13.             double ProdBalanceAmount, int ProdTenure)  
  14.         {  
  15.             ProductiD = Productid;  
  16.             ProductName = ProdName;  
  17.             ProductType = ProdType;  
  18.             ProductTotalAmount = ProdTotalAmount;  
  19.             ProductBalanceAmount = ProdBalanceAmount;  
  20.             ProductTenure = ProdTenure;  
  21.         }  
  22.   
  23.         public override string ToString()  
  24.         {  
  25.             return "Product id: "+ProductiD + "  Product Name:"  + ProductName+ " Product Type: "+ ProductType +   
  26.             " Product Total Amount: "+ProductTotalAmount+ " Product Balance Amount: "+ProductBalanceAmount + " Product Tenure: " +ProductTenure;  
  27.         }  
  28.     }  
  29.   
  30. // FpProductsEntities: This is our collection of  FpProduct and this will also contain  
  31. // the rules.Few things needed to note about the Class are:
  32. // 1. The class consists of the collection of FpProduct  
  33. // 2. The Class has exposés functionality LoadData() to load FpProduct.
  34. //    You can Overide it with with your own data load method.   
  35. // 3. The Class exposes functionality to attach rules.  
  36. // 4. It Implements an Interface InterfaceProductEntities,definition of which given just next
  37. //    to the definition of this Class
  38.         
  39.   class FpProductsEntities :InterfaceProductEntities<FpProduct>  
  40.     {  
  41.         public List<FpProduct> ListFpProduct { getset; }  
  42.         public List<InterfaceVisitor<FpProduct>> RuleDirectory { getset; }  
  43.         public void AttachRule(InterfaceVisitor<FpProduct> Rule)  
  44.         {  
  45.             if (RuleDirectory == null)  
  46.                 RuleDirectory = new List<InterfaceVisitor<FpProduct>>();  
  47.   
  48.             RuleDirectory.Add(Rule);  
  49.         }  
  50.         public void LoadDate()  
  51.         {  
  52.             if (ListFpProduct == null)  
  53.             {  
  54.                 ListFpProduct = new List<FpProduct>();  
  55.             }  
  56.                 ListFpProduct.Add(new FpProduct("Prd1""Loan0Tom2019""Loan", 2000, 1500, 1));  
  57.                 ListFpProduct.Add(new FpProduct("Prd2""Loan0Moody2017""USLease", 12000, 150, 1));  
  58.                 ListFpProduct.Add(new FpProduct("Prd3""Loan0Tom2018""SLoan", 2000, 1500, 1));  
  59.                 ListFpProduct.Add(new FpProduct("Prd4""Loan0Rex2018""LLoan", 20000, 1500, 1));  
  60.                 ListFpProduct.Add(new FpProduct("Prd5""Loan0Ahuja2020""CarLoan", 9000, 15000, 1));  
  61.                 ListFpProduct.Add(new FpProduct("Prd6""Loan0Pat2019""Loan", 7000, 7500, 1));              
  62.             }               
  63.         }  
  64. // InterfaceProductEntities   
  65. interface InterfaceProductEntities<T>  
  66.     {  
  67.          List<T> ListFpProduct { getset; }  
  68.          List<InterfaceVisitor<T>> RuleDirectory { getset; }          
  69.     }  
We defined how our entity and collection of entities will look like,now lets see the rules.For now I have added only two rule types.
  1. ClassVisitValidateField
    This rule will compare field value with a constant. For example, a rule of this type will be described: "ProductTotalAmount should be greater than 10000".
  2. ClassVisitCompareFields
    This will compare the values of two fields like ProductTotalAmount should be greater than ProductBalanceAmount.
          Based upon the criteria set by rules, the result set will be filtered out as output, which we will see later.
 
These classes are as follows
  1. // ClassVisitValidateField  
  2. class ClassVisitValidateField<T> : InterfaceVisitor<T>  
  3.     {  
  4.         public string _ruleiD { getset; }  
  5.         public string _propertyName { getset; }  
  6.         public ExpressionType _ExpOperator {get ; set;}  
  7.         public string  _PropertyValue { getset; }  
  8.   
  9.         public ClassVisitValidateField(string ruleid, string PropertyName, ExpressionType exp, string PropertyValue)  
  10.         {  
  11.             _ruleiD = ruleid;  
  12.             _propertyName = PropertyName;  
  13.             _ExpOperator = exp;  
  14.             _PropertyValue = PropertyValue;  
  15.         }  
  16.         public Func<T, bool> Visit()  ///  
  17.         {  
  18.            var parameterExpression = Expression.Parameter(typeof(T), "FinanacialProduct");  
  19.            var property = Expression.Property(parameterExpression, _propertyName);  
  20.            var propertyType = typeof(T).GetProperty(_propertyName).PropertyType;  
  21.            var constant = Expression.Constant(Convert.ChangeType(_PropertyValue, propertyType));  
  22.            var binaryExpression = Expression.MakeBinary(_ExpOperator, property, constant);  
  23.            var lambda = Expression.Lambda<Func<T, bool>>(binaryExpression, parameterExpression);  
  24.            return lambda.Compile();  
  25.           }  
  26.   
  27.         public override string ToString()  
  28.         {  
  29.             return "Rule Id: " + _ruleiD + ">" + _propertyName + "  Should be " + _ExpOperator.ToString() +" " + _PropertyValue;  
  30.         }  
  31.   
  32. // ClassVisitCompareFields  
  33. class ClassVisitCompareFields<T> : InterfaceVisitor<T>  
  34.     {  
  35.         public string _ruleid { getset; }  
  36.         public string _leftProperty { getset; }  
  37.         public string _rightProperty { getset; }  
  38.         public double _factorProperty { getset; }  
  39.         public ExpressionType _ExpOperator {get ; set;}  
  40.   
  41.         public ClassVisitCompareFields(string ruleId ,string leftField,ExpressionType expOperator,double factor,string rightProperty)  
  42.         {  
  43.             _ruleid=ruleId;  
  44.             _leftProperty=leftField;  
  45.             _ExpOperator=expOperator;  
  46.             _factorProperty =factor;  
  47.             _rightProperty=rightProperty;          
  48.         }  
  49.         public Func<T, bool> Visit()   
  50.         {  
  51.             var parameterExpression = Expression.Parameter(typeof(T), "FinanacialProduct");  
  52.             var propertyleft = Expression.Property(parameterExpression, _leftProperty);  
  53.             var propertyRight = Expression.Property(parameterExpression, _rightProperty);  
  54.             var binaryRight = Expression.Multiply(propertyRight, Expression.Constant(_factorProperty));  
  55.             var binaryExpression = Expression.MakeBinary(_ExpOperator, propertyleft, binaryRight);  
  56.             var lambda = Expression.Lambda<Func<T, bool>>(binaryExpression, parameterExpression);  
  57.             return lambda.Compile();          
  58.         }  
  59.         public override string ToString()  
  60.         {  
  61.             return "Rule Id: " + _ruleid + ">" + _leftProperty + "  Should be " + _ExpOperator.ToString() + "  " + _factorProperty + "  times  " + _rightProperty;  
  62.         }  
  63.     }  
Note that both rules types implement an interface InterfaceVisitor.This interface defines a method Visit. This method actually creates the compiled lambda expression. Both above rules, if you notice, implement this method differently. So if we need another type of rule besides them. We need to implement this method to create the lambda which will represent the rule. The definition of InterfaceVisitor is as follows,
  1. //Defines the method which returns the delegate which accepts a generic type as an input and returns Boolean.  
  2. interface InterfaceVisitor<T>  
  3.     {  
  4.         Func<T, bool> Visit();  
  5.     }  
Our wagon is ready; we only now need to pull them. Below is the Main function in Program.cs which will make use of the above classes and then delegate the run to a different class named MainEngine.cs. The reason behind this class is the separation of concern. Let’s see the Main method of Program.cs and the MainEngine.cs.
  1. static void Main(string[] args)  
  2.         {  
  3.             //Instantiate the collection of Financial Products  
  4.             FpProductsEntities fpent = new FpProductsEntities();  
  5.             //Load the data  
  6.             fpent.LoadDate();  
  7.             //Attach rules  
  8.             fpent.AttachRule(new ClassVisitValidateField<FpProduct>("Rule1""ProductTotalAmount", ExpressionType.GreaterThanOrEqual, "2000"));  
  9.             fpent.AttachRule(new ClassVisitCompareFields<FpProduct>("Rule2","ProductTotalAmount",ExpressionType.LessThanOrEqual,1,"ProductBalanceAmount"));  
  10.             fpent.AttachRule(new ClassVisitCompareFields<FpProduct>("Rule2""ProductTotalAmount", ExpressionType.GreaterThan ,1.5, "ProductBalanceAmount"));  
  11.             //Delegate the run to singleton class.  
  12.             MainEngine.Instance().RunRule(fpent);  
  13.             Console.ReadLine();            
  14.         }  
Below is the MainEngine.cs where actual filtered result sets are returned and displayed.
  1. class MainEngine {  
  2.     private static MainEngine _Instance;  
  3.     protected MainEngine() {}  
  4.     public static MainEngine Instance() {  
  5.         if (_Instance == null) {  
  6.             _Instance = new MainEngine();  
  7.         }  
  8.         return _Instance;  
  9.     }  
  10.     //Actual run happens here.  
  11.     public void RunRule < T > (InterfaceProductEntities < T > fp) {  
  12.             foreach(var rule in fp.RuleDirectory) {  
  13.                 Console.WriteLine("\n" + rule.ToString());  
  14.                 Console.WriteLine("-----------------------------------------------");  
  15.                 var result = fp.ListFpProduct.Where(rule.Visit());  
  16.                 foreach(var filteredProduct in result)  
  17.                 Console.WriteLine(filteredProduct.ToString());  
  18.                 Console.WriteLine("------------------------------------------------");  
  19.             } 

Conclusion

 
This is a simple rule engine with limited functionalities. The idea is to show that for a fixed dataset there can be multiple types of rules, each require different set of input, hence different implementation. The good thing is that chances of reusability are far greater than the need for additional new rule types. The second thing is that we don’t need data to create the rule as we have seen that implemented rules above use generic type to create the lambda expression.
 
The downside of this implementation is run time error. What if property name during the instantiation of a rule is misspelled? But that issue comes up with any dynamic implementation; it can be handled at the UI level.


Similar Articles