/// <summary>
        /// Defines an 'equals' validator on the current rule builder using a lambda to specify the comparison value.
        /// Validation will fail if the value returned by the lambda is not equal to the value of the property.
        /// </summary>
        /// <typeparam name="T">The type of object being validated</typeparam>
        /// <typeparam name="TProperty">Type of property being validated</typeparam>
        /// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
        /// <param name="expression">A lambda expression to provide the comparison value</param>
        /// <param name="comparer">Equality comparer to use</param>
        /// <returns></returns>
        public static IRuleBuilderOptions <T, TProperty> Equal <T, TProperty>(this IRuleBuilder <T, TProperty> ruleBuilder, Expression <Func <T, TProperty> > expression, IEqualityComparer comparer = null)
        {
            var func = expression.Compile();
            PropertySelector propertySelector = x => func((T)x);

            return(ruleBuilder.SetValidator(new EqualValidator(propertySelector, expression.GetMember(), comparer)));
        }
 public NotEqualValidator(PropertySelector func, MemberInfo memberToCompare, IEqualityComparer equalityComparer)
     : base(() => Messages.notequal_error)
 {
     this.func       = func;
     this.comparer   = equalityComparer;
     MemberToCompare = memberToCompare;
 }
 public EqualValidator(PropertySelector comparisonProperty, MemberInfo member, IEqualityComparer comparer)
     : base(() => Messages.equal_error)
 {
     func            = comparisonProperty;
     MemberToCompare = member;
     this.comparer   = comparer;
 }
Esempio n. 4
0
            /// <summary>
            /// Validates the parent object.
            /// </summary>
            public WatchShiftValidator()
            {
                RuleFor(x => x.Points).GreaterThanOrEqualTo(0);
                RuleFor(x => x.ShiftType).NotEmpty();
                RuleFor(x => x.Title).NotEmpty().Length(1, 50);

#pragma warning disable CS0618 // Type or member is obsolete
                Custom(watchShift =>
                {
                    if (watchShift.Range.Start == default(DateTime) || watchShift.Range.End == default(DateTime))
                    {
                        return(new FluentValidation.Results.ValidationFailure(PropertySelector.SelectPropertyFrom <WatchShift>(x => x.Range).Name, "The watch shift's range dates must make sense.  Please."));
                    }

                    if (watchShift.Range.Start >= watchShift.Range.End)
                    {
                        return(new FluentValidation.Results.ValidationFailure(PropertySelector.SelectPropertyFrom <WatchShift>(x => x.Range).Name, "The watch shift's range dates must make sense.  Please."));
                    }

                    if (watchShift.Range.End <= watchShift.Range.Start)
                    {
                        return(new FluentValidation.Results.ValidationFailure(PropertySelector.SelectPropertyFrom <WatchShift>(x => x.Range).Name, "The watch shift's range dates must make sense.  Please."));
                    }

                    return(null);
                });
#pragma warning restore CS0618 // Type or member is obsolete
            }
 public NotEqualValidator(PropertySelector func, MemberInfo memberToCompare, IEqualityComparer equalityComparer)
     : base(() => Messages.notequal_error)
 {
     this.func = func;
     this.comparer = equalityComparer;
     MemberToCompare = memberToCompare;
 }
 public EqualValidator(PropertySelector comparisonProperty, MemberInfo member, IEqualityComparer comparer)
     : base(() => Messages.equal_error)
 {
     func = comparisonProperty;
     MemberToCompare = member;
     this.comparer = comparer;
 }
Esempio n. 7
0
            public bool TryGetPropertySelector(PropertyInfo propertyInfo, out PropertySelector propertySelector)
            {
                var propertyType = propertyInfo.PropertyType;

                if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Value <>))
                {
                    Type valueType = propertyType.GetGenericArguments()[0];

                    Type type = typeof(ValuePropertySelector <>).MakeGenericType(valueType);

                    propertySelector = (PropertySelector)Activator.CreateInstance(type);
                    return(true);
                }

                var declaringType = propertyInfo.DeclaringType;

                if (declaringType.IsGenericType && declaringType.GetGenericTypeDefinition() == typeof(Value <>))
                {
                    Type valueType = declaringType.GetGenericArguments()[0];

                    Type type = typeof(ValuePropertySelector <>).MakeGenericType(valueType);

                    propertySelector = (PropertySelector)Activator.CreateInstance(type);
                    return(true);
                }

                propertySelector = null;
                return(false);
            }
