Пример #1
0
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(ObjectId))
            {
                return false;
            }

            var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (val == null)
            {
                return false;
            }

            var value = val.RawValue as string;
            if (value == null)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Wrong value type");
                return false;
            }

            ObjectId result;
            if (ObjectId.TryParse(value, out result))
            {
                bindingContext.Model = result;
                return true;
            }

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Cannot convert value to location");
            return false;
        }
        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            string name = Descriptor.ParameterName;
            Type type = Descriptor.ParameterType;

            string prefix = Descriptor.Prefix;

            IValueProvider vp = CreateValueProvider(this._valueProviderFactories, actionContext);

            ModelBindingContext ctx = new ModelBindingContext()
            {
                ModelName = prefix ?? name,
                FallbackToEmptyPrefix = prefix == null, // only fall back if prefix not specified
                ModelMetadata = metadataProvider.GetMetadataForType(null, type),
                ModelState = actionContext.ModelState,
                ValueProvider = vp
            };

            IModelBinder binder = this._modelBinderProvider.GetBinder(actionContext, ctx);

            bool haveResult = binder.BindModel(actionContext, ctx);
            object model = haveResult ? ctx.Model : Descriptor.DefaultValue;
            actionContext.ActionArguments.Add(name, model);

            return TaskHelpers.Completed();
        }
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof (CriteriaModel))
            {
                return false;
            }

            var value = bindingContext.ValueProvider.GetValue("Categories");

            if (value == null)
            {
                return false;
            }

            var categoryJson = value.RawValue as IEnumerable<string>;

            if (categoryJson == null)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Categories cannot be null.");
                return false;
            }

            var categories = categoryJson.Select(JsonConvert.DeserializeObject<CriteriaCategory>).ToList();

            bindingContext.Model = new CriteriaModel {Categories = categories};
            return true;
        }
