public void Add_HasARegexConflict_ThrowsException()
        {
            var table = new ExpressionTable();
            var expr1 = new CustomExpression
            {
                Name                = "Test",
                RegexPattern        = "[0-9]",
                ExpressionFunction  = FakeFunc,
                ReplacementFunction = FakeReplaceFunc
            };

            table.Add(expr1);

            var expr2 = new CustomExpression
            {
                Name                = "Test1",
                RegexPattern        = "[0-9]",
                ExpressionFunction  = FakeFunc,
                ReplacementFunction = FakeReplaceFunc
            };

            Action add = () => table.Add(expr2);

            add.Should().Throw <ArgumentException>();
        }
Example #2
0
        public void Transform_AddDays()
        {
            var value      = new CustomExpression(typeof(double));
            var methodInfo = MemberInfoFromExpressionUtility.GetMethod(() => DateTime.Now.AddDays(0.0));
            var expression = Expression.Call(_dateTimeInstance, methodInfo, value);

            var result = _transformer.Transform(expression);

            var expectedResult = new SqlFunctionExpression(
                typeof(DateTime),
                "DATEADD",
                new SqlCustomTextExpression("millisecond", typeof(string)),
                Expression.Modulo(
                    new SqlConvertExpression(typeof(long), Expression.Multiply(value, new SqlLiteralExpression(86400000.0))),
                    new SqlLiteralExpression(86400000L)),
                new SqlFunctionExpression
                (
                    typeof(DateTime),
                    "DATEADD",
                    new SqlCustomTextExpression("day", typeof(string)),
                    Expression.Divide(
                        new SqlConvertExpression(typeof(long), Expression.Multiply(value, new SqlLiteralExpression(86400000.0))),
                        new SqlLiteralExpression(86400000L)),
                    _dateTimeInstance));

            SqlExpressionTreeComparer.CheckAreEqualTrees(expectedResult, result);
        }
        public void UnknownExpression()
        {
            var unknownExpression = new CustomExpression(typeof(int));
            var result            = _visitor.Visit(unknownExpression);

            Assert.That(result, Is.SameAs(unknownExpression));
        }
Example #4
0
        public void TestPreviousContent()
        {
            CastDate currentDate = new CastDate {
                Time = 1484953200000
            };
            CastDate previousDate = new CastDate {
                Time = 1484953200000
            };
            ReportData reportData = TestUtility.PrepareApplicationReportData("ReportGenerator",
                                                                             null, @".\Data\CurrentBCresults.json", "AED/applications/3/snapshots/6", "PreVersion 1.5.0 sprint 2 shot 2", "V-1.5.0_Sprint 2_2", currentDate,
                                                                             null, @".\Data\PreviousBCresults.json", "AED/applications/3/snapshots/5", "Version 1.4.1", "V-1.4.1", previousDate);

            var component = new CustomExpression();
            Dictionary <string, string> config = new Dictionary <string, string>
            {
                { "PARAMS", "QR a QR b" },
                { "EXPR", "(a+b)/2" },
                { "a", "60012" },
                { "b", "60013" },
                { "SNAPSHOT", "PREVIOUS" }
            };
            var str = component.Content(reportData, config);

            Assert.AreEqual("2.54", str);
        }
Example #5
0
        public void GenerateSql_UnsupportedExpression()
        {
            var unknownExpression = new CustomExpression(typeof(int));

            SqlGeneratingExpressionVisitor.GenerateSql(
                unknownExpression, _commandBuilder, _stageMock);
        }
Example #6
0
        public void TestBfContent()
        {
            CastDate currentDate = new CastDate {
                Time = 1484953200000
            };
            ReportData reportData = TestUtility.PrepareApplicationReportData("ReportGenerator",
                                                                             null, @".\Data\CurrentBCresults.json", "AED/applications/3/snapshots/6", "PreVersion 1.5.0 sprint 2 shot 2", "V-1.5.0_Sprint 2_2", currentDate,
                                                                             null, null, null, null, null, null);

            WSConnection connection = new WSConnection()
            {
                Url      = "http://tests/CAST-RESTAPI/rest/",
                Login    = "******",
                Password = "******",
                IsActive = true,
                Name     = "Default"
            };

            reportData.SnapshotExplorer = new SnapshotBLLStub(connection, reportData.CurrentSnapshot);

            var component = new CustomExpression();
            Dictionary <string, string> config = new Dictionary <string, string>
            {
                { "PARAMS", "BF a SZ b" },
                { "EXPR", "b/a" },
                { "a", "66061" },
                { "b", "10151" },
                { "FORMAT", "N0" }
            };
            var str = component.Content(reportData, config);

            Assert.AreEqual("10,631", str);
        }
        public void GetTableForFromExpression_UnsupportedExpression_Throws()
        {
            var customExpression = new CustomExpression(typeof(Cook[]));

            SqlPreparationFromExpressionVisitor.AnalyzeFromExpression(
                customExpression, _stageMock, _generator, _methodCallTransformerProvider, _context, _tableGenerator, _someOrderingExtractionPolicy);
        }
