Suggestion for new Contrib Project - ValidationRulesLib

Suggestion for new Contrib Project - ValidationRulesLib

Old forum URL: forums.lhotka.net/forums/t/1742.aspx


sune42 posted on Sunday, November 12, 2006

Hi

I just have an idea for a new project that I think coul be very helpful.

Would it not be helpful to create a new library of common Validation rules, for things like

URL's, emails, zipcodes, URL/FTPs, CharactersOnly, NumbersOnly.......

Sure, its not that hard to create your own , but collaborating on a common library
could be even better so that we don't have to invent the wheel over and over again
and fight with regexes.

What do you think?

/Andy

david.wendelken replied on Sunday, November 12, 2006

I think it's a great idea.

I'll be adding in a new set of classes that support providing a public list of all rules in the object this week.

I would love for the library of validation rules to play well with it. :)

 

david.wendelken replied on Sunday, November 12, 2006

I've got a white paper some colleagues of mine and I did a few years back about the advantages of preparing a pre-defined list of solutions to common business rules.   I'm contacting Rocky to get the permissions necessary to attach it.

Here's a partial extract.  Hope it is of interest.

Building a Business Rule Play Book

Introduction

What is a Play Book?

In sports, the play book is tactically action-oriented and contains a short-hand version of the cooperative knowledge of the team.  That statement was very precisely stated, and we must very carefully analyze it. 

First, it is tactically action-oriented. It does not discuss strategic theory or the greater social context of the game.  Its focus is on short-term tactical operations.

Second, it is short-hand version.  It enables coach, captain and team members to communicate a complicated set of pre-planned actions quickly and unambiguously.  There is little leisure for long explanations while in the midst of a game, even less so for planning.  Time is of the essence.  So, too, is accuracy, for the game will be lost if the players have different understandings of what each is about to do.

Third, it is cooperative knowledge.  It does not incorporate the rules of the game, nor does it include the intricacies of how an individual can best kick, throw, or catch a ball.  It does not cover how the rules of the game will be enforced.  It covers what the team does together, so that their actions are coordinated and thus more powerful than they would be in isolation.

Fourth, it is a book of plays.  As a book, it can be opened and referred to at need.  It is a repository of information.  It contains plays.  Plays have a plot, a story to tell, and depend upon actors to fulfill appropriate roles in order to reach a denouement.  In a crunch, a new play can be improvised out of the building blocks of other plays, with each role having a reasonably certain and accurate expectation of its part in the new drama.

What is a Business Rule?

The term “business rule” is now beginning to be fashionable and thus subject to all the abuses of techno-babble and buzzword compliance.  To avoid this, let’s go back to basics and start our definition from there.  What is a rule?  There are two divergent meanings to the root word that are of interest to us. 

First, “to rule” meaning “to govern.”  Rulers constrain our behavior, forbid or command courses of action. 

Second, “a rule” as in “a measure, a ruler.”  Rules provide consistency in how we measure for all the benefits that can give us in communication and reliability.

Thus, a business rule is a rule about business, in particular, about how a business must or should operate, or how it takes measure of its situation.

Just as a law does not have to include why it was promulgated, or for what purpose, so it is with business rules.  Even as a law without proper context invites abuse when it is interpreted, so can a business rule foster inefficiency when it is enforced in inappropriate situations.  But, that particular issue is outside of the scope of this article.  (Remember, a play book is tactically oriented and does not cover the greater social context or the strategy of the game!  We invite you to check out our website www.casetech.net for papers covering those aspects of using business rules, and others.)

What is a Business Rule Play Book?

Well, one obvious answer is that it is a book full of business rules.  That’s a darn good guess, but not quite right!  If this were a business-oriented audience, we would focus on just that.  As you are, by and large, an audience composed of technicians, our focus is somewhat different.  A sports book does not contain actual plays where an actual person performs an actual task at an actual point in time; it contains the pattern of a play, its definition, if you will.  Thus, by analogy, the business rule play book we are discussing is a book of rule patterns.  Each rule pattern describes a standardized snippet of behavior, typically in the context of a standardized business or technical situation.

Rule Patterns

Sample Rule Pattern Definitions (with Sample Rules)

