Our business problem: We have properties that are required only when the status code is particular statuses. This caused us to look at how to dynamically add/remove Validation Rules.
Here’s a small example of the different pieces. I can’t include the full class because my work doesn’t like me to post that much code. This should show you the main parts. The only change to CSLA.NET that I can remember is that we had to make the ValidationRules public so we could call the AddRule and DeleteRule from outside the business object.
In the Extended Property of the FullName column:
Name = IsRequiredForStatus
Value = Codes.Status.Complete
Property is generated like this:
<IsRequiredForStatus(Codes.Status.Complete)> _
Public Overridable Property FullName() As String
In the “set” of the nogen Status property (which is of type Codes.Status enumeration), it calls the function to check the attributes. This calls the EVIL attributes to process the rules:
RunValidationAttributes()
In the Validator, it uses reflection to get all of the properties of the object. It loops through each of the properties and checks to see if any of the attributes are of type VBEvilBaseAttribute. If so then it calls the ProcessRule of that attribute class such as “IsRequiredForStats”.
Public Class IsRequiredForStatus
Inherits VBEvilBaseAttribute
Public Overrides Function ProcessRule(ByVal pi As PropertyInfo,
ByVal entity As Object) As Boolean
If the property’s attribute enumeration value matches the enumeration of the Status property then it’s required. The logic below is done for each datatype.
If IsRequired Then
If pi.PropertyType Is GetType(String) Then
Dim args As New Csla2.Validation.RuleArgs(pi.Name)
args.Description = pi.Name & " is required for this status."
args.Severity = Csla2.Validation.RuleSeverity.FailsCustomRules
busObject.ValidationRules.AddRule(AddressOf
Csla2.Validation.CommonRules.StringRequired, args)
Else
If pi.PropertyType Is GetType(String) Then
busObject.ValidationRules.DeleteRule(pi.Name, "StringRequired")
If you have any questions, comments, or better ideas, please let me know. I always like to hear ideas for using CSLA.NET. I would like to thank Dave Cottle. He is the one that figured out a lot details to make this work.
Mike
Code Smart Not Hard