Example #8
0
        protected internal override Node VisitSelectFromStatement(SelectFromStatement node)
        {
            node = (SelectFromStatement)base.VisitSelectFromStatement(node);

            if (node.Groupings.Any())
            {
                var groupQuery     = GroupQueryVisitor.GetGroupQuery(node, this.data);
                var groupFactories = this.GetGroupValueFactory(groupQuery.Expressions.Concat(new[]
                {
                    new AliasedSqlExpression(groupQuery.Having, "$having"),
                }).Concat(groupQuery.OrderBy.Select((o, i) => new AliasedSqlExpression(o.Expression, $"$order{i}"))).Where(e => e.Expression != null));
                var plan   = this.CreateSelectQueryPlan(groupQuery.RowSelect);
                var fields = node.Expressions.Select(f => f.Expression is WildcardSqlExpression ? "*" : f.Alias);
                var orders = groupQuery.OrderBy.Select((o, i) => new OrderByExpression(CustomExpression.MakeSourceField(null, $"$order{i}", true), o.Ascending));
                var having = groupQuery.Having == null ? null : CustomExpression.MakeSourceField(null, "$having", true, typeof(bool));

                var aliases = groupQuery.Expressions;

                this.data.SetQueryPlan(node, new SelectGroupByQueryPlan(plan, groupFactories, groupQuery.Groupings, aliases, having, orders, fields));
            }
            else
            {
                this.data.SetQueryPlan(node, this.CreateSelectQueryPlan(node));
            }

            return(node);
        }
        public void SplitPotentialCompoundComparison_BinaryExpression_NewExpressionOnLeftSideWithTwoPropertyInfoMembers_NotEqual()
        {
            var leftArgumentExpression1 = Expression.Constant(1);
            var leftArgumentExpression2 = Expression.Constant(2);
            var leftArgumentMemberInfo1 = typeof(TypeForNewExpression).GetProperty("A");
            var leftArgumentMemberInfo2 = typeof(TypeForNewExpression).GetProperty("B");
            var leftExpression          = Expression.New(
                TypeForNewExpression.GetConstructor(typeof(int), typeof(int)),
                new[] { leftArgumentExpression1, leftArgumentExpression2 },
                leftArgumentMemberInfo1,
                leftArgumentMemberInfo2);
            var rightExpression = new CustomExpression(typeof(TypeForNewExpression));
            var expression      = Expression.NotEqual(leftExpression, rightExpression);

            var result = _compoundExpressionComparisonSplitter.SplitPotentialCompoundComparison(expression);

            var expectedResult =
                Expression.OrElse(
                    Expression.NotEqual(
                        leftArgumentExpression1, Expression.MakeMemberAccess(rightExpression, typeof(TypeForNewExpression).GetProperty("A"))),
                    Expression.NotEqual(
                        leftArgumentExpression2, Expression.MakeMemberAccess(rightExpression, typeof(TypeForNewExpression).GetProperty("B"))));

            SqlExpressionTreeComparer.CheckAreEqualTrees(expectedResult, result);
        }