I’ve always found that using examples from personal life works better than more academic or business examples.  The examples seem to stick in student’s minds better.  Perhaps that is because real life is so much more amusing than business or academia could ever be!  Of course, real life can be much more scandalous, too!  The sample rules have been chosen to amuse or annoy, as the case may be, on the premise that any adrenaline surge from a technical article is a welcome relief!

Our rule pattern book has nearly a hundred patterns in it, and I expect to reach one hundred and fifty by the time rule patterns dealing with user interface issues are defined and added in.

Pattern Mnemonic

Description and Example

A and B

If one of the data items in this set is filled in with a non-blank value, all of them must be filled in with a non-blank value.

“If the name of the significant other is supplied, the gender of that person must also be supplied, and vice-versa.”

A or B

Only one of the set of data items may have a non-blank value.

“Men may record a wife’s name or a girlfriend’s name, but not both.”

B if A

A data item cannot have a non-blank value if another data item is blank.

“Address Line 2 must be blank unless Address Line 1 is filled in.”

MinMax LE

One data item must be less than, or equal to, another data item, if both are filled in.

“Divorce Date must be on or after Marriage Date.”

No Overlap

The data record has starting and ending range values, which must not overlap with another set of rule-specified data records.

“A wife may not have more than one husband at a time.”

No Cousin

Two or more different relational paths back to the same "ancestor" entity exist.  None of the specified relational paths may be traced back to the same data record in the specified "ancestor" entity. 

“A person may not marry someone who has the same mother.”

(The reverse of this pattern is the Cousin pattern, where the paths must trace back to the same record.)

Data Subset Definition

The data for the entity is subdivided into "business sets" which correspond to a subset of the data records based upon an algorithm specified in the rule.  This is used as a way to filter out unwanted data records.  A specific rule poses the question: “Is this record a member of the set?” and provides the information necessary to answer it correctly.

“A person is a marriage prospect if they are currently single, have a steady job, and have no debilitating diseases.”

Other Data Subset Definition rules may be needed, such as “Is this disease debilitating?” and “Is this a steady job?”  The sample rule could (and should) invoke them as part of getting its answer.  That way, the sample rule automatically stays up-to-date when how we determine if a disease is debilitating changes

The rule patterns mentioned above are primarily “data validation” oriented.  However, the last pattern mentioned is definitional in nature.  It defines a question of interest and how to answer it.  Rules that answer questions (which may be for data subset definitions or formula calculations) are a very useful way to organize code, because any program that needs to know the answer can just ask the rule.  This provides a single point of change for application creation and maintenance purposes.  In fact, properly done, many programs become fairly small control frameworks that just ask a series of rules for guidance and action.  This is structured design and programming on steroids, but without the health risks!

david.wendelken replied on Sunday, November 12, 2006

david.wendelken:

I think it's a great idea.

I'll be adding in a new set of classes that support providing a public list of all rules in the object this week.

I would love for the library of validation rules to play well with it. :)

Just loaded up the first cut of this to CSLA Contrib.

MikeHamilton replied on Monday, November 13, 2006

A Newb here, where do I get the files you uploaded?

Mike

david.wendelken replied on Monday, November 13, 2006

MikeHamilton:

A Newb here, where do I get the files you uploaded?

Mike

Near the top right of this screen is a link to CSLA Contrib.

Go there and click on the Source Code tab.

The download links are there.

You are looking for the CslaSrd project.  I only have a C# version done of my contribution.

Curelom replied on Wednesday, November 15, 2006

What would also be helpful in the validation rules is to be able to customize the property name that the user sees.  For example instead of the user seeing "StartDateString is required", they could see "Starting Date is required"

david.wendelken replied on Wednesday, November 15, 2006

Curelom:
What would also be helpful in the validation rules is to be able to customize the property name that the user sees.  For example instead of the user seeing "StartDateString is required", they could see "Starting Date is required"

That's a good idea and it prompted me to think of a way to do it.  I'll try it out and post back later.

Curelom replied on Tuesday, December 05, 2006

I've taken a stab at the property names that seems to work pretty good.  Let me know what you think.  It uses values from the resources from the calling application with a resource name format of ObjectName_PropertyName

With a little modification it could work well for globalization as well.

using System;

using System.Collections.Generic;

using System.Text;

using System.Text.RegularExpressions;

using System.Reflection;

using System.Resources;

using Csla;

using Csla.Properties;

using Csla.Validation;

