Ejemplo n.º 1
0
        public void Validate(ModelBindingExecutionContext modelBindingExecutionContext, ModelValidationNode parentNode)
        {
            if (modelBindingExecutionContext == null)
            {
                throw new ArgumentNullException("modelBindingExecutionContext");
            }

            if (SuppressValidation)
            {
                // no-op
                return;
            }

            // pre-validation steps
            ModelValidatingEventArgs eValidating = new ModelValidatingEventArgs(modelBindingExecutionContext, parentNode);

            OnValidating(eValidating);
            if (eValidating.Cancel)
            {
                return;
            }

            ValidateChildren(modelBindingExecutionContext);
            ValidateThis(modelBindingExecutionContext, parentNode);

            // post-validation steps
            ModelValidatedEventArgs eValidated = new ModelValidatedEventArgs(modelBindingExecutionContext, parentNode);

            OnValidated(eValidated);
        }
Ejemplo n.º 2
0
 public override IModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
 {
     return((from provider in _providers
             let binder = provider.GetBinder(modelBindingExecutionContext, bindingContext)
                          where binder != null
                          select binder).FirstOrDefault());
 }
Ejemplo n.º 3
0
        public override IValueProvider GetValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
        {
            if (modelBindingExecutionContext == null)
            {
                throw new ArgumentNullException("modelBindingExecutionContext");
            }

            HttpSessionStateBase session = modelBindingExecutionContext.HttpContext.Session;

            if (session == null)
            {
                // session is disabled
                return(null);
            }

            Dictionary <string, object> backingStore = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            foreach (string key in session)
            {
                if (key != null)
                {
                    backingStore[key] = session[key]; // copy to backing store
                }
            }

            // use the invariant culture since Session contains serialized objects
            return(new DictionaryValueProvider <object>(backingStore, CultureInfo.InvariantCulture));
        }
Ejemplo n.º 4
0
            public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
            {
                ModelBinderUtil.ValidateBindingContext(bindingContext);
                ValueProviderResult vpResult = bindingContext.UnvalidatedValueProvider.GetValue(bindingContext.ModelName);

                // case 1: there was no <input ... /> element containing this data
                if (vpResult == null)
                {
                    return(false);
                }

                string base64string = (string)vpResult.ConvertTo(typeof(string));

                // case 2: there was an <input ... /> element but it was left blank
                if (String.IsNullOrEmpty(base64string))
                {
                    return(false);
                }

                // Future proofing. If the byte array is actually an instance of System.Data.Linq.Binary
                // then we need to remove these quotes put in place by the ToString() method.
                string realValue = base64string.Replace("\"", String.Empty);

                try {
                    bindingContext.Model = ConvertByteArray(Convert.FromBase64String(realValue));
                    return(true);
                }
                catch {
                    // corrupt data - just ignore
                    return(false);
                }
            }
Ejemplo n.º 5
0
 protected virtual void EnsureModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
 {
     if (bindingContext.Model == null)
     {
         bindingContext.ModelMetadata.Model = CreateModel(modelBindingExecutionContext, bindingContext);
     }
 }
Ejemplo n.º 6
0
        private void ValidateProperties(ModelBindingExecutionContext modelBindingExecutionContext)
        {
            // Based off CompositeModelValidator.
            ModelStateDictionary modelState = modelBindingExecutionContext.ModelState;

            // DevDiv Bugs #227802 - Caching problem in ModelMetadata requires us to manually regenerate
            // the ModelMetadata.
            object        model           = ModelMetadata.Model;
            ModelMetadata updatedMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, ModelMetadata.ModelType);

            foreach (ModelMetadata propertyMetadata in updatedMetadata.Properties)
            {
                // Only want to add errors to ModelState if something doesn't already exist for the property node,
                // else we could end up with duplicate or irrelevant error messages.
                string propertyKeyRoot = ModelBinderUtil.CreatePropertyModelName(ModelStateKey, propertyMetadata.PropertyName);

                if (modelState.IsValidField(propertyKeyRoot))
                {
                    foreach (ModelValidator propertyValidator in propertyMetadata.GetValidators(modelBindingExecutionContext))
                    {
                        foreach (ModelValidationResult propertyResult in propertyValidator.Validate(model))
                        {
                            string thisErrorKey = ModelBinderUtil.CreatePropertyModelName(propertyKeyRoot, propertyResult.MemberName);
                            modelState.AddModelError(thisErrorKey, propertyResult.Message);
                        }
                    }
                }
            }
        }