Example #10
0
        /*
         * /// <summary>
         * /// Retrieves the data from the source.
         * /// </summary>
         * /// <param name="context">
         * ///     The context.
         * /// </param>
         * /// <param name="query">
         * ///     The query expression. Can be <c>null</c>.
         * /// </param>
         * /// <returns>
         * /// A task returning the data set.
         * /// </returns>
         * public async Task<DataSet> GetDataAsync(IExecutionContext context, IQuery query)
         * {
         *
         *  var leftRows = await context.MaterializeAsync(await this.GetDataAsync(context, this.left, query, query.GetFilter(context), Enumerable.Empty<OrderByExpression>()).ConfigureAwait(false)).ConfigureAwait(false);
         *
         *  if (leftRows.Count == 0)
         *  {
         *      return DataSet.Empty();
         *  }
         *
         *  var sortOrders = new List<OrderByExpression>();
         *  var filter = await this.CreateJoinFilterAsync(context, leftRows, sortOrders);
         *  var rightRows = await context.MaterializeAsync(await this.GetDataAsync(context, this.right, query, filter, sortOrders).ConfigureAwait(false));
         *
         *  if (rightRows.Count == 0)
         *  {
         *      return this.isInnerJoin ? DataSet.Empty() : DataSet.FromEnumerable(rightRows);
         *  }
         *
         *  var joinFilter = this.GetFilter(context);
         *
         *  return null;
         * }
         */

        /// <summary>
        /// Creates the join filter.
        /// </summary>
        /// <param name="context">
        /// The execution context.
        /// </param>
        /// <param name="leftRows">
        /// The left rows.
        /// </param>
        /// <param name="sortOrders">
        /// Will be filled with the sort orders for this join.
        /// </param>
        /// <returns>
        /// A task containing the the filter expression.
        /// </returns>
        private Task <Expression> CreateJoinFilterAsync(IExecutionContext context, IAsyncReadOnlyCollection <Row> leftRows, ICollection <OrderByExpression> sortOrders)
        {
            var filter = (Expression)null; // await this.GetFilter(context, null).ToRangedExpressionAsync(leftRows, this.right.Aliases);

            return(Task.FromResult(new GenericVisitor
            {
                (GenericVisitor visitor, BinaryExpression node) =>
                {
                    if (node.NodeType != ExpressionType.And && node.NodeType != ExpressionType.AndAlso)
                    {
                        return null;
                    }

                    Expression leftSide, rightSide;

                    if (((leftSide = visitor.Visit(node.Left)) as ConstantExpression)?.Value?.Equals(true) ?? false)
                    {
                        return visitor.Visit(node.Right);
                    }

                    if (((rightSide = visitor.Visit(node.Right)) as ConstantExpression)?.Value?.Equals(true) ?? false)
                    {
                        return visitor.Visit(node.Left);
                    }

                    return Expression.MakeBinary(ExpressionType.AndAlso, leftSide, rightSide);
                },
                (RangeExpression node) =>
                node.Type == typeof(bool) && object.Equals(node.Min, false) && object.Equals(node.Max, true)
                                   ? (Expression)Expression.Constant(true)
                                   : node,
                (CompareExpression node) =>
                {
                    var field = node.Left as SourceFieldExpression;
                    var range = node.Right as RangeExpression;

                    if (field == null || range == null)
                    {
                        return null;
                    }

                    switch (node.CompareType)
                    {
                    case ExpressionType.GreaterThan:
                    case ExpressionType.GreaterThanOrEqual:
                    case ExpressionType.LessThan:
                    case ExpressionType.LessThanOrEqual:
                        sortOrders.Add(
                            new OrderByExpression(
                                CustomExpression.MakeSourceField(field.SourceName, field.FieldName),
                                node.CompareType == ExpressionType.GreaterThan || node.CompareType == ExpressionType.GreaterThanOrEqual));
                        break;
                    }

                    return Expression.AndAlso(
                        CustomExpression.MakeCompare(ExpressionType.GreaterThanOrEqual, field, Expression.Constant(range.Min, range.Type)),
                        CustomExpression.MakeCompare(ExpressionType.LessThanOrEqual, field, Expression.Constant(range.Max, range.Type)));
                },
            }.Visit(filter)));
        }
Example #11
0
        public void VisitNotSupportedExpression_ThrowsNotImplentedException()
        {
            var expression = new CustomExpression(typeof(int));
            var result     = SqlPreparationExpressionVisitor.TranslateExpression(expression, _context, _stageMock, _methodCallTransformerProvider);

            Assert.That(result, Is.EqualTo(expression));
        }
        public void Transform_NonParseableEnumerable()
        {
            var argument = new CustomExpression(typeof(IEnumerable <string>));

            var expression = Expression.Call(
                typeof(string).GetMethod("Concat", new[] { typeof(IEnumerable <string>) }),
                argument);

            _transformer.Transform(expression);
        }
        private static Expression WriteIEnumerable(Expression value, ParameterExpression param, Type type, List <Expression> blockContent)
        {
            if (blockContent.Count > 0)
            {
                var block = Expression.Block(blockContent);
                return(CustomExpression.ForEach(param, value, block));
            }

            return(null);
        }
 /// <summary>
 /// The convert to data source.
 /// </summary>
 /// <param name="dataProvider">
 /// The data Provider.
 /// </param>
 /// <param name="expression">
 /// The expression.
 /// </param>
 /// <returns>
 /// The <see cref="Expression"/>.
 /// </returns>
 public static Expression ConvertToRows(this INodeDataProvider dataProvider, Expression expression)
 {
     return(Expression.Call(
                Evaluator.CreateDataSource(expression, null),
                typeof(DataSource).GetTypeInfo().GetDeclaredMethod(nameof(DataSource.GetRows)),
                Expression.Convert(CustomExpression.ExecutionContext(), typeof(IInternalExecutionContext)),
                Expression.Constant(new MultiPartQuery
     {
         WildcardAliases = new string[] { null },
     })));
 }
