Ejemplo n.º 1
0
        protected override ValidationResult IsValid(object?value, ValidationContext?validationContext)
        {
            if (value == null)
            {
                return(ValidationResult.Success);
            }

            if (validationContext == null)
            {
                throw new ArgumentNullException(nameof(validationContext));
            }

            var result = false;

            switch (value)
            {
            case IEnumerable <string> list:
                result = list.All(s => s.Equals(s.ToLowerInvariant(), StringComparison.Ordinal));
                break;

            default:
                string item = value.ToString() ?? string.Empty;
                result = item.Equals(item.ToLowerInvariant(), StringComparison.Ordinal);
                break;
            }

            return(result ? ValidationResult.Success
                : new ValidationResult(string.Format(CultureInfo.InvariantCulture, FieldNotLowercase, validationContext.DisplayName), new[] { validationContext.MemberName }));
        }
        /// <summary>
        ///		Returns <see cref="ValidationResult.Success"/> if the <paramref name="value"/> falls between minimum and maximum, inclusive.
        /// </summary>
        /// <remarks>
        ///		Returns <see cref="ValidationResult.Success"/> for null values. Use the <see cref="RequiredAttribute"/> to assert a value is not empty.
        /// </remarks>
        /// <exception cref="InvalidCastException">Thrown if the <paramref name="value"/> cannot be cast to a <see cref="DateTime"/>.</exception>
        protected override ValidationResult IsValid(object?value, ValidationContext?validationContext)
        {
            // Automatically pass if value is null or empty. RequiredAttribute should be used to assert a value is not empty.
            if (value == null)
            {
                return(ValidationResult.Success);
            }

            try
            {
                var dateTimeValue = (DateTime)value;
                if (Minimum <= dateTimeValue && dateTimeValue <= Maximum)
                {
                    return(ValidationResult.Success);
                }

                string[]? memberNames = validationContext?.MemberName is { } memberName
                                        ? new[] { memberName }
                                        : null;
                return(new ValidationResult(FormatErrorMessage(validationContext?.DisplayName), memberNames));
            }
            catch (InvalidCastException exc)
            {
                var castException = new InvalidCastException($@"The [SqlServerDate] attribute must be used on a DateTime member. [MemberName: ""{validationContext?.DisplayName}""]", exc);
                castException.Data["ValidationValue"] = value;
                throw castException;
            }
        }
 public OriginInfo(Uri origin, Version?version = null, long?size = null, ValidationContext?validationContext = null)
 {
     Origin            = origin ?? throw new ArgumentNullException(nameof(origin));
     Version           = version;
     Size              = size;
     ValidationContext = validationContext;
 }
Ejemplo n.º 4
0
        public static IComponent?DependencyToComponent(Dependency dependency)
        {
            if (string.IsNullOrEmpty(dependency.Name) || string.IsNullOrEmpty(dependency.Destination))
            {
                return(null);
            }
            var component = new Component
            {
                Name        = dependency.Name,
                Destination = GetRealDependencyDestination(dependency)
            };

            if (!string.IsNullOrEmpty(dependency.Origin))
            {
                var newVersion = dependency.GetVersion();
                var hash       = dependency.Sha2;
                var size       = dependency.Size;

                ValidationContext?validationContext = null;
                if (hash != null)
                {
                    validationContext = new ValidationContext {
                        Hash = hash, HashType = HashType.Sha256
                    }
                }
                ;
                var originInfo = new OriginInfo(new Uri(dependency.Origin, UriKind.Absolute), newVersion, size, validationContext);
                component.OriginInfo = originInfo;
            }

            return(component);
        }