Пример #4
0
        public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(Hash))
                return false;
            
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (value == null)
                return false;

            string valueStr = value.RawValue as string;
            if (valueStr == null)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Wrong value type.");
                return false;
            }

            Hash result;
            try
            {
                result = Hash.Parse(valueStr);
            }
            catch
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Cannot parse hash.");
                return false;
            }
            bindingContext.Model = result;
            return true;
        }
        public Tuple<string[], string[]> Get()
        {
            HttpActionContext actionContext = new HttpActionContext
            {
                ControllerContext = this.ControllerContext
            };
            ModelMetadataProvider metadataProvider = this.Configuration.Services.GetModelMetadataProvider();
            ModelMetadata metadata = metadataProvider.GetMetadataForType(null, typeof(DemoModel));
            IValueProvider valueProvider = new CompositeValueProviderFactory(this.Configuration.Services.GetValueProviderFactories()).GetValueProvider(actionContext);
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = metadata,
                ValueProvider = valueProvider,
                ModelState = actionContext.ModelState
            };
            actionContext.Bind(bindingContext);

            //验证之前的错误消息
            string[] errorMessages1 = actionContext.ModelState.SelectMany(
                item => item.Value.Errors.Select(
                error => error.ErrorMessage)).ToArray();

            //验证之前的错误消息
            bindingContext.ValidationNode.Validate(actionContext);
            string[] errorMessages2 = actionContext.ModelState.SelectMany(
                item => item.Value.Errors.Select(
                error => error.ErrorMessage)).ToArray();
            return new Tuple<string[], string[]>(errorMessages1, errorMessages2);
        }
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var nvc = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);
            var model = new GetPagedListParams
            {
                PageSize = int.Parse(nvc["count"]),
                Page = int.Parse(nvc["page"]),
                SortExpression = "Id"
            };

            var sortingKey = nvc.AllKeys.FirstOrDefault(x => x.StartsWith("sorting["));
            if (sortingKey != null)
            {
                model.SortExpression = sortingKey.RemoveStringEntries("sorting[", "]") + " " + nvc[sortingKey];
            }

            model.Filters = nvc.AllKeys.Where(x => x.StartsWith("filter["))
                .ToDictionary(x => x.RemoveStringEntries("filter[", "]"), y => nvc[y]);

            if (nvc.AllKeys.Contains("filter"))
            {
                model.Filters = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(nvc["filter"]);
            }

            bindingContext.Model = model;
            return true;
        }
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException("actionContext");
            }

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

            string segmentName = bindingContext.ModelName;
            ValueProviderResult segmentResult = bindingContext.ValueProvider.GetValue(segmentName);
            if (segmentResult == null)
            {
                return false;
            }

            string segmentValue = segmentResult.AttemptedValue;
            if (segmentValue != null)
            {
                bindingContext.Model = segmentValue.Split(new[] { ";" }, 2, StringSplitOptions.None).First();
            }
            else
            {
                bindingContext.Model = segmentValue;
            }
            return true;
        }
        public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            ComplexModelDto dto = bindingContext.Model as ComplexModelDto;
            if (dto == null)
            {
                return false;
            }
            foreach (ModelMetadata medadata in dto.PropertyMetadata)
            {
                ModelBindingContext subcontext = new ModelBindingContext(bindingContext)
                {
                    ModelMetadata = medadata,
                    //创建前缀形式的ModelName
                    ModelName = ModelNameBuilder.CreatePropertyModelName(bindingContext.ModelName, medadata.PropertyName)
                };
                if (actionContext.Bind(subcontext))
                {
                    dto.Results[medadata] = new ComplexModelDtoResult(subcontext.Model, subcontext.ValidationNode);
                }

            }
            return true;
            //  在实现的BindModd方法中,如果当前Modc1BindiⅡ gContext 的Modcl属 性不是一个CompIexModolDto对象,
            //我们会直接返回Fdsc。 接下来针对描述属 性的每个Mo山;lMetadata创 建当前ModeIBindingContext的 子上下文
            //,然 后调用当前 IIttpActioⅡContc灶 的Bi血 方法针对它实施新—轮的Mode1绑 定。Mode1绑 定成功完成之后 ,
            //作为子上下文的ModeIBiΠdiⅡgContext中 将包含属性对应的值和验证结果,我们将它们添加 到ComplexMo山 lDto
            //的 Results属 性中,Mut汕 1co切ectModelBhder为 空对象设置的属性值 就来源于此。
        }
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(DynamicContentEvaluationContext))
            {
                return false;
            }

            var qs = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query as string);

            var result = new DynamicContentEvaluationContext();

            result.StoreId = qs.Get("storeId") ?? qs.Get("evalContext.storeId");
            result.PlaceName= qs.Get("placeName") ?? qs.Get("evalContext.placeName");
            result.Tags = qs.GetValues("tags");
            if (result.Tags == null)
            {
                var tags = qs.Get("evalContext.tags");
                if (!String.IsNullOrEmpty(tags))
                {
                    result.Tags = tags.Split(',');
                }
            }

            var toDate = qs.Get("toDate") ?? qs.Get("evalContext.toDate");
            if (toDate != null)
            {
                result.ToDate = Convert.ToDateTime(toDate, CultureInfo.InvariantCulture);
            }

            bindingContext.Model = result;
            return true;
        }
        /// <summary>
        /// Gets the <see cref="ModelBindingContext"/> for this <see cref="HttpActionContext"/>.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        /// <param name="bindingContext">The binding context.</param>
        /// <param name="binder">When this method returns, the value associated with the specified binding context, if the context is found; otherwise, the default value for the type of the value parameter.</param>
        /// <returns><c>true</c> if <see cref="ModelBindingContext"/> was present; otherwise <c>false</c>.</returns>
        public static bool TryGetBinder(this HttpActionContext actionContext, ModelBindingContext bindingContext, out IModelBinder binder)
        {
            if (actionContext == null)
            {
                throw Error.ArgumentNull("actionContext");
            }

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

            binder = null;
            ModelBinderProvider providerFromAttr;
            if (ModelBindingHelper.TryGetProviderFromAttributes(bindingContext.ModelType, out providerFromAttr))
            {
                binder = providerFromAttr.GetBinder(actionContext, bindingContext);
            }
            else
            {
                binder = actionContext.ControllerContext.Configuration.Services.GetModelBinderProviders()
                    .Select(p => p.GetBinder(actionContext, bindingContext))
                    .Where(b => b != null)
                    .FirstOrDefault();
            }

            return binder != null;
        }
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            DemoVector vector;

            if (bindingContext.ModelType != typeof (DemoVector))
            {
                return false;
            }

            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (value == null)
            {
                return false; 
            }

            var text = value.RawValue as string;

            if (DemoVector.TryParse(text, out vector))
            {
                bindingContext.Model = vector;
                return true;
            }

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Cannot convert value to vector.");
            return false;
        }