Example #15
0
        public void Transform_Add_TimeSpan_NoConstantTimeSpan()
        {
            var value      = new CustomExpression(typeof(TimeSpan));
            var methodInfo = MemberInfoFromExpressionUtility.GetMethod(() => DateTime.Now.Add(new TimeSpan()));
            var expression = Expression.Call(_dateTimeInstance, methodInfo, value);

            Assert.That(
                () => _transformer.Transform(expression),
                Throws.TypeOf <NotSupportedException> ().With.Message.EqualTo(
                    "The method 'System.DateTime.Add' can only be transformed to SQL when its argument is a constant value. "
                    + "Expression: '12/17/2012 00:00:00.Add(CustomExpression)'."));
        }
    public void Transform_Add_TimeSpan_NoConstantTimeSpan ()
    {
      var value = new CustomExpression (typeof (TimeSpan));
      var methodInfo = ReflectionUtility.GetMethod (() => DateTime.Now.Add (new TimeSpan ()));
      var expression = Expression.Call (_dateTimeInstance, methodInfo, value);

      Assert.That (
          () => _transformer.Transform (expression),
          Throws.TypeOf<NotSupportedException> ().With.Message.EqualTo (
              "The method 'System.DateTime.Add' can only be transformed to SQL when its argument is a constant value. "
              + "Expression: '12/17/2012 00:00:00.Add(CustomExpression)'."));
    }
Example #17
0
        public void ToWhereSql_EqualsPropertyValue_SqlIsCorrect()
        {
            var dbCommandMock = new Mock <IDbCommand> {
                DefaultValue = DefaultValue.Mock
            };

            var filter = new CustomExpression {
                MyStringAttribute = "Value"
            };
            var whereSql = SqlExtension.ToWhereSql((Expression <Func <CustomExpression, bool> >)(model => model.MyStringAttribute == filter.MyStringAttribute), dbCommandMock.Object);

            Assert.AreEqual("mystringattribute = @mystringattribute", whereSql);
        }
        public void Get_HasANameMatch_ReturnsValidResult()
        {
            var table = new ExpressionTable();
            var expr1 = new CustomExpression()
            {
                Name                = "Test",
                RegexPattern        = "[0-9]",
                ExpressionFunction  = FakeFunc,
                ReplacementFunction = FakeReplaceFunc
            };

            table.Add(expr1);

            table.Get("Test").Should().Be(expr1);
        }
        public void SplitPotentialCompoundComparison_BinaryExpression_NewExpressionOnRightSideWithOnePropertyInfoMember()
        {
            var rightArgumentExpression = Expression.Constant(1);
            var rightArgumentMemberInfo = typeof(TypeForNewExpression).GetProperty("A");
            var rightExpression         = Expression.New(
                TypeForNewExpression.GetConstructor(typeof(int)), new[] { rightArgumentExpression }, rightArgumentMemberInfo);
            var leftExpression = new CustomExpression(typeof(TypeForNewExpression));
            var expression     = Expression.Equal(leftExpression, rightExpression);

            var result = _compoundExpressionComparisonSplitter.SplitPotentialCompoundComparison(expression);

            var expectedResult = Expression.Equal(rightArgumentExpression, Expression.MakeMemberAccess(leftExpression, typeof(TypeForNewExpression).GetProperty("A")));

            SqlExpressionTreeComparer.CheckAreEqualTrees(expectedResult, result);
        }
        public void Add_HasNoConflicts()
        {
            var table = new ExpressionTable();
            var expr  = new CustomExpression
            {
                Name                = "Test",
                RegexPattern        = "[0-9]",
                ExpressionFunction  = FakeFunc,
                ReplacementFunction = FakeReplaceFunc
            };

            Action add = () => table.Add(expr);

            add.Should().NotThrow <Exception>();
        }
