Example #1
0
        public void Validate_ReturnsExpectedResults_Scalar()
        {
            // Arrange
            var validator = new DataSetValidator();
            var model     = DataSet <SampleModel> .Create();

            model.AddRow();

            var metadata = _metadataProvider.GetMetadataForProperty(
                typeof(ScalarSampleModelContainer),
                nameof(ScalarSampleModelContainer.SampleModel));
            var validationContext = new ModelValidationContext(
                new ActionContext(),
                metadata,
                _metadataProvider,
                container: null,
                model: model);

            // Act
            var results      = validator.Validate(validationContext);
            var resultsArray = results.ToArray();

            // Assert
            Assert.NotNull(results);
            Assert.Single(resultsArray);
            Assert.Equal(nameof(SampleModel.ID), resultsArray[0].MemberName);
        }
Example #2
0
        public static string RealDisplayNameFor <TModel, TValue>(this HtmlHelper <TModel> htmlHelper, Expression <System.Func <TModel, TValue> > expression)
        {
            string result;

            if (htmlHelper.ViewData.Model == null)
            {
                result = "";
            }
            else
            {
                string property = ExpressionHelper.GetExpressionText(expression);
                if (string.IsNullOrEmpty(property))
                {
                    result = "";
                }
                else
                {
                    ModelMetadata metadata = null;
                    try
                    {
                        ModelMetadataProvider arg_94_0 = ModelMetadataProviders.Current;
                        System.Func <object>  arg_94_1 = () => htmlHelper.ViewData.Model;
                        TModel model = htmlHelper.ViewData.Model;
                        metadata = arg_94_0.GetMetadataForProperty(arg_94_1, model.GetType(), property);
                    }
                    catch
                    {
                    }
                    result = ((metadata != null) ? metadata.DisplayName : property);
                }
            }
            return(result);
        }
Example #3
0
        public bool IsRequiredMember(MemberInfo member)
        {
            if (member == null)
            {
                throw Error.ArgumentNull("member");
            }

            // Optimization : avoid computing validators if there are no validator providers
            if (_validatorProviders == null || !_validatorProviders.Any())
            {
                return(false);
            }

            PropertyInfo property = member as PropertyInfo;

            // if member is not a property or there is no public getter
            if (property == null || property.GetGetMethod() == null)
            {
                return(false);
            }

            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => null, member.DeclaringType, member.Name);

            if (metadata.ModelType.IsNullable())
            {
                // If the model type is nullable, the value validator will raise a model error for the null member
                // Only non-nullable property types need to be checked by the formatter
                return(false);
            }

            IEnumerable <ModelValidator> validators = metadata.GetValidators(_validatorProviders);

            return(validators.Any(validator => validator.IsRequired));
        }
Example #4
0
        /// <summary>
        /// Specifies a column should be constructed for the specified property.
        /// </summary>
        /// <param name="propertySpecifier">Lambda that specifies the property for which a column should be constructed</param>
        public IGridColumn <T> For(Expression <Func <T, object> > propertySpecifier)
        {
            var memberExpression = GetMemberExpression(propertySpecifier);
            var propertyType     = GetTypeFromMemberExpression(memberExpression);
            var declaringType    = memberExpression == null ? null : memberExpression.Expression.Type;
            var inferredName     = memberExpression == null ? null : memberExpression.Member.Name;
            var column           = new GridColumn <T>(propertySpecifier.Compile(), inferredName, propertyType);

            if (declaringType != null)
            {
                var metadata = _metadataProvider.GetMetadataForProperty(null, declaringType, inferredName);

                if (!string.IsNullOrEmpty(metadata.DisplayName))
                {
                    column.Named(metadata.DisplayName);
                }

                if (!string.IsNullOrEmpty(metadata.DisplayFormatString))
                {
                    column.Format(metadata.DisplayFormatString);
                }
            }

            Add(column);

            return(column);
        }
