private bool IsNullable(MemberExpression memberExpression, BinaryExpression equalityExpression)
        {
            if (_functionRegistry.TryGetGenerator(memberExpression.Member, out _))
            {
                // We have to skip the property as it will be converted to a function that can return null
                // if the argument is null
                return(IsNullable(memberExpression.Expression, equalityExpression));
            }

            var memberType = memberExpression.Member.GetPropertyOrFieldType();

            if (memberType?.IsValueType == true && !memberType.IsNullable())
            {
                return(IsNullable(memberExpression.Expression, equalityExpression));
            }

            // Check if there was a not null check prior or after the equality expression
            if (IsEqualOrNotEqual(equalityExpression) &&
                _equalityNotNullMembers.TryGetValue(equalityExpression, out var notNullMembers) &&
                notNullMembers.Any(o => AreEqual(o, memberExpression)))
            {
                return(false);
            }

            if (!ExpressionsHelper.TryGetMappedNullability(_sessionFactory, memberExpression, out var nullable) || nullable)
            {
                return(true);                // The expression contains one or many unsupported nodes or the member is nullable
            }

            return(IsNullable(memberExpression.Expression, equalityExpression));
        }
Example #2
0
        private IOperand createValueOperand(Type type, object value, Expression expr)
        {
            bool includeTimeValue = ExpressionsHelper.IncludeTimeValue(expr);
            var  storageTZ        = false;

            if (includeTimeValue)
            {
                if (value.GetType() == typeof(DateTime) && ((MethodCallExpression)expr).Arguments.Count == 2)
                {
                    storageTZ = (bool)this.evaluateExpression(((MethodCallExpression)expr).Arguments[1]);
                }
                if (value.GetType() == typeof(string) && ((MethodCallExpression)expr).Arguments.Count == 1)
                {
                    storageTZ = (bool)this.evaluateExpression(((MethodCallExpression)expr).Arguments[0]);
                }
            }

            int offsetDays = 0;

            if (ExpressionsHelper.HasOffsetDays(expr))
            {
                offsetDays = (int)this.evaluateExpression(((MethodCallExpression)expr).Arguments[0]);
            }
            bool isIntegerForUserId = ExpressionsHelper.IsIntegerForUserId(expr);

            return(CreateValueOperand(type, value, includeTimeValue, offsetDays, storageTZ, false, false, isIntegerForUserId));
        }
Example #3
0
        private IOperand createValueOperand(Type type, object value, Expression expr)
        {
            bool includeTimeValue   = ExpressionsHelper.IncludeTimeValue(expr);
            bool isIntegerForUserId = ExpressionsHelper.IsIntegerForUserId(expr);

            return(CreateValueOperand(type, value, includeTimeValue, false, false, isIntegerForUserId));
        }
        public async Task <List <ChatVm> > FindChatsByStringQueryAsync(string searchQuery, long?navigationId = 0, bool?direction = true, long?userId = null)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                ExpressionsHelper helper = new ExpressionsHelper();
                var searchExpression     = helper.GetChatExpression(searchQuery);
                IQueryable <Chat> query  = context.Chats
                                           .Where(opt => !opt.Deleted)
                                           .AsNoTracking();
                if (userId == null)
                {
                    query = query.Where(opt => (opt.Type == (short)ChatType.Public));
                }
                else
                {
                    query = query.Where(opt => opt.ChatUsers
                                        .Any(chatUser => chatUser.UserId == userId && !chatUser.Banned && !chatUser.Deleted) || (opt.Type == (short)ChatType.Public));
                }

                query = query.Where(searchExpression);
                if (direction.GetValueOrDefault() == true)
                {
                    query = query.OrderBy(opt => opt.Id)
                            .Where(opt => opt.Id > navigationId.GetValueOrDefault());
                }
                else
                {
                    query = query.OrderByDescending(opt => opt.Id)
                            .Where(opt => opt.Id < navigationId.GetValueOrDefault());
                }
                List <Chat> chats = await query.ToListAsync().ConfigureAwait(false);

                return(ChatConverter.GetChatsVm(chats));
            }
        }