Example #21
0
        public Expression CreateExpression(TypeMapRegistry typeMapRegistry,
                                           ParameterExpression srcParam,
                                           ParameterExpression ctxtParam,
                                           ref ParameterExpression parameterContext)
        {
            if (CustomExpression != null)
            {
                return(CustomExpression.ConvertReplaceParameters(srcParam).IfNotNull());
            }

            if (CustomValueResolver != null)
            {
                return(Invoke(Constant(CustomValueResolver), srcParam, ctxtParam));
            }

            if (!SourceMembers.Any() && Parameter.IsOptional)
            {
                return(Constant(Parameter.GetDefaultValue()));
            }

            if (typeMapRegistry.GetTypeMap(new TypePair(SourceType, DestinationType)) == null &&
                Parameter.IsOptional)
            {
                return(Constant(Parameter.GetDefaultValue()));
            }

            var valueResolverExpr = SourceMembers.Aggregate(
                (Expression)srcParam,
                (inner, getter) => getter.MemberInfo is MethodInfo
                    ? getter.MemberInfo.IsStatic()
                        ? Call(null, (MethodInfo)getter.MemberInfo, inner)
                        : (Expression)Call(inner, (MethodInfo)getter.MemberInfo)
                    : MakeMemberAccess(getter.MemberInfo.IsStatic() ? null : inner, getter.MemberInfo)
                );

            valueResolverExpr = valueResolverExpr.IfNotNull();

            if ((SourceType.IsEnumerableType() && SourceType != typeof(string)) ||
                typeMapRegistry.GetTypeMap(new TypePair(SourceType, DestinationType)) != null ||
                !DestinationType.IsAssignableFrom(SourceType))
            {
                /*
                 * var value = context.Mapper.Map(result, null, sourceType, destinationType, context);
                 */
                return(TypeMapPlanBuilder.ContextMap(valueResolverExpr, Default(DestinationType), DestinationType, ref parameterContext));
            }
            return(valueResolverExpr);
        }
Example #22
0
 public override void OnCustomExpression(CustomExpression node)
 {
     if (node is ByRefExpression)
     {
         Write("ref ");
         Write(((ByRefExpression)node).Expression);
         return;
     }
     if (node is OutputExpression)
     {
         Write("out ");
         Write(((OutputExpression)node).Expression);
         return;
     }
     throw new MatchError(new StringBuilder("`node` failed to match `").Append(node).Append("`").ToString());
 }
        private static Expression WriteIEnumerator(Expression value, ParameterExpression param, Type type, List <Expression> blockContent)
        {
            if (blockContent.Count > 0)
            {
                var getMethod = Expression.Call(value, MethodInfos.Instance.EnumeratorGetCurrent);

                var block = Expression.Block(new[] { param }, new[]
                {
                    Expression.Assign(param, type == typeof(object) ? Expression.Convert(getMethod, typeof(object)) : (Expression)getMethod)
                }.Concat(blockContent));

                return(CustomExpression.While(Expression.Call(value, MethodInfos.Instance.MoveNext), block));
            }

            return(null);
        }
Example #24
0
        /// <summary>
        /// The matches.
        /// </summary>
        /// <param name="data">
        /// The data.
        /// </param>
        /// <param name="expression">
        /// The expression.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        private bool Matches(TData data, CustomExpression expression)
        {
            bool result = false;
            Type type   = typeof(TData);

            foreach (var property in type.GetProperties())
            {
                var propertyValue = property.GetValue(data).ToString();
                if (property.Name == expression.Field &&
                    propertyValue == expression.Value)
                {
                    result = true;
                }
            }

            return(result);
        }
Example #25
0
        public void Transform_AddYears()
        {
            var value      = new CustomExpression(typeof(int));
            var methodInfo = MemberInfoFromExpressionUtility.GetMethod(() => DateTime.Now.AddYears(0));
            var expression = Expression.Call(_dateTimeInstance, methodInfo, value);

            var result = _transformer.Transform(expression);

            var expectedResult = new SqlFunctionExpression(
                typeof(DateTime),
                "DATEADD",
                new SqlCustomTextExpression("year", typeof(string)),
                value,
                _dateTimeInstance);

            SqlExpressionTreeComparer.CheckAreEqualTrees(expectedResult, result);
        }
        /// <summary>
        /// Moves field expressions in comparisons to the left.
        /// </summary>
        /// <typeparam name="T">
        /// The type of the expression.
        /// </typeparam>
        /// <param name="expression">
        /// The expression.
        /// </param>
        /// <param name="source">
        /// The source for which the fields should be moved to the left.
        /// </param>
        /// <returns>
        /// The <see cref="Expression"/>.
        /// </returns>
        public static T MoveFieldsToTheLeft <T>(this T expression, DataSource source)
            where T : Expression
        {
            return((T) new GenericVisitor
            {
                (CompareExpression node) =>
                {
                    if (!node.Right.ContainsField(source))
                    {
                        return null;
                    }

                    var opposite = ExpressionExtensions.InvertComparison(node.CompareType);

                    return opposite != null?CustomExpression.MakeCompare(opposite.Value, node.Right, node.Left) : null;
                },
            }.Visit(expression));
        }
