1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
|
namespace System.Web.ModelBinding {
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Web.Globalization;
// A factory for validators based on ValidationAttribute
public delegate ModelValidator DataAnnotationsModelValidationFactory(ModelMetadata metadata, ModelBindingExecutionContext context, ValidationAttribute attribute);
// A factory for validators based on IValidatableObject
public delegate ModelValidator DataAnnotationsValidatableObjectAdapterFactory(ModelMetadata metadata, ModelBindingExecutionContext context);
/// <summary>
/// An implementation of <see cref="ModelValidatorProvider"/> which providers validators
/// for attributes which derive from <see cref="ValidationAttribute"/>. It also provides
/// a validator for types which implement <see cref="IValidatableObject"/>. To support
/// client side validation, you can either register adapters through the static methods
/// on this class, or by having your validation attributes implement
/// <see cref="IClientValidatable"/>. The logic to support IClientValidatable
/// is implemented in <see cref="DataAnnotationsModelValidator"/>.
/// </summary>
public class DataAnnotationsModelValidatorProvider : AssociatedValidatorProvider {
private static bool _addImplicitRequiredAttributeForValueTypes = true;
private static ReaderWriterLockSlim _adaptersLock = new ReaderWriterLockSlim();
// Factories for validation attributes
internal static DataAnnotationsModelValidationFactory DefaultAttributeFactory =
(metadata, context, attribute) => new DataAnnotationsModelValidator(metadata, context, attribute);
internal static Dictionary<Type, DataAnnotationsModelValidationFactory> AttributeFactories = new Dictionary<Type, DataAnnotationsModelValidationFactory>() {
{
typeof(RangeAttribute),
(metadata, context, attribute) => new RangeAttributeAdapter(metadata, context, (RangeAttribute)attribute)
},
{
typeof(RegularExpressionAttribute),
(metadata, context, attribute) => new RegularExpressionAttributeAdapter(metadata, context, (RegularExpressionAttribute)attribute)
},
{
typeof(RequiredAttribute),
(metadata, context, attribute) => new RequiredAttributeAdapter(metadata, context, (RequiredAttribute)attribute)
},
{
typeof(StringLengthAttribute),
(metadata, context, attribute) => new StringLengthAttributeAdapter(metadata, context, (StringLengthAttribute)attribute)
},
{
typeof(MinLengthAttribute),
(metadata, context, attribute) => new MinLengthAttributeAdapter(metadata, context, (MinLengthAttribute)attribute)
},
{
typeof(MaxLengthAttribute),
(metadata, context, attribute) => new MaxLengthAttributeAdapter(metadata, context, (MaxLengthAttribute)attribute)
},
};
// Factories for IValidatableObject models
internal static DataAnnotationsValidatableObjectAdapterFactory DefaultValidatableFactory =
(metadata, context) => new ValidatableObjectAdapter(metadata, context);
internal static Dictionary<Type, DataAnnotationsValidatableObjectAdapterFactory> ValidatableFactories = new Dictionary<Type, DataAnnotationsValidatableObjectAdapterFactory>();
public static bool AddImplicitRequiredAttributeForValueTypes {
get {
return _addImplicitRequiredAttributeForValueTypes;
}
set {
_addImplicitRequiredAttributeForValueTypes = value;
}
}
protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ModelBindingExecutionContext context, IEnumerable<Attribute> attributes) {
_adaptersLock.EnterReadLock();
try {
List<ModelValidator> results = new List<ModelValidator>();
// Add an implied [Required] attribute for any non-nullable value type,
// unless they've configured us not to do that.
if (AddImplicitRequiredAttributeForValueTypes &&
metadata.IsRequired &&
!attributes.Any(a => a is RequiredAttribute)) {
attributes = attributes.Concat(new[] { new RequiredAttribute() });
}
// Produce a validator for each validation attribute we find
foreach (ValidationAttribute attribute in attributes.OfType<ValidationAttribute>()) {
DataAnnotationsModelValidationFactory factory;
if (!AttributeFactories.TryGetValue(attribute.GetType(), out factory)) {
factory = DefaultAttributeFactory;
}
results.Add(factory(metadata, context, attribute));
}
// Produce a validator if the type supports IValidatableObject
if (typeof(IValidatableObject).IsAssignableFrom(metadata.ModelType)) {
DataAnnotationsValidatableObjectAdapterFactory factory;
if (!ValidatableFactories.TryGetValue(metadata.ModelType, out factory)) {
factory = DefaultValidatableFactory;
}
results.Add(factory(metadata, context));
}
return results;
}
finally {
_adaptersLock.ExitReadLock();
}
}
#region Validation attribute adapter registration
public static void RegisterAdapter(Type attributeType, Type adapterType) {
ValidateAttributeType(attributeType);
ValidateAttributeAdapterType(adapterType);
ConstructorInfo constructor = GetAttributeAdapterConstructor(attributeType, adapterType);
_adaptersLock.EnterWriteLock();
try {
AttributeFactories[attributeType] = (metadata, context, attribute) => (ModelValidator)constructor.Invoke(new object[] { metadata, context, attribute });
}
finally {
_adaptersLock.ExitWriteLock();
}
}
[SuppressMessage("Microsoft.Usage", "CA2301:EmbeddableTypesInContainersRule", MessageId = "AttributeFactories", Justification = "The types that go into this dictionary are specifically ValidationAttribute derived types.")]
public static void RegisterAdapterFactory(Type attributeType, DataAnnotationsModelValidationFactory factory)
{
ValidateAttributeType(attributeType);
ValidateAttributeFactory(factory);
_adaptersLock.EnterWriteLock();
try {
AttributeFactories[attributeType] = factory;
}
finally {
_adaptersLock.ExitWriteLock();
}
}
public static void RegisterDefaultAdapter(Type adapterType) {
ValidateAttributeAdapterType(adapterType);
ConstructorInfo constructor = GetAttributeAdapterConstructor(typeof(ValidationAttribute), adapterType);
DefaultAttributeFactory = (metadata, context, attribute) => (ModelValidator)constructor.Invoke(new object[] { metadata, context, attribute });
}
public static void RegisterDefaultAdapterFactory(DataAnnotationsModelValidationFactory factory) {
ValidateAttributeFactory(factory);
DefaultAttributeFactory = factory;
}
// Helpers
private static ConstructorInfo GetAttributeAdapterConstructor(Type attributeType, Type adapterType) {
ConstructorInfo constructor = adapterType.GetConstructor(new[] { typeof(ModelMetadata), typeof(ModelBindingExecutionContext), attributeType });
if (constructor == null) {
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
SR.GetString(SR.DataAnnotationsModelValidatorProvider_ConstructorRequirements),
adapterType.FullName,
typeof(ModelMetadata).FullName,
typeof(ModelBindingExecutionContext).FullName,
attributeType.FullName
),
"adapterType"
);
}
return constructor;
}
private static void ValidateAttributeAdapterType(Type adapterType) {
if (adapterType == null) {
throw new ArgumentNullException("adapterType");
}
if (!typeof(ModelValidator).IsAssignableFrom(adapterType)) {
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
SR.GetString(SR.Common_TypeMustDriveFromType),
adapterType.FullName,
typeof(ModelValidator).FullName
),
"adapterType"
);
}
}
private static void ValidateAttributeType(Type attributeType) {
if (attributeType == null) {
throw new ArgumentNullException("attributeType");
}
if (!typeof(ValidationAttribute).IsAssignableFrom(attributeType)) {
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
SR.GetString(SR.Common_TypeMustDriveFromType),
attributeType.FullName,
typeof(ValidationAttribute).FullName
),
"attributeType");
}
}
private static void ValidateAttributeFactory(DataAnnotationsModelValidationFactory factory) {
if (factory == null) {
throw new ArgumentNullException("factory");
}
}
#endregion
#region IValidatableObject adapter registration
/// <summary>
/// Registers an adapter type for the given <see cref="modelType"/>, which must
/// implement <see cref="IValidatableObject"/>. The adapter type must derive from
/// <see cref="ModelValidator"/> and it must contain a public constructor
/// which takes two parameters of types <see cref="ModelMetadata"/> and
/// <see cref="ModelBindingExecutionContext"/>.
/// </summary>
public static void RegisterValidatableObjectAdapter(Type modelType, Type adapterType) {
ValidateValidatableModelType(modelType);
ValidateValidatableAdapterType(adapterType);
ConstructorInfo constructor = GetValidatableAdapterConstructor(adapterType);
_adaptersLock.EnterWriteLock();
try {
ValidatableFactories[modelType] = (metadata, context) => (ModelValidator)constructor.Invoke(new object[] { metadata, context });
}
finally {
_adaptersLock.ExitWriteLock();
}
}
/// <summary>
/// Registers an adapter factory for the given <see cref="modelType"/>, which must
/// implement <see cref="IValidatableObject"/>.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2301:EmbeddableTypesInContainersRule", MessageId = "ValidatableFactories", Justification = "The types that go into this dictionary are specifically those which implement IValidatableObject.")]
public static void RegisterValidatableObjectAdapterFactory(Type modelType, DataAnnotationsValidatableObjectAdapterFactory factory)
{
ValidateValidatableModelType(modelType);
ValidateValidatableFactory(factory);
_adaptersLock.EnterWriteLock();
try {
ValidatableFactories[modelType] = factory;
}
finally {
_adaptersLock.ExitWriteLock();
}
}
/// <summary>
/// Registers the default adapter type for objects which implement
/// <see cref="IValidatableObject"/>. The adapter type must derive from
/// <see cref="ModelValidator"/> and it must contain a public constructor
/// which takes two parameters of types <see cref="ModelMetadata"/> and
/// <see cref="ModelBindingExecutionContext"/>.
/// </summary>
public static void RegisterDefaultValidatableObjectAdapter(Type adapterType) {
ValidateValidatableAdapterType(adapterType);
ConstructorInfo constructor = GetValidatableAdapterConstructor(adapterType);
DefaultValidatableFactory = (metadata, context) => (ModelValidator)constructor.Invoke(new object[] { metadata, context });
}
/// <summary>
/// Registers the default adapter factory for objects which implement
/// <see cref="IValidatableObject"/>.
/// </summary>
public static void RegisterDefaultValidatableObjectAdapterFactory(DataAnnotationsValidatableObjectAdapterFactory factory) {
ValidateValidatableFactory(factory);
DefaultValidatableFactory = factory;
}
// Helpers
private static ConstructorInfo GetValidatableAdapterConstructor(Type adapterType) {
ConstructorInfo constructor = adapterType.GetConstructor(new[] { typeof(ModelMetadata), typeof(ModelBindingExecutionContext) });
if (constructor == null) {
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
SR.GetString(SR.DataAnnotationsModelValidatorProvider_ValidatableConstructorRequirements),
adapterType.FullName,
typeof(ModelMetadata).FullName,
typeof(ModelBindingExecutionContext).FullName
),
"adapterType"
);
}
return constructor;
}
private static void ValidateValidatableAdapterType(Type adapterType) {
if (adapterType == null) {
throw new ArgumentNullException("adapterType");
}
if (!typeof(ModelValidator).IsAssignableFrom(adapterType)) {
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
SR.GetString(SR.Common_TypeMustDriveFromType),
adapterType.FullName,
typeof(ModelValidator).FullName
),
"adapterType");
}
}
private static void ValidateValidatableModelType(Type modelType) {
if (modelType == null) {
throw new ArgumentNullException("modelType");
}
if (!typeof(IValidatableObject).IsAssignableFrom(modelType)) {
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
SR.GetString(SR.Common_TypeMustDriveFromType),
modelType.FullName,
typeof(IValidatableObject).FullName
),
"modelType"
);
}
}
private static void ValidateValidatableFactory(DataAnnotationsValidatableObjectAdapterFactory factory) {
if (factory == null) {
throw new ArgumentNullException("factory");
}
}
#endregion
}
}
|