示例#1
0
        /// <summary>
        /// Возвращает сортированный список периодов в которых запускались пакетные операции экспорта в СМО для указаннго
        ///   отправителя либо получателя
        /// </summary>
        /// <param name="senderId">
        /// The sender Id.
        /// </param>
        /// <param name="receiverId">
        /// The receiver Id.
        /// </param>
        /// <returns>
        /// The <see cref="IList"/>.
        /// </returns>
        public IList <Period> GetExportSmoBatchPeriodList(Guid senderId, Guid receiverId)
        {
            // Выбираем батчи
            var subQuery =
                QueryOver.Of <Batch>()
                .Where(x => x.Subject.Id == ExchangeSubjectType.Smo && x.Type.Id == ExchangeFileType.Rec)
                .Select(x => x.Period.Id);

            // Выбираем по отправителю
            if (senderId != null && senderId != Guid.Empty)
            {
                subQuery.Where(x => x.Sender.Id == senderId);
            }

            // Выбираем по получателю
            if (receiverId != null && receiverId != Guid.Empty)
            {
                subQuery.Where(x => x.Receiver.Id == receiverId);
            }

            // Выбираем периоды
            var session = ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession();
            var result  =
                session.QueryOver <Period>()
                .WithSubquery.WhereProperty(x => x.Id)
                .In(subQuery)
                .OrderBy(x => x.Year)
                .Desc.ThenBy(x => x.Code)
                .Desc.List();

            return(result);
        }
示例#2
0
        public void DetachedRestrictions()
        {
            DetachedCriteria expected =
                DetachedCriteria.For <Person>("personAlias")
                .Add(Restrictions.Between("Age", 18, 65))
                .Add(Restrictions.Between("personAlias.Age", 18, 65))
                .Add(Restrictions.In("Name", new string[] { "name1", "name2", "name3" }))
                .Add(Restrictions.In("personAlias.Name", new ArrayList()
            {
                "name1", "name2", "name3"
            }));

            Person             personAlias = null;
            QueryOver <Person> actual      =
                QueryOver.Of <Person>(() => personAlias)
                .WhereRestrictionOn(p => p.Age).IsBetween(18).And(65)
                .WhereRestrictionOn(() => personAlias.Age).IsBetween(18).And(65)
                .AndRestrictionOn(p => p.Name).IsIn(new string[] { "name1", "name2", "name3" })
                .AndRestrictionOn(() => personAlias.Name).IsIn(new ArrayList()
            {
                "name1", "name2", "name3"
            });

            AssertCriteriaAreEqual(expected, actual);
        }
示例#3
0
        public string get_current_script_hash(string script_name)
        {
            ScriptsRun script = get_from_script_cache(script_name);

            if (script != null)
            {
                return(script.text_hash);
            }

            QueryOver <ScriptsRun> crit = QueryOver.Of <ScriptsRun>()
                                          .Where(x => x.script_name == script_name)
                                          .OrderBy(x => x.id).Desc
                                          .Take(1);

            string hash = string.Empty;

            try
            {
                IList <ScriptsRun> items = repository.get_with_criteria(crit);
                if (items != null && items.Count > 0)
                {
                    hash = items[0].text_hash;
                }
            }
            catch (Exception ex)
            {
                Log.bound_to(this).log_an_error_event_containing(
                    "{0} with provider {1} does not provide a facility for hashing (through recording scripts run) at this time.{2}{3}",
                    GetType(), provider, Environment.NewLine, ex.Message);
                throw;
            }

            return(hash);
        }
        public void DetachedQuery_SimpleCriterion()
        {
            using (ISession s = OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    s.Save(new Person()
                    {
                        Name = "test person 1", Age = 20
                    });
                    t.Commit();
                }

            using (ISession s = OpenSession())
            {
                QueryOver <Person> personQuery =
                    QueryOver.Of <Person>()
                    .Where(p => p.Name == "test person 1");

                IList <Person> actual =
                    personQuery.GetExecutableQueryOver(s)
                    .List();

                Assert.That(actual[0].Age, Is.EqualTo(20));
            }
        }
        public virtual string get_version(string repository_path)
        {
            string version = "0";

            QueryOver <Version> crit = QueryOver.Of <Version>()
                                       .Where(x => x.repository_path == (repository_path ?? string.Empty))
                                       .OrderBy(x => x.entry_date).Desc
                                       .Take(1);

            IList <Version> items = null;

            try
            {
                items = retry_policy.ExecuteAction(() => repository.get_with_criteria(crit));
            }
            catch (Exception ex)
            {
                Log.bound_to(this).log_a_warning_event_containing("{0} with provider {1} does not provide a facility for retrieving versions at this time.{2}{3}",
                                                                  GetType(), provider, Environment.NewLine, ex.to_string());
            }

            if (items != null && items.Count > 0)
            {
                version = items[0].version;
            }

            return(version);
        }
