コード例 #1
0
 private static void ValidateSpecialProperties(string name, ValidationContext <Property> cntx, Property p, Catalog c, IGroupListCatalogs gc)
 {
     if (c.GetUseCodeProperty())
     {
         if (gc.PropertyCodeName == name)
         {
             var vf = new ValidationFailure(nameof(p.Name),
                                            $"Catalog parameter 'UseCodeProperty' is set to 'true'. Property name '{gc.PropertyCodeName}' is reserved for auto generated property");
             vf.Severity = Severity.Error;
             cntx.AddFailure(vf);
         }
     }
     if (c.GetUseNameProperty())
     {
         if (gc.PropertyNameName == name)
         {
             var vf = new ValidationFailure(nameof(p.Name),
                                            $"Catalog parameter 'UseNameProperty' is set to 'true'. Property name '{gc.PropertyNameName}' is reserved for auto generated property");
             vf.Severity = Severity.Error;
             cntx.AddFailure(vf);
         }
     }
     if (c.GetUseDescriptionProperty())
     {
         if (gc.PropertyDescriptionName == name)
         {
             var vf = new ValidationFailure(nameof(p.Name),
                                            $"Catalog parameter 'UseDescriptionProperty' is set to 'true'. Property name '{gc.PropertyDescriptionName}' is reserved for auto generated property");
             vf.Severity = Severity.Error;
             cntx.AddFailure(vf);
         }
     }
 }
コード例 #2
0
        private static void CheckObjectsWithDbTables(ValidationContext <Model> cntx, string recom, Model m, bool isCheckTabs)
        {
            var dic = new Dictionary <string, ITreeConfigNode>();

            foreach (var t in m.GroupCatalogs.ListCatalogs)
            {
                if (string.IsNullOrWhiteSpace(t.CompositeName))
                {
                    continue;
                }
                if (dic.ContainsKey(t.CompositeName))
                {
                    var sb = GenMessage(dic, t, t.CompositeName);
                    sb.Append("'.");
                    sb.Append(recom);
                    cntx.AddFailure(sb.ToString());
                }
                else
                {
                    dic[t.CompositeName] = t;
                }
                if (isCheckTabs)
                {
                    CheckTabs(cntx, dic, t.GroupPropertiesTabs, recom);
                }
            }
            foreach (var t in m.GroupDocuments.GroupListDocuments.ListDocuments)
            {
                if (string.IsNullOrWhiteSpace(t.CompositeName))
                {
                    continue;
                }
                if (dic.ContainsKey(t.CompositeName))
                {
                    var sb = GenMessage(dic, t, t.CompositeName);
                    sb.Append("'.");
                    sb.Append(recom);
                    cntx.AddFailure(sb.ToString());
                }
                else
                {
                    dic[t.CompositeName] = t;
                }
                if (isCheckTabs)
                {
                    CheckTabs(cntx, dic, t.GroupPropertiesTabs, recom);
                }
            }
        }
コード例 #3
0
        private void ValidateUserDisplayName(string displayName, ValidationContext <CreateUserProfileCommand> context)
        {
            // Checks whether the display name is not null, empty or contains only white spaces.
            if (string.IsNullOrWhiteSpace(displayName))
            {
                context.AddFailure("The display name must not be null or empty.");
                return;
            }

            // Checks whether the display name does not exceed 64 characters.
            if (displayName.Length > 30)
            {
                context.AddFailure("The display name must not exceed 64 characters.");
            }
        }
コード例 #4
0
        public static void AddValidationResults(ValidationContext <AppProjectGenerator> cntx, List <ValidationPluginMessage> lst)
        {
            foreach (var t in lst)
            {
                var r = new ValidationFailure(cntx.PropertyName, t.Message);
                switch (t.Level)
                {
                case ValidationPluginMessage.EnumValidationMessage.Error:
                    r.Severity = Severity.Error;
                    break;

                case ValidationPluginMessage.EnumValidationMessage.Warning:
                    r.Severity = Severity.Warning;
                    break;

                case ValidationPluginMessage.EnumValidationMessage.Info:
                    r.Severity = Severity.Info;
                    break;

                default:
                    throw new Exception();
                }
                cntx.AddFailure(r);
            }
        }
