public void ConvertToCanConvertArraysToSingleElements()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult(new int[] { 1, 20, 42 }, "", CultureInfo.InvariantCulture);

            // Act
            string converted = (string)vpr.ConvertTo(typeof(string));

            // Assert
            Assert.Equal("1", converted);
        }
        public void ConvertToCanConvertSingleElementsToSingleElements()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult(42, "", CultureInfo.InvariantCulture);

            // Act
            string converted = (string)vpr.ConvertTo(typeof(string));

            // Assert
            Assert.NotNull(converted);
            Assert.Equal("42", converted);
        }
        public static IEnumerable<string> GetIndexNamesFromValueProviderResult(ValueProviderResult valueProviderResult)
        {
            IEnumerable<string> indexNames = null;
            if (valueProviderResult != null)
            {
                var indexes = (string[])valueProviderResult.ConvertTo(typeof(string[]));
                if (indexes != null && indexes.Length > 0)
                {
                    indexNames = indexes;
                }
            }

            return indexNames;
        }
        public void ConstructorSetsProperties()
        {
            // Arrange
            object rawValue = new object();
            string attemptedValue = "some string";
            CultureInfo culture = CultureInfo.GetCultureInfo("fr-FR");

            // Act
            ValueProviderResult result = new ValueProviderResult(rawValue, attemptedValue, culture);

            // Assert
            Assert.Same(rawValue, result.RawValue);
            Assert.Same(attemptedValue, result.AttemptedValue);
            Assert.Same(culture, result.Culture);
        }
        public void ConvertToCanConvertArraysToArrays()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult(new int[] { 1, 20, 42 }, "", CultureInfo.InvariantCulture);

            // Act
            string[] converted = (string[])vpr.ConvertTo(typeof(string[]));

            // Assert
            Assert.NotNull(converted);
            Assert.Equal(3, converted.Length);
            Assert.Equal("1", converted[0]);
            Assert.Equal("20", converted[1]);
            Assert.Equal("42", converted[2]);
        }
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (!typeof(DerivationStrategyBase).GetTypeInfo().IsAssignableFrom(bindingContext.ModelType))
            {
                return(Task.CompletedTask);
            }

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

            if (val == null)
            {
                return(Task.CompletedTask);
            }

            string key = val.FirstValue as string;

            if (key == null)
            {
                return(Task.CompletedTask);
            }

            var networkProvider = (NBXplorer.NBXplorerNetworkProvider)bindingContext.HttpContext.RequestServices.GetService(typeof(NBXplorer.NBXplorerNetworkProvider));
            var cryptoCode      = bindingContext.ValueProvider.GetValue("cryptoCode").FirstValue;

            cryptoCode = cryptoCode ?? bindingContext.ValueProvider.GetValue("network").FirstValue;
            var network = networkProvider.GetFromCryptoCode((cryptoCode ?? "BTC"));

            try
            {
                var data = network.DerivationStrategyFactory.Parse(key);
                if (!bindingContext.ModelType.IsInstanceOfType(data))
                {
                    throw new FormatException("Invalid destination type");
                }
                bindingContext.Result = ModelBindingResult.Success(data);
            }
            catch { throw new FormatException("Invalid derivation scheme"); }
            return(Task.CompletedTask);
        }
        private string GetValue(ModelBindingContext context, string name)
        {
            ValueProviderResult result = context.ValueProvider.GetValue("Address." + name);

            if (result != null)
            {
                switch (name)
                {
                case "Line2":
                {
                    if (result.AttemptedValue.ToLower().Contains("po box") || result.AttemptedValue == string.Empty)
                    {
                        return("<not defined>");
                    }
                    break;
                }

                case "PostalCode":
                {
                    if (result.AttemptedValue.Length < 6)
                    {
                        return("<not defined>");
                    }
                    break;
                }

                case "Line1":
                {
                    if (result.AttemptedValue.ToLower().Contains("po box"))
                    {
                        return("<not defined>");
                    }
                    break;
                }
                }
                return(result.AttemptedValue);
            }

            return("<not defined>");
        }
        public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (!typeof(BalanceId).IsAssignableFrom(bindingContext.ModelType))
            {
                return(false);
            }

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

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

            string key = val.RawValue as string;

            if (key.Length > 3 && key.Length < 5000 && key.StartsWith("0x"))
            {
                bindingContext.Model = new BalanceId(new Script(Encoders.Hex.DecodeData(key.Substring(2))));
                return(true);
            }
            if (key.Length > 3 && key.Length < 5000 && key.StartsWith("W-"))
            {
                bindingContext.Model = new BalanceId(key.Substring(2));
                return(true);
            }
            var data = Network.Parse(key, actionContext.RequestContext.GetConfiguration().Indexer.Network);

            if (!(data is IDestination))
            {
                throw new FormatException("Invalid base58 type");
            }
            if (data is BitcoinColoredAddress)
            {
                actionContext.Request.Properties["BitcoinColoredAddress"] = true;
            }
            bindingContext.Model = new BalanceId((IDestination)data);
            return(true);
        }
        public BindResult BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            try
            {
                ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                string enumerationValue   = value == null ? string.Empty : value.AttemptedValue;

                if (enumerationValue == "")
                {
                    return(null);
                }

                Enumeration enumeration = GetEnumeration(bindingContext.ModelType, enumerationValue);
                return(new BindResult(enumeration, value));
            }
            catch (Exception ex)
            {
                string message = string.Format("Unable to locate a valid value for query string parameter '{0}'",
                                               bindingContext.ModelName);
                throw new ApplicationException(message, ex);
            }
        }
