Ejemplo n.º 1
0
        protected override bool CanValidateInternal(IValidatorContext validatorContext)
        {
            IViewModel viewModel;

            validatorContext.ValidationMetadata.TryGetData(ViewModelConstants.ViewModel, out viewModel);
            return(viewModel == null || !ReferenceEquals(viewModel, validatorContext.Instance));
        }
Ejemplo n.º 2
0
        /// <summary>
        ///     Initializes the current validator using the specified <see cref="IValidatorContext" />.
        /// </summary>
        /// <param name="context">
        ///     The specified <see cref="IValidatorContext" />.
        /// </param>
        public void Initialize(IValidatorContext context)
        {
            EnsureNotDisposed();
            Should.NotBeNull(context, "context");
            if (Interlocked.CompareExchange(ref _context, context, null) != null)
            {
                throw ExceptionManager.ValidatorInitialized(this);
            }
            if (!CanValidate(context))
            {
                throw ExceptionManager.InvalidContexValidator(this);
            }

            OnInitialized(context);

            _notifyPropertyChanged = Instance as INotifyPropertyChanged ??
                                     context.ValidationMetadata.GetData(ViewModelConstants.ViewModel);
            if (_notifyPropertyChanged == null)
            {
                Tracer.Warn(
                    "The type {0} doesn't implement the INotifyPropertyChanged, validator {1} cannot track errors.",
                    Instance.GetType(), GetType());
            }
            else
            {
                _weakPropertyHandler = ReflectionExtensions.MakeWeakPropertyChangedHandler(this, (@base, o, arg3) => @base.OnPropertyChangedNotifyDataError(arg3));
                _notifyPropertyChanged.PropertyChanged += _weakPropertyHandler;
            }
        }
Ejemplo n.º 3
0
 public OpenApiHttpRequestValidator(string urlPath, OperationType httpMethod, IValidatorContext validatorContext, OpenApiOperation openApiOperation) : base(validatorContext, openApiOperation)
 {
     UrlPath             = urlPath;
     HttpMethod          = httpMethod;
     _validatorContext   = validatorContext;
     _OpenApiRequestBody = openApiOperation.RequestBody;
 }
        /// <summary>
        /// Selects all elements of a `IEnumerable` property for validation.
        /// </summary>
        /// <typeparam name="T">The type of the current value.</typeparam>
        /// <typeparam name="TItem">The type of an individual item in the `IEnumerable` property.</typeparam>
        /// <param name="validator">The current validator context.</param>
        /// <param name="selector">
        ///     The property selector expression.
        ///     <para>
        ///         The expression must be a `MemberExpression` (e.g. `x => x.Property`) or a `ParameterExpression`
        ///         to select all elements of the current value (e.g. `x => x`).
        ///     </para>
        /// </param>
        /// <param name="action">The action to perform for each item of the selected `IEnumerable` property.</param>
        /// <returns>The unmodified validator context.</returns>
        public static IValidatorContext <T> ForEach <T, TItem>(this IValidatorContext <T> validator,
                                                               Expression <Func <T, IEnumerable <TItem> > > selector, Action <IValidatorContext <TItem> > action)
        {
            ValidationInternals.ValidateNotNull(validator, nameof(validator));
            ValidationInternals.ValidateNotNull(selector, nameof(selector));
            ValidationInternals.ValidateNotNull(action, nameof(action));

            var name = (selector.Body is ParameterExpression)
                ? null
                : ValidationInternals.GetPropertyName(selector);
            var value = selector.Compile().Invoke(validator.Value);

            if (value is null)
            {
                return(validator);
            }

            int i = 0;

            foreach (var item in value)
            {
                var context = (name is null)
                    ? new ValidatorContext <TItem>(item, $"{ValidationInternals.FormatName(validator.Path, null)}[{i++}]")
                    : new ValidatorContext <TItem>(item, validator.Path, $"{name}[{i++}]");
                action.Invoke(context);
            }

            return(validator);
        }
Ejemplo n.º 5
0
        protected virtual IValidator GetValidator([NotNull] Type validatorType, [NotNull] IValidatorContext context)
        {
            if (context.Instance is IValidatableViewModel)
            {
                var viewModel = context.ValidationMetadata.GetData(ViewModelConstants.ViewModel);
                if (typeof(ValidatableViewModelValidator).IsAssignableFrom(validatorType))
                {
                    if (ReferenceEquals(context.Instance, viewModel))
                    {
                        return(null);
                    }
                }
                else
                {
                    if (!ReferenceEquals(context.Instance, viewModel) && _validators.ContainsKey(typeof(ValidatableViewModelValidator)))
                    {
                        return(null);
                    }
                }
            }
            IServiceProvider serviceProvider = context.ServiceProvider ?? ServiceProvider.IocContainer;
            IValidator       validator       = serviceProvider == null
                ? (IValidator)Activator.CreateInstance(validatorType)
                : (IValidator)serviceProvider.GetService(validatorType);

            if (validator.Initialize(context))
            {
                return(validator);
            }
            validator.Dispose();
            return(null);
        }
