示例#1
0
        protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
        {
            // Check for existence of type discriminator field
            string typeDiscrimKey         = CreateSubPropertyName(bindingContext.ModelName, "_TYPEDISC_");
            ValueProviderResult vpDiscrim = bindingContext.ValueProvider.GetValue(typeDiscrimKey);

            if (vpDiscrim != null)
            {
                // check for attribute on property specifying the requested type name is allowed
                string typeName = (string)vpDiscrim.ConvertTo(typeof(string));
                var    attr     = propertyDescriptor.Attributes.OfType <AllowedSubtypesAttribute>().FirstOrDefault();
                if (attr != null && attr.AllowedSubtypeNames.Contains(typeName))
                {
                    // check if the requested type is different from the property type, but assignable to it
                    Type propType = Type.GetType(typeName);
                    if (propType != propertyDescriptor.PropertyType && propertyDescriptor.PropertyType.IsAssignableFrom(propType))
                    {
                        // substitute type of property for specified type
                        IModelBinder newPropertyBinder = Binders.GetBinder(propType);
                        var          propertyMetadata  =
                            ModelMetadataProviders.Current.GetMetadataForType(() => null, propType);
                        ModelBindingContext newBindingContext = new ModelBindingContext()
                        {
                            ModelMetadata = propertyMetadata,
                            ModelName     = bindingContext.ModelName,
                            ModelState    = bindingContext.ModelState,
                            ValueProvider = bindingContext.ValueProvider
                        };

                        return(base.GetPropertyValue(controllerContext, newBindingContext, propertyDescriptor, newPropertyBinder));
                    }
                }
            }
            return(base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder));
        }
示例#2
0
        protected internal bool TryUpdateModel <TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties, IValueProvider 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()
            {
                ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(TModel)),
                ModelName      = prefix,
                ModelState     = ModelState,
                PropertyFilter = propertyFilter,
                ValueProvider  = valueProvider
            };

            binder.BindModel(ControllerContext, bindingContext);
            return(ModelState.IsValid);
        }
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        IXpoController xpoController = controllerContext.Controller as IXpoController;

        if (xpoController == null)
        {
            throw new InvalidOperationException("The controller does not support IXpoController interface");
        }
        XPClassInfo         classInfo = xpoController.XpoSession.GetClassInfo(modelType);
        ModelBindingContext keyPropertyBindingContext = new ModelBindingContext()
        {
            ModelMetadata = bindingContext.PropertyMetadata[classInfo.KeyProperty.Name],
            ModelName     = classInfo.KeyProperty.Name,
            ModelState    = bindingContext.ModelState,
            ValueProvider = bindingContext.ValueProvider
        };
        PropertyDescriptorCollection properties  = GetModelProperties(controllerContext, bindingContext);
        PropertyDescriptor           keyProperty = properties.Find(classInfo.KeyProperty.Name, false);
        IModelBinder keyPropertyBinder           = Binders.GetBinder(keyProperty.PropertyType);
        object       keyValue = GetPropertyValue(controllerContext, keyPropertyBindingContext, keyProperty, keyPropertyBinder);

        if (keyValue == null)
        {
            return(classInfo.CreateNewObject(xpoController.XpoSession));
        }
        else
        {
            return(xpoController.XpoSession.GetObjectByKey(classInfo, keyValue));
        }
    }