Esempio n. 8
0
        private NotEqualValidator CreateValidator <T>(Expression <PropertySelector <Person, T> > expression, IEqualityComparer equalityComparer)
        {
            var func = expression.Compile();
            PropertySelector selector = x => func((Person)x);

            return(new NotEqualValidator(selector, expression.GetMember(), equalityComparer));
        }
Esempio n. 9
0
        public void Execute_Static_IsNotReturned()
        {
            var propertySelector = new PropertySelector();

            var result = propertySelector.Execute(typeof(FooWithStaticProperty));

            Assert.AreEqual(0, result.Count());
        }
Esempio n. 10
0
        public void Execute_Inherited_IsReturned()
        {
            var propertySelector = new PropertySelector();

            var result = propertySelector.Execute(typeof(FooWithInheritedProperyDepenency));

            Assert.AreEqual(1, result.Count());
        }
        public void Execute_Inherited_IsReturned()
        {
            var propertySelector = new PropertySelector();

            var result = propertySelector.Execute(typeof(FooWithInheritedProperyDepenency));

            Assert.AreEqual(1, result.Count());
        }
        public void Execute_PublicGetterWithPrivateSetter_IsNotReturned()
        {
            var propertySelector = new PropertySelector();

            var result = propertySelector.Execute(typeof(FooWithDependency));

            Assert.AreEqual(0, result.Count());
        }
        public void Execute_Static_IsNotReturned()
        {
            var propertySelector = new PropertySelector();

            var result = propertySelector.Execute(typeof(FooWithStaticProperty));

            Assert.AreEqual(0, result.Count());
        }
        public void Execute_PublicGetterAndSetter_IsReturned()
        {
            var propertySelector = new PropertySelector();
             
            var result = propertySelector.Execute(typeof(FooWithProperyDependency));

            Assert.Equal(1, result.Count());
        }
Esempio n. 15
0
        public void Execute_PublicGetterAndSetter_IsReturned()
        {
            var propertySelector = new PropertySelector();

            var result = propertySelector.Execute(typeof(FooWithProperyDependency));

            Assert.Equal(1, result.Count());
        }
Esempio n. 16
0
        public void Execute_Static_IsNotReturned()
        {
            var propertySelector = new PropertySelector();

            var result = propertySelector.Execute(typeof(FooWithStaticProperty));

            Assert.Empty(result);
        }
Esempio n. 17
0
        /// <summary>
        /// Creates a new property rule from a lambda expression.
        /// </summary>
        public static PropertyRule Create <T, TProperty>(Expression <Func <T, TProperty> > expression, Func <CascadeMode> cascadeModeThunk)
        {
            var member   = expression.GetMember();
            var compiled = expression.Compile();
            PropertySelector propertySelector = x => compiled((T)x);

            return(new PropertyRule(member, propertySelector, expression, cascadeModeThunk, typeof(TProperty), typeof(T)));
        }
Esempio n. 18
0
 public PropertyNode(int id, PropertyInfo propertyInfo, PropertySelector <TProperty, TValue> propertySelector,
                     Action <T, Action <TProperty> > propertyAction)
     : base(id)
 {
     _propertyInfo     = propertyInfo;
     _propertySelector = propertySelector;
     _propertyAction   = propertyAction;
 }
Esempio n. 19
0
        public void Execute_PublicGetterWithPrivateSetter_IsNotReturned()
        {
            var propertySelector = new PropertySelector();

            var result = propertySelector.Execute(typeof(FooWithDependency));

            Assert.AreEqual(0, result.Count());
        }
Esempio n. 20
0
        public void Execute_PublicGetterAndSetter_IsReturned()
        {
            var propertySelector = new PropertySelector();

            var result = propertySelector.Execute(typeof(FooWithPropertyDependency));

            Assert.Single(result);
        }
Esempio n. 21
0
        public void Execute_Inherited_IsReturned()
        {
            var propertySelector = new PropertySelector();

            var result = propertySelector.Execute(typeof(FooWithInheritedProperyDepenency));

            Assert.Single(result);
        }
        /// <summary>
        /// Defines a 'less than' validator on the current rule builder using a lambda expression.
        /// The validation will succeed if the property value is greater than or equal the specified value.
        /// The validation will fail if the property value is less than the specified value.
        /// </summary>
        /// <typeparam name="T">Type of object being validated</typeparam>
        /// <typeparam name="TProperty">Type of property being validated</typeparam>
        /// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
        /// <param name="valueToCompare">The value being compared</param>
        /// <returns></returns>
        public static IRuleBuilderOptions <T, TProperty> GreaterThanOrEqualTo <T, TProperty>(
            this IRuleBuilder <T, TProperty> ruleBuilder, Expression <Func <T, TProperty> > valueToCompare)
            where TProperty : IComparable <TProperty>, IComparable
        {
            var func = valueToCompare.Compile();
            PropertySelector selector = x => func((T)x);

            return(ruleBuilder.SetValidator(new GreaterThanOrEqualValidator(selector, valueToCompare.GetMember())));
        }