Пример #12
0
		public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
		{
			if (bindingContext.ModelType != typeof(coreModel.SearchCriteria))
			{
				return false;
			}

			var qs = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query as string);

			var result = new coreModel.SearchCriteria();

			result.Keyword = qs["q"].EmptyToNull();
			var respGroup = qs["respGroup"].EmptyToNull();
			if (respGroup != null)
			{
				result.ResponseGroup = EnumUtility.SafeParse<coreModel.ResponseGroup>(respGroup, coreModel.ResponseGroup.Default);
			}
			result.StoreIds = qs.GetValues("stores");
			result.CustomerId = qs["customer"].EmptyToNull();
            result.EmployeeId = qs["employee"].EmptyToNull();
			result.Count = qs["count"].TryParse(20);
			result.Start = qs["start"].TryParse(0);
			bindingContext.Model = result;
			return true;
		}
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            // Try to resolve hero
            ValueProviderResult heroValue = bindingContext.ValueProvider.GetValue(nameof(FreeToPlayPeriodPropertiesModel.Hero));
            Hero hero = null;

            if (!string.IsNullOrWhiteSpace(heroValue?.AttemptedValue))
            {
                Guid heroId = _cryptographyService.DecryptGuid(heroValue.AttemptedValue);
                hero = _heroRepository.GetHero(heroId);
            }

            // Try to resolve begin
            ValueProviderResult beginValue = bindingContext.ValueProvider.GetValue(nameof(FreeToPlayPeriodPropertiesModel.Begin));
            DateTime? begin = null;
            DateTime beginTry;

            if (!string.IsNullOrWhiteSpace(beginValue?.AttemptedValue) && DateTime.TryParse(beginValue.AttemptedValue, out beginTry))
            {
                begin = beginTry;
            }

            // Try to resolve end
            ValueProviderResult endValue = bindingContext.ValueProvider.GetValue(nameof(FreeToPlayPeriodPropertiesModel.End));
            DateTime? end = null;
            DateTime endTry;

            if (!string.IsNullOrWhiteSpace(endValue?.AttemptedValue) && DateTime.TryParse(endValue.AttemptedValue, out endTry))
            {
                end = endTry;
            }

            bindingContext.Model = new FreeToPlayPeriodPropertiesModel(hero, begin, end);
            return true;
        }
        public void BindComplexCollectionFromIndexes_InfiniteIndexes()
        {
            // Arrange
            CultureInfo culture = CultureInfo.GetCultureInfo("fr-FR");
            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),
                ModelName = "someName",
                ValueProvider = new SimpleHttpValueProvider
                {
                    { "someName[0]", "42" },
                    { "someName[1]", "100" },
                    { "someName[3]", "400" }
                }
            };

            HttpActionContext context = ContextUtil.CreateActionContext();
            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object));

            mockIntBinder
                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))
                .Returns((HttpActionContext ec, ModelBindingContext mbc) =>
                {
                    mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);
                    return true;
                });

            // Act
            List<int> boundCollection = CollectionModelBinder<int>.BindComplexCollectionFromIndexes(context, bindingContext, null /* indexNames */);

            // Assert
            Assert.Equal(new[] { 42, 100 }, boundCollection.ToArray());
            Assert.Equal(new[] { "someName[0]", "someName[1]" }, bindingContext.ValidationNode.ChildNodes.Select(o => o.ModelStateKey).ToArray());
        }
Пример #15
0
 public override bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) {
     BindModelOnSuccessOrFail(bindingContext,
                              () => ModelBinderUtils.CreateSimpleArgumentMap(actionContext.Request.RequestUri.Query) ??
                                    ModelBinderUtils.CreateArgumentMap(DeserializeQueryString(actionContext)),
                              ModelBinderUtils.CreateArgumentMapForMalformedArgs);
     return true;
 }