示例#4
0
        private void BindingProperty(HttpContext httpContext, ModelBindingContext bindingContext, PropertyDescriptor property)
        {
            // 将属性名添加到现有前缀上
            string prefix = $"{bindingContext.ModelName ?? ""}.{property.Name ?? ""}".Trim('.');

            // 针对属性创建绑定上下文
            ModelMetadata       metadata = bindingContext.PropertyMetadata[property.Name];
            ModelBindingContext context  = new ModelBindingContext(bindingContext.ValueProvider)
            {
                ModelName     = prefix,
                ModelMetadata = metadata,
            };

            // 针对属性实施Model绑定并对属性赋值
            // 注意BindModel方法的调用,复杂类型的递归调用就来自于这里
            object propertyValue = Binders.GetBinder(property.PropertyType).BindModel(httpContext, context);

            if (bindingContext.ModelMetadata.ConvertEmptyStringToNull &&
                Object.Equals(propertyValue, String.Empty))
            {
                propertyValue = null;
            }

            context.ModelMetadata.Model = propertyValue;
            property.SetValue(bindingContext.Model, propertyValue);
        }
        protected virtual void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            // need to skip properties that aren't part of the request, else we might hit a StackOverflowException
            string fullPropertyKey = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name);

            if (!DictionaryHelpers.DoesAnyKeyHavePrefix(bindingContext.ValueProvider, fullPropertyKey))
            {
                return;
            }

            // call into the property's model binder
            IModelBinder        propertyBinder        = Binders.GetBinder(propertyDescriptor.PropertyType);
            object              originalPropertyValue = propertyDescriptor.GetValue(bindingContext.Model);
            ModelBindingContext innerBindingContext   = new ModelBindingContext()
            {
                Model         = originalPropertyValue,
                ModelName     = fullPropertyKey,
                ModelState    = bindingContext.ModelState,
                ModelType     = propertyDescriptor.PropertyType,
                ValueProvider = bindingContext.ValueProvider
            };
            object newPropertyValue = propertyBinder.BindModel(controllerContext, innerBindingContext);

            // validation
            if (OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, newPropertyValue))
            {
                SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
                OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
            }
        }
示例#6
0
        private List <object> getArrayItems(ControllerContext controllerContext, ModelBindingContext bindingContext, string arrayName, Type elementType)
        {
            List <object> items = new List <object>();

            Regex      regex = createKeyRegexp(arrayName);
            List <int> keys  = getKeysInAscendingOrder(controllerContext.HttpContext.Request, regex);

            IModelBinder elementBinder = Binders.GetBinder(elementType);

            foreach (var key in keys)
            {
                ModelBindingContext innerContext = new ModelBindingContext()
                {
                    ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(null, elementType),
                    ModelName      = $"{arrayName}[{key}]",
                    ModelState     = bindingContext.ModelState,
                    PropertyFilter = bindingContext.PropertyFilter,
                    ValueProvider  = bindingContext.ValueProvider
                };

                object element = elementBinder.BindModel(controllerContext, innerContext);
                items.Add(element);
            }

            return(items);
        }
        /// <summary>
        /// 更新实体对象
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        protected new void UpdateModel <TModel>(TModel entity) where TModel : IEntity
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

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

            Type type = typeof(T);

            IModelBinder binder = Binders.GetBinder(type);

            ModelBindingContext bindingContext = new ModelBindingContext()
            {
                ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(() => entity, type),
                ModelName      = null,
                ModelState     = ModelState,
                PropertyFilter = null,
                ValueProvider  = ValueProvider
            };

            binder.BindModel(ControllerContext, bindingContext);

            UpdateEntity(entity);
        }
        protected virtual void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            // need to skip properties that aren't part of the request, else we might hit a StackOverflowException
            string fullPropertyKey = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name);

            if (!bindingContext.ValueProvider.ContainsPrefix(fullPropertyKey))
            {
                return;
            }

            // call into the property's model binder
            IModelBinder  propertyBinder        = Binders.GetBinder(propertyDescriptor.PropertyType);
            object        originalPropertyValue = propertyDescriptor.GetValue(bindingContext.Model);
            ModelMetadata propertyMetadata      = bindingContext.PropertyMetadata[propertyDescriptor.Name];

            propertyMetadata.Model = originalPropertyValue;
            ModelBindingContext innerBindingContext = new ModelBindingContext()
            {
                ModelMetadata = propertyMetadata,
                ModelName     = fullPropertyKey,
                ModelState    = bindingContext.ModelState,
                ValueProvider = bindingContext.ValueProvider
            };
            object newPropertyValue = GetPropertyValue(controllerContext, innerBindingContext, propertyDescriptor, propertyBinder);

            propertyMetadata.Model = newPropertyValue;

            // validation
            ModelState modelState = bindingContext.ModelState[fullPropertyKey];

            if (modelState == null || modelState.Errors.Count == 0)
            {
                if (OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, newPropertyValue))
                {
                    SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
                    OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
                }
            }
            else
            {
                SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);

                // Convert FormatExceptions (type conversion failures) into InvalidValue messages
                foreach (ModelError error in modelState.Errors.Where(err => String.IsNullOrEmpty(err.ErrorMessage) && err.Exception != null).ToList())
                {
                    for (Exception exception = error.Exception; exception != null; exception = exception.InnerException)
                    {
                        if (exception is FormatException)
                        {
                            string displayName          = propertyMetadata.GetDisplayName();
                            string errorMessageTemplate = GetValueInvalidResource(controllerContext);
                            string errorMessage         = String.Format(CultureInfo.CurrentCulture, errorMessageTemplate, modelState.Value.AttemptedValue, displayName);
                            modelState.Errors.Remove(error);
                            modelState.Errors.Add(errorMessage);
                            break;
                        }
                    }
                }
            }
        }
