private static bool TryGetProviderFromAttributes(Type modelType, out ModelBinderProvider provider)
        {
            ExtensibleModelBinderAttribute attr = TypeDescriptorHelper.Get(modelType).GetAttributes().OfType <ExtensibleModelBinderAttribute>().FirstOrDefault();

            if (attr == null)
            {
                provider = null;
                return(false);
            }

            if (typeof(ModelBinderProvider).IsAssignableFrom(attr.BinderType))
            {
                provider = (ModelBinderProvider)Activator.CreateInstance(attr.BinderType);
            }
            else if (typeof(IExtensibleModelBinder).IsAssignableFrom(attr.BinderType))
            {
                Type closedBinderType = (attr.BinderType.IsGenericTypeDefinition) ? attr.BinderType.MakeGenericType(modelType.GetGenericArguments()) : attr.BinderType;
                IExtensibleModelBinder binderInstance = (IExtensibleModelBinder)Activator.CreateInstance(closedBinderType);
                provider = new SimpleModelBinderProvider(modelType, binderInstance)
                {
                    SuppressPrefixCheck = attr.SuppressPrefixCheck
                };
            }
            else
            {
                string errorMessage = String.Format(CultureInfo.CurrentCulture, MvcResources.ModelBinderProviderCollection_InvalidBinderType,
                                                    attr.BinderType, typeof(ModelBinderProvider), typeof(IExtensibleModelBinder));
                throw new InvalidOperationException(errorMessage);
            }

            return(true);
        }
        internal static void GetRequiredPropertiesCollection(Type modelType, out HashSet <string> requiredProperties, out HashSet <string> skipProperties)
        {
            requiredProperties = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
            skipProperties     = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            // Use attributes on the property before attributes on the type.
            ICustomTypeDescriptor        modelDescriptor     = TypeDescriptorHelper.Get(modelType);
            PropertyDescriptorCollection propertyDescriptors = modelDescriptor.GetProperties();
            BindingBehaviorAttribute     typeAttr            = modelDescriptor.GetAttributes().OfType <BindingBehaviorAttribute>().SingleOrDefault();

            foreach (PropertyDescriptor propertyDescriptor in propertyDescriptors)
            {
                BindingBehaviorAttribute propAttr    = propertyDescriptor.Attributes.OfType <BindingBehaviorAttribute>().SingleOrDefault();
                BindingBehaviorAttribute workingAttr = propAttr ?? typeAttr;
                if (workingAttr != null)
                {
                    switch (workingAttr.Behavior)
                    {
                    case BindingBehavior.Required:
                        requiredProperties.Add(propertyDescriptor.Name);
                        break;

                    case BindingBehavior.Never:
                        skipProperties.Add(propertyDescriptor.Name);
                        break;
                    }
                }
            }
        }
        internal static IModelBinder GetBinderFromAttributes(Type type, Func <string> errorMessageAccessor)
        {
            AttributeCollection allAttrs = TypeDescriptorHelper.Get(type).GetAttributes();

            CustomModelBinderAttribute[] filteredAttrs = allAttrs.OfType <CustomModelBinderAttribute>().ToArray();
            return(GetBinderFromAttributesImpl(filteredAttrs, errorMessageAccessor));
        }
        private static bool TryGetProviderFromAttributes(Type modelType, out ModelBinderProvider provider)
        {
            ModelBinderAttribute attr = TypeDescriptorHelper.Get(modelType).GetAttributes().OfType <ModelBinderAttribute>().FirstOrDefault();

            if (attr == null)
            {
                provider = null;
                return(false);
            }

            // TODO, 386718, remove the following if statement when the bug is resolved
            if (attr.BinderType == null)
            {
                provider = null;
                return(false);
            }

            if (typeof(ModelBinderProvider).IsAssignableFrom(attr.BinderType))
            {
                provider = (ModelBinderProvider)Activator.CreateInstance(attr.BinderType);
            }
            else
            {
                throw Error.InvalidOperation(SRResources.ModelBinderProviderCollection_InvalidBinderType, attr.BinderType.Name, typeof(ModelBinderProvider).Name, typeof(IModelBinder).Name);
            }

            return(true);
        }
