AddFieldValidationResult() public méthode

Adds the field validation result.
The is null.
public AddFieldValidationResult ( IFieldValidationResult fieldValidationResult ) : void
fieldValidationResult IFieldValidationResult The field validation result.
Résultat void
        /// <summary>
        /// Synchronizes the current with the specified context. This means that the current contains will become the same as the
        /// specified context.
        /// </summary>
        /// <param name="validationContext">The validation context.</param>
        /// <param name="additionalValidationContext">The additional validation context.</param>
        /// <param name="onlyAddValidation">if set to <c>true</c>, validation is only added, not removed. This is great to build up summaries.</param>
        /// <returns>The list of changes.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException"></exception>
        /// <exception cref="ArgumentNullException">The <paramref name="validationContext" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="validationContext" /> is <c>null</c>.</exception>
        public static List <ValidationContextChange> SynchronizeWithContext(this ValidationContext validationContext, IValidationContext additionalValidationContext, bool onlyAddValidation = false)
        {
            Argument.IsNotNull("validationContext", validationContext);
            Argument.IsNotNull("additionalValidationContext", additionalValidationContext);

            var changes = ValidationContextHelper.GetChanges(validationContext, additionalValidationContext);

            foreach (var change in changes)
            {
                var validationResultAsField        = change.ValidationResult as IFieldValidationResult;
                var validationResultAsBusinessRule = change.ValidationResult as IBusinessRuleValidationResult;

                switch (change.ChangeType)
                {
                case ValidationContextChangeType.Added:
                    if (validationResultAsField != null)
                    {
                        validationContext.AddFieldValidationResult(validationResultAsField);
                    }
                    else if (validationResultAsBusinessRule != null)
                    {
                        validationContext.AddBusinessRuleValidationResult(validationResultAsBusinessRule);
                    }
                    break;

                case ValidationContextChangeType.Removed:
                    if (!onlyAddValidation)
                    {
                        if (validationResultAsField != null)
                        {
                            validationContext.RemoveFieldValidationResult(validationResultAsField);
                        }
                        else if (validationResultAsBusinessRule != null)
                        {
                            validationContext.RemoveBusinessRuleValidationResult(validationResultAsBusinessRule);
                        }
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException("change.ChangeType");
                }
            }

            return(changes);
        }
Exemple #2
0
        /// <summary>
        /// Sets the field validation result.
        /// </summary>
        /// <param name="validationResult">The field validation result.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="validationResult"/> is <c>null</c>.</exception>
        protected void SetFieldValidationResult(IFieldValidationResult validationResult)
        {
            Argument.IsNotNull("validationResult", validationResult);

            if (string.IsNullOrEmpty(validationResult.Message))
            {
                return;
            }

            var previousValidations = _internalValidationContext.GetFieldValidations(validationResult.PropertyName);

            // First, check if the same error already exists
            bool alreadyExists = (from previousValidation in previousValidations
                                  where string.Compare(previousValidation.Message, validationResult.Message, StringComparison.Ordinal) == 0
                                  select previousValidation).Any();

            if (alreadyExists)
            {
                return;
            }

            _internalValidationContext.AddFieldValidationResult(validationResult);

            if (!IsValidating)
            {
                switch (validationResult.ValidationResultType)
                {
                case ValidationResultType.Warning:
                    NotifyWarningsChanged(validationResult.PropertyName, true);
                    break;

                case ValidationResultType.Error:
                    NotifyErrorsChanged(validationResult.PropertyName, true);
                    break;
                }
            }
        }
        /// <summary>
        /// Validates the current object for field and business rule errors.
        /// </summary>
        /// <param name="force">If set to <c>true</c>, a validation is forced (even if the object knows it is already validated).</param>
        /// <param name="validateDataAnnotations">If set to <c>true</c>, the data annotations will be checked. This value is only used if <paramref name="force"/> is set to <c>true</c>.</param>
        /// <remarks>
        /// To check whether this object contains any errors, use the <see cref="INotifyDataErrorInfo.HasErrors"/> property.
        /// </remarks>
        internal void Validate(bool force, bool validateDataAnnotations)
        {
            if (SuspendValidation)
            {
                return;
            }

            if (IsValidating)
            {
                return;
            }

            IsValidating = true;

            var existingValidationContext = (ValidationContext)_validationContext;
            bool hasErrors = existingValidationContext.HasErrors;
            bool hasWarnings = existingValidationContext.HasWarnings;

            var validationContext = new ValidationContext();
            var changes = new List<ValidationContextChange>();

            var validator = GetValidator();
            if (validator != null)
            {
                validator.BeforeValidation(this, existingValidationContext.GetFieldValidations(), existingValidationContext.GetBusinessRuleValidations());
            }

            OnValidating(validationContext);

            CatchUpWithSuspendedAnnotationsValidation();

            if (force && validateDataAnnotations)
            {
                var type = GetType();

                var ignoredOrFailedPropertyValidations = _propertyValuesIgnoredOrFailedForValidation[type];

                // In forced mode, validate all registered properties for annotations
                var catelTypeInfo = PropertyDataManager.GetCatelTypeInfo(type);
                foreach (var propertyData in catelTypeInfo.GetCatelProperties())
                {
                    var propertyInfo = propertyData.Value.GetPropertyInfo(type);
                    if (propertyInfo == null || !propertyInfo.HasPublicGetter)
                    {
                        // Note: non-public getter, do not validate
                        ignoredOrFailedPropertyValidations.Add(propertyData.Key);
                        continue;
                    }

                    var propertyValue = GetValue(propertyData.Value);
                    ValidatePropertyUsingAnnotations(propertyData.Key, propertyValue, propertyData.Value);
                }

#if !WINDOWS_PHONE && !NETFX_CORE && !PCL && !NET35
                // Validate non-catel properties as well for attribute validation
                foreach (var propertyInfo in catelTypeInfo.GetNonCatelProperties())
                {
                    if (_firstAnnotationValidation)
                    {
                        if (propertyInfo.Value.IsDecoratedWithAttribute(typeof(ExcludeFromValidationAttribute)))
                        {
                            ignoredOrFailedPropertyValidations.Add(propertyInfo.Key);
                        }
                    }

                    if (!propertyInfo.Value.HasPublicGetter)
                    {
                        // Note: non-public getter, do not validate
                        ignoredOrFailedPropertyValidations.Add(propertyInfo.Key);
                        continue;
                    }

                    // TODO: Should we check for annotations attributes?
                    if (ignoredOrFailedPropertyValidations.Contains(propertyInfo.Key))
                    {
                        continue;
                    }

                    try
                    {
                        var propertyValue = propertyInfo.Value.PropertyInfo.GetValue(this, null);
                        ValidatePropertyUsingAnnotations(propertyInfo.Key, propertyValue, null);
                    }
                    catch (Exception ex)
                    {
                        Log.Warning(ex, "Failed to validate property '{0}.{1}', adding it to the ignore list", type.Name, propertyInfo.Key);
                        ignoredOrFailedPropertyValidations.Add(propertyInfo.Key);
                    }
                }

                _firstAnnotationValidation = false;
#endif
            }

            if (!IsValidated || force)
            {
                lock (_validationLock)
                {
                    var fieldValidationResults = new List<IFieldValidationResult>();
                    var businessRuleValidationResults = new List<IBusinessRuleValidationResult>();

                    #region Fields
                    if (validator != null)
                    {
                        validator.BeforeValidateFields(this, validationContext.GetFieldValidations());
                    }

                    OnValidatingFields(validationContext);

                    if (validator != null)
                    {
                        validator.ValidateFields(this, fieldValidationResults);
                    }

#if !WINDOWS_PHONE && !NETFX_CORE && !PCL && !NET35
                    // Support annotation validation
                    fieldValidationResults.AddRange(from fieldAnnotationValidation in _dataAnnotationValidationResults
                                                    where !string.IsNullOrEmpty(fieldAnnotationValidation.Value)
                                                    select (IFieldValidationResult)FieldValidationResult.CreateError(fieldAnnotationValidation.Key, fieldAnnotationValidation.Value));
#endif

                    ValidateFields(fieldValidationResults);

                    OnValidatedFields(validationContext);

                    if (validator != null)
                    {
                        validator.AfterValidateFields(this, fieldValidationResults);
                    }

                    // As the last step, sync the field validation results with the context
                    foreach (var fieldValidationResult in fieldValidationResults)
                    {
                        validationContext.AddFieldValidationResult(fieldValidationResult);
                    }
                    #endregion

                    #region Business rules
                    if (validator != null)
                    {
                        validator.BeforeValidateBusinessRules(this, validationContext.GetBusinessRuleValidations());
                    }

                    OnValidatingBusinessRules(validationContext);

                    if (validator != null)
                    {
                        validator.ValidateBusinessRules(this, businessRuleValidationResults);
                    }

                    ValidateBusinessRules(businessRuleValidationResults);

                    OnValidatedBusinessRules(validationContext);

                    if (validator != null)
                    {
                        validator.AfterValidateBusinessRules(this, businessRuleValidationResults);
                    }

                    // As the last step, sync the field validation results with the context
                    foreach (var businessRuleValidationResult in businessRuleValidationResults)
                    {
                        validationContext.AddBusinessRuleValidationResult(businessRuleValidationResult);
                    }
                    #endregion

                    if (validator != null)
                    {
                        validator.Validate(this, validationContext);
                    }

                    IsValidated = true;

                    // Manual sync to get the changes
                    changes = existingValidationContext.SynchronizeWithContext(validationContext);
                }
            }

            OnValidated(validationContext);

            if (validator != null)
            {
                validator.AfterValidation(this, validationContext.GetFieldValidations(), validationContext.GetBusinessRuleValidations());
            }

            #region Notify changes
            bool hasNotifiedBusinessWarningsChanged = false;
            bool hasNotifiedBusinessErrorsChanged = false;
            foreach (var change in changes)
            {
                var changeAsFieldValidationResult = change.ValidationResult as IFieldValidationResult;
                var changeAsBusinessRuleValidationResult = change.ValidationResult as IBusinessRuleValidationResult;

                if (changeAsFieldValidationResult != null)
                {
                    switch (change.ValidationResult.ValidationResultType)
                    {
                        case ValidationResultType.Warning:
                            NotifyWarningsChanged(changeAsFieldValidationResult.PropertyName, false);
                            break;

                        case ValidationResultType.Error:
                            NotifyErrorsChanged(changeAsFieldValidationResult.PropertyName, false);
                            break;

                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }
                else if (changeAsBusinessRuleValidationResult != null)
                {
                    switch (change.ValidationResult.ValidationResultType)
                    {
                        case ValidationResultType.Warning:
                            if (!hasNotifiedBusinessWarningsChanged)
                            {
                                hasNotifiedBusinessWarningsChanged = true;
                                NotifyWarningsChanged(string.Empty, false);
                            }
                            break;

                        case ValidationResultType.Error:
                            if (!hasNotifiedBusinessErrorsChanged)
                            {
                                hasNotifiedBusinessErrorsChanged = true;
                                NotifyErrorsChanged(string.Empty, false);
                            }
                            break;

                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }
            }

            if (_validationContext.HasWarnings != hasWarnings)
            {
                RaisePropertyChanged(HasWarningsMessageProperty);
            }

            if (_validationContext.HasErrors != hasErrors)
            {
                RaisePropertyChanged(HasErrorsMessageProperty);
            }
            #endregion

            IsValidating = false;
        }
            public void CorrectlyHandlesRemovalOfExistingValidationResult()
            {
                var validationContext = new ValidationContext();
                var fieldValidation = FieldValidationResult.CreateError("MyProperty", "MyError");

                validationContext.AddFieldValidationResult(fieldValidation);

                Assert.AreEqual(1, validationContext.GetFieldValidationCount());

                validationContext.RemoveFieldValidationResult(fieldValidation);

                Assert.AreEqual(0, validationContext.GetFieldValidationCount());
            }
            public void AddsMultipleValidationResultsForField()
            {
                var validationContext = new ValidationContext();
                var fieldValidation = FieldValidationResult.CreateError("MyProperty", "MyError");

                validationContext.AddFieldValidationResult(fieldValidation);

                Assert.AreEqual(1, validationContext.GetFieldValidationCount());

                validationContext.AddFieldValidationResult(fieldValidation);

                Assert.AreEqual(2, validationContext.GetFieldValidationCount());
            }
            public void ThrowsArgumentNullExceptionForNullValidationResult()
            {
                var validationContext = new ValidationContext();

                ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() => validationContext.AddFieldValidationResult(null));
            }
Exemple #7
0
        /// <summary>
        /// Validates the current object for field and business rule errors.
        /// </summary>
        /// <param name="force">If set to <c>true</c>, a validation is forced (even if the object knows it is already validated).</param>
        /// <param name="validateDataAnnotations">If set to <c>true</c>, the data annotations will be checked. This value is only used if <paramref name="force"/> is set to <c>true</c>.</param>
        /// <remarks>
        /// To check whether this object contains any errors, use the ValidationContext property.
        /// </remarks>
        internal void Validate(bool force, bool validateDataAnnotations)
        {
            if (IsValidating)
            {
                return;
            }

            if (IsValidationSuspended)
            {
                return;
            }

            IsValidating = true;

            var existingValidationContext = _validationContext;

            if (existingValidationContext == null)
            {
                existingValidationContext = new ValidationContext();
            }

            var hasErrors   = existingValidationContext.HasErrors;
            var hasWarnings = existingValidationContext.HasWarnings;

            var validationContext = new ValidationContext();
            var changes           = new List <ValidationContextChange>();

            var validator = GetValidator();

            if (validator != null)
            {
                validator.BeforeValidation(this, existingValidationContext.GetFieldValidations(), existingValidationContext.GetBusinessRuleValidations());
            }

            OnValidating(validationContext);

            if (force && validateDataAnnotations)
            {
                var type = GetType();

                var ignoredOrFailedPropertyValidations = PropertiesNotCausingValidation[type];

                // In forced mode, validate all registered properties for annotations
                var catelTypeInfo = PropertyDataManager.GetCatelTypeInfo(type);
                foreach (var propertyData in catelTypeInfo.GetCatelProperties())
                {
                    if (propertyData.Value.IsModelBaseProperty)
                    {
                        continue;
                    }

                    var propertyInfo = propertyData.Value.GetPropertyInfo(type);
                    if (propertyInfo == null || !propertyInfo.HasPublicGetter)
                    {
                        // Note: non-public getter, do not validate
                        ignoredOrFailedPropertyValidations.Add(propertyData.Key);
                        continue;
                    }

                    ValidatePropertyUsingAnnotations(propertyData.Key);
                }

#if !NETFX_CORE && !PCL
                // Validate non-catel properties as well for attribute validation
                foreach (var propertyInfo in catelTypeInfo.GetNonCatelProperties())
                {
                    if (_firstAnnotationValidation)
                    {
                        if (propertyInfo.Value.IsDecoratedWithAttribute <ExcludeFromValidationAttribute>())
                        {
                            ignoredOrFailedPropertyValidations.Add(propertyInfo.Key);
                        }
                    }

                    if (!propertyInfo.Value.HasPublicGetter)
                    {
                        // Note: non-public getter, do not validate
                        ignoredOrFailedPropertyValidations.Add(propertyInfo.Key);
                        continue;
                    }

                    // TODO: Should we check for annotations attributes?
                    if (ignoredOrFailedPropertyValidations.Contains(propertyInfo.Key))
                    {
                        continue;
                    }

                    try
                    {
                        ValidatePropertyUsingAnnotations(propertyInfo.Key);
                    }
                    catch (Exception ex)
                    {
                        Log.Warning(ex, "Failed to validate property '{0}.{1}', adding it to the ignore list", type.Name, propertyInfo.Key);
                        ignoredOrFailedPropertyValidations.Add(propertyInfo.Key);
                    }
                }

                _firstAnnotationValidation = false;
#endif
            }

            if (!_isValidated || force)
            {
                lock (_validationContext)
                {
                    var fieldValidationResults        = new List <IFieldValidationResult>();
                    var businessRuleValidationResults = new List <IBusinessRuleValidationResult>();

                    #region Fields
                    if (validator != null)
                    {
                        validator.BeforeValidateFields(this, validationContext.GetFieldValidations());
                    }

                    OnValidatingFields(validationContext);

                    if (validator != null)
                    {
                        validator.ValidateFields(this, fieldValidationResults);
                    }

#if !NETFX_CORE && !PCL
                    // Support annotation validation
                    fieldValidationResults.AddRange(from fieldAnnotationValidation in _dataAnnotationValidationResults
                                                    where !string.IsNullOrEmpty(fieldAnnotationValidation.Value)
                                                    select(IFieldValidationResult) FieldValidationResult.CreateError(fieldAnnotationValidation.Key, fieldAnnotationValidation.Value));
#endif

                    ValidateFields(fieldValidationResults);

                    OnValidatedFields(validationContext);

                    if (validator != null)
                    {
                        validator.AfterValidateFields(this, fieldValidationResults);
                    }

                    // As the last step, sync the field validation results with the context
                    foreach (var fieldValidationResult in fieldValidationResults)
                    {
                        validationContext.AddFieldValidationResult(fieldValidationResult);
                    }
                    #endregion

                    #region Business rules
                    if (validator != null)
                    {
                        validator.BeforeValidateBusinessRules(this, validationContext.GetBusinessRuleValidations());
                    }

                    OnValidatingBusinessRules(validationContext);

                    if (validator != null)
                    {
                        validator.ValidateBusinessRules(this, businessRuleValidationResults);
                    }

                    ValidateBusinessRules(businessRuleValidationResults);

                    OnValidatedBusinessRules(validationContext);

                    if (validator != null)
                    {
                        validator.AfterValidateBusinessRules(this, businessRuleValidationResults);
                    }

                    // As the last step, sync the field validation results with the context
                    foreach (var businessRuleValidationResult in businessRuleValidationResults)
                    {
                        validationContext.AddBusinessRuleValidationResult(businessRuleValidationResult);
                    }
                    #endregion

                    if (validator != null)
                    {
                        validator.Validate(this, validationContext);
                    }

                    _isValidated = true;

                    // Manual sync to get the changes
                    changes = existingValidationContext.SynchronizeWithContext(validationContext);
                }
            }

            OnValidated(validationContext);

            if (validator != null)
            {
                validator.AfterValidation(this, validationContext.GetFieldValidations(), validationContext.GetBusinessRuleValidations());
            }

            #region Notify changes
            var hasNotifiedBusinessWarningsChanged = false;
            var hasNotifiedBusinessErrorsChanged   = false;
            foreach (var change in changes)
            {
                var changeAsFieldValidationResult        = change.ValidationResult as IFieldValidationResult;
                var changeAsBusinessRuleValidationResult = change.ValidationResult as IBusinessRuleValidationResult;

                if (changeAsFieldValidationResult != null)
                {
                    switch (change.ValidationResult.ValidationResultType)
                    {
                    case ValidationResultType.Warning:
                        NotifyWarningsChanged(changeAsFieldValidationResult.PropertyName, false);
                        break;

                    case ValidationResultType.Error:
                        NotifyErrorsChanged(changeAsFieldValidationResult.PropertyName, false);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }
                else if (changeAsBusinessRuleValidationResult != null)
                {
                    switch (change.ValidationResult.ValidationResultType)
                    {
                    case ValidationResultType.Warning:
                        if (!hasNotifiedBusinessWarningsChanged)
                        {
                            hasNotifiedBusinessWarningsChanged = true;
                            NotifyWarningsChanged(string.Empty, false);
                        }
                        break;

                    case ValidationResultType.Error:
                        if (!hasNotifiedBusinessErrorsChanged)
                        {
                            hasNotifiedBusinessErrorsChanged = true;
                            NotifyErrorsChanged(string.Empty, false);
                        }
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }
            }

            if (_validationContext.HasWarnings != hasWarnings)
            {
                RaisePropertyChanged(this, new PropertyChangedEventArgs(nameof(HasWarnings)), false, false);
                RaisePropertyChanged(this, new PropertyChangedEventArgs(HasWarningsMessageProperty), false, false);
            }

            if (_validationContext.HasErrors != hasErrors)
            {
                RaisePropertyChanged(this, new PropertyChangedEventArgs(nameof(HasErrors)), false, false);
                RaisePropertyChanged(this, new PropertyChangedEventArgs(HasErrorsMessageProperty), false, false);
            }
            #endregion

            IsValidating = false;
        }
        public IValidationContext Parse(List<string> commandLineArguments, IContext targetContext)
        {
            var validationContext = new ValidationContext();

            targetContext.OriginalCommandLine = string.Join(" ", commandLineArguments);

            var isHelp = commandLineArguments.Any(commandLineArgument => commandLineArgument.IsHelp());
            if (isHelp)
            {
                targetContext.IsHelp = true;
                return validationContext;
            }

            var optionDefinitions = _optionDefinitionService.GetOptionDefinitions(targetContext);

            var handledOptions = new HashSet<char>();

            Log.Debug("Parsing command line");

            for (var i = 0; i < commandLineArguments.Count; i++)
            {
                var commandLineArgument = commandLineArguments[i];

                try
                {
                    // Allow the first one to be a non-switch
                    if (i == 0)
                    {
                        if (!commandLineArguments[i].IsSwitch())
                        {
                            var emptyOptionDefinition = (from x in optionDefinitions
                                                         where !x.HasSwitch()
                                                         select x).FirstOrDefault();

                            if (emptyOptionDefinition == null)
                            {
                                var message = string.Format(_languageService.GetString("CommandLine_CannotParseNoEmptySwitch"), commandLineArgument);
                                Log.Error(message);
                                validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError(message));
                                continue;
                            }

                            UpdateContext(targetContext, emptyOptionDefinition, commandLineArgument);
                            handledOptions.Add(emptyOptionDefinition.ShortName);
                            continue;
                        }
                    }

                    if (!commandLineArgument.IsSwitch())
                    {
                        var message = string.Format(_languageService.GetString("CommandLine_CannotParseNoSwitch"), commandLineArgument);
                        Log.Warning(message);
                        validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateWarning(message));
                        continue;
                    }

                    var optionDefinition = (from x in optionDefinitions
                                            where x.IsSwitch(commandLineArgument)
                                            select x).FirstOrDefault();
                    if (optionDefinition == null)
                    {
                        var message = string.Format(_languageService.GetString("CommandLine_CannotParseSwitchNotRecognized"), commandLineArgument);
                        Log.Warning(message);
                        validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateWarning(message));
                        continue;
                    }

                    var value = string.Empty;
                    if (!optionDefinition.AcceptsValue)
                    {
                        // Assume boolean switch
                        value = "true";
                    }
                    else
                    {
                        if (commandLineArguments.Count <= i + 1)
                        {
                            var message = string.Format(_languageService.GetString("CommandLine_CannotParseValueMissing"), commandLineArgument);
                            Log.Warning(message);
                            validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateWarning(message));
                            continue;
                        }

                        value = commandLineArguments[++i];
                    }

                    UpdateContext(targetContext, optionDefinition, value);
                    handledOptions.Add(optionDefinition.ShortName);
                }
                catch (Exception ex)
                {
                    validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError(_languageService.GetString("CommandLine_CannotParseExceptionOccurred"), commandLineArgument, ex.Message));
                }
            }

            Log.Debug("Checking if all required options are specified");

            foreach (var optionDefinition in optionDefinitions)
            {
                if (optionDefinition.IsMandatory)
                {
                    if (!handledOptions.Contains(optionDefinition.ShortName))
                    {
                        var message = string.Format(_languageService.GetString("CommandLine_RequiredSwitchNotSpecified"), optionDefinition);
                        Log.Error(message);
                        validationContext.AddFieldValidationResult(FieldValidationResult.CreateError(optionDefinition.GetSwitchDisplay(), message));
                    }
                }
            }

            Log.Debug("Finishing the context");

            targetContext.Finish();

            return validationContext;
        }