示例#1
0
 /// <summary>
 /// Инициализирует экземпляр результатом правила
 /// </summary>
 public ValidationResult(RuleValidationResult result) : this()
 {
     if (result != null)
     {
         Results.Add(result);
     }
 }
示例#2
0
        public override RuleValidationResult Validate(IQueryModel qm)
        {
            var badJoins = new List <string>();
            var joins    = qm.FromTableJoins.Where(j => !j.IsDeleted);

            foreach (var join in joins)
            {
                var leftObject  = qm.FromTables.First(t => t.Alias == join.Source.LeftObjectAlias);
                var leftProp    = leftObject.Properties.First(p => p.Name == join.Source.LeftField).OriginalStoreProperty;
                var rightObject = qm.FromTables.First(t => t.Alias == join.Source.RightObjectAlias);
                var rightProp   = rightObject.Properties.First(p => p.Name == join.Source.RightField).OriginalStoreProperty;

                if (GetPropertyDataType(leftProp) != GetPropertyDataType(rightProp))
                {
                    badJoins.Add($"{join.Source.GetJoinString()}({leftProp.Type} = {rightProp.Type})");
                }
            }

            if (badJoins.Any())
            {
                var result = new RuleValidationResult(
                    GetType().Name,
                    $"Query '{qm.Name}' has Joins that compare incompatible types: {string.Join(", ", badJoins)}");

                return(result);
            }
            return(null);
        }
示例#3
0
        public RuleValidationResult Validate(IQueryControllerModel model)
        {
            var list = new List <RuleValidationResult>();

            foreach (var q in model.SubQueryList)
            {
                var r = Validate(q);

                if (r != null)
                {
                    list.Add(r);
                }
            }

            if (list.Any())
            {
                var result = new RuleValidationResult($"FromTablesNotEmpty failed")
                {
                    Results = list
                };
                return(result);
            }
            else
            {
                return(null);
            }
        }
示例#4
0
 public ValidationOutputItem(RuleValidationResult src, ValidationLocationType locationType)
 {
     Message      = src.Message;
     Location     = src.Location;
     RuleName     = src.RuleName;
     Type         = src.Type;
     LocationType = locationType;
 }
示例#5
0
        /// <summary>
        /// Strong typed rule invocation.
        /// </summary>
        /// <typeparam name="TParameter">The type of the rule parameter.</typeparam>
        /// <param name="rule">The rule to be evaluated.</param>
        /// <param name="ruleParameter">The parameter for invoking the rule.</param>
        /// <param name="valueName">The name of the data to be checked.</param>
        /// <returns>True if the rule check is ok, false if the rule is violated.</returns>
        public bool ExecuteRuleExpression <TParameter>(RuleBase <TData, TParameter> rule, TParameter ruleParameter, string valueName)
        {
            // if there is no rule, we cannot say that the rule is validated
            if (rule == null)
            {
                return(true);
            }

            // let the concrete execution class decide if we want to execute the expression
            if (!this.BeforeInvoke(rule, ruleParameter, valueName))
            {
                return(true);
            }

            var validationResult = false;

            try
            {
                // execute the expression
                validationResult = rule.CheckExpression(this.Value, ruleParameter);
            }
            catch (NullReferenceException)
            {
            }
            catch (Exception ex)
            {
                if (!this.HandleInvokeException(ex, rule, ruleParameter, valueName))
                {
                    throw;
                }
            }

            var ruleType = rule.GetType();
            var result   = new RuleValidationResult(
                ruleType,
                string.Format(
                    CultureInfo.CurrentCulture,
                    Resources.RuleValidationResultStandardMessage,
                    ruleType.Namespace + "." + ruleType.Name,
                    valueName,
                    string.Format(CultureInfo.CurrentCulture, rule.Message, ruleParameter, valueName)),
                valueName,
                validationResult);

            foreach (var action in Bouncer.GetAfterInvokeActions())
            {
                action.Invoke(result);
            }

            this.AfterInvoke(result);

            if (this.PreviousExecuter != null)
            {
                this.PreviousExecuter.AssertAll();
            }

            return(validationResult);
        }