コード例 #5
0
        private static bool MatchChecksums(RomToProjectAssociation container, Project?project,
                                           ValidationContext <RomToProjectAssociation> validationContext)
        {
            if (project?.Data == null)
            {
                return(false);
            }

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

            var checksumToVerify =
                ByteUtil.ConvertByteArrayToUInt32(container.RomBytes, project.Data.RomComplementOffset);

            if (checksumToVerify == project.InternalCheckSum)
            {
                return(true);
            }

            validationContext.AddFailure($"The linked ROM's checksums '{checksumToVerify:X8}' " +
                                         $"doesn't match the project's checksums of '{project.InternalCheckSum:X8}'.");
            return(false);
        }
コード例 #6
0
 private void ValidateBucketName(string input, ValidationContext <T> context)
 {
     if (!_validator.TryValidateBucketName(input, _cfg.BucketNameValidationMode, out ValidationStatus status, out string?allowed))
     {
         context.AddFailure("Invalid bucket name: " + ValidationMessages.GetMessage(status, allowed));
     }
 }
コード例 #7
0
 private void ValidateObjectKey(string input, ValidationContext <T> context)
 {
     if (!_validator.TryValidateObjectKey(input, _cfg.ObjectKeyValidationMode, out ValidationStatus status, out string?allowed))
     {
         context.AddFailure("Invalid object key: " + ValidationMessages.GetMessage(status, allowed));
     }
 }
コード例 #8
0
ファイル: AccessKeyValidator.cs プロジェクト: Genbox/SimpleS3
 private void ValidateKeyId(string input, ValidationContext <IAccessKey> context)
 {
     if (!_inputValidator.TryValidateKeyId(input, out ValidationStatus status, out string?allowed))
     {
         context.AddFailure("Invalid key id: " + ValidationMessages.GetMessage(status, allowed));
     }
 }
コード例 #9
0
ファイル: AccessKeyValidator.cs プロジェクト: Genbox/SimpleS3
 private void ValidateSecretKey(byte[] input, ValidationContext <IAccessKey> context)
 {
     if (!_inputValidator.TryValidateAccessKey(input, out ValidationStatus status, out string?allowed))
     {
         context.AddFailure("Invalid secret key: " + ValidationMessages.GetMessage(status, allowed));
     }
 }
コード例 #10
0
        /// <inheritdoc/>
        public override bool IsValid(ValidationContext <WorkflowDefinition> context, List <StateDefinition> value)
        {
            var index = 0;

            foreach (var state in value)
            {
                if (!StateValidatorTypes.TryGetValue(state.GetType(), out var validatorTypes))
                {
                    continue;
                }
                var validators = validatorTypes !.Select(t => (IValidator)Activator.CreateInstance(t, (WorkflowDefinition)context.InstanceToValidate) !);
                foreach (IValidator validator in validators)
                {
                    var args             = new object[] { state };
                    var validationMethod = typeof(IValidator <>).MakeGenericType(state.GetType())
                                           .GetMethods()
                                           .Single(m =>
                                                   m.Name == nameof(IValidator.Validate) &&
                                                   m.GetParameters().Length == 1 &&
                                                   m.GetParameters().First().ParameterType != typeof(IValidationContext));
                    var validationResult = (ValidationResult)validationMethod.Invoke(validator, args) !;
                    if (validationResult.IsValid)
                    {
                        continue;
                    }
                    foreach (var failure in validationResult.Errors)
                    {
                        context.AddFailure(failure);
                    }
                    return(false);
                }
                index++;
            }
            return(true);
        }
コード例 #11
0
        /// <inheritdoc/>
        public override bool IsValid(ValidationContext <WorkflowDefinition> context, IEnumerable <TElement>?value)
        {
            int index = 0;

            if (value == null)
            {
                return(true);
            }
            foreach (TElement elem in value)
            {
                IEnumerable <IValidator <TElement> > validators = this.ServiceProvider.GetServices <IValidator <TElement> >();
                foreach (IValidator <TElement> validator in validators)
                {
                    ValidationResult validationResult = validator.Validate(elem);
                    if (validationResult.IsValid)
                    {
                        continue;
                    }
                    foreach (var failure in validationResult.Errors)
                    {
                        context.AddFailure(failure);
                    }
                    return(false);
                }
                index++;
            }
            return(true);
        }