Exemplo n.º 5
0
        private TypeInformation CreateTypeInformation(Type type)
        {
            TypeInformation       info           = new TypeInformation();
            ICustomTypeDescriptor typeDescriptor = TypeDescriptorHelper.Get(type);

            info.TypeDescriptor = typeDescriptor;
            info.Prototype      = CreateMetadataPrototype(
                AsAttributes(typeDescriptor.GetAttributes()),
                containerType: null,
                modelType: type,
                propertyName: null
                );

            Dictionary <string, PropertyInformation> properties =
                new Dictionary <string, PropertyInformation>();

            foreach (PropertyDescriptor property in typeDescriptor.GetProperties())
            {
                // Avoid re-generating a property descriptor if one has already been generated for the property name
                if (!properties.ContainsKey(property.Name))
                {
                    properties.Add(property.Name, CreatePropertyInformation(type, property));
                }
            }
            info.Properties = properties;

            return(info);
        }
        protected virtual void SetProperty(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext, ModelMetadata propertyMetadata, ComplexModelDtoResult dtoResult)
        {
            PropertyDescriptor propertyDescriptor = TypeDescriptorHelper.Get(bindingContext.ModelType).GetProperties().Find(propertyMetadata.PropertyName, true /* ignoreCase */);

            if (propertyDescriptor == null || propertyDescriptor.IsReadOnly)
            {
                return; // nothing to do
            }

            object value = dtoResult.Model ?? GetPropertyDefaultValue(propertyDescriptor);

            propertyMetadata.Model = value;

            // 'Required' validators need to run first so that we can provide useful error messages if
            // the property setters throw, e.g. if we're setting entity keys to null. See comments in
            // DefaultModelBinder.SetProperty() for more information.
            if (value == null)
            {
                string modelStateKey = dtoResult.ValidationNode.ModelStateKey;
                if (bindingContext.ModelState.IsValidField(modelStateKey))
                {
                    ModelValidator requiredValidator = ModelValidatorProviders.Providers.GetValidators(propertyMetadata, controllerContext).Where(v => v.IsRequired).FirstOrDefault();
                    if (requiredValidator != null)
                    {
                        foreach (ModelValidationResult validationResult in requiredValidator.Validate(bindingContext.Model))
                        {
                            bindingContext.ModelState.AddModelError(modelStateKey, validationResult.Message);
                        }
                    }
                }
            }

            if (value != null || TypeHelpers.TypeAllowsNullValue(propertyDescriptor.PropertyType))
            {
                try
                {
                    propertyDescriptor.SetValue(bindingContext.Model, value);
                }
                catch (Exception ex)
                {
                    // don't display a duplicate error message if a binding error has already occurred for this field
                    string modelStateKey = dtoResult.ValidationNode.ModelStateKey;
                    if (bindingContext.ModelState.IsValidField(modelStateKey))
                    {
                        bindingContext.ModelState.AddModelError(modelStateKey, ex);
                    }
                }
            }
            else
            {
                // trying to set a non-nullable value type to null, need to make sure there's a message
                string modelStateKey = dtoResult.ValidationNode.ModelStateKey;
                if (bindingContext.ModelState.IsValidField(modelStateKey))
                {
                    dtoResult.ValidationNode.Validated += CreateNullCheckFailedHandler(controllerContext, propertyMetadata, value);
                }
            }
        }
 private static void EnsureNoBindAttribute(Type modelType)
 {
     if (TypeDescriptorHelper.Get(modelType).GetAttributes().OfType <BindAttribute>().Any())
     {
         string errorMessage = String.Format(CultureInfo.CurrentCulture, MvcResources.ModelBinderProviderCollection_TypeCannotHaveBindAttribute,
                                             modelType);
         throw new InvalidOperationException(errorMessage);
     }
 }
Exemplo n.º 8
0
        internal static void GetRequiredPropertiesCollection(
            HttpActionContext actionContext,
            ModelBindingContext bindingContext,
            out HashSet <string> requiredProperties,
            out Dictionary <string, ModelValidator> requiredValidators,
            out HashSet <string> skipProperties
            )
        {
            requiredProperties = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
            requiredValidators = new Dictionary <string, ModelValidator>(
                StringComparer.OrdinalIgnoreCase
                );
            skipProperties = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            // Use attributes on the property before attributes on the type.
            ICustomTypeDescriptor modelDescriptor = TypeDescriptorHelper.Get(
                bindingContext.ModelType
                );
            PropertyDescriptorCollection propertyDescriptors = modelDescriptor.GetProperties();
            HttpBindingBehaviorAttribute typeAttr            = modelDescriptor
                                                               .GetAttributes()
                                                               .OfType <HttpBindingBehaviorAttribute>()
                                                               .SingleOrDefault();

            foreach (PropertyDescriptor propertyDescriptor in propertyDescriptors)
            {
                string         propertyName      = propertyDescriptor.Name;
                ModelMetadata  propertyMetadata  = bindingContext.PropertyMetadata[propertyName];
                ModelValidator requiredValidator = actionContext
                                                   .GetValidators(propertyMetadata)
                                                   .Where(v => v.IsRequired)
                                                   .FirstOrDefault();
                requiredValidators[propertyName] = requiredValidator;

                HttpBindingBehaviorAttribute propAttr = propertyDescriptor.Attributes
                                                        .OfType <HttpBindingBehaviorAttribute>()
                                                        .SingleOrDefault();
                HttpBindingBehaviorAttribute workingAttr = propAttr ?? typeAttr;
                if (workingAttr != null)
                {
                    switch (workingAttr.Behavior)
                    {
                    case HttpBindingBehavior.Required:
                        requiredProperties.Add(propertyName);
                        break;

                    case HttpBindingBehavior.Never:
                        skipProperties.Add(propertyName);
                        break;
                    }
                }
                else if (requiredValidator != null)
                {
                    requiredProperties.Add(propertyName);
                }
            }
        }