Ejemplo n.º 7
0
        public override IModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
        {
            ModelBinderUtil.ValidateBindingContext(bindingContext);

            Type[] typeArguments = null;
            if (ModelType.IsInterface)
            {
                Type matchingClosedInterface = TypeHelpers.ExtractGenericInterface(bindingContext.ModelType, ModelType);
                if (matchingClosedInterface != null)
                {
                    typeArguments = matchingClosedInterface.GetGenericArguments();
                }
            }
            else
            {
                typeArguments = TypeHelpers.GetTypeArgumentsIfMatch(bindingContext.ModelType, ModelType);
            }

            if (typeArguments != null)
            {
                if (SuppressPrefixCheck || bindingContext.UnvalidatedValueProvider.ContainsPrefix(bindingContext.ModelName))
                {
                    return(_modelBinderFactory(typeArguments));
                }
            }

            return(null);
        }
        public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
        {
            ModelBindingContext newBindingContext = bindingContext;
            IModelBinder        binder            = Providers.GetBinder(modelBindingExecutionContext, bindingContext);

            if (binder == null && !String.IsNullOrEmpty(bindingContext.ModelName) &&
                bindingContext.ModelMetadata.IsComplexType)
            {
                // fallback to empty prefix?
                newBindingContext = new ModelBindingContext(bindingContext)
                {
                    ModelName     = String.Empty,
                    ModelMetadata = bindingContext.ModelMetadata
                };
                binder = Providers.GetBinder(modelBindingExecutionContext, newBindingContext);
            }

            if (binder != null)
            {
                bool boundSuccessfully = binder.BindModel(modelBindingExecutionContext, newBindingContext);
                if (boundSuccessfully)
                {
                    // run validation
                    newBindingContext.ValidationNode.Validate(modelBindingExecutionContext, parentNode: null);
                    return(true);
                }
            }

            return(false); // something went wrong
        }
        private static string GetUserResourceString(ModelBindingExecutionContext modelBindingExecutionContext, string resourceName)
        {
#if UNDEF
            return(GetUserResourceString(modelBindingExecutionContext, resourceName, DefaultModelBinder.ResourceClassKey));
#endif
            return(GetUserResourceString(modelBindingExecutionContext, resourceName, String.Empty));
        }
Ejemplo n.º 10
0
        internal void ProcessComplexModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext, ComplexModel complexModel)
        {
            HashSet <string> requiredProperties;
            HashSet <string> skipProperties;

            GetRequiredPropertiesCollection(bindingContext.ModelType, out requiredProperties, out skipProperties);

            // Are all of the required fields accounted for?
            HashSet <string> missingRequiredProperties = new HashSet <string>(requiredProperties);

            missingRequiredProperties.ExceptWith(complexModel.Results.Select(r => r.Key.PropertyName));
            string missingPropertyName = missingRequiredProperties.FirstOrDefault();

            if (missingPropertyName != null)
            {
                string fullPropertyKey = ModelBinderUtil.CreatePropertyModelName(bindingContext.ModelName, missingPropertyName);
                throw Error.BindingBehavior_ValueNotFound(fullPropertyKey);
            }

            // for each property that was bound, call the setter, recording exceptions as necessary
            foreach (var entry in complexModel.Results)
            {
                ModelMetadata propertyMetadata = entry.Key;

                ComplexModelResult complexModelResult = entry.Value;
                if (complexModelResult != null)
                {
                    SetProperty(modelBindingExecutionContext, bindingContext, propertyMetadata, complexModelResult);
                    bindingContext.ValidationNode.ChildNodes.Add(complexModelResult.ValidationNode);
                }
            }
        }