Example #27
0
        /// <summary>
        /// The ranges to join filter.
        /// </summary>
        /// <param name="filter">
        /// The filter.
        /// </param>
        /// <returns>
        /// The <see cref="Expression"/>.
        /// </returns>
        private static Expression RangesToJoinFilter(Expression filter)
        {
            return(GenericVisitor.Visit(
                       (CompareExpression node) =>
            {
                var field = node.Left as SourceFieldExpression;
                var range = node.Right as RangeExpression;

                if (field == null || range == null)
                {
                    return null;
                }

                switch (node.CompareType)
                {
                case ExpressionType.Equal:

                    return Expression.AndAlso(
                        CustomExpression.MakeCompare(ExpressionType.GreaterThanOrEqual, field, Expression.Constant(range.Min, range.Type)),
                        CustomExpression.MakeCompare(ExpressionType.LessThanOrEqual, field, Expression.Constant(range.Max, range.Type)));

                case ExpressionType.GreaterThan:
                case ExpressionType.GreaterThanOrEqual:

                    return CustomExpression.MakeCompare(node.CompareType, field, Expression.Constant(range.Min, range.Type));

                case ExpressionType.LessThan:
                case ExpressionType.LessThanOrEqual:

                    return CustomExpression.MakeCompare(node.CompareType, field, Expression.Constant(range.Max, range.Type));

                case ExpressionType.NotEqual:

                    return Expression.Constant(true);

                default:
                    return null;
                }
            },
                       filter));
        }
Example #28
0
        public void TestErrorContent()
        {
            CastDate currentDate = new CastDate {
                Time = 1484953200000
            };
            ReportData reportData = TestUtility.PrepareApplicationReportData("ReportGenerator",
                                                                             null, @".\Data\CurrentBCresults.json", "AED/applications/3/snapshots/6", "PreVersion 1.5.0 sprint 2 shot 2", "V-1.5.0_Sprint 2_2", currentDate,
                                                                             null, null, null, null, null, null);

            var component = new CustomExpression();
            Dictionary <string, string> config = new Dictionary <string, string>
            {
                { "PARAMS", "BC a BC b" },
                { "EXPR", "(a+b)/2" },
                { "a", "60012" },
                { "b", "60013" }
            };
            var str = component.Content(reportData, config);

            Assert.AreEqual("No data found", str);
        }
Example #29
0
        public void ToWhereSql_EqualsPropertyValue_HasParameter()
        {
            var parameters    = new Fakes.DataParameterCollection();
            var dbCommandMock = new Mock <IDbCommand> {
                DefaultValue = DefaultValue.Mock
            };

            dbCommandMock.SetupGet(command => command.Parameters).Returns(parameters);
            dbCommandMock.Setup(command => command.CreateParameter()).Returns(() => Mock.Of <IDbDataParameter>());
            var dbCommand = dbCommandMock.Object;

            var filter = new CustomExpression {
                MyStringAttribute = "Value"
            };

            SqlExtension.ToWhereSql((Expression <Func <CustomExpression, bool> >)(model => model.MyStringAttribute == filter.MyStringAttribute), dbCommand);

            Assert.IsTrue(dbCommand.Parameters.Contains("@mystringattribute"));
            Assert.AreEqual("Value", (dbCommand.Parameters["@mystringattribute"] as IDbDataParameter).Value);
            Assert.AreEqual(DbType.String, (dbCommand.Parameters["@mystringattribute"] as IDbDataParameter).DbType);
        }
 private Expression ResolveSource(ParameterExpression sourceParameter, ParameterExpression contextParameter)
 {
     if (CustomExpression != null)
     {
         return(CustomExpression.ConvertReplaceParameters(sourceParameter).IfNotNull(DestinationType));
     }
     if (CustomValueResolver != null)
     {
         return(CustomValueResolver.ConvertReplaceParameters(sourceParameter, contextParameter));
     }
     if (Parameter.IsOptional)
     {
         DefaultValue = true;
         return(Constant(Parameter.GetDefaultValue(), Parameter.ParameterType));
     }
     return(SourceMembers.Aggregate(
                (Expression)sourceParameter,
                (inner, getter) => getter is MethodInfo
                         ? Call(getter.IsStatic() ? null : inner, (MethodInfo)getter)
                         : (Expression)MakeMemberAccess(getter.IsStatic() ? null : inner, getter)
                ).IfNotNull(DestinationType));
 }
