public IList <RecipeItem> SearchForRecipeItems(ItemSearchRequest query) { // No idea when recipes were added, the user probably wants owned items only. if (query.RecentOnly) { return(new List <RecipeItem>()); } using (ISession session = SessionCreator.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { ICriteria criterias = session.CreateCriteria <RecipeItem>(); if (!string.IsNullOrEmpty(query.Wildcard)) { criterias.Add(Subqueries.PropertyIn("BaseRecord", DetachedCriteria.For <DatabaseItem>() .Add(Restrictions.InsensitiveLike("Name", string.Format("%{0}%", query.Wildcard.Replace(' ', '%')))) .SetProjection(Projections.Property("Record")))); } AddItemSearchCriterias(criterias, query); criterias.Add(Restrictions.Eq("IsHardcore", query.IsHardcore)); IList <RecipeItem> items = criterias.List <RecipeItem>(); return(items); } } }
public void TestQuery() { if (!Dialect.SupportsSubSelectsWithPagingAsInPredicateRhs) { Assert.Ignore("Current dialect does not support paging within IN sub-queries"); } using (ISession session = OpenSession()) { DetachedCriteria page = DetachedCriteria.For <T1>() .SetFirstResult(3) .SetMaxResults(7) .AddOrder(NHibernate.Criterion.Order.Asc(Projections.Id())) .SetProjection(Projections.Id()); ICriteria crit = session.CreateCriteria <T1>() .Add(Subqueries.PropertyIn("id", page)) .SetResultTransformer(new DistinctRootEntityResultTransformer()) .SetFetchMode("Children", NHibernate.FetchMode.Join); session.EnableFilter("nameFilter").SetParameter("name", "Another child"); Assert.That(() => crit.List <T1>(), Throws.Nothing); } }
public IList <Flow> GetAllFlow(string userCode) { DetachedCriteria criteria = DetachedCriteria.For <Flow>(); criteria.CreateAlias("PartyTo", "pt"); criteria.CreateAlias("PartyFrom", "pf"); DetachedCriteria[] pfCrieteria = SecurityHelper.GetPartyPermissionCriteria(userCode, BusinessConstants.CODE_MASTER_PARTY_TYPE_VALUE_REGION, BusinessConstants.CODE_MASTER_PARTY_TYPE_VALUE_SUPPLIER); DetachedCriteria[] ptCrieteria = SecurityHelper.GetPartyPermissionCriteria(userCode, BusinessConstants.CODE_MASTER_PARTY_TYPE_VALUE_REGION, BusinessConstants.CODE_MASTER_PARTY_TYPE_VALUE_CUSTOMER); criteria.Add( Expression.Or( Subqueries.PropertyIn("pf.Code", pfCrieteria[0]), Subqueries.PropertyIn("pf.Code", pfCrieteria[1]) )); criteria.Add( Expression.Or( Subqueries.PropertyIn("pt.Code", ptCrieteria[0]), Subqueries.PropertyIn("pt.Code", ptCrieteria[1]) )); return(criteriaMgr.FindAll <Flow>(criteria)); }
public void Criteria_ComplexTest() { //Генерируем актуальный критерий var subQuery = repository.Object.SubQuery <Article>() .Like(x => x.Number, "123") .Select(x => x.Id); var crit = repository.Object.Query <ReceiptWaybillRow>(); crit.Restriction <ReceiptWaybill>(x => x.ReceiptWaybill).PropertyIn(x => x.ReceiptStorage.Id, subQuery); var actual = (crit as Criteria <ReceiptWaybillRow>).GetCriteria(); //Генерируем ожидаемый критерий var dc = DetachedCriteria.For <Article>(); dc.Add(Expression.Like("Number", "123", MatchMode.Anywhere)).SetProjection(Property.ForName("Id")); var expected = session.CreateCriteria <ReceiptWaybillRow>(); expected.Add(Expression.IsNull("DeletionDate")); expected.CreateCriteria("ReceiptWaybill").Add(Subqueries.PropertyIn("ReceiptStorage.Id", dc)); var sq = repository.Object.SubQuery <Article>(); crit.Or( y => y.PropertyIn(x => x.ReceiptWaybill, sq), y => y.PropertyIn(x => x.ReceiptWaybill, sq)); Assert.AreEqual(expected.ToString(), actual.ToString()); }
public ICriteria GetSearchCriteria(String searchString, ICorePrincipal user, int operationCode) { ICriteria criteria = Session.CreateCriteria <SectionLocale>().CreateAlias("Section", "section"); DetachedCriteria filter = DetachedCriteria.For <SectionLocale>("filteredLocale").CreateAlias("Section", "filteredSection") .SetProjection(Projections.Id()).SetMaxResults(1).AddOrder(Order.Desc("filteredLocale.Priority")).Add( Restrictions.EqProperty("filteredSection.Id", "section.Id")); criteria.Add(Subqueries.PropertyIn("Id", filter)); //apply permissions criteria var sectionsCriteria = DetachedCriteria.For <Section>("sections"); var permissionCommonService = ServiceLocator.Current.GetInstance <IPermissionCommonService>(); var permissionCriteria = permissionCommonService.GetPermissionsCriteria(user, operationCode, typeof(Section), "sections.Id", "sections.UserId"); if (permissionCriteria != null) { sectionsCriteria.Add(permissionCriteria).SetProjection(Projections.Id()); criteria.Add(Subqueries.PropertyIn("section.Id", sectionsCriteria)); } if (!String.IsNullOrEmpty(searchString)) { criteria.Add(Restrictions.Like("Title", searchString, MatchMode.Anywhere)); } return(criteria.SetCacheable(true)); }
private ICriterion GetCollectionContainsCriteria(CollectionAccessExpression arg, Expression containsExpression) { EntityExpression rootEntity = EntityExpressionVisitor.FirstEntity(arg); var rootEntityType = rootEntity.Type; if (rootEntity.MetaData.HasProxy) { rootEntityType = rootEntity.MetaData.GetMappedClass(EntityMode.Poco); } DetachedCriteria query = DetachedCriteria.For(rootEntityType) .SetProjection(Projections.Id()); var visitor = new MemberNameVisitor(query.Adapt(session), true); visitor.Visit(arg); //TODO: this won't work for collections of values var containedEntity = QueryUtil.GetExpressionValue(containsExpression); var collectionIdPropertyName = visitor.MemberName + "." + arg.ElementExpression.MetaData.IdentifierPropertyName; var idValue = arg.ElementExpression.MetaData.GetIdentifier(containedEntity, EntityMode.Poco); query.Add(Restrictions.Eq(collectionIdPropertyName, idValue)); string identifierName = rootEntity.MetaData.IdentifierPropertyName; return(Subqueries.PropertyIn(identifierName, query)); }
private static ICriterion CreateDetailExpression(Parameter p) { if (p.Comparison == Comparison.NotNull) { return(Subqueries.PropertyIn("ID", DetachedCriteria.For <ContentDetail>() .SetProjection(Projections.Property("EnclosingItem.ID")) .Add(Expression.Eq("Name", p.Name)))); } if (p.Comparison == Comparison.Null) { return(Subqueries.PropertyNotIn("ID", DetachedCriteria.For <ContentDetail>() .SetProjection(Projections.Property("EnclosingItem.ID")) .Add(Expression.Eq("Name", p.Name)))); } string propertyName = p.Comparison.HasFlag(Comparison.In) ? ContentDetail.GetAssociatedEnumerablePropertyName(p.Value as IEnumerable) : ContentDetail.GetAssociatedPropertyName(p.Value); var subselect = DetachedCriteria.For <ContentDetail>() .SetProjection(Projections.Property("EnclosingItem.ID")) .Add(CreateExpression(propertyName, ContentDetail.ExtractQueryValue(p.Value), p.Comparison, true)); if (p.Name != null) { subselect = subselect.Add(Expression.Eq("Name", p.Name)); } return(Subqueries.PropertyIn("ID", subselect)); }
/// <summary> /// Versuch über ein Detached Criteria die Where-Klauseln zu verarbeiten, damit es mit dem Order nicht zu /// komplikationen kommt. /// </summary> protected virtual IPage <T> Find(IPageable pageable, Action <DetachedCriteria> criteriaBuilder, Action <ICriteria> ordersBuilder = null) { Require.NotNull(pageable, "pageable"); Require.NotNull(criteriaBuilder, "criteriaBuilder"); HibernateDelegate <IPage <T> > finder = delegate(ISession session) { DetachedCriteria whereCriteria = DetachedCriteria.For(typeof(T)); criteriaBuilder(whereCriteria); whereCriteria.SetProjection(Projections.Property("Id")); ICriteria elementsCriteria = session.CreateCriteria(typeof(T)); elementsCriteria.Add(Subqueries.PropertyIn("Id", whereCriteria)); if (ordersBuilder != null) { ordersBuilder(elementsCriteria); } ApplyPaging(pageable, elementsCriteria); ICriteria countCriteria = session.CreateCriteria(typeof(T)); countCriteria.Add(Subqueries.PropertyIn("Id", whereCriteria)); countCriteria.SetProjection(Projections.RowCountInt64()); IFutureValue <long> futureTotalCount = countCriteria.FutureValue <long>(); IEnumerable <T> futureElements = elementsCriteria.Future <T>(); Page <T> page = new Page <T>(futureElements.ToList(), pageable, futureTotalCount.Value); return(page); }; return(HibernateTemplate.Execute(finder)); }
private void SetCriteria() { DetachedCriteria criteria = DetachedCriteria.For(typeof(InProcessLocationDetail)); criteria.CreateAlias("OrderLocationTransaction", "olt"); criteria.CreateAlias("InProcessLocation", "ip"); criteria.Add(Expression.Eq("ip.Status", BusinessConstants.CODE_MASTER_STATUS_VALUE_CREATE)); criteria.Add(Expression.Eq("ip.Type", BusinessConstants.CODE_MASTER_INPROCESS_LOCATION_TYPE_VALUE_NORMAL)); if (this.IOType == BusinessConstants.IO_TYPE_IN) { DetachedCriteria subCriteria = DetachedCriteria.For(typeof(OrderLocationTransaction)); subCriteria.CreateAlias("OrderDetail", "od"); subCriteria.CreateAlias("od.OrderHead", "oh"); OrderHelper.SetOpenOrderStatusCriteria(subCriteria, "oh.Status"); subCriteria.Add(Expression.Eq("IOType", BusinessConstants.IO_TYPE_IN)); subCriteria.Add(Expression.Eq("Item.Code", this.Item)); subCriteria.Add(Expression.Eq("Location.Code", this.Location)); subCriteria.SetProjection(Projections.ProjectionList().Add(Projections.GroupProperty("OrderDetail.Id"))); criteria.Add(Subqueries.PropertyIn("olt.OrderDetail.Id", subCriteria)); } else { criteria.Add(Expression.Eq("olt.Item.Code", this.Item)); criteria.Add(Expression.Eq("olt.Location.Code", this.Location)); } DetachedCriteria selectCountCriteria = CloneHelper.DeepClone <DetachedCriteria>(criteria); selectCountCriteria.SetProjection(Projections.Count("Id")); this.SetSearchCriteria(criteria, selectCountCriteria); }
public static DetachedCriteria[] GetPermissionCriteriaByCategory(User user, string category) { DetachedCriteria[] criteria = new DetachedCriteria[2]; DetachedCriteria upSubCriteria = DetachedCriteria.For <UserPermission>(); upSubCriteria.CreateAlias("User", "u"); upSubCriteria.CreateAlias("Permission", "pm"); upSubCriteria.CreateAlias("pm.Category", "pmc"); upSubCriteria.Add(Expression.Eq("pmc.Type", category)); upSubCriteria.Add(Expression.Eq("u.Code", user.Code)); upSubCriteria.SetProjection(Projections.ProjectionList().Add(Projections.GroupProperty("pm.Code"))); DetachedCriteria rpSubCriteria = DetachedCriteria.For <RolePermission>(); rpSubCriteria.CreateAlias("Role", "r"); rpSubCriteria.CreateAlias("Permission", "pm"); rpSubCriteria.CreateAlias("pm.Category", "pmc"); rpSubCriteria.Add(Expression.Eq("pmc.Type", category)); rpSubCriteria.SetProjection(Projections.ProjectionList().Add(Projections.GroupProperty("pm.Code"))); DetachedCriteria urSubCriteria = DetachedCriteria.For <UserRole>(); urSubCriteria.CreateAlias("User", "u"); urSubCriteria.CreateAlias("Role", "r"); urSubCriteria.Add(Expression.Eq("u.Code", user.Code)); urSubCriteria.SetProjection(Projections.ProjectionList().Add(Projections.GroupProperty("r.Code"))); rpSubCriteria.Add(Subqueries.PropertyIn("r.Code", urSubCriteria)); criteria[0] = upSubCriteria; criteria[1] = rpSubCriteria; return(criteria); }
public IList <AugmentationItem> Search(ItemSearchRequest query) { // User only wants recent items, so definitely not buyable. if (query.RecentOnly) { return(new List <AugmentationItem>()); } using (ISession session = SessionCreator.OpenSession()) { using (session.BeginTransaction()) { ICriteria criterias = session.CreateCriteria <AugmentationItem>(); if (!string.IsNullOrEmpty(query.Wildcard)) { criterias.Add(Subqueries.PropertyIn("BaseRecord", DetachedCriteria.For <DatabaseItem>() .Add(Restrictions.InsensitiveLike("Name", string.Format("%{0}%", query.Wildcard.Replace(' ', '%')))) .SetProjection(Projections.Property("Record")))); } DatabaseItemDaoImpl.AddItemSearchCriterias(criterias, query); IList <AugmentationItem> items = criterias.List <AugmentationItem>(); return(items); } } }
public List <ProductCardModel> GetListOfProductsWhoWhereAlsoBought(Product product) { if (product == null) { return(new List <ProductCardModel>()); } var items = _session.CreateCriteria <Product>() .Add( Subqueries.PropertyIn("Id", DetachedCriteria.For <ProductVariant>() .SetProjection(Projections.Property("Product.Id")) .Add(Subqueries.PropertyIn("Id", DetachedCriteria.For <OrderLine>() .SetProjection(Projections.Property("ProductVariant.Id")) .Add(Subqueries.PropertyIn("Order.Id", DetachedCriteria.For <OrderLine>() .SetProjection(Projections.Property("Order.Id")) .CreateCriteria("ProductVariant", JoinType.LeftOuterJoin) .Add(Restrictions.Eq("Product.Id", product.Id)) )) )) )) .Add(Restrictions.Not(Restrictions.Eq("Id", product.Id))) .Add(Restrictions.IsNotNull("PublishOn")).SetCacheable(true) .SetMaxResults(4) .List <Product>().ToList(); return(items.GetCardModels()); }
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())); }
private void BuildWithSubquery() { var criteria = (CriteriaImpl)MainQuery.UnderlyingCriteria; var session = (SessionImpl)criteria.Session; var metaData = session.SessionFactory.GetClassMetadata(typeof(TRoot)); var idName = metaData.IdentifierPropertyName; //TODO: multiple props var pe = Expression.Parameter(typeof(TRoot)); var idExprBody = Expression.Property(pe, typeof(TRoot).GetProperty(idName)); var expr = Expression.Lambda(idExprBody, pe); var mainCloned = MainQuery.Clone(); var projectionList = new List <IProjection>(); projectionList.Add(ExpressionProcessor.FindMemberProjection(expr.Body).AsProjection()); mainCloned.UnderlyingCriteria.SetProjection(projectionList.ToArray()); var tree = new QueryRelationTree(); foreach (var pathExpr in Includes) { tree.AddNode(pathExpr); } foreach (var pair in tree.DeepFirstSearch()) { var query = session.QueryOver <TRoot>(); //Add a SubQuery query.And(Subqueries.PropertyIn(idName, ((QueryOver <TRoot, TRoot>)mainCloned).DetachedCriteria)); CopyCriteriaValues(criteria, query); FillSubQuery(pair.Value, query, criteria); query.Future(); } }
private static ICriterion GetPermissionQueryInternal(IUser user, string operation, string securityKeyProperty) { string[] operationNames = Strings.GetHierarchicalOperationNames(operation); DetachedCriteria criteria = DetachedCriteria.For <Permission>("permission") .CreateAlias("Operation", "op") .CreateAlias("EntitiesGroup", "entityGroup", JoinType.LeftOuterJoin) .CreateAlias("entityGroup.Entities", "entityKey", JoinType.LeftOuterJoin) .SetProjection(Projections.Property("Allow")) .Add(Restrictions.In("op.Name", operationNames)) .Add(Restrictions.Eq("User", user) || Subqueries.PropertyIn("UsersGroup.Id", SecurityCriterions.AllGroups(user).SetProjection(Projections.Id()))) .Add( Property.ForName(securityKeyProperty).EqProperty("permission.EntitySecurityKey") || Property.ForName(securityKeyProperty).EqProperty("entityKey.EntitySecurityKey") || ( Restrictions.IsNull("permission.EntitySecurityKey") && Restrictions.IsNull("permission.EntitiesGroup") ) ) .SetMaxResults(1) .AddOrder(Order.Desc("Level")) .AddOrder(Order.Asc("Allow")); return(Subqueries.Eq(true, criteria)); }
private ICriteria ListLevelOnePagesCriteria(string search, CatalogPage parent, CategoryPageStatus?status) { ICriteria crit = GetCriteria(); if (!string.IsNullOrEmpty(search)) { Disjunction d = new Disjunction(); d.Add(Expression.InsensitiveLike("Name", search, MatchMode.Anywhere)); d.Add(Expression.InsensitiveLike("Description", search, MatchMode.Anywhere)); d.Add(Expression.InsensitiveLike("NameEnglish", search, MatchMode.Anywhere)); d.Add(Expression.InsensitiveLike("DescripionEnglish", search, MatchMode.Anywhere)); crit.Add(d); } if (parent != null) { crit.Add(Expression.Eq("Parent", parent)); } if (status != null) { crit.Add(Expression.Eq("CategoryPageStatus", status)); } DetachedCriteria levelOneCriteria = DetachedCriteria.For <CatalogPage>().SetProjection(Projections.Property("ID")) .Add(Expression.IsNull("Parent")); ICriterion levelOneSubquery = Subqueries.PropertyIn("Parent", levelOneCriteria); crit.Add(levelOneSubquery); return(crit); }
public void Property() { ICriteria expected = CreateTestCriteria(typeof(Person)) .Add(Subqueries.PropertyEq("Name", DetachedCriteriaName)) .Add(Subqueries.PropertyGe("Age", DetachedCriteriaAge)) .Add(Subqueries.PropertyGt("Age", DetachedCriteriaAge)) .Add(Subqueries.PropertyIn("Name", DetachedCriteriaName)) .Add(Subqueries.PropertyLe("Age", DetachedCriteriaAge)) .Add(Subqueries.PropertyLt("Age", DetachedCriteriaAge)) .Add(Subqueries.PropertyNe("Name", DetachedCriteriaName)) .Add(Subqueries.PropertyNotIn("Name", DetachedCriteriaName)); var actual = CreateTestQueryOver <Person>() .WithSubquery.WhereProperty(p => p.Name).Eq(DetachedQueryOverName) .WithSubquery.WhereProperty(p => p.Age).Ge(DetachedQueryOverAge) .WithSubquery.WhereProperty(p => p.Age).Gt(DetachedQueryOverAge) .WithSubquery.WhereProperty(p => p.Name).In(DetachedQueryOverName) .WithSubquery.WhereProperty(p => p.Age).Le(DetachedQueryOverAge) .WithSubquery.WhereProperty(p => p.Age).Lt(DetachedQueryOverAge) .WithSubquery.WhereProperty(p => p.Name).Ne(DetachedQueryOverName) .WithSubquery.WhereProperty(p => p.Name).NotIn(DetachedQueryOverName); AssertCriteriaAreEqual(expected, actual); }
public IEnumerable <ReferenciaGeografica> GetListForEmpresaLinea(int empresaId, int lineaId, bool conDependencias) { var dc = DetachedCriteria.For <ReferenciaGeografica>("drg").SetProjection(Projections.Property("drg.Id")); if (empresaId != -1) { dc.Add(Restrictions.Eq("Empresa.Id", empresaId)); } if (lineaId != -1) { dc.Add(Restrictions.Or(Restrictions.IsNull("Linea.Id"), Restrictions.Eq("Linea.Id", lineaId))); } dc.Add(Restrictions.Eq("drg.Baja", false)); dc.Add(Restrictions.Or(Restrictions.IsNull("drg.Vigencia.Inicio"), Restrictions.Lt("drg.Vigencia.Inicio", DateTime.UtcNow))); dc.Add(Restrictions.Or(Restrictions.IsNull("drg.Vigencia.Fin"), Restrictions.Gt("drg.Vigencia.Fin", DateTime.UtcNow))); var crit = Session.CreateCriteria <ReferenciaGeografica>("rg") .Add(Subqueries.PropertyIn("Id", dc)); if (conDependencias) { crit.CreateAlias("TipoReferenciaGeografica", "tr", JoinType.LeftOuterJoin) .CreateAlias("TipoReferenciaGeografica._velocidades", "trv", JoinType.LeftOuterJoin) .CreateAlias("_historia", "h", JoinType.LeftOuterJoin) .CreateAlias("_velocidades", "v", JoinType.LeftOuterJoin) .CreateAlias("_zonas", "z", JoinType.LeftOuterJoin) .CreateAlias("_historia.Direccion", "dir", JoinType.LeftOuterJoin) .CreateAlias("_historia.Poligono", "poly", JoinType.LeftOuterJoin) .CreateAlias("_historia.Poligono._puntos", "points", JoinType.LeftOuterJoin); } var list = crit.List <ReferenciaGeografica>(); return(list); }
public IList <Permission> GetUserPermissions(string loginid, object resourceObject) { DetachedCriteria user = GetUserPermissions(loginid).SetProjection(Projections.Property("permission.Id")); ; DetachedCriteria ug = GetUserGroupPermisssions(loginid) .SetProjection(Projections.Distinct(Projections.Property("permission.Id"))); ; DetachedCriteria org = GetUserOrgPermissions(loginid) .SetProjection(Projections.Distinct(Projections.Property("permission.Id"))); ; Type permissionInsType = Permission.CreatePermission(resourceObject).GetType(); DetachedCriteria permission = DetachedCriteria.For(permissionInsType) .Add(Restrictions.Eq(ResourceProperty, resourceObject)) .Add(Restrictions.Disjunction() .Add(Subqueries.PropertyIn("Id", org)) .Add(Subqueries.PropertyIn("Id", user)) .Add(Subqueries.PropertyIn("Id", ug)) ); return(permission.SetCacheMode(CacheMode.Normal).SetCacheable(true) .GetExecutableCriteria(CurrentSession).List <Permission>()); }
protected override Task <IList <Customer> > GetCustomersByOrderNumberUsingSubqueriesAndByNameUsingWhereClauseAsync( ISession session, int orderNumber, string customerName, CancellationToken cancellationToken = default(CancellationToken)) { try { var detachedCriteria = DetachedCriteria .For <Customer>() .CreateAlias("Orders", "order", JoinType.LeftOuterJoin, Restrictions.Eq("Number", orderNumber)) .SetProjection(Projections.Id()); return (session .CreateCriteria <Customer>() .CreateAlias("Orders", "order1", JoinType.LeftOuterJoin) .Add(Subqueries.PropertyIn("Id", detachedCriteria)) .Add(Restrictions.Eq("Name", customerName)) .SetResultTransformer(new DistinctRootEntityResultTransformer()) .ListAsync <Customer>(cancellationToken)); } catch (System.Exception ex) { return(Task.FromException <IList <Customer> >(ex)); } }
private IEnumerable <ViewModels.TranslationsViewModel.TranslationDTO> BuildTranslations(int id, string language) { var me = TranslatorService.FindByEmail(HttpContext.User.Identity.Name); var keys = DbSession.QueryOver <TranslateKey>() .Where(x => x.Set.Id == id) .Future(); var neutralTranslations = DbSession.QueryOver <Translation>() .Where(x => x.Language == LanguageService.GetNeutralLanguage()) .And(x => x.NeedsReviewing == false) .OrderBy(x => x.Votes).Desc .Future(); var leadingTranslations = DbSession.QueryOver <Translation>() .Where(x => x.Language == LanguageService.GetLanguageByIsoCode(language)) .And(x => x.IsPublished) .And(x => x.NeedsReviewing == false) .OrderBy(x => x.Votes).Desc .Future(); var userTranslations = DbSession.QueryOver <Translation>() .Where(x => x.Language == LanguageService.GetLanguageByIsoCode(language)) .And(x => x.Translator == me) .And(x => x.NeedsReviewing == false) .OrderBy(x => x.Votes).Desc .Future(); var dc = DetachedCriteria.For <TranslationVote>() .Add(Restrictions.Eq("Translator", me)) .CreateAlias("Translation", "t") .Add(Restrictions.Eq("t.Language", LanguageService.GetLanguageByIsoCode(language))) .SetProjection(Projections.Property("t.Key.Id")); var votedOnKeys = DbSession.CreateCriteria <TranslateKey>() .Add(Restrictions.Eq("Set.Id", id)) .Add(Subqueries.PropertyIn("Id", dc)) .SetProjection(Projections.Id()) .Future <int>().ToList(); var translations = ( from key in keys let neutralTranslation = neutralTranslations.Where(x => x.Key == key).FirstOrDefault() let leadingTranslation = leadingTranslations.Where(x => x.Key == key).FirstOrDefault() let userTranslation = userTranslations.Where(x => x.Key == key).FirstOrDefault() ?? leadingTranslation select new ViewModels.TranslationsViewModel.TranslationDTO { KeyId = key.Id, Term = neutralTranslation == null ? string.Empty : neutralTranslation.Value, Value = userTranslation == null ? string.Empty : userTranslation.Value, LeadingValue = leadingTranslation == null ? string.Empty : leadingTranslation.Value, Votes = leadingTranslation == null ? 0 : userTranslation.Votes, Voted = votedOnKeys.Contains(key.Id), SetId = id } ).ToList(); return(translations); }
/// <summary> /// Gets all permissions for the specified group /// </summary> /// <param name="group">The group</param> /// <returns></returns> public Permission[] GetPermissionsFor(UsersGroup group) { DetachedCriteria criteria = DetachedCriteria.For <Permission>() .Add(Subqueries.PropertyIn("UsersGroup.Id", SecurityCriterions.AllGroups(group).SetProjection(Projections.Id()))); return(FindResults(criteria)); }
public IList <Party> GetFromParty(string orderType, string userCode, bool includeInactive) { DetachedCriteria criteria = DetachedCriteria.For <Party>(); if (orderType == BusinessConstants.CODE_MASTER_FLOW_TYPE_VALUE_PROCUREMENT || orderType == BusinessConstants.CODE_MASTER_FLOW_TYPE_VALUE_SUBCONCTRACTING) { DetachedCriteria[] pfCrieteria = SecurityHelper.GetSupplierPermissionCriteria(userCode); criteria.Add( Expression.Or( Subqueries.PropertyIn("Code", pfCrieteria[0]), Subqueries.PropertyIn("Code", pfCrieteria[1]) )); } else if (orderType == BusinessConstants.CODE_MASTER_FLOW_TYPE_VALUE_DISTRIBUTION) { DetachedCriteria[] pfCrieteria = SecurityHelper.GetRegionPermissionCriteria(userCode); criteria.Add( Expression.Or( Subqueries.PropertyIn("Code", pfCrieteria[0]), Subqueries.PropertyIn("Code", pfCrieteria[1]) )); } else if (orderType == BusinessConstants.CODE_MASTER_FLOW_TYPE_VALUE_PRODUCTION) { DetachedCriteria[] regionCrieteria = SecurityHelper.GetRegionPermissionCriteria(userCode); criteria.Add( Expression.Or( Subqueries.PropertyIn("Code", regionCrieteria[0]), Subqueries.PropertyIn("Code", regionCrieteria[1]) )); } else if (orderType == BusinessConstants.CODE_MASTER_FLOW_TYPE_VALUE_TRANSFER) { DetachedCriteria[] pfCrieteria = SecurityHelper.GetRegionPermissionCriteria(userCode); criteria.Add( Expression.Or( Subqueries.PropertyIn("Code", pfCrieteria[0]), Subqueries.PropertyIn("Code", pfCrieteria[1]) )); } else if (orderType == BusinessConstants.CODE_MASTER_FLOW_TYPE_VALUE_CUSTOMERGOODS) { DetachedCriteria[] pfCrieteria = SecurityHelper.GetCustomerPermissionCriteria(userCode); criteria.Add( Expression.Or( Subqueries.PropertyIn("Code", pfCrieteria[0]), Subqueries.PropertyIn("Code", pfCrieteria[1]) )); } if (!includeInactive) { criteria.Add(Expression.Eq("IsActive", true)); } return(this.criteriaMgr.FindAll <Party>(criteria)); }
private IEnumerable <TranslationChange> BuildTranslations() { var me = TranslatorService.FindByEmail(HttpContext.User.Identity.Name); var changes = DbSession.CreateCriteria <Translation>() .Add(Restrictions.Eq("IsPublished", false)) .Add(Restrictions.Eq("Translator", me)) .CreateAlias("Key", "k") .CreateAlias("k.Set", "s") .Future <Translation>(); var votedOn = DetachedCriteria.For <TranslationVote>() .Add(Restrictions.Eq("IsPublished", false)) .Add(Restrictions.Eq("Translator", me)) .CreateAlias("Translation", "t") .SetProjection(Projections.Property("t.Id")); var votes = DbSession.CreateCriteria <Translation>() .Add(Subqueries.PropertyIn("Id", votedOn)) .Future <Translation>(); changes = changes.Concat(votes); var neutralTranslations = DbSession.QueryOver <Translation>() .Where(Restrictions.On <Translation>(x => x.Key).IsIn(changes.Select(x => x.Key).ToArray())) .And(x => x.Language == LanguageService.GetNeutralLanguage()) .And(x => x.NeedsReviewing == false) .OrderBy(x => x.Votes).Desc .Future(); var leadingTranslations = DbSession.QueryOver <Translation>() .Where(Restrictions.On <Translation>(x => x.Key).IsIn(changes.Select(x => x.Key).ToArray())) .And(x => x.IsPublished) .And(x => x.NeedsReviewing == false) .OrderBy(x => x.Votes).Desc .Future(); var translations = ( from change in changes let neutralTranslation = neutralTranslations.Where(x => x.Key == change.Key).FirstOrDefault() let leadingTranslation = leadingTranslations.Where(x => x.Key == change.Key && x.Language == change.Language).FirstOrDefault() let voted = votes.Any(x => x.Key == neutralTranslation.Key) select new TranslationChange { KeyId = change.Key.Id, SetId = change.Key.Set.Id, SetName = change.Key.Set.Name, Language = change.Language.IsoCode, Term = neutralTranslation.Value, LeadingValue = leadingTranslation == null ? (voted ? change.Value : string.Empty) : leadingTranslation.Value, Value = change.Value, Voted = voted } ).ToList(); return(translations); }
/// <summary> /// Finds all active users. /// </summary> /// <returns></returns> public override IQueryable <Usuario> FindAll() { var dc = DetachedCriteria.For <Usuario>() .Add(Restrictions.IsNull(Projections.Property <Usuario>(u => u.FechaBaja))) .SetProjection(Projections.Property <Usuario>(u => u.Id)); return(Session.CreateCriteria <Usuario>() .Add(Subqueries.PropertyIn("Id", dc)).Future <Usuario>().AsQueryable()); }
protected override void DoSearch() { string code = this.tbCode.Text != string.Empty ? this.tbCode.Text.Trim() : string.Empty; string carrier = this.tbCarrier.Text != string.Empty ? this.tbCarrier.Text.Trim() : string.Empty; string type = this.ddlType.SelectedIndex != -1 ? this.ddlType.SelectedValue : string.Empty; if (SearchEvent != null) { #region DetachedCriteria DetachedCriteria selectCriteria = DetachedCriteria.For(typeof(Vehicle)); DetachedCriteria selectCountCriteria = DetachedCriteria.For(typeof(Vehicle)) .SetProjection(Projections.Count("Code")); if (code != string.Empty) { selectCriteria.Add(Expression.Like("Code", code, MatchMode.Start)); selectCountCriteria.Add(Expression.Like("Code", code, MatchMode.Start)); } if (carrier != string.Empty) { selectCriteria.Add(Expression.Eq("Carrier.Code", carrier)); selectCountCriteria.Add(Expression.Eq("Carrier.Code", carrier)); } DetachedCriteria[] carrierCrieteria = SecurityHelper.GetCarrierPermissionCriteria(this.CurrentUser.Code); selectCriteria.Add( Expression.Or( Expression.Or( Subqueries.PropertyIn("Carrier.Code", carrierCrieteria[0]), Subqueries.PropertyIn("Carrier.Code", carrierCrieteria[1]) ), Expression.IsNull("Carrier.Code") ) ); selectCountCriteria.Add( Expression.Or( Expression.Or( Subqueries.PropertyIn("Carrier.Code", carrierCrieteria[0]), Subqueries.PropertyIn("Carrier.Code", carrierCrieteria[1]) ), Expression.IsNull("Carrier.Code") ) ); if (type != string.Empty) { selectCriteria.Add(Expression.Eq("Type", type)); selectCountCriteria.Add(Expression.Eq("Type", type)); } SearchEvent((new object[] { selectCriteria, selectCountCriteria }), null); #endregion } }
public Permission[] GetPermissionsFor(UsersGroup usersGroup, bool eager = false) { var criteria = DetachedCriteria.For <Permission>() .Add(Expression.Eq("UsersGroup", usersGroup) || Subqueries.PropertyIn("UsersGroup.Id", SecurityCriterions.AllUsersGroupParents(usersGroup).SetProjection(Projections.Id()))); return(FindResults(criteria, eager)); }
public static void SetPartySearchCriteria(DetachedCriteria criteria, string propertyName, string userCode) { DetachedCriteria[] partyCrieteria = SecurityHelper.GetPartyPermissionCriteria(userCode); criteria.Add( Expression.Or( Subqueries.PropertyIn(propertyName, partyCrieteria[0]), Subqueries.PropertyIn(propertyName, partyCrieteria[1]) )); }
/// <summary> /// Finds all active device types. /// </summary> /// <returns></returns> public override IQueryable <TipoDispositivo> FindAll() { var dc = getBaseDetachedCriteria(0); var c = Session.CreateCriteria <TipoDispositivo>() .Add(Subqueries.PropertyIn("Id", dc)); return(c.Future <TipoDispositivo>().AsQueryable()); }
/// <summary> /// Gets the permissions for the specified user /// </summary> /// <param name="user">The user.</param> /// <returns></returns> public Permission[] GetPermissionsFor(IUser user) { DetachedCriteria criteria = DetachedCriteria.For <Permission>() .Add(Expression.Eq("User", user) || Subqueries.PropertyIn("UsersGroup.Id", SecurityCriterions.AllGroups(user).SetProjection(Projections.Id()))); return(FindResults(criteria)); }