示例#6
0
        /// <inheritdoc />
        public RuleValidationResult Validate(T value, ValidationContext context)
        {
            var result = new RuleValidationResult(Identity);

            foreach (var member in _validationChain)
            {
                result.AppendRange(member.Validate(value, context));
            }
            return(result);
        }
        public override Task <RuleValidationResult> ExecuteAsync(ValidationContext ctx, string input)
        {
            RuleValidationResult result = GetSuccessResult();

            if (ctx.TransferAmount > ctx.ExpectedAmount)
            {
                result.Error = ErrorMessage;
            }

            return(Task.FromResult(result));
        }
示例#8
0
        /// <summary>
        /// Performs the rule execution result check.
        /// </summary>
        /// <param name="validationResult">The rule validation result structure with information about the rule validation process.</param>
        protected override void AfterInvoke(RuleValidationResult validationResult)
        {
            this.assertExecuted = true;

            if (validationResult == null)
            {
                throw new ArgumentNullException("validationResult", Resources.ErrorMessageForRuleResultIsNull);
            }

            this.conditionIsTrue &= validationResult.Result;
        }
        /// <summary>
        /// Adds the entry to the <see cref="Results"/>, if the validadtion did fail.
        /// </summary>
        /// <param name="validationResult">The rule validation result structure with information about the rule validation process.</param>
        protected override void AfterInvoke(RuleValidationResult validationResult)
        {
            if (validationResult == null)
            {
                throw new ArgumentNullException("validationResult", Resources.ErrorMessageForRuleResultIsNull);
            }

            if (!validationResult.Result)
            {
                this.myResults.Add(validationResult);
            }
        }
示例#10
0
        /// <inheritdoc />
        public async Task <RuleValidationResult> ValidateAsync(T value, ValidationContext context)
        {
            var result = new RuleValidationResult(Identity);

            foreach (var member in _validationChain)
            {
                var validateResults = await member.ValidateAsync(value, context);

                result.AppendRange(validateResults);
            }

            return(result);
        }
 public override RuleValidationResult Validate(ICollectionEntity value, ValidationContext context)
 {
   var result = new RuleValidationResult(Identity);
   if (Math.Abs(Math.Truncate(value.TotalAmount * 100) - (value.TotalAmount * 100)) != 0)
   {
     result.Append(new ErrorRuleMessage(new MessageIdentity("CSAL1M1"),
       string.Format("По счету физического лица {0} сумма заработной платы содержит более двух знаков поле запятой: {1} ",
         value.AccountCba,
         value.TotalAmount)));
     return result;
   }
   return null;
 }
示例#12
0
        /// <summary>
        /// Performs the rule execution result check. If the rule execution results in "false",
        /// this method will throw the <see cref="RuleValidationException"/>.
        /// </summary>
        /// <param name="validationResult">The rule validation result structure with information about the rule validation process.</param>
        /// <exception cref="RuleValidationException">If the validation result is "false".</exception>
        protected override void AfterInvoke(RuleValidationResult validationResult)
        {
            if (validationResult == null)
            {
                throw new ArgumentNullException("validationResult", Resources.ErrorMessageForRuleResultIsNull);
            }

            if (validationResult.Result)
            {
                return;
            }

            throw new RuleValidationException(validationResult.RuleType, validationResult.Message, validationResult.ValueName);
        }
示例#13
0
        private void DataGrid_OnCellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            if (!(e.EditingElement is TextBox textBox))
            {
                return;
            }
            if (textBox.DataContext is RuleValidationOutput ruleValidationOutput)
            {
                // 1. Try to change actual parameter value
                Document  document  = RegularApp.DocumentCacheService.GetDocument(RuleManagerViewModel.DocumentGuid);
                Element   element   = document.GetElement(ruleValidationOutput.ElementId);
                RegexRule regexRule = RuleManagerViewModel.SelectedRegexRule;
                Parameter parameter = ParameterUtils.GetParameterById
                                      (
                    document,
                    element,
                    regexRule.TrackingParameterObject.ParameterObjectId
                                      );
                if (parameter == null || parameter.IsReadOnly)
                {
                    return;
                }

                using (Transaction transaction = new Transaction(document, $"DataSpec User Modifying Element {element.Id}"))
                {
                    transaction.Start();
                    parameter.Set(textBox.Text);
                    transaction.Commit();

                    RuleValidationResult ruleValidationResult = RuleExecutionUtils.ExecuteRegexRule
                                                                (
                        RuleManagerViewModel.DocumentGuid,
                        regexRule.RuleGuid,
                        element
                                                                );

                    ruleValidationOutput.RuleValidationResult = ruleValidationResult;
                    ruleValidationOutput.ValidationText       = ruleValidationResult.GetEnumDescription();
                    if (ruleValidationOutput.RuleValidationResult != RuleValidationResult.Valid)
                    {
                        return;
                    }
                    ruleValidationOutput.CompliantExample = "";
                }
            }
        }
        public override Task <RuleValidationResult> ExecuteAsync(Domain.ValidationContext ctx, string input)
        {
            var cfg = JsonConvert.DeserializeObject <TransactionLimitInput>(input);

            var assetCfg = cfg.Limits.SingleOrDefault(x => x.AssetId == ctx.AssetId);

            RuleValidationResult result = GetSuccessResult();

            if (assetCfg != null)
            {
                if (ctx.TransferAmount > assetCfg.Limit)
                {
                    result.Error = ErrorMessage;
                }
            }

            return(Task.FromResult(result));
        }
