예제 #1
0
        public static EvaluationResult <IOrderedEnumerable <T> > TryOrderBy <T>(this IEnumerable <T> source, string expression, IEnumerable <string> validProperties = null, IDictionary <string, string> propertyMapping = null)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (string.IsNullOrWhiteSpace(expression))
            {
                throw new ArgumentException($"{expression} is required", nameof(expression));
            }

            var evaluationResult = OrderByParser.Parse(expression, new BuildArgument
            {
                ValidProperties = validProperties,
                EvaluationType  = typeof(T),
                PropertyMapping = propertyMapping
            });

            if (!evaluationResult.Succeeded)
            {
                return(new EvaluationResult <IOrderedEnumerable <T> >
                {
                    InvalidProperties = evaluationResult.InvalidProperties,
                    InvalidOrderByDirections = evaluationResult.InvalidOrderByDirections,
                    Exception = evaluationResult.Exception,
                });
            }

            return(new EvaluationResult <IOrderedEnumerable <T> >
            {
                Result = evaluationResult.Result.Sort(source),
                Succeeded = true
            });
        }
예제 #2
0
        public static EvaluationResult <IOrderedEnumerable <T> > TryOrderBy <T>(this IEnumerable <T> source, IEnumerable <OrderByInfo> orderByInfos, IEnumerable <string> validProperties = null, IDictionary <string, string> propertyMapping = null)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (orderByInfos == null)
            {
                throw new ArgumentNullException(nameof(orderByInfos));
            }

            var evaluationResult = OrderByParser.Parse(orderByInfos.ToArray(), new BuildArgument
            {
                ValidProperties = validProperties,
                EvaluationType  = typeof(T),
                PropertyMapping = propertyMapping
            });

            if (!evaluationResult.Succeeded)
            {
                return(new EvaluationResult <IOrderedEnumerable <T> >
                {
                    InvalidProperties = evaluationResult.InvalidProperties,
                    InvalidOrderByDirections = evaluationResult.InvalidOrderByDirections,
                    Exception = evaluationResult.Exception,
                });
            }

            return(new EvaluationResult <IOrderedEnumerable <T> >
            {
                Result = evaluationResult.Result.Sort(source),
                Succeeded = true
            });
        }
        public void Single_Order_By_Should_Parse_Global_And_Local_Custom_Direction_Successfully()
        {
            // Arrange
            var orderBy        = "FirstName[up],LastName[down]";
            var globalOverride = new Dictionary <OrderByDirection, string>()
            {
                { OrderByDirection.Ascending, "up" }
            };
            var localOverride = new Dictionary <OrderByDirection, string>()
            {
                { OrderByDirection.Descending, "down" }
            };

            // Act
            var parseResults = new OrderByParser(globalOverride).Parse(orderBy, localOverride);

            // Assert
            Assert.NotNull(parseResults);
            Assert.NotEmpty(parseResults);

            Assert.Equal("FirstName", parseResults.ElementAt(0).Name);
            Assert.Equal(OrderByDirection.Ascending, parseResults.ElementAt(0).Direction);

            Assert.Equal("LastName", parseResults.ElementAt(1).Name);
            Assert.Equal(OrderByDirection.Descending, parseResults.ElementAt(1).Direction);
        }
        public void Multiple_Order_By_Should_Convert_Successfully()
        {
            // Arrange
            var orderBy = "FirstName[asc],LastName[desc]";

            // Act
            var stringResults = new OrderByParser().Parse(orderBy);
            var typeResults   = new OrderByParser().ParseAs(orderBy, new TypeSearchConverter <object>());

            // Assert
            Assert.NotNull(stringResults);
            Assert.NotNull(typeResults);

            Assert.NotEmpty(stringResults);
            Assert.NotEmpty(typeResults.Criteria);

            Assert.Equal("FirstName", stringResults.ElementAt(0).Name);
            Assert.Equal(OrderByDirection.Ascending, stringResults.ElementAt(0).Direction);
            Assert.Equal("LastName", stringResults.ElementAt(1).Name);
            Assert.Equal(OrderByDirection.Descending, stringResults.ElementAt(1).Direction);

            Assert.Equal("FirstName", typeResults.Criteria.ElementAt(0).Name);
            Assert.Equal(SortDirection.Ascending, typeResults.Criteria.ElementAt(0).SortDirection);
            Assert.Equal("LastName", typeResults.Criteria.ElementAt(1).Name);
            Assert.Equal(SortDirection.Descending, typeResults.Criteria.ElementAt(1).SortDirection);
        }
