예제 #1
0
        public ICollection <TEntity> FindAll(NHibernate.Criterion.Order order, params ICriterion[] criteria)
        {
            ICriteria crit = RepositoryHelper <TEntity> .CreateCriteriaFromArray(sessionProvider.OpenSession.Session, criteria);

            crit.AddOrder(order);
            return(crit.List <TEntity>());
        }
예제 #2
0
        public ActionResult Index()
        {
            var criteria = DetachedCriteria.For(typeof(Article)).AddOrder(Order.Desc(Article.LastUpdatedProperty));
            var articles = daoTemplate.FindByCriteria <Article>(criteria);

            return(View(articles));
        }
예제 #3
0
        public ActionResult Index()
        {
            ViewData["categories"] = CategoryService.FindRootCategories().Where(cat => cat.IsVisible && cat.ParentIsVisible);

            var criteria = DetachedCriteria.For(typeof(Article));

            criteria.Add(Restrictions.Eq(Article.PlacementProperty, ArticlePlacement.News));
            criteria.AddOrder(Order.Desc(Article.LastUpdatedProperty));
            criteria.SetMaxResults(1);
            var articles = daoTemplate.FindByCriteria <Article>(criteria);

            if (articles.Count > 0)
            {
                ViewData["news"] = articles[0];
            }
            else
            {
                ViewData["news"] = new Article();
            }

            SetNewsArticleToViewData();


            return(View());
        }
예제 #4
0
        private DetachedCriteria GetSearchCriteriaFromListSearch(ProductListSearchCriteria listSearchCriteria, bool withTotal)
        {
            var searchCriteria = DetachedCriteria.For(typeof(Product), "p")
                                 .SetFetchMode("Prices", FetchMode.Join)
                                 .SetFetchMode("Categories", FetchMode.Join)
                                 .SetResultTransformer(new DistinctRootEntityResultTransformer());

            if (!listSearchCriteria.ShowDeletedProducts)
            {
                searchCriteria.Add(Restrictions.Eq("IsDeleted", false)); // default to showing not deleted products
            }

            if (!withTotal)
            {
                // add ordering by Property
                var sortBy = string.IsNullOrEmpty(listSearchCriteria.SortBy) ? "Name" : listSearchCriteria.SortBy;
                searchCriteria.AddOrder(listSearchCriteria.Ascending
                                            ? Order.Asc(sortBy)
                                            : Order.Desc(sortBy));
                searchCriteria.SetFirstResult(listSearchCriteria.CurrentPage * listSearchCriteria.ResultsPerPage)
                .SetMaxResults(listSearchCriteria.ResultsPerPage);
            }

            return(searchCriteria);
        }
예제 #5
0
파일: OrderDao.cs 프로젝트: kilonet/ezakaz
 public IList <Order> FindAllAdmin()
 {
     return(CreateCriteria()
            .Add(Expression.Eq("State", OrderState.Sent))
            .AddOrder(NHibOrder.Desc("DateSent"))
            .List <Order>());
 }
예제 #6
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="criteria"></param>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        protected Page <T> Paginated <T>(ICriteria criteria, PageRequest pageRequest) where T : class
        {
            if (pageRequest.Size > 0)
            {
                criteria.SetFirstResult(pageRequest.Offset);
                criteria.SetMaxResults(pageRequest.Size);
            }

            if (pageRequest.Sort != null && pageRequest.Sort.Orders != null && pageRequest.Sort.Orders.Count > 0)
            {
                foreach (var o in pageRequest.Sort.Orders)
                {
                    if (o.Ascending)
                    {
                        criteria.AddOrder(Order.Asc(o.Property));
                    }
                    else
                    {
                        criteria.AddOrder(Order.Desc(o.Property));
                    }
                }
            }

            var result = criteria.List <T>();

            criteria.SetFirstResult(0);
            criteria.SetMaxResults(1);

            var totalElements = criteria.SetProjection(Projections.Count(Projections.Id())).UniqueResult <long>();

            return(new Page <T>(result, result.Count, pageRequest.Page, result.Count, pageRequest.Sort, totalElements,
                                pageRequest.Size));
        }
        protected override void CreateMenu()
        {
            //base.CreateMenu();

            var orders = new Order[]
                         {
                             Order.Asc("Product"),
                             Order.Asc("NodePosition.Level"),
                             Order.Asc("NodePosition.Order")
                         };

            foreach(var menuTempate in Repository<MenuTemplate>.FindAll(orders))
            {
                var menu = NAccessContext.Domains.ProductRepository.CreateMenu(menuTempate, menuTempate.Code.Replace("TPL_ADMIN_", "ADMIN_"));

                if(menuTempate.Parent != null)
                {
                    var parent = NAccessContext.Domains.ProductRepository.FindAllMenuByMenuTemplate(menuTempate.Parent).FirstOrDefault();

                    if(parent != null)
                        NAccessContext.Domains.ProductRepository.ChangeMenuParent(menu, parent);
                }

                UnitOfWork.Current.TransactionalFlush();
            }
        }
