So I ran into this problem today. We have a validation attribute [Required] adorning a property who's value is an object type. This property has a default value of null. When CSLA's validation engine executes CommonRules.DataAnnotation for this property on the client (silverlight) it blows up at line 1417:
var ctx = new System.ComponentModel.DataAnnotations.ValidationContext(pValue, null, null);
because pValue can not be null.
Is the exception coming from the RequiredAttribute or from the DataAnnotation rule method?
If it is coming from the RequiredAttribute (and I suspect it is) then that's Microsoft's code. It may easily be that Required is only valid on string properties - which kind of makes sense.
The exception is being thrown from within the DataAnnotation rule method.
The problem appears to be with the use of System.ComponentModel.DataAnnotations.ValidationContext. It's ctor does not like having a null value for the first paramater (I think the param name is Instance?). I agree that this appears to be a flawed Microsoft implementation... If I understand correctly the RequiredAttribute does not require ValidationContext...but I haven't spent too much time investigating.
Looking at the silverlight SDK the RequiredAttribute class has the following code for IsValid:
/// <summary>
/// Override of <see cref="ValidationAttribute.IsValid(object)"/>
/// </summary>
/// <param name="value">The value to test</param>
/// <returns><c>false</c> if the <paramref name="value"/> is null or an empty string</returns>
#if !SILVERLIGHT
public
#else
internal
#endif
override bool IsValid(object value) {
if (value == null) {
return false;
}
var stringValue = value as string;
if (stringValue != null) {
return stringValue.Trim().Length != 0;
} else {
return true;
}
}
However I don't see any other way to get the IsValid method to run in silverlight (since it is internal for silverlight) other then what you are doing by creating a validation context and calling Attribute.GetValidationResults uing the property value and the created validation context..
I believe we are going to use the AddBusinessRules override in any event as the attributes do not suport err\warn\info.
Thanks for digging deeper.
I’m also in communication with the Microsoft PM who owns this
feature, and he’s helping me sort through some of the details. It turns out
that their API is somewhat inconsistent, not only between SL and .NET, but also
between different methods.
For example, IsValid() accepts an object – this is the value to
be validated. But the context object’s constructor accepts an object – this is
the object containing the value to be validated. How would you know? Apparently
by talking to the PM that owns the feature :)
So I think in Beta 2 you’ll find that the behaviors work as
expected – I surely hope so… Though I’m still not sure that there’ll be parity
between .NET and SL, because they don’t work the same way :(
Copyright (c) Marimer LLC