Beispiel #1
0
 public IMultiCriteria Add(DetachedCriteria detachedCriteria)
 {
     criteriaQueries.Add(
         detachedCriteria.GetExecutableCriteria(session)
         );
     return this;
 }
        public void AddUserSelectCriteria(string cacheKey, DetachedCriteria selectCriteria, DetachedCriteria selectCountCriteria, IDictionary<string, string> alias)
        {
            if (_page.Session["SelectCriteriaCache"] == null)
            {
                _page.Session["SelectCriteriaCache"] =  new Dictionary<string, CachedSelectCriteria>();
            }

            IDictionary<string, CachedSelectCriteria> selectCriteriaCache = (IDictionary<string, CachedSelectCriteria>)_page.Session["SelectCriteriaCache"];
            if (!selectCriteriaCache.ContainsKey(cacheKey) && selectCriteriaCache.Count > UserSelectCriteriaCacheSize)
            {
                //Cache��������UserSelectCriteria
                DateTime lastestTime = DateTime.Now;
                string lastestkey = string.Empty;
                foreach (string key in selectCriteriaCache.Keys)
                {

                    CachedSelectCriteria cache = selectCriteriaCache[key];
                    if (lastestTime > cache.LastAccessTime)
                    {
                        lastestkey = key;
                    }
                }
                selectCriteriaCache.Remove(lastestkey);
            }

            if (selectCriteriaCache.ContainsKey(cacheKey))
            {
                selectCriteriaCache[cacheKey] = new CachedSelectCriteria(DateTime.Now, selectCriteria, selectCountCriteria, alias);
            }
            else
            {
                selectCriteriaCache.Add(cacheKey, new CachedSelectCriteria(DateTime.Now, selectCriteria, selectCountCriteria, alias));
            }
        }