예제 #8
0
 public override List <Item> FindAll()
 {
     return(new List <Item>(CreateCriteria()
                            .CreateAlias("Category", "c")
                            .AddOrder(Order.Asc("c.Name"))
                            .AddOrder(Order.Asc("Name"))
                            .List <Item>()));
 }
예제 #9
0
        public ActionResult AsList()
        {
            var criteria = DetachedCriteria.For <Article>().AddOrder(Order.Asc(Article.IndexProperty));

            criteria.Add(Restrictions.Eq(Article.PlacementProperty, ArticlePlacement.TopMenu));
            IList <Article> articles = daoTemplate.FindByCriteria <Article>(criteria);

            return(View(articles));
        }
예제 #10
0
 private static string GetSortingProperty(Order order)
 {
     /**
      * This method relies on the format that Order is using:
      * propertyName + ' ' + (ascending?"asc":"desc")
      */
     string str = order.ToString();
     return str.Substring(0, str.IndexOf(' '));
 }
예제 #11
0
        private ActionResult CommentsWidget()
        {
            var criteria = DetachedCriteria.For <Comment>();

            criteria.AddOrder(Order.Desc(Comment.DateProperty));
            var coments = daoTemplate.FindByCriteria <Comment>(criteria);

            return(View(coments));
        }
예제 #12
0
        public OrderExitOperation(Order order)
        {
            IsAsc = order.ToString().EndsWith("asc");
            IsDesc = order.ToString().EndsWith("desc");

            Preconditions.CheckState(IsAsc || IsDesc);

            //this.order = order;
            propertyName = GetSortingProperty(order);
        }
예제 #13
0
		/// <summary>
		/// Adds a collection of Order (sort by) specifiers to an ICriteria.
		/// </summary>
		/// <param name="criteria">The ICriteria that will be modified.</param>
		/// <param name="orders">The collection of Order specifiers.</param>
		internal static void AddOrdersToCriteria(ICriteria criteria, Order[] orders)
		{
			if (orders != null)
			{
				foreach (Order order in orders)
				{
					criteria.AddOrder(order);
				}
			}
		}
 protected static IList <T> LoadAllWithDistinct <T>(NHibernate.Criterion.Order order)
 {
     return
         (DetachedCriteria
          .For <T>()
          .SetResultTransformer(new DistinctRootEntityResultTransformer())
          .GetExecutableCriteria(UnitOfWork.CurrentSession)
          .AddOrder(order)
          .List <T>());
 }
예제 #15
0
        public ICollection <TEntity> FindAll(
            int firstResult, int numberOfResults, NHibernate.Criterion.Order selectionOrder, params ICriterion[] criteria)
        {
            ICriteria crit = RepositoryHelper <TEntity> .CreateCriteriaFromArray(sessionProvider.OpenSession.Session, criteria);

            crit.SetFirstResult(firstResult)
            .SetMaxResults(numberOfResults);
            crit.AddOrder(selectionOrder);
            return(crit.List <TEntity>());
        }
예제 #16
0
        //
        // GET: /Outcome/

        public ActionResult List()
        {
            DetachedCriteria criteria = DetachedCriteria.For(typeof(Outcome));

            criteria.AddOrder(Order.Asc("Date"));
            var outcomes = daoTemplate.FindByCriteria <Outcome>(criteria);
            IEnumerable <OutcomeListItemViewModel> viewModels = outcomes.Select(income => new OutcomeListItemViewModel(income));

            return(View(viewModels));
        }