Example #5
0
        public bool IsRequiredMember(MemberInfo member)
        {
            if (member == null)
            {
                throw Error.ArgumentNull("member");
            }

            // Optimization : avoid computing validators if there are no validator providers
            if (_validatorProviders == null || !_validatorProviders.Any())
            {
                return(false);
            }

            PropertyInfo property = member as PropertyInfo;

            // if member is not a property or there is no public getter
            if (property == null || property.GetGetMethod() == null)
            {
                return(false);
            }

            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => null, member.DeclaringType, member.Name);
            IEnumerable <ModelValidator> validators = metadata.GetValidators(_validatorProviders);

            return(validators.Any(validator => validator.IsRequired));
        }
Example #6
0
        public override ModelMetadata GetMetadataForProperty(Func <object> modelAccessor, Type containerType, string propertyName)
        {
            var metadata = _innerProvider.GetMetadataForProperty(modelAccessor, containerType, propertyName);

            var additionalMetadata = _wrappedProvider.GetMetadataForProperty(modelAccessor, containerType, propertyName);

            MergeAdditionalValues(metadata.AdditionalValues, additionalMetadata.AdditionalValues);

            return(metadata);
        }
Example #7
0
        static void Main(string[] args)
        {
            HttpConfiguration     configuration    = new HttpConfiguration();
            ModelMetadataProvider metadataProvider = configuration.Services.GetModelMetadataProvider();
            ModelMetadata         metadata         = metadataProvider.GetMetadataForProperty(null, typeof(Employee), "Salary");
            IEnumerable <ModelValidatorProvider> validatorProviders = configuration.Services.GetModelValidatorProviders();

            ModelValidator[] validators = metadata.GetValidators(validatorProviders).ToArray();
            for (int i = 0; i < validators.Length; i++)
            {
                Console.WriteLine("{0}.{1}", i + 1, validators[i].GetType().Name);
            }
        }
Example #8
0
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            string name = "";

            if (metadata.ContainerType != null && this.OtherPropertyDisplayName == null)
            {
                CompareAttribute      displayName = this;
                ModelMetadataProvider current     = ModelMetadataProviders.Current;
                name = current.GetMetadataForProperty(() => metadata.Model, metadata.ContainerType, this.OtherProperty).GetDisplayName();
            }
            ILocalizationService _LocalizationService = DependencyResolver.Current.GetService <ILocalizationService>();

            yield return(new ModelClientValidationEqualToRule(String.Format(CultureInfo.CurrentCulture, _LocalizationService.LocalizeString(ErrorMessageString, CultureInfo.CurrentCulture.Name), name, OtherPropertyDisplayName ?? OtherProperty), FormatPropertyForClientValidation(this.OtherProperty)));
        }
        public bool IsRequiredMember(MemberInfo member)
        {
            if (member == null)
            {
                throw Error.ArgumentNull("member");
            }

            if (!(member is PropertyInfo))
            {
                return(false);
            }

            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => null, member.DeclaringType, member.Name);
            IEnumerable <ModelValidator> validators = metadata.GetValidators(_validatorProviders);

            return(validators.Any(validator => validator.IsRequired));
        }
        private ModelMetadata GetMetadataForProperty(
            Func <object> modelAccessor,
            Type containerType,
            string propertyName)
        {
            var propertyMetadata =
                _oldMetadataProvider.GetMetadataForProperty(modelAccessor, containerType, propertyName);

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

            if (propertyMetadata.ModelType == _modelType)
            {
                return(CloneMetadata(() => propertyMetadata.Model));
            }

            return(propertyMetadata);
        }
        private static void CreateModelValidationNodeRecursive(object o, ModelValidationNode parentNode, ModelMetadataProvider metadataProvider, ModelMetadata metadata, ModelStateDictionary modelStateDictionary, string modelStateKey, HashSet <object> visited)
        {
            if (visited.Contains(o))
            {
                return;
            }
            visited.Add(o);

            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(o))
            {
                // append the current property name to the model state path
                string propertyKey = modelStateKey;
                if (propertyKey.Length > 0)
                {
                    propertyKey += ".";
                }
                propertyKey += property.Name;

                // create the node for this property and add to the parent node
                object propertyValue = property.GetValue(o);
                metadata = metadataProvider.GetMetadataForProperty(() =>
                {
                    return(propertyValue);
                }, o.GetType(), property.Name);
                ModelValidationNode childNode = new ModelValidationNode(metadata, propertyKey);
                parentNode.ChildNodes.Add(childNode);

                // add the property node to model state
                ModelState modelState = new ModelState();
                modelState.Value = new ValueProviderResult(propertyValue, null, CultureInfo.CurrentCulture);
                modelStateDictionary.Add(propertyKey, modelState);

                if (propertyValue != null)
                {
                    CreateModelValidationNodeRecursive(propertyValue, childNode, metadataProvider, metadata, modelStateDictionary, propertyKey, visited);
                }
            }
        }
