Example #1
0
        public static DateTime ParseDate(ValueProviderResult value)
        {
            // Create an array of all supported standard date and time format specifiers.
            string[] formats = {"d", "D", "f", "F", "g", "G", "m", "o", "r",
                          "s", "t", "T", "u", "U", "Y", "dd/MM/yyyy hh:mm:ss", "MM/dd/yyyy hh:mm:ss"};

            //
            CultureInfo[] cultures = {CultureInfo.CreateSpecificCulture("de-DE"),
                                CultureInfo.CreateSpecificCulture("en-US"),
                                CultureInfo.CreateSpecificCulture("he-IL"),
                                CultureInfo.CreateSpecificCulture("es-ES"),
                                CultureInfo.CreateSpecificCulture("fr-FR")};

            var parsedSuccesfuly = false;
            int cultureIndex = 0;
            DateTime foundDateTime = DateTime.MinValue;
            while (!parsedSuccesfuly && cultureIndex < cultures.Length)
            {
                parsedSuccesfuly = DateTime.TryParseExact(value.AttemptedValue, formats, cultures[cultureIndex], DateTimeStyles.None, out foundDateTime);
                cultureIndex++;
            }

            if (parsedSuccesfuly)
            {
                return foundDateTime;
            }
            throw new FormatException("Could not parse the specified date, culture is not supported");
        }
Example #2
0
 internal static object GetModelValue(ValueProviderResult result, Type memberType)
 {
     var memberMapping = ModelMappingManager.MappingFor(memberType);
     var descriptor = new ModelDescriptor(memberMapping);
     var value = result.ConvertTo(descriptor.KeyProperty.PropertyType);
     return memberMapping.Configuration.Repository().Find(value);
 }
Example #3
0
 public ValueProviderResult GetValue(string key)
 {
     ValueProviderResult result;
     result = new ValueProviderResult(data,
         "Id", CultureInfo.CurrentCulture);
     return result;
 }
 protected virtual ValueProviderResult GetValue(string key)
 {
     ValueProviderResult res = null;
     string val = this._context.HttpContext.Request.Form[key.Replace('.', '[')+']'] as string;
     if (val != null)
         res = new ValueProviderResult(val, val, CultureInfo.CurrentCulture);
     return res;
 }
 /// <summary>
 /// </summary>
 /// <param name="result"></param>
 /// <param name="sessionWrapper"></param>
 /// <exception cref="ArgumentNullException"></exception>
 public NHValueProviderResult(ValueProviderResult result, SessionWrapper sessionWrapper)
 {
     _result = result;
     _sessionWrapper = sessionWrapper;
     AttemptedValue = result.AttemptedValue;
     Culture = result.Culture;
     RawValue = result.RawValue;
 }
Example #6
0
 private void SetModelState(ModelBindingContext bindingContext, ValueProviderResult valueProviderResult)
 {
     ModelState modelState;
     if (!bindingContext.ModelState.TryGetValue(bindingContext.ModelName, out modelState))
     {
         bindingContext.ModelState.Add(bindingContext.ModelName, modelState = new ModelState());
     }
     modelState.Value = valueProviderResult;
 }
        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.AreEqual("1", converted);
        }
        public ValueProviderResult GetValue(string key)
        {
            ValueProviderResult result=null;
            if (this.dictionary.ContainsKey(key))
            {
                result = new ValueProviderResult(this.dictionary[key],
                this.dictionary[key], CultureInfo.CurrentCulture);
            }

            return result;
        }
Example #9
0
        /// <summary>
        /// Creates the list of ministries selected by the system users
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        private static List<MinistryModel> BindMinistryModels(ValueProviderResult result)
        {
            var rawValue = result.RawValue as string[];
            if (rawValue == null || rawValue.Length == 0)
            {
                return null;
            }

            List<MinistryModel> models = ManageMinistryModelHelper.GetMinistryModels(rawValue);
            return models;
        }
        public void ConvertToCanConvertSingleElementsToSingleElements() {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult(42, "", CultureInfo.InvariantCulture);

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

            // Assert
            Assert.IsNotNull(converted);
            Assert.AreEqual("42", converted);
        }
        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.AreEqual(returned.Value, "someValue (fr-FR)");
        }