Example #10
0
        internal void AddAttemptedValues(ObjectAndControlData controlData)
        {
            var action = controlData.GetAction(Facade);
            var form   = controlData.Form;

            foreach (var parm in action.Parameters)
            {
                string name                = IdHelper.GetParameterInputId(action, parm);
                ValueProviderResult vp     = form.GetValue(name);
                string[]            values = vp == null ? new string[] {} : (string[])vp.RawValue;

                if (parm.Specification.IsCollection && !parm.Specification.IsParseable)
                {
                    // handle collection mementos

                    if (parm.IsChoicesEnabled == Choices.Multiple || !CheckForAndAddCollectionMementoNew(name, values, controlData))
                    {
                        var itemSpec   = parm.ElementType;
                        var itemvalues = values.Select(v => itemSpec.IsParseable ? (object)v : GetNakedObjectFromId(v).GetDomainObject <object>()).ToList();

                        if (itemvalues.Any())
                        {
                            var no = Facade.GetObject(itemvalues);

                            AddAttemptedValue(name, no);
                        }
                    }
                }
                else
                {
                    string value = values.Any() ? values.First() : "";

                    if (!string.IsNullOrEmpty(value))
                    {
                        AddAttemptedValue(name, parm.Specification.IsParseable ? (object)value : FilterCollection(GetNakedObjectFromId(value), controlData));
                    }
                }
            }
        }
Example #11
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            string attemptedValue     = value.AttemptedValue;

            string format = !String.IsNullOrEmpty(bindingContext.ModelMetadata.DisplayFormatString)
                ? bindingContext.ModelMetadata.DisplayFormatString
                : "HH:mm:ss tt";


            DateTime datetime = ToDateTime(attemptedValue, format);
            var      time     = new Time(datetime.Hour, datetime.Minute, datetime.Second);
            Type     type     = bindingContext.ModelType;

            if (!type.IsGenericType)
            {
                return(time);
            }
            Time?t = time;

            return(t);
        }
Example #12
0
        object IModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueProvider = bindingContext.ValueProvider;

            ValueProviderResult vprId = valueProvider.GetValue("Id");

            string name   = (string)valueProvider.GetValue("Name").ConvertTo(typeof(string));
            string author = (string)valueProvider.GetValue("Author").ConvertTo(typeof(string));
            int    year   = (int)valueProvider.GetValue("Year").ConvertTo(typeof(int));
            Book   book   = new Models.Book()
            {
                Name = name + "(new)", Author = author, Year = year
            };

            if (vprId != null)
            {
                book.Name = name;
                book.Id   = (int)vprId.ConvertTo(typeof(int));
            }

            return(book);
        }
        protected Nullable <T> GetValueStruct <T>(ControllerContext controllerContext, ModelBindingContext bindingContext, string key)
            where T : struct
        {
            ValueProviderResult valueResult = GetValueProviderResult(controllerContext, bindingContext, key);

            if (valueResult == null)
            {
                return(null);
            }

            bindingContext.ModelState.SetModelValue(key, valueResult);

            try
            {
                return(new Nullable <T>((T)valueResult.ConvertTo(typeof(T))));
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);
                return(null);
            }
        }
            public bool BindModel(
                ControllerContext controllerContext,
                ExtensibleModelBindingContext bindingContext
                )
            {
                ModelBinderUtil.ValidateBindingContext(bindingContext);
                ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(
                    bindingContext.ModelName
                    );

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

                string base64String = (string)valueProviderResult.ConvertTo(typeof(string));

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

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

                try
                {
                    bindingContext.Model = ConvertByteArray(Convert.FromBase64String(realValue));
                    return(true);
                }
                catch
                {
                    // corrupt data - just ignore
                    return(false);
                }
            }