예제 #5
0
        public void ParseOrderBy_WhenMultipleQuery_ExpectAllPartsParsed()
        {
            // Arrange
            var mockEntityParser = new Mock <IEntityParser <string> >();

            mockEntityParser.Setup(r => r.IsPermitted(It.IsAny <string>())).Returns(true);

            var orderByParser = new OrderByParser <string>(mockEntityParser.Object);

            // Act
            var stopwatch    = Stopwatch.StartNew();
            var orderByNodes = orderByParser.ParseOrderBy(" name asc value desc ");

            stopwatch.Stop();

            // Assert
            this.WriteTimeElapsed(stopwatch);

            Assert.That(orderByNodes, Is.Not.Null);
            Assert.That(orderByNodes.Count, Is.EqualTo(2));

            Assert.That(orderByNodes[0].Name, Is.EqualTo("name"));
            Assert.That(orderByNodes[0].SortOrder, Is.EqualTo(SortOrder.Asc));

            Assert.That(orderByNodes[1].Name, Is.EqualTo("value"));
            Assert.That(orderByNodes[1].SortOrder, Is.EqualTo(SortOrder.Desc));
        }
        public static IOrderedQueryable OrderBy(this IQueryable source, IEnumerable <OrderByInfo> orderByInfos, IEnumerable <string> validProperties = null, IDictionary <string, string> propertyMapping = null)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (orderByInfos == null)
            {
                throw new ArgumentNullException(nameof(orderByInfos));
            }

            var evaluationResult = OrderByParser.Parse(orderByInfos.ToArray(), new BuildArgument
            {
                ValidProperties = validProperties,
                EvaluationType  = source.ElementType,
                PropertyMapping = propertyMapping
            });

            if (!evaluationResult.Succeeded)
            {
                throw new InvalidOperationException("The property name or direction is not valid");
            }

            return(evaluationResult.Result.Sort(source));
        }
        public void Single_Order_By_Should_Parse_Local_Custom_Direction_Successfully()
        {
            // Arrange
            var orderBy1           = "FirstName[asc],LastName[down]";
            var directionOverride1 = new Dictionary <OrderByDirection, string>()
            {
                { OrderByDirection.Descending, "down" }
            };

            var orderBy2           = "FirstName[asc],LastName[!asc]";
            var directionOverride2 = new Dictionary <OrderByDirection, string>()
            {
                { OrderByDirection.Descending, "!asc" }
            };

            // Act
            var parser        = new OrderByParser();
            var parseResults1 = parser.Parse(orderBy1, directionOverride1);
            var parseResults2 = parser.Parse(orderBy2, directionOverride2);

            // Assert
            Assert.NotNull(parseResults1);
            Assert.NotEmpty(parseResults1);
            Assert.Equal("FirstName", parseResults1.ElementAt(0).Name);
            Assert.Equal(OrderByDirection.Ascending, parseResults1.ElementAt(0).Direction);
            Assert.Equal("LastName", parseResults1.ElementAt(1).Name);
            Assert.Equal(OrderByDirection.Descending, parseResults1.ElementAt(1).Direction);

            Assert.NotNull(parseResults2);
            Assert.NotEmpty(parseResults2);
            Assert.Equal("FirstName", parseResults2.ElementAt(0).Name);
            Assert.Equal(OrderByDirection.Ascending, parseResults2.ElementAt(0).Direction);
            Assert.Equal("LastName", parseResults2.ElementAt(1).Name);
            Assert.Equal(OrderByDirection.Descending, parseResults2.ElementAt(1).Direction);
        }
        public static IOrderedQueryable OrderBy(this IQueryable source, string expression, IEnumerable <string> validProperties = null, IDictionary <string, string> propertyMapping = null)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (string.IsNullOrWhiteSpace(expression))
            {
                throw new ArgumentException($"{expression} is required", nameof(expression));
            }

            var evaluationResult = OrderByParser.Parse(expression, new BuildArgument
            {
                ValidProperties = validProperties,
                EvaluationType  = source.ElementType,
                PropertyMapping = propertyMapping
            });

            if (!evaluationResult.Succeeded)
            {
                throw new InvalidOperationException("The property name or direction is not valid");
            }

            return(evaluationResult.Result.Sort(source));
        }