Beispiel #3
0
 ///<summary>
 /// Returns a clone of the original criteria, which will return the count 
 /// of rows that are returned by the original criteria query.
 ///</summary>
 public static DetachedCriteria TransformToRowCount(DetachedCriteria criteria)
 {
     ICriteria clonedCriteria = TransformToRowCount(criteria.GetCriteriaImpl());
     DetachedCriteria detachedCriteria = DetachedCriteria.For(clonedCriteria.CriteriaClass, clonedCriteria.Alias);
     detachedCriteria.SetCriteriaImpl((CriteriaImpl) clonedCriteria);
     return detachedCriteria;
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="rootAlias"></param>
        /// <param name="rootType"></param>
        /// <param name="matchMode"></param>
        /// <param name="entityMode"></param>
        /// <param name="instance"></param>
        /// <param name="classInfoProvider"></param>
        public CriteriaCompiled(string rootAlias, System.Type rootType, MatchMode matchMode, EntityMode entityMode,
                                object instance, Func<System.Type, IPersistentClassInfo> classInfoProvider)
        {
            
            if (rootAlias == null || rootAlias.Trim().Equals(string.Empty))
                throw new ArgumentException("The alias for making detached criteria cannot be empty or null", "rootAlias");

            if (rootType == null)
                throw new ArgumentNullException("rootType", "The type which can be used for maikng detached criteria cannot be null.");

            if (instance == null)
                throw new ArgumentNullException("instance", "The instance for building detached criteria cannot be null.");

            if (!rootType.IsInstanceOfType(instance))
                throw new ArgumentTypeException("The given instance for building detached criteria is not suitable for the given criteria type.", "instance", rootType, instance.GetType());

            this.matchMode = matchMode ?? MatchMode.Exact;
            this.entityMode = entityMode;
            this.instance = instance;
            this.classInfoProvider = classInfoProvider;

            this.relationshipTree = new RelationshipTree(rootAlias, rootType);
            this.criteria = DetachedCriteria.For(rootType, rootAlias);
            this.restrictions = new List<ICriterion>();
            this.Init();
        }
 public void InitPageParameter(DetachedCriteria criteria)
 {
     IList<PlannedBill> plannedBillList = TheCriteriaMgr.FindAll<PlannedBill>(criteria);
     this.MatchList = this.ConvertPlannedBillToTransformer(plannedBillList);
     this.BindList();
     this.tbItemCode.Focus();
 }
        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 int FindCount(DetachedCriteria selectCriteria)
 {
     IList list = CriteriaMgr.FindAll(selectCriteria);
     if (list != null && list.Count > 0)
     {
         if (list[0] is int)
         {
             return int.Parse(list[0].ToString());
         }
         else if (list[0] is object[])
         {
             return int.Parse(((object[])list[0])[0].ToString());
         }
         //由于性能问题,此后禁用该方法。
         //else if (list[0] is object)
         //{
         //    return list.Count;
         //}
         else
         {
             throw new Exception("unknow result type");
         }
     }
     else
     {
         return 0;
     }
 }
		protected SubqueryExpression(String op, String quantifier, DetachedCriteria dc, bool prefixOp)
		{
			criteriaImpl = dc.GetCriteriaImpl();
			this.quantifier = quantifier;
			this.prefixOp = prefixOp;
			this.op = op;
		}
Beispiel #9
0
 public void BindDataSource(DetachedCriteria selectCriteria)
 {
     IList<PlannedBill> plannedBillList = TheCriteriaMgr.FindAll<PlannedBill>(selectCriteria);
     this.AutoCalculate(plannedBillList);
     this.GV_List.DataSource = plannedBillList;
     this.GV_List.DataBind();
     UpdateView();
 }
    public void BindDataSource(DetachedCriteria selectCriteria, bool isExport)
    {
        IList<PlannedBill> plannedBills = TheCriteriaMgr.FindAll<PlannedBill>(selectCriteria);

        if (IsSupplier)
        {
            plannedBills = (from p in plannedBills
                            group p by new { p.Item, p.OrderNo, p.ReceiptNo, p.BillAddress, p.Uom, p.CreateDate, p.UnitPrice, p.Currency } into g
                            select new PlannedBill
                            {
                                Item = g.Key.Item,
                                OrderNo = g.Key.OrderNo,
                                ReceiptNo = g.Key.ReceiptNo,
                                BillAddress = g.Key.BillAddress,
                                Uom = g.Key.Uom,
                                CreateDate = g.Key.CreateDate,
                                UnitPrice = g.Key.UnitPrice,
                                Currency = g.Key.Currency,
                                PlannedQty = g.Sum(p => p.PlannedQty),
                                PlannedAmount = g.Sum(p => p.PlannedAmount),
                                ActingQty = g.Sum(p => p.ActingQty),
                                ActingAmount = g.Sum(p => p.ActingAmount)
                            })
                            //.Where(p => this.CurrentUser.HasPermission(p.BillAddress.Party.Code))
                            .ToList();
        }
        plannedBills = plannedBills.OrderBy(p => p.CreateDate).OrderBy(p => p.Item.Code).ToList();
        this.GV_List.DataSource = plannedBills;
        this.GV_List.DataBind();
        UpdateView();
        if (isExport && GV_List.Rows.Count > 0)
        {
            string dateTime = DateTime.Now.ToString("MMddhhmmss");
            int lastColumnIndex = GV_List.Columns.Count - 1;
            DataControlField dataControlField0 = null;
            //DataControlField dataControlFieldLast = null;
            if (!IsSupplier)
            {
                dataControlField0 = GV_List.Columns[0];
                //dataControlFieldLast = GV_List.Columns[lastColumnIndex];
                //GV_List.Columns.RemoveAt(lastColumnIndex);
                GV_List.Columns.RemoveAt(0);

            }

            this.ExportXLS(GV_List, "PlanBill" + dateTime + ".xls");

            if (!IsSupplier)
            {
                GV_List.Columns.Insert(0, dataControlField0);
                //GV_List.Columns.Insert(lastColumnIndex-1, dataControlFieldLast);
            }
        }

    }
		private void SerializeAndList(DetachedCriteria dc)
		{
			byte[] bytes = SerializationHelper.Serialize(dc);

			DetachedCriteria dcs = (DetachedCriteria)SerializationHelper.Deserialize(bytes);

			using (ISession s = OpenSession())
			{
				dcs.GetExecutableCriteria(s).List();
			}
		}
		private void AssertCriteriaAreNotEqual(DetachedCriteria expected, DetachedCriteria actual)
		{
			try
			{
				AssertCriteriaAreEqual(expected, actual);
			}
			catch
			{
				return;
			}
			Assert.Fail("No exception thrown");
		}
        public static Type GetRootType(DetachedCriteria criteria, ISession session)
        {
            Type rootType = criteria.GetRootEntityTypeIfAvailable();
            if (rootType != null)
            {
                return rootType;
            }

            ISessionFactoryImplementor factory = (ISessionFactoryImplementor)session.SessionFactory;
            IEntityPersister persister = factory.GetEntityPersister(criteria.EntityOrClassName);
            if (persister == null)
                throw new InvalidOperationException("Could not find entity named: " + criteria.EntityOrClassName);

            return persister.GetMappedClass(EntityMode.Poco);
        }
Beispiel #14
0
    public void InitPageParameter(DetachedCriteria selectCriteria)
    {
        this.InspectCriteria = selectCriteria;
        IList<InspectOrderDetail> pendingInspectOrderDetailList = TheCriteriaMgr.FindAll<InspectOrderDetail>(selectCriteria);

        this.GV_List.DataSource = pendingInspectOrderDetailList;
        this.GV_List.DataBind();
        if (pendingInspectOrderDetailList.Count == 0)
        {
            this.lblMessage.Visible = true;
            this.lblMessage.Text = "${Common.GridView.NoRecordFound}";
        }
        else
        {
            this.lblMessage.Visible = false;
        }
    }
Beispiel #15
0
    public void InitPageParameter(DetachedCriteria selectCriteria)
    {
        IList<InspectResult> unqualifiedGoodsList = TheCriteriaMgr.FindAll<InspectResult>(selectCriteria);

        this.GV_List.DataSource = unqualifiedGoodsList;
        this.GV_List.DataBind();
        if (unqualifiedGoodsList.Count == 0)
        {
            this.lblMessage.Visible = true;
            this.lblMessage.Text = "${Common.GridView.NoRecordFound}";
            this.btnPrint.Visible = false;
        }
        else
        {
            this.lblMessage.Visible = false;
            this.btnPrint.Visible = true;
        }
    }
Beispiel #16
0
    public void InitPageParameter(DetachedCriteria selectCriteria)
    {
        IList<OrderHead> orderHeadList = TheCriteriaMgr.FindAll<OrderHead>(selectCriteria);

        this.GV_List.DataSource = orderHeadList;
        this.GV_List.DataBind();
        if (orderHeadList.Count == 0)
        {
            this.lblMessage.Visible = true;
            this.lblMessage.Text = "${Common.GridView.NoRecordFound}";
            this.btnPrint.Visible = false;
        }
        else
        {
            this.lblMessage.Visible = false;
            this.btnPrint.Visible = true;
        }
    }
        public static DetachedCriteria[] GetPartyPermissionCriteria(string userCode, params string[] partyType)
        {
            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", BusinessConstants.CODE_MASTER_PERMISSION_CATEGORY_TYPE_VALUE_ORGANIZATION));
            if (partyType != null && partyType.Length > 0)
            {
                upSubCriteria.Add(Expression.In("pmc.Code", partyType));
            }
            upSubCriteria.Add(Expression.Eq("u.Code", userCode));
            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", BusinessConstants.CODE_MASTER_PERMISSION_CATEGORY_TYPE_VALUE_ORGANIZATION));
            if (partyType != null && partyType.Length > 0)
            {
                rpSubCriteria.Add(Expression.In("pmc.Code", partyType));
            }
            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", userCode));
            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 void SetSearchCriteria(DetachedCriteria SelectCriteria, DetachedCriteria SelectCountCriteria, IDictionary<string, string> alias, int range)
 {
     switch (range)
     {
         case 1:
             this.ucOrderTracerList.Visible = false;
             this.ucIpDetList.Visible = false;
             this.ucOrderDetailList.Visible = false;
             this.ucBillList.Visible = true;
             this.ucBillList.SetSearchCriteria(SelectCriteria, SelectCountCriteria, alias);
             this.ucBillList.UpdateView();
             break;
         case 2:
             this.ucOrderTracerList.Visible = false;
             this.ucBillList.Visible = false;
             this.ucOrderDetailList.Visible = false;
             this.ucIpDetList.Visible = true;
             this.ucIpDetList.SetSearchCriteria(SelectCriteria, SelectCountCriteria, alias);
             this.ucIpDetList.UpdateView();
             break;
         case 3:
             this.ucIpDetList.Visible = false;
             this.ucBillList.Visible = false;
             this.ucOrderDetailList.Visible = false;
             this.ucOrderTracerList.Visible = true;
             this.ucOrderTracerList.SetSearchCriteria(SelectCriteria, SelectCountCriteria, alias);
             this.ucOrderTracerList.UpdateView();
             break;
         case 4:
             this.ucIpDetList.Visible = false;
             this.ucBillList.Visible = false;
             this.ucOrderDetailList.Visible = true;
             this.ucOrderTracerList.Visible = false;
             this.ucOrderDetailList.SetSearchCriteria(SelectCriteria, SelectCountCriteria, alias);
             this.ucOrderDetailList.UpdateView();
             break;
     }
 }
		protected override Expression VisitMethodCall(MethodCallExpression expr)
		{
			Type = BinaryCriterionType.Criteria;

			//TODO: don't hardcode this alias 'sub'
			Criteria = DetachedCriteria.ForEntityName(rootCriteria.GetEntityOrClassName(), "sub");

			EntityExpression rootEntity = EntityExpressionVisitor.RootEntity(expr);
			if (rootEntity != null)
			{
				string identifierName = rootEntity.MetaData.IdentifierPropertyName;
				Criteria.Add(Restrictions.EqProperty(rootCriteria.Alias + "." + identifierName, "sub." + identifierName));
			}

			if (SelectArgumentsVisitor.SupportsMethod(expr.Method.Name))
			{
				var projectionVisitor = new SelectArgumentsVisitor(Criteria.Adapt(session), session);
				projectionVisitor.Visit(expr);
				Criteria.SetProjection(projectionVisitor.Projection);
			}

			return expr;
		}
Beispiel #20
0
 /// <summary> Create a query (ICriteria) </summary>
 public ICriteria CreateQuery(DetachedCriteria detachedCriteria)
 {
     return(detachedCriteria.GetExecutableCriteria(_session));
 }
Beispiel #21
0
 /// <summary>
 /// Exceutes the query for projection or aggregation  and returns the result as object collection
 /// </summary>
 /// <param name="criteria">the cirteria to look for</param>
 /// <returns>Objectcollection of particular type </returns>
 public ICollection <U> GetProjectedResultArray <U>(DetachedCriteria criteria)
 {
     return(internalRepository.GetProjectedResultArray <U>(criteria));
 }
Beispiel #22
0
 public IList <T> FindAll <T>(DetachedCriteria criteria, int firstRow, int maxRows)
 {
     return(queryDao.FindAll <T>(criteria, firstRow, maxRows));
 }
Beispiel #23
0
 public IList FindAll(DetachedCriteria criteria)
 {
     return(queryDao.FindAll(criteria));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ScalarProjectionQuery{ARType,TResult}"/> class.
 /// </summary>
 /// <param name="projection">The projection.</param>
 /// <param name="criteria">The detached criteria.</param>
 public ScalarProjectionQuery(IProjection projection, DetachedCriteria criteria)
 {
     this.projection  = projection;
     detachedCriteria = criteria;
 }
 /// <summary>
 /// Check if any instance matching the criteria exists in the database.
 /// </summary>
 /// <param name="targetType">The target type.</param>
 /// <param name="detachedCriteria">The criteria expression</param>
 /// <returns><c>true</c> if an instance is found; otherwise <c>false</c>.</returns>
 public static bool Exists(Type targetType, DetachedCriteria detachedCriteria)
 {
     return ActiveRecordBase.Exists(targetType, detachedCriteria);
 }
        public void ExecutableCriteria()
        {
            // All query below don't have sense, are only to test if all needed classes are serializable

            // Basic criterion
            DetachedCriteria dc = DetachedCriteria.For(typeof(Student))
                                  .Add(Expression.Between("Name", "aaaaa", "zzzzz"))
                                  .Add(Expression.EqProperty("Name", "Name"))
                                  .Add(Expression.Ge("Name", "a"))
                                  .Add(Expression.GeProperty("Name", "Name"))
                                  .Add(Expression.Gt("Name", "z"))
                                  .Add(Expression.GtProperty("Name", "Name"))
                                  .Add(Expression.IdEq(1))
                                  .Add(Expression.In("Name", new string[] { "Gavin", "Ralph" }))
                                  .Add(Expression.InsensitiveLike("Name", "GAVIN"))
                                  .Add(Expression.IsEmpty("Enrolments"))
                                  .Add(Expression.IsNotEmpty("Enrolments"))
                                  .Add(Expression.IsNotNull("PreferredCourse"))
                                  .Add(Expression.IsNull("PreferredCourse"))
                                  .Add(Expression.Le("Name", "a"))
                                  .Add(Expression.LeProperty("Name", "Name"))
                                  .Add(Expression.Lt("Name", "z"))
                                  .Add(Expression.LtProperty("Name", "Name"))
                                  .Add(Expression.Like("Name", "G%"))
                                  .Add(Expression.Not(Expression.Eq("Name", "Ralph")))
                                  .Add(Expression.NotEqProperty("Name", "Name"))
                                  .AddOrder(Order.Asc("StudentNumber"))
                                  .SetProjection(Property.ForName("StudentNumber"));

            SerializeAndList(dc);

            // Like match modes
            dc = DetachedCriteria.For(typeof(Student))
                 .Add(Expression.Like("Name", "Gavin", MatchMode.Anywhere))
                 .Add(Expression.Like("Name", "Gavin", MatchMode.End))
                 .Add(Expression.Like("Name", "Gavin", MatchMode.Exact))
                 .Add(Expression.Like("Name", "Gavin", MatchMode.Start));

            SerializeAndList(dc);

            // Logical Expression
            dc = DetachedCriteria.For(typeof(Student))
                 .Add(Expression.Or(Expression.Eq("Name", "Ralph"), Expression.Eq("Name", "Gavin")))
                 .Add(
                Expression.And(Expression.Gt("StudentNumber", 1L),
                               Expression.Lt("StudentNumber", 10L)));

            SerializeAndList(dc);

            // Projections
            dc = DetachedCriteria.For(typeof(Enrolment))
                 .SetProjection(Projections.Distinct(Projections.ProjectionList()
                                                     .Add(Projections.Property("StudentNumber"), "stNumber")
                                                     .Add(Projections.Property("CourseCode"), "cCode")))
                 .Add(Expression.Lt("StudentNumber", 668L));
            SerializeAndList(dc);

            dc = DetachedCriteria.For(typeof(Enrolment))
                 .SetProjection(Projections.Count("StudentNumber").SetDistinct());
            SerializeAndList(dc);

            dc = DetachedCriteria.For(typeof(Enrolment))
                 .SetProjection(Projections.ProjectionList()
                                .Add(Projections.Count("StudentNumber"))
                                .Add(Projections.Max("StudentNumber"))
                                .Add(Projections.Min("StudentNumber"))
                                .Add(Projections.Avg("StudentNumber")));
            SerializeAndList(dc);

            // Junctions
            dc = DetachedCriteria.For(typeof(Student))
                 .Add(Expression.Conjunction()
                      .Add(Expression.Eq("Name", "Ralph"))
                      .Add(Expression.Eq("StudentNumber", 1L)))
                 .Add(Expression.Disjunction()
                      .Add(Expression.Eq("Name", "Ralph"))
                      .Add(Expression.Eq("Name", "Gavin")));
            SerializeAndList(dc);

            // Subquery
            dc = DetachedCriteria.For(typeof(Student))
                 .Add(Property.ForName("StudentNumber").Eq(232L))
                 .SetProjection(Property.ForName("Name"));

            DetachedCriteria dcs = DetachedCriteria.For(typeof(Student))
                                   .Add(Subqueries.PropertyEqAll("Name", dc));

            SerializeAndList(dc);

            // SQLCriterion
            dc = DetachedCriteria.For(typeof(Student))
                 .Add(Expression.Sql("{alias}.Name = 'Gavin'"));
            SerializeAndList(dc);

            // SQLProjection
            dc = DetachedCriteria.For(typeof(Enrolment))
                 .SetProjection(Projections.SqlProjection("1 as constOne, count(*) as countStar",
                                                          new String[] { "constOne", "countStar" },
                                                          new IType[] { NHibernateUtil.Int32, NHibernateUtil.Int32 }));
            SerializeAndList(dc);

            dc = DetachedCriteria.For(typeof(Student))
                 .SetProjection(
                Projections.SqlGroupProjection("COUNT({alias}.studentId), {alias}.preferredCourseCode",
                                               "{alias}.preferredCourseCode",
                                               new string[] { "studentsOfCourse", "CourseCode" },
                                               new IType[] { NHibernateUtil.Int32, NHibernateUtil.Int32 }));
            SerializeAndList(dc);

            // Result transformers
            dc = DetachedCriteria.For(typeof(Enrolment))
                 .CreateAlias("Student", "st")
                 .CreateAlias("Course", "co")
                 .SetProjection(Projections.ProjectionList()
                                .Add(Projections.Property("st.Name"), "studentName")
                                .Add(Projections.Property("co.Description"), "courseDescription")
                                )
                 .AddOrder(Order.Desc("studentName"))
                 .SetResultTransformer(Transformers.AliasToBean(typeof(StudentDTO)));
            SerializeAndList(dc);
        }
Beispiel #27
0
        public async Task IncrementQueryExecutionCount_WhenExplicitQueryIsExecutedAsync()
        {
            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    await(FillDbAsync(s));
                    await(tx.CommitAsync());
                }

            IStatistics stats = Sfi.Statistics;

            stats.Clear();
            using (ISession s = OpenSession())
            {
                var r = await(s.CreateCriteria <Country>().ListAsync());
            }
            Assert.AreEqual(1, stats.QueryExecutionCount);

            stats.Clear();
            using (ISession s = OpenSession())
            {
                var r = await(s.CreateQuery("from Country").ListAsync());
            }
            Assert.AreEqual(1, stats.QueryExecutionCount);

            stats.Clear();

            var driver = Sfi.ConnectionProvider.Driver;

            if (driver.SupportsMultipleQueries)
            {
                using (var s = OpenSession())
                {
                    var r = await(s.CreateMultiQuery().Add("from Country").Add("from Continent").ListAsync());
                }
                Assert.AreEqual(1, stats.QueryExecutionCount);

                stats.Clear();
                using (var s = OpenSession())
                {
                    var r = await(s.CreateMultiCriteria().Add(DetachedCriteria.For <Country>()).Add(DetachedCriteria.For <Continent>()).ListAsync());
                }
                Assert.AreEqual(1, stats.QueryExecutionCount);
            }

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    await(CleanDbAsync(s));
                    await(tx.CommitAsync());
                }
        }
		internal SelectSubqueryExpression(DetachedCriteria dc)
			: base(null, null, dc)
		{
		}
Beispiel #29
0
        private void CreateNextPropertyLevel(DetachedCriteria criteria, List <string> propertyList, int listPointer, Junction dependencyCriterion)
        {
            Dictionary <string, AssociationEntry> ascs = GetAssociations();

            string           associationKey = GetAssociationKey(propertyList, listPointer);
            AssociationEntry e = null;

            if (ascs.ContainsKey(associationKey))
            {
                e = ascs[associationKey];
                if (listPointer == propertyList.Count - 1)
                {
                    if (mCriterion == null)
                    {
                        mCriterion = BuildCriterion(e.Association);
                    }
                    if (dependencyCriterion != null)
                    {
                        dependencyCriterion.Add(mCriterion);
                    }
                    else
                    {
                        criteria.Add(mCriterion);
                    }
                }
                else
                {
                    DetachedCriteria subCriteria = e.Criteria;
                    if (subCriteria == null)
                    {
                        subCriteria = criteria.CreateCriteria(e.Association, e.Alias, JoinType.InnerJoin);
                        e.Criteria  = subCriteria;
                    }
                    listPointer++;
                    CreateNextPropertyLevel(subCriteria, propertyList, listPointer, dependencyCriterion);
                }
            }
            else
            {
                bool isThisId = associationKey.ToLower().EndsWith(".id");
                if (listPointer == 0)
                {
                    e = new AssociationEntry(propertyList[0], propertyList[0], string.Format("p{0}{1}", Stopwatch.GetTimestamp().ToString(), listPointer.ToString()));
                }
                else
                {
                    string           parentAssociation = GetAssociationKey(propertyList, listPointer - 1);
                    AssociationEntry parentEntry       = ascs[parentAssociation]; // léteznie kell, máskülönben ide sem juthattam volna
                    e = new AssociationEntry(associationKey, string.Format("{0}.{1}", parentEntry.Alias, propertyList[listPointer]), string.Format("p{0}{1}", Stopwatch.GetTimestamp().ToString(), listPointer.ToString()));
                }
                if (!isThisId)
                {
                    // az id asszociációkat nem mentjük le
                    ascs[e.Key] = e;
                }

                if (listPointer == propertyList.Count - 1 || isThisId)
                {
                    if (mCriterion == null)
                    {
                        mCriterion = BuildCriterion((isThisId && listPointer < propertyList.Count - 1) ? string.Format("{0}.{1}", e.Association, propertyList[listPointer + 1]) : e.Association);
                    }
                    if (dependencyCriterion != null)
                    {
                        dependencyCriterion.Add(mCriterion);
                    }
                    else
                    {
                        criteria.Add(mCriterion);
                    }
                }
                else
                {
                    DetachedCriteria subCriteria = e.Criteria;
                    if (subCriteria == null)
                    {
                        subCriteria = criteria.CreateCriteria(e.Association, e.Alias, JoinType.InnerJoin);
                        e.Criteria  = subCriteria;
                    }
                    listPointer++;
                    CreateNextPropertyLevel(subCriteria, propertyList, listPointer, dependencyCriterion);
                }
            }
        }
Beispiel #30
0
 /// <summary>
 /// Builds the criterion.
 /// </summary>
 /// <param name="criteria">The criteria.</param>
 public virtual void BuildCriteria(DetachedCriteria criteria)
 {
     BuildCriteria(criteria, null);
 }
Beispiel #31
0
 public IMultiCriteria Add(string key, DetachedCriteria detachedCriteria)
 {
     return(Add <object>(key, detachedCriteria));
 }
Beispiel #32
0
 /// <summary>
 /// Sets the fetch mode.
 /// </summary>
 /// <typeparam name="T">Type setting fetch mode for.</typeparam>
 /// <param name="criteria">The criteria.</param>
 /// <param name="associationPropertyExpression">The association property expression.</param>
 /// <param name="mode">The mode to set.</param>
 /// <returns>A <see cref="DetachedCriteria"/></returns>
 public static DetachedCriteria SetFetchMode <T>(this DetachedCriteria criteria, Expression <Func <T, object> > associationPropertyExpression, FetchMode mode)
 {
     return(SetFetchMode <T, object>(criteria, associationPropertyExpression, mode));
 }
 /// <summary>
 /// Searches and returns the first row.
 /// </summary>
 /// <param name="targetType">The target type.</param>
 /// <param name="detachedCriteria">The criteria.</param>
 /// <param name="orders">The sort order - used to determine which record is the first one.</param>
 /// <returns>A <c>targetType</c> instance or <c>null.</c></returns>
 public static object FindFirst(Type targetType, DetachedCriteria detachedCriteria, params Order[] orders)
 {
     return ActiveRecordBase.FindFirst(targetType, detachedCriteria, orders);
 }
Beispiel #34
0
        public void CanExecuteQueryBatch()
        {
            FutureQueryOf <Parent> futureQueryOfParents  = new FutureQueryOf <Parent>(DetachedCriteria.For <Parent>());
            FutureQueryOf <Child>  futureQueryOfChildren = new FutureQueryOf <Child>(DetachedCriteria.For <Child>());

            Assert.AreEqual(0, futureQueryOfParents.Results.Count);

            //This also kills the database, because we use an in
            // memory one ,so we ensure that the code is not
            // executing a second query
            CurrentContext.DisposeUnitOfWork();

            Assert.AreEqual(0, futureQueryOfChildren.Results.Count);
        }
 /// <summary>
 /// Returns a portion of the query results (sliced)
 /// </summary>
 public static Array SlicedFindAll(Type targetType, int firstResult, int maxResults,
     DetachedCriteria criteria)
 {
     return ActiveRecordBase.SlicedFindAll(targetType, firstResult, maxResults, criteria);
 }
        public void SubqueriesExpressions()
        {
            DetachedCriteria dc = DetachedCriteria.For(typeof(Student))
                                  .Add(Expression.Eq("Name", "Gavin King"));
            ICriterion c = Subqueries.Eq("Gavin King", dc);

            NHAssert.IsSerializable(c);
            c = Subqueries.EqAll("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.Exists(dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.Ge("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.GeAll("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.GeSome("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.Gt("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.GtAll("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.GtSome("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.In("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.Le("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.LeAll("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.LeSome("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.Lt("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.LtAll("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.LtSome("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.Ne("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.NotExists(dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.NotIn("Gavin King", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyEq("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyEqAll("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyGe("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyGeAll("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyGeSome("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyGt("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyGtAll("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyGtSome("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyIn("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyLe("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyLeAll("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyLeSome("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyLt("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyLtAll("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyLtSome("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyNe("Name", dc);
            NHAssert.IsSerializable(c);
            c = Subqueries.PropertyNotIn("Name", dc);
            NHAssert.IsSerializable(c);
        }
Beispiel #37
0
 /// <summary>
 ///  Get a list of Media in the Library using the specified criteria.
 /// </summary>
 public virtual IList<Media> GetMediaList(DetachedCriteria mediaCriteria)
 {
     return
         DomainRegistry.Repository.CreateQuery(mediaCriteria)
             .List<Media>();
 }
    protected void btnConfirm_Click(object sender, EventArgs e)
    {
        string partyCode = this.tbPartyCode.Text != string.Empty ? this.tbPartyCode.Text.Trim() : string.Empty;
        string receiver  = this.tbReceiver.Text != string.Empty ? this.tbReceiver.Text.Trim() : string.Empty;
        string startDate = this.tbStartDate.Text != string.Empty ? this.tbStartDate.Text.Trim() : string.Empty;
        string endDate   = this.tbEndDate.Text != string.Empty ? this.tbEndDate.Text.Trim() : string.Empty;
        string itemCode  = this.tbItemCode.Text != string.Empty ? this.tbItemCode.Text.Trim() : string.Empty;
        string currency  = this.tbCurrency.Text != string.Empty ? this.tbCurrency.Text.Trim() : string.Empty;

        DateTime?effDateFrom = null;

        if (startDate != string.Empty)
        {
            effDateFrom = DateTime.Parse(startDate);
        }

        DateTime?effDateTo = null;

        if (endDate != string.Empty)
        {
            effDateTo = DateTime.Parse(endDate).AddDays(1).AddMilliseconds(-1);
        }

        //重新计价
        bool needRecalculate = bool.Parse(TheEntityPreferenceMgr.LoadEntityPreference(BusinessConstants.ENTITY_PREFERENCE_CODE_RECALCULATE_WHEN_BILL).Value);

        if (needRecalculate)
        {
            IList <ActingBill> allactingBillList = TheActingBillMgr.GetActingBill(partyCode, receiver, effDateFrom, effDateTo, itemCode, currency, this.ModuleType, null, true);

            TheActingBillMgr.RecalculatePrice(allactingBillList, this.CurrentUser);
        }

        IList <ActingBill> actingBillList = TheActingBillMgr.GetActingBill(partyCode, receiver, effDateFrom, effDateTo, itemCode, currency, this.ModuleType, null);



        if (actingBillList != null && actingBillList.Count > 0)
        {
            foreach (ActingBill actingBill in actingBillList)
            {
                actingBill.CurrentBillQty = actingBill.BillQty - actingBill.BilledQty;
                decimal orgAmount = actingBill.UnitPrice * actingBill.CurrentBillQty;
                actingBill.CurrentDiscount = orgAmount - (actingBill.BillAmount - actingBill.BilledAmount);
            }

            IList <Bill> billList = this.TheBillMgr.CreateBill(actingBillList, this.CurrentUser, (this.IsRelease.Checked ? BusinessConstants.CODE_MASTER_STATUS_VALUE_SUBMIT : BusinessConstants.CODE_MASTER_STATUS_VALUE_CREATE));
            ;

            DetachedCriteria selectCriteria      = DetachedCriteria.For(typeof(Bill));
            DetachedCriteria selectCountCriteria = DetachedCriteria.For(typeof(Bill))
                                                   .SetProjection(Projections.Count("BillNo"));

            selectCriteria.Add(Expression.Eq("CreateDate", billList[0].CreateDate));
            selectCriteria.Add(Expression.Eq("CreateUser.Code", this.CurrentUser.Code));
            selectCountCriteria.Add(Expression.Eq("CreateDate", billList[0].CreateDate));
            selectCountCriteria.Add(Expression.Eq("CreateUser.Code", this.CurrentUser.Code));

            SearchEvent((new object[] { selectCriteria, selectCountCriteria }), null);

            this.ShowSuccessMessage("MasterData.Bill.BatchCreateSuccessfully");
        }
        else
        {
            this.ShowErrorMessage("Bill.Error.EmptyBillDetail");
        }
    }
Beispiel #39
0
 /// <summary>
 /// Loads all the entities that match the criteria
 /// by order
 /// </summary>
 /// <param name="criteria">the criteria to look for</param>
 /// <param name="orders"> the order to load the entities</param>
 /// <returns>All the entities that match the criteria</returns>
 public ICollection <T> FindAll <T>(DetachedCriteria criteria, params Order[] orders)
 {
     return(internalRepository.FindAll <T>(criteria, orders));
 }
Beispiel #40
0
 /// <summary>
 /// Gets Total no. of Rows By Detached Criteria
 /// </summary>
 /// <param name="criteria">Detached Criteria to Check</param>
 /// <param name="orders">Order </param>
 /// <returns>No Of Rows Matches the Detached Criteria</returns>
 public int GetCount(DetachedCriteria criteria, params Order[] orders)
 {
     return(internalRepository.GetCount(criteria, orders));
 }
Beispiel #41
0
 /// <summary>
 /// Exceutes the query for projection or aggregation  and returns the result as object collection
 /// </summary>
 /// <param name="criteria">the cirteria to look for</param>
 /// <param name="firstResult">the first result to load</param>
 /// <param name="maxResults">the number of result to load</param>
 /// <returns>Objectcollection of particular type </returns>
 public ICollection <U> GetProjectedResultArray <U>(DetachedCriteria criteria, int firstResult, int maxResult)
 {
     return(internalRepository.GetProjectedResultArray <U>(criteria, firstResult, maxResult));
 }
Beispiel #42
0
 public static DetachedCriteria SetFetchMode <T>(this DetachedCriteria criteria, Expression <Func <T, object> > expression, FetchMode fetchmode)
 {
     return(criteria.SetFetchMode(Clr <T> .Name(expression), fetchmode));
 }
Beispiel #43
0
 public IList <T> FindAll <T>(DetachedCriteria criteria)
 {
     return(queryDao.FindAll <T>(criteria));
 }
Beispiel #44
0
 /// <summary>
 /// Loads all the entities that match the criteria
 /// by order
 /// </summary>
 /// <param name="criteria">the criteria to look for</param>
 /// <param name="orders"> the order to load the entities</param>
 /// <param name="firstResult">the first result to load</param>
 /// <param name="maxResults">the number of result to load</param>
 /// <returns>All the entities that match the criteria</returns>
 public ICollection <T> FindAll <T>(DetachedCriteria criteria,
                                    int firstResult, int maxResults,
                                    params Order[] orders)
 {
     return(internalRepository.FindAll <T>(criteria, firstResult, maxResults, orders));
 }
Beispiel #45
0
 /// <summary>
 /// Gets Total no. of Rows By Detached Criteria
 /// </summary>
 /// <param name="criteria">Detached Criteria to Check</param>
 /// <param name="orders">Order </param>
 /// <returns>No Of Rows Matches the Detached Criteria</returns>
 public int GetCount(DetachedCriteria criteria, bool isDistinctRequired)
 {
     return(internalRepository.GetCount(criteria, isDistinctRequired));
 }
 public IMultiCriteria Add(DetachedCriteria detachedCriteria)
 {
     return(Add <object>(detachedCriteria));
 }
Beispiel #47
0
 /// <summary>
 /// Creates the criteria.
 /// </summary>
 /// <typeparam name="T">Type creating criteria for.</typeparam>
 /// <param name="criteria">The criteria.</param>
 /// <param name="associationPropertyExpression">The association property expression.</param>
 /// <param name="joinType">Type of the join.</param>
 /// <returns>A <see cref="DetachedCriteria"/></returns>
 public static DetachedCriteria CreateCriteria <T>(
     this DetachedCriteria criteria, Expression <Func <T, object> > associationPropertyExpression, JoinType joinType)
 {
     return(CreateCriteria <T, object>(criteria, associationPropertyExpression, joinType));
 }
Beispiel #48
0
 /// <summary>
 /// Stateless Session 을 이용하여, <typeparamref name="T"/>의 엔티티들을 모두 조회합니다.
 /// </summary>
 /// <typeparam name="T">조회할 엔티티의 수형</typeparam>
 public static IList <T> FindAllStateless <T>() where T : IDataObject
 {
     return(FindAllStateless <T>(DetachedCriteria.For <T>(), UnitOfWork.CurrentSession));
 }
Beispiel #49
0
        public async Task MultiplePagingParametersInSingleQueryAsync()
        {
            if (!Dialect.SupportsSubSelectsWithPagingAsInPredicateRhs)
            {
                Assert.Ignore("Current dialect does not support paging within IN sub-queries");
            }

            using (var session = OpenSession())
                using (var transaction = session.BeginTransaction())
                {
                    await(session.SaveAsync(new Foo()
                    {
                        Ord = 0, Name = "00"
                    }));
                    await(session.SaveAsync(new Foo()
                    {
                        Ord = 1, Name = "10"
                    }));
                    await(session.SaveAsync(new Foo()
                    {
                        Ord = 2, Name = "10"
                    }));
                    await(session.SaveAsync(new Foo()
                    {
                        Ord = 3, Name = "11"
                    }));
                    await(session.SaveAsync(new Foo()
                    {
                        Ord = 4, Name = "10"
                    }));
                    await(session.SaveAsync(new Foo()
                    {
                        Ord = 5, Name = "10"
                    }));
                    await(session.SaveAsync(new Foo()
                    {
                        Ord = 6, Name = "10"
                    }));
                    await(session.SaveAsync(new Foo()
                    {
                        Ord = 7, Name = "10"
                    }));
                    await(session.SaveAsync(new Foo()
                    {
                        Ord = 8, Name = "10"
                    }));
                    await(session.SaveAsync(new Foo()
                    {
                        Ord = 9, Name = "10"
                    }));

                    // returns 2, 3, 4, 5, 6, 7, 8
                    DetachedCriteria pagedSubquery =
                        DetachedCriteria.For <Foo>()
                        .Add(Restrictions.Like("Name", "1%"))
                        .AddOrder(Order.Asc("Ord"))
                        .SetFirstResult(1)
                        .SetMaxResults(7)
                        .SetProjection(Projections.Property("Id"));

                    var query =
                        session.CreateCriteria <Foo>()
                        .Add(Subqueries.PropertyIn("Id", pagedSubquery))
                        .Add(Restrictions.Like("Name", "%0"))                         // excludes 3
                        .AddOrder(Order.Asc("Ord"))
                        .SetFirstResult(2)
                        .SetMaxResults(3);

                    var list = await(query.ListAsync <Foo>());

                    Assert.That(list.Count, Is.EqualTo(3));
                    Assert.That(list[0].Ord, Is.EqualTo(5));
                    Assert.That(list[1].Ord, Is.EqualTo(6));
                    Assert.That(list[2].Ord, Is.EqualTo(7));
                }
        }
		public ARPaginableCriteria(Type targetType, DetachedCriteria detachedCriteria) : this(targetType, null, (ICriterion[])null)
		{
			this.detachedCriteria = detachedCriteria;
		}
Beispiel #51
0
 /// <summary>
 /// Stateless Session 을 이용하여, <paramref name="criteria"/>에 해당하는 Entity를 조회합니다.
 /// </summary>
 public static IList <T> FindAllStateless <T>(this DetachedCriteria criteria) where T : IDataObject
 {
     return(FindAllStateless <T>(criteria, UnitOfWork.CurrentSession));
 }
 /// <summary>
 /// Returns all instances found for the specified type according to the criteria
 /// </summary>
 public static Array FindAll(Type targetType, DetachedCriteria detachedCriteria, params Order[] orders)
 {
     return ActiveRecordBase.FindAll(targetType, detachedCriteria, orders);
 }
Beispiel #53
0
 /// <summary>
 /// <paramref name="criteria"/>에 해당하는 엔티티가 존재하는지 검사합니다. 하나라도 있으면 True, 없으면 False
 /// </summary>
 public static bool ExistsStateless <T>(this DetachedCriteria criteria) where T : IDataObject
 {
     return(ExistsStateless <T>(criteria, UnitOfWork.CurrentSession));
 }
 /// <summary>
 /// Searches and returns a row. If more than one is found,
 /// throws <see cref="ActiveRecordException"/>
 /// </summary>
 /// <param name="targetType">The target type</param>
 /// <param name="criteria">The criteria</param>
 /// <returns>A <c>targetType</c> instance or <c>null</c></returns>
 public static object FindOne(Type targetType, DetachedCriteria criteria)
 {
     return ActiveRecordBase.FindOne(targetType, criteria);
 }
 protected void AssertCriteriaAreEqual(DetachedCriteria expected, DetachedCriteria actual)
 {
     AssertObjectsAreEqual(expected, actual);
 }
 /// <summary>
 /// Returns the number of records of the specified
 /// type in the database
 /// </summary>
 /// <param name="targetType">The target type.</param>
 /// <param name="detachedCriteria">The criteria expression</param>
 /// <returns>The count result</returns>
 public static int Count(Type targetType, DetachedCriteria detachedCriteria)
 {
     return ActiveRecordBase.Count(targetType, detachedCriteria);
 }
        protected void AssertCriteriaAreEqual <T>(DetachedCriteria expected, QueryOver <T> actual)
        {
            DetachedCriteria actualDetached = ToDetachedCriteria(actual);

            AssertObjectsAreEqual(expected, actualDetached);
        }
		internal SimpleSubqueryExpression(Object value, String op, String quantifier, DetachedCriteria dc)
			: base(op, quantifier, dc)

		{
			this.value = value;
		}
Beispiel #59
0
 public static DetachedCriteria CreateCriteria <T>(this DetachedCriteria criteria, Expression <Func <T, object> > expression)
 {
     return(criteria.CreateCriteria(Clr <T> .Name(expression)));
 }
    void Search_Render(object sender, EventArgs e)
    {

        this.ucList.Visible = true;
        this.Criteria = (DetachedCriteria)sender;
        this.ucList.BindDataSource(this.Criteria);
    }