Ejemplo n.º 1
0
        private void Validate(DataMetaData dataMetaData, AspectContext aspectContext)
        {
            var skip = dataMetaData.Attributes.FirstOrDefault(x => x is SkipValidationAttribute);

            if (skip != null)
            {
                dataMetaData.State = DataValidationState.Skipped;
                return;
            }
            if (dataMetaData.Value is IValidatableObject validatableObject)
            {
                var validationContext = new ValidationContext(validatableObject, null, null);
                var results           = validatableObject.Validate(validationContext)?.ToList() ?? new List <ValidationResult>();
                dataMetaData.State = results.Count == 0 ? DataValidationState.Valid : DataValidationState.Invalid;
                foreach (var result in results)
                {
                    foreach (var member in result.MemberNames ?? new List <string>())
                    {
                        dataMetaData.Errors.Add(new DataValidationError(member, result.ErrorMessage));
                    }
                }
            }
            foreach (var property in dataMetaData.Type.GetTypeInfo().GetProperties())
            {
                //property.GetIndexParameters().Length > 0 ;Indicates that the attribute is an indexer
                if (!property.CanRead || property.GetIndexParameters().Length > 0)
                {
                    continue;
                }
                var propertyValidationContext = new PropertyValidationContext(new PropertyMetaData(property, dataMetaData.Value), aspectContext);
                var results = _propertyValidator.Validate(propertyValidationContext).ToList();
                dataMetaData.State = results.Count == 0 && dataMetaData.State != DataValidationState.Invalid ? DataValidationState.Valid : DataValidationState.Invalid;
                results.ForEach(result => dataMetaData.Errors.Add(result));
            }
        }
        internal static Type GetBaseType(IServiceProvider serviceProvider, PropertyValidationContext validationContext)
        {
            Type propertyType = null;

            if (validationContext.Property is PropertyInfo)
            {
                return(Helpers.GetBaseType(validationContext.Property as PropertyInfo, validationContext.PropertyOwner, serviceProvider));
            }
            if (validationContext.Property is DependencyProperty)
            {
                DependencyProperty property = validationContext.Property as DependencyProperty;
                if (property == null)
                {
                    return(propertyType);
                }
                if (propertyType == null)
                {
                    IDynamicPropertyTypeProvider propertyOwner = validationContext.PropertyOwner as IDynamicPropertyTypeProvider;
                    if (propertyOwner != null)
                    {
                        propertyType = propertyOwner.GetPropertyType(serviceProvider, property.Name);
                    }
                }
                if (propertyType == null)
                {
                    propertyType = property.PropertyType;
                }
            }
            return(propertyType);
        }
Ejemplo n.º 3
0
        public void Ctor_Call_NoException()
        {
            Expression <Func <TestDataObject, int> > propertyExpression = x => x.IntValue;

            var _ = new PropertyValidationContext <TestDataObject, int>(propertyExpression,
                                                                        A.Fake <IValidationContext <TestDataObject> >());
        }
Ejemplo n.º 4
0
        public void Validate(IValidationContext <T> validationContext)
        {
            if (_checkCondition?.Invoke(validationContext.InstanceForValidation) == false)
            {
                return;
            }

            var propertyValidationContext = new PropertyValidationContext <T, TProperty>(_propertyExpression, validationContext);

            // ReSharper disable once LoopCanBePartlyConvertedToQuery
            foreach (var propertyValidationStep in _validationSteps)
            {
                if (!propertyValidationStep.Validate(propertyValidationContext) &&
                    validationContext.BreakRuleValidationAfterFirstFailedValidation)
                {
                    break;
                }
            }

            if (!propertyValidationContext.Faults.Any())
            {
                return;
            }

            validationContext.AddFaults(HasFaultMessage
                ? new[] { new ValidationFault(propertyValidationContext.PropertyName, FaultMessage) }
                : propertyValidationContext.Faults);
        }