Example #5
0
        public async Task <List <ChannelVm> > FindChannelsByStringQueryAsync(string searchQuery, long?navigationId, bool?direction = true)
        {
            ExpressionsHelper helper = new ExpressionsHelper();
            var searchExpression     = helper.GetChannelExpression(searchQuery);

            using (MessengerDbContext context = contextFactory.Create())
            {
                var query = context.Channels
                            .AsNoTracking()
                            .Where(opt => !opt.Deleted)
                            .Where(searchExpression);
                if (direction.GetValueOrDefault())
                {
                    query = query.OrderBy(opt => opt.ChannelId)
                            .Where(opt => opt.ChannelId > navigationId.GetValueOrDefault());
                }
                else
                {
                    query = query.OrderByDescending(opt => opt.ChannelId)
                            .Where(opt => opt.ChannelId < navigationId.GetValueOrDefault());
                }
                var channels = await query.ToListAsync().ConfigureAwait(false);

                return(ChannelConverter.GetChannels(channels));
            }
        }
 private bool IsCastRequired(Expression expression, System.Type toType, out bool existType)
 {
     existType = false;
     return(toType != typeof(object) &&
            expression.Type.UnwrapIfNullable() != toType.UnwrapIfNullable() &&
            IsCastRequired(ExpressionsHelper.GetType(_parameters, expression), TypeFactory.GetDefaultTypeFor(toType), out existType));
 }
Example #7
0
        public void AddColumnToShow(Expression <Func <T, object> > column, string columnHeaderName, string stringFormat, SearcherTextAlignment textAlignment)
        {
            var propertyName = ExpressionsHelper.GetPropertyName <T>(column);

            var columnName = string.IsNullOrEmpty(columnHeaderName) ? propertyName : columnHeaderName;

            var binding = new SearcherDataBinding()
            {
                HeaderName    = columnName,
                PropertyName  = propertyName,
                StringFormat  = stringFormat,
                TextAlignment = textAlignment
            };

            _DataGridColumnsNamesBinding.Add(binding);
            //var col = new Microsoft.Windows.Controls.DataGridTextColumn()
            //{
            //    Header = columnName,
            //    IsReadOnly = true,
            //    Binding = new Binding(propertyName)
            //};
            //col.Binding.StringFormat = stringFormat;

            ////_View.SearchItemsDataGridView.Columns.Add(col);
            //_UIColumns.Add(col);
        }
        public static void Render <T>(IEnumerable <ResultOrderingModel> orderBy, StringBuilder sb)
        {
            var olist = orderBy?.ToList();

            if ((olist == null) || (olist.Count == 0))
            {
                return;
            }

            sb.Append(" ORDER BY ");

            for (var i = 0; i < olist.Count; i++)
            {
                if (i > 0)
                {
                    sb.Append(", ");
                }

                var order = olist[i];

                var propchain = ExpressionsHelper.GetPropertiesChainText <T>(ExpressionsHelper.RemoveConvert(order.Expression));
                if (string.IsNullOrWhiteSpace(propchain))
                {
                    throw new InvalidOperationException($"Invalid OrderBy expression {order.Expression}");
                }

                var tabAndCol = DotPathHelper.SplitToEntityAndAttribute(propchain);

                sb.Append($"[{tabAndCol.Item1}].[{tabAndCol.Item2}]");

                sb.Append(order.Ascending ? " ASC" : " DESC");
            }

            sb.AppendLine();
        }
Example #9
0
        public async Task <List <UserVm> > FindUsersByStringQueryAsync(string stringQuery, long?navigationUserId = 0, bool?direction = true)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                ExpressionsHelper helper = new ExpressionsHelper();
                var query = context.Users
                            .Include(opt => opt.Emails)
                            .Include(opt => opt.Phones)
                            .Include(opt => opt.BlackList)
                            .Where(opt => opt.NodeId == NodeSettings.Configs.Node.Id && opt.Deleted == false && !opt.Deleted && opt.Confirmed == true);
                if (direction.GetValueOrDefault())
                {
                    query = query.OrderBy(opt => opt.Id)
                            .Where(opt => opt.Id > navigationUserId.GetValueOrDefault());
                }
                else
                {
                    query = query.OrderByDescending(opt => opt.Id)
                            .Where(opt => opt.Id < navigationUserId.GetValueOrDefault());
                }
                List <User> users = await query.Where(helper.GetUserExpression(stringQuery))
                                    .ToListAsync().ConfigureAwait(false);

                return(UserConverter.GetUsersVm(users));
            }
        }
