Пример #1
0
        public static ValidationItemViewModel ValidateUpvoteAccountMinVPRule(GetAccountsModel accountDetails, ValidationVariables vars)
        {
            ValidationPriority   prio       = ValidationPriority.High;
            ValidationResultType resultType = ValidationResultType.Failure;

            var validationItem = new ValidationItemViewModel();

            validationItem.Title               = string.Format("Minimum required VP for account {0} is {1} %", vars.UpvoteAccount, vars.VPMinRequired);
            validationItem.Priority            = prio;
            validationItem.PriorityDescription = prio.ToString();
            validationItem.OrderId             = 60;

            // get comments within range
            var vpCalculated = CalculationHelper.CalculateVotingManaPercentage(accountDetails);

            if (vpCalculated >= vars.VPMinRequired)
            {
                resultType = ValidationResultType.Success;
                validationItem.ResultMessage = string.Format("VP of account {0} is {1} %.", vars.UpvoteAccount, vpCalculated.ToString("N"));
            }
            else
            {
                resultType = ValidationResultType.Failure;
                validationItem.ResultMessage = string.Format("VP of account {0} is {1} %.", vars.UpvoteAccount, vpCalculated.ToString("N"));
            }

            validationItem.ResultType            = resultType;
            validationItem.ResultTypeDescription = resultType.ToString();

            return(validationItem);
        }
Пример #2
0
        public static ValidationItemViewModel ValidateMaxPostPayoutRule(CurationDetailsViewModel model, ValidationVariables vars)
        {
            var validationItem = new ValidationItemViewModel();

            ValidationPriority   prio       = ValidationPriority.High;
            ValidationResultType resultType = ValidationResultType.Failure;

            validationItem.Title               = string.Format("Max post payout <= {0} for posts created within {1} days", vars.MaxPostPayoutAmount, vars.MaxPostPayoutDays);
            validationItem.Priority            = prio;
            validationItem.PriorityDescription = prio.ToString();
            validationItem.OrderId             = 20;

            // get posts within given range in MaxReceivedPayoutDays
            var     dateFrom              = DateTime.Now.AddDays(-vars.MaxPostPayoutDays);
            decimal maxPayoutReceived     = 0;
            double  maxPayoutReceivedDays = 0;

            // check if we have sufficient data to run the validation
            if (model.LastRetrievedPostDate > dateFrom)
            {
                resultType = ValidationResultType.Neutral;
                validationItem.ResultMessage = string.Format(Resources.General.DataSetInsufficientWarning, model.LastRetrievedPostDate.ToString("yyyy-MM-dd HH:mm"));
            }
            else
            {
                // get posts within range
                var posts = model.Posts.Where(x => x.CreatedAt >= dateFrom).ToList();

                if (posts != null && posts.Any())
                {
                    // get the post containing max value
                    var maxReceived = posts.OrderByDescending(x => x.PaidOutTotal).Take(1).FirstOrDefault();

                    if (maxReceived != null)
                    {
                        maxPayoutReceived     = maxReceived.PaidOutTotal;
                        maxPayoutReceivedDays = Math.Floor(DateTime.Now.Subtract(maxReceived.CreatedAt).TotalDays);
                    }
                }

                if (maxPayoutReceived > 0 && maxPayoutReceived <= vars.MaxPostPayoutAmount)
                {
                    resultType = ValidationResultType.Success;
                }
                else
                {
                    resultType = ValidationResultType.Failure;
                }
            }

            validationItem.ResultType            = resultType;
            validationItem.ResultTypeDescription = resultType.ToString();

            if (String.IsNullOrEmpty(validationItem.ResultMessage))
            {
                validationItem.ResultMessage = string.Format("${0} is the highest payout for a post created {1} days ago", maxPayoutReceived.ToString("N"), maxPayoutReceivedDays);
            }

            return(validationItem);
        }
Пример #3
0
 public IEnumerable <ValidationResult> GetResultsByType(ValidationResultType type)
 {
     return
         (from item in Results
          where item.Type == type
          select item);
 }