예제 #17
0
        public IEnumerable <Category> ListCategoriesForProduct(Guid id)
        {
            var searchCriteria = DetachedCriteria.For(typeof(Category), "c")
                                 .CreateAlias("Products", "p")
                                 .Add(Restrictions.Eq("p.Id", id))
                                 .AddOrder(Order.Asc("Name"))
                                 .SetResultTransformer(new DistinctRootEntityResultTransformer());


            return(repository.Search(searchCriteria));
        }
예제 #18
0
        public ActionResult GetProductsJson(int productId)
        {
            var product  = daoTemplate.FindByID <Product>(productId);
            var criteria = DetachedCriteria.For <Product>();

            criteria.AddOrder(Order.Desc(Product.NameProperty));
            criteria.Add(Restrictions.Eq(Product.IsVisibleProperty, true));
            var products     = daoTemplate.FindByCriteria <Product>(criteria);
            var productsJson = products.Select(p => new { Name = p.Name, Id = p.Id, IsRecomended = product.Recomended.Contains(p) });

            return(Json(productsJson, JsonRequestBehavior.AllowGet));
        }
예제 #19
0
        public ActionResult List()
        {
            var crit = DetachedCriteria.For(typeof(Question));

            crit.AddOrder(Order.Desc(Question.DateProperty));
            IList <Question> qs = daoTemplate.FindByCriteria <Question>(crit);
            var notViewed       = qs.Where(x => x.IsViewed == false);

            foreach (var q in notViewed)
            {
                q.IsViewed = true;
                daoTemplate.Save(q);
            }
            return(View(qs));
        }
예제 #20
0
파일: OrderDao.cs 프로젝트: kilonet/ezakaz
        public IList <Order> FindByUserPaged(User user, int start, int size, SortDirection sortDirection, string sortField)
        {
            if (string.IsNullOrEmpty(sortField))
            {
                sortField     = "DateCreated";
                sortDirection = SortDirection.Descending;
            }

            return(CreateCriteria()
                   .Add(Expression.Eq("User", user))
                   //.AddOrder(NHibernate.Criterion.Order.Desc("DateCreated"))
                   .SetFirstResult(start)
                   .SetMaxResults(size)
                   .AddOrder(sortDirection == SortDirection.Ascending ? NHibOrder.Asc(sortField) : NHibOrder.Desc(sortField))
                   .List <Order>());
        }
예제 #21
0
파일: Form1.cs 프로젝트: sam39/ScudExporter
        private void button1_Click(object sender, EventArgs e)
        {
            BL.Settings settings = (BL.Settings)settingsBindingSource.DataSource;

            string FileName = settings.End_Date.ToString("yyyyMMdd") + "_1000_01.txt";
            string ZipFileName = settings.End_Date.ToString("yyyyMMdd") + "_1000_01.zip";

            NHibernate.ISession s = SessionFactory.GetSession();
            ICriteria crit = s.CreateCriteria(typeof(BL.Event));
                crit.Add(Expression.Eq("Event32", 32));
                crit.Add(Expression.Gt("Date_event", settings.Start_Date));
                crit.Add(Expression.Le("Date_event", settings.End_Date ));
                crit.Add(Expression.Eq("Zone_code", 2));
                crit.Add(Expression.Sql(" HozOrgan = some (select e.Id from pList as e where e.Section not in (" + settings.Excluded + "))"));
                Order ord = new Order("Date_event", false);
                crit.AddOrder(ord);
            System.Collections.IList listEv = crit.List();

            StreamWriter sw = new StreamWriter(dist_pathTextBox.Text + FileName, false, System.Text.Encoding.GetEncoding(1251));
            foreach (BL.Event evnt in listEv)
            {
                int ZoneIndex = 0;
                foreach (BL.DoorZone dz in settings.DoorZones)
                {
                    if (dz.Door_Index == evnt.Zone_code)
                    {
                        ZoneIndex = dz.Zone_code;
                    }
                }

                sw.WriteLine(evnt.Emp.TabNumber + ";"
                + evnt.Date_event.ToString("dd.MM.yyyy") + ";"
                + evnt.Date_event.ToString("HH:mm:ss") + ";"
                + evnt.Event_code.ToString() + ";"
                + ZoneIndex.ToString() + ";"
                );
            }
            sw.Close();

            using (ZipFile zip = new ZipFile())
            {
                zip.Password = settings.Password;
                zip.AddFile(dist_pathTextBox.Text + FileName, "");
                zip.Save(dist_pathTextBox.Text + ZipFileName);
            }
        }