namespace Library.Validation {

public static class CustomRules {

#region StringRequired

/// <summary>

/// Rule ensuring a string value contains one or more

/// characters.

/// </summary>

/// <param name="target">Object containing the data to validate</param>

/// <param name="e">Arguments parameter specifying the name of the string

/// property to validate</param>

/// <returns><see langword="false" /> if the rule is broken</returns>

/// <remarks>

/// This implementation uses late binding, and will only work

/// against string property values.

/// </remarks>

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]

public static bool StringRequired(object target, RuleArgs e) {

string value = (string)Utilities.CallByName(

target, e.PropertyName, CallType.Get);

//don't validate if user doesn't have write authorization

if (target is Csla.Security.IAuthorizeReadWrite) {

Csla.Security.IAuthorizeReadWrite rw = target as Csla.Security.IAuthorizeReadWrite;

if (!rw.CanWriteProperty(e.PropertyName))

return true;

}

if (string.IsNullOrEmpty(value)) {

ResourceManager rmCsla = new ResourceManager("Csla.Properties.Resources", Assembly.GetCallingAssembly());

e.Description = string.Format(rmCsla.GetString("StringRequiredRule"),

GetResourceValue((target.GetType()).Name, e.PropertyName));

return false;

}

return true;

}

#endregion

//get display value for property

public static string GetResourceValue(string objectName, string propertyName) {

ResourceManager appRm = new ResourceManager("HelpDesk.Properties.Resources",

Assembly.GetEntryAssembly());

string temp = appRm.GetString(objectName + "_" + propertyName);

if (string.IsNullOrEmpty(temp)) {

return propertyName;

}

return temp;

}

}

}

david.wendelken replied on Wednesday, April 18, 2007

Just posted a new validation library, plus new Smart classes, plus public rule list support to the CslaContrib project.

The sub-project is CslaSrd.  I have only updated the c# version.

Unfortunately, I put the new version in a sub-directory of the old version, and don't have the ability to fix it yet, so you'll have to dig a bit harder than I would like.

 

 

david.wendelken replied on Friday, April 27, 2007

david.wendelken:

Just posted a new validation library, plus new Smart classes, plus public rule list support to the CslaContrib project.

The sub-project is CslaSrd.  I have only updated the c# version.

Unfortunately, I put the new version in a sub-directory of the old version, and don't have the ability to fix it yet, so you'll have to dig a bit harder than I would like.

I made the corrections to the file placement.

david.wendelken replied on Wednesday, April 18, 2007

Some friends of mine and I are finishing up our first cut of extending the CommonRules library.

We've got the following extra "Smart" classes: SmartBool, SmartFloat, SmartDecimal, SmartInt16, SmartInt32, SmartInt64.

We added SmartSafeDataReader,  a subclass of SafeDataReader, that supports the additional "Smart" classes.

We took the CommonRules library, cloned it, and changed the name to StdRules.

We've added the following rules to the library:

We're about to add several more, including:

In addition, we've subclassed the BusinessBase and BusinessBaseList classes to add two additional properties:

/// <summary>
/// Provides a collection of all validation rules on the object that are broken, i.e., in an invalid state.
/// </summary>
public BrokenRulesCollection BrokenRules

/// <summary>
/// Provides a collection of all validation rules on the object.
/// </summary>
public PublicRuleInfoList Rules

To make the last method work, we had to re-factor the rule error messages in the resource file.  The current resource tags for CommonRules do not exactly match the rule name they go with.  In addition, they use the String.Format method of substitution.  For example:

MaxValueRule {0} can not exceed {1}

MinValueRule {0} can not be less than {1}

Our messages are structured like this:

ruleMaxValue {rulePropertyName} can not exceed {maxValue}.

ruleMinValue {rulePropertyName} can not be less than {minValue}.

This was necessary to allow the PublicRuleInfo class to deduce the correct error message to display.

 

Anyone want to give it a test drive?

 

FreeAsInBeer replied on Thursday, April 19, 2007

funny enough, I came to the contrib forum to see if there was work being done on validation libraries.

I think it's an excellent idea, and I'd be willing to help out where I can. Coding, documentation or testing, just let me know.


david.wendelken replied on Friday, April 20, 2007

I'll add some stubs to the StdRules library, and you can work on the ones you want.

Copyright (c) Marimer LLC