Example #12
0
        private static string BindStartEndTime(ValueProviderResult result)
        {
            var rawValue = result.RawValue as string;
            if (string.IsNullOrEmpty(rawValue))
            {
                return null;
            }

            // Is time valid?
            Convert.ToDateTime(string.Format("1/1/2012 {0}", rawValue));

            return rawValue.Trim();
        }
        public void GetValue_should_not_throw_exception_when_try_to_convert_value_from_ModelState()
        {
            result = new ValueProviderResult("11/22/2000", "11/22/2000", new CultureInfo("en-US"));
            state = new ModelState();
            state.Value = result;

            viewContext.ViewData.ModelState.Remove("DatePicker1");
            viewContext.ViewData.ModelState.Add("DatePicker1", state);

            System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");

            Assert.DoesNotThrow(() => datepicker.GetValue(o => (DateTime?)o));
        }
        public InputComponentExtensionsTests()
        {
            viewContext = TestHelper.CreateViewContext();
            datepicker = DatePickerTestHelper.CreateDatePicker(null, viewContext);
            datepicker.Name = "DatePicker1";

            result = new ValueProviderResult("s", "s", System.Threading.Thread.CurrentThread.CurrentCulture);
            state = new ModelState();
            state.Value = result;

            viewContext.ViewData.ModelState.Add("DatePicker1", state);
            currentCulture = CultureInfo.CurrentCulture;
        }
 public static bool TryGetValue(this IValueProvider valueProvider, string key, out ValueProviderResult result)
 {
     try
     {
         result = valueProvider.GetValue(key);
         return true;
     }
     catch
     {
         result = null;
         return false;
     }
 }
Example #16
0
        internal static object GetNonModelValue(ValueProviderResult result, Type memberType)
        {
            var innerType = Nullable.GetUnderlyingType(memberType) ?? memberType;

            if (innerType.IsEnum)
                return Enum.Parse(innerType, result.AttemptedValue);

            var value = innerType == typeof(Boolean)
                            ? result.AttemptedValue.Split(',')[0]
                            : result.AttemptedValue;

            return TypeDescriptor.GetConverter(innerType).ConvertFrom(null, CultureInfo.CurrentCulture, value);
        }
        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
        {
            bool isValidName = false;
            string keyValue = string.Format("{0}:{1}", Name, Argument);
            var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
            if (value != null) {
                value = new ValueProviderResult(Argument, Argument, null);
                controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
                isValidName = true;
            }

            return isValidName;
        }
        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.AreSame(rawValue, result.RawValue);
            Assert.AreSame(attemptedValue, result.AttemptedValue);
            Assert.AreSame(culture, result.Culture);
        }