Ejemplo n.º 5
0
        public void PropertyName_Get_ReturnsPropertyName()
        {
            var validationContext = A.Fake <IValidationContext <TestDataObject> >();

            var propertyValidationContext =
                new PropertyValidationContext <TestDataObject, string>(x => x.StrValue, validationContext);

            Assert.Equal("StrValue", propertyValidationContext.PropertyName);
        }
Ejemplo n.º 6
0
 public static OptionalMessagePropertyValidationContext <T> NotNull <T>(
     this PropertyValidationContext <T> context)
     where T : class
 {
     return(context.BeginPredicate(
                v => v != null,
                () => $"{context._currentRuleset.PropExpr.GetPropertyName()} must not be null."
                ));
 }
Ejemplo n.º 7
0
        public void AddFault_AddNull_ThrowsException()
        {
            var validationContext = A.Fake <IValidationContext <TestDataObject> >();

            var propertyValidationContext =
                new PropertyValidationContext <TestDataObject, string>(x => x.StrValue, validationContext);

            Assert.Throws <ArgumentNullException>(() => propertyValidationContext.AddFault(null));
        }
Ejemplo n.º 8
0
        public void AddFault_OneFault_FaultsHasExactOneElement()
        {
            var validationContext = A.Fake <IValidationContext <TestDataObject> >();

            var propertyValidationContext =
                new PropertyValidationContext <TestDataObject, string>(x => x.StrValue, validationContext);

            var fault = A.Fake <IValidationFault>();

            propertyValidationContext.AddFault(fault);

            Assert.Single((IEnumerable)propertyValidationContext.Faults);
            Assert.Single(propertyValidationContext.Faults, f => f == fault);
        }
Ejemplo n.º 9
0
        public void AddFault_MultipleFault_FaultsMultipleElements()
        {
            var validationContext = A.Fake <IValidationContext <TestDataObject> >();

            var propertyValidationContext =
                new PropertyValidationContext <TestDataObject, string>(x => x.StrValue, validationContext);

            var fault  = A.Fake <IValidationFault>();
            var fault1 = A.Fake <IValidationFault>();
            var fault2 = A.Fake <IValidationFault>();

            propertyValidationContext.AddFault(fault);
            propertyValidationContext.AddFault(fault1);
            propertyValidationContext.AddFault(fault2);

            Assert.Equal(new[] { fault, fault1, fault2 }, propertyValidationContext.Faults);
        }
Ejemplo n.º 10
0
        public void InstanceForValidation_Get_ReturnCorrectValue()
        {
            var testData = new TestDataObject
            {
                StrValue = "Test text"
            };

            var validationContext = A.Fake <IValidationContext <TestDataObject> >();

            A.CallTo(() => validationContext.InstanceForValidation).Returns(testData);

            var propertyValidationContext =
                new PropertyValidationContext <TestDataObject, string>(x => x.StrValue, validationContext);

            var instanceForValidation = propertyValidationContext.InstanceForValidation;

            Assert.Equal(testData, instanceForValidation);
        }
        internal static AccessTypes GetAccessType(IServiceProvider serviceProvider, PropertyValidationContext validationContext)
        {
            AccessTypes read = AccessTypes.Read;

            if (validationContext.Property is PropertyInfo)
            {
                return(Helpers.GetAccessType(validationContext.Property as PropertyInfo, validationContext.PropertyOwner, serviceProvider));
            }
            if (validationContext.Property is DependencyProperty)
            {
                IDynamicPropertyTypeProvider propertyOwner = validationContext.PropertyOwner as IDynamicPropertyTypeProvider;
                if (propertyOwner != null)
                {
                    read = propertyOwner.GetAccessType(serviceProvider, ((DependencyProperty)validationContext.Property).Name);
                }
            }
            return(read);
        }
