public DataAnnotationsModelMetadata(DataAnnotationsModelMetadataProvider provider, Type containerType,
                                     Func<object> modelAccessor, Type modelType, string propertyName,
                                     DisplayColumnAttribute displayColumnAttribute)
     : base(provider, containerType, modelAccessor, modelType, propertyName)
 {
     _displayColumnAttribute = displayColumnAttribute;
 }
 public DataAnnotationsModelMetadata(DataAnnotationsModelMetadataProvider provider, Type containerType,
                                     Func <object> modelAccessor, Type modelType, string propertyName,
                                     DisplayColumnAttribute displayColumnAttribute)
     : base(provider, containerType, modelAccessor, modelType, propertyName)
 {
     _displayColumnAttribute = displayColumnAttribute;
 }
Example #3
0
        public virtual ActionResult PropertyItemHtml(object data, string propertyPath, int depth, string pathPrefix)
        {
            ViewData["propertyPath"] = (pathPrefix ?? "") + propertyPath;
            ViewData["addDepth"] = depth - 1;
            string parentPath = propertyPath.Contains(".") ? propertyPath.UpToLast(".") : "";
            string propertyName = (propertyPath.Contains(".") ? propertyPath.LastAfter(".") : propertyPath).UpTo("[");
            Type parentType = ReflectionX.GetPropertyTypeByPath(data.GetType(), parentPath);
            IList list = ReflectionX.GetPropertyValueByPath(data, propertyPath, true) as IList;
            var listProp = ReflectionX.GetPropertyByPath(data.GetType(), propertyPath);
            Type listType = listProp.PropertyType;
            if (listType.GetType().IsArray)
            {
                list = (IList)Array.CreateInstance(ReflectionX.ElementType(listType), 1);
                list[0] = CreateInstance(listType.GetElementType());
            }
            else
            {
                list = (IList)Activator.CreateInstance(listType);
                list.Add(CreateInstance(ReflectionX.ElementType(listType)));
            }

            ViewData["list"] = list;
            var metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForProperty(null, parentType, propertyName);
            ViewData["CollectionAdditionalValues"] = metadata.AdditionalValues;

            RouteData.DataTokens.Add("CancelProcessingHtml", true);
            return PartialView(ConfigHelper.GetViewPath("LyniconPropertyItem.cshtml"), data);
        }
        public void GetValidators_ReturnsNumericValidator()
        {
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForProperty(null, typeof(ProviderModel), "Numeric");

            IEnumerable<Type> actual = provider.GetValidators(metadata, new ControllerContext()).Select(validator => validator.GetType());
            IEnumerable<Type> expected = new[] { typeof(NumberValidator) };

            Assert.Equal(expected, actual);
        }
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var provider = new DataAnnotationsModelMetadataProvider();
            OtherPropertyDisplayName = provider.GetMetadataForProperty(() => null, metadata.ContainerType, OtherProperty).DisplayName;

            var errorMessage = FormatErrorMessage(metadata.GetDisplayName());
            var typeName = metadata.DataTypeName ?? metadata.ModelType.Name;

            yield return new ModelClientValidationCompareValuesRule(OtherProperty, typeName, Operator, errorMessage);
        }
        public void ValidatbleObjectAdapter()
        {
            var model = new TestModel();
            var k = new DataAnnotationsModelMetadataProvider();
            var metadata = k.GetMetadataForType(() => model, model.GetType());
            var controllerContext = new ControllerContext();
            var adapter = new MvcContrib.Localization.ValidatableObjectAdapter(metadata, controllerContext);

            var result = adapter.Validate(model).ToList();
            Assert.AreNotEqual(0, result.Count);
        }
        public void RequiredAdapter_SetsErrorMessage()
        {
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider()
                .GetMetadataForProperty(null, typeof(AdaptersModel), "Required");
            RequiredAttribute attribute = new RequiredAttribute();
            new RequiredAdapter(metadata, new ControllerContext(), attribute);

            String expected = Validations.FieldIsRequired;
            String actual = attribute.ErrorMessage;

            Assert.Equal(expected, actual);
        }
        public void GetClientValidationRules_ReturnsDigitsValidationRule()
        {
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForProperty(null, typeof(AdaptersModel), "Digits");
            DigitsAdapter adapter = new DigitsAdapter(metadata, new ControllerContext(), new DigitsAttribute());

            String expectedMessage = new DigitsAttribute().FormatErrorMessage(metadata.GetDisplayName());
            ModelClientValidationRule actual = adapter.GetClientValidationRules().Single();

            Assert.Equal(expectedMessage, actual.ErrorMessage);
            Assert.Equal("digits", actual.ValidationType);
            Assert.Empty(actual.ValidationParameters);
        }
        public void RangeAdapter_SetsErrorMessage()
        {
            RangeAttribute attribute = new RangeAttribute(0, 128);
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider()
                .GetMetadataForProperty(null, typeof(AdaptersModel), "Range");
            new RangeAdapter(metadata, new ControllerContext(), attribute);

            String actual = attribute.ErrorMessage;
            String expected = Validations.Range;

            Assert.Equal(expected, actual);
        }
        public void StringLengthAdapter_SetsRangeErrorMessage()
        {
            StringLengthAttribute attribute = new StringLengthAttribute(128) { MinimumLength = 4 };
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider()
                .GetMetadataForProperty(null, typeof(AdaptersModel), "StringLength");
            new StringLengthAdapter(metadata, new ControllerContext(), attribute);

            String expected = Validations.FieldMustBeInRangeOfLength;
            String actual = attribute.ErrorMessage;

            Assert.Equal(expected, actual);
        }
        public void GetClientValidationRules_ReturnsGreaterValidationRule()
        {
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForProperty(null, typeof(AdaptersModel), "GreaterThan");
            GreaterThanAdapter adapter = new GreaterThanAdapter(metadata, new ControllerContext(), new GreaterThanAttribute(128));

            String expectedMessage = new GreaterThanAttribute(128).FormatErrorMessage(metadata.GetDisplayName());
            ModelClientValidationRule actual = adapter.GetClientValidationRules().Single();

            Assert.Equal(128M, actual.ValidationParameters["min"]);
            Assert.Equal(expectedMessage, actual.ErrorMessage);
            Assert.Equal("greater", actual.ValidationType);
            Assert.Single(actual.ValidationParameters);
        }