示例#15
0
 void RuleSetOnValidationCompleted(object sender, ValidationCompletedEventArgs args) {
     Validator.RuleSet.ValidationCompleted -= RuleSetOnValidationCompleted;
     var ruleSetValidationResult = new RuleSetValidationResult();
     var validationException = args.Exception;
     if (validationException != null)
         ruleSetValidationResult = validationException.Result;
     foreach (var modelMemberPasswordScore in _modelMemberPasswordScores) {
         var password = View.ObjectTypeInfo.FindMember(modelMemberPasswordScore.Name).GetValue(View.CurrentObject);
         var passwordScore = PasswordAdvisor.CheckStrength(password +"");
         if (passwordScore<modelMemberPasswordScore.PasswordScore) {
             var messageTemplate = String.Format(CaptionHelper.GetLocalizedText(XpandValidationModule.XpandValidation, "PasswordScoreFailed"), modelMemberPasswordScore.Name, passwordScore, modelMemberPasswordScore.PasswordScore);
             var ruleValidationResult = new RuleValidationResult(null, View.CurrentObject, ValidationState.Invalid, messageTemplate);
             ruleSetValidationResult.AddResult(new RuleSetValidationResultItem(View.CurrentObject, ContextIdentifier.Save, null,ruleValidationResult));
             args.Handled = true;
         }
     }
     if (args.Handled)
         throw validationException??new ValidationException(ruleSetValidationResult);
 }
示例#16
0
        public RuleValidationResult Validate(IQueryControllerModel qm)
        {
            var list = new List <RuleValidationResult>();

            if (string.IsNullOrWhiteSpace(qm.StoreParameters.DataService))
            {
                list.Add(new RuleValidationResult($"Settings Parameter 'DataService' cannot be empty"));
            }

            if (string.IsNullOrWhiteSpace(qm.StoreParameters.Namespace))
            {
                list.Add(new RuleValidationResult($"Settings Parameter 'Namespace' cannot be empty"));
            }

            if (string.IsNullOrWhiteSpace(qm.StoreParameters.QueryName))
            {
                list.Add(new RuleValidationResult($"Settings Parameter 'QueryName' cannot be empty"));
            }

            if (string.IsNullOrWhiteSpace(qm.StoreParameters.QueryReturnType))
            {
                list.Add(new RuleValidationResult($"Settings Parameter 'QueryReturnType' cannot be empty"));
            }

            if (string.IsNullOrWhiteSpace(qm.StoreParameters.StoreDataPath))
            {
                list.Add(new RuleValidationResult($"Settings Parameter 'StoreDataPath' cannot be empty"));
            }

            if (list.Any())
            {
                var result = new RuleValidationResult($"StoreSettingsNotEmpty failed")
                {
                    Results = list
                };
                return(result);
            }
            else
            {
                return(null);
            }
        }