Exemplo n.º 9
0
 protected override System.ComponentModel.ICustomTypeDescriptor GetTypeDescriptor(Type type)
 {
     var descriptor = TypeDescriptorHelper.Get(type);
     if (descriptor == null)
     {
         descriptor = base.GetTypeDescriptor(type);
     }
     return descriptor;
 }
Exemplo n.º 10
0
        private static ModelBinderAttribute GetModelBinderAttribute(Type modelType)
        {
            ModelBinderAttribute modelBinderAttribute;

            if (!_modelBinderAttributeCache.TryGetValue(modelType, out modelBinderAttribute))
            {
                modelBinderAttribute = TypeDescriptorHelper.Get(modelType).GetAttributes().OfType <ModelBinderAttribute>().FirstOrDefault();
                _modelBinderAttributeCache.TryAdd(modelType, modelBinderAttribute);
            }
            return(modelBinderAttribute);
        }
Exemplo n.º 11
0
        internal static bool TryGetProviderFromAttributes(Type modelType, out ModelBinderProvider provider)
        {
            ModelBinderAttribute attr = TypeDescriptorHelper.Get(modelType).GetAttributes().OfType <ModelBinderAttribute>().FirstOrDefault();

            if (attr == null)
            {
                provider = null;
                return(false);
            }

            return(TryGetProviderFromAttribute(modelType, attr, out provider));
        }
Exemplo n.º 12
0
        internal static bool IsRequiredDataMember(Type containerType, IEnumerable <Attribute> attributes)
        {
            DataMemberAttribute dataMemberAttribute = attributes.OfType <DataMemberAttribute>().FirstOrDefault();

            if (dataMemberAttribute != null)
            {
                // isDataContract == true iff the container type has at least one DataContractAttribute
                bool isDataContract = TypeDescriptorHelper.Get(containerType).GetAttributes().OfType <DataContractAttribute>().Any();
                if (isDataContract && dataMemberAttribute.IsRequired)
                {
                    return(true);
                }
            }
            return(false);
        }
        private TypeInformation CreateTypeInformation(Type type)
        {
            TypeInformation       info           = new TypeInformation();
            ICustomTypeDescriptor typeDescriptor = TypeDescriptorHelper.Get(type);

            info.TypeDescriptor = typeDescriptor;
            info.Prototype      = CreateMetadataPrototype(AsAttributes(typeDescriptor.GetAttributes()), containerType: null, modelType: type, propertyName: null);

            Dictionary <string, PropertyInformation> properties = new Dictionary <string, PropertyInformation>();

            foreach (PropertyDescriptor property in typeDescriptor.GetProperties())
            {
                properties.Add(property.Name, CreatePropertyInformation(type, property));
            }
            info.Properties = properties;

            return(info);
        }
Exemplo n.º 14
0
        internal static bool TryGetProviderFromAttributes(HttpParameterDescriptor parameterDescriptor, out ModelBinderProvider provider)
        {
            Contract.Assert(parameterDescriptor != null, "parameterDescriptor cannot be null.");

            Type modelType = parameterDescriptor.ParameterType;

            ModelBinderAttribute attr = parameterDescriptor.GetCustomAttributes <ModelBinderAttribute>().FirstOrDefault();

            if (attr == null)
            {
                attr = TypeDescriptorHelper.Get(modelType).GetAttributes().OfType <ModelBinderAttribute>().FirstOrDefault();
            }

            if (attr == null)
            {
                provider = null;
                return(false);
            }

            return(TryGetProviderFromAttribute(modelType, attr, out provider));
        }
Exemplo n.º 15
0
 protected virtual ICustomTypeDescriptor GetTypeDescriptor(Type type)
 {
     return(TypeDescriptorHelper.Get(type));
 }