示例#9
0
 protected AbstractMethodOperation(IMethod method, IObjectBinderLocator binderLocator)
 {
     binderLocator = binderLocator ?? new DefaultObjectBinderLocator();
     OwnerType     = (IType)method.Owner;
     Method        = method;
     Binders       = method.InputMembers.ToDictionary(x => x, binderLocator.GetBinder);
     Inputs        = Binders.Select(x => new InputMember(x.Key, x.Value, x.Key.IsOptional));
 }
 /// <summary>
 /// Clears all children of the DataBinderList. For emergency or instant clearing only
 /// </summary>
 public void ForceClearInstant()
 {
     Binders.Clear();
     for (int i = 0; i < transform.childCount; i++)
     {
         Destroy(transform.GetChild(i).gameObject);
     }
 }
示例#11
0
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            var fullPropertyKey = CreateSubPropertyName(propertyDescriptor.Name);

            if (!bindingContext.ValueProvider.ContainsPrefix(fullPropertyKey))
            {
                return;
            }

            var propertyBinder        = Binders.GetBinder(propertyDescriptor.PropertyType);
            var originalPropertyValue = propertyDescriptor.GetValue(bindingContext.Model);
            var propertyMetadata      = bindingContext.PropertyMetadata[propertyDescriptor.Name];

            propertyMetadata.Model = originalPropertyValue;

            var innerBindingContext = new ModelBindingContext {
                ModelMetadata = propertyMetadata,
                ModelName     = fullPropertyKey,
                ModelState    = bindingContext.ModelState,
                ValueProvider = bindingContext.ValueProvider
            };

            var newPropertyValue = GetPropertyValue(controllerContext, innerBindingContext, propertyDescriptor, propertyBinder);

            propertyMetadata.Model = newPropertyValue;

            var modelState = bindingContext.ModelState[fullPropertyKey];

            if (modelState == null || modelState.Errors.Count == 0)
            {
                if (OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, newPropertyValue))
                {
                    SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
                    OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
                }
            }
            else
            {
                SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);

                foreach (var modelError in modelState.Errors.Where(me => string.IsNullOrEmpty(me.ErrorMessage) && me.Exception != null).ToList())
                {
                    for (var exception = modelError.Exception; exception != null; exception = exception.InnerException)
                    {
                        if (exception is FormatException)
                        {
                            var displayName          = propertyMetadata.GetDisplayName();
                            var errorMessageTemplate = GetValueInvalidResource(controllerContext);
                            var errorMessage         = String.Format(CultureInfo.CurrentCulture, errorMessageTemplate, modelState.Value.AttemptedValue, displayName);
                            modelState.Errors.Remove(modelError);
                            modelState.Errors.Add(errorMessage);
                            break;
                        }
                    }
                }
            }
        }