コード例 #12
0
 private void ValidateMethod(string value, ValidationContext <TestStringModel> ctx)
 {
     if (UnallowedValues.Contains(value, StringComparer.InvariantCultureIgnoreCase))
     {
         ctx.AddFailure("Value is not allowed");
     }
 }
コード例 #13
0
        private async Task CheckUserIdUniquenessAsync(Guid proposedUserId, ValidationContext <CreateUserProfileCommand> context, CancellationToken cancellationToken)
        {
            // Checks whether the user id is empty.
            if (proposedUserId == Guid.Empty)
            {
                context.AddFailure("The user id can not be empty.");
                return;
            }
            // Checks whether the user id already exists.
            UserProfileAggregate userAggregate = await _userRepository.GetAsync(proposedUserId, cancellationToken);

            if (userAggregate != default)
            {
                context.AddFailure("A user with the proposed user id already exists.");
                return;
            }
        }
コード例 #14
0
 private void CheckUserIdExistsAsync(Guid proposedId, ValidationContext <CreateKweetCommand> context)
 {
     // Checks whether the user id is empty.
     if (proposedId == Guid.Empty)
     {
         context.AddFailure("The user id can not be empty.");
         return;
     }
 }
コード例 #15
0
        private async Task <bool> ValidateUserAsync(CreateAccountCommand cmd, long userId,
                                                    ValidationContext <CreateAccountCommand> ctx, CancellationToken cancellationToken)
        {
            var user = await _userService.GetByIdAsync(userId);

            if (user == null)
            {
                ctx.AddFailure("UserId", "User does not exist");
                return(false);
            }

            if (user.MonthlySalary - user.MonthlyExpenses < 1000)
            {
                ctx.AddFailure("UserId", "User does not meet account requirements");
                return(false);
            }

            return(true);
        }
        private void HaveValidHeaders <T>(BulkRegisterOdsInstancesModel model, ValidationContext <T> context)
        {
            var missingHeaders = model.MissingHeaders();

            if (missingHeaders == null || !missingHeaders.Any())
            {
                return;
            }

            ValidHeadersRuleFailed = true;
            context.AddFailure($"Missing Headers: {string.Join(",", model.MissingHeaders())}");
        }
コード例 #17
0
ファイル: PaymentValidator.cs プロジェクト: sgtux/Cashflow
        private void ValidateInstallments(IList <Installment> list, ValidationContext <Payment> context)
        {
            if (list != null)
            {
                if (list.Any(p => p.Value <= 0))
                {
                    context.AddFailure(ValidatorMessages.Payment.InstallmentWithInvalidValue);
                }

                if (list.Any(p => p.Date == default(DateTime)))
                {
                    context.AddFailure(ValidatorMessages.Payment.InstallmentWithInvalidDate);
                }

                if (list.Any(p => p.PaidDate == default(DateTime)))
                {
                    context.AddFailure(ValidatorMessages.Payment.InstallmentWithInvalidPaidDate);
                }

                if (list.Any(p => p.Number <= 0 || p.Number > 72))
                {
                    context.AddFailure(ValidatorMessages.Payment.InstallmentWithInvalidNumber);
                }

                if (list.Select(p => p.Number).Distinct().Count() != list.Count)
                {
                    context.AddFailure(ValidatorMessages.Payment.InstallmentWithRepeatedNumbers);
                }

                if (list.Count > 72)
                {
                    context.AddFailure(ValidatorMessages.Payment.InstallmentWithMaxLengthExceded);
                }
            }
        }
コード例 #18
0
 protected virtual void ApplyRuleForItems(CartValidationContext cartContext, ValidationContext <CartValidationContext> context)
 {
     cartContext.CartAggregate.Cart.Items?.Apply(item =>
     {
         var lineItemContext = new LineItemValidationContext
         {
             LineItem        = item,
             AllCartProducts = cartContext.AllCartProducts ?? cartContext.CartAggregate.CartProducts.Values
         };
         var result = LineItemValidator.Validate(lineItemContext);
         result.Errors.Apply(x => context.AddFailure(x));
     });
 }
