public void BinderReturnsNullIfValueProviderDoesNotContainKey()
        {
            // Arrange
            DeserializeAttribute attr      = new DeserializeAttribute();
            IModelBinder         binder    = attr.GetBinder();
            ModelBindingContext  mbContext = new ModelBindingContext
            {
                ModelName     = "someKey",
                ValueProvider = new SimpleValueProvider()
            };

            // Act
            object retVal = binder.BindModel(null, mbContext);

            // Assert
            Assert.Null(retVal);
        }
Пример #2
0
        private ComplexModelDto CreateAndPopulateDto(HttpActionContext actionContext, ModelBindingContext bindingContext, IEnumerable <ModelMetadata> propertyMetadatas)
        {
            ModelMetadataProvider metadataProvider = MetadataProvider ?? actionContext.GetMetadataProvider();

            // create a DTO and call into the DTO binder
            ComplexModelDto     originalDto       = new ComplexModelDto(bindingContext.ModelMetadata, propertyMetadatas);
            ModelBindingContext dtoBindingContext = new ModelBindingContext(bindingContext)
            {
                ModelMetadata = metadataProvider.GetMetadataForType(() => originalDto, typeof(ComplexModelDto)),
                ModelName     = bindingContext.ModelName
            };

            IModelBinder dtoBinder = actionContext.GetBinder(dtoBindingContext);

            dtoBinder.BindModel(actionContext, dtoBindingContext);
            return((ComplexModelDto)dtoBindingContext.Model);
        }
Пример #3
0
        /// <summary>
        /// Adiciona os itens para o dicionário.
        /// </summary>
        /// <param name="dictionary"></param>
        /// <param name="dictionaryType">Tipo do dicionário.</param>
        /// <param name="modelName"></param>
        /// <param name="controllerContext"></param>
        /// <param name="bindingContext"></param>
        private void AddItemsToDictionary(IDictionary dictionary, Type dictionaryType, string modelName, ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            List <string> keys    = new List <string>();
            var           request = controllerContext.HttpContext.Request;

            keys.AddRange(((IDictionary <string, object>)controllerContext.RouteData.Values).Keys.Cast <string>());
            keys.AddRange(request.QueryString.Keys.Cast <string>());
            keys.AddRange(request.Form.Keys.Cast <string>());
            Type         dictionaryValueType   = dictionaryType.GetGenericArguments()[1];
            IModelBinder dictionaryValueBinder = Binders.GetBinder(dictionaryValueType);

            foreach (string key in keys)
            {
                string dictItemKey    = null;
                string valueModelName = null;
                if (!key.Equals("area", StringComparison.InvariantCultureIgnoreCase) && !key.Equals("controller", StringComparison.InvariantCultureIgnoreCase) && !key.Equals("action", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (key.StartsWith(modelName + "[", StringComparison.InvariantCultureIgnoreCase))
                    {
                        int endIndex = key.IndexOf("]", modelName.Length + 1);
                        if (endIndex != -1)
                        {
                            dictItemKey    = key.Substring(modelName.Length + 1, endIndex - modelName.Length - 1);
                            valueModelName = key.Substring(0, endIndex + 1);
                        }
                    }
                    else
                    {
                        dictItemKey = valueModelName = key;
                    }
                    if (dictItemKey != null && valueModelName != null && !dictionary.Contains(dictItemKey))
                    {
                        object dictItemValue = dictionaryValueBinder.BindModel(controllerContext, new ModelBindingContext(bindingContext)
                        {
                            ModelName     = valueModelName,
                            ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, dictionaryValueType)
                        });
                        if (dictItemValue != null)
                        {
                            dictionary.Add(dictItemKey, dictItemValue);
                        }
                    }
                }
            }
        }