Example #15
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
            if (value != null)
            {
                try
                {
                    var date = value.ConvertTo(typeof(DateTime?), CultureInfo.CurrentCulture);
                    return(date);
                }
                catch
                {
                    //If something wrong, validation should take care
                    bindingContext.ModelState.AddModelError(bindingContext.ModelName, string.Format("{0} format is incorrect", bindingContext.ModelName));
                    return(value);
                }
            }

            return(value);
        }
Example #16
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 for testing.
        internal async Task <CollectionResult> BindSimpleCollection(
            ModelBindingContext bindingContext,
            ValueProviderResult values)
        {
            var boundCollection = new List <TElement>();

            var elementMetadata = bindingContext.ModelMetadata.ElementMetadata;

            foreach (var value in values)
            {
                bindingContext.ValueProvider = new CompositeValueProvider
                {
                    // our temporary provider goes at the front of the list
                    new ElementalValueProvider(bindingContext.ModelName, value, values.Culture),
                    bindingContext.ValueProvider
                };

                // Enter new scope to change ModelMetadata and isolate element binding operations.
                using (bindingContext.EnterNestedScope(
                           elementMetadata,
                           fieldName: bindingContext.FieldName,
                           modelName: bindingContext.ModelName,
                           model: null))
                {
                    await ElementBinder.BindModelAsync(bindingContext);

                    if (bindingContext.Result.IsModelSet)
                    {
                        var boundValue = bindingContext.Result.Model;
                        boundCollection.Add(CastOrDefault <TElement>(boundValue));
                    }
                }
            }

            return(new CollectionResult
            {
                Model = boundCollection
            });
        }
Example #17
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            try
            {
                ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                string enumerationValue   = value == null ? String.Empty : value.AttemptedValue;

                if (enumerationValue == String.Empty)
                {
                    return(null);
                }

                Enumeration enumeration = GetEnumeration(bindingContext.ModelType, enumerationValue);
                return(enumeration);
            }
            catch (Exception ex)
            {
                throw new CmsException(
                          String.Format("Unable to locate a valid value for enumeration query string parameter '{0}'",
                                        bindingContext.ModelName), ex);
            }
        }
Example #18
0
        public void GetValueProvider()
        {
            // Arrange
            RouteDataValueProviderFactory factory = new RouteDataValueProviderFactory();

            ControllerContext controllerContext = new ControllerContext();

            controllerContext.RouteData = new RouteData();
            controllerContext.RouteData.Values["forty-two"] = 42;

            // Act
            IValueProvider valueProvider = factory.GetValueProvider(controllerContext);

            // Assert
            Assert.IsType <RouteDataValueProvider>(valueProvider);
            ValueProviderResult vpResult = valueProvider.GetValue("forty-two");

            Assert.NotNull(vpResult);
            Assert.Equal(42, vpResult.RawValue);
            Assert.Equal("42", vpResult.AttemptedValue);
            Assert.Equal(CultureInfo.InvariantCulture, vpResult.Culture);
        }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider
                                              .GetValue(bindingContext.ModelName);
            ModelState modelState = new ModelState {
                Value = valueResult
            };
            object actualValue = null;

            try
            {
                actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                                                CultureInfo.CurrentCulture);
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return(actualValue);
        }
Example #20
0
        public Object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (value == null || value.AttemptedValue == null)
            {
                return(null);
            }

            Type containerType = bindingContext.ModelMetadata.ContainerType;

            if (containerType != null)
            {
                PropertyInfo property = containerType.GetProperty(bindingContext.ModelName);
                if (property.GetCustomAttribute <NotTrimmedAttribute>() != null)
                {
                    return(value.AttemptedValue);
                }
            }

            return(value.AttemptedValue.Trim());
        }
        private static void CheckModel(ModelBindingContext bindingContext, ValueProviderResult valueProviderResult, object model)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            // When converting newModel a null value may indicate a failed conversion for an otherwise required
            // model (can't set a ValueType to null). This detects if a null model value is acceptable given the
            // current bindingContext. If not, an error is logged.
            if (model == null && !bindingContext.ModelMetadata.IsReferenceOrNullableType)
            {
                bindingContext.ModelState.TryAddModelError(
                    bindingContext.ModelName,
                    bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueMustNotBeNullAccessor(
                        valueProviderResult.ToString()));
            }
            else
            {
                bindingContext.Result = ModelBindingResult.Success(model);
            }
        }