Ejemplo n.º 6
0
        public IList <IValidatorResult> Execute(IValidatorContext context)
        {
            log.Info("RabbitMQValidator Execute started");

            List <IValidatorResult> results = new List <IValidatorResult>();

            log.Debug("Validating rabbit mq environment for Server: {Server} Port: {Port} vHost: {vHost}",
                      _rabbitMQValidatorSettings.HostServer, _rabbitMQValidatorSettings.Port, _rabbitMQValidatorSettings.vHost);

            HareDuSettings settings = new HareDuSettings()
            {
                RabbitUrl = string.Format("http://{0}:{1}", _rabbitMQValidatorSettings.HostServer, _rabbitMQValidatorSettings.Port),
                Vhost     = _rabbitMQValidatorSettings.vHost,
                Username  = _rabbitMQValidatorSettings.UserName,
                Password  = _rabbitMQValidatorSettings.Password
            };

            var queues = this.GetErrorQueues(settings);

            foreach (var queue in queues)
            {
                log.Debug("RabbitMQValidator validating queue {RabbitQueue}", queue.Name);
                var queueResult = this.GetQueueResult(settings, queue);
                results.Add(queueResult);
            }

            log.Info("Starting RabbitMQValidator Execute completed with {ResultCount} results", results.Count);

            return(results);
        }
Ejemplo n.º 7
0
        public static IValidatorContext<T> AssertEqualValueAndPath<T>(this IValidatorContext<T> validator, T value, string path)
        {
            Assert.Equal(value, validator.Value);
            Assert.Equal(path, string.Join('.', validator.Path));

            return validator;
        }
Ejemplo n.º 8
0
        public static IValidatorContext<T> AssertEqualValueAndPathIndexed<T>(this IValidatorContext<T> validator, T value, string path,
            ref int index)
        {
            ++index;

            return validator.AssertEqualValueAndPath(value, path);
        }
        /// <summary>
        /// Throws if the current value is `null` or empty (contains the default value of the current type).
        /// <para>
        ///     This validation as well applies to empty strings or `IEnumerable` types without at least one element.
        /// </para>
        /// </summary>
        /// <typeparam name="T">The type of the current value.</typeparam>
        /// <param name="validator">The current validator context.</param>
        /// <returns>The unmodified validator context.</returns>
        public static IValidatorContext <T> NotNullOrEmpty <T>(this IValidatorContext <T> validator)
            where T : class
        {
            ValidationInternals.ValidateNotNull(validator, nameof(validator));

            try
            {
                validator.NotNull();
            }
            catch (ArgumentNullException)
            {
                throw new ArgumentNullException(validator.Path.First(), string.Format(CultureInfo.InvariantCulture,
                                                                                      Resources.ArgumentMustNotBeNullOrEmpty, ValidationInternals.FormatName(validator.Path, null)));
            }

            var isEmptyEnum   = (validator.Value is IEnumerable enumerable) && !enumerable.GetEnumerator().MoveNext();
            var isEmptyString = validator.Value is string { Length : 0 };

            if (isEmptyEnum || isEmptyString)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
                                                          Resources.ArgumentMustNotBeNullOrEmpty, ValidationInternals.FormatName(validator.Path, null)),
                                            validator.Path.First());
            }

            return(validator);
        }