示例#6
0
        public async Task StatelessSessionAsync()
        {
            int personId;

            using (var ss = Sfi.OpenStatelessSession())
                using (var t = ss.BeginTransaction())
                {
                    var person = new Person {
                        Name = "test1"
                    };
                    await(ss.InsertAsync(person));
                    personId = person.Id;
                    await(t.CommitAsync());
                }

            using (var ss = Sfi.OpenStatelessSession())
                using (ss.BeginTransaction())
                {
                    var statelessPerson1 = (await(ss.QueryOver <Person>()
                                                  .ListAsync()))[0];

                    Assert.That(statelessPerson1.Id, Is.EqualTo(personId));

                    var statelessPerson2 = (await(QueryOver.Of <Person>()
                                                  .GetExecutableQueryOver(ss)
                                                  .ListAsync()))[0];

                    Assert.That(statelessPerson2.Id, Is.EqualTo(personId));
                }
        }
示例#7
0
        public int GetUsersByRoleCount(UserType type, int roleId, string searchByName)
        {
            UserEntity userAlias = null;

            try
            {
                var session = GetSession();

                var usersWithRoleNotFromAuthServiceWithId = QueryOver.Of <UserEntity>()
                                                            .JoinQueryOver <RoleEntity>(m => m.Roles)
                                                            .Where(a => !a.AuthenticationServiceOnly).And(a => a.Id == roleId)
                                                            .Select(Projections.Distinct(Projections.Property <UserEntity>(m => m.Id)));

                var query = session.QueryOver(() => userAlias);

                query = AddRestrictionOnUserTypeToQuery(query, type);
                query = AddSearchByNameToQuery(query, searchByName);

                var result = query
                             .WithSubquery.WhereProperty(x => x.Id)
                             .In(usersWithRoleNotFromAuthServiceWithId) //TODO replace subquery by where clause
                             .RowCount();

                return(result);
            }
            catch (HibernateException ex)
            {
                throw new DatabaseException("Get users count operation failed", ex);
            }
        }
示例#8
0
        private Dictionary <Webpage, List <MobileFriendlyNavigationChildNode> > GetMobileFriendlyNavigationChildNodes(IList <Webpage> parents)
        {
            Webpage webpageAlias = null;
            MobileFriendlyNavigationChildNode nodeAlias = null;

            var countSubNodes = QueryOver.Of <Webpage>()
                                .Where(x => x.Parent.Id == webpageAlias.Id && x.RevealInNavigation && x.PublishOn != null)
                                .ToRowCountQuery();

            var parentIds = parents.Select(webpage => webpage.Id).ToList();
            var nodes     = _session.QueryOver(() => webpageAlias)
                            .Where(node => node.RevealInNavigation && node.Published)
                            .Where(node => node.Parent.Id.IsIn(parentIds))
                            .OrderBy(x => x.DisplayOrder).Asc
                            .SelectList(x => x.Select(y => y.Id).WithAlias(() => nodeAlias.Id)
                                        .Select(y => y.Parent.Id).WithAlias(() => nodeAlias.ParentId)
                                        .Select(y => y.Name).WithAlias(() => nodeAlias.Name)
                                        .Select(y => y.UrlSegment).WithAlias(() => nodeAlias.UrlSegment)
                                        .Select(y => y.PublishOn).WithAlias(() => nodeAlias.PublishOn)
                                        .Select(y => y.DocumentType).WithAlias(() => nodeAlias.DocumentType)
                                        .Select(y => y.DisplayOrder).WithAlias(() => nodeAlias.DisplayOrder)
                                        .SelectSubQuery(countSubNodes).WithAlias(() => nodeAlias.ChildCount))
                            .TransformUsing(Transformers.AliasToBean <MobileFriendlyNavigationChildNode>())
                            .List <MobileFriendlyNavigationChildNode>().ToList()
                            .GroupBy(node => node.ParentId)
                            .ToDictionary(grouping => grouping.Key, g => g.ToList());

            return(parents.ToDictionary(webpage => webpage,
                                        webpage =>
                                        nodes.ContainsKey(webpage.Id) ? nodes[webpage.Id] : new List <MobileFriendlyNavigationChildNode>()));
        }