Пример #16
0
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            //NOTE: Validation is done in the filter
            if (!actionContext.Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var root = HttpContext.Current.Server.MapPath("~/App_Data/TEMP/FileUploads");
            //ensure it exists
            Directory.CreateDirectory(root);
            var provider = new MultipartFormDataStreamProvider(root);

            var task = Task.Run(() => GetModel(actionContext.Request.Content, provider))
                .ContinueWith(x =>
                {
                    if (x.IsFaulted && x.Exception != null)
                    {
                        throw x.Exception;
                    }
                    bindingContext.Model = x.Result;
                });
            
            task.Wait();
            
            return bindingContext.Model != null;
        }
        /// <summary>
        /// Binds the model to a value by using the specified controller context and binding context.
        /// </summary>
        /// <returns>
        /// true if model binding is successful; otherwise, false.
        /// </returns>
        /// <param name="actionContext">The action context.</param><param name="bindingContext">The binding context.</param>
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var queryStructure = new QueryStructure();

            var query = actionContext.Request.GetQueryNameValuePairs().ToArray();

            int pageSize;
            if (query.Any(x => x.Key.InvariantEquals("pageSize")) && int.TryParse(query.Single(x => x.Key.InvariantEquals("pageSize")).Value, out pageSize))
            {
                queryStructure.PageSize = pageSize;
            }

            int pageIndex;
            if (query.Any(x => x.Key.InvariantEquals("pageIndex")) && int.TryParse(query.Single(x => x.Key.InvariantEquals("pageIndex")).Value, out pageIndex))
            {
                queryStructure.PageIndex = pageIndex;
            }

            if (query.Any(x => x.Key.InvariantEquals("lucene")))
            {
                queryStructure.Lucene = query.Single(x => x.Key.InvariantEquals("lucene")).Value;
            }

            bindingContext.Model = queryStructure;
            return true;
        }
Пример #18
0
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var jsonStr = actionContext.Request.Content.ReadAsStringAsync().Result;
            var msgObj = Json.Decode(jsonStr);

            bindingContext.Model = new Msg
            {
                UserName = msgObj.UserName,
                Email = msgObj.Email,
                HomePage = msgObj.HomePage,
                Text = msgObj.Text,
                Date = DateTime.Now
            };

            var captchaValidtor = new Recaptcha.RecaptchaValidator
            {
                PrivateKey = ConfigurationManager.AppSettings["ReCaptchaPrivateKey"],
                RemoteIP = ((System.Web.HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request.UserHostAddress,
                Challenge = msgObj.recaptcha_challenge_field,
                Response = msgObj.recaptcha_response_field
            };

            var recaptchaResponse = captchaValidtor.Validate();
            if (!recaptchaResponse.IsValid)
            {
                actionContext.ModelState.AddModelError("recaptcha_response_field", "Символы не соответствуют картинке.");
            }
            return true;
        }
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var model = (DashboardRequest) bindingContext.Model ?? new DashboardRequest();

            var hasPrefix = bindingContext
                .ValueProvider
                .ContainsPrefix(bindingContext.ModelName);

            var searchPrefix = (hasPrefix) ? bindingContext.ModelName + "." : string.Empty;

            Dimension dimension;
            Section section;

            Enum.TryParse(actionContext.ActionDescriptor.ActionName, out dimension);
            Enum.TryParse(GetValue(bindingContext, searchPrefix, "Section"), out section);

            model.ActivityGroupId =
                TryParser.Nullable<Guid>(GetValue(bindingContext, searchPrefix, "ActivityGroupId"));
            model.CostCode = GetValue(bindingContext, searchPrefix, "CostCode");
            model.StartDate = GetDateTime(bindingContext, searchPrefix, "StartDate");
            model.EndDate = GetDateTime(bindingContext, searchPrefix, "EndDate");
            model.Dimension = dimension;
            model.Section = section;

            bindingContext.Model = model;

            return true;
        }
        public void DefaultOptions()
        {
            var binder = new GeocodeOptionsModelBinding();
            var httpControllerContext = new HttpControllerContext
                {
                    Request =
                        new HttpRequestMessage(HttpMethod.Get,
                                               "http://webapi/api/v1/geocode/address/zone")
                };
            var httpActionContext = new HttpActionContext {ControllerContext = httpControllerContext};
            var moc = new Mock<ModelMetadataProvider>();
            var modelBindingContext = new ModelBindingContext
                {
                    ModelMetadata =
                        new ModelMetadata(moc.Object, null, null, typeof (GeocodeOptions), null)
                };

            var successful = binder.BindModel(httpActionContext, modelBindingContext);

            Assert.That(successful, Is.True);

            var model = modelBindingContext.Model as GeocodeOptions;

            Assert.That(model, Is.Not.Null);

            Assert.That(model.AcceptScore, Is.EqualTo(70));
            Assert.That(model.WkId, Is.EqualTo(26912));
            Assert.That(model.SuggestCount, Is.EqualTo(0));
            Assert.That(model.PoBox, Is.False);
            Assert.That(model.Locators, Is.EqualTo(LocatorType.All));
        }
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException("actionContext");
            }
            if (bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext");
            }

            string content = actionContext.Request.Content.ReadAsStringAsync().Result;

            try
            {
                // Try to parse as Json
                bindingContext.Model = Parse(content);
            }
            catch (Exception)
            {
                // Parse the QueryString
                _queryString = GetQueryString(content);
                bindingContext.Model = Parse(_queryString);
            }

            return true;
        }
        public override bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) {
            BindModelOnSuccessOrFail(bindingContext,
                () => ModelBinderUtils.CreateSingleValueArgument(DeserializeContent(actionContext)),
                ModelBinderUtils.CreateSingleValueArgumentForMalformedArgs);

            return true;
        }
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (!CanBindType(bindingContext.ModelType))
            {
                return false;
            }
            if (!bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))
            {
                return false;
            }

            bindingContext.Model = Activator.CreateInstance(bindingContext.ModelType);
            ComplexModelDto dto = new ComplexModelDto(bindingContext.ModelMetadata, bindingContext.PropertyMetadata.Values);
            ModelBindingContext subContext = new ModelBindingContext(bindingContext)
            {
                ModelMetadata = actionContext.GetMetadataProvider().GetMetadataForType(() => dto, typeof(ComplexModelDto)),
                ModelName = bindingContext.ModelName
            };
            actionContext.Bind(subContext);

            foreach (KeyValuePair<ModelMetadata, ComplexModelDtoResult> item in dto.Results)
            {
                ModelMetadata propertyMetadata = item.Key;
                ComplexModelDtoResult dtoResult = item.Value;
                if (dtoResult != null)
                {
                    PropertyInfo propertyInfo = bindingContext.ModelType.GetProperty(propertyMetadata.PropertyName);
                    if (propertyInfo.CanWrite)
                    {
                        propertyInfo.SetValue(bindingContext.Model, dtoResult.Model);
                    }
                }
            }
            return true;
        }