Example #19
0
        public IDictionary<string, ValueProviderResult> ToValueProvider() {
            CultureInfo currentCulture = CultureInfo.CurrentCulture;

            Dictionary<string, ValueProviderResult> dict = new Dictionary<string, ValueProviderResult>(StringComparer.OrdinalIgnoreCase);
            string[] keys = AllKeys;
            foreach (string key in keys) {
                string[] rawValue = GetValues(key);
                string attemptedValue = this[key];
                ValueProviderResult vpResult = new ValueProviderResult(rawValue, attemptedValue, currentCulture);
                dict[key] = vpResult;
            }

            return dict;
        }
        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.IsNotNull(converted);
            Assert.AreEqual(3, converted.Length);
            Assert.AreEqual("1", converted[0]);
            Assert.AreEqual("20", converted[1]);
            Assert.AreEqual("42", converted[2]);
        }
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResultHours = bindingContext.ValueProvider
                                           .GetValue(bindingContext.ModelName + ".Hours");
            ValueProviderResult valueResultMinutes = bindingContext.ValueProvider
               .GetValue(bindingContext.ModelName + ".Minutes");
            ValueProviderResult valueResultSeconds = bindingContext.ValueProvider
               .GetValue(bindingContext.ModelName + ".Seconds");

            if (valueResultHours != null || valueResultMinutes != null | valueResultSeconds != null)
            {
                int hours = 0;
                int minutes = 0;
                int seconds = 0;
                TimeSpan? actualValue = null;
                var valueResult = new ValueProviderResult(null, string.Empty, System.Globalization.CultureInfo.CurrentCulture);
                
                var modelState = new ModelState { Value = valueResult };
                try
                {
                    if (valueResultHours != null)
                    {
                        hours = int.Parse(valueResultHours.AttemptedValue);
                    }

                    if (valueResultMinutes != null)
                    {
                        minutes = int.Parse(valueResultMinutes.AttemptedValue);
                    }

                    if (valueResultSeconds != null)
                    {
                        seconds = int.Parse(valueResultSeconds.AttemptedValue);
                    }
                    actualValue = new TimeSpan(hours, minutes, seconds);                    
                }
                catch (FormatException e)
                {
                    modelState.Errors.Add(e);
                }

                bindingContext.ModelState.Add(bindingContext.ModelName, modelState);

                return actualValue;
            }
            else
            {
                return base.BindModel(controllerContext, bindingContext);
            }
        }
Example #22
0
        private static bool? GetBooleanValue(ValueProviderResult valueProviderResult)
        {
            string attemptedValue = ((valueProviderResult != null) ? valueProviderResult.AttemptedValue : null)
                                    ?? string.Empty;

            switch (attemptedValue)
            {
                case "0":
                    return false;
                case "1":
                    return true;
                default:
                    return null;
            }
        }
        private void AddValues(NameValueCollection collection, CultureInfo culture) {
            if (collection.Count > 0) {
                _prefixes.Add("");
            }

            foreach (string key in collection) {
                if (key != null) {
                    _prefixes.UnionWith(ValueProviderUtil.GetPrefixes(key));

                    string[] rawValue = collection.GetValues(key);
                    string attemptedValue = collection[key];
                    _values[key] = new ValueProviderResult(rawValue, attemptedValue, culture);
                }
            }
        }
            protected void HandleHttpRequestValidationException(System.Web.Mvc.ModelBindingContext bindingContext, HttpRequestValidationException ex)
            {
                var valueProviderCollection = bindingContext.ValueProvider as System.Web.Mvc.ValueProviderCollection;

                if (valueProviderCollection != null)
                {
                    System.Web.Mvc.ValueProviderResult valueProviderResult = valueProviderCollection.GetValue(bindingContext.ModelName, skipValidation: true);
                    bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
                }

                string errorMessage = string.Format(CultureInfo.CurrentCulture, "{0} contém caracteres inválidos: <, & ou >",
                                                    bindingContext.ModelMetadata.DisplayName);

                bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorMessage);
            }
Example #25
0
        public IDictionary<string, ValueProviderResult> ToValueProvider()
        {
            var currentCulture = CultureInfo.CurrentCulture;
            var dictionary = new Dictionary<string, ValueProviderResult>(StringComparer.OrdinalIgnoreCase);

            foreach (var str in this.AllKeys)
            {
                var values = this.GetValues(str);
                var attemptedValue = base[str];
                var result = new ValueProviderResult(values, attemptedValue, currentCulture);

                dictionary[str] = result;
            }

            return dictionary;
        }
        /// <summary>
        /// Vyparsuje dateTime vo formate ISO 8601
        /// </summary>
        /// <param name="value">Hodnota ktoru chceme parsovat</param>
        /// <returns>DateTime alebo null</returns>
        private Decimal? parseDecimal(ValueProviderResult value)
        {
            NumberFormatInfo numberFormatInfo = new NumberFormatInfo();
            numberFormatInfo.NumberDecimalDigits = 2;
            numberFormatInfo.NumberDecimalSeparator = ".";
            Decimal decimalValue = 0;

            if (Decimal.TryParse(value.AttemptedValue.Replace(",", "."), NumberStyles.Any, numberFormatInfo, out decimalValue))
            {
                return decimalValue;
            }
            else
            {
                return null;
            }
        }