예제 #22
0
        public static List <SelectListItem> GetBasicContent(StateType type)
        {
            ICriterion exp = Restrictions.Eq("DelFlag", false);

            exp = Restrictions.And(exp, Restrictions.Eq("TypeID", (int)type));
            NHibernate.Criterion.Order[] orders = new NHibernate.Criterion.Order[1] {
                new NHibernate.Criterion.Order("SequenceOrder", true)
            };
            var list = from content in FindAll(orders, exp).AsEnumerable()
                       select new SelectListItem
            {
                Text  = content.TypeName,
                Value = content.TypeID.ToString()
            };

            return(list.ToList());
        }
        private NHibernateCriterion.Order GetSortOrder(NHibernateRepositorySort sort)
        {
            if (sort == null)
            {
                return(null);
            }

            // Default the order to ascending
            var order = new NHibernateCriterion.Order(sort.Property, true);

            // Check to switch to descending
            if (sort.SortDirection == NHibernateRepositorySortDirection.Desc)
            {
                order = new NHibernateCriterion.Order(sort.Property, false);
            }

            return(order);
        }
예제 #24
0
        private void SetNewsArticleToViewData()
        {
            DetachedCriteria criteria;
            IList <Article>  articles;

            criteria = DetachedCriteria.For(typeof(Article));
            criteria.Add(Restrictions.Eq(Article.PlacementProperty, ArticlePlacement.MainPage));
            criteria.AddOrder(Order.Desc(Article.LastUpdatedProperty));
            criteria.SetMaxResults(1);
            articles = daoTemplate.FindByCriteria <Article>(criteria);
            if (articles.Count > 0)
            {
                ViewData["article"] = articles[0].Text;
            }
            else
            {
                ViewData["article"] = "";
            }
        }
예제 #25
0
        public Response <T> FindAllWithSort(int index, int count, IList <Sort> Sorts)
        {
            ICriteria criteriaQuery = SessionFactory.GetCurrentSession().CreateCriteria(typeof(T));

            // اگر سورت درخواست شده باشد
            if (Sorts != null)
            {
                foreach (var sort in Sorts)
                {
                    NHibernate.Criterion.Order order = new NHibernate.Criterion.Order(sort.SortColumn, sort.Asc);
                    criteriaQuery.AddOrder(order);
                }
            }
            int       resultCount = 0;
            IList <T> result      = (List <T>)criteriaQuery.List <T>();

            try
            {
                //resultCount = criteriaQuery.SetProjection(Projections.Count("ID")).UniqueResult<int>();
                resultCount = result.Count;
            }
            // در صورتی که آیدی نداشته باشیم شمارش از طریق دیگر انجام می شود
            catch (Exception ex)
            {
                //criteriaQuery = SessionFactory.GetCurrentSession().CreateCriteria(typeof(T));
                //IList<T> res = (List<T>)criteriaQuery.List<T>();
                //resultCount = result.Count;
            }
            // اگر ایندکس مقدار 1- داشت یعنی همه دیتا لود شود
            if (count != -1)
            {
                result = result.Skip(index).Take(count).ToList();
            }
            else
            {
                //result = (List<T>)criteriaQuery.List<T>();
            }



            return(new Response <T>(result, resultCount));
        }
 public KPGridJsonProperties(bool isSearch, int page, int rows,
                             string propertyOrder, string orderTypeJason,
                             string filterJson,  KPSessionJQGrid sessionJQGrid, string propertyCompany,
                             ICriterion initialFilter, Order initialOrder, object[] colModel)
 {
     IsSearch = isSearch;
     Page = page;
     Rows = rows;
     PropertyOrder = propertyOrder;
     OrderTypeJson = orderTypeJason;
     User = sessionJQGrid.SecuritySession.Login;
     Company = sessionJQGrid.SecuritySession.FrwCompany;
     PropertyCompanyEntity = propertyCompany;
     FilterJson = filterJson;
     ColModel = Array.ConvertAll<object, string>(colModel, Convert.ToString);
     List<JqGridColumnCustom> jqGridColumnCustomList = new List<JqGridColumnCustom>();
     foreach (string item in ColModel)
         jqGridColumnCustomList.Add(KPJsonJqGrid.GetColumnCustom(item));
     ColumnsCustom = jqGridColumnCustomList.ToArray();
     InitialFilter = initialFilter;
     InitialOrder = initialOrder;
 }
        public KPJqGridControl(string primaryKey, HiddenField hiddenKey, Type typeEntity, KPItemModelCollection KPitemsModel,
                              KPJqGridDoubleClickActionEnum DoubleClickAction, ICriterion filter, Order order)
        {
            #region Filter/Order
            this.InitialFilter = filter;
            this.InitialOrder = order;
            #endregion

            this.HiddenKey = hiddenKey == null ? new HiddenField() : hiddenKey;
            this.Caption = String.Empty;
            this.PrimaryKey = primaryKey;
            this.UrlService = System.Web.VirtualPathUtility.ToAbsolute("~/WCF/EntityService.svc/GetEntityFilter");
            this.TypeEntity = typeEntity;
            this.KPItemsModel = KPitemsModel;
            this.DoubleClickAction = DoubleClickAction;

            this.RowNum = KPJqGridRowNumEnum.RowsView_10;
            this.OrderRecords = KPJqGridTypeOrderEnum.ASC;
            this.ViewTotalRecordsLabel = true;
            this.Height = 100;
            this.Width = 300;
        }
 public static Array Where(Type t, ICriterion[] criteria, Order[] order)
 {
     return FindAll(t, order, criteria);
 }
