Ejemplo n.º 1
0
        public IPagedList <Category> GetCategories(Product product, string query, int page = 1)
        {
            QueryOver <Category, Category> queryOver = QueryOver.Of <Category>();

            if (!string.IsNullOrWhiteSpace(query))
            {
                queryOver = queryOver.Where(category => category.Name.IsInsensitiveLike(query, MatchMode.Anywhere));
            }

            queryOver = queryOver.Where(category => !category.Id.IsIn(product.Categories.Select(c => c.Id).ToArray()));

            return(_session.Paged(queryOver, page));
        }
        /// <summary>
        /// Given a query term, builds a simple search query and returns the query token.
        /// <para />
        /// Uses the simple search algorithm and uses all those properties that were marked to be used in a simple search.
        /// </summary>
        /// <param name="rawTerm"></param>
        /// <param name="properties"></param>
        /// <returns></returns>
        private QueryOver <T, T> CreateSimpleSearchQuery(string rawTerm, IEnumerable <Expression <Func <T, object> > > properties)
        {
            var searchParameters = properties.ToDictionary(x => x, x => rawTerm);

            QueryOver <T, T> result = QueryOver.Of <T>();

            //First, we're going to split the raw term
            foreach (var term in (rawTerm as string).Split(null))
            {
                var disjunction = Restrictions.Disjunction();

                foreach (var propertyExpression in searchParameters.Keys)
                {
                    var propertyGroup = PropertyGroups.FirstOrDefault(x => x.Expressions.Any(y => String.Equals(y.GetPropertyName(), propertyExpression.GetPropertyName(), StringComparison.CurrentCultureIgnoreCase)));

                    if (propertyGroup == null)
                    {
                        throw new CommandCentralException($"The member, {propertyExpression.GetPropertyName()}, declared no search strategy!  " +
                                                          "This is most likely because it is not searchable.  " +
                                                          "If you believe this is in error, please contact us.", ErrorTypes.Validation);
                    }
                    else
                    {
                        var token = new QueryToken <T>(result, new KeyValuePair <Expression <Func <T, object> >, object>(propertyExpression, term));

                        disjunction.Add(propertyGroup.CriteriaProvider(token));
                    }
                }

                result.Where(disjunction);
            }

            return(result);
        }
        /// <summary>
        /// Creates an advanced query by submitting each filter to the corresponding query provider and appending them all in a conjunction.
        /// </summary>
        /// <param name="filters"></param>
        /// <returns></returns>
        private QueryOver <T, T> CreateAdvancedQuery(Dictionary <Expression <Func <T, object> >, object> filters)
        {
            QueryOver <T, T> result = QueryOver.Of <T>();

            foreach (var filter in filters)
            {
                var propertyGroup = PropertyGroups.FirstOrDefault(x => x.Expressions.Any(y => String.Equals(y.GetPropertyName(), filter.Key.GetPropertyName(), StringComparison.CurrentCultureIgnoreCase)));

                if (propertyGroup == null)
                {
                    throw new CommandCentralException($"The member, {filter.Key.Name}, declared no search strategy!  " +
                                                      "This is most likely because it is not searchable.  " +
                                                      "If you believe this is in error, please contact us.", ErrorTypes.Validation);
                }
                else
                {
                    var disjunction = Restrictions.Disjunction();

                    var token = new QueryToken <T>(result, filter);

                    disjunction.Add(propertyGroup.CriteriaProvider(token));

                    result.Where(disjunction);
                }
            }

            return(result);
        }
Ejemplo n.º 4
0
 public static QueryOver <TRoot, TSub> AddInsensitiveLike <TRoot, TSub>(this QueryOver <TRoot, TSub> queryOver,
                                                                        Expression <Func <TSub, object> > expr,
                                                                        string value,
                                                                        MatchMode matchMode)
 {
     return(queryOver.Where(Restrictions.On(expr).IsInsensitiveLike(value, matchMode ?? MatchMode.Anywhere)));
 }