Example #12
0
 public override ModelMetadata GetMetadataForProperty(Func <object> modelAccessor, Type containerType, string propertyName)
 {
     return(_innerMetadataProvider.GetMetadataForProperty(modelAccessor, containerType, propertyName));
 }
        /// <summary>
        ///  Specifies a column should be constructed for the specified property.
        ///  add by zhangh 2013/06/03
        /// </summary>
        /// <param name="propertySpecifier"></param>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        public IGridColumn <T> For(Expression <Func <T, object> > propertySpecifier, string fieldName)
        {
            var memberExpression = GetMemberExpression(propertySpecifier);
            var propertyType     = GetTypeFromMemberExpression(memberExpression);
            var declaringType    = memberExpression == null?string.IsNullOrEmpty(fieldName) ? null : typeof(T) : memberExpression.Expression.Type;

            var inferredName = memberExpression == null ? fieldName : memberExpression.Member.Name;
            var column       = new GridColumn <T>(propertySpecifier.Compile(), inferredName, propertyType);

            if (!string.IsNullOrEmpty(fieldName))
            {
                column.FieldName = fieldName;
            }
            else
            {
                string tmpName = ExpressionHelper.GetExpressionText(propertySpecifier);
                if (string.IsNullOrEmpty(tmpName) && memberExpression != null)
                {
                    tmpName = memberExpression.ToString().Substring(memberExpression.ToString().IndexOf(".") + 1);
                }

                column.FieldName = tmpName;
            }

            if (!string.IsNullOrEmpty(column.FieldName))
            {
                string[]      props       = column.FieldName.Split('.');
                Type          type        = typeof(T);
                PropertyInfo  property    = null;
                string        displayName = string.Empty;
                ModelMetadata metadata;
                foreach (string prop in props)
                {
                    property = type.GetProperty(prop);
                    if (property == null)
                    {
                        continue;
                    }

                    metadata = _metadataProvider.GetMetadataForProperty(null, type, property.Name);
                    if (!string.IsNullOrEmpty(metadata.DisplayName))
                    {
                        displayName += metadata.DisplayName;
                        column.Named(displayName);
                    }
                    type = property.PropertyType;
                }

                #region TODO: 格式化等其他信息 zhangh 2013/06/03
                //if (declaringType != null)
                //{
                //    metadata = _metadataProvider.GetMetadataForProperty(null, declaringType, inferredName);

                //    //if (!string.IsNullOrEmpty(metadata.DisplayName))
                //    //{
                //    //    displayName += metadata.DisplayName;
                //    //    column.Named(displayName);
                //    //}

                //    if (!string.IsNullOrEmpty(metadata.DisplayFormatString))
                //    {
                //        column.Format(metadata.DisplayFormatString);
                //    }
                //}
                #endregion
            }

            Add(column);

            return(column);
        }