Пример #4
0
        public IEnumerable <T> FindAll <T>(IDbDataAdapter adapter, string sql, IDbDataParameter[] paramters)
        {
            QueryKey        key    = new QueryKey(sql, new QueryParameters(paramters));
            IEnumerable <T> result = (IEnumerable <T>)cache.Get(key);

            if (result != null)
            {
                return(result);
            }

            IModelBinder binder = ModelBinderFactory.Current.GetModelBinder();

            IEnumerable <T> list = binder.BindModel <T>(GetDataTable(adapter, sql, paramters));

            cache.Put(key, list, DateTime.Now.AddMinutes(1).Ticks);

            return(list);
        }
Пример #5
0
        protected virtual object GetPropertyValue(
            ControllerContext controllerContext,
            ModelBindingContext bindingContext,
            PropertyDescriptor propertyDescriptor,
            IModelBinder propertyBinder
            )
        {
            object value = propertyBinder.BindModel(controllerContext, bindingContext);

            if (
                bindingContext.ModelMetadata.ConvertEmptyStringToNull && Equals(value, String.Empty)
                )
            {
                return(null);
            }

            return(value);
        }
Пример #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="modeltype"></param>
        /// <param name="ignoreModelStateError"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="InvalidCastException"></exception>
        public static object GetModel(Controller controller, Type modeltype, bool ignoreModelStateError)
        {
            if (modeltype == null)
            {
                throw new ArgumentNullException("modeltype");
            }
            var model = DependencyResolver.Current.GetService(modeltype);

            if (model == null)
            {
                throw new ArgumentNullException("model");
            }


            var controllerContext = controller.ControllerContext;

            var valueProvider = ValueProviderFactories.Factories.GetValueProvider(controllerContext);

            IModelBinder binder = ModelBinders.Binders.GetBinder(modeltype);

            var innerModelState = new ModelStateDictionary();

            var bindingContext = new ModelBindingContext()
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, modeltype),
                //ModelName = prefix,
                ModelState = innerModelState,
                //PropertyFilter = propertyFilter,
                ValueProvider = valueProvider
            };



            var obj = binder.BindModel(controllerContext, bindingContext);

            var error = Dev.Comm.Web.Mvc.Model.ModelStateHandler.GetAllError(innerModelState);

            if (!ignoreModelStateError && error.Any())
            {
                throw new InvalidCastException(string.Join(",", error.Select(x => x.ErrorMessage)));
            }

            return(obj);
        }
Пример #7
0
        /// <summary>
        /// Gets the value of the specified action-method parameter.
        /// </summary>
        public virtual object GetParameterValue(ParameterDescriptor parameterDescriptor)
        {
            Type                parameterType  = parameterDescriptor.ParameterType;
            IModelBinder        modelBinder    = GetModelBinder(parameterDescriptor);
            IValueProvider      valueProvider  = ControllerContext.Controller.ValueProvider;
            string              str            = parameterDescriptor.BindingInfo.Prefix ?? parameterDescriptor.ParameterName;
            Predicate <string>  propertyFilter = GetPropertyFilter(parameterDescriptor);
            ModelBindingContext bindingContext = new ModelBindingContext()
            {
                FallbackToEmptyPrefix = parameterDescriptor.BindingInfo.Prefix == null,
                ModelMetadata         = ModelMetadataProviders.Current.GetMetadataForType((Func <object>)null, parameterType),
                ModelName             = str,
                ModelState            = ControllerContext.Controller.ViewData.ModelState,
                PropertyFilter        = propertyFilter,
                ValueProvider         = valueProvider
            };

            return(modelBinder.BindModel(ControllerContext, bindingContext) ?? parameterDescriptor.DefaultValue);
        }
        internal object UpdateCollection(ControllerContext controllerContext, ModelBindingContext bindingContext, Type elementType)
        {
            IModelBinder elementBinder = Binders.GetBinder(elementType);

            // build up a list of items from the request
            List <object> modelList = new List <object>();

            for (int currentIndex = 0; ; currentIndex++)
            {
                string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currentIndex);
                if (!DictionaryHelpers.DoesAnyKeyHavePrefix(bindingContext.ValueProvider, subIndexKey))
                {
                    // we ran out of elements to pull
                    break;
                }

                ModelBindingContext innerContext = new ModelBindingContext()
                {
                    ModelName      = subIndexKey,
                    ModelState     = bindingContext.ModelState,
                    ModelType      = elementType,
                    PropertyFilter = bindingContext.PropertyFilter,
                    ValueProvider  = bindingContext.ValueProvider
                };
                object thisElement = elementBinder.BindModel(controllerContext, innerContext);

                // we need to merge model errors up
                VerifyValueUsability(controllerContext, bindingContext.ModelState, subIndexKey, elementType, thisElement);
                modelList.Add(thisElement);
            }

            // if there weren't any elements at all in the request, just return
            if (modelList.Count == 0)
            {
                return(null);
            }

            // replace the original collection
            object collection = bindingContext.Model;

            CollectionHelpers.ReplaceCollection(elementType, collection, modelList);
            return(collection);
        }