Ejemplo n.º 5
0
        private QueryOver <CategoryFascicle, CategoryFascicle> SubQueryFascicle(QueryOver <CategoryFascicle, CategoryFascicle> queryOver)
        {
            if (CheckFascicleProcedure.HasValue && CheckFascicleProcedure.Value)
            {
                queryOver = queryOver.Where(x => x.FascicleType == FascicleType.Procedure);
            }
            else
            {
                queryOver = queryOver.Where(x => x.FascicleType != FascicleType.SubFascicle);
            }

            if (Environment.HasValue)
            {
                queryOver = queryOver.Where(x => x.DSWEnvironment == Environment.Value);
            }

            return(queryOver.Select(s => s.Category.Id));
        }
Ejemplo n.º 6
0
        public override QueryOver <NodeVersion> VisitFieldPredicate(FieldPredicateExpression node)
        {
            var fieldName      = node.SelectorExpression.FieldName;
            var valueKey       = node.SelectorExpression.ValueKey;
            var fieldValue     = node.ValueExpression.Value;
            var fieldValueType = fieldValue != null?fieldValue.GetType() : typeof(string);

            switch (fieldName.ToLowerInvariant())
            {
            case "id":
                Guid idValue = GetIdValue(node);

                switch (node.ValueExpression.ClauseType)
                {
                case ValuePredicateType.Equal:
                    return(QueryOver.Of <NodeVersion>().Where(x => x.Node.Id == idValue).Select(x => x.Id));

                case ValuePredicateType.NotEqual:
                    return(QueryOver.Of <NodeVersion>().Where(x => x.Node.Id != idValue).Select(x => x.Id));;

                default:
                    throw new InvalidOperationException(
                              "Cannot query an item by id by any other operator than == or !=");
                }
            }

            // First look up the types of the main field
            AttributeDefinition defAlias  = null;
            AttributeType       typeAlias = null;
            var attributeType             = _activeSession.QueryOver <AttributeDefinition>(() => defAlias)
                                            .JoinAlias(() => defAlias.AttributeType, () => typeAlias)
                                            .Where(() => defAlias.Alias == fieldName)
                                            .Select(x => typeAlias.PersistenceTypeProvider)
                                            .List <string>();

            var typesAlreadyEstablished = new List <string>();
            var typesToQuery            = new List <DataSerializationTypes>();

            foreach (var type in attributeType)
            {
                var typeName = type;
                if (typesAlreadyEstablished.Contains(typeName))
                {
                    continue;
                }
                try
                {
                    typesAlreadyEstablished.Add(typeName);
                    var persisterType = Type.GetType(typeName, false);
                    if (persisterType != null)
                    {
                        var persisterInstance = Activator.CreateInstance(persisterType) as IAttributeSerializationDefinition;
                        if (persisterInstance != null)
                        {
                            typesToQuery.Add(persisterInstance.DataSerializationType);
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }

            // U5-789
            // Workaround pending a better check of what data is actually saved
            // An issue arose because previous data had been saved in long-string,
            // but the datatype changed to be just string, therefore only string was
            // being queried despite all the data residing still in long-string
            if (typesToQuery.Contains(DataSerializationTypes.String) && !typesToQuery.Contains(DataSerializationTypes.LongString))
            {
                typesToQuery.Add(DataSerializationTypes.LongString);
            }

            NodeVersion              aliasNodeVersion         = null;
            Attribute                aliasAttribute           = null;
            AttributeDefinition      aliasAttributeDefinition = null;
            AttributeStringValue     aliasStringValue         = null;
            AttributeLongStringValue aliasLongStringValue     = null;
            AttributeIntegerValue    aliasIntegerValue        = null;
            AttributeDecimalValue    aliasDecimalValue        = null;
            NodeRelation             aliasNodeRelation        = null;
            AttributeDateValue       aliasDateValue           = null;

            QueryOver <NodeVersion, AttributeDefinition> queryExtender = QueryOver.Of <NodeVersion>(() => aliasNodeVersion)
                                                                         .JoinQueryOver <Attribute>(() => aliasNodeVersion.Attributes, () => aliasAttribute)
                                                                         .JoinQueryOver <AttributeDefinition>(() => aliasAttribute.AttributeDefinition, () => aliasAttributeDefinition);

            int numberOfMatchesEvaluated         = 0;
            AbstractCriterion restrictionBuilder = null;

            foreach (var dataSerializationTypese in typesToQuery.Distinct())
            {
                AbstractCriterion           restriction        = null;
                Expression <Func <object> > propertyExpression = null;
                Expression <Func <object> > subkeyExpression   = null;
                List <ValuePredicateType>   validClauseTypes   = null;
                var useLikeMatchForStrings = false;
                switch (dataSerializationTypese)
                {
                case DataSerializationTypes.SmallInt:
                case DataSerializationTypes.LargeInt:
                case DataSerializationTypes.Boolean:
                    queryExtender      = queryExtender.Left.JoinAlias(() => aliasAttribute.AttributeIntegerValues, () => aliasIntegerValue);
                    propertyExpression = () => aliasIntegerValue.Value;
                    subkeyExpression   = () => aliasIntegerValue.ValueKey;
                    validClauseTypes   = new List <ValuePredicateType>()
                    {
                        ValuePredicateType.Equal,
                        ValuePredicateType.GreaterThan,
                        ValuePredicateType.GreaterThanOrEqual,
                        ValuePredicateType.LessThan,
                        ValuePredicateType.LessThanOrEqual,
                        ValuePredicateType.NotEqual
                    };
                    break;

                case DataSerializationTypes.Decimal:
                    queryExtender      = queryExtender.Left.JoinAlias(() => aliasAttribute.AttributeDecimalValues, () => aliasDecimalValue);
                    propertyExpression = () => aliasDecimalValue.Value;
                    subkeyExpression   = () => aliasDecimalValue.ValueKey;
                    validClauseTypes   = new List <ValuePredicateType>()
                    {
                        ValuePredicateType.Equal,
                        ValuePredicateType.GreaterThan,
                        ValuePredicateType.GreaterThanOrEqual,
                        ValuePredicateType.LessThan,
                        ValuePredicateType.LessThanOrEqual,
                        ValuePredicateType.NotEqual
                    };
                    break;

                case DataSerializationTypes.String:
                    queryExtender      = queryExtender.Left.JoinAlias(() => aliasAttribute.AttributeStringValues, () => aliasStringValue);
                    propertyExpression = () => aliasStringValue.Value;
                    subkeyExpression   = () => aliasStringValue.ValueKey;
                    validClauseTypes   = new List <ValuePredicateType>()
                    {
                        ValuePredicateType.Equal,
                        ValuePredicateType.NotEqual,
                        ValuePredicateType.Contains,
                        ValuePredicateType.StartsWith,
                        ValuePredicateType.EndsWith,
                        ValuePredicateType.MatchesWildcard
                    };
                    break;

                case DataSerializationTypes.LongString:
                    queryExtender          = queryExtender.Left.JoinAlias(() => aliasAttribute.AttributeLongStringValues, () => aliasLongStringValue);
                    propertyExpression     = () => aliasLongStringValue.Value;
                    subkeyExpression       = () => aliasLongStringValue.ValueKey;
                    useLikeMatchForStrings = true;
                    validClauseTypes       = new List <ValuePredicateType>()
                    {
                        ValuePredicateType.Equal,
                        ValuePredicateType.NotEqual,
                        ValuePredicateType.Contains,
                        ValuePredicateType.StartsWith,
                        ValuePredicateType.EndsWith,
                        ValuePredicateType.MatchesWildcard
                    };
                    break;

                case DataSerializationTypes.Date:
                    queryExtender      = queryExtender.Left.JoinAlias(() => aliasAttribute.AttributeDateValues, () => aliasDateValue);
                    propertyExpression = () => aliasDateValue.Value;
                    subkeyExpression   = () => aliasDateValue.ValueKey;
                    validClauseTypes   = new List <ValuePredicateType>()
                    {
                        ValuePredicateType.Equal,
                        ValuePredicateType.GreaterThan,
                        ValuePredicateType.GreaterThanOrEqual,
                        ValuePredicateType.LessThan,
                        ValuePredicateType.LessThanOrEqual,
                        ValuePredicateType.NotEqual,
                        ValuePredicateType.Empty
                    };
                    break;
                }

                if (!validClauseTypes.Contains(node.ValueExpression.ClauseType))
                {
                    throw new InvalidOperationException("A field of type {0} cannot be queried with operator {1}".InvariantFormat(dataSerializationTypese.ToString(), node.ValueExpression.ClauseType.ToString()));
                }

                switch (node.ValueExpression.ClauseType)
                {
                case ValuePredicateType.Equal:
                    restriction = GetRestrictionEq(fieldValue, useLikeMatchForStrings, propertyExpression, subkeyExpression, valueKey);
                    break;

                case ValuePredicateType.NotEqual:
                    restriction = !GetRestrictionEq(fieldValue, useLikeMatchForStrings, propertyExpression);
                    break;

                case ValuePredicateType.LessThan:
                    restriction = GetRestrictionLt(fieldValue, propertyExpression);
                    break;

                case ValuePredicateType.LessThanOrEqual:
                    restriction = GetRestrictionLtEq(fieldValue, propertyExpression);
                    break;

                case ValuePredicateType.GreaterThan:
                    restriction = GetRestrictionGt(fieldValue, propertyExpression);
                    break;

                case ValuePredicateType.GreaterThanOrEqual:
                    restriction = GetRestrictionGtEq(fieldValue, propertyExpression);
                    break;

                case ValuePredicateType.Contains:
                    restriction = GetRestrictionContains(fieldValue, propertyExpression);
                    break;

                case ValuePredicateType.StartsWith:
                    restriction = GetRestrictionStarts(fieldValue, propertyExpression);
                    break;

                case ValuePredicateType.EndsWith:
                    restriction = GetRestrictionEnds(fieldValue, propertyExpression);
                    break;
                }

                if (restriction != null)
                {
                    if (numberOfMatchesEvaluated == 0)
                    {
                        restrictionBuilder = restriction;
                        numberOfMatchesEvaluated++;
                    }
                    else
                    {
                        restrictionBuilder = Restrictions.Or(restriction, restrictionBuilder);
                    }
                }
            }

            if (restrictionBuilder != null)
            {
                queryExtender = queryExtender.Where(restrictionBuilder);
            }

            queryExtender = queryExtender
                            .And(x => aliasAttributeDefinition.Alias == fieldName);

            return(queryExtender.Select(x => x.Id));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// The add criteria data.
        /// </summary>
        /// <param name="criteria">
        /// The criteria.
        /// </param>
        /// <param name="deatachQuery">
        /// The deatach query.
        /// </param>
        /// <param name="dpersonDatum">
        /// The dperson datum.
        /// </param>
        /// <param name="ddocument">
        /// The ddocument.
        /// </param>
        /// <param name="dmedicalInsurance">
        /// The dmedical Insurance.
        /// </param>
        /// <param name="emptyCriteria">
        /// The empty Criteria.
        /// </param>
        private void AddCriteriaData(
            SearchStatementCriteria criteria,
            QueryOver <Statement, Statement> deatachQuery,
            InsuredPersonDatum dpersonDatum,
            Document ddocument,
            MedicalInsurance dmedicalInsurance,
            bool emptyCriteria)
        {
            // Номер ВС
            if (!string.IsNullOrEmpty(criteria.CertificateNumber))
            {
                emptyCriteria = false;
                deatachQuery.Where(x => dmedicalInsurance.PolisNumber == criteria.CertificateNumber)
                .And(x => dmedicalInsurance.PolisType.Id == PolisType.В);
            }

            // Имя
            if (!string.IsNullOrEmpty(criteria.FirstName))
            {
                emptyCriteria = false;
                deatachQuery.Where(x => dpersonDatum.FirstName == criteria.FirstName.Trim());
            }

            // Фамилия
            if (!string.IsNullOrEmpty(criteria.LastName))
            {
                emptyCriteria = false;
                deatachQuery.Where(x => dpersonDatum.LastName == criteria.LastName.Trim());
            }

            // Отчество
            if (!string.IsNullOrEmpty(criteria.MiddleName))
            {
                emptyCriteria = false;
                deatachQuery.Where(x => dpersonDatum.MiddleName == criteria.MiddleName.Trim());
            }

            // СНИЛС
            if (!string.IsNullOrEmpty(criteria.SNILS))
            {
                emptyCriteria = false;
                deatachQuery.Where(x => dpersonDatum.Snils == SnilsChecker.SsToShort(criteria.SNILS));
            }

            // Тип документа
            if (criteria.DocumentTypeId > 0 &&
                (!string.IsNullOrEmpty(criteria.DocumentSeries) || !string.IsNullOrEmpty(criteria.DocumentNumber)))
            {
                emptyCriteria = false;
                deatachQuery.Where(x => ddocument.DocumentType.Id == criteria.DocumentTypeId);
            }

            // Серия документа
            if (!string.IsNullOrEmpty(criteria.DocumentSeries))
            {
                emptyCriteria = false;
                deatachQuery.Where(x => ddocument.Series == criteria.DocumentSeries);
            }

            // Номер документа
            if (!string.IsNullOrEmpty(criteria.DocumentNumber))
            {
                emptyCriteria = false;
                deatachQuery.Where(x => ddocument.Number == criteria.DocumentNumber);
            }

            // Номер документа
            if (!string.IsNullOrEmpty(criteria.BirthPlace))
            {
                emptyCriteria = false;
                deatachQuery.Where(x => dpersonDatum.Birthplace == criteria.BirthPlace.Trim());
            }

            // Номер полиса
            if (!string.IsNullOrEmpty(criteria.PolicyNumber))
            {
                emptyCriteria = false;

                // deatachQuery.Where(x => x.NumberPolicy == criteria.PolicyNumber.Trim());
                deatachQuery.Where(x => dmedicalInsurance.Enp == criteria.PolicyNumber.Trim())
                .And(x => dmedicalInsurance.PolisType.Id != PolisType.В);
            }

            // Дата рождения
            if (criteria.BirthDate.HasValue)
            {
                emptyCriteria = false;
                deatachQuery.Where(x => dpersonDatum.Birthday == criteria.BirthDate.Value);
            }

            if (!string.IsNullOrEmpty(criteria.Error))
            {
                emptyCriteria = false;
                Error error = null;
                deatachQuery.JoinAlias(x => x.Errors, () => error).Where(x => error.Message1 == criteria.Error);
            }

            // если не сработал ни один критерий то осталяем выборку пустой
            if (emptyCriteria)
            {
                throw new SetParameterSearchException();
            }
        }
Ejemplo n.º 8
0
        private static void ConjoinAsAndOperation(ICriterion rightCriterion, BinaryFilterResult toReturn, AggregateNodeStatus agg, FilterResult left, ICriterion leftCriterion, FilterResult right, Join[] allJoins, QueryOver <AggregateNodeStatus, AggregateNodeStatus> newQuery)
        {
            // If either side is a binary, it'll already have a subquery generated, so can use that,
            // otherwise we need to make one
            var leftAsBinary     = left as BinaryFilterResult;
            var rightAsBinary    = right as BinaryFilterResult;
            var leftAsSchema     = left as SchemaFilterResult;
            var rightAsSchema    = right as SchemaFilterResult;
            var addedLeftSchema  = false;
            var addedRightSchema = false;

            if (leftAsSchema != null && rightAsSchema != null)
            {
                toReturn.Joins = allJoins;
                var addSchemaJoin = Restrictions.Conjunction()
                                    .Add(leftAsSchema.NhCriterion)
                                    .Add(rightAsSchema.NhCriterion);
                toReturn.Subquery = newQuery.Where(addSchemaJoin);
            }
            else if (leftAsSchema != null)
            {
                toReturn.Joins = allJoins;

                var theQuery = QueryOver.Of(() => agg);
                if (rightCriterion != null)
                {
                    theQuery = theQuery.Where(rightCriterion);
                }
                foreach (var rightJoin in allJoins)
                {
                    theQuery = theQuery.JoinAlias(rightJoin.Path, rightJoin.Alias, rightJoin.JoinType);
                }

                // One side is a schema restriction, and we can generate faster sql by avoiding
                // a subquery and just adding the schema restriction to the field restriction(s)
                var addSchemaJoin = Restrictions.Conjunction()
                                    .Add(leftAsSchema.NhCriterion)
                                    .Add(GetAutoSubqueryCriterion(right));

                theQuery          = theQuery.Where(addSchemaJoin);
                toReturn.Subquery = theQuery;
                return;

                addedLeftSchema = true;
            }
            else if (rightAsSchema != null)
            {
                toReturn.Joins = allJoins;

                var theQuery = QueryOver.Of(() => agg);
                if (leftCriterion != null)
                {
                    theQuery = theQuery.Where(rightCriterion);
                }
                foreach (var rightJoin in allJoins)
                {
                    theQuery = theQuery.JoinAlias(rightJoin.Path, rightJoin.Alias, rightJoin.JoinType);
                }

                // One side is a schema restriction, and we can generate faster sql by avoiding
                // a subquery and just adding the schema restriction to the field restriction(s)
                var addSchemaJoin = Restrictions.Conjunction()
                                    .Add(GetAutoSubqueryCriterion(left))
                                    .Add(rightAsSchema.NhCriterion);

                theQuery          = theQuery.Where(addSchemaJoin);
                toReturn.Subquery = theQuery;
                return;

                addedRightSchema = true;
            }

            if (leftAsBinary == null && !addedLeftSchema)
            {
                left.Subquery = QueryOver.Of(() => agg);

                if (leftCriterion != null)
                {
                    left.Subquery = left.Subquery.Where(leftCriterion);
                }
                foreach (var leftJoin in left.Joins)
                {
                    left.Subquery = left.Subquery.JoinAlias(leftJoin.Path, leftJoin.Alias, leftJoin.JoinType);
                }
            }

            if (rightAsBinary == null && !addedRightSchema)
            {
                right.Subquery = QueryOver.Of(() => agg);
                if (rightCriterion != null)
                {
                    right.Subquery = right.Subquery.Where(rightCriterion);
                }
                foreach (var rightJoin in right.Joins)
                {
                    right.Subquery = right.Subquery.JoinAlias(rightJoin.Path, rightJoin.Alias, rightJoin.JoinType);
                }
            }

            toReturn.Joins    = new List <Join>(left.Joins);
            toReturn.Subquery = left
                                .Subquery
                                .WithSubquery.WhereProperty(x => x.NodeVersion.Id).In(right.Subquery.Select(x => x.NodeVersion.Id));
        }
Ejemplo n.º 9
0
 /// <summary>
 /// <see cref="ITreeNodeEntity{T}"/>를 구현한 노드의 자식 노드들이 없는 경우를 조회하는 조건을 추가합니다.
 /// </summary>
 public static QueryOver <TRoot, TSub> AddHasNotChild <TRoot, TSub>(this QueryOver <TRoot, TSub> queryOver)
     where TSub : ITreeNodeEntity <TSub>
 {
     return(queryOver.Where(Restrictions.On <TSub>(node => node.Children).IsEmpty));
 }
Ejemplo n.º 10
0
 public static QueryOver <TRoot, TSub> AddWhere <TRoot, TSub>(this QueryOver <TRoot, TSub> queryOver,
                                                              Expression <Func <TSub, bool> > expr)
 {
     return(queryOver.Where(expr));
 }
Ejemplo n.º 11
0
 public static QueryOver <T, T> AddWhere <T>(this QueryOver <T, T> queryOver, Expression <Func <bool> > expr)
 {
     return(queryOver.Where(expr));
 }