Example #10
0
        private bool IsCastRequired(string sqlFunctionName, Expression argumentExpression, System.Type returnType)
        {
            var argumentType = ExpressionsHelper.GetType(_parameters, argumentExpression);

            if (argumentType == null || returnType == typeof(object))
            {
                return(false);
            }

            var returnNhType = TypeFactory.GetDefaultTypeFor(returnType);

            if (returnNhType == null)
            {
                return(true);                // Fallback to the old behavior
            }

            var sqlFunction = _parameters.SessionFactory.SQLFunctionRegistry.FindSQLFunction(sqlFunctionName);

            if (sqlFunction == null)
            {
                return(true);                // Fallback to the old behavior
            }

            var fnReturnType = sqlFunction.GetEffectiveReturnType(new[] { argumentType }, _parameters.SessionFactory, false);

            return(fnReturnType == null || IsCastRequired(fnReturnType, returnNhType, out _));
        }
Example #11
0
        public async Task <List <ChatVm> > FindChatsAsync(SearchChatVm template, int limit = 100, long navigationChatId = 0, long?nodeId = null)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                IQueryable <Chat> query;
                if (template != null)
                {
                    ExpressionsHelper expressionsHelper = new ExpressionsHelper();
                    query = context.Chats
                            .AsNoTracking()
                            .OrderBy(chat => chat.Id)
                            .Where(expressionsHelper.GetChatExpression(template))
                            .Take(limit);
                }
                else
                {
                    query = context.Chats
                            .AsNoTracking()
                            .OrderBy(chat => chat.Id)
                            .Take(limit);
                }
                if (nodeId != null)
                {
                    query = query.Where(chat => chat.NodesId.Contains(nodeId.Value));
                }
                List <Chat> result = await query
                                     .Where(chat => chat.Deleted == false && chat.Id > navigationChatId && (ChatType)chat.Type != ChatType.Private)
                                     .ToListAsync()
                                     .ConfigureAwait(false);

                return(ChatConverter.GetChatsVm(result));
            }
        }
        bool IIsEntityDecider.IsEntity(MemberExpression expression, out bool isIdentifier)
        {
            isIdentifier =
                ExpressionsHelper.TryGetMappedType(_sessionFactory, expression, out var mappedType, out var entityPersister, out _, out var memberPath) &&
                entityPersister?.IdentifierPropertyName == memberPath;

            return(mappedType?.IsEntityType == true);
        }
Example #13
0
        private bool isExpressionWithStringBasedSyntax(Expression rightExpression)
        {
            // it is for case when right expression is a method call to IncludeTimeValue method
            rightExpression = ExpressionsHelper.RemoveIncludeTimeValueMethodCallIfAny(rightExpression);

            return(rightExpression.NodeType == ExpressionType.Convert &&
                   rightExpression.Type.IsSubclassOf(typeof(BaseFieldType)));
        }
Example #14
0
 private IType GetType(Expression expression)
 {
     // Try to get the mapped type for the member as it may be a non default one
     return(expression.Type == typeof(object)
                         ? null
                         : (ExpressionsHelper.TryGetMappedType(_parameters.SessionFactory, expression, out var type, out _, out _, out _)
                                 ? type
                                 : TypeFactory.GetDefaultTypeFor(expression.Type)));
 }
Example #15
0
        private static bool IsCircularReference(PropertyInfo property, object propertyValue, List <object> serializeStack)
        {
            if (propertyValue == null || ExpressionsHelper.IsSimpleType(propertyValue.GetType()))
            {
                return(false);
            }

            return(serializeStack.Contains(propertyValue));
        }