Ejemplo n.º 5
0
 public static void AssertIsValid <T>(
     this T obj,
     ValidationContext?context  = null,
     bool errorOnNull           = true,
     bool validateAllProperties = true
     ) where T : class?
 {
     if (obj == null)
 public Accessor(WeakReference <object?> reference, string name, IPropertyAccessor inner)
     : base(inner)
 {
     if (reference.TryGetTarget(out var target))
     {
         _context            = new ValidationContext(target);
         _context.MemberName = name;
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Validates as a subschema.  To be called from within keywords.
        /// </summary>
        /// <param name="context">The validation context for this validation pass.</param>
        public void ValidateSubschema(ValidationContext context)
        {
            if (BoolValue.HasValue)
            {
                context.Log(() => $"Found {(BoolValue.Value ? "true" : "false")} schema: {BoolValue.Value.GetValidityString()}");
                context.IsValid        = BoolValue.Value;
                context.SchemaLocation = context.SchemaLocation.Combine(PointerSegment.Create($"${BoolValue}".ToLowerInvariant()));
                if (!context.IsValid)
                {
                    context.Message = "All values fail against the false schema";
                }
                return;
            }

            var metaSchemaUri = Keywords !.OfType <SchemaKeyword>().FirstOrDefault()?.Schema;
            var keywords      = context.Options.FilterKeywords(Keywords !, metaSchemaUri, context.Options.SchemaRegistry);

            ValidationContext?newContext = null;
            var overallResult            = true;

            foreach (var keyword in keywords.OrderBy(k => k.Priority()))
            {
                var previousContext = newContext;
                newContext = ValidationContext.From(context,
                                                    subschemaLocation: context.SchemaLocation.Combine(PointerSegment.Create(keyword.Keyword())));
                newContext.NavigatedByDirectRef = context.NavigatedByDirectRef;
                newContext.ParentContext        = context;
                newContext.LocalSchema          = this;
                newContext.ImportAnnotations(previousContext);
                if (context.HasNestedContexts)
                {
                    newContext.SiblingContexts.AddRange(context.NestedContexts);
                }
                keyword.Validate(newContext);
                context.IsNewDynamicScope |= newContext.IsNewDynamicScope;
                overallResult             &= newContext.IsValid;
                if (!overallResult && context.ApplyOptimizations)
                {
                    break;
                }
                if (!newContext.Ignore)
                {
                    context.NestedContexts.Add(newContext);
                }
            }

            if (context.IsNewDynamicScope)
            {
                context.Options.SchemaRegistry.ExitingUriScope();
            }

            context.IsValid = overallResult;
            if (context.IsValid)
            {
                context.ImportAnnotations(newContext);
            }
        }
Ejemplo n.º 8
0
        public void ValidationThrowsArgumentNullExceptionIfValidationContextIsNull()
        {
            // Arrange.
            Person            value             = new();
            ValidationContext?validationContext = null;
            ValidateComplexTypeAttributeTest validateComplexTypeAttribute = new();

            // Act.
            void act()
            {
#pragma warning disable CS8604 // Возможно, аргумент-ссылка, допускающий значение NULL.
                validateComplexTypeAttribute.IsValid(value, validationContext);
#pragma warning restore CS8604 // Возможно, аргумент-ссылка, допускающий значение NULL.
            }

            // Assert.
            Assert.ThrowsException <ArgumentNullException>(act);
        }
Ejemplo n.º 9
0
        protected override ValidationResult IsValid(object?value, ValidationContext?validationContext)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            if (validationContext == null)
            {
                throw new ArgumentNullException(nameof(validationContext));
            }

            if (!Guid.TryParse(value.ToString(), out var guid) || guid == Guid.Empty)
            {
                return(new ValidationResult(string.Format(CultureInfo.InvariantCulture, ValidationMessage.FieldInvalidGuid, validationContext.DisplayName), new[] { validationContext.MemberName }));
            }

            return(ValidationResult.Success);
        }
Ejemplo n.º 10
0
        public bool PerformValidate(string?propertyName = null)
        {
            try
            {
                _validateResults = new List <ValidationResult>();

                if (_validationContext == null)
                {
                    _validationContext = new ValidationContext(this);
                }

                if (!string.IsNullOrEmpty(propertyName))
                {
                    _validationContext.MemberName = propertyName;

                    PropertyInfo?propertyInfo = GetType().GetProperty(propertyName);

                    if (propertyInfo != null)
                    {
                        object?propertyValue = propertyInfo.GetValue(this);

                        return(Validator.TryValidateProperty(propertyValue, _validationContext, _validateResults));
                    }
                }

                bool result = Validator.TryValidateObject(this, _validationContext, _validateResults, true);

                return(result);
            }
            catch (ArgumentNullException)
            {
                return(false);
            }
            catch (ArgumentException)
            {
                return(false);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 11
0
        protected override ValidationResult IsValid(object?value, ValidationContext?validationContext)
        {
            if (value == null)
            {
                return(ValidationResult.Success);
            }

            if (validationContext == null)
            {
                throw new ArgumentNullException(nameof(validationContext));
            }

            var validChars = "abcdefghijklmnopqrstuvwxyz01234567890_-/";
            var result     = value switch
            {
                IEnumerable <string> list => list.All(x => x.Length > 0 && x.All(y => validChars.Contains(y, StringComparison.OrdinalIgnoreCase))),
                _ => value.ToString().All(x => validChars.Contains(x, StringComparison.OrdinalIgnoreCase)),
            };

            return(result ? ValidationResult.Success
                : new ValidationResult(string.Format(CultureInfo.InvariantCulture, FieldNotUrlPath, validationContext.DisplayName), new[] { validationContext.MemberName }));
        }