Ejemplo n.º 12
0
        public void PropertyValue_StrProperty_ReturnsStrValue()
        {
            var testData = new TestDataObject
            {
                StrValue = "Test text"
            };

            var validationContext = A.Fake <IValidationContext <TestDataObject> >();

            A.CallTo(() => validationContext.InstanceForValidation).Returns(testData);

            var propertyValidationContext =
                new PropertyValidationContext <TestDataObject, string>(x => x.StrValue, validationContext);

            var value = propertyValidationContext.PropertyValue;

            Assert.Equal("Test text", value);
        }
        public IEnumerable <DataValidationError> Validate(PropertyValidationContext propertyValidationContext)
        {
            var propertyMetaData = propertyValidationContext.PropertyMetaData;

            foreach (var attribute in propertyMetaData.Attributes)
            {
                if (attribute is ValidationAttribute validation)
                {
                    var validationContext = new ValidationContext(propertyMetaData.Container ?? propertyMetaData.Value, null, null)
                    {
                        MemberName  = propertyMetaData.MemberName,
                        DisplayName = propertyMetaData.DisplayName
                    };
                    var result = validation.GetValidationResult(propertyMetaData.Value, validationContext);
                    if (result != ValidationResult.Success)
                    {
                        yield return(new DataValidationError(propertyMetaData.MemberName, result.ErrorMessage));
                    }
                }
            }
        }
Ejemplo n.º 14
0
        public void PropertyValue_GetStrPropertyMultipleTimes_ReturnsAlwaysTheSameResult()
        {
            var testData = new TestDataObject
            {
                StrValue = "Test text"
            };

            var validationContext = A.Fake <IValidationContext <TestDataObject> >();

            A.CallTo(() => validationContext.InstanceForValidation).Returns(testData);

            var propertyValidationContext =
                new PropertyValidationContext <TestDataObject, string>(x => x.StrValue, validationContext);

            var value = propertyValidationContext.PropertyValue;

            Assert.Equal("Test text", value);

            var value1 = propertyValidationContext.PropertyValue;

            Assert.Equal(value, value1);
        }