Example #22
0
        /// <summary>Binds a received decimal value to the view model.</summary>
        /// <param name="controllerContext">An instance that encapsulates information about the HTTP request.</param>
        /// <param name="bindingContext">The context for the model binder.</param>
        /// <returns>The converted decimal value.</returns>
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            Guard.ArgumentIsNotNull(bindingContext, nameof(bindingContext));

            /* Retrieve the value information from the received data */
            ValueProviderResult providerValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            ModelState          modelState    = new ModelState {
                Value = providerValue
            };

            object actualValue = null;

            if (providerValue != null && providerValue.RawValue != null && !string.Empty.Equals(providerValue.RawValue))
            {
                /* Retrieve the raw value and convert it to a decimal */
                actualValue = Convert.ToDecimal(providerValue.RawValue, this.formatProvider);
            }

            /* Register the succesfull conversion and return the converted value */
            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return(actualValue);
        }
        private static void BindValue(dynamic shape, IValueProvider valueProvider, string prefix)
        {
            // if the shape has a Name property, look for a value in
            // the ValueProvider
            var name = shape.Name;

            if (name != null)
            {
                ValueProviderResult value = valueProvider.GetValue(prefix + name);
                if (value != null)
                {
                    if (shape.Metadata.Type == "Checkbox" || shape.Metadata.Type == "Radio")
                    {
                        shape.Checked = Convert.ToString(shape.Value) == Convert.ToString(value.AttemptedValue);
                    }
                    else
                    {
                        shape.Value = value.AttemptedValue;
                    }
                }
            }
        }
Example #24
0
        public void GetValueProvider()
        {
            // Arrange
            RouteDataValueProviderFactory factory = new RouteDataValueProviderFactory();

            ControllerContext controllerContext = new ControllerContext();

            controllerContext.RouteData = new RouteData();
            controllerContext.RouteData.Values["forty-two"] = 42;

            // Act
            IValueProvider valueProvider = factory.GetValueProvider(controllerContext);

            // Assert
            Assert.AreEqual(typeof(RouteDataValueProvider), valueProvider.GetType());
            ValueProviderResult vpResult = valueProvider.GetValue("forty-two");

            Assert.IsNotNull(vpResult, "Should have contained a value for key 'forty-two'.");
            Assert.AreEqual(42, vpResult.RawValue);
            Assert.AreEqual("42", vpResult.AttemptedValue);
            Assert.AreEqual(CultureInfo.InvariantCulture, vpResult.Culture);
        }
Example #25
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            string?stringValue = valueProviderResult.FirstValue;

            if (string.IsNullOrWhiteSpace(stringValue) && IsNullableStruct(bindingContext.ModelType) == false)
            {
                bindingContext.Result = ModelBindingResult.Failed();
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "The value is required");
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

                return(Task.CompletedTask);
            }

            IOptions <JsonOptions> jsonOptions = bindingContext.HttpContext.RequestServices.GetRequiredService <IOptions <JsonOptions> >();

            byte[] byteValue = JsonSerializer.SerializeToUtf8Bytes(stringValue);
            object?enumValue = JsonSerializer.Deserialize(byteValue, bindingContext.ModelType, jsonOptions.Value.JsonSerializerOptions);

            bindingContext.Result = ModelBindingResult.Success(enumValue ?? GetDefault(bindingContext.ModelType));
            return(Task.CompletedTask);
        }
        private string GetValue(ModelBindingContext context, string name)
        {
            name = (context.ModelName == "" ? "" : context.ModelName + ".") + name;

            ValueProviderResult result = context.ValueProvider.GetValue(name);

            if (result == null || result.AttemptedValue == "")
            {
                return("<not-defined>");
            }

            if ((name.Contains("Line1") || name.Contains("Line2")) && result.AttemptedValue.Contains("PO BOX"))
            {
                return("<not-defined>");
            }

            if (name.Contains("PostalCode") && result.AttemptedValue.Length < 6)
            {
                return("<not-defined>");
            }
            return(result.AttemptedValue);
        }
Example #27
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (!typeof(uint256).GetTypeInfo().IsAssignableFrom(bindingContext.ModelType))
            {
                return(Task.CompletedTask);
            }

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

            string key = val.FirstValue as string;

            if (key == null)
            {
                bindingContext.Result = ModelBindingResult.Success(null);
                return(Task.CompletedTask);
            }
            var value = uint256.Parse(key);

            bindingContext.Result = ModelBindingResult.Success(value);
            return(Task.CompletedTask);
        }
        /// <summary>
        /// Binds the model to a value by using the specified controller context and binding context.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        /// <param name="bindingContext">The binding context.</param>
        /// <returns>
        /// true if model binding is successful; otherwise, false.
        /// </returns>
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            string key = bindingContext.ModelName;

            ValueProviderResult value = bindingContext.ValueProvider.GetValue(key);

            if (value != null)
            {
                string attempt = value.AttemptedValue;

                if (string.IsNullOrWhiteSpace(attempt) == false &&
                    attempt.Split(new[] { '-' }).Length == 3)                     // 2017-01-07
                {
                    // DateBinder (not DateTime) --> so only Date is parsed
                    bindingContext.Model = DateTimeParser.ParseUrlString(attempt);                     //TODO: UTC?!
                }

                return(true);
            }

            return(false);
        }
