Tuesday 14 August 2012

Simple Business Rules Engine

Rules Engine is a . NET C# project that validates business logic by defining a bunch of rules for your data classes. Rules are defined using a fluent-interface (fluent validation) helper class, and not by decorating your existing objects with attributes, therefore de-coupling validation logic from data (or domain) classes.

Features

  • Rules are inheritable. Defining RuleX for TypeA will also apply to TypeB (given that TypeB inherits from Type A) 
  • Rules are extensible. Creating custom rules are only a matter of implementing an interface. 
  • Conditional validation. When defining rules, it is possible to have different rules given different conditions. E.g. Not Null Rule only applies to FieldA when FieldB > 100
  • Cross-Field validation. Defining a rule that FieldA must be greater than FieldB comes very naturally with the fluent-interface helper class. 
  • Fluent-Interface. Adding rules to objects is done by a fluent-interface helper class. 
  • Error Messages. Defining error messages can be done at the same time as defining your rules (Or separately). They can apply to the Class, A Property of that class, or a Rule for that property. 
Below is the simple example for rules engine:

public class Person
    {
        public string Name { get; set; }
        public string Phone { get; set; }
        public DateTime DateOfBirth { get; set; }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            Engine engine = new Engine();
            engine.For<Person>()
                    .Setup(p => p.DateOfBirth)
                        .MustBeLessThan(DateTime.Now)
                    .Setup(p => p.Name)
                        .MustNotBeNull()
                        .MustMatchRegex("^[a-zA-z]+$")
                    .Setup(p => p.Phone)
                        .MustNotBeNull()
                        .MustMatchRegex("^[0-9]+$");

            Person person = new Person();
            person.Name = "Bill";
            person.Phone = "1234214";
            person.DateOfBirth = new DateTime(1999, 10, 2);

            bool isValid = engine.Validate(person);
        }
    }


Please Follow the Following LInk for downloading Rules Engine http://rulesengine.codeplex.com/