예제 #29
0
		/// <summary>
		/// Paginates using an <see cref="ARPaginableCriteria"/>
		/// </summary>
		public static IPaginatedPage CreatePagination(int pageSize, Type targetType, Order[] orders, params ICriterion[] criterions)
		{
			IARPaginableDataSource criteria = new ARPaginableCriteria(targetType, orders, criterions);
			return CreatePagination(pageSize, criteria);
		}
 public static Array All(Type t, Order[] order)
 {
     return FindAll(t, order, new ICriterion[0]);
 }
 public static Array Where(Type t, ICriterion[] criteria, Order order)
 {
     return Where(t, criteria, new Order[] { order } );
 }
예제 #32
0
		/// <summary>
		/// Returns all instances found for the specified type
		/// using criteria and IStatelessSession.
		/// </summary>
		/// <param name="type">The target type.</param>
		/// <param name="criterias">The criteria expression</param>
		/// <param name="sortItems">An <see cref="Array"/> of <see cref="Order"/> objects.</param>
		/// <returns>The <see cref="Array"/> of results.</returns>
		public virtual Array FindAllStateless(Type type, ICriterion[] criterias, Order[] sortItems)
		{
			return FindAllStateless(type, criterias, sortItems, int.MinValue, int.MinValue);
		}
예제 #33
0
 /// <summary>
 /// Returns all instances found for the specified type
 /// using sort orders and criterias.
 /// </summary>
 /// <param name="targetType"></param>
 /// <param name="orders"></param>
 /// <param name="criterias"></param>
 /// <returns></returns>
 public static Array FindAll(Type targetType, Order[] orders, params ICriterion[] criterias)
 {
     return ActiveRecordBase.FindAll(targetType, orders, criterias);
 }
예제 #34
0
        /// <summary>
        /// Returns all instances found for the specified type 
        /// using sort orders and criteria.
        /// </summary>
        /// <param name="targetType">The The target type.</param>
        /// <param name="orders">An <see cref="Array"/> of <see cref="Order"/> objects.</param>
        /// <param name="criteria">The criteria expression</param>
        /// <returns>The <see cref="Array"/> of results.</returns>
        protected internal static Array FindAll(Type targetType, Order[] orders, params ICriterion[] criteria)
        {
            EnsureInitialized(targetType);

            ISession session = holder.CreateSession(targetType);

            try
            {
                ICriteria sessionCriteria = session.CreateCriteria(targetType);

                foreach(ICriterion cond in criteria)
                {
                    sessionCriteria.Add(cond);
                }

                AddOrdersToCriteria(sessionCriteria, orders);

                return SupportingUtils.BuildArray(targetType, sessionCriteria.List());
            }
            catch (ValidationException)
            {
                holder.FailSession(session);

                throw;
            }
            catch (Exception ex)
            {
                holder.FailSession(session);

                throw new ActiveRecordException("Could not perform FindAll for " + targetType.Name, ex);
            }
            finally
            {
                holder.ReleaseSession(session);
            }
        }
예제 #35
0
		public ARPaginableCriteria(Type targetType, Order[] orders, params ICriterion[] criterions)
		{
			this.targetType = targetType;
			this.orders = orders;
			this.criterions = criterions;
		}