コード例 #19
0
 protected virtual void ApplyRuleForShipments(CartValidationContext cartContext, ValidationContext <CartValidationContext> context)
 {
     cartContext.CartAggregate.Cart.Shipments?.Apply(shipment =>
     {
         var shipmentContext = new ShipmentValidationContext
         {
             Shipment           = shipment,
             AvailShippingRates = cartContext.AvailShippingRates
         };
         var result = ShipmentValidator.Validate(shipmentContext);
         result.Errors.Apply(x => context.AddFailure(x));
     });
 }
コード例 #20
0
 protected virtual void ApplyRuleForPayments(CartValidationContext cartContext, ValidationContext <CartValidationContext> context)
 {
     cartContext.CartAggregate.Cart.Payments?.Apply(payment =>
     {
         var paymentContext = new PaymentValidationContext
         {
             Payment             = payment,
             AvailPaymentMethods = cartContext.AvailPaymentMethods
         };
         var result = PaymentValidator.Validate(paymentContext);
         result.Errors.Apply(x => context.AddFailure(x));
     });
 }
コード例 #21
0
        private async Task <bool> ValidateEmailAsync(CreateUserCommand cmd, string email,
                                                     ValidationContext <CreateUserCommand> ctx, CancellationToken cancellationToken)
        {
            var user = await _userService.GetUserByEmailAsync(email);

            if (user != null)
            {
                ctx.AddFailure("Email", $"User with such email [{email}] already exists");
                return(false);
            }

            return(true);
        }
コード例 #22
0
        private void ValidateRangeValuesRequirements(ValidationContext <Property> cntx, Property p)
        {
            var req = PropertyValidator.GetRangeValidation(p);

            if (req.IsHasErrors)
            {
                foreach (var t in req.ListErrors)
                {
                    var vf = new ValidationFailure(nameof(p.RangeValuesRequirementStr), t);
                    vf.Severity = Severity.Error;
                    cntx.AddFailure(vf);
                }
            }
        }
コード例 #23
0
        private static bool MatchCartTitle(string requiredGameNameMatch, string gameNameFromRomBytes,
                                           ValidationContext <RomToProjectAssociation> validationContext)
        {
            if (requiredGameNameMatch == gameNameFromRomBytes)
            {
                return(true);
            }

            validationContext.AddFailure(
                $"Verification check: The project file requires the linked ROM's SNES header " +
                $"to have a cartridge title name of:'{requiredGameNameMatch}'. \n" +
                $"But, this doesn't match the title in the ROM file, which is:\n'{gameNameFromRomBytes}'.");
            return(false);
        }
コード例 #24
0
        private static bool HaveValidRomSize(RomToProjectAssociation container, Project?project, ValidationContext <RomToProjectAssociation> validationContext)
        {
            if (project == null)
            {
                return(false);
            }

            if (container.RomBytes?.Length > project.Data?.RomSettingsOffset + 10)
            {
                return(true);
            }

            validationContext.AddFailure("The linked ROM is too small. It can't be opened.");
            return(false);
        }
コード例 #25
0
 private void CheckUserIdExists(Guid proposedId, ValidationContext <CreatedFollowerCommand> context)
 {
     // Checks whether the user id is empty.
     if (proposedId == Guid.Empty)
     {
         context.AddFailure("The user id can not be empty.");
         return;
     }
     // Checks whether the user id already exists.
     // TODO Check if user ids already exists.
     //KweetAggregate kweetAggregate = await _kweetRepository.GetAsync(proposedId, cancellationToken);
     //if (kweetAggregate != default)
     //{
     //    context.AddFailure("A user with the proposed user id already exists.");
     //    return;
     //}
 }