示例#12
0
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var viewModel     = GetCurrentStep();
            var viewModelType = viewModel.GetType();

            //var viewModelBindingContext = CreateViewModelBindingContext(bindingContext, viewModel, viewModelType);

            return(Binders.GetBinder(viewModelType).BindModel(controllerContext, bindingContext));
        }
    //Instantly clears the list regardless of if it is an animated list or not
    private void ClearListInstant()
    {
        //clear the list
        for (int i = 0; i < Binders.Count; i++)
        {
            DestroyImmediate(Binders[i].gameObject);
        }

        Binders.Clear();
    }
 private void Awake()
 {
     if (transform.childCount > 0)
     {
         foreach (DataBinder binder in GetComponentsInChildren <DataBinder>())
         {
             Binders.Add(binder);
         }
     }
 }
示例#15
0
 private void EnsureDictSplatSite() {
     if (_dictSite == null) {
         Interlocked.CompareExchange(
             ref _dictSite,
             CallSite<Func<CallSite, CodeContext, object, object[], IDictionary<object, object>, object>>.Create(
                 Binders.InvokeKeywords(_context.LanguageContext)
             ),
             null
         );
     }
 }
示例#16
0
 private void EnsureSplatSite() {
     if (_splatSite == null) {
         Interlocked.CompareExchange(
             ref _splatSite,
             CallSite<Func<CallSite, CodeContext, object, object[], object>>.Create(
                 Binders.InvokeSplat(_context.LanguageContext)
             ),
             null
         );
     }
 }
        internal object UpdateCollection(ControllerContext controllerContext, ModelBindingContext bindingContext, Type elementType)
        {
            bool stopOnIndexNotFound;
            IEnumerable <string> indexes;

            GetIndexes(bindingContext, out stopOnIndexNotFound, out indexes);
            IModelBinder elementBinder = Binders.GetBinder(elementType);

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

            foreach (string currentIndex in indexes)
            {
                string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currentIndex);
                if (!bindingContext.ValueProvider.ContainsPrefix(subIndexKey))
                {
                    if (stopOnIndexNotFound)
                    {
                        // we ran out of elements to pull
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }

                ModelBindingContext innerContext = new ModelBindingContext()
                {
                    ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(null, elementType),
                    ModelName      = subIndexKey,
                    ModelState     = bindingContext.ModelState,
                    PropertyFilter = bindingContext.PropertyFilter,
                    ValueProvider  = bindingContext.ValueProvider
                };
                object thisElement = elementBinder.BindModel(controllerContext, innerContext);

                // we need to merge model errors up
                AddValueRequiredMessageToModelState(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);
        }
示例#18
0
            public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                Type modelType = bindingContext.ModelType;
                Type idictType = modelType.GetInterface("System.Collections.Generic.IDictionary`2");

                if (idictType != null)
                {
                    Type[] argumetTypes = idictType.GetGenericArguments();

                    object       result      = null;
                    IModelBinder valueBinder = Binders.GetBinder(argumetTypes[1]);

                    foreach (string key in GetValueProviderKeys(controllerContext))
                    {
                        if (!key.StartsWith(bindingContext.ModelName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            continue;
                        }

                        object dictKey;
                        string parameterName = key.Substring(bindingContext.ModelName.Length);
                        try
                        {
                            dictKey = ConvertType(parameterName, argumetTypes[0]);
                        }
                        catch (NotSupportedException)
                        {
                            continue;
                        }

                        ModelBindingContext innerBindingContext = new ModelBindingContext()
                        {
                            ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(() => null, argumetTypes[1]),
                            ModelName      = key,
                            ModelState     = bindingContext.ModelState,
                            PropertyFilter = bindingContext.PropertyFilter,
                            ValueProvider  = bindingContext.ValueProvider
                        };
                        object newPropertyValue = valueBinder.BindModel(controllerContext, innerBindingContext);

                        if (result == null)
                        {
                            result = CreateModel(controllerContext, bindingContext, modelType);
                        }

                        if (!(bool)idictType.GetMethod("ContainsKey").Invoke(result, new object[] { dictKey }))
                        {
                            idictType.GetProperty("Item").SetValue(result, newPropertyValue, new object[] { dictKey });
                        }
                    }
                    return(result);
                }
                return(new DefaultModelBinder().BindModel(controllerContext, bindingContext));
            }
示例#19
0
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var viewModel               = CreateViewModel(bindingContext);
            var viewModelType           = viewModel.GetType();
            var viewModelBindingContext = CreateViewModelBindingContext(bindingContext, viewModel, viewModelType);

            var binder = Binders.GetBinder(viewModelType);
            var result = binder.BindModel(controllerContext, viewModelBindingContext);

            return(result);
        }