示例#9
0
        /// <summary>
        /// 조건 람다 식이 일치하는 모든 Entity 정보를 Load한다.
        /// </summary>
        /// <typeparam name="T">검색하고자하는 Entity의 수형</typeparam>
        /// <param name="firstResult">결과 셋의 첫번째 레코드의 인덱스(0부터 시작)</param>
        /// <param name="maxResults">결과 셋의 최대 크기</param>
        /// <param name="expressions">조건 절 람다 식</param>
        /// <returns></returns>
        public static IList <T> FindAll <T>(int?firstResult, int?maxResults, params Expression <Func <T, bool> >[] expressions)
            where T : class, IDataObject
        {
            if (IsDebugEnabled)
            {
                log.Debug("FindAll entities. entity=[{0}], firstResult=[{1}], maxResults=[{2}], expression=[{3}]",
                          typeof(T).Name, firstResult, maxResults, expressions.CollectionToString());
            }

            var query = QueryOver.Of <T>();

            if (expressions != null)
            {
                foreach (var expr in expressions)
                {
                    query.AddWhere(expr);
                }
            }

            return
                (query
                 .AddSkip(firstResult)
                 .AddTake(maxResults)
                 .GetExecutableQueryOver(UnitOfWork.CurrentSession)
                 .List());
        }
示例#10
0
        public ProductPagedList Search(string queryTerm = null, int page = 1)
        {
            IPagedList <Product> pagedList;
            var pageSize = _ecommerceSettings.DefaultPageSize > 0 ? _ecommerceSettings.DefaultPageSize : 10;

            if (!string.IsNullOrWhiteSpace(queryTerm))
            {
                Product        productAlias        = null;
                ProductVariant productVariantAlias = null;
                pagedList = _session.QueryOver(() => productAlias)
                            .JoinAlias(() => productAlias.Variants, () => productVariantAlias, JoinType.LeftOuterJoin)
                            .Where(
                    () =>
                    productVariantAlias.SKU == queryTerm ||
                    productAlias.Name.IsInsensitiveLike(queryTerm, MatchMode.Anywhere) ||
                    productVariantAlias.Name.IsInsensitiveLike(queryTerm, MatchMode.Anywhere))
                            .Paged(page, pageSize);
            }
            else
            {
                pagedList = _session.Paged(QueryOver.Of <Product>(), page, pageSize);
            }

            var productContainer   = _uniquePageService.GetUniquePage <ProductContainer>();
            var productContainerId = productContainer == null ? (int?)null : productContainer.Id;

            return(new ProductPagedList(pagedList, productContainerId));
        }
示例#11
0
        public static IList <DriverPosition> GetLastPointForRouteLists(IUnitOfWork uow, int[] routeListsIds, DateTime?beforeTime = null)
        {
            Track          trackAlias = null;
            TrackPoint     subPoint   = null;
            DriverPosition result     = null;

            var lastTimeTrackQuery = QueryOver.Of <TrackPoint>(() => subPoint)
                                     .Where(() => subPoint.Track.Id == trackAlias.Id);

            if (beforeTime.HasValue)
            {
                lastTimeTrackQuery.Where(p => p.TimeStamp <= beforeTime);
            }

            lastTimeTrackQuery.Select(Projections.Max(() => subPoint.TimeStamp));

            return(uow.Session.QueryOver <TrackPoint>()
                   .JoinAlias(p => p.Track, () => trackAlias)
                   .Where(() => trackAlias.RouteList.Id.IsIn(routeListsIds))
                   .WithSubquery.WhereProperty(p => p.TimeStamp).Eq(lastTimeTrackQuery)
                   .SelectList(list => list
                               .Select(() => trackAlias.Driver.Id).WithAlias(() => result.DriverId)
                               .Select(() => trackAlias.RouteList.Id).WithAlias(() => result.RouteListId)
                               .Select(x => x.TimeStamp).WithAlias(() => result.Time)
                               .Select(x => x.Latitude).WithAlias(() => result.Latitude)
                               .Select(x => x.Longitude).WithAlias(() => result.Longitude)
                               ).TransformUsing(Transformers.AliasToBean <DriverPosition>())
                   .List <DriverPosition>());
        }
示例#12
0
        public static QueryOver <Equipment, Equipment> AvailableEquipmentQuery()
        {
            Vodovoz.Domain.Orders.Order orderAlias = null;
            Equipment equipmentAlias = null;
            WarehouseMovementOperation operationAddAlias   = null;
            OrderEquipment             orderEquipmentAlias = null;

            var equipmentInStockCriterion = Subqueries.IsNotNull(
                QueryOver.Of <WarehouseMovementOperation>(() => operationAddAlias)
                .OrderBy(() => operationAddAlias.OperationTime).Desc
                .Where(() => equipmentAlias.Id == operationAddAlias.Equipment.Id)
                .Select(op => op.IncomingWarehouse)
                .Take(1).DetachedCriteria
                );

            var subqueryAllReservedEquipment = QueryOver.Of <Vodovoz.Domain.Orders.Order>(() => orderAlias)
                                               .Where(() => orderAlias.OrderStatus == OrderStatus.Accepted ||
                                                      orderAlias.OrderStatus == OrderStatus.InTravelList ||
                                                      orderAlias.OrderStatus == OrderStatus.OnLoading) // чтобы не добавить в доп соглашение оборудование добавленное в уже созданный заказ.
                                               .JoinAlias(() => orderAlias.OrderEquipments, () => orderEquipmentAlias)
                                               .Where(() => orderEquipmentAlias.Direction == Direction.Deliver)
                                               .Select(Projections.Property(() => orderEquipmentAlias.Equipment.Id));

            return(QueryOver.Of <Equipment>(() => equipmentAlias)
                   .Where(equipmentInStockCriterion)
                   .Where(e => e.AssignedToClient == null)
                   .WithSubquery.WhereProperty(() => equipmentAlias.Id).NotIn(subqueryAllReservedEquipment));
        }