예제 #9
0
        public static IResult <Query, NonEmptyString> TryCreate(string orderBy, int skip, int top, Guid id)
        {
            var orderByParseResult = OrderByParser.TryParse(orderBy, Columns.GetAllowedColumns());

            return(orderByParseResult.
                   OnSuccess(orderBys => OrderByTopSkip.TryCreate(orderBys, skip, top, (NonEmptyString)nameof(TopSkip.Top), (NonEmptyString)nameof(TopSkip.Skip))).
                   OnSuccess(orderByTopSkip => GetOkResult(new Query(orderByTopSkip, id))));
        }
예제 #10
0
        public void CorectData_ShouldSucceed(string value, int count)
        {
            var result = OrderByParser.TryParse(value, GetAllowedColumns());

            result.IsSuccess.ShouldBeTrue();

            result.Value.OrderBys.Count.ShouldBe(count);
        }
예제 #11
0
        public void Single_Order_By_Parses_Successfully()
        {
            // Arrange
            var orderBy = "FirstName[asc]";

            // Act
            var parseResults = new OrderByParser().Parse(orderBy);

            // Assert
            Assert.NotNull(parseResults);
            Assert.NotEmpty(parseResults);
            Assert.Single(parseResults);
            Assert.Equal("FirstName", parseResults.ElementAt(0).Name);
            Assert.Equal(OrderByDirection.Ascending, parseResults.ElementAt(0).Direction);
        }
예제 #12
0
        /// <summary>
        /// Initializes this instance.
        /// </summary>
        /// <typeparam name="TEntity">The type of the entity.</typeparam>
        /// <param name="parserOptions">The parser options.</param>
        /// <returns>The IEntityParser.</returns>
        private static object Initialize <TEntity>(ParserOptions parserOptions)
        {
            var tokenSplitter = new TokenSplitter();

            var rangeParser  = new RangeParser();
            var equalsParser = new EqualsParser();

            var entityParser = new EntityParser <TEntity>();
            var typeSplitter = new TypeSplitter();

            var whereStatementParser = new WhereStatementParser <TEntity>(rangeParser, equalsParser, entityParser, typeSplitter);
            var whereParser          = new WhereParser(whereStatementParser, parserOptions);
            var orderByParser        = new OrderByParser <TEntity>(entityParser);
            var pageParser           = new PageParser();
            var selectParser         = new SelectParser <TEntity>(entityParser);

            return(new StatementParser(tokenSplitter, whereParser, pageParser, orderByParser, selectParser));
        }
예제 #13
0
        public static EvaluationResult <OrderByClause> TryBuildOrderByClause(this OrderByInfo orderByInfo, Type type, IEnumerable <string> validProperties = null, IDictionary <string, string> propertyMapping = null)
        {
            if (orderByInfo is null)
            {
                throw new ArgumentNullException(nameof(orderByInfo));
            }
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            var arg = new BuildArgument
            {
                ValidProperties = validProperties,
                EvaluationType  = type,
                PropertyMapping = propertyMapping
            };

            return(OrderByParser.Parse(new[] { orderByInfo }, arg));
        }