Пример #24
0
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(GeoPoint))
            {
                return false;
            }

            ValueProviderResult val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (val == null)
            {
                return false;
            }

            string key = val.RawValue as string;
            if (key == null)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Wrong value type");
                return false;
            }

            GeoPoint result;
            if (_locations.TryGetValue(key, out result) || GeoPoint.TryParse(key, out result))
            {
                bindingContext.Model = result;
                return true;
            }

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Cannot convert value to Location");
            return false;
        }
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var key = bindingContext.ModelName;
            var val = bindingContext.ValueProvider.GetValue(key);
            if (val != null)
            {
                var s = val.AttemptedValue;
                if (s != null)
                {
                    var elementType = bindingContext.ModelType.GetElementType();
                    var converter = TypeDescriptor.GetConverter(elementType);
                    var values = Array.ConvertAll(s.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries),
                        x => { return converter.ConvertFromString(x != null ? x.Trim() : x); });

                    var typedValues = Array.CreateInstance(elementType, values.Length);

                    values.CopyTo(typedValues, 0);

                    bindingContext.Model = typedValues;
                }
                else
                {
                    // change this line to null if you prefer nulls to empty arrays
                    bindingContext.Model = Array.CreateInstance(bindingContext.ModelType.GetElementType(), 0);
                }
                return true;
            }
            return false;
        }
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var keyValueModel = actionContext.Request.RequestUri.ParseQueryString();

            var spatialReference = keyValueModel["spatialReference"];
            var distance = keyValueModel["distance"];

            int wkid;
            double distanceValue;

            int.TryParse(string.IsNullOrEmpty(spatialReference) ? "26912" : spatialReference, out wkid);
            double.TryParse(string.IsNullOrEmpty(distance) ? "5" : distance, out distanceValue);

            if (distanceValue < 5)
            {
                distanceValue = 5;
            }

            bindingContext.Model = new ReverseGeocodeOptions
            {
                Distance = distanceValue,
                WkId = wkid
            };

            return true;
        }
        public void AllOptions()
        {
            var binder = new GeocodeOptionsModelBinding();
            var httpControllerContext = new HttpControllerContext
                {
                    Request =
                        new HttpRequestMessage(HttpMethod.Get,
                                               "http://webapi/api/v1/geocode/address/zone?spatialReference=111&format=geojson&callback=p&acceptScore=80&suggest=1&locators=roadCenterlines&pobox=tRue&apiKey=AGRC-ApiExplorer")
                };
            var httpActionContext = new HttpActionContext {ControllerContext = httpControllerContext};
            var moc = new Mock<ModelMetadataProvider>();
            var modelBindingContext = new ModelBindingContext
                {
                    ModelMetadata =
                        new ModelMetadata(moc.Object, null, null, typeof (GeocodeOptions), null)
                };

            var successful = binder.BindModel(httpActionContext, modelBindingContext);

            Assert.That(successful, Is.True);

            var model = modelBindingContext.Model as GeocodeOptions;
            
            Assert.That(model, Is.Not.Null);

            Assert.That(model.AcceptScore, Is.EqualTo(80));
            Assert.That(model.WkId, Is.EqualTo(111));
            Assert.That(model.SuggestCount, Is.EqualTo(1));
            Assert.That(model.PoBox, Is.True);
            Assert.That(model.Locators, Is.EqualTo(LocatorType.RoadCenterlines));
        }
		public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
		{
			if (bindingContext.ModelType != typeof(ListEntrySearchCriteria))
			{
				return false;
			}
			
			var qs = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query as string);

			var result = new ListEntrySearchCriteria();

			result.ResponseGroup = ResponseGroup.WithCatalogs | ResponseGroup.WithCategories | ResponseGroup.WithProducts;

			var respGroup = qs["respGroup"].EmptyToNull();
			if(respGroup != null)
			{
				result.ResponseGroup = (ResponseGroup)Enum.Parse(typeof(ResponseGroup), respGroup, true);
			}
			result.Keyword = qs["q"].EmptyToNull();
		
			result.CatalogId = qs["catalog"].EmptyToNull();
			result.CategoryId = qs["category"].EmptyToNull();
			result.Count = qs["count"].TryParse(20);
			result.Start = qs["start"].TryParse(0);
			bindingContext.Model = result;
			return true;
		}