示例#13
0
        public override Oficina BuscarOficinaDoInscrito(int idEvento, int idInscricao)
        {
            Oficina aliasAfrac = null;

            var consultaParticipantes = QueryOver.Of <Oficina>()
                                        .Where(x => x.Id == aliasAfrac.Id)
                                        .JoinQueryOver(x => x.Participantes)
                                        .Where(y => y.Id == idInscricao)
                                        .SelectList(lista => lista
                                                    .Select(x => x.Id));

            var consultaCoordenadores = QueryOver.Of <AtividadeInscricaoOficinasCoordenacao>()
                                        .Where(x => x.OficinaEscolhida.Id == aliasAfrac.Id && x.Inscrito.Id == idInscricao)
                                        .SelectList(lista => lista
                                                    .Select(x => x.Inscrito.Id));

            return(mSessao.QueryOver <Oficina>(() => aliasAfrac)
                   .Where(Restrictions.Conjunction()
                          .Add <Oficina>(x => x.Evento.Id == idEvento)
                          .Add(Restrictions.Disjunction()
                               .Add(Subqueries.WhereExists(consultaCoordenadores))
                               .Add(Subqueries.WhereExists(consultaParticipantes)
                                    )
                               )
                          )
                   .SingleOrDefault());
        }
        public FilterResult GenerateFilterQuery(System.Linq.Expressions.Expression fromExpression)
        {
            var filterResult = Visit(fromExpression);

            // Before sending it back, check if we need to add the joins if it wasn't a binary
            var schemaFilter = filterResult as SchemaFilterResult;
            var fieldFilter  = filterResult as FieldFilterResult;

            if (filterResult.Subquery == null)
            {
                filterResult.Subquery = QueryOver.Of(() => agg);
            }

            // Add the joins (provided there's any point)
            if (schemaFilter != null || fieldFilter != null)
            {
                foreach (var queryJoin in filterResult.Joins)
                {
                    filterResult.Subquery = filterResult.Subquery.JoinAlias(queryJoin.Path, queryJoin.Alias, queryJoin.JoinType);
                }
            }

            if (schemaFilter != null && schemaFilter.NhCriterion != null)
            {
                filterResult.Subquery = filterResult.Subquery.Where(schemaFilter.NhCriterion);
            }
            else if (fieldFilter != null && fieldFilter.NhCriterion != null)
            {
                filterResult.Subquery = filterResult.Subquery.Where(fieldFilter.NhCriterion);
            }

            return(filterResult);
        }
示例#15
0
        public static int GetStockForNomenclature(IUnitOfWork uow, int nomenclatureId)
        {
            Nomenclature nomenclatureAlias = null;
            WarehouseMovementOperation operationAddAlias    = null;
            WarehouseMovementOperation operationRemoveAlias = null;

            var subqueryAdd = QueryOver.Of <WarehouseMovementOperation>(() => operationAddAlias)
                              .Where(() => operationAddAlias.Nomenclature.Id == nomenclatureAlias.Id)
                              .Select(Projections.Sum <WarehouseMovementOperation>(o => o.Amount));


            var subqueryRemove = QueryOver.Of <WarehouseMovementOperation>(() => operationRemoveAlias)
                                 .Where(() => operationRemoveAlias.Nomenclature.Id == nomenclatureAlias.Id)
                                 .Select(Projections.Sum <WarehouseMovementOperation>(o => o.Amount));

            var amountProjection = Projections.SqlFunction(new SQLFunctionTemplate(NHibernateUtil.Int32, "( ?1 - ?2 )"),
                                                           NHibernateUtil.Int32, new IProjection[] {
                Projections.SubQuery(subqueryAdd),
                Projections.SubQuery(subqueryRemove)
            }
                                                           );

            ItemInStock inStock     = null;
            var         queryResult = uow.Session.QueryOver <Nomenclature>(() => nomenclatureAlias)
                                      .Where(() => nomenclatureAlias.Id == nomenclatureId)
                                      .SelectList(list => list
                                                  .SelectGroup(() => nomenclatureAlias.Id)
                                                  .Select(amountProjection)
                                                  ).SingleOrDefault <object[]>();

            return((int)queryResult[1]);
        }