Example #16
0
        public override Expression Visit(Expression expression)
        {
            // Only evaluate expressions which do not use any of the surrounding parameter expressions. Don't evaluate
            // lambda expressions (even if you could), we want to analyze those later on.
            if (expression == null)
            {
                return(null);
            }

            if (expression.NodeType == ExpressionType.Lambda || !_partialEvaluationInfo.IsEvaluatableExpression(expression) ||
                #region NH additions
                // Variables should be evaluated only when they are part of an evaluatable expression (e.g. o => string.Format("...", variable))
                expression is UnaryExpression unaryExpression &&
                ExpressionsHelper.IsVariable(unaryExpression.Operand, out _, out _))
            #endregion
            { return(base.Visit(expression)); }

            Expression evaluatedExpression;
            try
            {
                evaluatedExpression = EvaluateSubtree(expression);
            }
            catch (Exception ex)
            {
                // Evaluation caused an exception. Skip evaluation of this expression and proceed as if it weren't evaluable.
                var baseVisitedExpression = base.Visit(expression);

                throw new HibernateException($"Evaluation failure on {baseVisitedExpression}", ex);
            }

            if (evaluatedExpression != expression)
            {
                evaluatedExpression = EvaluateIndependentSubtrees(evaluatedExpression, _preTransformationParameters);
            }

            #region NH additions

            // When having multiple level closure, we have to evaluate each closure independently
            if (evaluatedExpression is ConstantExpression constantExpression)
            {
                evaluatedExpression = VisitConstant(constantExpression);
            }

            // Variables in expressions are never a constant, they are encapsulated as fields of a compiler generated class.
            if (expression.NodeType != ExpressionType.Constant &&
                _preTransformationParameters.MinimizeParameters &&
                evaluatedExpression is ConstantExpression variableConstant &&
                !_preTransformationParameters.QueryVariables.ContainsKey(variableConstant) &&
                ExpressionsHelper.IsVariable(expression, out var path, out var closureContext))
            {
                _preTransformationParameters.QueryVariables.Add(variableConstant, new QueryVariable(path, closureContext));
            }

            #endregion

            return(evaluatedExpression);
        }
 public void DecodeMemberAccessExpression()
 {
     Assert.That(ExpressionsHelper.DecodeMemberAccessExpression <TestingClass, int>(x => x.IntProp),
                 Is.EqualTo(typeof(TestingClass).GetMember("IntProp")[0]));
     Assert.That(ExpressionsHelper.DecodeMemberAccessExpression <TestingClass, bool>(x => x.BoolProp),
                 Is.EqualTo(typeof(TestingClass).GetMember("BoolProp")[0]));
     Assert.That(ExpressionsHelper.DecodeMemberAccessExpression <TestingClass, IEnumerable <string> >(x => x.CollectionProp),
                 Is.EqualTo(typeof(TestingClass).GetMember("CollectionProp")[0]));
 }
        private static IType GetCandidateType(
            ISessionFactoryImplementor sessionFactory,
            IEnumerable <ConstantExpression> constantExpressions,
            ConstantTypeLocatorVisitor visitor,
            System.Type constantType)
        {
            IType candidateType = null;

            foreach (var expression in constantExpressions)
            {
                // In order to get the actual type we have to check first the related member expressions, as
                // an enum is translated in a numeric type when used in a BinaryExpression and also it can be mapped as string.
                // By getting the type from a related member expression we also get the correct length in case of StringType
                // or precision when having a DecimalType.
                if (!visitor.RelatedExpressions.TryGetValue(expression, out var relatedExpressions))
                {
                    continue;
                }
                foreach (var relatedExpression in relatedExpressions)
                {
                    if (!ExpressionsHelper.TryGetMappedType(sessionFactory, relatedExpression, out var mappedType, out _, out _, out _))
                    {
                        continue;
                    }

                    if (mappedType.IsCollectionType)
                    {
                        var collection = (IQueryableCollection)((IAssociationType)mappedType).GetAssociatedJoinable(sessionFactory);
                        mappedType = collection.ElementType;
                    }

                    if (candidateType == null)
                    {
                        candidateType = mappedType;
                    }
                    else if (!candidateType.Equals(mappedType))
                    {
                        return(null);
                    }
                }
            }

            if (candidateType == null)
            {
                return(null);
            }

            // When comparing an integral column with a real parameter, the parameter type must remain real type
            // and the column needs to be casted in order to prevent invalid results (e.g. Where(o => o.Integer >= 2.2d)).
            if (constantType.IsRealNumberType() && candidateType.ReturnedClass.IsIntegralNumberType())
            {
                return(null);
            }

            return(candidateType);
        }