예제 #14
0
        public static EvaluationResult <OrderByClause> TryBuildOrderByClause(this string expression, Type type, IEnumerable <string> validProperties = null, IDictionary <string, string> propertyMapping = null)
        {
            if (string.IsNullOrWhiteSpace(expression))
            {
                throw new ArgumentException($"{nameof(expression)} is required", nameof(expression));
            }
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            var arg = new BuildArgument
            {
                ValidProperties = validProperties,
                EvaluationType  = type,
                PropertyMapping = propertyMapping
            };

            return(OrderByParser.Parse(expression, arg));
        }
        internal static EvaluationResult <IOrderedQueryable> TryOrderBy(this IQueryable source, IEnumerable <OrderByInfo> orderByInfos, BuildArgument arg)
        {
            var evaluationResult = OrderByParser.Parse(orderByInfos.ToArray(), arg);

            if (!evaluationResult.Succeeded)
            {
                return(new EvaluationResult <IOrderedQueryable>
                {
                    InvalidProperties = evaluationResult.InvalidProperties,
                    InvalidOrderByDirections = evaluationResult.InvalidOrderByDirections,
                    Exception = evaluationResult.Exception,
                });
            }

            return(new EvaluationResult <IOrderedQueryable>
            {
                Result = evaluationResult.Result.Sort(source),
                Succeeded = true
            });
        }
        internal static EvaluationResult <IOrderedQueryable> TryOrderBy(this IQueryable source, string expression, BuildArgument arg)
        {
            var evaluationResult = OrderByParser.Parse(expression, arg);

            if (!evaluationResult.Succeeded)
            {
                return(new EvaluationResult <IOrderedQueryable>
                {
                    InvalidProperties = evaluationResult.InvalidProperties,
                    InvalidOrderByDirections = evaluationResult.InvalidOrderByDirections,
                    Exception = evaluationResult.Exception,
                });
            }

            return(new EvaluationResult <IOrderedQueryable>
            {
                Result = evaluationResult.Result.Sort(source),
                Succeeded = true
            });
        }
예제 #17
0
        public void ParseOrderBy_WhenColumnNotPermitted_ExpectSkip()
        {
            // Arrange
            var mockEntityParser = new Mock <IEntityParser <string> >();

            mockEntityParser.Setup(r => r.IsPermitted(It.IsAny <string>())).Returns(false);

            var orderByParser = new OrderByParser <string>(mockEntityParser.Object);

            // Act
            var stopwatch    = Stopwatch.StartNew();
            var orderByNodes = orderByParser.ParseOrderBy(" name asc ");

            stopwatch.Stop();

            // Assert
            this.WriteTimeElapsed(stopwatch);

            Assert.That(orderByNodes, Is.Not.Null);
            Assert.That(orderByNodes.Count, Is.EqualTo(0));
        }
예제 #18
0
        public void ParseOrderBy_WhenEscapedName_ExpectActualName()
        {
            // Arrange
            var mockEntityParser = new Mock <IEntityParser <string> >();

            mockEntityParser.Setup(r => r.IsPermitted(It.IsAny <string>())).Returns(true);

            var orderByParser = new OrderByParser <string>(mockEntityParser.Object);

            // Act
            var stopwatch    = Stopwatch.StartNew();
            var orderByNodes = orderByParser.ParseOrderBy("\"Test Value\" asc");

            stopwatch.Stop();

            // Assert
            this.WriteTimeElapsed(stopwatch);

            Assert.That(orderByNodes, Is.Not.Null);
            Assert.That(orderByNodes.Count, Is.EqualTo(1));

            Assert.That(orderByNodes[0].Name, Is.EqualTo("Test Value"));
            Assert.That(orderByNodes[0].SortOrder, Is.EqualTo(SortOrder.Asc));
        }
예제 #19
0
        public void Multiple_Order_By_Parses_Successfully()
        {
            // Arrange
            var orderBy = "FirstName[asc],LastName[desc],DateOfBirth[desc],Age[asc]";

            // Act
            var parseResults = new OrderByParser().Parse(orderBy);

            // Assert
            Assert.NotNull(parseResults);
            Assert.NotEmpty(parseResults);

            Assert.Equal("FirstName", parseResults.ElementAt(0).Name);
            Assert.Equal(OrderByDirection.Ascending, parseResults.ElementAt(0).Direction);

            Assert.Equal("LastName", parseResults.ElementAt(1).Name);
            Assert.Equal(OrderByDirection.Descending, parseResults.ElementAt(1).Direction);

            Assert.Equal("DateOfBirth", parseResults.ElementAt(2).Name);
            Assert.Equal(OrderByDirection.Descending, parseResults.ElementAt(2).Direction);

            Assert.Equal("Age", parseResults.ElementAt(3).Name);
            Assert.Equal(OrderByDirection.Ascending, parseResults.ElementAt(3).Direction);
        }