Пример #4
0
        public static ValidationItemViewModel ValidateAuthorReputationRule(CurationDetailsViewModel model, ValidationVariables vars)
        {
            ValidationPriority   prio       = ValidationPriority.High;
            ValidationResultType resultType = ValidationResultType.Failure;

            var validationItem = new ValidationItemViewModel();

            validationItem.Title               = string.Format("Author reputation is >= {0} and < {1}", vars.AuthorRepMin, vars.AuthorRepMax);
            validationItem.Priority            = prio;
            validationItem.PriorityDescription = prio.ToString();
            validationItem.OrderId             = 35;

            // Check if the author rep value is within the required range
            if (model.Author.ReputationCalculated >= vars.AuthorRepMin &&
                model.Author.ReputationCalculated < vars.AuthorRepMax)
            {
                resultType = ValidationResultType.Success;
            }
            else
            {
                resultType = ValidationResultType.Failure;
            }

            validationItem.ResultType            = resultType;
            validationItem.ResultTypeDescription = resultType.ToString();
            validationItem.ResultMessage         = string.Format("Author reputation is {0}", model.Author.ReputationCalculated.ToString("N"));

            return(validationItem);
        }
Пример #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ValidatorDescriptionAttribute" /> class.
 /// </summary>
 /// <param name="tag">The validation tag.</param>
 /// <param name="validationResultType">The validation result type.</param>
 /// <param name="validationType">The validation type.</param>
 public ValidatorDescriptionAttribute(string tag, ValidationResultType validationResultType = ValidationResultType.Error,
                                      ValidationType validationType = ValidationType.Field)
 {
     Tag = tag;
     ValidationResultType = validationResultType;
     ValidationType       = validationType;
 }
Пример #6
0
        public static ValidationItemViewModel ValidatePostMaxPendingPayoutRule(CurationDetailsViewModel model, ValidationVariables vars)
        {
            var validationItem = new ValidationItemViewModel();

            ValidationPriority   prio       = ValidationPriority.High;
            ValidationResultType resultType = ValidationResultType.Failure;

            validationItem.Title               = string.Format("Post max pending payout value < {0}", vars.PostMaxPendingPayout);
            validationItem.Priority            = prio;
            validationItem.PriorityDescription = prio.ToString();
            validationItem.OrderId             = 25;

            decimal postPendingPayoutValue  = 0;
            var     postPendingPayoutString = model.BlogPost.Details.pending_payout_value.Replace("SBD", "").Trim();

            Decimal.TryParse(postPendingPayoutString, out postPendingPayoutValue);

            // check if the pending payout value of the post is less than the max payout setting
            if (postPendingPayoutValue < vars.PostMaxPendingPayout)
            {
                resultType = ValidationResultType.Success;
            }
            else
            {
                resultType = ValidationResultType.Failure;
            }

            validationItem.ResultType            = resultType;
            validationItem.ResultTypeDescription = resultType.ToString();

            validationItem.ResultMessage = string.Format("Post pending payout value = ${0}", postPendingPayoutValue.ToString("N"));

            return(validationItem);
        }