Ejemplo n.º 15
0
        internal static ValidationErrorCollection ValidateProperty(ValidationManager manager, Activity activity, object obj, PropertyValidationContext propertyValidationContext, object extendedPropertyContext)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            if (propertyValidationContext == null)
            {
                throw new ArgumentNullException("propertyValidationContext");
            }

            ValidationErrorCollection errors = new ValidationErrorCollection();

            manager.Context.Push(activity);
            manager.Context.Push(propertyValidationContext);
            if (extendedPropertyContext != null)
            {
                manager.Context.Push(extendedPropertyContext);
            }
            try
            {
                errors.AddRange(ValidationHelpers.ValidateObject(manager, obj));
            }
            finally
            {
                manager.Context.Pop();
                manager.Context.Pop();
                if (extendedPropertyContext != null)
                {
                    manager.Context.Pop();
                }
            }

            return(errors);
        }
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection validationErrors = base.Validate(manager, obj);

            RuleSetReference ruleSetReference = obj as RuleSetReference;

            if (ruleSetReference == null)
            {
                string message = string.Format(CultureInfo.CurrentCulture, Messages.UnexpectedArgumentType, typeof(RuleSetReference).FullName, "obj");
                throw new ArgumentException(message, "obj");
            }
            Activity activity = manager.Context[typeof(Activity)] as Activity;

            if (activity == null)
            {
                string message = string.Format(CultureInfo.CurrentCulture, Messages.ContextStackItemMissing, typeof(Activity).Name);
                throw new InvalidOperationException(message);
            }
            PropertyValidationContext validationContext = manager.Context[typeof(PropertyValidationContext)] as PropertyValidationContext;

            if (validationContext == null)
            {
                string message = string.Format(CultureInfo.CurrentCulture, Messages.ContextStackItemMissing, typeof(PropertyValidationContext).Name);
                throw new InvalidOperationException(message);
            }
            if (!string.IsNullOrEmpty(ruleSetReference.RuleSetName))
            {
                RuleDefinitions   rules             = null;
                RuleSetCollection ruleSetCollection = null;

                CompositeActivity declaringActivity = Helpers.GetDeclaringActivity(activity);
                if (declaringActivity == null)
                {
                    declaringActivity = Helpers.GetRootActivity(activity) as CompositeActivity;
                }
                if (activity.Site != null)
                {
                    rules = ConditionHelper.Load_Rules_DT(activity.Site, declaringActivity);
                }
                else
                {
                    rules = ConditionHelper.Load_Rules_RT(declaringActivity);
                }

                if (rules != null)
                {
                    ruleSetCollection = rules.RuleSets;
                }

                if (ruleSetCollection == null || !ruleSetCollection.Contains(ruleSetReference.RuleSetName))
                {
                    string          message         = string.Format(CultureInfo.CurrentCulture, Messages.RuleSetNotFound, ruleSetReference.RuleSetName);
                    ValidationError validationError = new ValidationError(message, ErrorNumbers.Error_RuleSetNotFound);
                    validationError.PropertyName = GetFullPropertyName(manager) + "." + "RuleSetName";
                    validationErrors.Add(validationError);
                }
                else
                {
                    RuleSet actualRuleSet = ruleSetCollection[ruleSetReference.RuleSetName];

                    ITypeProvider typeProvider = (ITypeProvider)manager.GetService(typeof(ITypeProvider));

                    IDisposable localContextScope = (WorkflowCompilationContext.Current == null ? WorkflowCompilationContext.CreateScope(manager) : null);
                    try
                    {
                        RuleValidation validation = new RuleValidation(activity, typeProvider, WorkflowCompilationContext.Current.CheckTypes);
                        actualRuleSet.Validate(validation);
                        ValidationErrorCollection actualRuleSetErrors = validation.Errors;

                        if (actualRuleSetErrors.Count > 0)
                        {
                            string expressionPropertyName = GetFullPropertyName(manager);
                            string genericErrorMsg        = string.Format(CultureInfo.CurrentCulture, Messages.InvalidRuleSetExpression, expressionPropertyName);
                            int    errorNumber            = ErrorNumbers.Error_InvalidRuleSetExpression;

                            if (activity.Site != null)
                            {
                                foreach (ValidationError actualError in actualRuleSetErrors)
                                {
                                    ValidationError validationError = new ValidationError(actualError.ErrorText, errorNumber);
                                    validationError.PropertyName = expressionPropertyName + "." + "RuleSet Definition";
                                    validationErrors.Add(validationError);
                                }
                            }
                            else
                            {
                                foreach (ValidationError actualError in actualRuleSetErrors)
                                {
                                    ValidationError validationError = new ValidationError(genericErrorMsg + " " + actualError.ErrorText, errorNumber);
                                    validationError.PropertyName = expressionPropertyName;
                                    validationErrors.Add(validationError);
                                }
                            }
                        }
                        //
                    }
                    finally
                    {
                        if (localContextScope != null)
                        {
                            localContextScope.Dispose();
                        }
                    }
                }
            }
            else
            {
                string          message         = string.Format(CultureInfo.CurrentCulture, Messages.InvalidRuleSetName, "RuleSetReference");
                ValidationError validationError = new ValidationError(message, ErrorNumbers.Error_InvalidRuleSetName);
                validationError.PropertyName = GetFullPropertyName(manager) + "." + "RuleSetName";
                validationErrors.Add(validationError);
            }
            return(validationErrors);
        }
Ejemplo n.º 17
0
 internal static ValidationErrorCollection ValidateProperty(ValidationManager manager, Activity activity, object obj, PropertyValidationContext propertyValidationContext)
 {
     return(ValidateProperty(manager, activity, obj, propertyValidationContext, null));
 }