예제 #20
0
        public virtual Condition BuildCondition(Type type, VariableResolver variableResolver = null, IEnumerable <string> validProperties = null, IDictionary <string, string> propertyMapping = null)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            var arg = new BuildArgument
            {
                ValidProperties  = validProperties,
                VariableResolver = variableResolver,
                EvaluationType   = type,
                PropertyMapping  = propertyMapping
            };

            var           error         = new ConditionBase.ErrorInfo();
            var           result        = new Condition();
            var           predicates    = new List <LambdaExpression>();
            var           exceptions    = new List <Exception>();
            OrderByClause orderByClause = null;

            if (Filters != null && Filters.Any())
            {
                var filtersResult = Filters.TryBuildPredicate(type, arg);
                if (filtersResult.Succeeded)
                {
                    predicates.Add(filtersResult.Result);
                }
                else
                {
                    if (filtersResult.Exception != null)
                    {
                        exceptions.Add(filtersResult.Exception);
                    }
                }
            }

            if (FilterGroups != null && FilterGroups.Any())
            {
                var filterGroupsResult = FilterGroups.TryBuildPredicate(type, arg);
                if (filterGroupsResult.Succeeded)
                {
                    predicates.Add(filterGroupsResult.Result);
                }
                else
                {
                    if (filterGroupsResult.Exception != null)
                    {
                        exceptions.Add(filterGroupsResult.Exception);
                    }
                }
            }

            if (!string.IsNullOrEmpty(Where))
            {
                var whereResult = ExpressionParser.Parse(Where, type, arg);
                if (whereResult.Succeeded)
                {
                    predicates.Add(whereResult.Result);
                }
                else
                {
                    if (whereResult.Exception != null)
                    {
                        exceptions.Add(whereResult.Exception);
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(OrderBy))
            {
                var orderByResult = OrderByParser.Parse(OrderBy, arg);
                if (orderByResult.Succeeded)
                {
                    orderByClause = orderByResult.Result;
                }
                else
                {
                    if (orderByResult.Exception != null)
                    {
                        exceptions.Add(orderByResult.Exception);
                    }
                }
            }
            else if (OrderBys != null && OrderBys.Any())
            {
                var orderBysResult = OrderByParser.Parse(OrderBys.ToArray(), arg);
                if (orderBysResult.Succeeded)
                {
                    orderByClause = orderBysResult.Result;
                }
                else
                {
                    if (orderBysResult.Exception != null)
                    {
                        exceptions.Add(orderBysResult.Exception);
                    }
                }
            }

            var isInvalid = arg.InvalidProperties.Any() || arg.InvalidOperators.Any() || arg.InvalidVariables.Any() || exceptions.Any();

            result.IsValid = !isInvalid;
            if (isInvalid)
            {
                error.EvaluationResult = new EvaluationResultBase
                {
                    InvalidProperties        = arg.InvalidProperties,
                    InvalidValues            = arg.InvalidValues,
                    InvalidOperators         = arg.InvalidOperators,
                    InvalidVariables         = arg.InvalidVariables,
                    InvalidOrderByDirections = arg.InvalidOrderByDirections
                };
                error.Exceptions = exceptions;
                result.Error     = error;
            }
            else
            {
                result.Predicates    = predicates;
                result.OrderByClause = orderByClause;
            }

            return(result);
        }
예제 #21
0
        public void IncorectData_ShouldFail()
        {
            var result = OrderByParser.TryParse("abc", GetAllowedColumns());

            result.IsFailure.ShouldBeTrue();
        }
예제 #22
0
 public QueryFilterBuilder(IEntityQueryWrapper entityQueryWrapper)
 {
     this.EntityQueryWrapper = entityQueryWrapper;
     _expressionParser = new ExpressionParser(this.EntityQueryWrapper);
     _orderByParser = new OrderByParser(this.EntityQueryWrapper);
 }
 public QueryFilterBuilder(IEntityQueryWrapper entityQueryWrapper)
 {
     this.EntityQueryWrapper = entityQueryWrapper;
     _expressionParser       = new ExpressionParser(this.EntityQueryWrapper);
     _orderByParser          = new OrderByParser(this.EntityQueryWrapper);
 }
예제 #24
0
 internal OrderByClause(OrderByParser parser)
 {
     _parser = parser;
 }
예제 #25
0
		public ExpressionParsers()
		{
			IncludeParser = new IncludeParser();
			WhereParser = new WhereParser();
			OrderByParser = new OrderByParser();
		}