示例#17
0
        public override RuleValidationResult Validate(IQueryModel qm)
        {
            var emptyOutputs = qm.SelectionProperties.Where(s =>
                                                            !string.IsNullOrWhiteSpace(s.Having) &&
                                                            (string.IsNullOrWhiteSpace(s.GroupByFunction) || s.GroupByFunction == "Where")
                                                            ).ToList();

            if (emptyOutputs.Any())
            {
                var badFields = emptyOutputs.Select(f => f.OutputName);

                var result = new RuleValidationResult(
                    GetType().Name,
                    $"Query '{qm.Name}' cannot have Group By Having not included in Group By clause or aggregate functions: {string.Join(", ", badFields)}");

                return(result);
            }

            return(null);
        }
        public override RuleValidationResult Validate(IQueryModel qm)
        {
            if (qm.SelectionProperties.Any(s => s.IsOutput && !string.IsNullOrWhiteSpace(s.GroupByFunction)))
            {
                var emptyOutputs = qm.SelectionProperties.Where(s => s.IsOutput && string.IsNullOrWhiteSpace(s.GroupByFunction)).ToList();

                if (emptyOutputs.Any())
                {
                    var emptyFields = emptyOutputs.Select(f => f.OutputName);

                    var result = new RuleValidationResult(
                        GetType().Name,
                        $"Query '{qm.Name}' uses Aggregate functions but it has some output fields not included in Group By clause and without aggregate functions: {string.Join(", ", emptyFields)}");

                    return(result);
                }
            }

            return(null);
        }
        public override RuleValidationResult Validate(IQueryModel qm)
        {
            if (qm.SelectionProperties.Any(s => s.GroupByFunction == "Group By"))
            {
                var badOutputs = qm.SelectionProperties.Where(s => s.IsOutput && s.GroupByFunction == "Where").ToList();

                if (badOutputs.Any())
                {
                    var badFields = badOutputs.Select(f => f.OutputName);

                    var result = new RuleValidationResult(
                        GetType().Name,
                        $"Query '{qm.Name}' is a Group By query but it has some output fields included in Where clause: {string.Join(", ", badFields)}");

                    return(result);
                }
            }

            return(null);
        }
示例#20
0
        public RuleValidationResult Validate(IQueryModel qm)
        {
            var fields = qm.SelectionProperties;

            var q = from f in fields
                    where f.IsOutput
                    group f by f.OutputName into fg
                    where fg.Count() > 1
                    select fg.Key;

            var notUnique = q.ToList();

            if (notUnique.Any())
            {
                var result = new RuleValidationResult(GetType().Name, $"Query '{qm.Name}' output fields must have unique names, these fields are not unique: {string.Join(", ", notUnique)}");
                return(result);
            }

            return(null);
        }
示例#21
0
 protected override void AfterInvoke(RuleValidationResult validationResult)
 {
     cummulatedValidationResult &= validationResult.Result;
 }
 public bool Equals(RuleValidationResult other)
 {
     if ((object)other == null) return false;
     return other._severity.Equals(_severity) && Equals(other._description, _description);
 }
示例#23
0
        /// <summary>
        /// Fires after the next button has been clicked
        /// </summary>
        private bool Validate(XafWizardPage page)
        {
            if (page == null)
            {
                return(true);
            }
            var validationResults           = new RuleSetValidationResult();
            var usedProperties              = new List <string>();
            var resultsHighlightControllers = new List <ResultsHighlightController> {
                Frame.GetController <ResultsHighlightController>()
            };

            foreach (var item in page.View.GetItems <PropertyEditor>())
            {
                if (item.Control != null && ((Control)item.Control).Visible)
                {
                    usedProperties.Add(item.PropertyName);
                    var editor = item as ListPropertyEditor;
                    if (editor != null)
                    {
                        usedProperties.AddRange(editor.ListView.Editor.RequiredProperties.Select(property => property.TrimEnd('!')));

                        var nestedController = editor.Frame.GetController <ResultsHighlightController>();
                        if (nestedController != null)
                        {
                            resultsHighlightControllers.Add(nestedController);
                        }
                    }
                }
            }

            var modifiedObjects = ModifiedObjects(page);

            foreach (var obj in modifiedObjects)
            {
                IList <IRule> rules = Validator.RuleSet.GetRules(obj, ContextIdentifier.Save);
                foreach (IRule rule in rules)
                {
                    bool   ruleInUse = rule.UsedProperties.Any(property => usedProperties.Contains(property) || !string.IsNullOrEmpty(usedProperties.FirstOrDefault(p => p.EndsWith(String.Format(".{0}", property)))));
                    string reason;
                    if (ruleInUse && RuleSet.NeedToValidateRule(ObjectSpace, rule, obj, out reason))
                    {
                        RuleValidationResult result = rule.Validate(obj);

                        if (result.State == ValidationState.Invalid)
                        {
                            validationResults.AddResult(new RuleSetValidationResultItem(obj, ContextIdentifier.Save, rule, result));
                        }
                    }
                }
            }

            foreach (ResultsHighlightController resultsHighlightController in resultsHighlightControllers)
            {
                resultsHighlightController.ClearHighlighting();
                if (validationResults.State == ValidationState.Invalid)
                {
                    resultsHighlightController.HighlightResults(validationResults);
                }
            }

            return(validationResults.State != ValidationState.Invalid);
        }