示例#16
0
        public IEnumerable <OperationNode> CurrentCashForGivenSubdivisions(IUnitOfWork uow, int[] subdivisionIds)
        {
            Subdivision   subdivisionAlias = null;
            Income        incomeAlias      = null;
            Expense       expenseAlias     = null;
            OperationNode resultAlias      = null;

            var expenseSub = QueryOver.Of(() => expenseAlias)
                             .Where(x => x.RelatedToSubdivision.Id == subdivisionAlias.Id)
                             .Select(Projections.Sum <Expense>(o => o.Money));

            var incomeSub = QueryOver.Of(() => incomeAlias)
                            .Where(x => x.RelatedToSubdivision.Id == subdivisionAlias.Id)
                            .Select(Projections.Sum <Income>(o => o.Money));

            var projection = Projections.SqlFunction(
                new SQLFunctionTemplate(NHibernateUtil.Decimal, "( IFNULL(?1, 0) - IFNULL(?2, 0) )"),
                NHibernateUtil.Decimal,
                Projections.SubQuery(incomeSub),
                Projections.SubQuery(expenseSub)
                );

            var results = uow.Session
                          .QueryOver(() => subdivisionAlias)
                          .Where(() => subdivisionAlias.Id.IsIn(subdivisionIds)).SelectList(list => list
                                                                                            .Select(() => subdivisionAlias.Name).WithAlias(() => resultAlias.Name)
                                                                                            .Select(projection).WithAlias(() => resultAlias.Balance)
                                                                                            )
                          .TransformUsing(Transformers.AliasToBean <OperationNode>())
                          .List <OperationNode>();

            return(results);
        }
示例#17
0
        public static Dictionary <int, decimal> EquipmentInStock(IUnitOfWork UoW, int warehouseId, int[] equipmentIds)
        {
            Equipment equipmentAlias = null;
            WarehouseMovementOperation operationAddAlias    = null;
            WarehouseMovementOperation operationRemoveAlias = null;

            var subqueryAdd = QueryOver.Of <WarehouseMovementOperation>(() => operationAddAlias)
                              .Where(() => operationAddAlias.Equipment.Id == equipmentAlias.Id)
                              .And(Restrictions.Eq(Projections.Property <WarehouseMovementOperation>(o => o.IncomingWarehouse.Id), warehouseId))
                              .Select(Projections.Sum <WarehouseMovementOperation>(o => o.Amount));

            var subqueryRemove = QueryOver.Of <WarehouseMovementOperation>(() => operationRemoveAlias)
                                 .Where(() => operationRemoveAlias.Equipment.Id == equipmentAlias.Id)
                                 .And(Restrictions.Eq(Projections.Property <WarehouseMovementOperation>(o => o.WriteoffWarehouse.Id), warehouseId))
                                 .Select(Projections.Sum <WarehouseMovementOperation>(o => o.Amount));

            ItemInStock inStock   = null;
            var         stocklist = UoW.Session.QueryOver <Equipment>(() => equipmentAlias)
                                    .Where(() => equipmentAlias.Id.IsIn(equipmentIds))
                                    .SelectList(list => list
                                                .SelectGroup(() => equipmentAlias.Id).WithAlias(() => inStock.Id)
                                                .SelectSubQuery(subqueryAdd).WithAlias(() => inStock.Added)
                                                .SelectSubQuery(subqueryRemove).WithAlias(() => inStock.Removed)
                                                ).TransformUsing(Transformers.AliasToBean <ItemInStock>()).List <ItemInStock>();
            var result = new Dictionary <int, decimal>();

            foreach (var nomenclatureInStock in stocklist)
            {
                result.Add(nomenclatureInStock.Id, nomenclatureInStock.Amount);
            }

            return(result);
        }
示例#18
0
        protected ScriptsRun get_script_run(string script_name)
        {
            QueryOver <ScriptsRun> criteria = QueryOver.Of <ScriptsRun>()
                                              .Where(x => x.script_name == script_name)
                                              .OrderBy(x => x.id).Desc
                                              .Take(1);

            ScriptsRun         script = null;
            IList <ScriptsRun> found_items;

            try
            {
                found_items = retry_policy.ExecuteAction(() => repository.get_with_criteria(criteria));
            }
            catch (Exception ex)
            {
                Log.bound_to(this).log_an_error_event_containing(
                    "{0} with provider {1} does not provide a facility for recording scripts run this time.{2}{3}",
                    GetType(), provider, Environment.NewLine, ex.to_string());
                throw;
            }

            if (found_items != null && found_items.Count > 0)
            {
                script = found_items[0];
            }

            return(script);
        }