예제 #36
0
        /// <summary>
        /// Returns a portion of the query results (sliced)
        /// </summary>
        /// <param name="targetType">The target type.</param>
        /// <param name="firstResult">The number of the first row to retrieve.</param>
        /// <param name="maxResults">The maximum number of results retrieved.</param>
        /// <param name="orders">An <see cref="Array"/> of <see cref="Order"/> objects.</param>
        /// <param name="criteria">The criteria expression</param>
        /// <returns>The sliced query results.</returns>
        protected internal static Array SlicedFindAll(Type targetType, int firstResult, int maxResults,
            Order[] orders, params ICriterion[] criteria)
        {
            EnsureInitialized(targetType);

            ISession session = holder.CreateSession(targetType);

            try
            {
                ICriteria sessionCriteria = session.CreateCriteria(targetType);

                foreach(ICriterion cond in criteria)
                {
                    sessionCriteria.Add(cond);
                }

                if (orders != null)
                {
                    foreach (Order order in orders)
                    {
                        sessionCriteria.AddOrder(order);
                    }
                }

                sessionCriteria.SetFirstResult(firstResult);
                sessionCriteria.SetMaxResults(maxResults);

                return SupportingUtils.BuildArray(targetType, sessionCriteria.List());
            }
            catch (ValidationException)
            {
                holder.FailSession(session);

                throw;
            }
            catch (Exception ex)
            {
                holder.FailSession(session);

                throw new ActiveRecordException("Could not perform SlicedFindAll for " + targetType.Name, ex);
            }
            finally
            {
                holder.ReleaseSession(session);
            }
        }
예제 #37
0
        /// <summary>
        /// Returns a portion of the query results (sliced)
        /// </summary>
        /// <param name="targetType">The target type.</param>
        /// <param name="firstResult">The number of the first row to retrieve.</param>
        /// <param name="maxResults">The maximum number of results retrieved.</param>
        /// <param name="orders">An <see cref="Array"/> of <see cref="Order"/> objects.</param>
        /// <param name="criteria">The criteria expression</param>
        /// <returns>The sliced query results.</returns>
        protected internal static Array SlicedFindAll(Type targetType, int firstResult, int maxResults,
            Order[] orders, DetachedCriteria criteria)
        {
            EnsureInitialized(targetType);

            ISession session = holder.CreateSession(targetType);

            try
            {
                ICriteria executableCriteria = criteria.GetExecutableCriteria(session);
                AddOrdersToCriteria(executableCriteria, orders);
                executableCriteria.SetFirstResult(firstResult);
                executableCriteria.SetMaxResults(maxResults);

                return SupportingUtils.BuildArray(targetType, executableCriteria.List());
            }
            catch(ValidationException)
            {
                holder.FailSession(session);

                throw;
            }
            catch(Exception ex)
            {
                holder.FailSession(session);

                throw new ActiveRecordException("Could not perform SlicedFindAll for " + targetType.Name, ex);
            }
            finally
            {
                holder.ReleaseSession(session);
            }
        }
예제 #38
0
        internal static Order[] PropertyNamesToOrderArray(bool asc, params string[] propertyNames)
        {
            Order[] orders = new Order[propertyNames.Length];

            for (int i = 0; i < propertyNames.Length; i++)
            {
                orders[i] = new Order(propertyNames[i], asc);
            }
            return orders;
        }
예제 #39
0
		public void OrderBySpecifiedPropertyWithCriteria()
		{
			using (var session = OpenSession())
			using (session.BeginTransaction())
			{
				var selectList = Projections.ProjectionList()
				                            .Add(Projections.Property("Id"), "Id")
				                            .Add(Projections.Property("Name"), "Name")
				                            .Add(Projections.Property("Address"), "Address")
											.Add(Projections.Property("Age"), "Age");
				var order = new Order("Age", false);
				var people = session.CreateCriteria<Person>()
									.SetProjection(selectList)
									.AddOrder(order)
									.SetResultTransformer(Transformers.AliasToBean<PersonDto>())
									.List<PersonDto>();

				Assert.That(people.Count, Is.EqualTo(2));
				Assert.That(people, Is.Ordered.By("Age").Descending);
			}
		}