Ejemplo n.º 11
0
        // Used when the ValueProvider contains the collection to be bound as multiple elements, e.g. foo[0], foo[1].
        private static List <TElement> BindComplexCollection(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
        {
            string indexPropertyName           = ModelBinderUtil.CreatePropertyModelName(bindingContext.ModelName, "index");
            ValueProviderResult  vpResultIndex = bindingContext.UnvalidatedValueProvider.GetValue(indexPropertyName);
            IEnumerable <string> indexNames    = CollectionModelBinderUtil.GetIndexNamesFromValueProviderResult(vpResultIndex);

            return(BindComplexCollectionFromIndexes(modelBindingExecutionContext, bindingContext, indexNames));
        }
        private static string GetResourceCommon(ModelBindingExecutionContext modelBindingExecutionContext, ModelMetadata modelMetadata, object incomingValue, Func <ModelBindingExecutionContext, string> resourceAccessor)
        {
            string displayName          = modelMetadata.GetDisplayName();
            string errorMessageTemplate = resourceAccessor(modelBindingExecutionContext);
            string errorMessage         = String.Format(CultureInfo.CurrentCulture, errorMessageTemplate, incomingValue, displayName);

            return(errorMessage);
        }
Ejemplo n.º 13
0
        public IValueProvider GetValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
        {
            if (modelBindingExecutionContext == null)
            {
                throw new ArgumentNullException("modelBindingExecutionContext");
            }

            return(new UserProfileValueProvider(modelBindingExecutionContext));
        }
        public override IValueProvider GetValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
        {
            if (modelBindingExecutionContext == null)
            {
                throw new ArgumentNullException("modelBindingExecutionContext");
            }

            return(new FormValueProvider(modelBindingExecutionContext));
        }
Ejemplo n.º 15
0
        protected virtual void SetProperty(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext, ModelMetadata propertyMetadata, ComplexModelResult complexModelResult)
        {
            PropertyDescriptor propertyDescriptor = TypeDescriptorHelper.Get(bindingContext.ModelType).GetProperties().Find(propertyMetadata.PropertyName, true /* ignoreCase */);

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

            object value = complexModelResult.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 = complexModelResult.ValidationNode.ModelStateKey;
                if (bindingContext.ModelState.IsValidField(modelStateKey))
                {
                    ModelValidator requiredValidator = ModelValidatorProviders.Providers.GetValidators(propertyMetadata, modelBindingExecutionContext).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 = complexModelResult.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 = complexModelResult.ValidationNode.ModelStateKey;
                if (bindingContext.ModelState.IsValidField(modelStateKey))
                {
                    complexModelResult.ValidationNode.Validated += CreateNullCheckFailedHandler(modelBindingExecutionContext, propertyMetadata, value);
                }
            }
        }
Ejemplo n.º 16
0
        protected override object FetchValue(string key)
        {
            StateBag pageViewState = ModelBindingExecutionContext.GetService <StateBag>();

            if (pageViewState != null)
            {
                return(pageViewState[key]);
            }
            return(null);
        }
        internal IModelBinder GetRequiredBinder(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
        {
            IModelBinder binder = GetBinder(modelBindingExecutionContext, bindingContext);

            if (binder == null)
            {
                throw Error.ModelBinderProviderCollection_BinderForTypeNotFound(bindingContext.ModelType);
            }
            return(binder);
        }
        public DataAnnotationsModelValidator(ModelMetadata metadata, ModelBindingExecutionContext context, ValidationAttribute attribute)
            : base(metadata, context)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException("attribute");
            }

            Attribute = attribute;
        }
        public ModelValidatedEventArgs(ModelBindingExecutionContext modelBindingExecutionContext, ModelValidationNode parentNode)
        {
            if (modelBindingExecutionContext == null)
            {
                throw new ArgumentNullException("modelBindingExecutionContext");
            }

            ModelBindingExecutionContext = modelBindingExecutionContext;
            ParentNode = parentNode;
        }