示例#19
0
        public IList <UserEntity> FindUsersByRole(UserType type, int roleId, int start, int count, string searchByName)
        {
            UserEntity userAlias = null;

            try
            {
                var session = GetSession();

                var usersWithRoleNotFromAuthServiceWithId = QueryOver.Of <UserEntity>()
                                                            .JoinQueryOver <RoleEntity>(m => m.Roles)
                                                            .Where(a => !a.AuthenticationServiceOnly).And(a => a.Id == roleId)
                                                            .Select(Projections.Distinct(Projections.Property <UserEntity>(m => m.Id)));

                var query = session.QueryOver(() => userAlias);

                query = AddRestrictionOnUserTypeToQuery(query, type);
                query = AddOrderingByLastNameAndFirstNameToQuery(query, userAlias);
                query = AddSearchByNameToQuery(query, searchByName);

                var result = query
                             .WithSubquery.WhereProperty(x => x.Id)
                             .In(usersWithRoleNotFromAuthServiceWithId) //TODO replace subquery by where clause
                             .Skip(start)                               // TODO replace with GetValuesList(start, count, ...)
                             .Take(count)
                             .Future <UserEntity>();

                FetchCollections(session);

                return(result.ToList());
            }
            catch (HibernateException ex)
            {
                throw new DatabaseException("Get users list operation failed", ex);
            }
        }
        public decimal GetUndelivered19LBottlesQuantity(IUnitOfWork uow, DateTime?start = null, DateTime?end = null)
        {
            Order        orderAlias        = null;
            Nomenclature nomenclatureAlias = null;

            var subquery = QueryOver.Of <UndeliveredOrder>()
                           .Left.JoinAlias(u => u.OldOrder, () => orderAlias);

            if (start != null && end != null)
            {
                subquery.Where(() => orderAlias.DeliveryDate >= start)
                .Where(() => orderAlias.DeliveryDate <= end);
            }

            subquery.Select(u => u.OldOrder.Id);

            var bottles19L = uow.Session.QueryOver <OrderItem>()
                             .WithSubquery.WhereProperty(i => i.Order.Id).In(subquery)
                             .Left.JoinQueryOver(i => i.Nomenclature, () => nomenclatureAlias)
                             .Where(n => n.Category == NomenclatureCategory.water && n.TareVolume == TareVolume.Vol19L)
                             .SelectList(list => list.SelectSum(i => i.Count))
                             .List <decimal?>()
                             .FirstOrDefault();

            return(bottles19L ?? 0);
        }
示例#21
0
        public IPage <UserGroupMembership> FindOtherMembershipsInUsersGroups(IPageable pageRequest, User user, IList <UserGroupMembershipType> membershipTypes = null)
        {
            Require.NotNull(pageRequest, "pageRequest");
            Require.NotNull(user, "user");

            HibernateDelegate <IPage <UserGroupMembership> > finder = delegate(ISession session) {
                IQueryOver <UserGroupMembership, UserGroupMembership> queryOver = session.QueryOver <UserGroupMembership>();
                /*Die Mitgliedschaften des Nutzers nicht!*/
                queryOver.Where(membership => membership.User != user);

                /*Nur die der Gruppen des Nutzers*/
                var userGroupQueryOver = QueryOver.Of <UserGroupMembership>().Where(mem => mem.User == user).And(mem => mem.MembershipType == UserGroupMembershipType.Administrator || mem.MembershipType == UserGroupMembershipType.Member).Select(mem => mem.UserGroup.Id);
                queryOver.WithSubquery.WhereProperty(membership => membership.UserGroup).In(userGroupQueryOver);

                if (membershipTypes != null && membershipTypes.Any())
                {
                    /*Einschränkung der Mitgliedschaften*/
                    queryOver.WhereRestrictionOn(memberShip => memberShip.MembershipType).IsIn(membershipTypes.ToArray());
                }

                return(FindPage(queryOver, pageRequest));
            };

            return(HibernateTemplate.Execute(finder));
        }