示例#20
0
        private object BindDictionary(ControllerContext controllerContext, ModelBindingContext bindingContext, Type idictType)
        {
            Type   modelType = bindingContext.ModelType;
            object result    = null;

            Type[]       ga          = idictType.GetGenericArguments();
            IModelBinder valueBinder = Binders.GetBinder(ga[1]);

            foreach (string key in GetValueProviderKeys(controllerContext))
            {
                bool isMatch = key.StartsWith(bindingContext.ModelName + "[", StringComparison.InvariantCultureIgnoreCase);
                if (isMatch)
                {
                    int endbracket = key.IndexOf("]", bindingContext.ModelName.Length + 1);
                    if (endbracket == -1)
                    {
                        continue;
                    }

                    object dictKey;
                    try
                    {
                        dictKey = ConvertType(key.Substring(bindingContext.ModelName.Length + 1, endbracket - bindingContext.ModelName.Length - 1), ga[0]);
                    }
                    catch (NotSupportedException)
                    {
                        continue;
                    }

                    ModelBindingContext innerBindingContext = new ModelBindingContext()
                    {
                        ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(() => null, ga[1]),
                        ModelName      = key.Substring(0, endbracket + 1),
                        ModelState     = bindingContext.ModelState,
                        PropertyFilter = bindingContext.PropertyFilter,
                        ValueProvider  = bindingContext.ValueProvider
                    };
                    object newPropertyValue = valueBinder.BindModel(controllerContext, innerBindingContext);

                    if (result == null)
                    {
                        result = CreateModel(controllerContext, bindingContext, modelType);
                    }

                    if (!(bool)idictType.GetMethod("ContainsKey").Invoke(result, new object[] { dictKey }))
                    {
                        idictType.GetProperty("Item").SetValue(result, ((string[])newPropertyValue)[0], new object[] { dictKey });
                    }
                }
            }

            return(result);
        }
        protected virtual IModelBinder GetPropertyBinder(PropertyDescriptor property)
        {
            ModelBinderAttribute attribute = property.Attributes
                                             .OfType <ModelBinderAttribute>().FirstOrDefault();

            if (attribute == null)
            {
                return(Binders.GetBinder(property.PropertyType));
            }

            return(attribute.GetBinder());
        }
