Using the Rules Engine

PLINQO Rules! Yes, PLINQO provides several different ways to lay down the law. Rules can be added programmatically or declaratively through attributes. Constraints like property length and required field rules can be enforced. Regular Expression data validation as well as several built in rules including authorization rules are possible with PLINQO. Before any data is saved, the rules are automatically executed against any entities in your change set. If any rules are broken, a BrokenRulesException will be thrown with a list of the rules that were broken and the entity will not be updated.

The PLINQO rule manager generates rules based on the schema and any custom rules can be added to the rules collection. The rules are enforced when any attempt to save changes is made. Custom rules are a snap to add and the AddSharedRules partial method on each entity is the place to add them. Only a few lines of code and a custom rule can be added. Here is a look.

A rule for the minimum length of UserName is added.

static partial void AddSharedRules()
{
    RuleManager.AddShared(new CustomRule("UserName", "UserName must be 5 characters.", MinLengthUserName));
}

private static bool MinLengthUserName(string username)
{
    if (String.IsNullOrEmpty(username) || username.Length < 5)
        return false;
    else
        return true;
}

When any rules are broken, no data is updated and a nice list of the rules broken is returned.

using (var context = new TrackerDataContext())
{
    User user = new User();
    context.User.InsertOnSubmit(user);
    context.SubmitChanges();
}

Rules can be added declaratively as well by taking advantage of the metadata class mentioned previously. PLINQO supports the standard rules in the System.ComponentModel.DataAnnotations assembly as well as the rules defined by PLINQO.

As you can see there are many ways to enforce that the data that gets saved is data that follows the rules.

Next: Rules Example Code