Ejemplo n.º 10
0
 protected override bool CanValidateInternal(IValidatorContext validatorContext)
 {
     if (CanValidate == null)
     {
         return(base.CanValidateInternal(validatorContext));
     }
     return(CanValidate(validatorContext));
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Throws if the current value is equal to the blacklisted value.
        /// </summary>
        /// <typeparam name="T">The type of the current value.</typeparam>
        /// <param name="validator">The current validator context.</param>
        /// <param name="value">The blacklisted value.</param>
        /// <returns>The unmodified validator context.</returns>
        public static IValidatorContext <T> NotEqual <T>(this IValidatorContext <T> validator, T value)
        {
            ValidationInternals.ValidateNotNull(validator, nameof(validator));

            if (EqualityComparer <T> .Default.Equals(validator.Value, value))
            {
                throw new ArgumentNullException(validator.Path.First(), string.Format(CultureInfo.InvariantCulture,
                                                                                      Resources.ArgumentMustNotBeValue, ValidationInternals.FormatName(validator.Path, null), value));
            }

            return(validator);
        }
 /// <summary>
 ///     Checks to see whether the validator can validate objects of the specified IValidatorContext.
 /// </summary>
 internal override bool CanValidateContext(IValidatorContext validatorContext)
 {
     if (_validationElementProvider == null)
     {
         var iocContainer = validatorContext.ServiceProvider as IIocContainer ?? ServiceProvider.IocContainer;
         if (iocContainer == null || !iocContainer.TryGet(out _validationElementProvider))
         {
             return(false);
         }
     }
     return(_validationElementProvider.GetValidationElements(validatorContext.Instance).Count > 0);
 }
Ejemplo n.º 13
0
        private IValidatorResult RelativityBillingCaseStatisticsTableUpdated(IValidatorContext validatorContext)
        {
            log.Debug("BillingValidator: Running {testName} billing check.", CaseStatisticsTableUpdated);

            return(CheckRelativityDbValueNotUpdated(validatorContext,
                                                    CaseStatisticsTableUpdated,
                                                    () =>
            {
                DateTime dateToCheck = this.GetBillingRunDate(this._billingSettings.BillingRunTime);
                CaseStatistics caseStatistics = _relBillingRepo.GetCaseStatistics(dateToCheck.Date).FirstOrDefault();
                return caseStatistics == null;
            }));
        }
Ejemplo n.º 14
0
        public IList <IValidatorResult> Execute(IValidatorContext context)
        {
            log.Debug("BillingValidator: BillingValidator beginning validation.");

            List <IValidatorResult> validatorResults = new List <IValidatorResult>();

            validatorResults.Add(this.RelativityBillingCaseStatisticsMonthlyTableUpdated(context));
            validatorResults.Add(this.RelativityBillingCaseStatisticsTableUpdated(context));
            validatorResults.Add(this.RelativityProviderDataCollectionRunsTableUpdated(context));
            validatorResults.Add(this.RelativityProviderUserCollectionRunsTableUpdated(context));

            return(validatorResults);
        }
Ejemplo n.º 15
0
        private IValidatorResult RelativityProviderUserCollectionRunsTableUpdated(IValidatorContext validatorContext)
        {
            log.Debug("BillingValidator: Running {testName} billing check.", UserCollectionRunsTableUpdated);

            return(CheckRelativityDbValueNotUpdated(validatorContext,
                                                    UserCollectionRunsTableUpdated,
                                                    () =>
            {
                DateTime dateToCheck = this.GetBillingRunDate(this._billingSettings.BillingRunTime);
                UserCollectionsRuns userCollectionRun = this._relProvidersRepo.GetUserCollectionsRuns(dateToCheck.Date).FirstOrDefault();
                return userCollectionRun == null;
            }));
        }
        public IList<IValidatorResult> Execute(IValidatorContext context)
        {
            log.Info("SuccessValidator Execute started");

            List<IValidatorResult> validatorResults = new List<IValidatorResult>();

            var vr = new ValidatorResult(this.ValidatorProxyId, "SuccessValidator always returns result code of success ", ValidatorResultCode.Success , "SuccessValidator");
            validatorResults.Add(vr);

            log.Info("Starting SuccessValidator Execute completed with {ResultCount} results", validatorResults.Count);

            return validatorResults;
        }
Ejemplo n.º 17
0
        /// <inheritdoc cref="NotNull{T}(ZySharp.Validation.IValidatorContext{T})"/>
        public static IValidatorContext <T?> NotNull <T>(this IValidatorContext <T?> validator)
            where T : struct
        {
            ValidationInternals.ValidateNotNull(validator, nameof(validator));

            if (!validator.Value.HasValue)
            {
                throw new ArgumentNullException(validator.Path.First(), string.Format(CultureInfo.InvariantCulture,
                                                                                      Resources.ArgumentMustNotBeNull, ValidationInternals.FormatName(validator.Path, null)));
            }

            return(validator);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Performs validations after projecting the current value to a new type.
        /// </summary>
        /// <typeparam name="T">The type of the current value.</typeparam>
        /// <typeparam name="TNew">The type of the projected value.</typeparam>
        /// <param name="validator">The current validator context.</param>
        /// <param name="selector">The selector lambda.</param>
        /// <param name="action">The action to perform with the projected value.</param>
        /// <returns>The unmodified validator context.</returns>
        public static IValidatorContext <T> Select <T, TNew>(this IValidatorContext <T> validator, Func <T, TNew> selector,
                                                             Action <IValidatorContext <TNew> > action)
        {
            ValidationInternals.ValidateNotNull(validator, nameof(validator));
            ValidationInternals.ValidateNotNull(selector, nameof(selector));
            ValidationInternals.ValidateNotNull(action, nameof(action));

            var context = new ValidatorContext <TNew>(selector.Invoke(validator.Value), validator.Path, null);

            action.Invoke(context);

            return(validator);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Throws if the current value is empty (contains the default value of the current type).
        /// </summary>
        /// <typeparam name="T">The type of the current value.</typeparam>
        /// <param name="validator">The current validator context.</param>
        /// <returns>The unmodified validator context.</returns>
        public static IValidatorContext <T> NotEmpty <T>(this IValidatorContext <T> validator)
            where T : struct
        {
            ValidationInternals.ValidateNotNull(validator, nameof(validator));

            if (validator.Value.Equals(default(T)))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
                                                          Resources.ArgumentMustNotBeEmpty, ValidationInternals.FormatName(validator.Path, null)),
                                            validator.Path.First());
            }

            return(validator);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Performs validations if a user-defined condition is met.
        /// </summary>
        /// <typeparam name="T">The type of the current value.</typeparam>
        /// <param name="validator">The current validator context.</param>
        /// <param name="predicate">The filter predicate.</param>
        /// <param name="action">The action to perform if the condition is met.</param>
        /// <returns>The unmodified validator context.</returns>
        public static IValidatorContext <T> When <T>(this IValidatorContext <T> validator, Func <T, bool> predicate,
                                                     Action <IValidatorContext <T> > action)
        {
            ValidationInternals.ValidateNotNull(validator, nameof(validator));
            ValidationInternals.ValidateNotNull(predicate, nameof(predicate));
            ValidationInternals.ValidateNotNull(action, nameof(action));

            if (predicate(validator.Value))
            {
                action.Invoke(validator);
            }

            return(validator);
        }
Ejemplo n.º 21
0
        public override IEnumerable <ValidationResult> Validate(IValidatorContext <IEntity> context)
        {
            var results = new List <ValidationResult>();

            try
            {
                var ctx = new ValidationContext(context.Entity, _serviceProvider, null);
                // even though this says Try, and therefore it should not throw an error, IT DOES when a given property is not part of Entity
                Validator.TryValidateObject(context.Entity, ctx, results, true);
            }
            catch { }

            return(results);
        }
Ejemplo n.º 22
0
        protected virtual void AddInstanceInternal(object instanceToValidate)
        {
            if (_instanceToValidators.ContainsKey(instanceToValidate))
            {
                RemoveInstanceInternal(instanceToValidate);
            }
            IValidatorContext  context    = CreateContext(instanceToValidate);
            IList <IValidator> validators = ValidatorProvider.GetValidators(context);

            for (int index = 0; index < validators.Count; index++)
            {
                AddValidatorInternal(validators[index]);
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Throws if the uri does not contain an absolute uri.
        /// </summary>
        /// <typeparam name="T">The type of the current value.</typeparam>
        /// <param name="validator">The current validator context.</param>
        /// <returns>The unmodified validator context.</returns>
        public static IValidatorContext <T> Absolute <T>(this IValidatorContext <T> validator)
            where T : Uri
        {
            ValidationInternals.ValidateNotNull(validator, nameof(validator));

            if (!validator.Value.IsAbsoluteUri)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
                                                          Resources.UriMustBeAbsolute, ValidationInternals.FormatName(validator.Path, null)),
                                            validator.Path.First());
            }

            return(validator);
        }