Example #27
0
        private TableRequest GetPropertyValues(TableRequest request, ValueProviderResult filtersValueResult)
        {
            var filters = (string)filtersValueResult.ConvertTo(typeof(string));
            var appliedFilters = JObject.Parse(filters);
            var tokens = appliedFilters.Children();

            var Name = "";
            var Surname = "";
            var Role = Roles.All;
            int? Id = null;
            var index = 0;

            foreach (var token in tokens)
            {
                if (index != 0)
                {
                    for (var j = 0; j < token.First.Count(); j++)
                    {
                        var currentToken = token.First[j];
                        if (currentToken.Value<string>("field").Equals("Name"))
                        {
                            Name = currentToken["data"].ToString().Trim();
                        }
                        if (currentToken.Value<string>("field").Equals("Surname"))
                        {
                            Surname = currentToken["data"].ToString().Trim();
                        }
                        if (currentToken.Value<string>("field").Equals("Position"))
                        {
                            Role = (Roles)(Enum.Parse(typeof(Roles), currentToken["data"].ToString().Trim()));
                        }
                        if (currentToken.Value<string>("field").Equals("Id"))
                        {
                            Id = Convert.ToInt32(currentToken["data"].ToString().Trim());
                        }
                    }
                }
                index++;
            }

            request.Name = Name.Trim();
            request.Surname = Surname.Trim();
            request.Role = Role;
            request.Id = Id;

            return request;
        }
        private void AddValues(HttpSessionStateBase session)
        {
            if (session.Keys.Count > 0)
            {
            _prefixes.Add("");
            }

            foreach (string key in session.Keys)
            {
            if (key != null)
            {
            _prefixes.Add(key);

            object rawValue = session[key];
            string attemptedValue = session[key].ToString();
            _values[key] = new ValueProviderResult(
                rawValue,
                attemptedValue,
                CultureInfo.CurrentCulture);
            }
            }
        }
        /// <summary>
        /// Binds the model by using the specified controller context and binding context.
        /// </summary>
        /// <param name="controllerContext">The context within which the controller operates. The context information includes the controller, HTTP content, request context, and route data.</param>
        /// <param name="bindingContext">The context within which the model is bound. The context includes information such as the model object, model name, model type, property filter, and value provider.</param>
        /// <returns>The bound object.</returns>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="bindingContext " />parameter is null.</exception>
        public object BindModel( ControllerContext controllerContext, ModelBindingContext bindingContext )
        {
            if( bindingContext == null )
            {
                throw new ArgumentNullException( "bindingContext" );
            }

            string checkBoxListKey = string.Format( "{0}.{1}", bindingContext.ModelName, CheckBoxListItemExtensions.CheckBoxListHiddenName );
            ValueProviderResult isCheckBoxListResult = bindingContext.ValueProvider.GetValue( checkBoxListKey );
            if( isCheckBoxListResult != null )
            {
                if( bindingContext.ValueProvider.GetValue( bindingContext.ModelName ) == null )
                {
                    var emptyValueResult = new ValueProviderResult( new string[] { }, string.Empty, isCheckBoxListResult.Culture );
                    bindingContext.ModelState.SetModelValue( bindingContext.ModelName, emptyValueResult );

                    return null;
                }
            }

            return System.Web.Mvc.ModelBinders.Binders.DefaultBinder.BindModel( controllerContext, bindingContext );
        }
        public virtual object BindModel(
            ControllerContext controllerContext,
            ModelBindingContext bindingContext
            )
        {
            RuntimeHelpers.EnsureSufficientExecutionStack();

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

            bool performedFallback = false;

            if (
                !String.IsNullOrEmpty(bindingContext.ModelName) &&
                !bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName)
                )
            {
                // We couldn't find any entry that began with the prefix. If this is the top-level element, fall back
                // to the empty prefix.
                if (bindingContext.FallbackToEmptyPrefix)
                {
                    bindingContext = new ModelBindingContext()
                    {
                        ModelMetadata  = bindingContext.ModelMetadata,
                        ModelState     = bindingContext.ModelState,
                        PropertyFilter = bindingContext.PropertyFilter,
                        ValueProvider  = bindingContext.ValueProvider
                    };
                    performedFallback = true;
                }
                else
                {
                    return(null);
                }
            }

            // Simple model = int, string, etc.; determined by calling TypeConverter.CanConvertFrom(typeof(string))
            // or by seeing if a value in the request exactly matches the name of the model we're binding.
            // Complex type = everything else.
            if (!performedFallback)
            {
                bool performRequestValidation = ShouldPerformRequestValidation(
                    controllerContext,
                    bindingContext
                    );
                ValueProviderResult valueProviderResult =
                    bindingContext.UnvalidatedValueProvider.GetValue(
                        bindingContext.ModelName,
                        skipValidation: !performRequestValidation
                        );
                if (valueProviderResult != null)
                {
                    return(BindSimpleModel(controllerContext, bindingContext, valueProviderResult));
                }
            }
            if (!bindingContext.ModelMetadata.IsComplexType)
            {
                return(null);
            }

            return(BindComplexModel(controllerContext, bindingContext));
        }