示例#22
0
        protected AbstractMethodOperation(IType targetType, IMethod method, IObjectBinderLocator binderLocator,
                                          IDependencyResolver resolver, Dictionary <Type, object[]> attributeCache)
        {
            _attributeCache = attributeCache ?? _emptyCache;
            binderLocator ??= new DefaultObjectBinderLocator();
            TargetType = targetType;
            Method     = method;

            Binders = method.InputMembers.ToDictionary(x => x, binderLocator.GetBinder);
            Inputs  = Binders
                      .Select(x => new InputMember(x.Key, x.Value, x.Key.IsOptional))
                      .ToArray();
            Resolver = resolver;
        }
    private object UpdateDynamicDictionary(
        ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        var modelList = new List <KeyValuePair <string, object> >();
        var enumerableValueProvider = bindingContext.ValueProvider as IEnumerableValueProvider;

        if (enumerableValueProvider != null)
        {
            var keys   = enumerableValueProvider.GetKeysFromPrefix(bindingContext.ModelName);
            var groups = keys.GroupBy((k) => k.Key.Split('[')[0]);
            foreach (var group in groups)
            {
                if (group.Count() > 1)
                {
                    var valueType = typeof(ICollection <ExpandoObject>);
                    modelList.Add(
                        CreateEntryForModel(
                            controllerContext,
                            bindingContext,
                            valueType,
                            Binders.GetBinder(valueType),
                            bindingContext.ModelName + '.' + group.Key,
                            group.Key));
                }
                else
                {
                    var item      = group.Single();
                    var value     = bindingContext.ValueProvider.GetValue(item.Value);
                    var valueType = value != null && value.RawValue != null ?
                                    typeof(object) : typeof(ExpandoObject);
                    modelList.Add(
                        CreateEntryForModel(
                            controllerContext,
                            bindingContext,
                            valueType,
                            Binders.GetBinder(valueType),
                            item.Value,
                            item.Key));
                }
            }
        }
        var dictionary = (IDictionary <string, object>)bindingContext.Model;

        foreach (var kvp in modelList)
        {
            dictionary[kvp.Key] = kvp.Value;
        }
        return(dictionary);
    }
示例#24
0
        private object GetParametersFromType(Type parameterType)
        {
            var binder         = Binders.GetBinder(parameterType);
            var model          = Activator.CreateInstance(parameterType);
            var bindingContext = new ModelBindingContext
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, parameterType),
                ModelName     = "Parameters",
                ModelState    = ModelState,
                ValueProvider = ValueProvider
            };

            binder.BindModel(ControllerContext, bindingContext);
            return(model);
        }
示例#25
0
        protected void updateModel(M model, FormCollection form)
        {
            Predicate <string> propertyFilter = propertyName => IsPropertyAllowed(propertyName, null, null);
            IModelBinder       binder         = Binders.GetBinder(typeof(M));

            ModelBindingContext bindingContext = new ModelBindingContext()
            {
                ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(M)),
                ModelName      = null,
                ModelState     = new ModelStateDictionary(),
                PropertyFilter = propertyFilter,
                ValueProvider  = form
            };

            binder.BindModel(ControllerContext, bindingContext);
        }
示例#26
0
        private void PopulateParams()
        {
            var modelType           = typeof(IDictionary <SymbolId, object>);
            var request             = ControllerContext.HttpContext.Request;
            var binder              = Binders.GetBinder(modelType);
            var modelBindingContext = new ModelBindingContext
            {
                Model         = new Dictionary <SymbolId, object>(ControllerContext.RouteData.Values.Count + request.QueryString.Count + request.Form.Count),
                ModelName     = "params",
                ModelState    = ModelState,
                ModelType     = modelType,
                ValueProvider = ValueProvider
            };

            _params = binder.BindModel(ControllerContext, modelBindingContext) as IDictionary <SymbolId, object>;
        }
示例#27
0
        public void TryBindInvocations_should_convert_exact_parameter_type_matches_exactly()
        {
            var param = Expression.Parameter(typeof(Func <int, int>));
            Expression <Func <int, int> > lambda = i => 0 + i;
            var args           = new[] { Expression.Constant(1) };
            var lambdaBindings = new Dictionary <ParameterExpression, LambdaExpression> {
                { param, lambda }
            };

            var isBound = Binders.TryBindInvocations(lambdaBindings, Enumerable.Empty <ParameterExpression>(), out var invocationBindings, out var errors);

            Assert.True(isBound);
            Assert.Null(errors);
            Assert.Equal(lambdaBindings.Keys, invocationBindings.Keys);
            Assert.Equal(lambdaBindings.Values, invocationBindings.Values.Select(create => create(args).Expression));
        }