Esempio n. 23
0
        public static void Nested()
        {
            Expression <Func <Nested, string[]> > to = o => o.Options.Multiple;

            PropertySelector
            .Do(to)
            .Should()
            .Be("Options:Multiple");
        }
Esempio n. 24
0
        public static void MethodFromBody()
        {
            Expression <Func <Nested, string> > to = o => o.ToString();
            Action test = () => PropertySelector.Do(to);

            test
            .Should()
            .Throw <ArgumentException>();
        }
        /// <summary>
        /// Defines a 'less than or equal' validator on the current rule builder using a lambda expression.
        /// The validation will succeed if the property value is less than or equal to the specified value.
        /// The validation will fail if the property value is greater than the specified value.
        /// </summary>
        /// <typeparam name="T">Type of object being validated</typeparam>
        /// <typeparam name="TProperty">Type of property being validated</typeparam>
        /// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
        /// <param name="expression">The value being compared</param>
        /// <returns></returns>
        public static IRuleBuilderOptions <T, TProperty> LessThanOrEqualTo <T, TProperty>(
            this IRuleBuilder <T, TProperty> ruleBuilder, Expression <Func <T, TProperty> > expression)
            where TProperty : IComparable <TProperty>, IComparable
        {
            var func = expression.Compile();
            PropertySelector selector = x => func((T)x);

            return(ruleBuilder.SetValidator(new LessThanOrEqualValidator(selector, expression.GetMember())));
        }
Esempio n. 26
0
        public static void Simple()
        {
            Expression <Func <Simple, string[]> > to = o => o.Multiple;

            PropertySelector
            .Do(to)
            .Should()
            .Be("Multiple");
        }
        public static PropertyNode <T, TProperty, TValue> Property <T, TProperty, TValue>(
            this RuntimeConfigurator configurator, PropertyInfo propertyInfo,
            PropertySelector <TProperty, TValue> propertySelector)
            where T : class
        {
            PropertyNode <T, TProperty, TValue> propertyNode = configurator.CreateNode(
                id => new PropertyNode <T, TProperty, TValue>(id, propertyInfo, propertySelector));

            return(propertyNode);
        }
 public PropertyValidatorContext(string propertyDescription, object instance, PropertySelector propertyValueFunc, string propertyName, MemberInfo member)
 {
     propertyValueFunc.Guard("propertyValueFunc cannot be null");
     PropertyDescription = propertyDescription;
     Instance = instance;
     messageFormatter = new MessageFormatter();
     this.PropertyName = propertyName;
     this.propertyValueFunc = propertyValueFunc;
     this.Member = member;
 }
Esempio n. 29
0
        public SelectVideoViewModel()
        {
            var grouping = PropertySelector <VideoInfoViewModel> .Start(z => z.Source.GroupIndex).ToString();

            Debug.Assert(grouping == "Source.GroupIndex");
            this.Items.View.GroupDescriptions?.Add(new PropertyGroupDescription(grouping));

            this.Items.View.CustomSort = Comparer <VideoInfoViewModel> .Create((x, y) =>
                                                                               x.Source.GroupIndex.CompareTo(y.Source.GroupIndex));
        }