Example #31
0
 public void SetModelValue(string key, ValueProviderResult value)
 {
     GetModelStateForKey(key).Value = value;
 }
 private static object ConvertProviderResult(ModelStateDictionary modelState, string modelStateKey, ValueProviderResult valueProviderResult, Type destinationType)
 {
     try
     {
         object convertedValue = valueProviderResult.ConvertTo(destinationType);
         return(convertedValue);
     }
     catch (Exception ex)
     {
         modelState.AddModelError(modelStateKey, ex);
         return(null);
     }
 }
        internal object BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult)
        {
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

            // if the value provider returns an instance of the requested data type, we can just short-circuit
            // the evaluation and return that instance
            if (bindingContext.ModelType.IsInstanceOfType(valueProviderResult.RawValue))
            {
                return(valueProviderResult.RawValue);
            }

            // since a string is an IEnumerable<char>, we want it to skip the two checks immediately following
            if (bindingContext.ModelType != typeof(string))
            {
                // conversion results in 3 cases, as below
                if (bindingContext.ModelType.IsArray)
                {
                    // case 1: user asked for an array
                    // ValueProviderResult.ConvertTo() understands array types, so pass in the array type directly
                    object modelArray = ConvertProviderResult(bindingContext.ModelState, bindingContext.ModelName, valueProviderResult, bindingContext.ModelType);
                    return(modelArray);
                }

                Type enumerableType = TypeHelpers.ExtractGenericInterface(bindingContext.ModelType, typeof(IEnumerable <>));
                if (enumerableType != null)
                {
                    // case 2: user asked for a collection rather than an array
                    // need to call ConvertTo() on the array type, then copy the array to the collection
                    object modelCollection = CreateModel(controllerContext, bindingContext, bindingContext.ModelType);
                    Type   elementType     = enumerableType.GetGenericArguments()[0];
                    Type   arrayType       = elementType.MakeArrayType();
                    object modelArray      = ConvertProviderResult(bindingContext.ModelState, bindingContext.ModelName, valueProviderResult, arrayType);

                    Type collectionType = typeof(ICollection <>).MakeGenericType(elementType);
                    if (collectionType.IsInstanceOfType(modelCollection))
                    {
                        CollectionHelpers.ReplaceCollection(elementType, modelCollection, modelArray);
                    }
                    return(modelCollection);
                }
            }

            // case 3: user asked for an individual element
            object model = ConvertProviderResult(bindingContext.ModelState, bindingContext.ModelName, valueProviderResult, bindingContext.ModelType);

            return(model);
        }
        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.AreEqual(returned, "someValue (en-US)");
        }
        public void CulturePropertyDefaultsToInvariantCulture() {
            // Arrange
            ValueProviderResult result = new ValueProviderResult(null, null, null);

            // Act & assert
            Assert.AreSame(CultureInfo.InvariantCulture, result.Culture);
        }