예제 #40
0
파일: OrderDao.cs 프로젝트: kilonet/ezakaz
        public IList <Order> FindAllAdminPaged(int start, int size, SortDirection sortDirection, string sortField)
        {
            if (string.IsNullOrEmpty(sortField))
            {
                sortDirection = SortDirection.Descending;
                sortField     = "DateSent";
            }

            ICriteria criteria = CreateCriteria()
                                 .SetFirstResult(start)
                                 .SetMaxResults(size)
                                 .Add(Expression.Eq("State", OrderState.Sent))
                                 .CreateAlias("User", "user")
                                 .AddOrder(sortDirection == SortDirection.Ascending ? NHibOrder.Asc(sortField) : NHibOrder.Desc(sortField));

            return(criteria.List <Order>());
        }
		public void CompositeIdJoinsFailureExpected()
		{
			ISession s = OpenSession();
			ITransaction t = s.BeginTransaction();
			Person person = new Person();
			person.Name = "Noob";

			Product product = new Product();
			product.ProductId = new Product.ProductIdType();
			product.ProductId.Orgid = "x";
			product.ProductId.Productnumber = "1234";
			product.Name = "Hibernate 3";

			Order order = new Order();
			order.OrderId = new Order.OrderIdType();
			order.OrderId.Ordernumber = "1";
			order.OrderId.Orgid = "y";

			product.Orders.Add(order);
			order.Product = product;
			order.Person = person;

			s.Save(product);
			s.Save(order);
			s.Save(person);

			t.Commit();
			s.Close();

			s = OpenSession();
			t = s.BeginTransaction();
			Product p = (Product) s.CreateQuery("from Product p join fetch p.orders").List()[0];
			Assert.IsTrue(NHibernateUtil.IsInitialized(p.Orders));
			t.Commit();
			s.Close();

			s = OpenSession();
			t = s.BeginTransaction();
			object[] o = (object[]) s.CreateSQLQuery("select\r\n" +
			                                         "        product.orgid as {product.id.orgid}," +
			                                         "        product.productnumber as {product.id.productnumber}," +
			                                         "        {prod_orders}.orgid as orgid3_1_,\r\n" +
			                                         "        {prod_orders}.ordernumber as ordernum2_3_1_,\r\n" +
			                                         "        product.name as {product.name}," +
			                                         "        {prod_orders.element.*}," +
			                                         /*"        orders.PROD_NO as PROD4_3_1_,\r\n" +
				"        orders.person as person3_1_,\r\n" +
				"        orders.PROD_ORGID as PROD3_0__,\r\n" +
				"        orders.PROD_NO as PROD4_0__,\r\n" +
				"        orders.orgid as orgid0__,\r\n" +
				"        orders.ordernumber as ordernum2_0__ \r\n" +*/
			                                         "    from\r\n" +
			                                         "        Product product \r\n" +
			                                         "    inner join\r\n" +
			                                         "        TBL_ORDER {prod_orders} \r\n" +
			                                         "            on product.orgid={prod_orders}.PROD_ORGID \r\n" +
			                                         "            and product.productnumber={prod_orders}.PROD_NO")
			                        	.AddEntity("product", typeof(Product))
			                        	.AddJoin("prod_orders", "product.orders")
			                        	.List()[0];

			p = (Product) o[0];
			Assert.IsTrue(NHibernateUtil.IsInitialized(p.Orders));
			IEnumerator en = p.Orders.GetEnumerator();
			Assert.IsTrue(en.MoveNext());
			Assert.IsNotNull(en.Current);
			t.Commit();
			s.Close();
		}
예제 #42
0
 /// <summary>
 /// Searches and returns the first row.
 /// </summary>
 /// <param name="targetType">The target type</param>
 /// <param name="orders">The sort order - used to determine which record is the first one</param>
 /// <param name="criteria">The criteria expression</param>
 /// <returns>A <c>targetType</c> instance or <c>null</c></returns>
 protected internal static object FindFirst(Type targetType, Order[] orders, params ICriterion[] criteria)
 {
     Array result = SlicedFindAll(targetType, 0, 1, orders, criteria);
     return (result != null && result.Length > 0 ? result.GetValue(0) : null);
 }
예제 #43
0
 private static bool IsAscending(Order order)
 {
     return order.ToString().ToUpper().EndsWith("ASC");
 }