コード例 #26
0
 private static void CheckTabs(ValidationContext <Model> cntx, Dictionary <string, ITreeConfigNode> dic, IGroupListPropertiesTabs tabs, string recom)
 {
     foreach (var t in tabs.ListPropertiesTabs)
     {
         if (string.IsNullOrWhiteSpace(t.CompositeName))
         {
             continue;
         }
         if (dic.ContainsKey(t.CompositeName))
         {
             var sb = GenMessage(dic, t, t.CompositeName);
             sb.Append("'.");
             sb.Append(recom);
             cntx.AddFailure(sb.ToString());
         }
         else
         {
             dic[t.CompositeName] = t;
         }
         CheckTabs(cntx, dic, t.GroupPropertiesTabs, recom);
     }
 }
        /// <inheritdoc/>
        public override bool IsValid(ValidationContext <WorkflowDefinition> context, IEnumerable <FunctionDefinition> value)
        {
            WorkflowDefinition workflow = context.InstanceToValidate;
            int index = 0;
            IValidator <FunctionDefinition> validator = new FunctionDefinitionValidator(workflow);

            foreach (FunctionDefinition function in value)
            {
                ValidationResult validationResult = validator.Validate(function);
                if (validationResult.IsValid)
                {
                    index++;
                    continue;
                }
                foreach (var failure in validationResult.Errors)
                {
                    context.AddFailure(failure);
                }
                return(false);
            }
            return(true);
        }
コード例 #28
0
        public override ValidationResult Validate(ValidationContext <ResourceElement> context)
        {
            EnsureArg.IsNotNull(context, nameof(context));
            var failures = new List <ValidationFailure>();

            if (context.InstanceToValidate is ResourceElement resourceElement)
            {
                var fhirContext       = _contextAccessor.RequestContext;
                var profileValidation = _runProfileValidation;
                if (fhirContext.RequestHeaders.ContainsKey(KnownHeaders.ProfileValidation) &&
                    fhirContext.RequestHeaders.TryGetValue(KnownHeaders.ProfileValidation, out var hValue))
                {
                    if (bool.TryParse(hValue, out bool headerValue))
                    {
                        profileValidation = headerValue;
                    }
                }

                if (profileValidation)
                {
                    var errors = _profileValidator.TryValidate(resourceElement.Instance);
                    foreach (var error in errors.Where(x => x.Severity == IssueSeverity.Error || x.Severity == IssueSeverity.Fatal))
                    {
                        var validationFailure = new FhirValidationFailure(
                            resourceElement.InstanceType,
                            error.DetailsText,
                            error);
                        failures.Add(validationFailure);
                    }
                }

                var baseValidation = base.Validate(context);
                failures.AddRange(baseValidation.Errors);
            }

            failures.ForEach(x => context.AddFailure(x));
            return(new ValidationResult(failures));
        }
コード例 #29
0
        public override FluentValidation.Results.ValidationResult Validate(ValidationContext <ResourceElement> context)
        {
            EnsureArg.IsNotNull(context, nameof(context));
            var failures = new List <ValidationFailure>();

            if (context.InstanceToValidate is ResourceElement resourceElement)
            {
                var results = new List <ValidationResult>();
                if (!_modelAttributeValidator.TryValidate(resourceElement, results, false))
                {
                    foreach (var error in results)
                    {
                        var fullFhirPath = resourceElement.InstanceType;
                        fullFhirPath += string.IsNullOrEmpty(error.MemberNames?.FirstOrDefault()) ? string.Empty : "." + error.MemberNames?.FirstOrDefault();
                        var validationFailure = new ValidationFailure(fullFhirPath, error.ErrorMessage);
                        failures.Add(validationFailure);
                    }
                }
            }

            failures.ForEach(x => context.AddFailure(x));
            return(new FluentValidation.Results.ValidationResult(failures));
        }
コード例 #30
0
        public override ValidationResult Validate(ValidationContext <ResourceElement> context)
        {
            EnsureArg.IsNotNull(context, nameof(context));
            var failures = new List <ValidationFailure>();

            if (context.InstanceToValidate is ResourceElement resourceElement)
            {
                if (resourceElement.IsDomainResource)
                {
                    failures.AddRange(ValidateResource(resourceElement.Instance));
                }
                else if (resourceElement.InstanceType.Equals(KnownResourceTypes.Bundle, System.StringComparison.OrdinalIgnoreCase))
                {
                    var bundleEntries = resourceElement.Instance.Select(KnownFhirPaths.BundleEntries);
                    if (bundleEntries != null)
                    {
                        failures.AddRange(bundleEntries.SelectMany(ValidateResource));
                    }
                }
            }

            failures.ForEach(x => context.AddFailure(x));
            return(new ValidationResult(failures));
        }