Ejemplo n.º 24
0
        public IList <IValidatorResult> Execute(IValidatorContext context)
        {
            log.Info("WarningValidator Execute started");

            List <IValidatorResult> validatorResults = new List <IValidatorResult>();

            var vr = new ValidatorResult(this.ValidatorProxyId, "WarningValidator always returns result code of warning ", ValidatorResultCode.Warning, "WarningValidator");

            validatorResults.Add(vr);

            log.Info("Starting WarningValidator Execute completed with {ResultCount} results", validatorResults.Count);

            return(validatorResults);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Throws if the stream is not seekable.
        /// </summary>
        /// <typeparam name="T">The type of the current value.</typeparam>
        /// <param name="validator">The current validator context.</param>
        /// <returns>The unmodified validator context.</returns>
        public static IValidatorContext <T> Seekable <T>(this IValidatorContext <T> validator)
            where T : Stream
        {
            ValidationInternals.ValidateNotNull(validator, nameof(validator));

            if (!validator.Value.CanSeek)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
                                                          Resources.StreamMustBeSeekable, ValidationInternals.FormatName(validator.Path, null)),
                                            validator.Path.First());
            }

            return(validator);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Throws if the current value is not less than or equal to the given threshold.
        /// </summary>
        /// <typeparam name="T">The type of the current value.</typeparam>
        /// <param name="validator">The current validator context.</param>
        /// <param name="threshold">The threshold value.</param>
        /// <returns>The unmodified validator context.</returns>
        public static IValidatorContext <T> LessThanOrEqualTo <T>(this IValidatorContext <T> validator, T threshold)
            where T : struct, IComparable <T>
        {
            ValidationInternals.ValidateNotNull(validator, nameof(validator));

            if (validator.Value.CompareTo(threshold) > 0)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
                                                          Resources.ArgumentMustBeGreaterThan, ValidationInternals.FormatName(validator.Path, null), threshold),
                                            validator.Path.First());
            }

            return(validator);
        }
Ejemplo n.º 27
0
        public void CreateContextShouldCreateContextWithDefaultValuesFromVm()
        {
            var obj = new object();
            ValidatableViewModel viewModel = GetValidatableViewModel();
            IViewModel           vm        = viewModel;

            IValidatorContext validatorContext = viewModel.CreateContext(obj);

            validatorContext.ServiceProvider.ShouldEqual(vm.IocContainer);
            validatorContext.ValidationMetadata.ShouldEqual(viewModel.Settings.Metadata);
            validatorContext.PropertyMappings.ShouldEqual(viewModel.PropertyMappings);
            validatorContext.IgnoreProperties.ShouldEqual(viewModel.IgnoreProperties);
            validatorContext.Instance.ShouldEqual(obj);
            validatorContext.ServiceProvider.ShouldEqual(vm.IocContainer);
        }
        public IList <IValidatorResult> Execute(IValidatorContext context)
        {
            log.Info("LongRunningValidator Execute started");

            List <IValidatorResult> validatorResults = new List <IValidatorResult>();

            string message = string.Format("Long Running validator is configured to run for {0} minutes and return result code of success.", _settings.RunTimeInMinutes);
            var    vr      = new ValidatorResult(this.ValidatorProxyId, message, ValidatorResultCode.Error, "LongRunningValidator");

            validatorResults.Add(vr);

            log.Info("Starting LongRunningValidator Execute completed with {ResultCount} results", validatorResults.Count);

            return(validatorResults);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Throws if the current value is equal to one of the blacklisted values.
        /// </summary>
        /// <typeparam name="T">The type of the current value.</typeparam>
        /// <param name="validator">The current validator context.</param>
        /// <param name="values">The blacklisted values.</param>
        /// <returns>The unmodified validator context.</returns>
        public static IValidatorContext <T> NotEqual <T>(this IValidatorContext <T> validator, params T[] values)
        {
            ValidationInternals.ValidateNotNull(validator, nameof(validator));

            var isValidValue = values.All(x => !EqualityComparer <T> .Default.Equals(validator.Value, x));

            if (!isValidValue)
            {
                throw new ArgumentNullException(validator.Path.First(), string.Format(CultureInfo.InvariantCulture,
                                                                                      Resources.ArgumentMustNotBeOneOf, ValidationInternals.FormatName(validator.Path, null),
                                                                                      string.Join(", ", values.Select(x => $"'{x}'").ToList())));
            }

            return(validator);
        }
Ejemplo n.º 30
0
        IEnumerable <ValidationResult> IEntityValidator.Validate(IValidatorContext context)
        {
            _context = context;

            var result = Validate((TEntity)context.Entity);

            if (result.IsValid)
            {
                return(Enumerable.Empty <ValidationResult>());
            }
            else
            {
                return(result.Errors.Select(error => new ValidationResult(error.ErrorMessage, new[] { error.PropertyName })));
            }
        }
 public IList<IValidator> GetValidators(IValidatorContext context)
 {
     Should.NotBeNull(context, nameof(context));
     var validators = new List<IValidator>();
     var instanceType = context.Instance.GetType();
     lock (_validators)
     {
         foreach (var type in _validators)
         {
             if (!type.Value.IsAssignableFrom(instanceType))
                 continue;
             var validator = GetValidator(type.Key, context);
             if (validator != null)
                 validators.Add(validator);
         }
         return validators;
     }
 }