Example #29
0
        public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (null == result)
            {
                return(false);
            }
            try
            {
                bindingContext.Model = result.ConvertTo(bindingContext.ModelType);
                if (bindingContext.Model is string && string.IsNullOrWhiteSpace((string)bindingContext.Model) && bindingContext.ModelMetadata.ConvertEmptyStringToNull)
                {
                    bindingContext.Model = null;
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        public object BindModel(ControllerContext cntrlrContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult valFirstName = bindingContext.ValueProvider.GetValue("FirstName");
            ValueProviderResult valLastName  = bindingContext.ValueProvider.GetValue("LastName");
            ValueProviderResult valAge       = bindingContext.ValueProvider.GetValue("Age");

            string firstName = valFirstName.AttemptedValue ?? null;
            string lastName  = valLastName.AttemptedValue ?? null;
            int    Age       = valAge.AttemptedValue != null?Convert.ToInt32(valAge.AttemptedValue) : 0;

            EmployeesModel empModel = new EmployeesModel();

            empModel.FirstName = firstName;
            empModel.LastName  = lastName;
            empModel.Name      = firstName + " " + lastName;
            empModel.Age       = Age;
            return(empModel);
            // string Name = firstName+ " "+lastName;
            //ValueProviderResult val = new ValueProviderResult(Name,Name,valFirstName.Culture);
            //ModelStateDictionary mstate = bindingContext.ModelState;
            //mstate.SetModelValue("Name", val);
        }
Example #31
0
        public void GetValue_NonValidating_WithArraysInCollection(
            string name, string value, string index, string expectedAttemptedValue)
        {
            // Arrange
            string[]            expectedRawValue      = new[] { expectedAttemptedValue };
            NameValueCollection unvalidatedCollection = new NameValueCollection();

            unvalidatedCollection.Add(name, value);

            CultureInfo culture = CultureInfo.GetCultureInfo("fr-FR");
            NameValueCollectionValueProvider valueProvider =
                new NameValueCollectionValueProvider(_backingStore, unvalidatedCollection, culture, true);

            // Act
            ValueProviderResult vpResult = valueProvider.GetValue(index, skipValidation: true);

            // Asserts
            Assert.NotNull(vpResult);
            Assert.Equal(culture, vpResult.Culture);
            Assert.Equal(expectedRawValue, (string[])vpResult.RawValue);
            Assert.Equal(expectedAttemptedValue, vpResult.AttemptedValue);
        }
        public void GetValueProvider()
        {
            // Arrange
            Mock <MockableUnvalidatedRequestValues> mockUnvalidatedValues = new Mock <MockableUnvalidatedRequestValues>();
            JQueryFormValueProviderFactory          factory =
                new JQueryFormValueProviderFactory(_ => mockUnvalidatedValues.Object);

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

            mockControllerContext.Setup(o => o.HttpContext.Request.Form).Returns(_backingStore);

            // Act
            IValueProvider valueProvider = factory.GetValueProvider(mockControllerContext.Object);

            // Assert
            Assert.Equal(typeof(JQueryFormValueProvider), valueProvider.GetType());
            ValueProviderResult vpResult = valueProvider.GetValue("fooArray[0].bar1");

            Assert.NotNull(vpResult);
            Assert.Equal("fooArrayValue", vpResult.AttemptedValue);
            Assert.Equal(CultureInfo.CurrentCulture, vpResult.Culture);
        }
Example #33
0
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            MethodInfo deserializeMethod = GetType().GetMethod("DeserializeModel")
                                           .MakeGenericMethod(bindingContext.ModelType);
            var model = deserializeMethod.Invoke(this, new object[] { actionContext }) ??
                        Activator.CreateInstance(bindingContext.ModelType);

            foreach (var prop in model.GetType().GetProperties())
            {
                ValueProviderResult uriVal = bindingContext.ValueProvider.GetValue(prop.Name.ToLowerInvariant());
                if (uriVal != null)
                {
                    prop.SetValue(model, Convert.ChangeType(uriVal.RawValue, prop.PropertyType), null);
                }
            }

            bindingContext.Model = model;
            bindingContext.ValidationNode.ValidateAllProperties = true;
            bindingContext.ValidationNode.Validate(actionContext);

            return(true);
        }
        public bool BindModel(
            ControllerContext controllerContext,
            ExtensibleModelBindingContext bindingContext
            )
        {
            ValueProviderResult valueProviderResult = GetCompatibleValueProviderResult(
                bindingContext
                );

            if (valueProviderResult == null)
            {
                return(false); // conversion would have failed
            }

            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
            object model = valueProviderResult.RawValue;

            ModelBinderUtil.ReplaceEmptyStringWithNull(bindingContext.ModelMetadata, ref model);
            bindingContext.Model = model;

            return(true);
        }
        /// <summary>
        ///     Determines whether the intelligent captcha is valid.
        /// </summary>
        /// <param name="captchaManager">The specified captcha manager.</param>
        /// <param name="controller">
        ///     The specified <see cref="ControllerBase" />.
        /// </param>
        /// <param name="parameterContainer">
        ///     The specified <see cref="IParameterContainer" />.
        /// </param>
        /// <returns>
        ///     <c>True</c> if the intelligent captcha is valid; <c>false</c> not valid; <c>null</c> is not intelligent captcha.
        /// </returns>
        public virtual bool?IsValid(ICaptchaManager captchaManager, ControllerBase controller, IParameterContainer parameterContainer)
        {
            Validate.ArgumentNotNull(captchaManager, "captchaManager");
            Validate.ArgumentNotNull(controller, "controller");
            ValueProviderResult tokenValue = controller
                                             .ValueProvider
                                             .GetValue(captchaManager.TokenElementName + PolicyType);

            if (tokenValue == null || string.IsNullOrEmpty(tokenValue.AttemptedValue))
            {
                return(null);
            }
            if (!RemoveTokenValue(controller, tokenValue.AttemptedValue))
            {
                return(null);
            }

            ValueProviderResult validationVal = controller.ValueProvider.GetValue(ValidationInputName);

            return(captchaManager.StorageProvider.Remove(tokenValue.AttemptedValue) && validationVal != null &&
                   Reverse(validationVal.AttemptedValue) == tokenValue.AttemptedValue);
        }
Example #36
0
        public void Enumerator_WithString()
        {
            // Arrange
            var result = new ValueProviderResult("Hi There");

            // Act & Assert
            Assert.Equal<string>(new string[] { "Hi There", }, result);
        }
        public void ConvertToReturnsValueIfArrayElementInstanceOfDestinationType()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult(new object[] { "some string" }, null, CultureInfo.InvariantCulture);

            // Act
            object outValue = vpr.ConvertTo(typeof(string));

            // Assert
            Assert.Equal("some string", outValue);
        }