Example #19
0
 public string GetSql(Expression expr)
 {
     Result.Clear();
     if (expr.Type == typeof(bool) && expr.NodeType == ExpressionType.MemberAccess)
     {
         expr = ExpressionsHelper.GetBinaryExpression(expr);
     }
     Visit(expr);
     return(Result.ToString());
 }
        public static Expression <Func <SPListItem, bool> > GetOperation_AndNeq(SPField field, string[] values)
        {
            var andNotConditions = new List <Expression <Func <SPListItem, bool> > >();

            foreach (string _val in values)
            {
                andNotConditions.Add(GetOperation_Neq(field, _val));
            }

            return(ExpressionsHelper.CombineAnd(andNotConditions));
        }
Example #21
0
        protected override Expression VisitInvocation(InvocationExpression expression)
        {
            if (ExpressionsHelper.TryGetDynamicMemberBinder(expression, out _))
            {
                // Avoid adding System.Runtime.CompilerServices.CallSite instance as a parameter
                base.Visit(expression.Arguments[1]);
                return(expression);
            }

            return(base.VisitInvocation(expression));
        }
        public static Expression <Func <SPListItem, bool> > GetOperation_OrEq(SPField field, string[] values)
        {
            var orConditions = new List <Expression <Func <SPListItem, bool> > >();

            foreach (string _val in values)
            {
                orConditions.Add(GetOperation_Eq(field, _val));
            }

            return(ExpressionsHelper.CombineOr(orConditions));
        }
Example #23
0
        protected override Expression VisitInvocation(InvocationExpression expression)
        {
            if (ExpressionsHelper.TryGetDynamicMemberBinder(expression, out var memberBinder))
            {
                Visit(expression.Arguments[1]);
                FormatBinder(memberBinder);
                return(expression);
            }

            return(base.VisitInvocation(expression));
        }
Example #24
0
        private bool IsCastRequired(Expression expression, System.Type toType, out bool needTransparentCast)
        {
            needTransparentCast =
                toType != typeof(object) &&
                expression.Type != typeof(object) &&
                expression.Type != toType &&
                HqlIdent.SupportsType(toType) &&
                expression.Type.UnwrapIfNullable() != toType.UnwrapIfNullable();

            return(needTransparentCast && IsCastRequired(ExpressionsHelper.GetType(_parameters, expression), TypeFactory.GetDefaultTypeFor(toType), out needTransparentCast));
        }
Example #25
0
        public IOperand CreateValueOperandForStringBasedSyntax(Expression expr)
        {
            var newExpr = ExpressionsHelper.RemoveIncludeTimeValueMethodCallIfAny(expr);

            // retrieve internal native expression from string based syntax
            var internalExpression = ((UnaryExpression)((UnaryExpression)newExpr).Operand).Operand;

            // use conversion type as operand type (subclass of BaseFieldType should be used here)
            // because conversion operand has always string type for string based syntax
            return(this.CreateValueOperandForNativeSyntax(internalExpression, newExpr.Type, expr));
        }
Example #26
0
        public IQueryBuilder <T> Join <T2>(Expression <Func <T, T2> > expression)
        {
            var path = ExpressionsHelper.GetPropertiesChainText <T>(expression);

            if (string.IsNullOrWhiteSpace(path))
            {
                throw new InvalidOperationException($"Invalid join expression {expression}");
            }
            Include(path);

            return(this);
        }
Example #27
0
        private HqlTreeNode VisitInvocationExpression(InvocationExpression expression)
        {
#if NETCOREAPP2_0_OR_GREATER
            if (ExpressionsHelper.TryGetDynamicMemberBinder(expression, out var binder))
            {
                return(_hqlTreeBuilder.Dot(
                           VisitExpression(expression.Arguments[1]).AsExpression(),
                           _hqlTreeBuilder.Ident(binder.Name)));
            }
#endif
            return(VisitExpression(expression.Expression));
        }
