/// <summary> /// Find non-deleted concrete data by a keyword which may be included in concrete data name or value. /// </summary> /// <param name="concreteDataType">Concrete data type.</param> /// <param name="query">Keyword included in Name or Value. Null or empty value indicates to query all records in the concrete type.</param> /// <param name="limit">Maximum number of returned records.</param> /// <returns></returns> public Collection<ConcreteDataObject> FindByKeywordJson(string concreteDataType, string query, int limit) { LinqPredicate predicate = new LinqPredicate("Type=@0 AND DeleteStatus=@1", concreteDataType, DeleteStatus.NotDeleted); if (!string.IsNullOrEmpty(query)) predicate.Add("Name.Contains(@0) OR Value.Contains(@0)", query); int recordCount; try { Collection<ConcreteDataObject> results = new Collection<ConcreteDataObject>(concreteDataApi.FindConcreteData(predicate, "Name Asc", 0, limit, out recordCount).ToList()); return results; } catch (ArgumentException ex) { throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, ex.Message)); } catch (BadRequestException bad) { throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, bad.Message)); } catch (FormatException formatEx) { throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, formatEx.Message)); } catch (Exception exp) { Logger.Instance(this).Error(exp); throw new InternalServerErrorException(); } }
public void ComplexHierarchyDataTest() { // define the metadata of geography. metadataTypeId = metadataApi.AddType("Geography", "HierarchyData", null, ObjectMetadataTypes.Custom, false, null); metadataApi.SaveField(metadataTypeId, new StringFieldMetadata { Name = "Chief Executive" }); metadataApi.SaveField(metadataTypeId, new IntegerFieldMetadata { Name = "Population", MinValue = 0 }); // create geographic areas with extension properties HierarchyDataObject china = new HierarchyDataObject { HierarchyType = GEOGRAPHY, Name = "China", ExtensionDataTypeId = metadataTypeId }; china["Chief Executive"] = "XXX"; china["Population"] = 1300000000; hierarchyApi.Save(china); HierarchyDataObject shanghai = new HierarchyDataObject { HierarchyType = GEOGRAPHY, Name = "Shanghai", ParentHierarchyDataId = china.HierarchyDataId, ExtensionDataTypeId = metadataTypeId }; shanghai["Chief Executive"] = "YYY"; shanghai["Population"] = 20000000; hierarchyApi.Save(shanghai); HierarchyDataObject beijing = new HierarchyDataObject { HierarchyType = GEOGRAPHY, Name = "Beijing", ParentHierarchyDataId = china.HierarchyDataId, ExtensionDataTypeId = metadataTypeId }; beijing["Chief Executive"] = "ZZZ"; beijing["Population"] = 30000000; hierarchyApi.Save(beijing); this.temporaryHierarchyDataIds.AddRange(new[] { china.HierarchyDataId, shanghai.HierarchyDataId, beijing.HierarchyDataId }); // query hierarchy data by name. int recordCount; LinqPredicate predicate = new LinqPredicate("Name=@0 AND HierarchyType=@1", "Shanghai", GEOGRAPHY); IEnumerable<HierarchyDataObject> geographicAreas = hierarchyApi.FindHierarchyData(predicate, null, 0, 10, out recordCount); shanghai = geographicAreas.First(); Assert.AreEqual(1, recordCount); Assert.AreEqual("YYY", shanghai["Chief Executive"]); Assert.AreEqual(20000000, shanghai["Population"]); }
public void LinqPredicateSimpleTest() { LinqPredicate predicate = new LinqPredicate("Name=@0 AND Height=@1", "Eunge", 170); Assert.AreEqual(2, predicate.Parameters.Length); Assert.AreEqual("Eunge", predicate.Parameters[0]); Assert.AreEqual(170, predicate.Parameters[1]); Assert.AreEqual("(Name=@0 AND Height=@1)", predicate.Expression); }
public void MergeLinqPredicateWithDuplicateExpressionVariables() { LinqPredicate predicate = new LinqPredicate("City=@0 AND Height>=@1", "Shanghai", 170); predicate.Add("Name.StartsWith(@0) AND Height>=@1", "Eunge", 170); Assert.AreEqual(3, predicate.Parameters.Length); Assert.AreEqual("Shanghai", predicate.Parameters[0]); Assert.AreEqual(170, predicate.Parameters[1]); Assert.AreEqual("Eunge", predicate.Parameters[2]); Assert.AreEqual("(City=@0 AND Height>=@1) AND (Name.StartsWith(@2) AND Height>=@1)", predicate.Expression); }
public void MergeLinqPredicateWithSequentialParameters() { LinqPredicate predicate = new LinqPredicate("Name=@0 AND Height=@1", "Eunge", 170); predicate.Add("Degree=@0 AND City=@1", "Master", "Shanghai"); Assert.AreEqual(4, predicate.Parameters.Length); Assert.AreEqual("Eunge", predicate.Parameters[0]); Assert.AreEqual(170, predicate.Parameters[1]); Assert.AreEqual("Master", predicate.Parameters[2]); Assert.AreEqual("Shanghai", predicate.Parameters[3]); Assert.AreEqual("(Name=@0 AND Height=@1) AND (Degree=@2 AND City=@3)", predicate.Expression); }
/// <summary> /// Find hierarchy data in all types by custom predicates. /// </summary> /// <param name="predicate">linq predicate which supports properties of <see cref="RapidWebDev.Platform.HierarchyDataObject"/> for query expression.</param> /// <param name="orderby">dynamic orderby command</param> /// <param name="pageIndex">current paging index</param> /// <param name="pageSize">page size</param> /// <param name="recordCount">total hit records count</param> /// <returns></returns> public IEnumerable<HierarchyDataObject> FindHierarchyData(LinqPredicate predicate, string orderby, int pageIndex, int pageSize, out int recordCount) { try { using (MembershipDataContext ctx = DataContextFactory.Create<MembershipDataContext>()) { IQueryable<HierarchyData> q = from hd in ctx.HierarchyDatas where hd.ApplicationId == this.authenticationContext.ApplicationId select hd; if (predicate != null && !string.IsNullOrEmpty(predicate.Expression)) q = q.Where(predicate.Expression, predicate.Parameters); if (!Kit.IsEmpty(orderby)) q = q.OrderBy(orderby); recordCount = q.Count(); List<HierarchyData> hierarchyDataSets = q.Skip(pageIndex * pageSize).Take(pageSize).ToList(); List<HierarchyDataObject> hierarchyDataObjects = new List<HierarchyDataObject>(); foreach (HierarchyData entity in hierarchyDataSets) { HierarchyDataObject hierarchyDataObject = new HierarchyDataObject { HierarchyDataId = entity.HierarchyDataId, HierarchyType = entity.HierarchyType, Code = entity.Code, Name = entity.Name, Description = entity.Description, ParentHierarchyDataId = entity.ParentHierarchyDataId, ExtensionDataTypeId = entity.ExtensionDataTypeId, CreatedBy = entity.CreatedBy, CreatedDate = LocalizationUtility.ConvertUtcTimeToClientTime(entity.CreatedDate), LastUpdatedBy = entity.LastUpdatedBy, LastUpdatedDate = LocalizationUtility.ConvertUtcTimeToClientTime(entity.LastUpdatedDate) }; hierarchyDataObject.ParseExtensionPropertiesFrom(entity); hierarchyDataObjects.Add(hierarchyDataObject); } return hierarchyDataObjects; } } catch (Exception exp) { Logger.Instance(this).Error(exp); throw; } }
/// <summary> /// Find all hierarchies which include the query keyword in code or name. /// </summary> /// <param name="hierarchyType"></param> /// <param name="query"></param> /// <param name="maxReturnedCount"></param> /// <returns></returns> public Collection<HierarchyDataObject> FindByKeywordJson(string hierarchyType, string query, int maxReturnedCount) { if (string.IsNullOrEmpty(hierarchyType)) throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidHierarchyType, hierarchyType)); try { int recordCount; LinqPredicate predicate = new LinqPredicate("HierarchyType=@0", hierarchyType); if (!string.IsNullOrEmpty(query)) predicate = predicate.Add("(Code!=null AND Code.StartsWith(@0)) OR (Name!=null AND Name.StartsWith(@0))", query.Replace("-", "").Trim()); IEnumerable<HierarchyDataObject> hierarchyDataObjects = hierarchyApi.FindHierarchyData(predicate, "Name ASC", 0, maxReturnedCount, out recordCount); Collection<HierarchyDataObject> results = new Collection<HierarchyDataObject>(); IEnumerable<HierarchyDataObject> dummyRootHierarchyDataObjects = FindHierarchyDataObjectWithParentNotExist(hierarchyDataObjects); foreach (HierarchyDataObject dummyRootHierarchyDataObject in dummyRootHierarchyDataObjects) HierarchizeHierarchyData(hierarchyDataObjects, dummyRootHierarchyDataObject, results, 0); if (results.Count() == 0) return new Collection<HierarchyDataObject>(); return results; } catch (ArgumentException ex) { throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, ex.Message)); } catch (BadRequestException bad) { throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, bad.Message)); } catch (FormatException formatEx) { throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, formatEx.Message)); } catch (Exception exp) { Logger.Instance(this).Error(exp); throw new InternalServerErrorException(); } }
/// <summary> /// Execute query for results binding to dynamic page grid. /// </summary> /// <param name="parameter">Query parameter.</param> /// <returns>Returns query results.</returns> public override QueryResults Query(QueryParameter parameter) { LinqPredicate predicate = LinqPredicate.Concat(parameter.Expressions.Compile(), this.CreateCustomQuery(parameter)); int recordCount; string sortingExpression = null; if (parameter.SortExpression != null) sortingExpression = parameter.SortExpression.Compile(); if (Kit.IsEmpty(sortingExpression)) sortingExpression = "LastUpdatedDate ASC"; string hierarchyType = authenticationContext.TempVariables["HierarchyType"] as string; LinqPredicate hierarchyTypePredicate = new LinqPredicate("HierarchyType=@0", hierarchyType); predicate = hierarchyTypePredicate.Add(predicate); IEnumerable<HierarchyDataObject> hierarchyDataObjects = hierarchyApi.FindHierarchyData(predicate, sortingExpression, parameter.PageIndex, parameter.PageSize, out recordCount); return new QueryResults(recordCount, hierarchyDataObjects); }
public void FindOrganizationTest() { IOrganizationApi organizationApi = SpringContext.Current.GetObject<IOrganizationApi>(); OrganizationTypeObject department = new OrganizationTypeObject { Name = "department", Domain = "Department", Description = "department-desc" }; organizationApi.Save(department); createdOrganizationTypeIds.Add(department.OrganizationTypeId); OrganizationObject shanghai = new OrganizationObject { OrganizationCode = "sh", OrganizationName = "shanghai department", OrganizationTypeId = department.OrganizationTypeId, Status = OrganizationStatus.Enabled, Description = "shanghai desc" }; organizationApi.Save(shanghai); createdOrganizationIds.Add(shanghai.OrganizationId); OrganizationObject chengdu = new OrganizationObject { OrganizationCode = "cd", OrganizationName = "chengdu department", OrganizationTypeId = department.OrganizationTypeId, Status = OrganizationStatus.Enabled, Description = "chengdu desc" }; organizationApi.Save(chengdu); createdOrganizationIds.Add(chengdu.OrganizationId); int recordCount; LinqPredicate linqPredicate = new LinqPredicate("OrganizationName.EndsWith(@0) And Status=@1", "department", OrganizationStatus.Enabled); IEnumerable<OrganizationObject> organizations = organizationApi.FindOrganizations(linqPredicate, null, 0, 10, out recordCount); Assert.AreEqual(2, recordCount); }
/// <summary> /// Merge other predicate expression with parameters into the current predicate. /// </summary> /// <param name="linqPredicate">linq predicate</param> public LinqPredicate Add(LinqPredicate linqPredicate) { if (linqPredicate != null && !string.IsNullOrEmpty(linqPredicate.Expression)) { ValidatePredicateWithParameters(linqPredicate.Expression, linqPredicate.Parameters); this.cachedMergedExpression = null; this.cachedMergedParameters = null; this.expressionsWithParameters.Add(new KeyValuePair<string, object[]>(linqPredicate.Expression, linqPredicate.Parameters)); } return this; }
/// <summary> /// Concat two linq predicates. /// </summary> /// <param name="predicate1"></param> /// <param name="predicate2"></param> /// <returns></returns> public static LinqPredicate Concat(LinqPredicate predicate1, LinqPredicate predicate2) { if (predicate1 != null && predicate2 != null) return predicate1.Add(predicate2); else if (predicate1 == null && predicate2 != null) return predicate2; else if (predicate1 != null && predicate2 == null) return predicate1; else return null; }
/// <summary> /// Find role objects by custom predicates. /// </summary> /// <param name="predicate">linq predicate. see role properties for predicate at <see cref="RapidWebDev.Platform.Linq.Role"/>.</param> /// <param name="orderby">dynamic orderby command</param> /// <param name="pageIndex">current paging index</param> /// <param name="pageSize">page size</param> /// <param name="recordCount">total hit records count</param> /// <returns>Returns enumerable role objects</returns> public IEnumerable<RoleObject> FindRoles(LinqPredicate predicate, string orderby, int pageIndex, int pageSize, out int recordCount) { try { using (MembershipDataContext ctx = DataContextFactory.Create<MembershipDataContext>()) { IAuthenticationContext authenticationContext = SpringContext.Current.GetObject<IAuthenticationContext>(); var q = from r in ctx.Roles where r.ApplicationId == authenticationContext.ApplicationId select r; if (predicate != null && !Kit.IsEmpty(predicate.Expression)) q = q.Where(predicate.Expression, predicate.Parameters); if (!Kit.IsEmpty(orderby)) q = q.OrderBy(orderby); recordCount = q.Count(); List<Guid> roleIds = q.Skip(pageIndex * pageSize).Take(pageSize) .Select(r => r.RoleId).ToList(); return this.BulkGet(roleIds).Values; } } catch (Exception exp) { Logger.Instance(this).Error(exp); throw; } }
public void ConcreteDataWithinDifferentTypesTest() { const string DEGREE = "Degree"; const string CITY = "City"; ConcreteDataObject master = new ConcreteDataObject { Type = DEGREE, Name = "Master" }; ConcreteDataObject regularCollege = new ConcreteDataObject { Type = DEGREE, Name = "Regular College" }; ConcreteDataObject juniorCollege = new ConcreteDataObject { Type = DEGREE, Name = "Junior College" }; ConcreteDataObject shanghai = new ConcreteDataObject { Type = CITY, Name = "Shanghai" }; ConcreteDataObject beijing = new ConcreteDataObject { Type = CITY, Name = "Beijing" }; concreteDataApi.Save(master); concreteDataApi.Save(regularCollege); concreteDataApi.Save(juniorCollege); concreteDataApi.Save(shanghai); concreteDataApi.Save(beijing); IEnumerable<ConcreteDataObject> degrees = concreteDataApi.FindAllByType(DEGREE); Assert.AreEqual(3, degrees.Count()); IEnumerable<ConcreteDataObject> cities = concreteDataApi.FindAllByType(CITY); Assert.AreEqual(2, cities.Count()); int recordCount; LinqPredicate predicate = new LinqPredicate("Name.EndsWith(@0) AND Type=@1", "College", DEGREE); degrees = concreteDataApi.FindConcreteData(predicate, null, 0, 10, out recordCount); Assert.AreEqual(2, recordCount); predicate = new LinqPredicate("Name=@0 AND Type=@1", "Shanghai", CITY); degrees = concreteDataApi.FindConcreteData(predicate, null, 0, 10, out recordCount); Assert.AreEqual(1, recordCount); }
/// <summary> /// Find concrete data in all types by custom predicates. /// </summary> /// <param name="predicate"></param> /// <param name="orderby"></param> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="recordCount"></param> /// <returns></returns> public IEnumerable<ConcreteDataObject> FindConcreteData(LinqPredicate predicate, string orderby, int pageIndex, int pageSize, out int recordCount) { try { using (MembershipDataContext ctx = DataContextFactory.Create<MembershipDataContext>()) { var q = from c in ctx.ConcreteDatas where c.ApplicationId == authenticationContext.ApplicationId select c; if (predicate != null && !string.IsNullOrEmpty(predicate.Expression)) q = q.Where(predicate.Expression, predicate.Parameters); if (!string.IsNullOrEmpty(orderby)) q = q.OrderBy(orderby); recordCount = q.Count(); List<ConcreteDataObject> concreteDataObjects = new List<ConcreteDataObject>(); List<ConcreteData> concreteDataEntities = q.Skip(pageIndex * pageSize).Take(pageSize).ToList(); foreach (ConcreteData entity in concreteDataEntities) { ConcreteDataObject concreteDataObject = new ConcreteDataObject { ConcreteDataId = entity.ConcreteDataId, Type = entity.Type, CreatedBy = entity.CreatedBy, CreatedDate = LocalizationUtility.ConvertUtcTimeToClientTime(entity.CreatedDate), DeleteStatus = entity.DeleteStatus, Description = entity.Description, ExtensionDataTypeId = entity.ExtensionDataTypeId, LastUpdatedBy = entity.LastUpdatedBy, LastUpdatedDate = LocalizationUtility.ConvertUtcTimeToClientTime(entity.LastUpdatedDate), Name = entity.Name, Value = entity.Value }; concreteDataObject.ParseExtensionPropertiesFrom(entity); concreteDataObjects.Add(concreteDataObject); } return concreteDataObjects; } } catch (Exception exp) { Logger.Instance(this).Error(exp); throw; } }
/// <summary> /// Validate data input from client. /// </summary> /// <param name="userId"></param> protected virtual void ValidateDataInputForm(Guid? userId) { using (ValidationScope validationScope = new ValidationScope()) { int recordCount; if (this.OrganizationSelector != null && this.OrganizationSelector.SelectedOrganization == null) validationScope.Error(Resources.OrganizationCannotBeEmpty); if (this.TextBoxUserName != null && this.TextBoxUserName.Text.Trim().Length == 0) validationScope.Error(Resources.UserNameCannotBeEmpty); else if (this.TextBoxUserName != null) { LinqPredicate linqPredicate = new LinqPredicate("UserName=@0 AND UserId!=@1", this.TextBoxUserName.Text, userId.HasValue ? userId.Value : Guid.NewGuid()); membershipApi.FindUsers(linqPredicate, null, 0, 1, out recordCount); if (recordCount > 0) validationScope.Error(Resources.DuplicateUserName, this.TextBoxUserName.Text); } if (this.TextBoxPassword != null && !userId.HasValue && this.TextBoxPassword.Text.Trim().Length == 0) validationScope.Error(Resources.PasswordCannotBeEmpty); if (this.TextBoxPassword != null && this.TextBoxPassword.Text.Trim().Length > 0) { if (this.TextBoxPassword.Text.Trim() != this.TextBoxConfirmPassword.Text.Trim()) validationScope.Error(Resources.PasswordNotEqualToConfirmPassword); else { if (this.TextBoxPassword.Text.Trim().Length < AspNetMembership.MinRequiredPasswordLength) validationScope.Error(Resources.PasswordLengthLessThanRequired, AspNetMembership.MinRequiredPasswordLength); if (!Kit.IsEmpty(AspNetMembership.PasswordStrengthRegularExpression)) { Regex regex = new Regex(AspNetMembership.PasswordStrengthRegularExpression, RegexOptions.Compiled); if (!regex.IsMatch(TextBoxPassword.Text.Trim())) validationScope.Error(Resources.PasswordFormatIsInvalid, AspNetMembership.PasswordStrengthRegularExpression); } } } if (this.TextBoxDisplayName != null && this.TextBoxDisplayName.Text.Trim().Length == 0) validationScope.Error(Resources.DisplayNameCannotBeEmpty); else if (this.TextBoxDisplayName != null) { LinqPredicate linqPredicate = new LinqPredicate("DisplayName=@0 AND UserId!=@1", this.TextBoxDisplayName.Text, userId.HasValue ? userId.Value : Guid.NewGuid()); membershipApi.FindUsers(linqPredicate, null, 0, 1, out recordCount); if (recordCount > 0) validationScope.Error(Resources.DuplicateDisplayName, this.TextBoxDisplayName.Text); } } }
public void MergeNullOrEmptyLinqPredicate() { LinqPredicate predicate = new LinqPredicate("City=@0 AND Height>=@1", "Shanghai", 170); predicate.Add((LinqPredicate)null); predicate.Add(new LinqPredicate(null)); predicate.Add((string)null); Assert.AreEqual("(City=@0 AND Height>=@1)", predicate.Expression); Assert.AreEqual(2, predicate.Parameters.Length); }
/// <summary> /// Convert Web query predicate to LinqPredicate /// </summary> /// <param name="predicate"></param> /// <returns></returns> public static LinqPredicate ConvertWebPredicateToLinqPredicate(WebServiceQueryPredicate predicate) { if (predicate == null) return null; IList<object> LinqPredicateParameters = new List<object>(); foreach (var param in predicate.Parameters) { try { switch (param.Type) { case WebServiceQueryPredicateParameterTypes.DateTime: LinqPredicateParameters.Add(Kit.ConvertType(param.Value, typeof(System.DateTime))); break; case WebServiceQueryPredicateParameterTypes.Decimal: LinqPredicateParameters.Add(Kit.ConvertType(param.Value, typeof(System.Decimal))); break; case WebServiceQueryPredicateParameterTypes.Double: LinqPredicateParameters.Add(Kit.ConvertType(param.Value, typeof(System.Double))); break; case WebServiceQueryPredicateParameterTypes.Guid: LinqPredicateParameters.Add(Kit.ConvertType(param.Value, typeof(System.Guid))); break; case WebServiceQueryPredicateParameterTypes.Integer: LinqPredicateParameters.Add(Kit.ConvertType(param.Value, typeof(System.Int32))); break; default: LinqPredicateParameters.Add(param.Value); break; } } catch (Exception exp) { throw new BadRequestException(exp.Message); } } LinqPredicate linqPredicate = new LinqPredicate(predicate.Expression, LinqPredicateParameters.ToArray()); return linqPredicate; }
public void FindUserTest() { IMembershipApi membershipApi = SpringContext.Current.GetObject<IMembershipApi>(); this.CreateUser(membershipApi); this.CreateUser(membershipApi); this.CreateUser(membershipApi); this.CreateUser(membershipApi); int recordCount; LinqPredicate predicate = new LinqPredicate("UserName!=@0 AND UserName!=@1", "Admin", "Anonymous"); IEnumerable<UserObject> userObjects = membershipApi.FindUsers(predicate, "UserName", 0, 10, out recordCount); Assert.AreEqual(4, recordCount); Assert.AreEqual(4, userObjects.Count()); userObjects = membershipApi.FindUsers(predicate, "DisplayName", 0, 3, out recordCount); Assert.AreEqual(4, recordCount); Assert.AreEqual(3, userObjects.Count()); }
private IEnumerable<RoleObject> FindRolesByOrganization(OrganizationObject organizationObject) { int recordCount; OrganizationTypeObject orgType = organizationApi.GetOrganizationType(organizationObject.OrganizationTypeId); LinqPredicate linqPredicate = new LinqPredicate("Domain=@0", orgType.Domain); IEnumerable<RoleObject> results = roleApi.FindRoles(linqPredicate, "RoleName ASC", 0, int.MaxValue, out recordCount); return results.ToList(); }
public void SimpleHierarchyDataTest() { HierarchyDataObject china = new HierarchyDataObject { HierarchyType = GEOGRAPHY, Name = "China" }; hierarchyApi.Save(china); HierarchyDataObject shanghai = new HierarchyDataObject { HierarchyType = GEOGRAPHY, Name = "Shanghai", ParentHierarchyDataId = china.HierarchyDataId }; hierarchyApi.Save(shanghai); HierarchyDataObject beijing = new HierarchyDataObject { HierarchyType = GEOGRAPHY, Name = "Beijing", ParentHierarchyDataId = china.HierarchyDataId }; hierarchyApi.Save(beijing); this.temporaryHierarchyDataIds.AddRange(new[] { china.HierarchyDataId, shanghai.HierarchyDataId, beijing.HierarchyDataId }); // get all areas IEnumerable<HierarchyDataObject> areas = hierarchyApi.GetAllChildren(GEOGRAPHY, null); Assert.AreEqual(3, areas.Count()); // get both implicit and explicit child areas of China areas = hierarchyApi.GetAllChildren(GEOGRAPHY, china.HierarchyDataId); Assert.AreEqual(2, areas.Count()); // get only explicit child areas which is the root node in geography. areas = hierarchyApi.GetImmediateChildren(GEOGRAPHY, null); Assert.AreEqual(1, areas.Count()); Assert.AreEqual("China", areas.First().Name); // query hierarchy data by name. int recordCount; LinqPredicate predicate = new LinqPredicate("Name=@0 AND ParentHierarchyDataId=@1 AND HierarchyType=@2", "Beijing", china.HierarchyDataId, GEOGRAPHY); hierarchyApi.FindHierarchyData(predicate, null, 0, 10, out recordCount); Assert.AreEqual(1, recordCount); }
public void ConcreteDataSimpleTest() { const string DEGREE = "Degree"; ConcreteDataObject master = new ConcreteDataObject { Type = DEGREE, Name = "Master" }; ConcreteDataObject regularCollege = new ConcreteDataObject { Type = DEGREE, Name = "Regular College" }; ConcreteDataObject juniorCollege = new ConcreteDataObject { Type = DEGREE, Name = "Junior College" }; concreteDataApi.Save(master); concreteDataApi.Save(regularCollege); concreteDataApi.Save(juniorCollege); IEnumerable<ConcreteDataObject> degrees = concreteDataApi.FindAllByType(DEGREE); Assert.AreEqual(3, degrees.Count()); int recordCount; LinqPredicate predicate = new LinqPredicate("Name.EndsWith(@0) AND Type=@1", "College", DEGREE); degrees = concreteDataApi.FindConcreteData(predicate, null, 0, 10, out recordCount); Assert.AreEqual(2, recordCount); }
/// <summary> /// Get first organization matching the specified query. /// The matching algorithm is to try to search organizations in following order. Once an organization is found, it's returned as the result. /// 1) completely match organization code; /// 2) completely match organization name; /// 3) match whether there has organizations with code starts with specified query; /// 4) match whether there has organizations with name starts with specified query; /// </summary> /// <param name="domain"></param> /// <param name="q"></param> /// <returns></returns> public OrganizationObject GetOrganizationJson(string domain, string q) { Guid userId = authenticationContext.User.UserId; if (string.IsNullOrEmpty(domain)) throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidDomain )); if (!platformConfiguration.Domains.Select(d => d.Value).Contains(domain)) throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidDomain )); int recordCount; IEnumerable<OrganizationTypeObject> organizationTypes = organizationApi.FindOrganizationTypes(new[] { domain }); IEnumerable<Guid> organizationTypeIds = organizationTypes.Select(ct => ct.OrganizationTypeId); LinqPredicate linqPredicate = new LinqPredicate("Status=@0 AND OrganizationType.Domain=@1 AND OrganizationCode=@2", OrganizationStatus.Enabled, domain, q); IEnumerable<OrganizationObject> organizations = organizationApi.FindOrganizations(linqPredicate, "OrganizationCode", 0, 1, out recordCount); if (recordCount > 0) return organizations.FirstOrDefault(); linqPredicate = new LinqPredicate("Status=@0 AND OrganizationType.Domain=@1 AND OrganizationName=@2", OrganizationStatus.Enabled, domain, q); organizations = organizationApi.FindOrganizations(linqPredicate, "OrganizationName", 0, 1, out recordCount); if (recordCount > 0) return organizations.FirstOrDefault(); linqPredicate = new LinqPredicate("Status=@0 AND OrganizationType.Domain=@1 AND OrganizationCode.StartWith(@2)", OrganizationStatus.Enabled, domain, q); organizations = organizationApi.FindOrganizations(linqPredicate, "OrganizationCode", 0, 1, out recordCount); if (recordCount > 0) return organizations.FirstOrDefault(); linqPredicate = new LinqPredicate("Status=@0 AND OrganizationType.Domain=@1 AND OrganizationName.Contains(@2)", OrganizationStatus.Enabled, domain, q); organizations = organizationApi.FindOrganizations(linqPredicate, "OrganizationName", 0, 1, out recordCount); if (recordCount > 0) return organizations.FirstOrDefault(); return null; }
public void ComplexConcreteDataTest() { metadataTypeId = metadataApi.AddType("OpenSourceLicense", "ConcreteData", null, ObjectMetadataTypes.Custom, false, null); metadataApi.SaveField(metadataTypeId, new StringFieldMetadata { Name = "Copyright" }); metadataApi.SaveField(metadataTypeId, new DateTimeFieldMetadata { Name = "CreatedOn" }); const string LICENSE = "License"; string GPLv2Description = "The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too."; ConcreteDataObject GPLv2 = new ConcreteDataObject { Type = LICENSE, Name = "GNU General Public License version 2", Value = "GPLv2", ExtensionDataTypeId = metadataTypeId, Description = GPLv2Description }; GPLv2["Copyright"] = "Free Software Foundation, Inc"; GPLv2["CreatedOn"] = new DateTime(1989, 1, 1); concreteDataApi.Save(GPLv2); ConcreteDataObject Apache = new ConcreteDataObject { Type = LICENSE, Name = "Apache License", Value = "Apache", ExtensionDataTypeId = metadataTypeId, Description = "Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form." }; Apache["Copyright"] = "Apache License"; Apache["CreatedOn"] = new DateTime(2004, 1, 1); concreteDataApi.Save(Apache); IEnumerable<ConcreteDataObject> licenses = concreteDataApi.FindAllByType(LICENSE); Assert.AreEqual(2, licenses.Count()); int recordCount; LinqPredicate predicate = new LinqPredicate("Value=@0 AND TYPE=@1", "GPLv2", LICENSE); licenses = concreteDataApi.FindConcreteData(predicate, null, 0, 10, out recordCount); Assert.AreEqual(1, recordCount); GPLv2 = licenses.First(); Assert.AreEqual("GNU General Public License version 2", GPLv2.Name); Assert.AreEqual("GPLv2", GPLv2.Value); Assert.AreEqual(GPLv2Description, GPLv2.Description); Assert.AreEqual("Free Software Foundation, Inc", GPLv2["Copyright"]); Assert.AreEqual(new DateTime(1989, 1, 1), GPLv2["CreatedOn"]); }
/// <summary> /// Search organizations by a collection of criterias for the authenticated user of request. /// </summary> /// <param name="domain">Which domain of the searching organizations.</param> /// <param name="orgTypeId">Which organization type the searching organizations should belong to.</param> /// <param name="q">Keywords for searching.</param> /// <param name="sortDirection">Sorting field name, the default sorting field is LastUpdatedDate.</param> /// <param name="sortOrder">Sorting order, DESC or ASC, the default sorting order is DESC.</param> /// <param name="start">The start organization index of hit to return.</param> /// <param name="limit">The limit of returned organizations.</param> /// <returns>The query results object includes total hit count, returned records, start and limit.</returns> public OrganizationQueryResult SearchJson(string domain, string orgTypeId, string q, string sortDirection, string sortOrder, int start, int limit) { #region Arguments Validation //if (!authenticationContext.Identity.IsAuthenticated) // throw new BadRequestException( "The access is not authenticated."); Guid userId = authenticationContext.User.UserId; if (string.IsNullOrEmpty(domain)) throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidDomain )); if (!platformConfiguration.Domains.Select(d => d.Value).Contains(domain)) throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidDomain )); string sortOrderValue = "DESC"; if (!Kit.IsEmpty(sortOrder)) { sortOrderValue = sortOrder.ToUpperInvariant(); if (sortOrderValue != "ASC" && sortOrderValue != "DESC") throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, "The value of parameter \"sortOrder\" is invalid. The candidate value are ASC and DESC.")); } string sortFieldValue = "LastUpdatedDate"; if (!Kit.IsEmpty(sortDirection)) sortFieldValue = sortDirection; string orderby = sortFieldValue + " " + sortOrderValue; int pageIndex = start / limit; int pageSize = limit; Guid orgTypeIdValue = Guid.Empty; try { orgTypeIdValue = new Guid(orgTypeId); } catch { } #endregion int recordCount; IEnumerable<OrganizationObject> organizations; if (Kit.IsEmpty(q)) { LinqPredicate linqPredicate = new LinqPredicate("OrganizationType.Domain=@0 AND Status=@1", domain, OrganizationStatus.Enabled); if (orgTypeIdValue != Guid.Empty) linqPredicate.Add("OrganizationTypeId=@0", orgTypeIdValue); organizations = organizationApi.FindOrganizations(linqPredicate, orderby, pageIndex, pageSize, out recordCount); } else { LinqPredicate linqPredicate = new LinqPredicate("OrganizationType.Domain=@0 AND Status=@1 AND (OrganizationCode.StartsWith(@2) || OrganizationName.Contains(@3))", domain, OrganizationStatus.Enabled, q, q); if (orgTypeIdValue != Guid.Empty) linqPredicate.Add("OrganizationTypeId=@0", orgTypeIdValue); organizations = organizationApi.FindOrganizations(linqPredicate, orderby, pageIndex, pageSize, out recordCount); } return new OrganizationQueryResult(organizations.ToList()) { PageIndex = pageIndex, PageSize = pageSize, TotalRecordCount = recordCount }; }
/// <summary> /// Find organization business objects by custom predicates. /// </summary> /// <param name="predicate">linq predicate. see organization properties for predicate at <see cref="RapidWebDev.Platform.Linq.Organization"/>.</param> /// <param name="orderby">dynamic orderby command</param> /// <param name="pageIndex">current paging index</param> /// <param name="pageSize">page size</param> /// <param name="recordCount">total hit records count</param> /// <returns>Returns enumerable organizations</returns> public IEnumerable<OrganizationObject> FindOrganizations(LinqPredicate predicate, string orderby, int pageIndex, int pageSize, out int recordCount) { try { using (MembershipDataContext ctx = DataContextFactory.Create<MembershipDataContext>()) { // set query criteria. var q = from org in ctx.Organizations where org.ApplicationId == authenticationContext.ApplicationId select org; if (predicate != null && !Kit.IsEmpty(predicate.Expression)) q = q.Where(predicate.Expression, predicate.Parameters); if (!Kit.IsEmpty(orderby)) q = q.OrderBy(orderby); // get count of matched organizations recordCount = q.Count(); // collect organizations List<Organization> organizations = q.Skip(pageIndex * pageSize).Take(pageSize).ToList(); // collect all OrganizationsInHierarchy entities of the organizations. Guid[] organizationIdArray = organizations.Select(org => org.OrganizationId).ToArray(); var organizationsInHierarchyDictionary = (from organizationsInHierarchy in ctx.OrganizationsInHierarchies where organizationsInHierarchy.ApplicationId == this.authenticationContext.ApplicationId && organizationIdArray.Contains(organizationsInHierarchy.OrganizationId) group organizationsInHierarchy by organizationsInHierarchy.OrganizationId into g select g).ToDictionary(g => g.Key, g => g.ToList()); List<OrganizationObject> organizationObjects = new List<OrganizationObject>(); // go through each organization to parse dynamic properties and hierarchies. foreach (Organization org in organizations) { OrganizationObject organizationObject = new OrganizationObject() { ExtensionDataTypeId = org.ExtensionDataTypeId, OrganizationId = org.OrganizationId, OrganizationCode = org.OrganizationCode, OrganizationName = org.OrganizationName, OrganizationTypeId = org.OrganizationTypeId, Description = org.Description, Status = org.Status, CreatedBy = org.CreatedBy, CreatedDate = org.CreatedDate, LastUpdatedBy = org.LastUpdatedBy, LastUpdatedDate = org.LastUpdatedDate, ParentOrganizationId = org.ParentOrganizationId }; if (organizationsInHierarchyDictionary.ContainsKey(org.OrganizationId)) { List<OrganizationsInHierarchy> organizationsInHierarchies = organizationsInHierarchyDictionary[org.OrganizationId]; foreach (OrganizationsInHierarchy organizationsInHierarchy in organizationsInHierarchies) organizationObject.Hierarchies[organizationsInHierarchy.HierarchyType] = organizationsInHierarchy.HierarchyDataId; } organizationObject.ParseExtensionPropertiesFrom(org); base.AddCache(organizationObject.OrganizationId, organizationObject.Clone()); UpdateTimeZone(organizationObject); organizationObjects.Add(organizationObject); } return organizationObjects; } } catch (Exception exp) { Logger.Instance(this).Error(exp); throw; } }
public void FindRolesTest() { IRoleApi roleApi = SpringContext.Current.GetObject<IRoleApi>(); RoleObject powerAdministrators = new RoleObject { RoleName = "powerAdministrators", Description = "powerAdministrators-desc", Domain = "Department", Predefined = true }; RoleObject business = new RoleObject { RoleName = "business", Description = "business-desc", Domain = "Department", Predefined = true }; RoleObject customers = new RoleObject { RoleName = "customers", Description = "customers-desc", Domain = "Customer"}; roleApi.Save(powerAdministrators); roleApi.Save(business); roleApi.Save(customers); createdRoleIds.AddRange(new Guid[] { powerAdministrators.RoleId, business.RoleId, customers.RoleId }); LinqPredicate linqPredicate = new LinqPredicate("Predefined=@0 And RoleName=@1", true, "business"); int recordCount; IEnumerable<RoleObject> roles = roleApi.FindRoles(linqPredicate, null, 0, 10, out recordCount); Assert.AreEqual(1, recordCount); Assert.AreEqual("business", roles.First().RoleName); Assert.AreEqual("business-desc", roles.First().Description); }