Example #31
0
        public void TestSzContent()
        {
            CastDate currentDate = new CastDate {
                Time = 1484953200000
            };
            ReportData reportData = TestUtility.PrepareApplicationReportData("ReportGenerator",
                                                                             null, @".\Data\CurrentBCresults.json", "AED/applications/3/snapshots/6", "PreVersion 1.5.0 sprint 2 shot 2", "V-1.5.0_Sprint 2_2", currentDate,
                                                                             null, null, null, null, null, null);

            var component = new CustomExpression();
            Dictionary <string, string> config = new Dictionary <string, string>
            {
                { "PARAMS", "SZ a SZ b" },
                { "EXPR", "b/a" },
                { "a", "10151" },
                { "b", "68001" },
                { "FORMAT", "N0" }
            };
            var str = component.Content(reportData, config);

            Assert.AreEqual("11", str);
        }
    public void SplitPotentialCompoundComparison_BinaryExpression_NewExpressionOnRightSideWithOnePropertyInfoMember ()
    {
      var rightArgumentExpression = Expression.Constant (1);
      var rightArgumentMemberInfo = typeof (TypeForNewExpression).GetProperty ("A");
      var rightExpression = Expression.New (
          TypeForNewExpression.GetConstructor (typeof (int)), new[] { rightArgumentExpression }, rightArgumentMemberInfo);
      var leftExpression = new CustomExpression (typeof (TypeForNewExpression));
      var expression = Expression.Equal (leftExpression, rightExpression);

      var result = _compoundExpressionComparisonSplitter.SplitPotentialCompoundComparison (expression);

      var expectedResult = Expression.Equal (rightArgumentExpression, Expression.MakeMemberAccess (leftExpression, typeof (TypeForNewExpression).GetProperty ("A")));
      SqlExpressionTreeComparer.CheckAreEqualTrees (expectedResult, result);
    }
    public void VisitExpression_SingleValueRequired_ConvertsBool_ToSingleValue ()
    {
      var expression = new CustomExpression (typeof (bool));
      var nullableExpression = new CustomExpression (typeof (bool?));

      var visitor = new TestableSqlContextExpressionVisitor (SqlExpressionContext.SingleValueRequired, _stageMock, _mappingResolutionContext);
      var result = visitor.VisitExpression (expression);
      var resultNullable = visitor.VisitExpression (nullableExpression);

      var expected = new SqlConvertedBooleanExpression (GetNonNullablePredicateAsValueExpression (expression));
      SqlExpressionTreeComparer.CheckAreEqualTrees (expected, result);
      var expectedNullable = new SqlConvertedBooleanExpression (GetNullablePredicateAsValueExpression (nullableExpression));
      SqlExpressionTreeComparer.CheckAreEqualTrees (expectedNullable, resultNullable);
    }
 public void GenerateSql_UnsupportedExpression ()
 {
   var unknownExpression = new CustomExpression (typeof (int));
   SqlGeneratingExpressionVisitor.GenerateSql (
       unknownExpression, _commandBuilder, _stageMock);
 }
    public void VisitExpression_SingleValueRequired_LeavesExistingSingleValue ()
    {
      var expression = new CustomExpression (typeof (int));

      var visitor = new TestableSqlContextExpressionVisitor (SqlExpressionContext.SingleValueRequired, _stageMock, _mappingResolutionContext);
      var result = visitor.VisitExpression (expression);

      Assert.That (result, Is.SameAs (expression));
    }
    public void VisitExpression_LeavesExistingPredicate ()
    {
      var expression = new CustomExpression (typeof (bool));
      var nullableExpression = new CustomExpression (typeof (bool?));

      var visitor = new TestableSqlContextExpressionVisitor (SqlExpressionContext.PredicateRequired, _stageMock, _mappingResolutionContext);
      var result = visitor.VisitExpression (expression);
      var resultNullable = visitor.VisitExpression (nullableExpression);

      Assert.That (result, Is.SameAs (expression));
      Assert.That (resultNullable, Is.SameAs (nullableExpression));
    }
    public void VisitExpression_ThrowsOnNonConvertible_ToPredicate ()
    {
      var expression = new CustomExpression (typeof (string));

      var visitor = new TestableSqlContextExpressionVisitor (SqlExpressionContext.PredicateRequired, _stageMock, _mappingResolutionContext);
      visitor.VisitExpression (expression);
    }
    public void Transform_NonParseableEnumerable ()
    {
      var argument = new CustomExpression (typeof (IEnumerable<string>));

      var expression = Expression.Call (
          typeof (string).GetMethod ("Concat", new[] { typeof (IEnumerable<string>) }),
          argument);

      _transformer.Transform (expression);
    }
    public void VisitExpression_ThrowsOnInvalidContext ()
    {
      var expression = new CustomExpression (typeof (string));

      var visitor = new TestableSqlContextExpressionVisitor ((SqlExpressionContext) (-1), _stageMock, _mappingResolutionContext);
      visitor.VisitExpression (expression);
    }
    public void VisitBinaryExpression_NonBoolBinaryExpression_OperandsGetSingleValueSemantics_ComplexValueNotAllowed ()
    {
      var entity = SqlStatementModelObjectMother.CreateSqlEntityDefinitionExpression (typeof (Cook));
      var other = new CustomExpression (typeof (Cook));
      var complexExpressionLeft = BinaryExpression.And (entity, other, ReflectionUtility.GetMethod (() => FakeAndOperator (null, null)));
      var complexExpressionRight = BinaryExpression.And (other, entity, ReflectionUtility.GetMethod (() => FakeAndOperator (null, null)));

      Assert.That (() => _valueRequiredVisitor.VisitBinaryExpression (complexExpressionLeft), Throws.TypeOf<NotSupportedException> ());
      Assert.That (() => _valueRequiredVisitor.VisitBinaryExpression (complexExpressionRight), Throws.TypeOf<NotSupportedException> ());
    }
    public void UnknownExpression ()
    {
      var unknownExpression = new CustomExpression (typeof (int));
      var result = _visitor.VisitExpression (unknownExpression);

      Assert.That (result, Is.SameAs (unknownExpression));
    }
    public void SplitPotentialCompoundComparison_BinaryExpression_NewExpressionOnLeftSideWithTwoMethodInfoMembers ()
    {
      var leftArgumentExpression1 = Expression.Constant (1);
      var leftArgumentExpression2 = Expression.Constant (2);
      var leftArgumentMemberInfo1 = typeof (TypeForNewExpression).GetProperty ("A");
      var leftArgumentMemberInfo2 = typeof (TypeForNewExpression).GetProperty ("B");
      var leftExpression = Expression.New (
          TypeForNewExpression.GetConstructor (typeof (int), typeof (int)),
          new[] { leftArgumentExpression1, leftArgumentExpression2 },
          leftArgumentMemberInfo1,
          leftArgumentMemberInfo2);
      var rightExpression = new CustomExpression (typeof (TypeForNewExpression));
      var expression = Expression.Equal (leftExpression, rightExpression);

      var result = _compoundExpressionComparisonSplitter.SplitPotentialCompoundComparison (expression);

      var expectedResult = Expression.AndAlso (
          Expression.Equal (leftArgumentExpression1, Expression.Property (rightExpression, "A")),
          Expression.Equal (leftArgumentExpression2, Expression.Property (rightExpression, "B")));
      SqlExpressionTreeComparer.CheckAreEqualTrees (expectedResult, result);
    }
    public void GetTableForFromExpression_UnsupportedExpression_Throws ()
    {
      var customExpression = new CustomExpression (typeof (Cook[]));

      SqlPreparationFromExpressionVisitor.AnalyzeFromExpression (
          customExpression, _stageMock, _generator, _methodCallTransformerProvider, _context, null);
    }
    public void Transform_AddYears ()
    {
      var value = new CustomExpression (typeof (int));
      var methodInfo = ReflectionUtility.GetMethod (() => DateTime.Now.AddYears (0));
      var expression = Expression.Call (_dateTimeInstance, methodInfo, value);

      var result = _transformer.Transform (expression);

      var expectedResult = new SqlFunctionExpression (
          typeof (DateTime),
          "DATEADD",
          new SqlCustomTextExpression ("year", typeof (string)),
          value,
          _dateTimeInstance);
      SqlExpressionTreeComparer.CheckAreEqualTrees (expectedResult, result);
    }
    public void Transform_AddDays ()
    {
      var value = new CustomExpression (typeof (double));
      var methodInfo = ReflectionUtility.GetMethod (() => DateTime.Now.AddDays (0.0));
      var expression = Expression.Call (_dateTimeInstance, methodInfo, value);

      var result = _transformer.Transform (expression);

      var expectedResult = new SqlFunctionExpression (
          typeof (DateTime),
          "DATEADD",
          new SqlCustomTextExpression ("millisecond", typeof (string)),
          Expression.Modulo (
              new SqlConvertExpression (typeof (long), Expression.Multiply (value, new SqlLiteralExpression (86400000.0))),
              new SqlLiteralExpression (86400000L)),
          new SqlFunctionExpression
              (
              typeof (DateTime),
              "DATEADD",
              new SqlCustomTextExpression ("day", typeof (string)),
              Expression.Divide (
                  new SqlConvertExpression (typeof (long), Expression.Multiply (value, new SqlLiteralExpression (86400000.0))),
                  new SqlLiteralExpression (86400000L)),
              _dateTimeInstance));
      SqlExpressionTreeComparer.CheckAreEqualTrees (expectedResult, result);
    }