예제 #44
0
        public IList<User> FindUsersByEmail(Site site, string email)
        {
            if (site == null)
            throw new ArgumentNullException("site");

             DetachedCriteria crit = DetachedCriteria.For<User>();

             crit.Add(Restrictions.Eq("Email", email));
             crit.Add(Restrictions.Eq("Site", site));
             crit.Add(Restrictions.Eq("IsLogicallyDeleted", false));
             Order[] o = new Order[] { new Order("Email", true) };
             return Repository<User>.FindAll(crit, o);
        }
예제 #45
0
        private IList <SelectListItem> Products()
        {
            var products = daoTemplate.FindByCriteria(DetachedCriteria.For(typeof(Product)).AddOrder(Order.Asc("Name")));

            return((from Product product in products
                    select new SelectListItem()
            {
                Text = product.Name, Value = product.Id.ToString()
            }).ToList());
        }
  public static Array All(Type t, Order order)
 {
     return All(t, new Order[] { order });
 }
예제 #47
0
		/// <summary>
		/// Returns all instances found for the specified type
		/// using criteria and IStatelessSession.
		/// </summary>
		/// <param name="type">The target type.</param>
		/// <param name="criterias">The criteria expression</param>
		/// <param name="sortItems">An <see cref="Array"/> of <see cref="Order"/> objects.</param>
		/// <param name="firstRow">The number of the first row to retrieve.</param>
		/// <param name="maxRows">The maximum number of results retrieved.</param>
		/// <returns>The <see cref="Array"/> of results.</returns>
		public virtual Array FindAllStateless(Type type, ICriterion[] criterias, Order[] sortItems, int firstRow, int maxRows)
		{
			using (IStatelessSession session = GetStatelessSession())
			{
				try
				{
					ICriteria criteria = session.CreateCriteria(type);

					if (criterias != null)
					{
						foreach (ICriterion cond in criterias)
						{
							criteria.Add(cond);
						}
					}

					if (sortItems != null)
					{
						foreach (Order order in sortItems)
						{
							criteria.AddOrder(order);
						}
					}

					if (firstRow != int.MinValue) criteria.SetFirstResult(firstRow);
					if (maxRows != int.MinValue) criteria.SetMaxResults(maxRows);
					IList result = criteria.List();

					Array array = Array.CreateInstance(type, result.Count);
					result.CopyTo(array, 0);

					return array;
				}
				catch (Exception ex)
				{
					throw new DataException("Could not perform FindAllStateless for " + type.Name, ex);
				}
			}
		}
예제 #48
0
 /// <summary>
 /// Returns a portion of the query results (sliced)
 /// </summary>
 public static Array SlicedFindAll(Type targetType, int firstResult, int maxresults,
     Order[] orders, params ICriterion[] criterias)
 {
     return ActiveRecordBase.SlicedFindAll(targetType, firstResult,
                                           maxresults, orders, criterias);
 }
예제 #49
0
 /// <summary>
 /// Searches and returns the first row.
 /// </summary>
 /// <param name="targetType">The target type</param>
 /// <param name="orders">The sort order - used to determine which record is the first one</param>
 /// <param name="criterias">The criteria expression</param>
 /// <returns>A <c>targetType</c> instance or <c>null</c></returns>
 public static object FindFirst(Type targetType, Order[] orders, params ICriterion[] criterias)
 {
     return ActiveRecordBase.FindFirst(targetType, orders, criterias);
 }
예제 #50
0
 private static void GetOrder(Sort sort, ICriteria cr)
 {
     bool sortDir = sort.Direction == "ASC" ? true : false;
     Order order = new Order(string.Format("dept.{0}", sort.Column), sortDir);
     cr.AddOrder(order);
 }
예제 #51
0
 /// <summary>
 /// Returns a portion of the query results (sliced)
 /// </summary>
 public static Array SlicedFindAll(Type targetType, int firstResult, int maxResults,
     Order[] orders, DetachedCriteria criteria)
 {
     return ActiveRecordBase.SlicedFindAll(targetType, firstResult, maxResults, orders, criteria);
 }
예제 #52
0
        private static void GetOrder(Sort sort, ICriteria cr)
        {
            bool sortDir = sort.Direction == "ASC" ? true : false;
            Order order = null;

            if (sort.Column.IndexOf(".", StringComparison.OrdinalIgnoreCase) >= 0)
                order = new Order(sort.Column, sortDir);

            else
                order = new Order(string.Format("attendance.{0}", sort.Column), sortDir);

            cr.AddOrder(order);
        }