Esempio n. 30
0
        private void SortDescTest()
        {
            var data     = GetTestSelectables(500).ToList();
            var selector = new PropertySelector();
            var sort     = new Sort(Sort.Direction.Desc, selector);
            var actual   = sort.Apply(data.ToList());
            var expected = data.ToList().OrderByDescending(selector.Select);

            Assert.Equal(expected, actual);
        }
        /// <summary>
        /// Defines a 'less than' validator on the current rule builder using a lambda expression.
        /// The validation will succeed if the property value is less than the specified value.
        /// The validation will fail if the property value is greater than or equal to the specified value.
        /// </summary>
        /// <typeparam name="T">Type of object being validated</typeparam>
        /// <typeparam name="TProperty">Type of property being validated</typeparam>
        /// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
        /// <param name="expression">A lambda that should return the value being compared</param>
        /// <returns></returns>
        public static IRuleBuilderOptions <T, TProperty> LessThan <T, TProperty>(this IRuleBuilder <T, TProperty> ruleBuilder,
                                                                                 Expression <Func <T, TProperty> > expression)
            where TProperty : IComparable <TProperty>, IComparable
        {
            expression.Guard("Cannot pass null to LessThan");

            var func = expression.Compile();
            PropertySelector selector = x => func((T)x);

            return(ruleBuilder.SetValidator(new LessThanValidator(selector, expression.GetMember())));
        }
 protected override IEnumerable <FilterDefinition <VideoRoleCollection> > BuildFilters(VideoRoleCollection.QueryParameter parameter)
 {
     if (parameter.ActorId != null)
     {
         yield return(Builders <VideoRoleCollection> .Filter.Or(
                          Builders <VideoRoleCollection> .Filter.Eq(PropertySelector <VideoRoleCollection> .Start(z => z)
                                                                    .SelectMany(z => z.MajorRoles).Select(z => z.Id).ToString(), parameter.ActorId),
                          Builders <VideoRoleCollection> .Filter.Eq(PropertySelector <VideoRoleCollection> .Start(z => z)
                                                                    .SelectMany(z => z.MinorRoles).Select(z => z.Id).ToString(), parameter.ActorId)));
     }
 }
Esempio n. 33
0
        /// <summary>
        /// Creates a new property rule.
        /// </summary>
        /// <param name="member">Property</param>
        /// <param name="propertyFunc">Function to get the property value</param>
        /// <param name="expression">Lambda expression used to create the rule</param>
        /// <param name="cascadeModeThunk">Function to get the cascade mode.</param>
        /// <param name="typeToValidate">Type to validate</param>
        /// <param name="containerType">Container type that owns the property</param>
        public PropertyRule(MemberInfo member, PropertySelector propertyFunc, Expression expression, Func <CascadeMode> cascadeModeThunk, Type typeToValidate, Type containerType)
        {
            Member                = member;
            PropertyFunc          = propertyFunc;
            Expression            = expression;
            OnFailure             = x => { };
            TypeToValidate        = typeToValidate;
            this.cascadeModeThunk = cascadeModeThunk;

            PropertyName = ValidatorOptions.PropertyNameResolver(containerType, member);
        }
        private ICollection <PropertySelector> ToPropertySelectors(IDictionary <ResourceFieldAttribute, QueryLayer> resourceFieldSelectors,
                                                                   ResourceContext resourceContext, Type elementType)
        {
            var propertySelectors = new Dictionary <PropertyInfo, PropertySelector>();

            // If a read-only attribute is selected, its value likely depends on another property, so select all resource properties.
            bool includesReadOnlyAttribute = resourceFieldSelectors.Any(selector =>
                                                                        selector.Key is AttrAttribute attribute && attribute.Property.SetMethod == null);

            bool containsOnlyRelationships = resourceFieldSelectors.All(selector => selector.Key is RelationshipAttribute);

            foreach (KeyValuePair <ResourceFieldAttribute, QueryLayer> fieldSelector in resourceFieldSelectors)
            {
                var propertySelector = new PropertySelector(fieldSelector.Key, fieldSelector.Value);

                if (propertySelector.Property.SetMethod != null)
                {
                    propertySelectors[propertySelector.Property] = propertySelector;
                }
            }

            if (includesReadOnlyAttribute || containsOnlyRelationships)
            {
                IEntityType             entityModel      = _entityModel.GetEntityTypes().Single(type => type.ClrType == elementType);
                IEnumerable <IProperty> entityProperties = entityModel.GetProperties().Where(property => !property.IsShadowProperty()).ToArray();

                foreach (IProperty entityProperty in entityProperties)
                {
                    var propertySelector = new PropertySelector(entityProperty.PropertyInfo);

                    if (propertySelector.Property.SetMethod != null)
                    {
                        propertySelectors[propertySelector.Property] = propertySelector;
                    }
                }
            }

            foreach (EagerLoadAttribute eagerLoad in resourceContext.EagerLoads)
            {
                var propertySelector = new PropertySelector(eagerLoad.Property);

                // When an entity navigation property is decorated with both EagerLoadAttribute and RelationshipAttribute,
                // it may already exist with a sub-layer. So do not overwrite in that case.
                if (!propertySelectors.ContainsKey(propertySelector.Property))
                {
                    propertySelectors[propertySelector.Property] = propertySelector;
                }

                propertySelectors[propertySelector.Property] = propertySelector;
            }

            return(propertySelectors.Values);
        }
        public static Activation <T> Property <T, TProperty>(this RuntimeConfigurator configurator,
                                                             PropertyInfo propertyInfo)
            where T : class
        {
            PropertySelector propertySelector = configurator.GetPropertySelector(propertyInfo);

            Type propertyNodeType = typeof(PropertyNode <, ,>)
                                    .MakeGenericType(typeof(T), propertySelector.PropertyType, propertySelector.ValueType);

            return(configurator.CreateNode(
                       id => (Activation <T>)Activator.CreateInstance(propertyNodeType, id, propertyInfo, propertySelector)));
        }
        /// <summary>
        /// Verify a member of the entity. <br />
        /// 成员验证入口
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="memberValue"></param>
        /// <typeparam name="TVal"></typeparam>
        /// <returns></returns>
        public virtual VerifyResult VerifyOne <TVal>(Expression <Func <T, TVal> > expression, TVal memberValue)
        {
            var memberName     = PropertySelector.GetPropertyName(expression);
            var memberContract = VerifiableObjectContractManager.Resolve <T>()?.GetMemberContract(memberName);

            if (memberContract is null)
            {
                return(VerifyResult.MemberIsNotExists(memberName));
            }
            var memberContext = VerifiableMemberContext.Create(memberValue, memberContract);

            return(VerifyOneImpl(memberContext));
        }