Пример #7
0
        public static TSource NotEqual <TSource, TProperty>(this TSource source, Expression <Func <TSource, TProperty> > propertyLambda,
                                                            object value,
                                                            List <ValidationResult> result,
                                                            ValidationResultType resultType)
        {
            var valueResult = source.GetExpressionValue(propertyLambda);

            if (object.Equals(valueResult.Value, value))
            // AH!
            //(value is Guid && ((Guid)value == (Guid)valueResult.Value)))
            {
                result.Add(new ValidationResult
                {
                    PropertyName = valueResult.Name,
                    ResultType   = resultType,
                    IsValid      = false,
                    Message      = string.Format("Property [{0}] of type [{1}] must not be equal to [{2}].",
                                                 valueResult.Name,
                                                 valueResult.ObjectType.FullName,
                                                 value)
                });
            }

            return(source);
        }
        public static string GetValidationSummary(this IModel model, ValidationResultType validationResultType)
        {
            Argument.IsNotNull(() => model);

            var builder = new StringBuilder();

            var objectGraphValidationContext = model.GetValidationContextForObjectGraph();

            switch (validationResultType)
            {
                case ValidationResultType.Warning:
                    var warnings = GetSummary(objectGraphValidationContext.GetWarnings());
                    if (!string.IsNullOrWhiteSpace(warnings))
                    {
                        builder.Append(warnings);
                    }
                    break;

                case ValidationResultType.Error:
                    var errors = GetSummary(objectGraphValidationContext.GetErrors());
                    if (!string.IsNullOrWhiteSpace(errors))
                    {
                        builder.Append(errors);
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException("validationResultType");
            }

            return builder.ToString();
        }
Пример #9
0
 public ValidationResult(string propertyName, string propertyPath, string message, ValidationResultType type)
 {
     PropertyName = propertyName;
     PropertyPath = propertyPath;
     Message      = message;
     Type         = type;
 }
Пример #10
0
 public ValidationResult(IPropertyDescriptor property, string description, ValidationResultSeverity severity, ValidationResultType resultType)
 {
     Property    = property;
     Description = description;
     Severity    = severity;
     ResultType  = resultType;
 }
Пример #11
0
 private void EnsureThatPropertyIsInitialized(string name, ValidationResultType value)
 {
     if (value == 0)
     {
         throw new InvalidOperationException($"Property {name} must be set");
     }
 }
Пример #12
0
 public ModelValidationResultImpl(IModelElementInstance element, ValidationResultType type, int code, string message)
 {
     this.Element = element;
     this.type    = type;
     this.code    = code;
     this.message = message;
 }
Пример #13
0
        public static ValidationItemViewModel ValidatePostCreateDateRule(CurationDetailsViewModel model, ValidationVariables vars)
        {
            ValidationPriority   prio       = ValidationPriority.High;
            ValidationResultType resultType = ValidationResultType.Failure;

            var validationItem = new ValidationItemViewModel();

            validationItem.Title               = string.Format("Post creation date is >= {0} minutes and < {1} hours", vars.PostCreatedAtMin, vars.PostCreatedAtMax / 60);
            validationItem.Priority            = prio;
            validationItem.PriorityDescription = prio.ToString();
            validationItem.OrderId             = 10;

            var postCreatedDate = model.BlogPost.Details.created;

            // Check if the post creation date is between the required ranges
            if (DateTime.Now >= postCreatedDate.AddMinutes(vars.PostCreatedAtMin) &&
                DateTime.Now < postCreatedDate.AddMinutes(vars.PostCreatedAtMax))
            {
                resultType = ValidationResultType.Success;
            }
            else
            {
                resultType = ValidationResultType.Failure;
            }

            validationItem.ResultType            = resultType;
            validationItem.ResultTypeDescription = resultType.ToString();

            var span = (TimeSpan)(DateTime.Now - postCreatedDate);

            validationItem.ResultMessage = string.Format("Post created {0} days, {1} hours, {2} minutes ago.", span.Days, span.Hours, span.Minutes);

            return(validationItem);
        }
Пример #14
0
 public ValidationRule(string propertyName, string message, Func <IDbEntity, bool> matches, ValidationResultType type)
 {
     PropertyName = propertyName;
     Message      = message;
     Matches      = matches;
     Type         = type;
 }
Пример #15
0
 /// <summary>
 /// Cria uma nova instancia com os valores iniciais.
 /// </summary>
 /// <param name="key"></param>
 /// <param name="message"></param>
 /// <param name="resultType"></param>
 /// <param name="parameters"></param>
 public ValidationResultItem(string key, IMessageFormattable message, ValidationResultType resultType, params object[] parameters)
 {
     _key        = key;
     _message    = message;
     _resultType = resultType;
     _parameters = parameters ?? new object[0];
 }
Пример #16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ValidatorDescriptionAttribute" /> class.
 /// </summary>
 /// <param name="tag">The validation tag.</param>
 /// <param name="validationResultType">The validation result type.</param>
 /// <param name="validationType">The validation type.</param>
 public ValidatorDescriptionAttribute(string tag, ValidationResultType validationResultType = ValidationResultType.Error,
     ValidationType validationType = ValidationType.Field)
 {
     Tag = tag;
     ValidationResultType = validationResultType;
     ValidationType = validationType;
 }
        public static void FilledExactlyOneOf <TRoot, TChild>(
            this MutatorsConfigurator <TRoot, TChild, TChild> configurator,
            Expression <Func <TChild, object[]> > targets,
            Expression <Func <TChild, MultiLanguageTextBase> > message,
            int priority = 0,
            ValidationResultType type = ValidationResultType.Error)
        {
            Expression sum = null;

            if (targets.Body.NodeType != ExpressionType.NewArrayInit)
            {
                throw new InvalidOperationException("Expected new array creation");
            }
            Expression lcp = null;

            foreach (var expression in ((NewArrayExpression)targets.Body).Expressions)
            {
                var target = expression.NodeType == ExpressionType.Convert ? ((UnaryExpression)expression).Operand : expression;
                if (target.Type.IsValueType && !IsNullable(target.Type))
                {
                    throw new InvalidOperationException("Type '" + target.Type + "' cannot be null");
                }
                lcp = lcp == null ? target : lcp.LCP(target);
                Expression current = Expression.Condition(Expression.Equal(target, Expression.Constant(null, target.Type)), Expression.Constant(0), Expression.Constant(1));
                sum = sum == null ? current : Expression.Add(sum, current);
            }

            if (sum == null)
            {
                return;
            }
            Expression condition = Expression.NotEqual(sum, Expression.Constant(1));

            configurator.SetMutator(configurator.PathToChild.Merge(Expression.Lambda(lcp, targets.Parameters)).Body, configurator.PathToChild.Merge(targets).Body, InvalidIfConfiguration.Create(MutatorsCreator.Sharp, priority, configurator.PathToChild.Merge(Expression.Lambda <Func <TChild, bool?> >(Expression.Convert(condition, typeof(bool?)), targets.Parameters)), configurator.PathToChild.Merge(message), type));
        }
Пример #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ValidationResult"/> class.
        /// </summary>
        /// <param name="validationResultType">Type of the validation result.</param>
        /// <param name="message">The message.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="validationResultType"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="message"/> is <c>null</c>.</exception>
        protected ValidationResult(ValidationResultType validationResultType, string message)
        {
            Argument.IsNotNull("validationResultType", validationResultType);
            Argument.IsNotNull("message", message);

            ValidationResultType = validationResultType;
            Message = message;
        }
Пример #19
0
 private void WriteTypeCount(ValidationResultType type, int count)
 {
     if (count > 0)
     {
         Console.ForegroundColor = GetColorFromResultType(type);
         Console.WriteLine("{0} {1} messages:", count, type.ToString());
     }
 }
Пример #20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FieldValidationResult"/> class.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="validationResultType">Type of the validation result.</param>
        /// <param name="messageFormat">The message format.</param>
        /// <param name="args">The args.</param>
        /// <exception cref="ArgumentException">The <paramref name="propertyName"/> is <c>null</c> or whitespace.</exception>
        /// <exception cref="ArgumentException">The <paramref name="messageFormat"/> is <c>null</c> or whitespace.</exception>
        public FieldValidationResult(string propertyName, ValidationResultType validationResultType, string messageFormat, params object[] args)
            : base(validationResultType, (args == null || args.Length == 0) ? messageFormat : string.Format(messageFormat, args))
        {
            Argument.IsNotNullOrWhitespace("propertyName", propertyName);
            Argument.IsNotNull("messageFormat", messageFormat);

            PropertyName = propertyName;
        }
 /// <summary>
 /// Creates a new instance of validation result and sets its values.
 /// </summary>
 /// <param name="path">a dot notation path of the validated element.</param>
 /// <param name="type">a type of the validation result: Information, Warning, or Error.</param>
 /// <param name="code">an error code.</param>
 /// <param name="message">a human readable message.</param>
 /// <param name="expected">an value expected by schema validation.</param>
 /// <param name="actual">an actual value found by schema validation.</param>
 public ValidationResult(string path, ValidationResultType type,
                         string code, string message, object expected, object actual)
 {
     Path    = path;
     Type    = type;
     Code    = code;
     Message = message;
 }
 public static MutatorsConfigurator <TRoot, TChild, string> NotLongerThan <TRoot, TChild>(
     this MutatorsConfigurator <TRoot, TChild, string> configurator,
     int length,
     int priority = 0,
     ValidationResultType type = ValidationResultType.Error)
 {
     return(configurator.NotLongerThan(length, configurator.Title, priority, type));
 }
Пример #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ValidationResult"/> class.
        /// </summary>
        /// <param name="validationResultType">Type of the validation result.</param>
        /// <param name="message">The message.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="validationResultType"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="message"/> is <c>null</c>.</exception>
        protected ValidationResult(ValidationResultType validationResultType, string message)
        {
            Argument.IsNotNull("validationResultType", validationResultType);
            Argument.IsNotNull("message", message);

            ValidationResultType = validationResultType;
            Message = message;
        }
Пример #24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FieldValidationResult"/> class.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="validationResultType">Type of the validation result.</param>
        /// <param name="messageFormat">The message format.</param>
        /// <param name="args">The args.</param>
        /// <exception cref="ArgumentException">The <paramref name="propertyName"/> is <c>null</c> or whitespace.</exception>
        /// <exception cref="ArgumentException">The <paramref name="messageFormat"/> is <c>null</c> or whitespace.</exception>
        public FieldValidationResult(string propertyName, ValidationResultType validationResultType, string messageFormat, params object[] args)
            : base(validationResultType, string.Format(messageFormat, args))
        {
            Argument.IsNotNullOrWhitespace("propertyName", propertyName);
            Argument.IsNotNull("messageFormat", messageFormat);

            PropertyName = propertyName;
        }
 public static MutatorsConfigurator <TRoot, TChild, TValue> MustBeEqualTo <TRoot, TChild, TValue>(
     this MutatorsConfigurator <TRoot, TChild, TValue> configurator,
     TValue expectedValue,
     Expression <Func <TValue, TValue, MultiLanguageTextBase> > message,
     int priority = 0,
     ValidationResultType type = ValidationResultType.Error)
 {
     return(configurator.MustBeEqualTo(child => expectedValue, message, priority, type));
 }
Пример #26
0
        /// <summary>
        /// Tests the validity of an object. If not valid, throws an exception.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="resultType"></param>
        /// <param name="container"></param>
        public static void AssertValidity(object target, ValidationResultType resultType, IContainer container = null)
        {
            var results = Validate(target, resultType, container);

            if (results.Any())
            {
                throw new System.Exception(results.First().Message);
            }
        }
 public static MutatorsConfigurator <TRoot, TChild, TValue> MustBeEqualTo <TRoot, TChild, TValue>(
     this MutatorsConfigurator <TRoot, TChild, TValue> configurator,
     TValue expectedValue,
     IEqualityComparer <TValue> comparer = null,
     int priority = 0,
     ValidationResultType type = ValidationResultType.Error)
 {
     return(configurator.MustBeEqualTo(child => expectedValue, comparer, priority, type));
 }
 public static MutatorsConfigurator <TRoot, TChild, TValue> Required <TRoot, TChild, TValue>(
     this MutatorsConfigurator <TRoot, TChild, TValue> configurator,
     int priority = 0,
     ValidationResultType type = ValidationResultType.Error)
 {
     return(configurator.Required(child => new ValueRequiredText {
         Title = configurator.Title
     }, priority, type));
 }
 public static MutatorsConfigurator <TRoot, TChild, TValue> RequiredIf <TRoot, TChild, TValue>(
     this MutatorsConfigurator <TRoot, TChild, TValue> configurator,
     Expression <Func <TChild, bool?> > condition,
     int priority = 0,
     ValidationResultType type = ValidationResultType.Error)
 {
     return(configurator.RequiredIf(condition, child => new ValueRequiredText {
         Title = configurator.Title
     }, priority, type));
 }
 public static MutatorsConfigurator <TRoot, TChild, string> IsLike <TRoot, TChild>(
     this MutatorsConfigurator <TRoot, TChild, string> configurator,
     string pattern,
     int priority = 0,
     ValidationResultType type = ValidationResultType.Error)
 {
     return(configurator.IsLike(pattern, child => new ValueShouldMatchPatternText {
         Title = configurator.Title, Pattern = pattern
     }, priority, type));
 }
 public static MutatorsConfigurator <TRoot, TChild, TValue> InvalidIfFromRoot <TRoot, TChild, TValue>(
     this MutatorsConfigurator <TRoot, TChild, TValue> configurator,
     Expression <Func <TRoot, bool?> > condition,
     Expression <Func <TRoot, MultiLanguageTextBase> > message,
     int priority = 0,
     ValidationResultType type = ValidationResultType.Error)
 {
     configurator.SetMutator(InvalidIfConfiguration.Create(MutatorsCreator.Sharp, priority, condition, message, type));
     return(configurator);
 }
Пример #32
0
        public override void Initialize(MemberInfo member, Type memberValueType)
        {
            if (this.Attribute.MemberName != null && this.Attribute.MemberName.Length > 0 && this.Attribute.MemberName[0] == '@')
            {
                var expression = this.Attribute.MemberName.Substring(1);

                var emitContext = new EmitContext()
                {
                    IsStatic       = member.IsStatic(),
                    ReturnType     = typeof(bool),
                    Type           = member.ReflectedType,
                    Parameters     = new Type[] { member.GetReturnType() },
                    ParameterNames = new string[] { "value" }
                };

                var del = ExpressionUtility.ParseExpression(expression, emitContext, out this.memberErrorMessage);

                if (emitContext.IsStatic)
                {
                    this.staticValidationExpression = (ExpressionFunc <T, bool>)del;
                }
                else
                {
                    this.instanceValidationExpression = del;
                }
            }
            else
            {
                LegacyFindMember(member);
            }

            this.defaultMessageString = this.Attribute.DefaultMessage ?? "Value is invalid for member '" + member.Name + "'";
            this.defaultResultType    = this.Attribute.MessageType.ToValidationResultType();

            if (this.Attribute.DefaultMessage != null)
            {
                this.validationMessageHelper = new StringMemberHelper(member.ReflectedType, false, this.Attribute.DefaultMessage);

                if (this.validationMessageHelper.ErrorMessage != null)
                {
                    if (this.memberErrorMessage != null)
                    {
                        this.memberErrorMessage += "\n\n" + this.validationMessageHelper.ErrorMessage;
                    }
                    else
                    {
                        this.memberErrorMessage = this.validationMessageHelper.ErrorMessage;
                    }

                    this.validationMessageHelper = null;
                }
            }
        }
        public static MutatorsConfigurator <TRoot, TChild, TValue> Required <TRoot, TChild, TValue>(
            this MutatorsConfigurator <TRoot, TChild, TValue> configurator,
            Expression <Func <TChild, TValue, MultiLanguageTextBase> > message,
            int priority = 0,
            ValidationResultType type = ValidationResultType.Error)
        {
            var pathToValue = (Expression <Func <TRoot, TValue> >)configurator.PathToValue.ReplaceEachWithCurrent();
            var pathToChild = (Expression <Func <TRoot, TChild> >)configurator.PathToChild.ReplaceEachWithCurrent();

            configurator.SetMutator(RequiredIfConfiguration.Create(MutatorsCreator.Sharp, priority, null, pathToValue, message.Merge(pathToChild, pathToValue), type));
            return(configurator);
        }
Пример #34
0
        private void PrintResultsOfType(ProjectValidator validator, ValidationResultType type)
        {
            var filteredResults = validator.GetResultsByType(type);

            Console.WriteLine();
            WriteTypeCount(type, filteredResults.Count());

            foreach (var item in filteredResults)
            {
                WriteValidationResult(item);
            }
        }
Пример #35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FieldValidationResult"/> class.
 /// </summary>
 /// <param name="property">The property data.</param>
 /// <param name="validationResultType">Type of the validation result.</param>
 /// <param name="messageFormat">The message format.</param>
 /// <param name="args">The args.</param>
 /// <exception cref="ArgumentNullException">The <paramref name="property"/> is <c>null</c>.</exception>
 /// <exception cref="ArgumentException">The <paramref name="messageFormat"/> is <c>null</c> or whitespace.</exception>
 public FieldValidationResult(PropertyData property, ValidationResultType validationResultType, string messageFormat, params object[] args)
     : this(property.Name, validationResultType, string.Format(messageFormat, args)) { }
Пример #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BusinessRuleValidationResult"/> class.
 /// </summary>
 /// <param name="validationResultType">Type of the validation result.</param>
 /// <param name="messageFormat">The message format.</param>
 /// <param name="args">The args.</param>
 /// <exception cref="ArgumentException">The <paramref name="messageFormat"/> is <c>null</c> or whitespace.</exception>
 public BusinessRuleValidationResult(ValidationResultType validationResultType, string messageFormat, params object[] args)
     : base(validationResultType,  string.Format(messageFormat, args))
 {
 }
Пример #37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BusinessRuleValidationResult"/> class.
 /// </summary>
 /// <param name="validationResultType">Type of the validation result.</param>
 /// <param name="messageFormat">The message format.</param>
 /// <param name="args">The args.</param>
 /// <exception cref="ArgumentException">The <paramref name="messageFormat"/> is <c>null</c> or whitespace.</exception>
 public BusinessRuleValidationResult(ValidationResultType validationResultType, string messageFormat, params object[] args)
     : base(validationResultType, (args == null || args.Length == 0) ? messageFormat : string.Format(messageFormat, args))
 {
 }
Пример #38
0
        /// <summary>
        /// Gets the list messages.
        /// </summary>
        /// <param name="validationContext">The validation context.</param>
        /// <param name="validationResult">The validation result.</param>
        /// <returns>
        /// String representing the output of all items in the fields an business object.
        /// </returns>
        /// <remarks>
        /// This method is used to create a message string for field warnings or errors and business warnings
        /// or errors. Just pass the right dictionary and list to this method.
        /// </remarks>
        /// <exception cref="ArgumentNullException">The <paramref name="validationContext"/> is <c>null</c>.</exception>
        private static string GetListMessages(IValidationContext validationContext, ValidationResultType validationResult)
        {
            Argument.IsNotNull("validationContext", validationContext);

            var messageBuilder = new StringBuilder();

            switch (validationResult)
            {
                case ValidationResultType.Warning:
                    foreach (var field in validationContext.GetFieldWarnings())
                    {
                        messageBuilder.AppendLine("* {0}", field.Message);
                    }

                    foreach (var businessItem in validationContext.GetBusinessRuleWarnings())
                    {
                        messageBuilder.AppendLine("* {0}", businessItem.Message);
                    }
                    break;

                case ValidationResultType.Error:
                    foreach (var field in validationContext.GetFieldErrors())
                    {
                        messageBuilder.AppendLine("* {0}", field.Message);
                    }

                    foreach (var businessItem in validationContext.GetBusinessRuleErrors())
                    {
                        messageBuilder.AppendLine("* {0}", businessItem.Message);
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException("validationResult");
            }

            return messageBuilder.ToString();
        }