示例#22
0
        public IList <GoodsInRouteListResult> GetGoodsInRLWithoutEquipments(IUnitOfWork uow, RouteList routeList)
        {
            GoodsInRouteListResult resultAlias = null;

            Vodovoz.Domain.Orders.Order orderAlias  = null;
            OrderItem    orderItemsAlias            = null;
            Nomenclature OrderItemNomenclatureAlias = null;

            var ordersQuery = QueryOver.Of(() => orderAlias);

            var routeListItemsSubQuery = QueryOver.Of <RouteListItem>()
                                         .Where(r => r.RouteList.Id == routeList.Id)
                                         .Where(r => !r.WasTransfered || (r.WasTransfered && r.NeedToReload))
                                         .Select(r => r.Order.Id);

            ordersQuery.WithSubquery.WhereProperty(o => o.Id).In(routeListItemsSubQuery).Select(o => o.Id);

            var orderitemsQuery = uow.Session.QueryOver <OrderItem>(() => orderItemsAlias)
                                  .WithSubquery.WhereProperty(i => i.Order.Id).In(ordersQuery)
                                  .JoinAlias(() => orderItemsAlias.Nomenclature, () => OrderItemNomenclatureAlias)
                                  .Where(() => OrderItemNomenclatureAlias.Category.IsIn(Nomenclature.GetCategoriesForShipment()));

            return(orderitemsQuery.SelectList(list => list
                                              .SelectGroup(() => OrderItemNomenclatureAlias.Id).WithAlias(() => resultAlias.NomenclatureId)
                                              .SelectSum(() => orderItemsAlias.Count).WithAlias(() => resultAlias.Amount))
                   .TransformUsing(Transformers.AliasToBean <GoodsInRouteListResult>())
                   .List <GoodsInRouteListResult>());
        }
        public void StatelessSession()
        {
            int personId;

            using (var ss = sessions.OpenStatelessSession())
                using (var t = ss.BeginTransaction())
                {
                    var person = new Person {
                        Name = "test1"
                    };
                    ss.Insert(person);
                    personId = person.Id;
                    t.Commit();
                }

            using (var ss = sessions.OpenStatelessSession())
                using (ss.BeginTransaction())
                {
                    var statelessPerson1 = ss.QueryOver <Person>()
                                           .List()[0];

                    Assert.That(statelessPerson1.Id, Is.EqualTo(personId));

                    var statelessPerson2 = QueryOver.Of <Person>()
                                           .GetExecutableQueryOver(ss)
                                           .List()[0];

                    Assert.That(statelessPerson2.Id, Is.EqualTo(personId));
                }
        }
示例#24
0
        public IList <GoodsInRouteListResult> GetEquipmentsInRL(IUnitOfWork uow, RouteList routeList)
        {
            GoodsInRouteListResult resultAlias = null;

            Vodovoz.Domain.Orders.Order orderAlias         = null;
            OrderEquipment orderEquipmentAlias             = null;
            Nomenclature   OrderEquipmentNomenclatureAlias = null;

            //Выбирается список Id заказов находящихся в МЛ
            var ordersQuery            = QueryOver.Of <Vodovoz.Domain.Orders.Order>(() => orderAlias);
            var routeListItemsSubQuery = QueryOver.Of <RouteListItem>()
                                         .Where(r => r.RouteList.Id == routeList.Id)
                                         .Where(r => !r.WasTransfered || (r.WasTransfered && r.NeedToReload))
                                         .Select(r => r.Order.Id);

            ordersQuery.WithSubquery.WhereProperty(o => o.Id).In(routeListItemsSubQuery).Select(o => o.Id);

            var orderEquipmentsQuery = uow.Session.QueryOver <OrderEquipment>(() => orderEquipmentAlias)
                                       .WithSubquery.WhereProperty(i => i.Order.Id).In(ordersQuery)
                                       .Where(() => orderEquipmentAlias.Direction == Direction.Deliver)
                                       .JoinAlias(() => orderEquipmentAlias.Nomenclature, () => OrderEquipmentNomenclatureAlias);

            return(orderEquipmentsQuery
                   .SelectList(list => list
                               .SelectGroup(() => OrderEquipmentNomenclatureAlias.Id).WithAlias(() => resultAlias.NomenclatureId)
                               .Select(Projections.Sum(
                                           Projections.Cast(NHibernateUtil.Decimal, Projections.Property(() => orderEquipmentAlias.Count)))).WithAlias(() => resultAlias.Amount)
                               )
                   .TransformUsing(Transformers.AliasToBean <GoodsInRouteListResult>())
                   .List <GoodsInRouteListResult>());
        }