示例#28
0
        private object BindDictionary(HttpContext httpContext, ModelBindingContext bindingContext)
        {
            Type modelType = bindingContext.ModelType;

            Type[] argumentTypes = modelType.GetGenericArguments();
            Type   keyType       = argumentTypes[0];
            Type   valueType     = argumentTypes[1];
            object model         = CreateModel(httpContext, bindingContext, modelType);

            List <KeyValuePair <object, object> > list = new List <KeyValuePair <object, object> >();
            var isZeroBased = GetIndexes(bindingContext, out var indexes);

            foreach (var index in indexes)
            {
                string prefix = $"{bindingContext.ModelName}.[{index}]";
                if (!bindingContext.ValueProvider.ContainsPrefix(prefix))
                {
                    if (isZeroBased)
                    {
                        break;
                    }

                    continue;
                }

                ModelBindingContext contextForKey = new ModelBindingContext(bindingContext.ValueProvider)
                {
                    ModelMetadata = ModelMetadataProvider.GetMetadataForType(null, keyType),
                    ModelName     = prefix + ".key"
                };

                ModelBindingContext contextForValue = new ModelBindingContext(bindingContext.ValueProvider)
                {
                    ModelMetadata = ModelMetadataProvider.GetMetadataForType(null, valueType),
                    ModelName     = prefix + ".value"
                };

                object key = Binders.GetBinder(keyType)
                             .BindModel(httpContext, contextForKey);
                object value = Binders.GetBinder(valueType)
                               .BindModel(httpContext, contextForValue);
                list.Add(new KeyValuePair <object, object>(key, value));
            }

            ReplaceDictionary(keyType, valueType, model, list);
            return(model);
        }
示例#29
0
        public void TryBindInvocations_should_append_synthetic_parameters_types()
        {
            var syntheticParameters = new[] { Expression.Parameter(typeof(bool)), Expression.Parameter(typeof(bool)) };
            var param = Expression.Parameter(typeof(Func <int, int>));              // Our unbound param doesn't know about the synthetic params
            Expression <Func <int, bool, bool, int> > lambda = (i, _, __) => 0 + i; // Our implementation depends on (well, discards) the synthetic params
            var args           = new[] { Expression.Constant(1) };                  // Our runtime arguments (non-synthetic, our synthetic args would be supplied later)
            var lambdaBindings = new Dictionary <ParameterExpression, LambdaExpression> {
                { param, lambda }
            };

            var isBound = Binders.TryBindInvocations(lambdaBindings, syntheticParameters, out var invocationBindings, out var errors);

            Assert.True(isBound);
            Assert.Null(errors);
            Assert.Equal(lambdaBindings.Keys, invocationBindings.Keys);
            Assert.Equal(lambdaBindings.Values, invocationBindings.Values.Select(create => create(args).Expression));
        }
 public override IWeldInjetionPoint TranslateGenericArguments(IComponent component, IDictionary <Type, Type> translations)
 {
     if (IsConstructor)
     {
         var ctor = (ConstructorInfo)_param.Member;
         ctor = GenericUtils.TranslateConstructorGenericArguments(ctor, translations);
         var param = ctor.GetParameters()[_param.Position];
         return(new MethodParameterInjectionPoint(component, param, Binders.ToArray()));
     }
     else
     {
         var method = (MethodInfo)_param.Member;
         method = GenericUtils.TranslateMethodGenericArguments(method, translations);
         var param = method.GetParameters()[_param.Position];
         return(new MethodParameterInjectionPoint(component, param, Binders.ToArray()));
     }
 }