Example #1
0
        /// <summary>
        /// Wrapper for Validator.TryValidateObject
        /// </summary>
        /// <exception cref="System.ArgumentNullException">instance is null</exception>
        private static CombinedValues TryValidateObject(object objectToValidate)
        {
            ValidationContext       validationContext = new ValidationContext(objectToValidate, null, null);
            List <ValidationResult> validationResults = new List <ValidationResult>();
            bool isValid = MvcValidator.TryValidateObject(objectToValidate, validationContext, validationResults, true);

            return(new CombinedValues
            {
                IsValid = isValid,
                ValidationResults = validationResults
            });
        }
        public void TestDataAnnotations()
        {
            var sw = Stopwatch.StartNew();

            foreach (var item in _testData)
            {
                var ctx    = new ValidationContext(item, null, null);
                var errors = new List <ValidationResult>();
                DAValidator.TryValidateObject(item, ctx, errors);
            }

            sw.Stop();
            Assert.Inconclusive("DataAnnotations validated {0} objects in {1} ticks", TestDataCount, sw.ElapsedTicks);
        }
Example #3
0
        public static (bool isValid, ModelErrorDictionary modelErrors) IsValid(
            object model,
            IServiceProvider serviceProvider   = null,
            IDictionary <object, object> items = null)
        {
            var validationContext = new ValidationContext(model, serviceProvider, items);
            var validationResults = new List <ValidationResult>();

            SystemValidator.TryValidateObject(model, validationContext, validationResults, validateAllProperties: true);
            var(resultsWithMember, resultsWithoutMember) = validationResults.Fork(v => v.MemberNames.Count() > 0);

            var modelErrors = new ModelErrorDictionary(
                resultsWithMember
                .SelectMany(v => v.MemberNames.Select(m => (MemberName: m, ErrorMessage: v.ErrorMessage)))
                .ToLookup(t => t.MemberName)
                .ToDictionary(g => g.Key, g => g.Select(t => t.ErrorMessage)),
                resultsWithoutMember.Select(v => v.ErrorMessage));

            model.GetType().GetProperties().ForEach(pi =>
            {
                var attributes = pi.GetCustomAttributes(typeof(ValidateCustomBehaviourAttribute), false);
                attributes.ForEach(attribute =>
                {
                    if (attribute is ValidateEnumerableElementsAttribute)
                    {
                        ValidateEnumerableElements(model, serviceProvider, items, modelErrors, pi);
                        return;
                    }

                    var validateAgainstTypeIfAttribute = attribute as ValidateAgainstTypeIfAttribute;
                    if (validateAgainstTypeIfAttribute != null)
                    {
                        ValidateAgainstTypeIf(model, serviceProvider, items, modelErrors, pi, validateAgainstTypeIfAttribute);
                        return;
                    }

                    var validateAgainstTypeAttribute = attribute as ValidateAgainstTypeAttribute;
                    if (validateAgainstTypeAttribute != null)
                    {
                        ValidateAgainstType(model, serviceProvider, items, modelErrors, pi, validateAgainstTypeAttribute);
                        return;
                    }

                    throw new Exception("Unsupported ValidateCustomBehaviourAttribute");
                });
            });

            return(!modelErrors.HasErrors, modelErrors);
        }
        public static bool IsValid <TOptions>(this TOptions instance, IServiceProvider serviceProvider)
        {
            var results = Pooling.ListPool <ValidationResult> .Get();

            try
            {
                // FIXME: Use TK Validator
                var context = new ValidationContext(instance, serviceProvider, null);
                Validator.TryValidateObject(instance, context, results, true);
                return(results.Count == 0);
            }
            finally
            {
                Pooling.ListPool <ValidationResult> .Return(results);
            }
        }
        public static TOptions Validate <TOptions>(this TOptions instance, IServiceProvider serviceProvider)
        {
            var results = Pooling.ListPool <ValidationResult> .Get();

            try
            {
                var context = new ValidationContext(instance, serviceProvider, null);
                Validator.TryValidateObject(instance, context, results, true);
                if (results.Count == 0)
                {
                    return(instance);
                }

                var message = Pooling.StringBuilderPool.Scoped(sb =>
                {
                    sb.Append(typeof(TOptions).Name).Append(": ");
                    sb.AppendLine();

                    foreach (var result in results)
                    {
                        sb.Append(result.ErrorMessage);
                        sb.Append(" [");
                        var count = 0;
                        foreach (var field in result.MemberNames)
                        {
                            if (count != 0)
                            {
                                sb.Append(", ");
                            }

                            sb.Append(field);
                            count++;
                        }

                        sb.AppendLine("]");
                    }
                });

                throw new ValidationException(message);
            }
            finally
            {
                Pooling.ListPool <ValidationResult> .Return(results);
            }
        }