Esempio n. 37
0
        public void Initialize()
        {
            var index = new IndexKeysDefinitionBuilder <Thing>().Ascending(
                PropertySelector <Thing> .Start(z => z)
                .SelectMany(z => z.Words)
                .Select(z => z.Text)
                .ToString());

            this.Collection.Indexes.CreateOne(index, new CreateIndexOptions
            {
                Version    = 1,
                Background = true
            });
        }
        public bool TryGetPropertySelector(PropertyInfo propertyInfo,
            out PropertySelector propertySelector)
        {
            Type underlyingType = Nullable.GetUnderlyingType(propertyInfo.PropertyType);
            if (underlyingType != null)
            {
                Type selectorType = typeof(NullableTypePropertySelector<>).MakeGenericType(underlyingType);
                propertySelector = (PropertySelector)Activator.CreateInstance(selectorType);
                return true;
            }

            if (propertyInfo.PropertyType.IsEnum)
            {
                Type selectorType = typeof(EnumPropertySelector<,>).MakeGenericType(propertyInfo.PropertyType,
                    typeof(int));
                propertySelector = (PropertySelector)Activator.CreateInstance(selectorType);
                return true;
            }

            if (propertyInfo.PropertyType.IsValueType)
            {
                Type selectorType = typeof(ValueTypePropertySelector<>).MakeGenericType(propertyInfo.PropertyType);
                propertySelector = (PropertySelector)Activator.CreateInstance(selectorType);
                return true;
            }

            Type genericType = typeof(ReferenceTypePropertySelector<>).MakeGenericType(propertyInfo.PropertyType);
            propertySelector = (PropertySelector)Activator.CreateInstance(genericType);
            return true;

            //			if (typeof(IEnumerable<>).IsAssignableFrom(type))
            //				return CreateEnumerableSerializer(type);
            //
            //			if (type.IsInterface)
            //				return CreateObjectSerializerForInterface(type);
        }
 /// <summary>
 /// Enables annotated property injection.
 /// </summary>
 /// <param name="serviceContainer">The target <see cref="ServiceContainer"/>
 /// for which to enable annotated property injection.</param>
 public static void EnableAnnotatedPropertyInjection(this ServiceContainer serviceContainer)
 {
     var propertySelector = new PropertySelector();
     serviceContainer.PropertyDependencySelector = new AnnotatedPropertyDependencySelector(propertySelector);
 }
 public PropertyValidatorContext(string propertyDescription, object instance, PropertySelector propertyValueFunc)
     : this(propertyDescription, instance, propertyValueFunc, null, null)
 {
 }
 public LessThanValidator(PropertySelector valueToCompareFunc, MemberInfo member)
     : base(valueToCompareFunc, member, () => Messages.lessthan_error)
 {
 }
 public GreaterThanOrEqualValidator(PropertySelector valueToCompareFunc, MemberInfo member)
     : base(valueToCompareFunc, member, () => Messages.greaterthanorequal_error)
 {
 }
 protected AbstractComparisonValidator(PropertySelector valueToCompareFunc, MemberInfo member, Expression<Func<string>> errorMessageSelector)
     : base(errorMessageSelector)
 {
     this.valueToCompareFunc = valueToCompareFunc;
     this.MemberToCompare = member;
 }