示例#25
0
        public bool IsUniqueDocumentAtDay(IUnitOfWork UoW, RouteList routeList, Warehouse warehouse, int documentId)
        {
            if (documentId != 0)
            {
                return(true);
            }

            var start = DateTime.Now.Date;
            var end   = DateTime.Now.Date.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(59).AddTicks(59);

            CarUnloadDocument carUnloadDocument = null;
            var getSimilarCarUnloadDoc          = QueryOver.Of <CarUnloadDocument>(() => carUnloadDocument)
                                                  .Where(() => carUnloadDocument.RouteList.Id == routeList.Id)
                                                  .And(() => carUnloadDocument.Warehouse.Id == warehouse.Id)
                                                  .And(() => start <= carUnloadDocument.TimeStamp)
                                                  .And(() => carUnloadDocument.TimeStamp <= end);
            IList <CarUnloadDocument> documents = getSimilarCarUnloadDoc.GetExecutableQueryOver(UoW.Session)
                                                  .List();

            if (documents.Count > 0)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
示例#26
0
        public override QueryOver <NodeVersion> VisitBinary(BinaryExpression node)
        {
            var left  = Visit(node.Left);
            var right = Visit(node.Right);

            switch (node.NodeType)
            {
            case ExpressionType.And:
            case ExpressionType.AndAlso:
                return(QueryOver.Of <NodeVersion>()
                       .Where(Restrictions.Conjunction()
                              .Add(Subqueries.PropertyIn(Projections.Property <NodeVersion>(x => x.Id).PropertyName, left.DetachedCriteria))
                              .Add(Subqueries.PropertyIn(Projections.Property <NodeVersion>(x => x.Id).PropertyName, right.DetachedCriteria)))
                       .Select(x => x.Id));

            case ExpressionType.Or:
            case ExpressionType.OrElse:
            {
                return(QueryOver.Of <NodeVersion>()
                       .Where(Restrictions.Disjunction()
                              .Add(Subqueries.PropertyIn(Projections.Property <NodeVersion>(x => x.Id).PropertyName, left.DetachedCriteria))
                              .Add(Subqueries.PropertyIn(Projections.Property <NodeVersion>(x => x.Id).PropertyName, right.DetachedCriteria)))
                       .Select(x => x.Id));
            }
            }

            throw new InvalidOperationException("This provider only supports binary expressions with And, AndAlso, Or, OrElse expression types. ExpressionType was {0}".InvariantFormat(node.NodeType.ToString()));
        }
示例#27
0
        public string get_version(string repository_path)
        {
            string version = "0";

            QueryOver <Version> crit = QueryOver.Of <Version>()
                                       .Where(x => x.repository_path == (repository_path ?? string.Empty))
                                       .OrderBy(x => x.entry_date).Desc
                                       .Take(1);

            try
            {
                IList <Version> items = repository.get_with_criteria(crit);
                if (items != null && items.Count > 0)
                {
                    version = items[0].version;
                }
            }
            catch (Exception)
            {
                Log.bound_to(this).log_a_warning_event_containing("{0} with provider {1} does not provide a facility for retrieving versions at this time.",
                                                                  GetType(), provider);
            }

            return(version);
        }
        public IList <WebpageStats> GetSummary()
        {
            WebpageStats countAlias   = null;
            Webpage      webpageAlias = null;

            return(_session.QueryOver(() => webpageAlias)
                   .Where(x => x.Site.Id == _site.Id)
                   .SelectList(
                       builder =>
                       builder.SelectGroup(() => webpageAlias.DocumentType)
                       .WithAlias(() => countAlias.DocumentType)
                       .SelectCount(() => webpageAlias.Id)
                       .WithAlias(() => countAlias.NumberOfPages)
                       .SelectSubQuery(
                           QueryOver.Of <Webpage>()
                           .Where(
                               webpage =>
                               webpage.Site.Id == _site.Id &&
                               webpage.DocumentType == webpageAlias.DocumentType &&
                               !webpage.Published && !webpage.IsDeleted)
                           .ToRowCountQuery())
                       .WithAlias(() => countAlias.NumberOfUnPublishedPages))
                   .TransformUsing(Transformers.AliasToBean <WebpageStats>())
                   .List <WebpageStats>());
        }
示例#29
0
        public bool has_run_script_already(string script_name)
        {
            ScriptsRun script = get_from_script_cache(script_name);

            if (script != null)
            {
                return(true);
            }

            bool script_has_run = false;

            QueryOver <ScriptsRun> crit = QueryOver.Of <ScriptsRun>()
                                          .Where(x => x.script_name == script_name)
                                          .OrderBy(x => x.id).Desc
                                          .Take(1);

            try
            {
                IList <ScriptsRun> items = repository.get_with_criteria(crit);
                if (items != null && items.Count > 0)
                {
                    script_has_run = true;
                }
            }
            catch (Exception ex)
            {
                Log.bound_to(this).log_an_error_event_containing(
                    "{0} with provider {1} does not provide a facility for determining if a script has run at this time.{2}{3}",
                    GetType(), provider, Environment.NewLine, ex.Message);
                throw;
            }

            return(script_has_run);
        }
示例#30
0
        public HomeViewModel Get(HomeRequest request)
        {
            OrderSummary orderSummaryAlias = null;
            var          orderCount        = QueryOver.Of <OrderDetail>()
                                             .SelectList(list => list
                                                         .SelectGroup(c => c.Track).WithAlias(() => orderSummaryAlias.Track)
                                                         .SelectCount(c => c.Track).WithAlias(() => orderSummaryAlias.OrderCount))
                                             .TransformUsing(Transformers.AliasToBean <OrderSummary>())
                                             .OrderBy(Projections.Count <OrderDetail>(c => c.Track)).Desc
                                             .Take(request.Count);



            var topSellingAlbums = _session.QueryOver <Track>()
                                   .Fetch(x => x.Album).Eager
                                   .Fetch(x => x.Album.Artist).Eager
                                   .WithSubquery.WhereExists(orderCount)
                                   .Take(request.Count)
                                   .List();



            return(new HomeViewModel()
            {
                Tracks = topSellingAlbums
            });
        }