Пример #9
0
        public void GetBinder_InvalidValueProviderResult_ReturnsNull()
        {
            // Arrange
            ModelBindingContext bindingContext = GetBindingContext();

            bindingContext.ValueProvider = new SimpleHttpValueProvider
            {
                { "theModelName", "not an integer" }
            };

            TypeMatchModelBinderProvider provider = new TypeMatchModelBinderProvider();

            // Act
            IModelBinder binder = provider.GetBinder(null, bindingContext.ModelType);
            bool         bound  = binder.BindModel(null, bindingContext);

            // Assert
            Assert.False(bound);
        }
Пример #10
0
        public void GetBinder_ValueProviderDoesNotContainPrefix_ReturnsNull()
        {
            // Arrange
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int[])),
                ModelName     = "foo",
                ValueProvider = new SimpleHttpValueProvider()
            };

            ArrayModelBinderProvider binderProvider = new ArrayModelBinderProvider();

            // Act
            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);
            bool         bound  = binder.BindModel(null, bindingContext);

            // Assert
            Assert.False(bound);
        }
Пример #11
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string componentName = bindingContext.ModelName.ToLower() + "modelbinder";

            if (_container.Kernel.HasComponent(componentName))
            {
                var binderFromWindsor = _container.Resolve(componentName) as IModelBinder;

                if (binderFromWindsor == null)
                {
                    throw new InvalidOperationException(string.Format("Expected component with key {0} to be an IModelBinder.", componentName));
                }

                return(binderFromWindsor.BindModel(null, bindingContext));
            }

            // Delegate to the base binder if the type hasn't been registered in Windsor (also does String, Int32 etc if we're using DefaultModelBinder)
            return(_defaultModelBinder.BindModel(null, bindingContext));
        }
Пример #12
0
        /// <summary>
        /// Attempt to bind against the given ActionContext.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        /// <param name="bindingContext">The binding context.</param>
        /// <param name="binders">set of binders to use for binding</param>
        /// <returns>True if the bind was successful, else false.</returns>
        public static bool Bind(this HttpActionContext actionContext, ModelBindingContext bindingContext, IEnumerable <IModelBinder> binders)
        {
            if (actionContext == null)
            {
                throw Error.ArgumentNull("actionContext");
            }

            if (bindingContext == null)
            {
                throw Error.ArgumentNull("bindingContext");
            }

            // Protects against stack overflow for deeply nested model binding
            EnsureStackHelper.EnsureStack();

            Type modelType           = bindingContext.ModelType;
            HttpConfiguration config = actionContext.ControllerContext.Configuration;

            ModelBinderProvider providerFromAttr;

            if (ModelBindingHelper.TryGetProviderFromAttributes(modelType, out providerFromAttr))
            {
                IModelBinder binder = providerFromAttr.GetBinder(config, modelType);
                if (binder != null)
                {
                    return(binder.BindModel(actionContext, bindingContext));
                }
            }

            foreach (IModelBinder binder in binders)
            {
                if (binder != null)
                {
                    if (binder.BindModel(actionContext, bindingContext))
                    {
                        return(true);
                    }
                }
            }

            // Either we couldn't find a binder, or the binder couldn't bind. Distinction is not important.
            return(false);
        }
Пример #13
0
        public void GetBinder_TypeMatches_PrefixNotFound_ReturnsNull()
        {
            // Arrange
            IModelBinder binderInstance        = new Mock <IModelBinder>().Object;
            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(
                typeof(string),
                binderInstance
                );

            ModelBindingContext bindingContext = GetBindingContext(typeof(string));

            bindingContext.ValueProvider = new SimpleHttpValueProvider();

            // Act
            IModelBinder returnedBinder = provider.GetBinder(null, bindingContext.ModelType);
            bool         bound          = returnedBinder.BindModel(null, bindingContext);

            // Assert
            Assert.False(bound);
        }
Пример #14
0
        public void BinderReturnsDeserializedValue()
        {
            // Arrange
            DeserializeAttribute attr      = new DeserializeAttribute();
            IModelBinder         binder    = attr.GetBinder();
            ModelBindingContext  mbContext = new ModelBindingContext()
            {
                ModelName     = "someKey",
                ValueProvider = new SimpleValueProvider()
                {
                    { "someKey", "/wECKg==" }
                }
            };

            // Act
            object retVal = binder.BindModel(null, mbContext);

            // Assert
            Assert.AreEqual(42, retVal, "Object was not properly deserialized.");
        }
Пример #15
0
        private static object ReadAsInternal(this FormDataCollection formData, Type type, string modelName, HttpActionContext actionContext)
        {
            Contract.Assert(formData != null);
            Contract.Assert(type != null);
            Contract.Assert(actionContext != null);

            IValueProvider      valueProvider  = formData.GetJQueryValueProvider();
            ModelBindingContext bindingContext = CreateModelBindingContext(actionContext, modelName ?? String.Empty, type, valueProvider);

            ModelBinderProvider modelBinderProvider = CreateModelBindingProvider(actionContext);

            IModelBinder modelBinder = modelBinderProvider.GetBinder(actionContext.ControllerContext.Configuration, type);
            bool         haveResult  = modelBinder.BindModel(actionContext, bindingContext);

            if (haveResult)
            {
                return(bindingContext.Model);
            }

            return(MediaTypeFormatter.GetDefaultValueForType(type));
        }
    private static KeyValuePair <string, object> CreateEntryForModel(
        ControllerContext controllerContext,
        ModelBindingContext bindingContext,
        Type valueType,
        IModelBinder valueBinder,
        string modelName,
        string modelKey)
    {
        var valueBindingContext = new ModelBindingContext()
        {
            ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(null, valueType),
            ModelName      = modelName,
            ModelState     = bindingContext.ModelState,
            PropertyFilter = bindingContext.PropertyFilter,
            ValueProvider  = bindingContext.ValueProvider
        };

        var thisValue = valueBinder.BindModel(controllerContext, valueBindingContext);

        return(new KeyValuePair <string, object>(modelKey, thisValue));
    }
        public virtual bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            //// REVIEW: from MVC Futures
            ////CheckPropertyFilter(bindingContext);

            ModelBindingContext newBindingContext = CreateNewBindingContext(bindingContext, bindingContext.ModelName);

            IModelBinder binder = GetBinder(actionContext, newBindingContext);

            if (binder == null && !String.IsNullOrEmpty(bindingContext.ModelName) &&
                bindingContext.FallbackToEmptyPrefix)
            {
                // fallback to empty prefix?
                newBindingContext = CreateNewBindingContext(bindingContext, String.Empty /* modelName */);
                binder            = GetBinder(actionContext, newBindingContext);
            }

            if (binder != null)
            {
                bool boundSuccessfully = binder.BindModel(actionContext, newBindingContext);
                if (boundSuccessfully)
                {
                    // run validation and return the model
                    // If we fell back to an empty prefix above and are dealing with simple types,
                    // propagate the non-blank model name through for user clarity in validation errors.
                    // Complex types will reveal their individual properties as model names and do not require this.
                    if (!newBindingContext.ModelMetadata.IsComplexType && String.IsNullOrEmpty(newBindingContext.ModelName))
                    {
                        newBindingContext.ValidationNode = new Validation.ModelValidationNode(newBindingContext.ModelMetadata, bindingContext.ModelName);
                    }

                    newBindingContext.ValidationNode.Validate(actionContext, null /* parentNode */);
                    bindingContext.Model = newBindingContext.Model;
                    return(true);
                }
            }

            return(false); // something went wrong
        }
        private object BindCollection(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            object collection           = bindingContext.Model;
            Type   collectionMemberType = typeof(Object);

            if (collection.GetType().IsGenericType)
            {
                collectionMemberType =
                    collection.GetType().GetGenericArguments()[0];
            }
            int count = collection.CollectionGetCount();

            for (int index = 0; index < count; index++)
            {
                // Create a BindingContext for the collection member:
                ModelBindingContext innerContext = new ModelBindingContext();
                object member     = collection.CollectionGetItem(index);
                Type   memberType =
                    (member == null) ? collectionMemberType : member.GetType();
                innerContext.ModelMetadata =
                    ModelMetadataProviders.Current.GetMetadataForType(
                        delegate() { return(member); },
                        memberType);
                innerContext.ModelName =
                    String.Format("{0}[{1}]", bindingContext.ModelName, index);
                innerContext.ModelState     = bindingContext.ModelState;
                innerContext.PropertyFilter = bindingContext.PropertyFilter;
                innerContext.ValueProvider  = bindingContext.ValueProvider;

                // Bind the collection member:
                IModelBinder binder      = Binders.GetBinder(memberType);
                object       boundMember =
                    binder.BindModel(controllerContext, innerContext) ?? member;
                collection.CollectionSetItem(index, boundMember);
            }

            // Return the collection:
            return(collection);
        }
        private object GetParameterValue(ParameterDescriptor pd, ActionExecutingContext filterContext)
        {
            Type               parameterType  = pd.ParameterType;
            IModelBinder       binder         = pd.BindingInfo.Binder ?? ModelBinders.Binders.GetBinder(pd.ParameterType);
            IValueProvider     valueProvider  = filterContext.Controller.ValueProvider;
            string             parameterName  = pd.BindingInfo.Prefix ?? pd.ParameterName;
            Predicate <string> propertyFilter = GetPropertyFilter(pd);

            ModelBindingContext bindingContext = new ModelBindingContext()
            {
                FallbackToEmptyPrefix = (pd.BindingInfo.Prefix == null),
                ModelMetadata         = ModelMetadataProviders.Current.GetMetadataForType(null, parameterType),
                ModelName             = parameterName,
                ModelState            = filterContext.Controller.ViewData.ModelState,
                PropertyFilter        = propertyFilter,
                ValueProvider         = valueProvider
            };

            object result = binder.BindModel(filterContext, bindingContext);

            return(result ?? pd.DefaultValue);
        }
Пример #20
0
        protected internal bool TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties, IDictionary<string, ValueProviderResult> valueProvider) where TModel : class {
            if (model == null) {
                throw new ArgumentNullException("model");
            }
            if (valueProvider == null) {
                throw new ArgumentNullException("valueProvider");
            }

            Predicate<string> propertyFilter = propertyName => BindAttribute.IsPropertyAllowed(propertyName, includeProperties, excludeProperties);
            IModelBinder binder = Binders.GetBinder(typeof(TModel));

            ModelBindingContext bindingContext = new ModelBindingContext() {
                Model = model,
                ModelName = prefix,
                ModelState = ModelState,
                ModelType = typeof(TModel),
                PropertyFilter = propertyFilter,
                ValueProvider = valueProvider
            };
            binder.BindModel(ControllerContext, bindingContext);
            return ModelState.IsValid;
        }
Пример #21
0
        public void BindModel_EmptyValue_Fails()
        {
            // Arrange
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(byte[])),
                ModelName     = "foo",
                ValueProvider = new SimpleHttpValueProvider
                {
                    { "foo", "" }
                }
            };

            BinaryDataModelBinderProvider binderProvider = new BinaryDataModelBinderProvider();

            // Act
            IModelBinder binder = binderProvider.GetBinder(null, bindingContext);
            bool         retVal = binder.BindModel(null, bindingContext);

            // Assert
            Assert.False(retVal);
        }
        public void CustomBinderBindModelReturnsFormCollection()
        {
            // Arrange
            NameValueCollection nvc = new NameValueCollection()
            {
                { "foo", "fooValue" }, { "bar", "barValue" }
            };
            IModelBinder binder = ModelBinders.Binders.GetBinder(typeof(FormCollection));

            Mock <ControllerContext> mockControllerContext = new Mock <ControllerContext>();

            mockControllerContext.Setup(c => c.HttpContext.Request.Form).Returns(nvc);

            // Act
            FormCollection formCollection = (FormCollection)binder.BindModel(mockControllerContext.Object, null);

            // Assert
            Assert.NotNull(formCollection);
            Assert.Equal(2, formCollection.Count);
            Assert.Equal("fooValue", nvc["foo"]);
            Assert.Equal("barValue", nvc["bar"]);
        }
Пример #23
0
        // Used when the ValueProvider contains the collection to be bound as a single element, e.g. the raw value
        // is [ "1", "2" ] and needs to be converted to an int[].
        internal static List <TElement> BindSimpleCollection(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext, object rawValue, CultureInfo culture)
        {
            if (rawValue == null)
            {
                return(null); // nothing to do
            }

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

            object[] rawValueArray = ModelBinderUtil.RawValueToObjectArray(rawValue);
            foreach (object rawValueElement in rawValueArray)
            {
                ModelBindingContext innerBindingContext = new ModelBindingContext(bindingContext)
                {
                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TElement)),
                    ModelName     = bindingContext.ModelName,
                    ValueProvider = new ValueProviderCollection()                                       // aggregate value provider
                    {
                        new ElementalValueProvider(bindingContext.ModelName, rawValueElement, culture), // our temporary provider goes at the front of the list
                        bindingContext.ValueProvider
                    }
                };

                object       boundValue  = null;
                IModelBinder childBinder = bindingContext.ModelBinderProviders.GetBinder(modelBindingExecutionContext, innerBindingContext);
                if (childBinder != null)
                {
                    if (childBinder.BindModel(modelBindingExecutionContext, innerBindingContext))
                    {
                        boundValue = innerBindingContext.Model;
                        bindingContext.ValidationNode.ChildNodes.Add(innerBindingContext.ValidationNode);
                    }
                }
                boundCollection.Add(ModelBinderUtil.CastOrDefault <TElement>(boundValue));
            }

            return(boundCollection);
        }
Пример #24
0
        protected virtual object GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
        {
            // collect all of the necessary binding properties
            Type               parameterType  = parameterDescriptor.ParameterType;
            IModelBinder       binder         = GetModelBinder(parameterDescriptor);
            IValueProvider     valueProvider  = controllerContext.Controller.ValueProvider;
            string             parameterName  = parameterDescriptor.BindingInfo.Prefix ?? parameterDescriptor.ParameterName;
            Predicate <string> propertyFilter = GetPropertyFilter(parameterDescriptor);

            ModelBindingContext bindingContext = new ModelBindingContext()
            {
                FallbackToEmptyPrefix = (parameterDescriptor.BindingInfo.Prefix == null), // only fall back if prefix not specified
                ModelMetadata         = ModelMetadataProviders.Current.GetMetadataForType(null, parameterType),
                ModelName             = parameterName,
                ModelState            = controllerContext.Controller.ViewData.ModelState,
                PropertyFilter        = propertyFilter,
                ValueProvider         = valueProvider
            };

            object result = binder.BindModel(controllerContext, bindingContext);

            return(result ?? parameterDescriptor.DefaultValue);
        }
        protected virtual object GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
        {
            // collect all of the necessary binding properties
            Type         parameterType = parameterDescriptor.ParameterType;
            IModelBinder binder        = GetModelBinder(parameterDescriptor);
            IDictionary <string, ValueProviderResult> valueProvider = controllerContext.Controller.ValueProvider;
            string             parameterName  = parameterDescriptor.BindingInfo.Prefix ?? parameterDescriptor.ParameterName;
            Predicate <string> propertyFilter = GetPropertyFilter(parameterDescriptor);

            // finally, call into the binder
            ModelBindingContext bindingContext = new ModelBindingContext()
            {
                FallbackToEmptyPrefix = (parameterDescriptor.BindingInfo.Prefix == null), // only fall back if prefix not specified
                ModelName             = parameterName,
                ModelState            = controllerContext.Controller.ViewData.ModelState,
                ModelType             = parameterType,
                PropertyFilter        = propertyFilter,
                ValueProvider         = valueProvider
            };
            object result = binder.BindModel(controllerContext, bindingContext);

            return(result);
        }
Пример #26
0
        public void BindModel_GoodValue_ByteArray_Succeeds()
        {
            // Arrange
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(byte[])),
                ModelName     = "foo",
                ValueProvider = new SimpleHttpValueProvider
                {
                    { "foo", _base64String }
                }
            };

            BinaryDataModelBinderProvider binderProvider = new BinaryDataModelBinderProvider();

            // Act
            IModelBinder binder = binderProvider.GetBinder(null, bindingContext);
            bool         retVal = binder.BindModel(null, bindingContext);

            // Assert
            Assert.True(retVal);
            Assert.Equal(_base64Bytes, (byte[])bindingContext.Model);
        }
Пример #27
0
        public void BinderThrowsIfDataCorrupt()
        {
            // Arrange
            DeserializeAttribute attr      = new DeserializeAttribute();
            IModelBinder         binder    = attr.GetBinder();
            ModelBindingContext  mbContext = new ModelBindingContext()
            {
                ModelName     = "someKey",
                ValueProvider = new SimpleValueProvider()
                {
                    { "someKey", "This data is corrupted." }
                }
            };

            // Act & assert
            Exception exception = ExceptionHelper.ExpectException <SerializationException>(
                delegate {
                binder.BindModel(null, mbContext);
            },
                @"Deserialization failed. Verify that the data is being deserialized using the same SerializationMode with which it was serialized. Otherwise see the inner exception.");

            Assert.IsNotNull(exception.InnerException, "Inner exception was not propagated correctly.");
        }
Пример #28
0
        public void GetBinder_ModelMetadataReturnsReadOnly_ReturnsNull()
        {
            // Arrange
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int[])),
                ModelName     = "foo",
                ValueProvider = new SimpleHttpValueProvider
                {
                    { "foo[0]", "42" },
                }
            };

            bindingContext.ModelMetadata.IsReadOnly = true;

            ArrayModelBinderProvider binderProvider = new ArrayModelBinderProvider();

            // Act
            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);
            bool         bound  = binder.BindModel(null, bindingContext);

            // Assert
            Assert.False(bound);
        }
        public void BinderThrowsIfDataCorrupt()
        {
            // Arrange
            Mock <MvcSerializer> mockSerializer = new Mock <MvcSerializer>();

            mockSerializer.Setup(o => o.Deserialize(It.IsAny <string>(), It.IsAny <SerializationMode>())).Throws(new SerializationException());
            DeserializeAttribute attr = new DeserializeAttribute {
                Serializer = mockSerializer.Object
            };

            IModelBinder        binder    = attr.GetBinder();
            ModelBindingContext mbContext = new ModelBindingContext
            {
                ModelName     = "someKey",
                ValueProvider = new SimpleValueProvider
                {
                    { "someKey", "This data is corrupted." }
                }
            };

            // Act & assert
            Exception exception = Assert.Throws <SerializationException>(
                delegate { binder.BindModel(null, mbContext); });
        }
Пример #30
0
        protected internal bool TryUpdateModel(Type type, object model, string prefix, string[] includeProperties, string[] excludeProperties, IValueProvider valueProvider)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }
            if (valueProvider == null)
            {
                throw new ArgumentNullException("valueProvider");
            }
            Predicate <string>  predicate      = propertyName => IsPropertyAllowed(propertyName, includeProperties, excludeProperties);
            IModelBinder        binder         = this.Binders.GetBinder(type);
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(() => model, type),
                ModelName      = prefix,
                ModelState     = this.ModelState,
                PropertyFilter = predicate,
                ValueProvider  = valueProvider
            };

            binder.BindModel(base.ControllerContext, bindingContext);
            return(this.ModelState.IsValid);
        }
Пример #31
0
        /// <summary>
        ///     Returns the value of a property using the specified controller context, binding context, property descriptor, and
        ///     property binder.
        /// </summary>
        /// <returns>
        ///     An object that represents the property value.
        /// </returns>
        /// <param name="controllerContext">
        ///     The context within which the controller operates. The context information includes the
        ///     controller, HTTP content, request context, and route data.
        /// </param>
        /// <param name="bindingContext">
        ///     The context within which the model is bound. The context includes information such as the
        ///     model object, model name, model type, property filter, and value provider.
        /// </param>
        /// <param name="propertyDescriptor">
        ///     The descriptor for the property to access. The descriptor provides information such as
        ///     the component type, property type, and property value. It also provides methods to get or set the property value.
        /// </param>
        /// <param name="propertyBinder">An object that provides a way to bind the property.</param>
        protected override object GetPropertyValue(ControllerContext controllerContext,
            ModelBindingContext bindingContext,
            PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
        {
            if (!IsPersistentType(bindingContext.ModelType))
            {
                return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
            }
            var context = new NHModelBindingContext(bindingContext)
            {
                Wrapper = _wrapper
            };
            object value = propertyBinder.BindModel(controllerContext, context);
            if (bindingContext.ModelMetadata.ConvertEmptyStringToNull && Equals(value, String.Empty))
            {
                return null;
            }

            return value;
        }
        object ModelBind(ControllerContext controllerContext, ModelBindingContext bindingContext, IModelBinder binder = null)
        {
            if (this.Name != null) {
            bindingContext.ModelName = this.Name;
             }

             // For action parameters, ValueProvider is ValueProviderCollection (composite).
             // For controller properties (BindRouteProperties), it's null.
             // That's why we always need to set it to the appropriate instance here.

             bindingContext.ValueProvider = (ValueProviderFactories.Factories
            .OfType<RouteDataValueProviderFactory>()
            .FirstOrDefault()
            ?? new RouteDataValueProviderFactory())
            .GetValueProvider(controllerContext);

             if (binder == null) {
            bool isDefaultBinder;
            binder = GetModelBinder(this, bindingContext.ModelType, out isDefaultBinder);
             }

             return binder.BindModel(controllerContext, bindingContext);
        }
        bool ModelBind(HttpActionContext actionContext, ModelBindingContext bindingContext, IModelBinder binder = null)
        {
            if (this.Name != null) {
            bindingContext.ModelName = this.Name;
             }

             // For action parameters, ValueProvider is set by ModelBinderParameterBinding (see GetBinding).
             // For controller properties (BindRouteProperties), and if for some other reason it's null,
             // we set it here.

             if (bindingContext.ValueProvider == null) {

            // Multiple bindings with the same context should be able to reuse this computation

            bindingContext.ValueProvider = GetValueProviderFactories(actionContext.ControllerContext.Configuration)
               .Single()
               .GetValueProvider(actionContext);
             }

             if (binder == null) {
            binder = GetModelBinder(this, bindingContext.ModelType, actionContext.ControllerContext.Configuration);
             }

             return binder.BindModel(actionContext, bindingContext);
        }