Ejemplo n.º 20
0
        private static RouteValueDictionary GetRouteValues(ModelBindingExecutionContext modelBindingExecutionContext)
        {
            RouteData routeData = modelBindingExecutionContext.GetService <RouteData>();

            if (routeData != null)
            {
                return(routeData.Values);
            }

            return(new RouteValueDictionary());
        }
Ejemplo n.º 21
0
        private void ValidateChildren(ModelBindingExecutionContext modelBindingExecutionContext)
        {
            foreach (ModelValidationNode child in ChildNodes)
            {
                child.Validate(modelBindingExecutionContext, this);
            }

            if (ValidateAllProperties)
            {
                ValidateProperties(modelBindingExecutionContext);
            }
        }
Ejemplo n.º 22
0
        public override IModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
        {
            ModelBinderUtil.ValidateBindingContext(bindingContext);

            if (!bindingContext.ModelMetadata.IsReadOnly && bindingContext.ModelType.IsArray &&
                bindingContext.UnvalidatedValueProvider.ContainsPrefix(bindingContext.ModelName))
            {
                Type elementType = bindingContext.ModelType.GetElementType();
                return((IModelBinder)Activator.CreateInstance(typeof(ArrayModelBinder <>).MakeGenericType(elementType)));
            }

            return(null);
        }
Ejemplo n.º 23
0
        public virtual bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
        {
            ModelBinderUtil.ValidateBindingContext(bindingContext);

            ValueProviderResult vpResult        = bindingContext.UnvalidatedValueProvider.GetValue(bindingContext.ModelName, skipValidation: !bindingContext.ValidateRequest);
            List <TElement>     boundCollection = (vpResult != null)
                ? BindSimpleCollection(modelBindingExecutionContext, bindingContext, vpResult.RawValue, vpResult.Culture)
                : BindComplexCollection(modelBindingExecutionContext, bindingContext);

            bool retVal = CreateOrReplaceCollection(modelBindingExecutionContext, bindingContext, boundCollection);

            return(retVal);
        }
        public override IModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
        {
            ModelBinderUtil.ValidateBindingContext(bindingContext);

            if (bindingContext.UnvalidatedValueProvider.ContainsPrefix(bindingContext.ModelName))
            {
                return(CollectionModelBinderUtil.GetGenericBinder(typeof(IDictionary <,>), typeof(Dictionary <,>), typeof(DictionaryModelBinder <,>), bindingContext.ModelMetadata));
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 25
0
        internal static List <TElement> BindComplexCollectionFromIndexes(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext, IEnumerable <string> indexNames)
        {
            bool indexNamesIsFinite;

            if (indexNames != null)
            {
                indexNamesIsFinite = true;
            }
            else
            {
                indexNamesIsFinite = false;
                indexNames         = CollectionModelBinderUtil.GetZeroBasedIndexes();
            }

            List <TElement> boundCollection = new List <TElement>();

            foreach (string indexName in indexNames)
            {
                string fullChildName = ModelBinderUtil.CreateIndexModelName(bindingContext.ModelName, indexName);
                ModelBindingContext childBindingContext = new ModelBindingContext(bindingContext)
                {
                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TElement)),
                    ModelName     = fullChildName
                };

                object       boundValue  = null;
                IModelBinder childBinder = bindingContext.ModelBinderProviders.GetBinder(modelBindingExecutionContext, childBindingContext);
                if (childBinder != null)
                {
                    if (childBinder.BindModel(modelBindingExecutionContext, childBindingContext))
                    {
                        boundValue = childBindingContext.Model;

                        // merge validation up
                        bindingContext.ValidationNode.ChildNodes.Add(childBindingContext.ValidationNode);
                    }
                }
                else
                {
                    // should we even bother continuing?
                    if (!indexNamesIsFinite)
                    {
                        break;
                    }
                }

                boundCollection.Add(ModelBinderUtil.CastOrDefault <TElement>(boundValue));
            }

            return(boundCollection);
        }