Example #12
0
        public void GetClientValidationRules_SetsOtherPropertyDisplayName()
        {
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForProperty(null, typeof(AdaptersModel), "EqualTo");
            EqualToAttribute attribute = new EqualToAttribute("StringLength");
            attribute.OtherPropertyDisplayName = null;

            new EqualToAdapter(metadata, new ControllerContext(), attribute).GetClientValidationRules();

            String expected = ResourceProvider.GetPropertyTitle(typeof(AdaptersModel), "EqualTo");
            String actual = attribute.OtherPropertyDisplayName;

            Assert.Equal(expected, actual);
        }
Example #13
0
        public void GetClientValidationRules_ReturnsEqualToValidationRule()
        {
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForProperty(null, typeof(AdaptersModel), "EqualTo");
            EqualToAdapter adapter = new EqualToAdapter(metadata, new ControllerContext(), new EqualToAttribute("StringLength"));

            String expectedMessage = new EqualToAttribute("StringLength").FormatErrorMessage(metadata.GetDisplayName());
            ModelClientValidationRule actual = adapter.GetClientValidationRules().Single();

            Assert.Equal("*.StringLength", actual.ValidationParameters["other"]);
            Assert.Equal(expectedMessage, actual.ErrorMessage);
            Assert.Equal("equalto", actual.ValidationType);
            Assert.Single(actual.ValidationParameters);
        }
        public void MinLengthAdapter_SetsErrorMessage()
        {
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider()
                .GetMetadataForProperty(null, typeof(AdaptersModel), "MinLength");

            MinLengthAttribute attribute = new MinLengthAttribute(128);
            new MinLengthAdapter(metadata, new ControllerContext(), attribute);

            String expected = Validations.FieldMustBeWithMinLengthOf;
            String actual = attribute.ErrorMessage;

            Assert.Equal(expected, actual);
        }
        public void DefaultRequiredClientValidationString()
        {
            var model = new MetadataTarget {LastName = "Arne", UserName = "******"};
            var metadataProvider = new DataAnnotationsModelMetadataProvider();
            var metadata = metadataProvider.GetMetadataForProperty(() => model, typeof (MetadataTarget), "UserName");

            var validator =
                _provider.GetValidators(metadata, new ControllerContext(new RequestContext(), new SomeController())).
                    Single();

            var clientRules = validator.GetClientValidationRules();

            Assert.True(validator.IsRequired);
            Assert.Equal("The UserName field is required.", clientRules.Single().ErrorMessage);
        }
        public void GetClientValidationRules_ReturnsMinRangeValidationRule()
        {
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForProperty(null, typeof(AdaptersModel), "Integer");
            IntegerAdapter adapter = new IntegerAdapter(metadata, new ControllerContext(), new IntegerAttribute());
            String errorMessage = new IntegerAttribute().FormatErrorMessage(metadata.GetDisplayName());

            ModelClientValidationRule actual = adapter.GetClientValidationRules().Single();
            ModelClientValidationRule expected = new ModelClientValidationRule();
            expected.ErrorMessage = errorMessage;
            expected.ValidationType = "integer";

            Assert.Equal(expected.ValidationParameters.Count, actual.ValidationParameters.Count);
            Assert.Equal(expected.ValidationType, actual.ValidationType);
            Assert.Equal(expected.ErrorMessage, actual.ErrorMessage);
        }
        public void RequiredClientValidationString()
        {
            var model = new MetadataTarget {LastName = "Arne", UserName = "******"};
            var metadataProvider = new DataAnnotationsModelMetadataProvider();
            var metadata = metadataProvider.GetMetadataForProperty(() => model, typeof (MetadataTarget), "UserName");
            _stringProvider.Setup(k => k.GetValidationString(typeof (RequiredAttribute))).Returns(
                "Fältet '{0}' är humm!").Verifiable();

            var validator =
                _provider.GetValidators(metadata, new ControllerContext(new RequestContext(), new SomeController())).
                    Single();

            var clientRules = validator.GetClientValidationRules();

            Assert.True(validator.IsRequired);
            Assert.Equal("Fältet 'UserName' är humm!", clientRules.Single().ErrorMessage);
            _stringProvider.VerifyAll();
        }
        public void DefaultRequiredClientValidationString()
        {
            var model = new TestModel {
                RequiredStringLength10 = "Arne", Required = "Kalle"
            };
            var metadataProvider = new System.Web.Mvc.DataAnnotationsModelMetadataProvider();
            var metadata         = metadataProvider.GetMetadataForProperty(() => model, typeof(TestModel), "Required");

            _stringProvider.Setup(k => k.GetMessage(It.Is <IGetMessageContext>(x => x.Attribute is RequiredAttribute))).Returns(
                "The {0} field is required.").Verifiable();

            var validator =
                _provider.GetValidators(metadata, new ControllerContext(new RequestContext(), new SomeController())).
                First();

            var clientRules = validator.GetClientValidationRules();

            Assert.IsTrue(validator.IsRequired);
            Assert.AreEqual("The Required field is required.", clientRules.Single().ErrorMessage);
        }
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var provider = new DataAnnotationsModelMetadataProvider();
            var otherPropertyMetadata = provider.GetMetadataForProperty(() => null, metadata.ContainerType, OtherProperty);

            var typeName = otherPropertyMetadata.DataTypeName;
            if (typeName == null)
            {
                var nullableType = Nullable.GetUnderlyingType(otherPropertyMetadata.ModelType);
                if (nullableType != null)
                {
                    typeName = nullableType.Name;
                }
                else
                {
                    typeName = otherPropertyMetadata.ModelType.Name;
                }
            }

            yield return new ModelClientValidationRequiredConditionalRule(OtherProperty, typeName, OtherPropertyValues, Any, Operator, FormatErrorMessage(metadata.GetDisplayName()));
        }