Пример #29
0
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            
            var values = actionContext.Request.RequestUri.ParseQueryString();
            try
            {
                
                _filterGenerator = new ConditionalFilterGenerator<Good>(values);

                _filterGenerator.SetKeyValueExpression<IEnumerable<int>, IEnumerable<int>>
                    ((g, c, s) => g.ClassificationGoods.Any(cat => c.Contains(cat.ColorId) && s.Contains(cat.SizeId)), "colors", "sizes");
                _filterGenerator.SetKeyValueExpression<IEnumerable<int>>((g, c) => g.ClassificationGoods.Any(cat => c.Contains(cat.ColorId)), false, "colors");
                _filterGenerator.SetKeyValueExpression<IEnumerable<int>>((g, s) => g.ClassificationGoods.Any(cat => s.Contains(cat.SizeId)), false, "sizes");

                _filterGenerator.SetKeyValueExpression<decimal>((g, p) => Math.Ceiling(g.PriceUsd - (g.Discount ?? 0) / (decimal)100 * g.PriceUsd) >= p, "priceMin");
                _filterGenerator.SetKeyValueExpression<decimal>((g, p) => g.PriceUsd - (g.Discount ?? 0) / (decimal)100 * g.PriceUsd <= p, "priceMax");

                bindingContext.Model = _filterGenerator.GetConditional();

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
 private static DateTime GetDateTime(ModelBindingContext context, string prefix, string key)
 {
     var dateValue = GetValue(context, prefix, key);
     dateValue = dateValue.Replace("\"", string.Empty);
     dateValue = dateValue.Split('T')[0];
     return TryParser.DateTime(dateValue) ?? DateTime.Today;
 }
    /// <summary>
    /// Implementing Base method and binding received data in API to its respected property in Model class
    /// </summary>
    /// <param name="actionContext">Http Action Context</param>
    /// <param name="bindingContext">Model Binding Context</param>
    /// <returns>True if no error while binding. False if any error occurs during model binding</returns>
    public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
    {
        try
        {
            var bodyString = actionContext.Request.Content.ReadAsStringAsync().Result;
            if (actionContext.Request.Method.Method.ToUpper().Equals("GET"))
            {
                var uriContext = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);
                if (uriContext.HasKeys())
                {
                    this.kvps = uriContext.AllKeys.ToDictionary(k => k, k => uriContext[k]).ToList <KeyValuePair <string, string> >();
                }
            }
            else if (!string.IsNullOrEmpty(bodyString))
            {
                this.kvps = this.ConvertToKvps(bodyString);
            }
            else
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Please provide valid input data.");
                return(false);
            }
        }
        catch (Exception ex)
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Please provide data in a valid format.");
            return(false);
        }

        // Initiate primary object
        var obj = Activator.CreateInstance(bindingContext.ModelType);

        try
        {
            this.SetPropertyValues(obj);
        }
        catch (Exception ex)
        {
            if (this.dictionaryErrors.Any())
            {
                foreach (KeyValuePair <string, string> keyValuePair in this.dictionaryErrors)
                {
                    bindingContext.ModelState.AddModelError(keyValuePair.Key, keyValuePair.Value);
                }
            }
            else
            {
                bindingContext.ModelState.AddModelError("Internal Error", ex.Message);
            }

            this.dictionaryErrors.Clear();
            return(false);
        }

        // Assign completed Mapped object to Model
        bindingContext.Model = obj;
        return(true);
    }