Example #28
0
        public IQueryBuilder <T> Where(Expression <Func <T, bool> > condition)
        {
            if (condition == null)
            {
                throw new ArgumentNullException(nameof(condition));
            }

            m_where = m_where == s_emptyWhere ? condition : ExpressionsHelper.CombineConditions(m_where, condition);


            return(this);
        }
Example #29
0
        // Right expression for string based syntax should be constant, variable or method call
        protected bool isValidRightExpressionWithStringBasedSyntax(Expression rightExpression)
        {
            // it is for case when right expression is a method call to IncludeTimeValue method
            rightExpression = ExpressionsHelper.RemoveIncludeTimeValueMethodCallIfAny(rightExpression);

            // it is for case when right expression is a method call to OffsetDays method
            rightExpression = ExpressionsHelper.RemoveOffsetDaysMethodCallIfAny(rightExpression);

            // 1st convertion is conversion to specific subclass of BaseFieldType
            if (!(rightExpression is UnaryExpression))
            {
                return(false);
            }
            if (rightExpression.NodeType != ExpressionType.Convert)
            {
                return(false);
            }
            if (!rightExpression.Type.IsSubclassOf(typeof(BaseFieldType)))
            {
                return(false);
            }

            // 2nd convertion is conversion to BaseFieldType
            var operandExpression = ((UnaryExpression)rightExpression).Operand;

            if (!(operandExpression is UnaryExpression))
            {
                return(false);
            }
            if (operandExpression.NodeType != ExpressionType.Convert)
            {
                return(false);
            }
            if (operandExpression.Type != typeof(BaseFieldType))
            {
                return(false);
            }

            var expr = ((UnaryExpression)operandExpression).Operand;

            // operand should be valid native expression
            if (!this.isValidRightExpressionWithNativeSyntax(expr))
            {
                return(false);
            }

            // type of casted expression should be string (althoug compiler will not
            // allow to cast to subclass of BaseFieldType from anything except string - because
            // BaseFieldType has explicit conversion operator only for string, we need to do this
            // because there is possibility to cast from BaseFieldType to any subclass)
            return(expr.Type == typeof(string));
        }
Example #30
0
        private static void SetObjectStateRecursive(object entity, ObjectState objectState, List <object> serializeStack, IEnumerable <Type> ignoreTypes)
        {
            if (entity != null)
            {
                var type                = entity.GetType();
                var entityType          = typeof(Entity);
                var objectStateProperty = type.GetProperty("ObjectState", BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

                serializeStack.Add(entity);
                objectStateProperty.SetValue(entity, objectState);

                foreach (var property in type.GetProperties())
                {
                    var isPropertySubclassOfEntity = property.PropertyType.IsSubclassOf(entityType);
                    var isEnumerableEntity         = ExpressionsHelper.IsPropertyNonStringEnumerable(property.PropertyType) &&
                                                     ExpressionsHelper.GetElementType(property.PropertyType) != null &&
                                                     ExpressionsHelper.GetElementType(property.PropertyType).IsSubclassOf(entityType);
                    object propertyValue = null;

                    if (isPropertySubclassOfEntity || isEnumerableEntity)
                    {
                        propertyValue = property.GetValue(entity);
                    }

                    if (propertyValue != null)
                    {
                        if (isPropertySubclassOfEntity)
                        {
                            if (!IsCircularReference(property, propertyValue, serializeStack) && !ignoreTypes.Contains(property.PropertyType))
                            {
                                SetObjectStateRecursive(propertyValue, objectState, serializeStack, ignoreTypes);
                            }
                        }
                        else if (isEnumerableEntity)
                        {
                            var entityList = propertyValue as IEnumerable <object>;

                            if (entityList != null)
                            {
                                foreach (var entityFromList in entityList)
                                {
                                    if (!IsCircularReference(property, entityFromList, serializeStack) && !ignoreTypes.Contains(entityFromList.GetType()))
                                    {
                                        SetObjectStateRecursive(entityFromList, objectState, serializeStack, ignoreTypes);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }