/// <summary>
        /// Validates the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>IEnumerable{ValidationFailure}.</returns>
        public override IEnumerable <ValidationFailure> Validate([NotNull] PropertyValidatorContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // bail out if the property is null
            if (context.PropertyValue == null || !(context.PropertyValue is T value))
            {
                return(Enumerable.Empty <ValidationFailure>());
            }

            var validator = _validatorFactory.GetValidator(value.GetType());

            if (context.ParentContext.IsChildCollectionContext)
            {
                return(validator.Validate(context.ParentContext.CloneForChildValidator(value)).Errors);
            }

            var validationContext = new ValidationContext <T>(
                value,
                PropertyChain.FromExpression(context.Rule.Expression),
                context.ParentContext.Selector
                );

            validationContext.SetServiceProvider(_serviceProvider);
            return(validator.Validate(validationContext).Errors);
        }
        public void CreateTestMasterMapping(TestMasterMapping testMasterMapping)
        {
            var validator = validatorFactory.GetValidator <TestMasterMapping>();

            validator.ValidateAndThrow(testMasterMapping);
            testMasterMappingRepositry.Add(testMasterMapping);
        }
        void ITestMasterService.CreateTestMaster(TestMaster testMaster)
        {
            var validator = validatorFactory.GetValidator <TestMaster>();

            validator.ValidateAndThrow(testMaster);
            testMasterRepository.Add(testMaster);
        }
Esempio n. 4
0
 public PublisherService(IUnitOfWork unitOfWork, IValidatorFactory validatorFactory, ILogger logger)
 {
     _unitOfWork = unitOfWork;
     _logger     = logger;
     _createUpdatePublisherValidator = validatorFactory.GetValidator <CreateUpdatePublisherInput>();
     _getDeletePublisherValidator    = validatorFactory.GetValidator <GetDeletePublisherInput>();
 }
        public async Task <IOperationResult <Product> > CreateAsync(Product entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            var validator       = _validatorFactory.GetValidator <CreateProductValidator>();
            var validatorResult = validator.Validate(entity);

            if (!validatorResult.Succeeded)
            {
                return(OperationResult <Product> .Failed(validatorResult.Errors.ToArray()));
            }

            Product repositoryResult;

            var userId = _authenticationService.GetUserId();

            try
            {
                repositoryResult = await _productRepository.CreateAsync(entity, userId);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "An error occured");
                return(OperationResult <Product> .Failed(new OperationError()
                {
                    Name = "Repository",
                    Description = e.Message
                }));
            }

            return(OperationResult <Product> .Success(repositoryResult));
        }
Esempio n. 6
0
 public CommentService(IUnitOfWork unitOfWork, IValidatorFactory validatorFactory, ILogger logger)
 {
     _unitOfWork = unitOfWork;
     _logger     = logger;
     _createUpdateCommentValidator = validatorFactory.GetValidator <CreateUpdateCommentInput>();
     _getDeleteCommentValidator    = validatorFactory.GetValidator <GetDeleteCommentInput>();
     _getDeleteGameValidator       = validatorFactory.GetValidator <GetDeleteGameInput>();
 }
 protected virtual IValidator CreateValidator(ModelValidatorProviderContext context)
 {
     if (IsValidatingProperty(context))
     {
         return(_ValidatorFactory.GetValidator(context.ModelMetadata.ContainerType));
     }
     return(_ValidatorFactory.GetValidator(context.ModelMetadata.ModelType));
 }
Esempio n. 8
0
        public GameService(IUnitOfWork unitOfWork, IValidatorFactory validatorFactory, ILogger logger)
        {
            _unitOfWork = unitOfWork;

            _logger = logger;
            _createUpdateGameValidator      = validatorFactory.GetValidator <CreateUpdateGameInput>();
            _getDeleteGameValidator         = validatorFactory.GetValidator <GetDeleteGameInput>();
            _getDeleteGenreValidator        = validatorFactory.GetValidator <GetDeleteGenreInput>();
            _getDeletePlatformTypeValidator = validatorFactory.GetValidator <GetDeletePlatformTypeInput>();
        }
Esempio n. 9
0
        public bool IsValid <T>(T item)
        {
            var validator = ValidatorFactory.GetValidator(typeof(T));

            if (validator != null)
            {
                return(validator.Validate(item).IsValid);
            }

            return(true);
        }
Esempio n. 10
0
        public TResult Query <TResult>(IQuery <TResult> query)
        {
            var validator = _factory.GetValidator(query.GetType());
            var result    = validator?.Validate(query);

            if ((result != null) && !result.IsValid)
            {
                throw new ValidationException(result.Errors);
            }

            return(_inner.Query(query));
        }
Esempio n. 11
0
 private void Validate <TRequest>(TRequest request)
     where TRequest : ApiRequest
 {
     _validators
     .GetValidator(request.GetType())
     .ThrowIf(request);
 }
Esempio n. 12
0
        public ActionResult Creation(UpdateUserViewModel user)
        {
            var validator = _validatorFactory.GetValidator <UpdateUserViewModel>();
            var result    = validator.Validate(user);

            if (result.IsValid)
            {
                if (user.UserId != 0)
                {
                    _userService.Update(Mapper.Map <UpdateUserViewModel, UserDto>(user));
                }
                else
                {
                    _userService.Add(Mapper.Map <UpdateUserViewModel, UserDto>(user));
                }

                return(RedirectToAction("Index"));
            }
            else
            {
                SetErrorsInModelState(result.Errors);
                InitializeDictionary(user);

                return(View(user));
            }
        }
        public void CreateValidators(ClientValidatorProviderContext context)
        {
            var modelType = context.ModelMetadata.ContainerType;

            if (modelType != null)
            {
                var validator = _validatorFactory.GetValidator(modelType);

                if (validator != null)
                {
                    var descriptor   = validator.CreateDescriptor();
                    var propertyName = context.ModelMetadata.PropertyName;

                    var validatorsWithRules = from rule in descriptor.GetRulesForMember(propertyName)
                                              let propertyRule = (PropertyRule)rule
                                                                 let validators = rule.Validators
                                                                                  where validators.Any()
                                                                                  from propertyValidator in validators
                                                                                  let modelValidatorForProperty = GetModelValidator(context, propertyRule, propertyValidator)
                                                                                                                  where modelValidatorForProperty != null
                                                                                                                  select modelValidatorForProperty;

                    foreach (var propVal in validatorsWithRules)
                    {
                        context.Results.Add(new ClientValidatorItem {
                            Validator  = propVal,
                            IsReusable = false
                        });
                    }
                }
            }
        }
        public ReflectionBasedValidator(IValidatorFactory validatorFactory)
        {
            if (validatorFactory == null)
            {
                throw new ArgumentNullException(nameof(validatorFactory));
            }

            foreach (var property in typeof(T).GetProperties( ))
            {
                if (!property.CanRead)
                {
                    continue;
                }

                var validator = validatorFactory.GetValidator(property.PropertyType);
                if (validator == null)
                {
                    continue;
                }

                var rule = new PropertyRule(property,
                                            NonGenericExpression(property).Compile( ),
                                            GenericExpression(property),
                                            () => ValidatorOptions.Global.CascadeMode,
                                            property.PropertyType,
                                            typeof(T));

                var adaptorType = typeof(ChildValidatorAdaptor <, >).MakeGenericType(typeof(T), property.PropertyType);

                rule.AddValidator((IPropertyValidator)Activator.CreateInstance(adaptorType, validator, validator.GetType( )));

                AddRule(rule);
            }
        }
Esempio n. 15
0
        public sealed override void OnActionExecuting(FilterContext filterContext)
        {
            IValidatorFactory factory = Container.Resolve <IValidatorFactory>();

            foreach (KeyValuePair <Type, object> p in filterContext.ServiceArguments)
            {
                Type type = p.Key;

                if (type.IsClass && !type.FullName.StartsWith("System.") && typeof(List <ServerFile>) != type)
                {
                    IValidator validator = factory.GetValidator(type);
                    if (validator != null)
                    {
                        if (p.Value != null)
                        {
                            ValidationResult result = validator.Validate(p.Value);
                            if (!result.IsValid)
                            {
                                ValidationFailure error = result.Errors.First();
                                filterContext.Result = ValidateModel(error);
                            }
                        }
                    }
                }
            }
        }
        IEnumerable <Attribute> ConvertFVMetaDataToAttributes(Type type, string name)
        {
            var validator = factory.GetValidator(type);

            if (validator == null)
            {
                return(Enumerable.Empty <Attribute>());
            }

            IEnumerable <IPropertyValidator> validators;

//			if (name == null) {
            //validators = validator.CreateDescriptor().GetMembersWithValidators().SelectMany(x => x);
//				validators = Enumerable.Empty<IPropertyValidator>();
//			}
//			else {
            validators = validator.CreateDescriptor().GetValidatorsForMember(name);
//			}

            var attributes = validators.OfType <IAttributeMetadataValidator>()
                             .Select(x => x.ToAttribute())
                             .Concat(SpecialCaseValidatorConversions(validators));



            return(attributes.ToList());
        }
Esempio n. 17
0
        public ValidationResult Validate <T>(T item) where T : class
        {
            var validator = _validatorFactory.GetValidator(item.GetType());
            var result    = validator.Validate(item);

            return(result);
        }
        public virtual async Task Store <TAggregate>(TAggregate aggregate, Func <StreamState, Task> action = null) where TAggregate : IAggregate
        {
            var events         = aggregate.DequeueUncommittedEvents();
            var initialVersion = aggregate.Version - events.Count();

            foreach (var @event in events)
            {
                initialVersion++;

                var validator = _validationFactory.GetValidator(@event.GetType());
                var result    = validator?.Validate(new ValidationContext <IEvent>(@event));
                if (result != null && !result.IsValid)
                {
                    continue;
                }

                await AppendEvent <TAggregate>(aggregate.Id, @event, initialVersion, action);

                foreach (var projection in projections.Where(
                             projection => projection.Handles.Contains(@event.GetType())))
                {
                    projection.Handle(@event);
                }
            }

            snapshots
            .FirstOrDefault(snapshot => snapshot.Handles == typeof(TAggregate))?
            .Handle(aggregate);
        }
Esempio n. 19
0
        protected ValidationResult Validate(IValidatorFactory factory, Type modelType, object model)
        {
            IValidationContext context = new ValidationContext <object>(model);
            var result = factory.GetValidator(modelType)?.Validate(context);

            return(result);
        }
Esempio n. 20
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var typeName = request.GetType().Name;

            _logger.LogInformation("----- Validating command {CommandType}", typeName);

            IValidator <TRequest> validator = _validatorFactory.GetValidator <TRequest>();

            if (validator != null)
            {
                var result = validator.Validate(request);
                if (!result.IsValid)
                {
                    var failures = result.Errors;
                    var sb       = new StringBuilder();
                    if (failures.Any())
                    {
                        _logger.LogWarning("Validation errors - {CommandType} - Command: {@Command} - Errors: {@ValidationErrors}", typeName, request, failures);

                        failures.ToList()
                        .ForEach(x => sb.AppendLine(x.ErrorMessage));

                        throw new Exception(sb.ToString());
                    }
                }
            }

            return(await next());
        }
Esempio n. 21
0
        public ValidationResult Validate <T>(T entity) where T : class
        {
            var validator = _validatorFactory.GetValidator(entity.GetType());
            var result    = validator.Validate(entity);

            return(result);
        }
        /// <inheritdoc />
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            if (_validatorFactory == null)
            {
                _logger.LogWarning(0, "ValidatorFactory is not provided. Please register FluentValidation.");
                return;
            }

            IValidator validator = null;

            try
            {
                validator = _validatorFactory.GetValidator(context.Type);
            }
            catch (Exception e)
            {
                _logger.LogWarning(0, e, $"GetValidator for type '{context.Type}' fails.");
            }

            if (validator == null)
            {
                return;
            }

            ApplyRulesToSchema(schema, context, validator);

            try
            {
                AddRulesFromIncludedValidators(schema, context, validator);
            }
            catch (Exception e)
            {
                _logger.LogWarning(0, e, $"Applying IncludeRules for type '{context.Type}' fails.");
            }
        }
Esempio n. 23
0
        public IEnumerable <Post> GetPosts(int limit)
        {
            var posts     = new List <Post>();
            var validator = _validatorFactory.GetValidator <Post>();

            // Get ids of top stories
            var ids = _httpClientWrapper.Get <List <int> >(TopStoriesUri).GetRange(0, limit);

            // Load each item
            for (int i = 0; i < ids.Count; i++)
            {
                //TODO: make this async and run in parallel
                var item = _httpClientWrapper.Get <HackerNewsItem>($"{ItemBaseUrl}/{ids[i]}.json");

                // Map to post - could use Automapper here but it's easier to do it manually here with the index/ranking
                var post = new Post()
                {
                    Author   = item.By,
                    Comments = item.Descendants,
                    Points   = item.Score,
                    Rank     = i + 1, //Items are already sorted when we retrieve them
                    Title    = item.Title,
                    Uri      = item.Url
                };

                // Add only if pass validation
                if (validator.Validate(post).IsValid)
                {
                    posts.Add(post);
                }
            }

            return(posts);
        }
Esempio n. 24
0
        public virtual void Execute(TCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            var validator = _validatorFactory.GetValidator <TCommand>();

            if (validator != null)
            {
                var result = validator.Validate(command);

                if (result == null)
                {
                    throw new ValidationException("Validation failed");
                }

                if (!result.IsValid)
                {
                    throw new ValidationException(result.Errors);
                }
            }

            RunCommand(command);
        }
        public async Task ValidateAsync <T>(T model)
        {
            var validator = _validatorFactory.GetValidator <T>();

            await InvokePhases(validator, model, "Phase 1");
            await InvokePhases(validator, model, "Phase 2");
        }
        private static async Task <ValidationResult> InternalValidateAsync(object model)
        {
            var validator = ValidatorFactory.GetValidator(model.GetType());

            if (null == validator)
            {
                throw new InvalidOperationException("Validator for model " + model.GetType().FullName + " not found!");
            }
            var result = await validator.ValidateAsync(model);

            if (!ValidationCache.TryGetValue(model, out var tmp))
            {
                ValidationCache.Add(model, result);
            }
            return(result);
        }
Esempio n. 27
0
        private async Task ValidateEntries(CancellationToken cancellationToken = default)
        {
            if (_validatorFactory == null)
            {
                return;
            }

            var addedOrModifiedEntries = ChangeTracker.Entries()
                                         .Where(x => x.State == EntityState.Added || x.State == EntityState.Modified)
                                         .ToList();

            foreach (var entry in addedOrModifiedEntries)
            {
                var validator = _validatorFactory.GetValidator(entry.Metadata.ClrType);
                if (validator == null)
                {
                    continue;
                }
                var validationContext = ValidationContext <object> .CreateWithOptions(entry.Entity, options => options.IncludeRuleSets(RuleSetNames.All));

                var validationResult = await validator.ValidateAsync(validationContext, cancellationToken);

                if (validationResult.IsValid == false)
                {
                    throw new ValidationException(validationResult.Errors);
                }
            }
        }
Esempio n. 28
0
        private void NullifyInvalidFieldAttributes(IValidatorFactory validatorFactory)
        {
            var validator = validatorFactory.GetValidator(GetType());

            if (validator == null)
            {
                return;
            }

            var result = validator.Validate(this);

            foreach (var property in GetProperties(this))
            {
                var attribute = EntityFieldAttribute(property);

                if (attribute == null)
                {
                    continue;
                }

                if (result.Errors.Any(e => e.PropertyName == property.Name))
                {
                    property.SetValue(this, null);
                }
            }
        }
        public CorporateRegisterController(INotificationManager notificationManager, IStoreService storeService,
                                           IMemberService memberService, IRoleManagementService roleService, ISecurityService securityService,
                                           IValidatorFactory validatorFactory) : base(securityService)
        {
            _notificationManager = notificationManager;
            _storeService        = storeService;
            _memberService       = memberService;
            _roleService         = roleService;
            _securityService     = securityService;

            _companyOwnerRegistrationDataValidator          = validatorFactory.GetValidator <CompanyOwnerRegistrationData>();
            _companyMemberRegistrationDataValidator         = validatorFactory.GetValidator <CompanyMemberRegistrationData>();
            _companyMemberRegistrationByInviteDataValidator = validatorFactory.GetValidator <CompanyMemberRegistrationByInviteData>();

            _inviteValidator     = validatorFactory.GetValidator <Invite>();
            _inviteDataValidator = validatorFactory.GetValidator <InviteData>();
        }
Esempio n. 30
0
        public void Validate(ActionContext actionContext, IModelValidatorProvider validatorProvider,
                             ValidationStateDictionary validationState, string prefix, object model)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException(nameof(actionContext));
            }

            // would model ever be null ??

            if (model == null)
            {
                return;
            }

            // get our IValidator

            var validator = _validatorFactory.GetValidator(model.GetType());

            if (validator == null)
            {
                return;
            }

            foreach (var value in actionContext.ModelState.Values
                     .Where(v => v.ValidationState == ModelValidationState.Unvalidated))
            {
                // Set all unvalidated states to valid. If we end up adding an error below then that properties state
                // will become ModelValidationState.Invalid and will set ModelState.IsValid to false

                value.ValidationState = ModelValidationState.Valid;
            }



            // validate the model using Fluent Validation rules

            var result = validator.Validate(model);

            // add all our model errors to the modelstate

            if (!string.IsNullOrEmpty(prefix))
            {
                prefix = prefix + ".";
            }

            foreach (var modelError in result.Errors)
            {
                // See if there's already an item in the ModelState for this key.
                if (actionContext.ModelState.ContainsKey(modelError.PropertyName))
                {
                    actionContext.ModelState[modelError.PropertyName].Errors.Clear();
                }


                actionContext.ModelState.AddModelError(prefix + modelError.PropertyName, modelError.ErrorMessage);
            }
        }