Пример #32
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="actionContext"></param>
        /// <param name="bindingContext"></param>
        /// <returns></returns>
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            bindingContext.Model = bindingContext.ValueProvider
                                   .GetValue(bindingContext.ModelName)
                                   .ConvertTo(bindingContext.ModelType, Thread.CurrentThread.CurrentCulture);

            bindingContext.ValidationNode.ValidateAllProperties = true;

            return(true);
        }
Пример #33
0
        public bool BindModel(
            System.Web.Http.Controllers.HttpActionContext actionContext,
            System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
        {
            if (actionContext.Request.Content.IsMimeMultipartContent())
            {
                var inputModel = new Foo();

                inputModel.Bar    = ""; //From the actionContext.Request etc
                inputModel.Stream = actionContext.Request.Content.ReadAsByteArrayAsync()
                                    .Result;

                bindingContext.Model = inputModel;
                return(true);
            }
            else
            {
                throw new HttpResponseException(actionContext.Request.CreateResponse(
                                                    HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
            }
        }
 public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
 {
     throw new NotImplementedException();
 }
Пример #35
0
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            string body  = actionContext.Request.Content.ReadAsStringAsync().Result;
            var    model = new NameAndAddressParameter();
            var    a     = JsonConvert.DeserializeObject <NameAndAddressParameter>(body);

            JsonConvert.PopulateObject(body, model);

            if ((model.ReturnMe.Permissions != null && model.ReturnMe.Permissions.Required))
            {
                model.ResponseRequestedItems.Add("permissions");
                model.NameAndAddress.Address.Address1  = BuildAddress1(model.NameAndAddress);
                model.NameAndAddress.Address.Address2  = model.NameAndAddress.Address.Address2 ?? (model.NameAndAddress.CustomerAddress.City ?? "");
                model.NameAndAddress.Address.Address3  = model.NameAndAddress.Address.Address3 ?? (model.NameAndAddress.CustomerAddress.County ?? "");
                model.NameAndAddress.Address.Address4  = model.NameAndAddress.Address.Address4 ?? (model.NameAndAddress.CustomerAddress.Country ?? "");
                model.NameAndAddress.Address.Postcode  = model.NameAndAddress.Address.Postcode ?? model.NameAndAddress.CustomerAddress.Postcode;
                model.NameAndAddress.Address.MatchType = MatchType.NAME_AND_ADDRESS.ToLowerString();
                model.NameAndAddress.MatchType         = MatchType.NAME_AND_ADDRESS.ToLowerString();
                model.ReturnMe.Permissions.MatchType   = MatchType.NAME_AND_ADDRESS.ToLowerString();
            }
            if ((model.ReturnMe.Membership != null && model.ReturnMe.Membership.Required))
            {
                model.ResponseRequestedItems.Add("membership");
            }
            if (model.ReturnMe.MailingHistory != null)
            {
                model.ResponseRequestedItems.Add("mailinghistory");
                model.NameAndAddress.MatchType          = MatchType.NAME_AND_ADDRESS.ToLowerString();
                model.ReturnMe.MailingHistory.MatchType = MatchType.NAME_AND_ADDRESS.ToLowerString();
            }
            List <string> emptyList = new List <string>();

            if (model.ReturnMe.CustomerKeys != null && model.ReturnMe.CustomerKeys.SequenceEqual(emptyList) || model.ReturnMe.CustomerKeys?.Count > 0)
            {
                model.ResponseRequestedItems.Add("customerkeys");
                model.AccessControl.CustomerKeyAccess = model.ReturnMe.CustomerKeys.ToCustomerKeyGroupCodeEnum();
            }
            if (model.ReturnMe.CustomerDetail != null && model.ReturnMe.CustomerDetail.Required)
            {
                model.ResponseRequestedItems.Add("customerdetail");
            }
            if (model.ReturnMe.TravelSummary != null && model.ReturnMe.TravelSummary.Required)
            {
                model.ResponseRequestedItems.Add("travelsummary");
            }
            // if (model.ReturnMe.CustomerMatch?.MatchType != null)
            if (model.ReturnMe.CustomerMatch != null)
            {
                //matchtype we need in all levels models to validate purpose, hence we hae MatchPrperty in child object of NameAndAddressParameter model
                model.ResponseRequestedItems.Add("customermatch");
                //
                // GITCS-3 : We now accept "null" match type value - must map to DEFAULT MatchType enum value for new default matching rules
                model.ReturnMe.CustomerMatch.MatchType =
                    model.ReturnMe.CustomerMatch.MatchType?.ToLower().Trim() == "null"
                        ? MatchType.DEFAULT.ToString().ToLower()
                        : model.ReturnMe.CustomerMatch.MatchType?.ToLower().Trim()
                ;
                // Synch the other 2 match types
                model.NameAndAddress.MatchType         = model.ReturnMe.CustomerMatch.MatchType;
                model.NameAndAddress.Address.MatchType = model.ReturnMe.CustomerMatch.MatchType;
                //
                // model.NameAndAddress.MatchType = model.ReturnMe.CustomerMatch.MatchType.ToLower().Trim();
                // model.NameAndAddress.Address.MatchType = model.ReturnMe.CustomerMatch.MatchType.ToLower().Trim();
            }


            model.AccessControl.ModuleAccess = model.ResponseRequestedItems.ToGroupCodeEnum();


            var validator = new NameAndAddressParameterValidator();
            var result    = validator.Validate(model);

            foreach (var e in result.Errors)
            {
                bindingContext.ModelState.AddModelError(e.PropertyName, e.ErrorMessage);
            }

            bindingContext.Model = model;

            return(true);
        }
        public void BindModel_SuccessfulBind_ComplexTypeFallback_RunsValidationAndReturnsModel()
        {
            // Arrange
            HttpActionContext actionContext = ContextUtil.CreateActionContext(
                GetHttpControllerContext()
                );

            bool       validationCalled = false;
            List <int> expectedModel    = new List <int> {
                1, 2, 3, 4, 5
            };

            ModelBindingContext bindingContext = new ModelBindingContext
            {
                FallbackToEmptyPrefix = true,
                ModelMetadata         = new EmptyModelMetadataProvider().GetMetadataForType(
                    null,
                    typeof(List <int>)
                    ),
                ModelName = "someName",
                //ModelState = executionContext.Controller.ViewData.ModelState,
                //PropertyFilter = _ => true,
                ValueProvider = new SimpleValueProvider {
                    { "someOtherName", "dummyValue" }
                }
            };

            Mock <IModelBinder> mockIntBinder = new Mock <IModelBinder>();

            mockIntBinder
            .Setup(o => o.BindModel(actionContext, It.IsAny <ModelBindingContext>()))
            .Returns(
                delegate(HttpActionContext cc, ModelBindingContext mbc)
            {
                if (!String.IsNullOrEmpty(mbc.ModelName))
                {
                    return(false);
                }

                Assert.Same(bindingContext.ModelMetadata, mbc.ModelMetadata);
                Assert.Equal("", mbc.ModelName);
                Assert.Same(bindingContext.ValueProvider, mbc.ValueProvider);

                mbc.Model = expectedModel;
                mbc.ValidationNode.Validating += delegate
                {
                    validationCalled = true;
                };
                return(true);
            }
                );

            //binderProviders.RegisterBinderForType(typeof(List<int>), mockIntBinder.Object, false /* suppressPrefixCheck */);
            IModelBinder shimBinder = new CompositeModelBinder(mockIntBinder.Object);

            // Act
            bool isBound = shimBinder.BindModel(actionContext, bindingContext);

            // Assert
            Assert.True(isBound);
            Assert.Equal(expectedModel, bindingContext.Model);
            Assert.True(validationCalled);
            Assert.True(bindingContext.ModelState.IsValid);
        }
Пример #37
0
 public bool BindModel(
     System.Web.Http.Controllers.HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
 {
     return(true);
 }