Example #38
0
        public void Construct_With_Array()
        {
            // Arrange & Act
            var result = new ValueProviderResult(new string[] { "Hi", "There" });

            // Assert
            Assert.Equal(2, result.Length);
            Assert.Equal(new string[] { "Hi", "There" }, result.Values);
            Assert.Equal("Hi", result.FirstValue);
            Assert.NotEqual(ValueProviderResult.None, result);
            Assert.Equal("Hi,There", (string)result);
            Assert.Equal(new string[] { "Hi", "There" }, (string[])result);
        }
        public void ForExcludedModelBoundTypes_Properties_MarkedAsSkipped()
        {
            // Arrange
            var user = new User()
            {
                Password = "******",
                ConfirmPassword = "******"
            };

            var testValidationContext = GetModelValidationContext(
                user,
                typeof(User),
                new List<Type> { typeof(User) });
            var validationContext = testValidationContext.ModelValidationContext;

            // Set the value on model state as a model binder would.
            var valueProviderResult = new ValueProviderResult(rawValue: "password");
            validationContext.ModelState.SetModelValue("user.Password", valueProviderResult);
            var validator = new DefaultObjectValidator(
                testValidationContext.ExcludeFilters,
                testValidationContext.ModelMetadataProvider);
            var topLevelValidationNode =
                new ModelValidationNode(
                    "user",
                    testValidationContext.ModelValidationContext.ModelExplorer.Metadata,
                    testValidationContext.ModelValidationContext.ModelExplorer.Model)
                {
                    ValidateAllProperties = true
                };

            // Act
            validator.Validate(validationContext, topLevelValidationNode);

            // Assert
            var entry = Assert.Single(validationContext.ModelState);
            Assert.Equal("user.Password", entry.Key);
            Assert.Empty(entry.Value.Errors);
            Assert.Equal(entry.Value.ValidationState, ModelValidationState.Skipped);
            Assert.Same(valueProviderResult, entry.Value.Value);
        }