示例#24
0
        /// <summary>
        /// Evaluates the rule check expression for a rule attribute (property or method attribute).
        /// The attributes of methods and properties need to be executed by reflection, so we need a
        /// public method for that purpose.
        /// </summary>
        /// <param name="ruleExecuter">The rule executer (inherits from <see cref="RuleExecuter{TData,TResultClass}"/>) that will invoke the rule validation.</param>
        /// <param name="ruleAttribute">The attribute that defines the rule.</param>
        /// <param name="propertyName">The name of the data to be validated by the rule.</param>
        /// <returns>A new instance of <see cref="RuleValidationResult"/>.</returns>
        public RuleValidationResult InvokeRuleExecutionForAttribute(IRuleExecuter ruleExecuter, ContractRuleBaseAttribute ruleAttribute, string propertyName)
        {
            if (ruleAttribute == null || ruleExecuter == null)
            {
                return(null);
            }

            var typeAttributeType = ruleAttribute.RuleType;

            if (typeAttributeType.Implements(typeof(IEnumerable)))
            {
                return(null);
            }

            // the following line would be more specific - but seems to be hard to be implemented
            ////if (!ruleAttribute.Type.Implements(typeof(RuleBase<,>)))
            if (!typeAttributeType.IsSubclassOf(typeof(RuleBaseInformation)))
            {
                throw new ArgumentException("The attribute does not contain a valid rule.");
            }

            var assertMethod = ruleExecuter.GetType().GetMethod("ExecuteRuleExpression");

            var parameter = ruleAttribute.Parameter;

            assertMethod =
                assertMethod.MakeGenericMethod(
                    parameter != null
                        ? parameter.GetType()
                        : typeof(object));

            try
            {
                // create an instance of the rule and invoke the Assert statement
                var constructorInfo = typeAttributeType.GetConstructor(Type.EmptyTypes);
                RuleBaseInformation rule;
                if (constructorInfo.ContainsGenericParameters)
                {
                    rule = CreateRule(typeAttributeType, ruleExecuter.GetValueType());
                }
                else
                {
                    rule = (RuleBaseInformation)constructorInfo.Invoke(null);
                }

                var ruleType = rule.GetType();
                if (!string.IsNullOrEmpty(ruleAttribute.Message))
                {
                    rule.Message = ruleAttribute.Message;
                }

                var invokeResult = (bool)assertMethod.Invoke(ruleExecuter, new[] { rule, parameter, propertyName });

                var result = new RuleValidationResult(
                    ruleType,
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.RuleValidationResultStandardMessage,
                        ruleType.Namespace + "." + ruleType.Name,
                        propertyName,
                        string.Format(CultureInfo.CurrentCulture, rule.Message, parameter, propertyName)),
                    propertyName,
                    invokeResult);

                return(result);
            }
            catch (TargetInvocationException ex)
            {
                throw ex.InnerException;
            }
        }
示例#25
0
 /// <summary>
 /// The action to be done for each rule validation result. This method must be overridden with the
 /// logic, the inheriting class should implement - e.g. throwing an exception, adding messages
 /// to a list or log etc.
 /// </summary>
 /// <param name="validationResult">The result of a rule validation.</param>
 protected abstract void AfterInvoke(RuleValidationResult validationResult);
示例#26
0
 protected override void AfterInvoke(RuleValidationResult validationResult)
 {
 }
示例#27
0
        public void RuleValidationResultAutoRuleNameTest()
        {
            var vr = new RuleValidationResult("message");

            Assert.Equal(GetType().Name, vr.RuleName);
        }