Example #20
0
        public BscModelMetadata(DataAnnotationsModelMetadataProvider provider, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName, DisplayColumnAttribute displayColumnAttribute, IEnumerable<Attribute> attributes)
            : base(provider, containerType, modelAccessor, modelType, propertyName, displayColumnAttribute)
        {
            var descAttr = attributes.OfType<DescriptionAttribute>().SingleOrDefault();
            _description = descAttr != null ? descAttr.Description : "";

            DataSourceAttribute = attributes.OfType<DataSourceAttribute>().SingleOrDefault();

            var enumAttribute = attributes.OfType<EnumDataTypeAttribute>().SingleOrDefault();
            if (enumAttribute != null)
            {
                DataSource = new EnumTypeSelectListDataSource(enumAttribute.EnumType);
            }

            Attributes = attributes;

            var defaultValueAttr = attributes.OfType<DefaultValueAttribute>().SingleOrDefault();

            DefaultValue = defaultValueAttr != null ? defaultValueAttr.Value : this.ModelType.GetDefaultValue();

            this.AdditionalValues["DefaultValue"] = DefaultValue;
        }
        public void Should_request_correct_repository_type()
        {
            const int id = 1;
            const string propertyName = "entity";

            var builder = new TestControllerBuilder();
            var controllerContext = new ControllerContext(builder.HttpContext, builder.RouteData, builder.CreateController<FakeController>());
            var metaDataProvider = new DataAnnotationsModelMetadataProvider();
            var bindingContext = new ModelBindingContext
                                     {
                                         ModelName = propertyName,
                                         ValueProvider = new FormCollection
                                                             {
                                                                 {propertyName, id.ToString()}
                                                             },
                                         ModelMetadata = new ModelMetadata(metaDataProvider, null, null, typeof(TestEntity), propertyName)
                                     };
            _entityBinder.BindModel(controllerContext, bindingContext);
            var requestedType = _resolver.GetArgumentsForCallsMadeOn(m => m.GetService(null)).FirstOf<Type>();
            var requestedId = _repository.GetArgumentsForCallsMadeOn(m => m.GetById(0)).FirstOf<int>();
            Assert.AreEqual(typeof(IRepository<TestEntity>), requestedType);
            Assert.AreEqual(id, requestedId);
        }