Ejemplo n.º 26
0
        public override IModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
        {
            ModelBinderUtil.ValidateBindingContext(bindingContext);

            if (bindingContext.ModelType == ModelType)
            {
                if (SuppressPrefixCheck || bindingContext.UnvalidatedValueProvider.ContainsPrefix(bindingContext.ModelName))
                {
                    return(_modelBinderFactory());
                }
            }

            return(null);
        }
Ejemplo n.º 27
0
        protected virtual IEnumerable <ModelMetadata> GetMetadataForProperties(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
        {
            // keep a set of the required properties so that we can cross-reference bound properties later
            HashSet <string> requiredProperties;
            HashSet <string> skipProperties;

            GetRequiredPropertiesCollection(bindingContext.ModelType, out requiredProperties, out skipProperties);

            return(from propertyMetadata in bindingContext.ModelMetadata.Properties
                   let propertyName = propertyMetadata.PropertyName
                                      let shouldUpdateProperty = requiredProperties.Contains(propertyName) || !skipProperties.Contains(propertyName)
                                                                 where shouldUpdateProperty && CanUpdateProperty(propertyMetadata)
                                                                 select propertyMetadata);
        }
Ejemplo n.º 28
0
        protected ModelValidator(ModelMetadata metadata, ModelBindingExecutionContext modelBindingExecutionContext)
        {
            if (metadata == null)
            {
                throw new ArgumentNullException("metadata");
            }
            if (modelBindingExecutionContext == null)
            {
                throw new ArgumentNullException("modelBindingExecutionContext");
            }

            Metadata = metadata;
            ModelBindingExecutionContext = modelBindingExecutionContext;
        }
Ejemplo n.º 29
0
        private ComplexModel CreateAndPopulateComplexModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext, IEnumerable <ModelMetadata> propertyMetadatas)
        {
            // create a Complex Model and call into the Complex Model binder
            ComplexModel        originalComplexModel       = new ComplexModel(bindingContext.ModelMetadata, propertyMetadatas);
            ModelBindingContext complexModelBindingContext = new ModelBindingContext(bindingContext)
            {
                ModelMetadata = MetadataProvider.GetMetadataForType(() => originalComplexModel, typeof(ComplexModel)),
                ModelName     = bindingContext.ModelName
            };

            IModelBinder complexModelBinder = bindingContext.ModelBinderProviders.GetRequiredBinder(modelBindingExecutionContext, complexModelBindingContext);

            complexModelBinder.BindModel(modelBindingExecutionContext, complexModelBindingContext);
            return((ComplexModel)complexModelBindingContext.Model);
        }
Ejemplo n.º 30
0
        public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
        {
            ModelBinderUtil.ValidateBindingContext(bindingContext, typeof(KeyValuePair <TKey, TValue>), true /* allowNullModel */);

            TKey key;
            bool keyBindingSucceeded = KeyValuePairModelBinderUtil.TryBindStrongModel <TKey>(modelBindingExecutionContext, bindingContext, "key", MetadataProvider, out key);

            TValue value;
            bool   valueBindingSucceeded = KeyValuePairModelBinderUtil.TryBindStrongModel <TValue>(modelBindingExecutionContext, bindingContext, "value", MetadataProvider, out value);

            if (keyBindingSucceeded && valueBindingSucceeded)
            {
                bindingContext.Model = new KeyValuePair <TKey, TValue>(key, value);
            }
            return(keyBindingSucceeded || valueBindingSucceeded);
        }