Example #40
0
        public void Operator_NotEquals(ValueProviderResult x, ValueProviderResult y, bool expected)
        {
            // Arrange
            var result = x != y;

            // Act & Assert
            Assert.NotEqual(expected, result);
        }
        public void ConvertToChecksTypeConverterCanConvertFrom()
        {
            // Arrange
            object original = "someValue";
            ValueProviderResult vpr = new ValueProviderResult(original, null, CultureInfo.GetCultureInfo("fr-FR"));

            // Act
            DefaultModelBinderTest.StringContainer returned = (DefaultModelBinderTest.StringContainer)vpr.ConvertTo(typeof(DefaultModelBinderTest.StringContainer));

            // Assert
            Assert.Equal(returned.Value, "someValue (fr-FR)");
        }
        public void CulturePropertyDefaultsToInvariantCulture()
        {
            // Arrange
            ValueProviderResult result = new ValueProviderResult(null, null, null);

            // Act & assert
            Assert.Same(CultureInfo.InvariantCulture, result.Culture);
        }
        public void ConvertToThrowsIfTypeIsNull()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult("x", null, CultureInfo.InvariantCulture);

            // Act & Assert
            Assert.ThrowsArgumentNull(
                delegate { vpr.ConvertTo(null); }, "type");
        }
        public void ConvertToChecksTypeConverterCanConvertTo()
        {
            // Arrange
            object original = new DefaultModelBinderTest.StringContainer("someValue");
            ValueProviderResult vpr = new ValueProviderResult(original, "", CultureInfo.GetCultureInfo("en-US"));

            // Act
            string returned = (string)vpr.ConvertTo(typeof(string));

            // Assert
            Assert.Equal(returned, "someValue (en-US)");
        }
        public void ConvertToThrowsIfConverterThrows()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult("x", null, CultureInfo.InvariantCulture);
            Type destinationType = typeof(DefaultModelBinderTest.StringContainer);

            // Act & Assert
            // Will throw since the custom converter assumes the first 5 characters to be digits
            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(
                delegate { vpr.ConvertTo(destinationType); },
                "The parameter conversion from type 'System.String' to type 'System.Web.Mvc.Test.DefaultModelBinderTest+StringContainer' failed. See the inner exception for more information.");

            Exception innerException = exception.InnerException;
            Assert.Equal("Value must have at least 3 characters.", innerException.Message);
        }
        public void ConvertToUsesProvidedCulture()
        {
            // Arrange
            object original = "someValue";
            CultureInfo gbCulture = CultureInfo.GetCultureInfo("en-GB");
            ValueProviderResult vpr = new ValueProviderResult(original, null, CultureInfo.GetCultureInfo("fr-FR"));

            // Act
            DefaultModelBinderTest.StringContainer returned = (DefaultModelBinderTest.StringContainer)vpr.ConvertTo(typeof(DefaultModelBinderTest.StringContainer), gbCulture);

            // Assert
            Assert.Equal(returned.Value, "someValue (en-GB)");
        }
        public void GetValueFromProvider_UnvalidatedProvider_DoNotSkipValidation()
        {
            // Arrange
            ValueProviderResult expectedResult = new ValueProviderResult("Success", "Success", null);

            Mock<IUnvalidatedValueProvider> mockProvider = new Mock<IUnvalidatedValueProvider>();
            mockProvider.Setup(o => o.GetValue("key", false)).Returns(expectedResult);

            // Act
            ValueProviderResult actualResult = ValueProviderCollection.GetValueFromProvider(mockProvider.Object, "key", skipValidation: false);

            // Assert
            Assert.Equal(expectedResult, actualResult);
        }
        public void ConvertToThrowsIfNoConverterExists()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult("x", null, CultureInfo.InvariantCulture);
            Type destinationType = typeof(MyClassWithoutConverter);

            // Act & Assert
            Assert.Throws<InvalidOperationException>(
                delegate { vpr.ConvertTo(destinationType); },
                "The parameter conversion from type 'System.String' to type 'System.Web.Mvc.Test.ValueProviderResultTest+MyClassWithoutConverter' failed because no type converter can convert between these types.");
        }
        public void GetValueFromProvider_UnvalidatedProvider_SkipValidation() {
            // Arrange
            ValueProviderResult expectedResult = new ValueProviderResult("Success", "Success", null);

            Mock<IUnvalidatedValueProvider> mockProvider = new Mock<IUnvalidatedValueProvider>();
            mockProvider.Setup(o => o.GetValue("key", true)).Returns(expectedResult);

            // Act
            ValueProviderResult actualResult = ValueProviderCollection.GetValueFromProvider(mockProvider.Object, "key", skipValidation: true);

            // Assert
            Assert.AreEqual(expectedResult, actualResult, "Collection did not properly flow through 'skipValidation' flag.");
        }
        public void ConvertToReturnsValueIfInstanceOfDestinationType()
        {
            // Arrange
            string[] original = new string[] { "some string" };
            ValueProviderResult vpr = new ValueProviderResult(original, null, CultureInfo.InvariantCulture);

            // Act
            object outValue = vpr.ConvertTo(typeof(string[]));

            // Assert
            Assert.Same(original, outValue);
        }
        public void GetValueFromProvider_NormalProvider_SkipValidation() {
            // Arrange
            ValueProviderResult expectedResult = new ValueProviderResult("Success", "Success", null);

            Mock<IValueProvider> mockProvider = new Mock<IValueProvider>();
            mockProvider.Setup(o => o.GetValue("key")).Returns(expectedResult);

            // Act
            ValueProviderResult actualResult = ValueProviderCollection.GetValueFromProvider(mockProvider.Object, "key", skipValidation: true);

            // Assert
            Assert.AreEqual(expectedResult, actualResult, "Regular IValueProvider instances should be treated as validation-agnostic, so the collection should call GetValue as normal.");
        }
        public void ValidationMessageNonUnobtrusive_HtmlEncodes_ModelStateAttemptedValue(
            string text,
            bool htmlEncode,
            string encodedText)
        {
            // Arrange
            var viewData = new ViewDataDictionary<string>(model: null);
            viewData.ModelMetadata.HtmlEncode = htmlEncode;
            viewData.ModelState.AddModelError(key: "name", errorMessage: null);
            var valueProvider = new ValueProviderResult(rawValue: null, attemptedValue: text, culture: null);
            viewData.ModelState.SetModelValue(key: "name", value: valueProvider);

            var helper = MvcHelper.GetHtmlHelper(viewData);
            helper.EnableClientValidation();
            helper.EnableUnobtrusiveJavaScript(enabled: false);

            // Act
            var result = helper.ValidationMessage(modelName: "name").ToHtmlString();

            // Assert
            Assert.Equal(
                "<span class=\"field-validation-error\" id=\"name_validationMessage\">The value &#39;" +
                    encodedText +
                    "&#39; is invalid.</span>",
                result);
        }
        public void ConvertToReturnsNullIfArrayElementValueIsNull()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult(new string[] { null }, null, CultureInfo.InvariantCulture);

            // Act
            object outValue = vpr.ConvertTo(typeof(int));

            // Assert
            Assert.Null(outValue);
        }
        public void ConvertToReturnsValueIfElementIsDecimalDoubleAndDestionationIsNullableLong()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult(12.5M, null, CultureInfo.InvariantCulture);

            // Act
            object outValue = vpr.ConvertTo(typeof(long?));

            // Assert
            Assert.Equal(12L, outValue);
        }
        public void ConvertToReturnsValueIfArrayElementIsStringKeyAndDestinationTypeIsEnum()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult(new object[] { "Value1" }, null, CultureInfo.InvariantCulture);

            // Act
            object outValue = vpr.ConvertTo(typeof(MyEnum));

            // Assert
            Assert.Equal(outValue, MyEnum.Value1);
        }
        public void ConvertToReturnsValueIfElementIsStringAndDestionationIsNullableDouble()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult("12.5", null, CultureInfo.InvariantCulture);

            // Act
            object outValue = vpr.ConvertTo(typeof(double?));

            // Assert
            Assert.Equal(12.5, outValue);
        }
        public void ConvertToReturnsNullIfTrimmedValueIsEmptyString()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult(" \t \r\n ", null, CultureInfo.InvariantCulture);

            // Act
            object outValue = vpr.ConvertTo(typeof(int));

            // Assert
            Assert.Null(outValue);
        }
        public void ConvertToReturnsNullIfValueIsNull()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult(null /* rawValue */, null /* attemptedValue */, CultureInfo.InvariantCulture);

            // Act
            object outValue = vpr.ConvertTo(typeof(int[]));

            // Assert
            Assert.Null(outValue);
        }
        public bool TryGetValue(out ValueProviderResult value)
        {
			return ((value = GetValue()) != null);
        }
        public void ConvertToReturnsNullIfTryingToConvertEmptyArrayToSingleElement()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult(new int[0], "", CultureInfo.InvariantCulture);

            // Act
            object outValue = vpr.ConvertTo(typeof(int));

            // Assert
            Assert.Null(outValue);
        }