/// <summary>
		/// Validates the specified value with respect to the current validation attribute.
		/// </summary>
		/// <param name="value">
		/// The value to validate.
		/// </param>
		/// <param name="validationContext">
		/// The context information about the validation operation.
		/// </param>
		/// <returns>
		/// An instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult"/> class.
		/// </returns>
		protected override ValidationResult PerformCustomValidation(object value, ValidationContext validationContext)
		{
			if (value.IsNull())
			{
				return ValidationResult.Success;
			}

			if (validationContext.IsNull())
			{
				validationContext = new ValidationContext(value, null, null) { DisplayName = "The value" };
			}

			var memberNames = new[] { validationContext.MemberName };

			int length = value.ToString().Length;

			if (length > this.maximumLength)
			{
				this.ErrorMessage = string.Format(ValidationMessages.ValueGreaterThanMaximumLength, validationContext.DisplayName, this.maximumLength);

				return new ValidationResult(this.ErrorMessage, memberNames);
			}

			return ValidationResult.Success;
		}
Пример #2
0
        /// <summary>
        /// The overrided Server Validation method.
        /// </summary>
        public ValidationResult IsValidCoords(MakeRouteViewModel makerouteVieModel)
        {
            var jsonObj = makerouteVieModel; // cast the object to type MakeRouteViewModel

            /// Coordinates of the boundary of Dnepropetrovsk
            var polyCoords = new
            {
                SWLong = GeneralSettings.GetSouthWestLongitude,
                SWLat = GeneralSettings.GetSouthWestLatitude,
                NELong = GeneralSettings.GetNorthEastLongitude,
                NELat = GeneralSettings.GetNorthEastLatitude
            };

            double startPointLon;
            double startPointLat;
            double endPointLon;
            double endPointLat;

            // Convert the the Latitudes and Longitudes to type of double
            bool convertFlg = (double.TryParse(jsonObj.StartPointLongitude, out startPointLon)
            & double.TryParse(jsonObj.StartPointLatitude, out startPointLat)
            & double.TryParse(jsonObj.EndPointLongitude, out endPointLon)
            & double.TryParse(jsonObj.EndPointLatitude, out endPointLat));

            /// Verify that the Point A and Point B are in the boundries of Dnepropetrovsk
            if (convertFlg == true
            && startPointLon >= polyCoords.SWLong
            && startPointLon <= polyCoords.NELong
            && startPointLat <= polyCoords.NELat
            && startPointLat >= polyCoords.SWLat
            && endPointLon >= polyCoords.SWLong
            && endPointLon <= polyCoords.NELong
            && endPointLat <= polyCoords.NELat
            && endPointLat >= polyCoords.SWLat)
                return ValidationResult.Success;
            else
            {
                return new ValidationResult(Resources.Resources.ValidationCoords);
            }
        }
        public override bool IsValid(object value)
        {
            var file = value as HttpPostedFileBase;
            if (file != null)
            {
                var fileExtension = System.IO.Path.GetExtension(file.FileName);

                var imgExtList = new[] { ".jpg", ".jpeg", ".png", ".bmp", ".gif" };

                if (!imgExtList.Contains(fileExtension.ToLower()))
                {
                    return false;
                }

                if (file.ContentLength > 1 * 3048 * 3048)
                {
                    return false;
                }
            }

            return true;
        }
        public void BindModel_Performs_ValidationOnArrays()
        {
            // Arrange
            TypeMatchModelBinder binder = new TypeMatchModelBinder();
            HttpActionContext actionContext = new HttpActionContext
            {
                ControllerContext = new HttpControllerContext { Configuration = new HttpConfiguration() }
            };

            Customer[] model = new[] { new Customer { Age = 99999 } };
            ModelBindingContext bindingContext = GetBindingContext(typeof(Customer[]));
            bindingContext.ValueProvider = new SimpleHttpValueProvider
            {
                { "theModelName", model }
            };
            bindingContext.ModelState = actionContext.ModelState;

            // Act
            bool retVal = binder.BindModel(actionContext, bindingContext);

            // Assert
            Assert.True(retVal);
            Assert.Same(model, bindingContext.Model);
            Assert.True(actionContext.ModelState.ContainsKey("theModelName"));
            Assert.False(actionContext.ModelState.IsValid);
            Assert.Equal("The field Age must be between 0 and 100.", actionContext.ModelState["theModelName[0].Age"].Errors[0].ErrorMessage);
        }
            internal static object ConvertTo(string valueString, Type type)
            {
                if (valueString == null)
                {
                    return null;
                }

                // TODO 1668: ODL beta1's ODataUriUtils.ConvertFromUriLiteral does not support converting uri literal
                // to ODataEnumValue, but beta1's ODataUriUtils.ConvertToUriLiteral supports converting ODataEnumValue
                // to uri literal.
                if (TypeHelper.IsEnum(type))
                {
                    string[] values = valueString.Split(new[] { '\'' }, StringSplitOptions.None);
                    if (values.Length == 3 && String.IsNullOrEmpty(values[2]))
                    {
                        // Remove the type name if the enum value is a fully qualified literal.
                        valueString = values[1];
                    }

                    Type enumType = TypeHelper.GetUnderlyingTypeOrSelf(type);
                    object[] parameters = new[] { valueString, Enum.ToObject(type, 0) };
                    bool isSuccessful = (bool)enumTryParseMethod.MakeGenericMethod(enumType).Invoke(null, parameters);

                    if (!isSuccessful)
                    {
                        throw Error.InvalidOperation(SRResources.ModelBinderUtil_ValueCannotBeEnum, valueString, type.Name);
                    }

                    return parameters[1];
                }

                object value = ODataUriUtils.ConvertFromUriLiteral(valueString, ODataVersion.V4);

                bool isNonStandardEdmPrimitive;
                EdmLibHelpers.IsNonstandardEdmPrimitive(type, out isNonStandardEdmPrimitive);

                if (isNonStandardEdmPrimitive)
                {
                    return EdmPrimitiveHelpers.ConvertPrimitiveValue(value, type);
                }
                else
                {
                    type = Nullable.GetUnderlyingType(type) ?? type;
                    return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
                }
            }
        public void Should_not_split_single_word_property_name()
        {
            var model = new { Name = "Hello World!" };
            var provider = new ConventionalDataAnnotationsModelMetadataProvider();

            var metadata = provider.GetMetadataForProperty(() => model, model.GetType(), "Name");

            Assert.Equal("Name", metadata.DisplayName);
        }
        public void InputHelpersUseCurrentCultureToConvertValueParameter()
        {
            // Arrange
            DateTime dt = new DateTime(1900, 1, 1, 0, 0, 0);
            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary { { "foo", dt } });

            var tests = new[]
            {
                // Hidden(name)
                new
                {
                    Html = @"<input id=""foo"" name=""foo"" type=""hidden"" value=""01/01/1900 00:00:00"" />",
                    Action = new Func<MvcHtmlString>(() => helper.Hidden("foo"))
                },
                // Hidden(name, value)
                new
                {
                    Html = @"<input id=""foo"" name=""foo"" type=""hidden"" value=""01/01/1900 00:00:00"" />",
                    Action = new Func<MvcHtmlString>(() => helper.Hidden("foo", dt))
                },
                // Hidden(name, value, htmlAttributes)
                new
                {
                    Html = @"<input id=""foo"" name=""foo"" type=""hidden"" value=""01/01/1900 00:00:00"" />",
                    Action = new Func<MvcHtmlString>(() => helper.Hidden("foo", dt, null))
                },
                // Hidden(name, value, htmlAttributes)
                new
                {
                    Html = @"<input id=""foo"" name=""foo"" type=""hidden"" value=""01/01/1900 00:00:00"" />",
                    Action = new Func<MvcHtmlString>(() => helper.Hidden("foo", dt, new RouteValueDictionary()))
                },
                // RadioButton(name, value)
                new
                {
                    Html = @"<input checked=""checked"" id=""foo"" name=""foo"" type=""radio"" value=""01/01/1900 00:00:00"" />",
                    Action = new Func<MvcHtmlString>(() => helper.RadioButton("foo", dt))
                },
                // RadioButton(name, value, isChecked)
                new
                {
                    Html = @"<input id=""foo"" name=""foo"" type=""radio"" value=""01/01/1900 00:00:00"" />",
                    Action = new Func<MvcHtmlString>(() => helper.RadioButton("foo", dt, false))
                },
                // RadioButton(name, value, htmlAttributes)
                new
                {
                    Html = @"<input checked=""checked"" id=""foo"" name=""foo"" type=""radio"" value=""01/01/1900 00:00:00"" />",
                    Action = new Func<MvcHtmlString>(() => helper.RadioButton("foo", dt, null))
                },
                // RadioButton(name, value)
                new
                {
                    Html = @"<input checked=""checked"" id=""foo"" name=""foo"" type=""radio"" value=""01/01/1900 00:00:00"" />",
                    Action = new Func<MvcHtmlString>(() => helper.RadioButton("foo", dt, new RouteValueDictionary()))
                },
                // RadioButton(name, value, isChecked, htmlAttributes)
                new
                {
                    Html = @"<input id=""foo"" name=""foo"" type=""radio"" value=""01/01/1900 00:00:00"" />",
                    Action = new Func<MvcHtmlString>(() => helper.RadioButton("foo", dt, false, null))
                },
                // RadioButton(name, value, isChecked, htmlAttributes)
                new
                {
                    Html = @"<input id=""foo"" name=""foo"" type=""radio"" value=""01/01/1900 00:00:00"" />",
                    Action = new Func<MvcHtmlString>(() => helper.RadioButton("foo", dt, false, new RouteValueDictionary()))
                },
                // TextBox(name)
                new
                {
                    Html = @"<input id=""foo"" name=""foo"" type=""text"" value=""01/01/1900 00:00:00"" />",
                    Action = new Func<MvcHtmlString>(() => helper.TextBox("foo"))
                },
                // TextBox(name, value)
                new
                {
                    Html = @"<input id=""foo"" name=""foo"" type=""text"" value=""01/01/1900 00:00:00"" />",
                    Action = new Func<MvcHtmlString>(() => helper.TextBox("foo", dt))
                },
                // TextBox(name, value, hmtlAttributes)
                new
                {
                    Html = @"<input id=""foo"" name=""foo"" type=""text"" value=""01/01/1900 00:00:00"" />",
                    Action = new Func<MvcHtmlString>(() => helper.TextBox("foo", dt, (object)null))
                },
                // TextBox(name, value, hmtlAttributes)
                new
                {
                    Html = @"<input id=""foo"" name=""foo"" type=""text"" value=""01/01/1900 00:00:00"" />",
                    Action = new Func<MvcHtmlString>(() => helper.TextBox("foo", dt, new RouteValueDictionary()))
                }
            };

            // Act && Assert
            foreach (var test in tests)
            {
                Assert.Equal(test.Html, test.Action().ToHtmlString());
            }
        }
        public void TextBoxHelpersFormatValue()
        {
            // Arrange
            DateTime dt = new DateTime(1900, 1, 1, 0, 0, 0);
            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary { { "viewDataDate", dt } });

            ViewDataDictionary<DateModel> viewData = new ViewDataDictionary<DateModel>() { Model = new DateModel { date = dt } };
            HtmlHelper<DateModel> dateModelhelper = MvcHelper.GetHtmlHelper(viewData);

            var tests = new[]
            {
                // TextBox(name, value, format)
                new
                {
                    Html = @"<input id=""viewDataDate"" name=""viewDataDate"" type=""text"" value=""-01/01/1900 00:00:00-"" />",
                    Action = new Func<MvcHtmlString>(() => helper.TextBox("viewDataDate", null, "-{0}-"))
                },
                // TextBox(name, value, format)
                new
                {
                    Html = @"<input id=""date"" name=""date"" type=""text"" value=""-01/01/1900 00:00:00-"" />",
                    Action = new Func<MvcHtmlString>(() => helper.TextBox("date", dt, "-{0}-"))
                },
                // TextBox(name, value, format, hmtlAttributes)
                new
                {
                    Html = @"<input id=""date"" name=""date"" type=""text"" value=""-01/01/1900 00:00:00-"" />",
                    Action = new Func<MvcHtmlString>(() => helper.TextBox("date", dt, "-{0}-", (object)null))
                },
                // TextBox(name, value, format, hmtlAttributes)
                new
                {
                    Html = @"<input id=""date"" name=""date"" type=""text"" value=""-01/01/1900 00:00:00-"" />",
                    Action = new Func<MvcHtmlString>(() => helper.TextBox("date", dt, "-{0}-", new RouteValueDictionary()))
                },
                // TextBoxFor(expression, format)
                new
                {
                    Html = @"<input id=""date"" name=""date"" type=""text"" value=""-01/01/1900 00:00:00-"" />",
                    Action = new Func<MvcHtmlString>(() => dateModelhelper.TextBoxFor(m => m.date, "-{0}-"))
                },
                // TextBoxFor(expression, format, hmtlAttributes)
                new
                {
                    Html = @"<input id=""date"" name=""date"" type=""text"" value=""-01/01/1900 00:00:00-"" />",
                    Action = new Func<MvcHtmlString>(() => dateModelhelper.TextBoxFor(m => m.date, "-{0}-", (object)null))
                },
                // TextBoxFor(expression, format, hmtlAttributes)
                new
                {
                    Html = @"<input id=""date"" name=""date"" type=""text"" value=""-01/01/1900 00:00:00-"" />",
                    Action = new Func<MvcHtmlString>(() => dateModelhelper.TextBoxFor(m => m.date, "-{0}-", new RouteValueDictionary()))
                }
            };

            // Act && Assert
            foreach (var test in tests)
            {
                Assert.Equal(test.Html, test.Action().ToHtmlString());
            }
        }
Пример #9
0
        public IEnumerable<da.ValidationResult> Validate(da.ValidationContext validationContext)
        {
            var validator = new ForecastValidator(this);
            var result = validator.Validate(this);

            return result.Errors.Select(error => 
                new da.ValidationResult(PrependProcessStatusToString(error.ErrorMessage, ProcessStatus.Warning), 
                    new [] { error.PropertyName }));
        }
 public void Assemblies_can_be_called_from_multiple_threads_concurrently()
 {
     var expectedAssemblies = new[] { typeof(PregenContextEdmxViews).Assembly };
     var cache = new ViewAssemblyCache();
     cache.CheckAssembly(typeof(PregenContextEdmxViews).Assembly, followReferences: true);
     ExecuteInParallel(() => Assert.Equal(expectedAssemblies, cache.Assemblies));
 }