protected virtual ICriteria BuildCriteria(ISession session) { if (cachedCriteria == null) { if (detachedCriteria != null) { cachedCriteria = detachedCriteria.GetExecutableCriteria(session); } else { cachedCriteria = session.CreateCriteria(targetType); if (criterions != null) { foreach (var queryCriteria in criterions) { cachedCriteria.Add(queryCriteria); } } } if (orders != null) { foreach (var order in orders) { cachedCriteria.AddOrder(order); } } } return cachedCriteria; }
private static void AppendStringPropertyCriteriaTo( ICriteria criteria, PropertyInfo signatureProperty, object propertyValue) { criteria.Add( propertyValue != null ? Restrictions.InsensitiveLike(signatureProperty.Name, propertyValue.ToString(), MatchMode.Exact) : Restrictions.IsNull(signatureProperty.Name)); }
private static void AppendEntityCriteriaTo( ICriteria criteria, PropertyInfo signatureProperty, object propertyValue) { criteria.Add( propertyValue != null ? Restrictions.Eq(signatureProperty.Name + ".Id", ((IEntity)propertyValue).Id) : Restrictions.IsNull(signatureProperty.Name + ".Id")); }
/// <summary> /// Adiciona uma Expressão ao ICriteria /// </summary> /// <param name="type">Tipo da Entidade do ICriteria</param> /// <param name="criteria">ICriteria</param> /// <param name="propriedade">Nome da Property do Tipo</param> /// <param name="expressao">Expressão do ICriteria</param> /// <param name="valor">Valor para Comparação</param> private void AddExpressionToCriteria(Type type, ICriteria criteria, string propriedade, int expressao, object valor) { //Converte o valor object no tipo da Property usando Reflection a partir do Type object value = Convert.ChangeType(valor, type.GetProperty(propriedade).PropertyType); //Adiciona a Expression no Criteria switch (expressao) { case 0: criteria.Add(Expression.Eq(propriedade, value)); break; case 1: criteria.Add(Expression.Not(Expression.Eq(propriedade, value))); break; case 2: criteria.Add(Expression.Gt(propriedade, value)); break; case 3: criteria.Add(Expression.Ge(propriedade, value)); break; case 4: criteria.Add(Expression.Lt(propriedade, value)); break; case 5: criteria.Add(Expression.Le(propriedade, value)); break; case 6: criteria.Add(Expression.Like(propriedade, value)); break; } }
/// <summary> /// Adds a collection of ICriterion to an ICriteria. /// </summary> /// <param name="criteria">The ICriteria that will be modified.</param> /// <param name="criterions">The collection of Criterion.</param> internal static void AddCriterionToCriteria(ICriteria criteria, ICriterion[] criterions) { if (criterions != null) { foreach (ICriterion cond in criterions) { criteria.Add(cond); } } }
private static void AddWordRestrictions(string query, ICriteria criteria) { query.Split(' ').ForEach(word => criteria.Add( Restrictions.Or( Restrictions.InsensitiveLike("Title", word, MatchMode.Anywhere), Restrictions.Or( Restrictions.InsensitiveLike("ShortDescription", word, MatchMode.Anywhere), Restrictions.InsensitiveLike("LongDescription", word, MatchMode.Anywhere)) ))); }
public static ICriteria SetSearchCriteria(object obj, ICriteria c) { Type t = obj.GetType(); string strTemp; foreach (PropertyInfo p in t.GetProperties()) { if (p.GetValue(obj, null) == null) continue; strTemp = p.GetValue(obj, null).ToString(); if (strTemp != "") c.Add(Expression.Eq(p.Name, p.GetValue(obj, null))); } return c; }
public ICriteria ConstructCriteria(bool matchAllCriteria, ICriteria criteria, params AbstractCriterion[] criterias) { if (matchAllCriteria) { var conjunction = Restrictions.Conjunction(); foreach (var t in criterias.Where(t => t != null)) { conjunction.Add(t); } criteria.Add(conjunction); } else { var disjunction = Restrictions.Disjunction(); foreach (var t in criterias.Where(t => t != null)) { disjunction.Add(t); } criteria.Add(disjunction); } return criteria; }
public List <Recensione> GetRecensioniScritte(string username) { List <Recensione> recensioni = null; try { if (username == null) { throw new ArgumentException("Username nullo"); } ISession sessione = GetConnection(); sessione.BeginTransaction(); List <Recensione> recensioniRicevute = null; ICriteria criteria = sessione.CreateCriteria <Recensione>(); recensioniRicevute = (List <Recensione>)criteria.Add(Expression.Like("Username", username)).List <Recensione>(); sessione.Transaction.Commit(); sessione.Transaction.Dispose(); recensioni = new List <Recensione>(); foreach (Recensione r in recensioniRicevute) { Libro temp = new Libro { Anno = r.Libro.Anno, Autore = r.Libro.Autore, FilePath = r.Libro.FilePath, Gen = r.Libro.Gen, Titolo = r.Libro.Titolo }; Recensione recTemp = new Recensione() { Punteggio = r.Punteggio, Libro = temp, Commento = r.Commento, Username = r.Username, Id = r.Id }; recensioni.Add(recTemp); } RegisterOperazione("get recensioni salvate", username); return(recensioni); } catch (Exception e) { throw new FaultException <BookFault>(new BookFault(e.Message)); } }
private void LoadIndexes() { if ((_Indexes == null) || (_Indexes.Count == 0)) { IRepository <IIndexDefinition> rep = EntityFactory.GetRepository <IIndexDefinition>(); IQueryable qry = (IQueryable)rep; IExpressionFactory ef = qry.GetExpressionFactory(); ICriteria crit = qry.CreateCriteria(); IExpression accessExp = ef.Le("UserAccess", _UserType); crit.Add(ef.And(accessExp, ef.Eq("Enabled", true))); crit.AddOrder(ef.Asc("IndexName")); IList <IIndexDefinition> tempIndexes = crit.List <IIndexDefinition>(); Assembly interfaceAsm = Assembly.GetAssembly(typeof(IIndexDefinition)); Type[] types = interfaceAsm.GetTypes(); _TablesEntities = new Dictionary <string, Type>(); foreach (Type entity in types) { AttributeCollection attrs = TypeDescriptor.GetAttributes(entity); foreach (Attribute attr in attrs) { ActiveRecordAttribute activeRecord = attr as ActiveRecordAttribute; if (activeRecord != null) { _TablesEntities.Add(activeRecord.Table.ToUpper(), entity); } } } _Indexes = new List <IIndexDefinition>(); foreach (IIndexDefinition index in tempIndexes) { if (index.Type == 1) // database index { DBIndexDefinition dbid = DBIndexDefinition.SetFromString(index.MetaData); if (_TablesEntities.ContainsKey(dbid.MainTable.ToUpper())) { _Indexes.Add(index); } } else { _Indexes.Add(index); } } } }
/// <summary> /// Lấy về price config theo trip, room type và room class /// </summary> /// <param name="trip"></param> /// <param name="type"></param> /// <param name="roomClass"></param> /// <param name="option"></param> /// <returns></returns> public SailsPriceConfig SailsPriceConfigGetBy_RoomType_RoomClass_Trip(SailsTrip trip, RoomTypex type, RoomClass roomClass, TripOption option) { ICriteria criteria = _session.OpenSession().CreateCriteria(typeof(SailsPriceConfig)); criteria.Add(Expression.Eq("Trip", trip)) .Add(Expression.Eq("RoomType", type)) .Add(Expression.Eq("RoomClass", roomClass)) .Add(Expression.Eq("TripOption", option)); criteria.AddOrder(new Order("Id", false)); IList result = criteria.List(); if (result.Count > 0) { return(result[0] as SailsPriceConfig); } return(null); }
public void SingleCriteriaQueriesWithStringsShouldExecuteCorrectly() { // Test querying StringData using (ISession session = this.OpenSession()) { ICriteria criteriaWithPagination = session.CreateCriteria <DomainClass>(); criteriaWithPagination.Add(Expression.Like("StringData", "%Doe%")); ICriteria criteriaWithRowCount = CriteriaTransformer.Clone(criteriaWithPagination); criteriaWithPagination.SetFirstResult(0).SetMaxResults(1); criteriaWithRowCount.SetProjection(Projections.RowCountInt64()); IList <DomainClass> list = criteriaWithPagination.List <DomainClass>(); Assert.AreEqual(2, criteriaWithRowCount.UniqueResult <long>()); Assert.AreEqual(1, list.Count); } }
public async Task SingleCriteriaQueriesWithIntsShouldExecuteCorrectlyAsync() { // Test querying IntData using (ISession session = this.OpenSession()) { ICriteria criteriaWithPagination = session.CreateCriteria <DomainClass>(); criteriaWithPagination.Add(Expression.Le("IntData", 2)); ICriteria criteriaWithRowCount = CriteriaTransformer.Clone(criteriaWithPagination); criteriaWithPagination.SetFirstResult(0).SetMaxResults(1); criteriaWithRowCount.SetProjection(Projections.RowCountInt64()); IList <DomainClass> list = await(criteriaWithPagination.ListAsync <DomainClass>()); Assert.AreEqual(2, await(criteriaWithRowCount.UniqueResultAsync <long>())); Assert.AreEqual(1, list.Count); } }
public virtual IList <T> FindAll <T>(ICriterion[] criterias, Order[] sortItems, int firstRow, int maxRows) { using (ISession session = GetSession()) { try { ICriteria criteria = session.CreateCriteria(typeof(T)); 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 <T> result = criteria.List <T>(); if (result == null || result.Count == 0) { return(null); } return(result); } catch (Exception ex) { throw new DataException("Could not perform FindAll for " + typeof(T).Name, ex); } } }
public double GetKasaGelirGiderBySubeKoduAndKasaKodu(string subeKodu, string kasaKodu, KasaGelirGider gelirGider) { double res = 0; string strGelirGider = gelirGider == KasaGelirGider.Gelir ? "G" : "C"; ICriteria criter = Session.CreateCriteria <KasaHareket>().SetProjection(Projections.Sum("Tutar")) .Add(Expression.Eq("GelirGider", strGelirGider)).CreateCriteria("Kasa").Add(Expression.Eq("Id", kasaKodu)); ICriteria subeCriteria = criter.CreateCriteria("Sube"); subeCriteria.Add(NHibernate.Criterion.Expression.Eq("Id", subeKodu)); object obj = criter.UniqueResult(); if (obj != null) { res = Convert.ToDouble(obj); } return(res); }
public void updatePassword(string Sn, string Password) { object o = null; using (ISession session = getSession()) { ICriteria c = session.CreateCriteria(typeof(Student)); c.Add(Restrictions.Eq("Sn", Sn)); o = c.UniqueResult(); } if (o != null) { Student s = (Student)o; s.Password = Password; save(s); } }
// public static void AddCaching(ICriteria crit) // { // if (With.Caching.ShouldForceCacheRefresh == false && // With.Caching.Enabled) // { // crit.SetCacheable(true); // if (With.Caching.CurrentCacheRegion != null) // crit.SetCacheRegion(With.Caching.CurrentCacheRegion); // } // } public static ICriteria CreateCriteriaFromArray(ISession session, ICriterion[] criteria) { ICriteria crit = session.CreateCriteria(typeof(T)); foreach (ICriterion criterion in criteria) { //allow some fancy antics like returning possible return // or null to ignore the criteria if (criterion == null) { continue; } crit.Add(criterion); } //AddCaching(crit); return(crit); }
void UpdateCreteria() { IsFiltred = false; if (BaseCriteria == null) { return; } FiltredCriteria = (ICriteria)BaseCriteria.Clone(); if (!checkShowDeleted.Active) { FiltredCriteria.Add(Restrictions.Eq("Deleted", false)); IsFiltred = true; } OnRefiltered(); }
/// <summary> /// Search for articles with the specified filters. /// The filters are aggregated with an AND expression. /// </summary> /// <param name="categoryName"></param> /// <param name="searchFor"></param> /// <param name="author"></param> /// <param name="owner"></param> /// <param name="tag"></param> /// <param name="fromDate"></param> /// <param name="toDate"></param> /// <param name="status"></param> /// <param name="paging"></param> /// <returns></returns> public IList <Article> FindByFields(Filter <string> categoryName, Filter <string> searchFor, Filter <string> author, Filter <string> owner, Filter <string> tag, DateTime?fromDate, DateTime?toDate, ArticleStatus status, PagingInfo paging) { ICriteria criteria = CreateCriteria(); if (author != null) { criteria.Add(author.ToCriterion("Author")); } if (owner != null) { criteria.Add(owner.ToCriterion("Owner")); } if (tag != null) { criteria.Add(tag.ToCriterion("Tag")); } if (searchFor != null) { criteria.Add(Expression.Or(searchFor.ToCriterion("Body"), searchFor.ToCriterion("Title"))); } if (fromDate != null) { criteria.Add(Expression.Ge("UpdateDate", fromDate)); } if (toDate != null) { criteria.Add(Expression.Le("UpdateDate", toDate)); } if (categoryName != null) { ICriteria categoryCriteria = criteria.CreateCriteria("Category"); categoryCriteria.Add(categoryName.ToCriterion("Name")); } AddCriteriaForStatus(criteria, status); criteria.AddOrder(Order.Desc("UpdateDate")); return(Find(criteria, paging, false)); }
/// <summary> /// Load persisted objects from region storage. /// </summary> /// <param name="regionUUID">The region UUID</param> /// <returns>List of loaded groups</returns> public List <SceneObjectGroup> LoadObjects(UUID regionUUID) { Dictionary <UUID, SceneObjectGroup> SOG = new Dictionary <UUID, SceneObjectGroup>(); List <SceneObjectGroup> ret = new List <SceneObjectGroup>(); ICriteria criteria = manager.GetSession().CreateCriteria(typeof(SceneObjectPart)); criteria.Add(Expression.Eq("RegionID", regionUUID)); criteria.AddOrder(Order.Asc("ParentID")); criteria.AddOrder(Order.Asc("LinkNum")); foreach (SceneObjectPart p in criteria.List()) { // root part if (p.UUID == p.ParentUUID) { SceneObjectGroup group = new SceneObjectGroup(); group.SetRootPart(p); SOG.Add(p.ParentUUID, group); } else { SOG[p.ParentUUID].AddPart(p); } // get the inventory ICriteria InvCriteria = manager.GetSession().CreateCriteria(typeof(TaskInventoryItem)); InvCriteria.Add(Expression.Eq("ParentPartID", p.UUID)); IList <TaskInventoryItem> inventory = new List <TaskInventoryItem>(); foreach (TaskInventoryItem i in InvCriteria.List()) { inventory.Add(i); } if (inventory.Count > 0) { p.Inventory.RestoreInventoryItems(inventory); } } foreach (SceneObjectGroup g in SOG.Values) { ret.Add(g); } return(ret); }
/// <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); } } }
public string VerificaCredenziali(string username, string password) { string ruolo = null; if (String.IsNullOrEmpty(username)) { throw new ArgumentException("Username nullo"); } if (String.IsNullOrEmpty(password)) { throw new ArgumentException("Password nulla"); } if (username.Length < 3) { throw new ArgumentException("Lunghezza minima username: 3 caratteri"); } if (password.Length < 10) { throw new ArgumentException("Lunghezza minima password: 10 caratteri"); } try { ISession sessione = GetConnection(); sessione.BeginTransaction(); List <Iscritto> res = null; ICriteria criteria = sessione.CreateCriteria <Iscritto>(); res = (List <Iscritto>)criteria.Add(Expression.Like("Username", username)).Add(Expression.Like("Password", password)).List <Iscritto>(); sessione.Transaction.Commit(); sessione.Transaction.Dispose(); if (res.Count == 1) { ruolo = res[0].Ruolo; } PrintAccesso("login", username); } catch (Exception e) { throw new ArgumentException("Credenziali non valide: " + e.ToString()); } return(ruolo); }
//access_token=2.00R9OGxBLdkETB0b080b9ec3l6bsME&expires_in=86400&uid=1789422193 public ActionResult WeiboAuthResponse(string uid) { if (string.IsNullOrEmpty(uid)) { return(View()); } if (this.getAuthMember() != null) { MemberModel m = BaseZdBiz.Load <MemberModel>(this.getAuthMember().id); m.weiboUid = uid; JsResultObject re = BaseZdBiz.Update(m, ""); if (re.code == JsResultObject.CODE_SUCCESS) { this.SetResult(JsResultObject.CODE_ALERT, string.Format("当前帐号已和你的微博帐号:{0}已绑定成功,以后可以直接使用新浪微博进行登录", uid), true); WebUtil.SetSessionAttr(typeof(MemberModel).Name, m); } else { this.SetResult(JsResultObject.CODE_ALERT, string.Format("当前帐号已和你的微博帐号:{0}已绑定失败,可能已有相同的微博帐号与其他帐号绑定了", uid), true); } return(RedirectToAction("Edit", "Account")); } ICriteria icr = BaseZdBiz.CreateCriteria <MemberModel>(); icr.Add(Restrictions.Eq("weiboUid", uid)); IList <MemberModel> members = icr.List <MemberModel>(); if (members.Count == 1) { MemberModel member = members[0]; member.pwd = ""; WebUtil.SetSessionAttr(typeof(MemberModel).Name, members[0]); return(Redirect(this.getPreUrl())); } else { this.SetResult(JsResultObject.CODE_ALERT, string.Format("你的微博帐号:{0}已绑定成功,请保完以下基本资料完成登陆", uid), true); MemberModel member = new MemberModel(); member.weiboUid = uid; ViewData[typeof(MemberModel).Name] = member; return(View("Index")); //return Redirect(WebUtil.GetWebRootPath()+"/MemberAdmin/Reg/Index"); } }
public static IList GetTradeData() { ISession session = SessionFactory.OpenSession(); IList tradeData = null; try { ICriteria criteria = session.CreateCriteria(typeof(SummaryData)); criteria.Add(Expression.Eq("FinalApprovalFlag", "N")); tradeData = criteria.List(); return(tradeData); } catch (Exception e) { throw new Exception("An error occurred while retrieving a list of Trade Data." + Environment.NewLine + "Error CNF-372 in " + PROJ_FILE_NAME + ".GetTradeData(): " + e.Message); } }
/// <summary> /// Retrieves objects of a specified type where a specified property equals a specified value. /// </summary> /// <typeparam name="T">The type of the objects to be retrieved.</typeparam> /// <param name="propertyName">The name of the property to be tested.</param> /// <param name="propertyValue">The value that the named property must hold.</param> /// <returns>A list of all objects meeting the specified criteria.</returns> public IList <T> GetEquals <T>(string propertyName, object propertyValue) { ISession session = _sessionFactory.GetCurrentSession(); session.CacheMode = CacheMode.Ignore; session.FlushMode = FlushMode.Commit; // Create a criteria object with the specified criteria ICriteria criteria = session.CreateCriteria(typeof(T)); criteria.Add(Expression.Eq(propertyName, propertyValue)); // Get the matching objects IList <T> matchingObjects = criteria.List <T>(); // Set return value return(matchingObjects); }
public bool HaveCategory(CategoryBase cb) { ICriteria crit = GetCriteria(); if (cb != null) { crit.Add(Expression.Eq("CategoryBase", cb)); } if (crit.List <PriceCalculation>().Count > 0) { return(true); } else { return(false); } }
public int CountObjet <T>(ICriterion criterion) { using (var session = _commonDao.OpenSession()) { ICriteria criteria = session.CreateCriteria(typeof(T)); criteria.Add(criterion); criteria.SetProjection(Projections.RowCount()); var list = criteria.List(); if (list.Count > 0 && list[0] != null) { return((int)list[0]); } return(0); } }
/// <summary> /// Retrieves the object from database using the provided id as the lookup. /// </summary> /// <param name="id">The id to search with (the primary key/id column)</param> /// <typeparam name="TKey">The type of the Id column</typeparam> /// <returns>The object (if found) otherwise null.</returns> public T Read <T, TKey>(TKey id) where T : class { ISession session = SessionFactory.OpenSession(); ICriteria criteria = session.CreateCriteria(typeof(T)); criteria.Add(Expression.Eq(IdName, id)); if (DisposeSessions) { var result = criteria.UniqueResult <T>(); session.Dispose(); return(result); } else { return(criteria.UniqueResult <T>()); } }
public virtual string[] SelecionarAutoComplete(string prefixText, int count) { ICriteria criteria = Sessao.CreateCriteria(this.GetType()). CreateAlias("Pessoa", "pes"); criteria.Add(Expression.Like("pes.Nome", prefixText, MatchMode.Anywhere).IgnoreCase()); criteria.SetMaxResults(count); criteria.AddOrder(Order.Asc("pes.Nome")); IList <Aluno> lista = criteria.List <Aluno>(); ArrayList resultado = new ArrayList(); foreach (Aluno aluno in lista) { resultado.Add(aluno.Pessoa.Nome); } return((string[])resultado.ToArray(typeof(string))); }
public List <SaleOrderItem> PendingSaleOrderQuantity(DateTime startdate) { ICriteria crit = GetCriteria(); crit.Add(new GtPropertyExpression("Quantity", "QuantityDelivery")); crit.CreateCriteria("SaleOrder").Add(new GeExpression("Date", startdate)); crit.SetProjection(Projections.ProjectionList() .Add(Projections.Sum("Quantity")) .Add(Projections.Avg("QuantityDelivery")) .Add(Projections.GroupProperty("Product")) ); crit.SetResultTransformer( new AliasToBeanConstructorResultTransformer(typeof(SaleOrderItem).GetConstructors()[2])); return(crit.List <SaleOrderItem>() as List <SaleOrderItem>); }
private void CriteriaAddOrganizationTreeRootParentIdCriterion(ICriteria criteria) { IList <object> rootParentIdValues = new object[] { "" }; if (rootParentIdValues.Count == 1) { NHibernateUtils.CriteriaAddCriterion(criteria, "Id.ParentId", rootParentIdValues[0]); } else { var j = Restrictions.Disjunction(); foreach (var pIdValue in rootParentIdValues) { NHibernateUtils.DisjunctionAddCriterion(j, "Id.ParentId", pIdValue); } criteria.Add(j); } }
public void AllowSingleCallSyntax() { ICriteria expected = CreateTestCriteria(typeof(Person)); expected.Add(Restrictions.IsNotEmpty("Children")); expected.AddOrder(Order.Asc("Name")); expected.SetFetchMode("PersonList", FetchMode.Eager); expected.SetLockMode(LockMode.UpgradeNoWait); IQueryOver <Person, Person> actual = CreateTestQueryOver <Person>(); actual.WhereRestrictionOn(p => p.Children).IsNotEmpty(); actual.OrderBy(p => p.Name).Asc(); actual.Fetch(p => p.PersonList).Eager(); actual.Lock().UpgradeNoWait(); AssertCriteriaAreEqual(expected, actual); }
/// <summary> /// Adds the chunk if not exists. /// </summary> /// <param name="session">The session.</param> /// <param name="chunk">The chunk.</param> /// <returns>True if the chunk already exists and this chunk is not /// inserted.</returns> public static bool AddChunkIfNotExists(IStatelessSession session, DataChunk chunk) { ICriteria crit = session.CreateCriteria(typeof(DataChunk)); ICriterion hashEq = Expression.Eq("Hash", chunk.Hash); crit.Add(hashEq); if ((DataChunk)crit.UniqueResult() == null) { // Save if no duplicate is found. session.Insert(chunk); return(false); } else { return(true); } }
public IList <T> FindByExample(T exampleInstance, params string[] excludeProperty) { try { ICriteria crit = Session.CreateCriteria(typeof(T)); Example example = Example.Create(exampleInstance); foreach (string exclude in excludeProperty) { example.ExcludeProperty(exclude); } crit.Add(example); return(crit.List <T>()); } catch (HibernateException ex) { throw new InfrastructureException(Strings.getFullDatabaseAccessExceptionMessage(ex), ex); } }
public T FindFirstByExample <T>(object propertiesAndValues) { var dictionary = GetPropertyInformation(propertiesAndValues); using (var session = SessionFactory.GetNewSession()) { ICriteria criteriaQuery = session.CreateCriteria(typeof(T)); foreach (var pair in dictionary) { ICriterion criterion = Expression.Eq(pair.Key, pair.Value); criteriaQuery.Add(criterion); } return(criteriaQuery.List <T>().SingleOrDefault()); } }
public int CountObject <T>(ICriterion criterion) { ISession session = _sessionManager.OpenSession(); ICriteria criteria = session.CreateCriteria(typeof(T)); criteria.SetProjection(Projections.RowCount()); if (criterion != null) { criteria.Add(criterion); } IList list = criteria.List(); if (list.Count > 0) { return((int)list[0]); } return(0); }
/// <summary> /// Create Criteria using <paramref name="odr"/> /// </summary> /// <param name="odr">can pass null</param> /// <param name="criterion"></param> /// <returns></returns> protected ICriteria CreateCriteria(Order odr, IEnumerable <ICriterion> criterion) { ICriteria retVal = CreateCriteria(); if (criterion != null) { foreach (ICriterion crit in criterion) { retVal.Add(crit); } } if (odr != null) { retVal.AddOrder(odr); } return(retVal); }
public Distributor GetByName(string name) { ICriteria crit = GetCriteria(); crit.Add(Expression.Eq("Name", name)); IList <Distributor> lst = crit.List <Distributor>(); if (lst.Count > 0) { new Exception("Existe mas de un distribuidor con ese nombre."); } else if (lst.Count == 0) { return(null); } return(lst[0]); }
public override void Apply(ICriteria criteria) { if (FeedId != 0) { criteria.Add(Expression.Eq("Feed.Id", FeedId)); } base.Apply(criteria); }
public void OnEvent(ICriteria crit) { crit.Add(criterion); }
private static void AppendValuePropertyCriteriaTo( ICriteria criteria, PropertyInfo signatureProperty, object propertyValue) { criteria.Add( propertyValue != null ? Restrictions.Eq(signatureProperty.Name, propertyValue) : Restrictions.IsNull(signatureProperty.Name)); }
private static void AddTimePeriodRestrictions(TimePeriod period, ICriteria criteria) { criteria .Add(Restrictions.Eq("Year", period.Year)) .Add(Restrictions.Eq("YearRange", period.YearRange)) .Add(Restrictions.Eq("Quarter", period.Quarter)) .Add(Restrictions.Eq("Month", period.Month)); }
public virtual IEnumerable<Item> GetContents(ICriteria c) { return c.Add(Expression.Eq("Container", this)).List<Item>(); }
private static void GetFilterCriteria(ICriteria cr, Dictionary<string, object> filters) { string employee = Convert.ToString(filters["employee"]); string username = Convert.ToString(filters["username"]); int role = (int)filters["role"]; int status = (int)filters["status"]; bool statusVal = status == 1 ? true : false; if (!string.IsNullOrEmpty(username)) cr.Add(Restrictions.InsensitiveLike("user.Username", username, MatchMode.Anywhere)); if (role != 0) cr.Add(Restrictions.Eq("user.Role", role)); if (status != 0) cr.Add(Restrictions.Eq("user.Status", statusVal)); if (!string.IsNullOrEmpty(employee)) { cr = cr.CreateCriteria("user.Employee", "e", JoinType.InnerJoin); AbstractCriterion a1 = Restrictions.InsensitiveLike("e.Firstname", employee, MatchMode.Anywhere); AbstractCriterion a2 = Restrictions.InsensitiveLike("e.Middlename", employee, MatchMode.Anywhere); AbstractCriterion a3 = Restrictions.InsensitiveLike("e.Lastname", employee, MatchMode.Anywhere); AbstractCriterion b1 = Restrictions.Or(a1, a2); AbstractCriterion b2 = Restrictions.Or(b1, a3); cr.Add(b2); } }
private void AppendSignaturePropertyCriteriaTo(ICriteria criteria, IEntity entity) { foreach (var signatureProperty in entity.GetSignatureProperties()) { var propertyType = signatureProperty.PropertyType; var propertyValue = signatureProperty.GetValue(entity, null); if (propertyType.IsEnum) { criteria.Add(Restrictions.Eq(signatureProperty.Name, (int)propertyValue)); } else if ( propertyType.GetInterfaces().Any( x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEntity))) { AppendEntityCriteriaTo(criteria, signatureProperty, propertyValue); } else if (propertyType == typeof(DateTime)) { this.AppendDateTimePropertyCriteriaTo(criteria, signatureProperty, propertyValue); } else if (propertyType == typeof(string)) { AppendStringPropertyCriteriaTo(criteria, signatureProperty, propertyValue); } else if (propertyType.IsValueType) { AppendValuePropertyCriteriaTo(criteria, signatureProperty, propertyValue); } else { throw new ApplicationException( "Can't determine how to use " + entity.GetType() + "." + signatureProperty.Name + " when looking for duplicate entries. To remedy this, " + "you can create a custom validator or report an issue to the S#arp Architecture " + "project, detailing the type that you'd like to be accommodated."); } } }
private void AppendDateTimePropertyCriteriaTo( ICriteria criteria, PropertyInfo signatureProperty, object propertyValue) { criteria.Add( (DateTime)propertyValue > this.uninitializedDatetime ? Restrictions.Eq(signatureProperty.Name, propertyValue) : Restrictions.IsNull(signatureProperty.Name)); }
public override void AddToCriteria(ICriteria criteria) { criteria.Add(GetCriterion()); }
/// <summary> /// Gets the filter expressions. /// </summary> /// <param name="expressions">The expressions.</param> /// <returns></returns> private ICriteria GetExpressions(ICriteria criteria, IExpressionFactory expressions) { if (chkLeadSource.Checked) criteria.Add(expressions.Eq("response.LeadSource", lbxLeadSource.SelectedItem.Text.ToString())); if (chkMethod.Checked) criteria.Add(expressions.Eq("response.ResponseMethod", lbxMethods.SelectedItem.Text)); if (chkStage.Checked) criteria.Add(expressions.Eq("response.Stage", lbxStage.SelectedItem.Text)); return criteria; }
private static void GetFilterCriteria(ICriteria cr, Dictionary<string, object> filters) { int year = (int)filters["year"]; if (year != 0) cr.Add(Restrictions.Eq("ov.Year", year)); }
/// <summary> /// Called when [set filters] event is fired on the TargetViewDataSource object. /// </summary> /// <param name="criteria">The criteria.</param> /// <param name="expressions">The expressions.</param> protected void OnSetFilters(ICriteria criteria, IExpressionFactory expressions) { ICampaign campaign = GetParentEntity() as ICampaign; criteria.Add(expressions.Eq("Campaignid", campaign.Id.ToString())); if (!chkContacts.Checked && !chkLeads.Checked) criteria.Add(expressions.Eq("TargetType", "NONE")); if (chkContacts.Checked && !chkLeads.Checked) criteria.Add(expressions.Eq("TargetType", "Contact")); if (!chkContacts.Checked && chkLeads.Checked) criteria.Add(expressions.Eq("TargetType", "Lead")); if (chkPriority.Checked && lbxPriority.SelectedItem != null) criteria.Add(expressions.Eq("Priority", lbxPriority.SelectedItem.Text)); if (chkGroup.Checked && lbxGroups.SelectedItem != null) criteria.Add(expressions.Eq("GroupName", lbxGroups.SelectedItem.Text)); if (chkStatus.Checked && lbxStatus.SelectedItem != null) criteria.Add(expressions.Eq("Status", lbxStatus.SelectedItem.Text)); if (chkStage.Checked && lbxStages.SelectedItem != null) criteria.Add(expressions.Eq("Stage", lbxStages.SelectedItem.Text)); if (chkResponded.Checked) { criteria.Add(rdgResponded.SelectedIndex == 0 ? expressions.IsNotNull("ResponseDate") : expressions.IsNull("ResponseDate")); } }
private static void GetFilterCriteria(ICriteria cr, string keyword) { if (!string.IsNullOrEmpty(keyword)) cr.Add(Restrictions.InsensitiveLike("dept.Name", keyword, MatchMode.Anywhere)); }
public override void Apply(ICriteria criteria) { if (!string.IsNullOrEmpty(Query)) { criteria.CreateAlias(string.Format("FREETEXTTABLE(Post, (Title, Body), '{0}')", Renderer.SqlEncode(Query)), "KEY_TBL", JoinType.InnerJoin).Add(Restrictions.Eq("Post.Post_Id", "KEY_TBL.[KEY]")); } if (TopicId != 0) { criteria.Add(Expression.Sql(string.Format("EXISTS ( SELECT * FROM PostTopic t WHERE t.Post_Id = this_.Post_Id AND t.Topic_Id = {0})", TopicId))); } if (DateStart != DateTime.MinValue) { criteria.Add(Expression.Ge("Created", DateStart)); } if (DateEnd != DateTime.MaxValue) { criteria.Add(Expression.Le("Created", DateEnd)); } if (PublishedOnly) { criteria.Add(Expression.Eq("Publish", true)); } if (DisplayedOnly) { criteria.Add(Expression.Eq("Display", true)); } base.Apply(criteria); }
/// <summary> /// Adds the comma delimited strings to the expression factory. /// </summary> /// <param name="criteria">The criteria.</param> /// <param name="expressions">The expressions.</param> /// <param name="text">The text.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="clause">The clause.</param> private static void AddCommaDelimitedStringsToExpression(ICriteria criteria, IExpressionFactory expressions, String text, String propertyName, SearchParameter clause) { if (!string.IsNullOrEmpty(text)) { IList<IExpression> expression = new List<IExpression>(); IJunction junction; string[] values = text.Split(','); foreach (String value in values) { expression.Add(GetExpression(expressions, clause, propertyName, value)); } junction = expressions.Disjunction(); foreach (IExpression e in expression) { junction.Add(e); } criteria.Add(junction); } return; }
/// <summary> /// Adds the expressions criteria. /// </summary> /// <param name="criteria">The criteria.</param> /// <param name="expressions">The expressions.</param> /// <returns></returns> private void AddExpressionsCriteria(ICriteria criteria, IExpressionFactory expressions) { if (criteria != null) { SearchParameter clause; Boolean isLeads = (rdgIncludeType.SelectedIndex == 0); Boolean isPrimaryContact = (rdgIncludeType.SelectedIndex == 1); Boolean isIndividual = (rdgIncludeType.SelectedIndex == 3); criteria.Add(expressions.Eq("address.IsPrimary", true)); if (isPrimaryContact) { criteria.Add(expressions.Eq("a1.IsPrimary", true)); } if (chkCompany.Checked) { clause = (SearchParameter)lbxCompany.SelectedIndex; if (isLeads) criteria.Add(GetExpression(expressions, clause, "a1.Company", txtCompany.Text)); else criteria.Add(GetExpression(expressions, clause, "account.AccountName", txtCompany.Text)); } if (chkIndustry.Checked) { clause = (SearchParameter)lbxIndustry.SelectedIndex; if (isLeads) criteria.Add(GetExpression(expressions, clause, "a1.Industry", pklIndustry.PickListValue)); else criteria.Add(GetExpression(expressions, clause, "account.Industry", pklIndustry.PickListValue)); } if (chkSIC.Checked) { clause = (SearchParameter)lbxSIC.SelectedIndex; if (isLeads) criteria.Add(GetExpression(expressions, clause, "a1.SICCode", txtSIC.Text)); else criteria.Add(GetExpression(expressions, clause, "account.SicCode", txtSIC.Text)); } if (chkTitle.Checked) { clause = (SearchParameter)lbxTitle.SelectedIndex; criteria.Add(GetExpression(expressions, clause, "a1.Title", pklTitle.PickListValue)); } if (chkProducts.Checked && !isLeads) { criteria.CreateCriteria("account.AccountProducts", "product"); clause = (SearchParameter)lbxProducts.SelectedIndex; criteria.Add(GetExpression(expressions, clause, "product.ProductName", lueProducts.Text)); } if (chkStatus.Checked) { clause = (SearchParameter)lbxStatus.SelectedIndex; if (isLeads || isIndividual) criteria.Add(GetExpression(expressions, clause, "a1.Status", pklStatus.PickListValue)); else criteria.Add(GetExpression(expressions, clause, "account.Status", pklStatus.PickListValue)); } if (!chkSolicit.Checked) criteria.Add(expressions.Or(expressions.Eq("a1.DoNotSolicit", false), expressions.IsNull("a1.DoNotSolicit"))); if (!chkEmail.Checked) criteria.Add(expressions.Or(expressions.Eq("a1.DoNotEmail", false), expressions.IsNull("a1.DoNotEmail"))); if (!chkCall.Checked) criteria.Add(expressions.Or(expressions.Eq("a1.DoNotPhone", false), expressions.IsNull("a1.DoNotPhone"))); if (!chkMail.Checked) criteria.Add(expressions.Or(expressions.Eq("a1.DoNotMail", false), expressions.IsNull("a1.DoNotMail"))); if (!chkFax.Checked) { if (isLeads) criteria.Add(expressions.Or(expressions.Eq("a1.DoNotFAX", false), expressions.IsNull("a1.DoNotFAX"))); else criteria.Add(expressions.Or(expressions.Eq("a1.DoNotFax", false), expressions.IsNull("a1.DoNotFax"))); } if (chkCity.Checked) { clause = (SearchParameter)lbxCity.SelectedIndex; AddCommaDelimitedStringsToExpression(criteria, expressions, txtCity.Text, "address.City", clause); } if (chkState.Checked) { clause = (SearchParameter)lbxState.SelectedIndex; AddCommaDelimitedStringsToExpression(criteria, expressions, txtState.Text, "address.State", clause); } if (chkZip.Checked) { clause = (SearchParameter)lbxZip.SelectedIndex; AddCommaDelimitedStringsToExpression(criteria, expressions, txtZip.Text, "address.PostalCode", clause); } if (chkLeadSource.Checked) { switch (rdgIncludeType.SelectedIndex) { case 0: criteria.CreateCriteria("a1.LeadSource", "leadsource"); break; case 3: criteria.CreateCriteria("a1.LeadSources", "leadsource"); break; default: criteria.CreateCriteria("account.LeadSource", "leadsource"); break; } clause = (SearchParameter)lbxLeadSource.SelectedIndex; criteria.Add(GetExpression(expressions, clause, "leadsource.Description", lueLeadSource.Text)); } if (chkImportSource.Checked) { clause = (SearchParameter)lbxImportSource.SelectedIndex; if (isLeads || isIndividual) criteria.Add(GetExpression(expressions, clause, "a1.ImportSource", pklImportSource.PickListValue)); else criteria.Add(GetExpression(expressions, clause, "account.ImportSource", pklImportSource.PickListValue)); } if (!string.IsNullOrEmpty(dtpCreateFromDate.Text)) { if (chkCreateDate.Checked && (isLeads || isIndividual)) criteria.Add(expressions.Between("a1.CreateDate", CheckForNullDate(dtpCreateFromDate.DateTimeValue), CheckForNullDate(dtpCreateToDate.DateTimeValue))); else if (chkCreateDate.Checked) criteria.Add(expressions.Between("account.CreateDate", CheckForNullDate(dtpCreateFromDate.DateTimeValue), CheckForNullDate(dtpCreateToDate.DateTimeValue))); } } return; }
private void GetFilterCriteria(ICriteria criteria, int find, string keyword) { string text = string.Format("%{0}%", keyword); // Search by make if (find == 1) { ICriterion qmake = Restrictions.Like("Make", text, MatchMode.Anywhere); criteria.Add(qmake); } // Search by model else if (find == 2) { ICriterion qmodel = Restrictions.Like("Model", text, MatchMode.Anywhere); criteria.Add(qmodel); } // Search by year else if (find == 3) { try { int year = Convert.ToInt32(keyword); ICriterion qyear = Restrictions.Eq("Year", year); criteria.Add(qyear); } catch { } } // Search by doors else if (find == 4) { try { int doors = Convert.ToInt32(keyword); ICriterion qdoors = Restrictions.Eq("Doors", doors); criteria.Add(qdoors); } catch { } } // Search by colour else if (find == 5) { ICriterion qcolour = Restrictions.Like("Colour", text, MatchMode.Anywhere); criteria.Add(qcolour); } // Search by price else if (find == 6) { double price = Convert.ToDouble(keyword); ICriterion qprice = Restrictions.Eq("Price", price); criteria.Add(qprice); } // Search all else { bool isNumeric = Utils.IsNumber(keyword); if (!isNumeric) { ICriterion qmake = Restrictions.Like("Make", text, MatchMode.Anywhere); ICriterion qmodel = Restrictions.Like("Model", text, MatchMode.Anywhere); ICriterion qcolour = Restrictions.Like("Colour", text, MatchMode.Anywhere); AbstractCriterion exp1 = Restrictions.Or(qmake, qmodel); AbstractCriterion exp2 = Restrictions.Or(exp1, qcolour); criteria.Add(exp2); } else { int year = Utils.GetInt(keyword); int doors = Utils.GetInt(keyword); double price = Utils.GetDouble(keyword); ICriterion qyear = Restrictions.Eq("Year", year); ICriterion qdoors = Restrictions.Eq("Doors", doors); ICriterion qprice = Restrictions.Eq("Price", price); ICriterion qmake = Restrictions.Like("Make", text, MatchMode.Anywhere); ICriterion qmodel = Restrictions.Like("Model", text, MatchMode.Anywhere); ICriterion qcolour = Restrictions.Like("Colour", text, MatchMode.Anywhere); AbstractCriterion exp1 = Restrictions.Or(qyear, qdoors); AbstractCriterion exp2 = Restrictions.Or(exp1, qprice); AbstractCriterion exp3 = Restrictions.Or(exp2, qmake); AbstractCriterion exp4 = Restrictions.Or(exp3, qmodel); AbstractCriterion exp5 = Restrictions.Or(exp4, qcolour); criteria.Add(exp5); } } }
private static void GetFilterCriteria(ICriteria cr, Dictionary<string, object> filters, Sort sort = null) { string employee = Convert.ToString(filters["employee"]); DateTime work_date = (DateTime)filters["work_date"]; if (!string.IsNullOrEmpty(employee)) { cr = cr.CreateCriteria("attendance.Employee", "e", JoinType.InnerJoin); AbstractCriterion a1 = Restrictions.InsensitiveLike("e.Firstname", employee, MatchMode.Anywhere); AbstractCriterion a2 = Restrictions.InsensitiveLike("e.Middlename", employee, MatchMode.Anywhere); AbstractCriterion a3 = Restrictions.InsensitiveLike("e.Lastname", employee, MatchMode.Anywhere); AbstractCriterion b1 = Restrictions.Or(a1, a2); AbstractCriterion b2 = Restrictions.Or(b1, a3); cr.Add(b2); } if (work_date != default(DateTime)) cr.Add(Restrictions.Eq("attendance.Workdate", work_date)); if (sort != null) SetJoinCriteria(cr, sort); }
/// <summary> /// /// </summary> /// <param name="hibernateCriteria"></param> /// <param name="where"></param> /// <param name="orders"></param> private void AddCriteriaAndOrder(ICriteria hibernateCriteria, IEnumerable<ICriterion> where, IEnumerable<Order> orders) { foreach (ICriterion criterion in where) { hibernateCriteria.Add(criterion); } foreach (Order order in orders) { hibernateCriteria.AddOrder(order); } }
private void AddRestriction(ICriteria criteria, String type, Object value,Boolean exactMatch) { if (criteria != null && type != null && value != null){ if (exactMatch){ criteria.Add(Restrictions.Eq(type, value)); } else{ criteria.Add(Restrictions.Like(type, value)); } } }
public override void Apply(ICriteria criteria) { if (PostId != 0) { criteria.Add(Expression.Eq("Post.Id", PostId)); } base.Apply(criteria); }
public override void Apply(ICriteria criteria) { if (AssociatedId != 0) { criteria.Add(Expression.Eq(string.Format("{0}.Id", Table), AssociatedId)); } base.Apply(criteria); }