Example #22
0
        public override string ProcessTag(NDjango.Interfaces.IContext context, string content, object[] parms)
        {
            var htmlHelperOption = context.tryfind("Html");
            if (htmlHelperOption == null)
                return "";

            var htmlHelper = (HtmlHelper)htmlHelperOption.Value;

            var metadata_provider = new DataAnnotationsModelMetadataProvider();

            if (context.ModelType == null)
                htmlHelper.ViewData.ModelMetadata = null;
            else
            {
                var model = Activator.CreateInstance(context.ModelType.Value);
                htmlHelper.ViewData.ModelMetadata = metadata_provider.GetMetadataForType(() => model, context.ModelType.Value);
            }

            var result = htmlHelper.Label(parms[0].ToString());
            if (result == null)
                return "";
            else
                return result.ToHtmlString();
        }
 private static ModelMetadata GetMetadataForCanUpdateProperty(string propertyName)
 {
     DataAnnotationsModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();
     return metadataProvider.GetMetadataForProperty(null, typeof(MyModelTestingCanUpdateProperty), propertyName);
 }
        private IEnumerable<ModelClientValidationRule> GetClientRules(Expression<Func<TestModel, object>> expression )
        {
            var propertyName = expression.GetMember().Name;
            var metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForProperty(null, typeof(TestModel), propertyName);

            var factory = new Mock<IValidatorFactory>();
            factory.Setup(x => x.GetValidator(typeof(TestModel))).Returns(validator);

            var provider = new FluentValidationModelValidatorProvider(factory.Object);
            var propertyValidators = provider.GetValidators(metadata, controllerContext);

            return (propertyValidators.SelectMany(x => x.GetClientValidationRules())).ToList();
        }
        private ModelClientValidationRule GetClientRule(Expression<Func<TestModel, object>> expression)
        {
            var propertyName = expression.GetMember().Name;
            var metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForProperty(null, typeof(TestModel), propertyName);

            var factory = new Mock<IValidatorFactory>();
            factory.Setup(x => x.GetValidator(typeof(TestModel))).Returns(validator);

            var provider = new FluentValidationModelValidatorProvider(factory.Object);
            var propertyValidator = provider.GetValidators(metadata, controllerContext).Single();

            var clientRule = propertyValidator.GetClientValidationRules().Single();
            return clientRule;
        }
        public void ClientValidatable()
        {
            ValidationMessageProviders.Reset();
            var model = new TestModel();
            var k = new DataAnnotationsModelMetadataProvider();
            var metadata = k.GetMetadataForType(() => model, model.GetType());
            var validators = _provider.GetValidators(metadata, new ControllerContext());

            var result = validators.ToList().First().Validate(model).ToList();

            Assert.NotEqual(0, result.Count);

        }
        public void RegisterAdapters_RegistersAdapter(String property, Type adapterType)
        {
            DataAnnotationsModelValidatorProvider provider = new DataAnnotationsModelValidatorProvider();
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider()
                .GetMetadataForProperty(null, typeof(AdaptersModel), property);

            application.RegisterAdapters();

            ModelValidator adapter = provider
                .GetValidators(metadata, new ControllerContext())
                .SingleOrDefault(validator => validator.GetType() == adapterType);

            Assert.NotNull(adapter);
        }
Example #28
0
 public FieldTemplateMetadata(DataAnnotationsModelMetadataProvider provider, Type containerType, Func <object> modelAccessor, Type modelType, string propertyName, DisplayColumnAttribute displayColumnAttribute, IEnumerable <Attribute> attributes)
     : base(provider, containerType, modelAccessor, modelType, propertyName, displayColumnAttribute)
 {
     Attributes = new List <Attribute>(attributes);
 }
Example #29
0
 public FieldTemplateMetadata(DataAnnotationsModelMetadataProvider provider, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName, DisplayColumnAttribute displayColumnAttribute, IEnumerable<Attribute> attributes)
     : base(provider, containerType, modelAccessor, modelType, propertyName, displayColumnAttribute)
 {
     this.Attributes = new List<Attribute>(attributes);
 }
 public void Setup()
 {
     _provider = new DataAnnotationsModelMetadataProvider();
 }
        public void GetValidators_ReturnsEmpty()
        {
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForProperty(null, typeof(ProviderModel), "Id");

            Assert.Empty(provider.GetValidators(metadata, new ControllerContext()));
        }
 private static ModelMetadata GetMetadataForType(Type t)
 {
     DataAnnotationsModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();
     return metadataProvider.GetMetadataForType(null, t);
 }
 private static ModelMetadata GetMetadataForObject(object o)
 {
     DataAnnotationsModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();
     return metadataProvider.GetMetadataForType(() => o, o.GetType());
 }