object DoRetrieveEntities(object arg) { SendStepChange("Retrieving entities..."); var entities = new List<EntityDefinition>(); var queryComponents = new QueryExpression(SolutionComponent.EntityLogicalName); queryComponents.ColumnSet.AllColumns = true; queryComponents.Criteria.AddCondition("componenttype", ConditionOperator.Equal, (int)componenttype.Entity); var linkSolution = queryComponents.AddLink(Solution.EntityLogicalName, "solutionid", "solutionid"); linkSolution.EntityAlias = "solution"; linkSolution.Columns.AddColumn("uniquename"); var linkPublisher = linkSolution.AddLink(Publisher.EntityLogicalName, "publisherid", "publisherid"); linkPublisher.EntityAlias = "publisher"; linkPublisher.Columns.AddColumn("customizationprefix"); queryComponents.Criteria.AddCondition("solutionid", ConditionOperator.Equal, _solution.Id); var components = _service.RetrieveMultiple(queryComponents).Entities; var max = components.Count; var current = 1; foreach (SolutionComponent component in components) { var entity = _service.RetrieveEntity(new RetrieveEntityRequest { MetadataId = component.ObjectId.Value, EntityFilters = EntityFilters.Entity | EntityFilters.Attributes | EntityFilters.Relationships }).EntityMetadata; var solutionName = component.GetAttributeValue<AliasedValue>("solution.uniquename").Value as string; Prefix = component.GetAttributeValue<AliasedValue>("publisher.customizationprefix").Value as string; var entityDefinition = new EntityDefinition { LogicalName = entity.LogicalName, Name = RemovePrefix(entity.SchemaName).FormatText() + "Definition", IsActivity = entity.IsActivity.Value, IsLoaded = true }; ClassDefinition keyDefinition = null; if (entity.Keys != null && entity.Keys.Any()) { keyDefinition = new ClassDefinition { LogicalName = "AlternateKeyNames", Name = "AlternateKeyNames" }; entityDefinition.AdditionalClassesCollection.Add(keyDefinition); foreach (var key in entity.Keys) { keyDefinition.Attributes.Add(new AttributeDefinition { LogicalName = key.LogicalName, Name = key.DisplayName.UserLocalizedLabel.Label.FormatText(), Value = key.LogicalName }); } } if (entity.OneToManyRelationships.Any()) { var classDefinition = new ClassDefinition { LogicalName = "OneToManyRelationships", Name = "OneToManyRelationships" }; entityDefinition.AdditionalClassesCollection.Add(classDefinition); foreach (var relationship in entity.OneToManyRelationships) { classDefinition.Attributes.Add(new AttributeDefinition { LogicalName = relationship.SchemaName, Name = relationship.SchemaName, Value = relationship.SchemaName }); } } if (entity.ManyToManyRelationships.Any()) { var classDefinition = new ClassDefinition { LogicalName = "ManyToManyRelationships", Name = "ManyToManyRelationships" }; entityDefinition.AdditionalClassesCollection.Add(classDefinition); foreach (var relationship in entity.ManyToManyRelationships) { classDefinition.Attributes.Add(new AttributeDefinition { LogicalName = relationship.SchemaName, Name = relationship.SchemaName, Value = relationship.SchemaName }); } } var lookupFields = new Dictionary<string, List<OneToManyRelationshipMetadata>>(); if (entity.ManyToOneRelationships.Any()) { ClassDefinition classDefinition = new ClassDefinition { LogicalName = "ManyToOneRelationships", Name = "ManyToOneRelationships" }; entityDefinition.AdditionalClassesCollection.Add(classDefinition); foreach (var relationship in entity.ManyToOneRelationships) { classDefinition.Attributes.Add(new AttributeDefinition { LogicalName = relationship.SchemaName, Name = relationship.SchemaName, Value = relationship.SchemaName }); List<OneToManyRelationshipMetadata> list; if (lookupFields.ContainsKey(relationship.ReferencingAttribute)) { list = lookupFields[relationship.ReferencingAttribute]; } else { list = new List<OneToManyRelationshipMetadata>(); lookupFields.Add(relationship.ReferencingAttribute, list); } list.Add(relationship); } } SendStepChange(string.Format("({1}/{2}) Retrieved '{0}' entity", entity.LogicalName, current.ToString("00"), max.ToString("00"))); current++; entities.Add(entityDefinition); foreach (AttributeMetadata attributeMetadata in entity.Attributes.OrderBy(a => a.LogicalName)) { if (!attributeMetadata.IsValidForCreate.Value && !attributeMetadata.IsValidForRead.Value && !attributeMetadata.IsValidForUpdate.Value) { continue; } if (attributeMetadata.AttributeType.Value == AttributeTypeCode.EntityName || !string.IsNullOrEmpty(attributeMetadata.AttributeOf)) { continue; } EnumDefinition enumDefinition = null; if (attributeMetadata.AttributeType.Value == AttributeTypeCode.Picklist || attributeMetadata.AttributeType.Value == AttributeTypeCode.State || attributeMetadata.AttributeType.Value == AttributeTypeCode.Status) { var meta = ((EnumAttributeMetadata)attributeMetadata).OptionSet; var enumLogicalName = meta.IsGlobal.Value ? meta.Name : entity.LogicalName + "_" + attributeMetadata.LogicalName; var tempEnumDefinition = new EnumDefinition { LogicalName = enumLogicalName, IsGlobal = meta.IsGlobal.Value, HasNullValue = attributeMetadata.AttributeType.Value == AttributeTypeCode.Picklist }; if (attributeMetadata.AttributeType.Value == AttributeTypeCode.State) { tempEnumDefinition.Name = entityDefinition.Name.Replace("Definition", "") + "State"; } else if (attributeMetadata.AttributeType.Value == AttributeTypeCode.Status) { tempEnumDefinition.Name = entityDefinition.Name.Replace("Definition", "") + "Status"; } else { tempEnumDefinition.Name = meta.DisplayName.UserLocalizedLabel.Label.FormatText(); } foreach (var option in meta.Options) { tempEnumDefinition.Values.Add(new EnumValueDefinition { Name = option.Label.UserLocalizedLabel.Label.FormatText(), LogicalName = option.Value.Value.ToString(), DisplayName = option.Label.UserLocalizedLabel.Label, Value = option.Value.Value.ToString() }); } if (!EnumDefinitionCollection.Instance.Contains(enumLogicalName)) { enumDefinition = tempEnumDefinition; EnumDefinitionCollection.Instance.Add(enumDefinition); } else { enumDefinition = EnumDefinitionCollection.Instance[enumLogicalName]; enumDefinition.Merge(tempEnumDefinition); } } var name = RemovePrefix(attributeMetadata.SchemaName); if (attributeMetadata.LogicalName == entity.PrimaryIdAttribute) { name = "Id"; } var attributeDefinition = new AttributeDefinition { LogicalName = attributeMetadata.LogicalName, Name = name, DisplayName = attributeMetadata.DisplayName.UserLocalizedLabel == null ? attributeMetadata.SchemaName : attributeMetadata.DisplayName.UserLocalizedLabel.Label, IsValidForAdvancedFind = attributeMetadata.IsValidForAdvancedFind.Value, IsValidForCreate = attributeMetadata.IsValidForCreate.Value, IsValidForRead = attributeMetadata.IsValidForRead.Value, IsValidForUpdate = attributeMetadata.IsValidForUpdate.Value, Type = attributeMetadata.AttributeType.Value.ToString(), Enum = enumDefinition, ParentEntity = entityDefinition, IsPrimaryIdAttribute = attributeMetadata.LogicalName == entity.PrimaryIdAttribute, IsPrimaryNameAttribute = attributeMetadata.LogicalName == entity.PrimaryNameAttribute, IsPrimaryImageAttribute = attributeMetadata.LogicalName == entity.PrimaryImageAttribute, Relationships = lookupFields.ContainsKey(attributeMetadata.LogicalName) ? lookupFields[attributeMetadata.LogicalName] : null }; if (keyDefinition != null) { foreach (var key in entity.Keys.Where(k => k.KeyAttributes.Contains(attributeDefinition.LogicalName))) { attributeDefinition.KeyNames.Add(keyDefinition.Attributes[key.LogicalName].Name); } } if (attributeDefinition.IsPrimaryIdAttribute || attributeDefinition.IsPrimaryNameAttribute || attributeDefinition.IsPrimaryImageAttribute || attributeDefinition.KeyNames.Any()) { attributeDefinition.IsSelected = true; } entityDefinition.AttributesCollection.Add(attributeDefinition); } } SendStepChange(string.Empty); return entities; }
private Task <List <Privilege> > LoadPrivileges(Guid roleId) { return(Task.Run(() => { var query = new QueryExpression("privilege"); query.NoLock = true; query.ColumnSet = new ColumnSet("name", "accessright"); query.AddOrder("name", OrderType.Ascending); var typecode = query.AddLink("privilegeobjecttypecodes", "privilegeid", "privilegeid", JoinOperator.LeftOuter); typecode.EntityAlias = "privilegeobjecttypecode"; typecode.Columns = new ColumnSet("objecttypecode"); var intersect = query.AddLink("roleprivileges", "privilegeid", "privilegeid"); intersect.EntityAlias = "roleprivilege"; intersect.Columns = new ColumnSet("privilegedepthmask"); var role = intersect.AddLink("role", "roleid", "roleid"); role.LinkCriteria.AddCondition("roleid", ConditionOperator.Equal, roleId); var result = _service.RetrieveMultiple(query); return result.Entities.Select(e => new Privilege { PrivilegeId = e.Id, Name = e["name"] as string, AccessRight = GetAccessRight(e), LogicalName = GetEntityName(e), Depth = GetDepth(e) }).ToList(); })); }
/// <summary> /// Gets a list of Coastguard Codes from CRM where "Applies To" = Coastguard Region OR Coastguard Unit /// </summary> public List <Unit> GetUnits() { object[] codes = new object[] { (int)TagAppliesToCode.CoastguardRegion, (int)TagAppliesToCode.CoastguardUnit }; QueryExpression query = new QueryExpression { EntityName = "mag_tag" }; query.Criteria.AddCondition("mag_appliestocode", ConditionOperator.In, codes); query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); // active only var link1 = query.AddLink("businessunit", "mag_coastguardregionid", "businessunitid", JoinOperator.LeftOuter); link1.EntityAlias = "region"; link1.Columns = new ColumnSet("name"); var link2 = query.AddLink("mag_coastguardunit", "mag_coastguardunitid", "mag_coastguardunitid", JoinOperator.LeftOuter); link2.EntityAlias = "unit"; link2.Columns = new ColumnSet("mag_coastguardregionid"); query.AddOrder("mag_name", OrderType.Ascending); EntityCollection results = this._sdk.RetrieveMultiple(query); List <Unit> units = (from e in results.Entities.ToList() select new Unit { UnitCodeId = e.Id, Name = e.Get <string>("mag_name"), Region = e.Contains("region.name") ? e.Get <string>("region.name") : e.Contains("unit.mag_coastguardregionid") ? ((EntityReference)e.GetAttributeValue <AliasedValue>("unit.mag_coastguardregionid").Value).Name : "" }).ToList(); return(units.OrderBy(u => u.Name).ToList()); }
private Task <IEnumerable <User> > RetrieveUsers() { return(Task.Run(() => { var query = new QueryExpression("systemuser"); query.NoLock = true; query.ColumnSet = new ColumnSet("domainname", "fullname", "systemuserid"); query.AddOrder("fullname", OrderType.Ascending); if (SelectedRole.RoleId == Guid.Empty) { var userroles = query.AddLink("systemuserroles", "systemuserid", "systemuserid", JoinOperator.LeftOuter); userroles.EntityAlias = "roles"; query.Criteria.AddCondition("roles", "roleid", ConditionOperator.Null); } else { var userroles = query.AddLink("systemuserroles", "systemuserid", "systemuserid"); userroles.LinkCriteria.AddCondition("roleid", ConditionOperator.Equal, SelectedRole.RoleId); } var result = _service.RetrieveMultiple(query); var users = result.Entities.Select(e => new User { UserId = e.Id, DomainName = e.Contains("domainname") ? e["domainname"] as string : null, FullName = e.Contains("fullname") ? e["fullname"] as string : null }); return users; })); }
/// <summary> /// Retrieves a reinsurance contract for insured cover based on the policy version inception date and reinsurance contract /// connections to individual covers. /// </summary> /// <param name="context">Local plug-in context.</param> /// <param name="insuredCover">Insured cover, for which Reinsurance contract will be retrieved</param> /// <param name="method">Reinsurance method (arrangement) to filter reinsurance contracts.</param> /// <returns></returns> public ReinsuranceContract RetrieveReinsuranceContract(ReinsuranceSectionMethod?method = null) { var policyVersion = this.PolicyVersion; if (policyVersion.TransactionType == PolicyVersionTransactionType.Quote) { return(null); } var contractQuery = new QueryExpression("new_reinsuranceagreement"); contractQuery.ColumnSet.AllColumns = true; // policy version inception date must be between contract's inception and expiry contractQuery.Criteria.AddCondition("new_incepciondate", ConditionOperator.OnOrBefore, policyVersion.TransactionEffectiveDate); contractQuery.Criteria.AddCondition("new_expirydate", ConditionOperator.OnOrAfter, policyVersion.TransactionEffectiveDate); if (method != null) { var sectionLink = contractQuery.AddLink("new_reinscontract", "new_reinsuranceagreementid", "new_reinsuranceagreement"); sectionLink.LinkCriteria.AddCondition("new_reinsurancearrangement", ConditionOperator.Equal, (int)method.Value); } var reinsuredCoverLink = contractQuery.AddLink("new_reinsuredcover", "new_reinsuranceagreementid", "new_reinsuranceagreement"); reinsuredCoverLink.LinkCriteria.AddCondition("new_cover", ConditionOperator.Equal, this.CoverRef.Id); var contracts = this.OrgService.RetrieveMultiple(contractQuery).Entities; return(contracts.Select(e => new ReinsuranceContract(this.OrgService, this.TracingService, e)).FirstOrDefault()); }
public static IEnumerable <Entity> RetrievePerilSectionsForProduct(this IOrganizationService svc, Guid productId) { var query1 = new QueryExpression("new_cover"); query1.ColumnSet.AddColumns("new_name", "new_coverbasepercentage", "statecode", "new_coverid"); query1.Criteria.AddCondition("new_productid", ConditionOperator.Equal, productId); //query1.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); var link = query1.AddLink("new_product", "new_productid", "new_productid"); link.Columns.AddColumn("new_code"); link.EntityAlias = "PR"; var link1 = query1.AddLink("new_regulatoryclass", "new_firstlevelregulatoryclassid", "new_regulatoryclassid"); link1.Columns.AddColumn("new_regulatoryclasscode"); link1.EntityAlias = "REG"; var link2 = query1.AddLink("new_reportingclass", "new_reportingclass", "new_reportingclassid"); link2.Columns.AddColumn("new_reportingclasscode"); link2.EntityAlias = "REP"; var link3 = query1.AddLink("new_lobclass", "new_lobclass", "new_lobclassid"); link3.Columns.AddColumn("new_lobclasscode"); link3.EntityAlias = "LOB"; var link4 = query1.AddLink("new_risk", "new_riskid", "new_riskid"); link4.Columns.AddColumns("new_riskcode", "new_name"); link4.EntityAlias = "COV"; return(svc.RetrieveMultiple(query1).Entities); }
private bool HasMetricDetailsToMember(IOrganizationService service, find_metric metric, EntityReference memberReference) { QueryExpression QEfind_metricdetails = new QueryExpression("find_metricdetails"); QEfind_metricdetails.ColumnSet.AddColumns("find_name"); QEfind_metricdetails.Criteria.AddCondition("find_metric", "find_metricid", ConditionOperator.Equal, metric.Id); QEfind_metricdetails.AddLink("find_metric", "find_lookupmetric", "find_metricid"); switch (memberReference.LogicalName) { case "account": QEfind_metricdetails.Criteria.AddCondition("account", "accountid", ConditionOperator.Equal, memberReference.Id); QEfind_metricdetails.AddLink("account", "find_lookupaccount", "accountid"); break; case "contact": QEfind_metricdetails.Criteria.AddCondition("contact", "contactid", ConditionOperator.Equal, memberReference.Id); QEfind_metricdetails.AddLink("contact", "find_lookupcontact", "contactid"); break; case "lead": QEfind_metricdetails.Criteria.AddCondition("lead", "leadid", ConditionOperator.Equal, memberReference.Id); QEfind_metricdetails.AddLink("contact", "find_lookuplead", "leadid"); break; } return(service.RetrieveMultiple(QEfind_metricdetails).Entities.Count != 0); }
/// <summary> /// Returns a summarised text of all permit lines /// </summary> /// <param name="service">CRM organisation service</param> /// <param name="permitId">permit id to query</param> /// <returns>Descriptive text for all permit facilities</returns> public static string GetPermitLinesSummary(IOrganizationService service, Guid permitId) { // Set-up query var query = new QueryExpression(defra_permit_lines.EntityLogicalName); query.Criteria.AddCondition(defra_permit_lines.Fields.defra_permitid, ConditionOperator.Equal, permitId); // Filter by application FilterExpression notNullFilter = new FilterExpression { FilterOperator = LogicalOperator.Or }; notNullFilter.AddCondition(defra_permit_lines.Fields.defra_itemid, ConditionOperator.NotNull); notNullFilter.AddCondition(defra_permit_lines.Fields.defra_standardruleid, ConditionOperator.NotNull); query.Criteria.AddFilter(notNullFilter); // Link to standard rule entity const string aliasStandarRule = "sr"; LinkEntity srLink = query.AddLink(defra_standardrule.EntityLogicalName, defra_permit_lines.Fields.defra_standardruleid, defra_standardrule.Fields.defra_standardruleId, JoinOperator.LeftOuter); srLink.EntityAlias = aliasStandarRule; srLink.Columns.AddColumns(defra_standardrule.Fields.defra_name, defra_standardrule.Fields.defra_rulesnamegovuk); // Link to item entity const string aliasItem = "item"; LinkEntity itemLink = query.AddLink(defra_item.EntityLogicalName, defra_permit_lines.Fields.defra_itemid, defra_item.Fields.defra_itemId, JoinOperator.LeftOuter); itemLink.EntityAlias = aliasItem; itemLink.Columns.AddColumns(defra_item.Fields.defra_code, defra_item.Fields.defra_officialname); // TODO return(null); }
/// <summary> /// Returns a summarised text of all application lines /// </summary> /// <param name="service">CRM organisation service</param> /// <param name="applicationId">application id to query</param> /// <returns>Descriptive text for all application facilities</returns> public static string GetApplicationLinesSummary(IOrganizationService service, Guid applicationId) { // Set-up query var query = new QueryExpression(defra_applicationline.EntityLogicalName); query.Criteria.AddCondition(defra_applicationline.Fields.defra_applicationId, ConditionOperator.Equal, applicationId); // Filter by application FilterExpression notNullFilter = new FilterExpression { FilterOperator = LogicalOperator.Or }; notNullFilter.AddCondition(defra_applicationline.Fields.defra_itemid, ConditionOperator.NotNull); notNullFilter.AddCondition(defra_applicationline.Fields.defra_standardruleId, ConditionOperator.NotNull); query.Criteria.AddFilter(notNullFilter); // Link to standard rule entity const string aliasStandarRule = "sr"; LinkEntity srLink = query.AddLink(defra_standardrule.EntityLogicalName, defra_applicationline.Fields.defra_standardruleId, defra_standardrule.Fields.defra_standardruleId, JoinOperator.LeftOuter); srLink.EntityAlias = aliasStandarRule; srLink.Columns.AddColumns(defra_standardrule.Fields.defra_name, defra_standardrule.Fields.defra_rulesnamegovuk); // Link to item entity const string aliasItem = "item"; LinkEntity itemLink = query.AddLink(defra_item.EntityLogicalName, defra_applicationline.Fields.defra_itemid, defra_item.Fields.defra_itemId, JoinOperator.LeftOuter); itemLink.EntityAlias = aliasItem; itemLink.Columns.AddColumns(defra_item.Fields.defra_code, defra_item.Fields.defra_officialname); // Call CRM EntityCollection result = service.RetrieveMultiple(query); // Check the results if (result?.Entities == null) { // No Results return(string.Empty);; } foreach (Entity line in result.Entities) { if (line.Contains($"{aliasStandarRule}.{defra_standardrule.Fields.defra_rulesnamegovuk}")) { // TODO } } return(null); }
private Entity ReturnEmailData(Guid recordId) { var queryEmail = new QueryExpression(Email.EntityLogicalName); queryEmail.TopCount = 1; // Add columns for Email entity queryEmail.ColumnSet.AddColumns(Email.Fields.Description, Email.Fields.Subject, Email.Fields.ActivityId, Email.Fields.StatusCode, Email.Fields.RegardingObjectId, Email.Fields.DirectionCode, Email.Fields.Sender, Email.Fields.ToRecipients, Email.Fields.CreatedOn, Email.Fields.defra_uploadedtosharepoint); // Define filter queryEmail.Criteria.AddCondition(Email.Fields.ActivityId, ConditionOperator.Equal, recordId); // Add Application link-entity and define an alias. // Its an outer join as we want to return results even if not regarding an application var queryEmailApplication = queryEmail.AddLink(Application.EntityLogicalName, Email.Fields.RegardingObjectId, Application.ApplicationId, JoinOperator.LeftOuter); queryEmailApplication.EntityAlias = "application"; // Add columns for Application link entity queryEmailApplication.Columns.AddColumns(Application.ApplicationNumber, Application.Name, Application.PermitNumber); // Add link-entity to Case and define an alias. // Its an outer join as we want to return results even if not regarding a case var queryEmailIncident = queryEmail.AddLink(Case.EntityLogicalName, Case.RegardingObjectId, Case.IncidentId, JoinOperator.LeftOuter); queryEmailIncident.EntityAlias = "case"; // Add columns for Case link entity queryEmailIncident.Columns.AddColumns(Case.CaseType, Case.Title, Case.IncidentId, Case.TicketNumber); // Add link-entity from Case to Application and define an alias var queryEmailIncidentApplication = queryEmailIncident.AddLink(Application.EntityLogicalName, Case.Application, Application.ApplicationId, JoinOperator.LeftOuter); queryEmailIncidentApplication.EntityAlias = "case.application"; // Add columns to for Application entity regarding the Case queryEmailIncidentApplication.Columns.AddColumns(Application.ApplicationNumber, Application.Name, Application.PermitNumber, defra_application.Fields.defra_applicationId); var results = Service.RetrieveMultiple(queryEmail); if (results != null && results.Entities.Count >= 1) { CrmExtensions.TraceEntity(TracingService, results.Entities[0]); return(results.Entities[0]); } return(null); }
public void Should_Allow_Using_Aliases_with_Dot() { var contact = new Entity("contact") { Id = Guid.NewGuid() }; contact["firstname"] = "Jordi"; var account = new Entity("account") { Id = Guid.NewGuid() }; account["primarycontactid"] = contact.ToEntityReference(); account["name"] = "Dynamics Value"; var context = new XrmFakedContext(); context.Initialize(new Entity[] { contact, account }); var service = context.GetOrganizationService(); QueryExpression query = new QueryExpression("account"); query.ColumnSet = new ColumnSet("name"); var link = query.AddLink("contact", "contactid", "primarycontactid"); link.EntityAlias = "primary.contact"; link.Columns = new ColumnSet("firstname"); var accounts = service.RetrieveMultiple(query); Assert.True(accounts.Entities.First().Contains("primary.contact.firstname")); Assert.Equal("Jordi", accounts.Entities.First().GetAttributeValue <AliasedValue>("primary.contact.firstname").Value); }
public void Can_Filter_Using_Entity_Name_With_Alias() { XrmFakedContext context = new XrmFakedContext(); IOrganizationService service = context.GetOrganizationService(); Entity e = new Entity("contact") { Id = Guid.NewGuid(), ["retrieve"] = true }; Entity e2 = new Entity("account") { Id = Guid.NewGuid(), ["contactid"] = e.ToEntityReference() }; context.Initialize(new Entity[] { e, e2 }); QueryExpression query = new QueryExpression("account"); query.Criteria.AddCondition("mycontact", "retrieve", ConditionOperator.Equal, true); query.AddLink("contact", "contactid", "contactid").EntityAlias = "mycontact"; EntityCollection result = service.RetrieveMultiple(query); Assert.Equal(1, result.Entities.Count); }
public ImportJob GetLatest(IOrganizationService service) { var query = new QueryExpression("importjob") { TopCount = 1, NoLock = true }; query.ColumnSet.AddColumns( nameof(solutionname), nameof(progress), nameof(startedon), nameof(completedon), nameof(createdon), nameof(createdby), nameof(data)); var solutionLink = query.AddLink("solution", "solutionid", "solutionid", JoinOperator.LeftOuter); solutionLink.EntityAlias = "s"; solutionLink.Columns.AddColumns( nameof(uniquename), nameof(friendlyname), nameof(description), nameof(publisherid), nameof(version)); query.AddOrder(nameof(startedon), OrderType.Descending); var importJob = service.RetrieveMultiple(query).Entities.Select(x => new ImportJob(x)).FirstOrDefault(); return(importJob); }
protected override void Execute(CodeActivityContext context) { _IWorkflowContext = context.GetExtension <IWorkflowContext>(); _IOrganizationServiceFactory = context.GetExtension <IOrganizationServiceFactory>(); _OrgService = _IOrganizationServiceFactory.CreateOrganizationService(_IWorkflowContext.UserId); try { Guid roleId = securityRole.Get <EntityReference>(context).Id; var roleQuery = new QueryExpression("role"); roleQuery.ColumnSet.AddColumns("name"); roleQuery.Criteria.AddCondition("systemuserroles", "systemuserid", ConditionOperator.Equal, _IWorkflowContext.UserId); var queryExpression_systemuserroles = roleQuery.AddLink("systemuserroles", "roleid", "roleid"); EntityCollection roleRecords = _OrgService.RetrieveMultiple(roleQuery); foreach (var role in roleRecords.Entities) { var id = role.Id; if (roleId == id) { hasRole.Set(context, true); } break; } } catch (Exception ex) { throw new InvalidPluginExecutionException("Custom Step: " + ex.Message); } }
/// <exception cref="Exception">Thrown when unknown communication type was finded</exception> public IEnumerable <Data> GetEntitiesForUpdate() { QueryExpression query = new QueryExpression(Constants.Communication.ENTITYNAME) { ColumnSet = new ColumnSet( Constants.Communication.Fields.CONTACTID, Constants.Communication.Fields.TYPE, Constants.Communication.Fields.PHONE, Constants.Communication.Fields.EMAIL), NoLock = true, }; LinkEntity contactLink = query.AddLink( Constants.Contact.ENTITYNAME, Constants.Communication.Fields.CONTACTID, Constants.Contact.Fields.CONTACTID, JoinOperator.Inner); contactLink.Columns = new ColumnSet( Constants.Contact.Fields.PHONE, Constants.Contact.Fields.EMAIL); contactLink.EntityAlias = Constants.Communication.PARSERALIAS; query.Criteria.AddCondition(Constants.Communication.Fields.MAIN, ConditionOperator.Equal, true); EntityCollection result = _Service.RetrieveMultiple(query); return(ParseEntities(result.Entities)); }
/// <summary> /// Gets the latest active membership of a member. /// </summary> public Guid GetLatestActiveMembershipId(string membershipNumber, bool ignoreLifeTimeMemberships = false) { QueryExpression query = new QueryExpression { EntityName = "mag_membership" }; query.Criteria.AddCondition("mag_idnumber", ConditionOperator.Equal, membershipNumber); //query.Criteria.AddCondition("statuscode", ConditionOperator.Equal, 809730001); // active query.Criteria.AddCondition("statuscode", ConditionOperator.In, new object[] { 809730001, 809730005 }); // active OR service end - PN - 27/11/13 query.AddOrder("mag_startdate", OrderType.Descending); // this is used by the renewal process, lifetime memberships dont need to be renewd if (ignoreLifeTimeMemberships) { LinkEntity le = query.AddLink("product", "mag_membershiptypeid", "productid", JoinOperator.Inner); //le.LinkCriteria.AddCondition("name", ConditionOperator.NotEqual, "Lifetime Membership"); LinkEntity unit = le.AddLink("uom", "defaultuomid", "uomid", JoinOperator.Inner); // Needs to look at the Unit name, as many products can be lifetime memberships - PN - 27/11/13 unit.LinkCriteria.AddCondition("name", ConditionOperator.NotEqual, "Lifetime"); } EntityCollection results = this._sdk.RetrieveMultiple(query); if (results != null && results.Entities != null && results.Entities.Count > 0) { return(results[0].Get <Guid>("mag_membershipid")); } return(Guid.Empty); }
public List <Entity> RetrieveEtablissementForMisson(string idMission) { var result = new List <Entity>(); QueryExpression queryExp = new QueryExpression(); queryExp.EntityName = "new_etablissementjkwe"; queryExp.ColumnSet = new ColumnSet(); queryExp.ColumnSet.Columns.Add("new_name"); queryExp.ColumnSet.Columns.Add("new_etablissementjkweid"); LinkEntity link = queryExp.AddLink("new_new_etablissementjkwe_new_missionjkwe", "new_etablissementjkweid", "new_etablissementjkweid", JoinOperator.Inner); link.Columns.AddColumn("new_missionjkweid"); link.EntityAlias = "etablissementsliees"; queryExp.Criteria = new FilterExpression(); queryExp.Criteria.AddCondition("etablissementsliees", "new_missionjkweid", ConditionOperator.Equal, idMission); EntityCollection contCollection = orgService.RetrieveMultiple(queryExp); if (contCollection.Entities.Count > 0) { result.AddRange(contCollection.Entities.ToList()); } return(result); }
private void RemoveRoles(Team team) { var query = new QueryExpression("role"); query.Distinct = true; query.ColumnSet = new ColumnSet("roleid"); if (team.SecurityRoles != null && team.SecurityRoles.Count > 0) { query.Criteria.AddCondition("name", ConditionOperator.NotIn, team.SecurityRoles.ToArray()); } query.Criteria.AddCondition("businessunitid", ConditionOperator.Equal, team.DestinationBusinessUnitId); var teamLink = query.AddLink("teamroles", "roleid", "roleid", JoinOperator.Inner); teamLink.LinkCriteria.AddCondition("teamid", ConditionOperator.Equal, team.TeamId); var result = OrganizationService.RetrieveMultiple(query); if (result == null || result.Entities == null || result.Entities.Count == 0) { // Nothing to remove return; } var roles = result.Entities .Select(e => new EntityReference("role", e.Id)) .ToList(); OrganizationService.Disassociate("team", team.TeamId, new Relationship("teamroles_association"), new EntityReferenceCollection(roles)); }
public bool IsTeamMember(String teamname, Guid userId) { _tracing.Trace("CrmHelper.IsTeamMember"); if (teamname == null) { throw new ArgumentNullException("teamname"); } //No I don't normally use ColumnSet(true) in real-world code! :) var query = new QueryExpression("team") { ColumnSet = new ColumnSet(true) }; query.Criteria.AddCondition(new ConditionExpression("name", ConditionOperator.Equal, teamname)); var link = query.AddLink("teammembership", "teamid", "teamid"); link.LinkCriteria.AddCondition(new ConditionExpression("systemuserid", ConditionOperator.Equal, userId)); try { var results = _service.RetrieveMultiple(query); return(results.Entities.Count > 0); } catch (Exception ex) { _tracing.Trace( "Exception Verifying User {0} is a member of team {1}. Error: {2} / Inner Exception {3}. Stack Trace: {4}", userId, teamname, ex.Message, ex.InnerException != null ? ex.InnerException.Message : "(None)", ex.StackTrace); throw; } }
public bool IsSystemAdministrator(Guid userId) { bool isAdmin = false; var query = new QueryExpression("role") { Criteria = new FilterExpression(LogicalOperator.And) { Conditions = { new ConditionExpression("roletemplateid", ConditionOperator.Equal, new Guid(AdminRoleTemplateId)) } } }; var link = query.AddLink("systemuserroles", "roleid", "roleid"); link.LinkCriteria.AddCondition("systemuserid", ConditionOperator.Equal, userId); var results = _organizationService.RetrieveMultiple(query); if (results.Entities != null) { isAdmin = results.Entities.Count > 0; } return(isAdmin); }
public bool IsFirstAgreement(Guid contactId, Guid agreementId) { QueryExpression query = new QueryExpression(Common.Entities.nav_agreement.EntityLogicalName); query.ColumnSet = new ColumnSet(Common.Entities.nav_agreement.Fields.Id); query.NoLock = true; var link = query.AddLink(Common.Entities.Contact.EntityLogicalName, Common.Entities.nav_agreement.Fields.nav_contact, Common.Entities.Contact.Fields.Id); link.EntityAlias = "co"; query.Criteria.AddCondition(Common.Entities.Contact.Fields.Id, ConditionOperator.Equal, contactId); query.Criteria.AddCondition(Common.Entities.nav_agreement.Fields.Id, ConditionOperator.NotEqual, agreementId); var result = _service.RetrieveMultiple(query); if (result.TotalRecordCount == 0) { return(true); } else { return(false); } }
private Entity GetStatistics(string typename) { if (statistics == null) { statistics = new Dictionary <string, Entity>(); } if (!statistics.ContainsKey(typename)) { var qex = new QueryExpression("plugintypestatistic"); qex.ColumnSet.AddColumns("failurepercent", "terminatememorycontributionpercent", "averageexecutetimeinmilliseconds", "crashpercent", "crashcount", "terminatehandlescontributionpercent", "executecount", "failurecount", "terminatecpucontributionpercent", "modifiedon", "createdon", "terminateothercontributionpercent", "crashcontributionpercent"); var leType = qex.AddLink("plugintype", "plugintypeid", "plugintypeid"); leType.LinkCriteria.AddCondition("typename", ConditionOperator.Equal, typename); var res = ptv.Service.RetrieveMultiple(qex); if (res.Entities.Count == 1) { statistics.Add(typename, res[0]); } } if (statistics.ContainsKey(typename)) { return(statistics[typename]); } return(null); }
protected override void ExecuteWorkflowLogic() { var emailId = Email.Get(Context.ExecutionContext).Id; var email = Context.UserService.Retrieve("email", emailId, new ColumnSet("to")); var to = email.Contains("to") ? email.GetAttributeValue <EntityCollection>("to") : new EntityCollection(); var userQuery = new QueryExpression("systemuser") { ColumnSet = new ColumnSet(false) }; var teamLink = userQuery.AddLink("teammembership", "systemuserid", "systemuserid"); teamLink.LinkCriteria.AddCondition("teamid", ConditionOperator.Equal, Team.Get(Context.ExecutionContext).Id); var users = QueryWithPaging(userQuery); users.ForEach(u => { to.Entities.Add(new Entity("activityparty") { ["partyid"] = u.ToEntityReference() }); }); email["to"] = to; Context.UserService.Update(email); if (SendAfterOperation.Get(Context.ExecutionContext)) { base.ExecuteWorkflowLogic(); } }
public static QueryExpression ConvertFetchToQueryExpression(LocalCrmDatabaseOrganizationService service, FetchType fe) { var fetchEntity = ((FetchEntityType)fe.Items[0]); var qe = new QueryExpression(fetchEntity.name); var idName = EntityHelper.GetIdAttributeName(fetchEntity.name); var entityLink = qe.AddLink(fetchEntity.name, idName, idName); foreach (dynamic item in fetchEntity.Items) { ProcessFetchXmlItem(service, entityLink, item); } if (!fe.aggregateSpecified) { // Move ColumnSet for entityLink to qe. Not sure if the entity link is really needed... qe.ColumnSet.AddColumns(entityLink.Columns.Columns.ToArray()); entityLink.Columns.Columns.Clear(); // Remove LinkEntity... again, not sure if it is really needed for aggregates, but believe it was at one time... qe.LinkEntities.Clear(); qe.Criteria = entityLink.LinkCriteria; qe.LinkEntities.AddRange(entityLink.LinkEntities); } return(qe); }
public int TipoAcessoPortal(string login) { int representante = 0, assistenciaTecnica = 0; var queryHelper = new QueryExpression("new_permissao_usuario_b2b"); queryHelper.ColumnSet.AllColumns = true; queryHelper.AddLink("contact", "new_contatoid", "contactid"); queryHelper.LinkEntities[0].LinkCriteria.Conditions.Add(new ConditionExpression("new_login", ConditionOperator.Equal, login)); var bec = base.Provider.RetrieveMultiple(queryHelper); if (bec.Entities.Count > 0) { foreach (Entity item in bec.Entities) { if (item.Attributes.Contains("itbc_codigo_representante")) { representante = 1; } else if (item.Attributes.Contains("new_unidade_negocioid")) { assistenciaTecnica = 2; } } } return(representante + assistenciaTecnica); }
private static EntityReference[] GetMatchingSteps(bool isEnabled, string[] pluginPatternsToToggle) { var stepQuery = new QueryExpression("sdkmessageprocessingstep"); stepQuery.ColumnSet.AddColumns("sdkmessageprocessingstepid", "name"); stepQuery.Criteria.AddCondition("statecode", ConditionOperator.Equal, isEnabled ? 0 : 1); var typeLink = stepQuery.AddLink("plugintype", "eventhandler", "plugintypeid"); typeLink.EntityAlias = "typeAliased"; typeLink.Columns.AddColumns("name"); var assemblyLink = typeLink.AddLink("pluginassembly", "pluginassemblyid", "pluginassemblyid"); assemblyLink.EntityAlias = "assemblyAliased"; assemblyLink.Columns.AddColumns("name"); return(Service.RetrieveMultiple(stepQuery).Entities .Select(step => new { stepId = step.Id, stepName = step.GetAttributeValue <string>("name"), typeName = (string)step.GetAttributeValue <AliasedValue>("typeAliased.name").Value, assemblyName = (string)step.GetAttributeValue <AliasedValue>("assemblyAliased.name").Value }) .ToArray() .Where(s => pluginPatternsToToggle.Any(n => Regex.IsMatch(s.stepName, n)) || pluginPatternsToToggle.Any(n => Regex.IsMatch(s.typeName, n)) || pluginPatternsToToggle.Any(n => Regex.IsMatch(s.assemblyName, n))) .Select(s => new EntityReference(SdkMessageProcessingStep.EntityLogicalName, s.stepId)) .ToArray()); }
private void PopulateStats() { var qex = new QueryExpression(PluginTypeStatistic.EntityName); qex.ColumnSet.AddColumns( PluginTypeStatistic.CreatedOn, PluginTypeStatistic.ModifiedOn, PluginTypeStatistic.ExecuteCount, PluginTypeStatistic.Averageexecutetimeinmilliseconds, PluginTypeStatistic.FailureCount, PluginTypeStatistic.FailurePercent, PluginTypeStatistic.CrashCount, PluginTypeStatistic.CrashPercent, PluginTypeStatistic.CrashcontributionPercent, PluginTypeStatistic.TerminatememorycontributionPercent, PluginTypeStatistic.TerminatehandlescontributionPercent, PluginTypeStatistic.TerminatecpucontributionPercent, PluginTypeStatistic.TerminateothercontributionPercent); var leplugin = qex.AddLink(PluginType.EntityName, PluginType.PrimaryKey, PluginTypeStatistic.PluginTypeId, JoinOperator.LeftOuter); leplugin.EntityAlias = PluginTypeAlias; leplugin.Columns.AddColumns(PluginType.PrimaryName); var stats = _service.RetrieveMultiple(qex); foreach (var stat in stats.Entities) { var secperday = StatsControl.GetStatTimePerDay(stat); stat["secondsperday"] = secperday; } gridPluginStats.DataSource = stats; gridPluginStats.AutoResizeColumns(); }
/// <summary> /// Returns all the locations and location details linked to the given application /// </summary> /// <param name="service">CRM Organisation Service</param> /// <param name="applicationId">Application Id to return locations for</param> /// <param name="permitId">Permit Id to return locations for</param> /// <returns>List of Locations and location details</returns> public static Entity[] GetLocationAndLocationDetails(IOrganizationService service, Guid?applicationId, Guid?permitId) { // Set-up Location Query QueryExpression qEdefraLocation = new QueryExpression(Location.EntityLogicalName) { TopCount = 1000 }; qEdefraLocation.ColumnSet.AddColumns(Location.State, Location.Name, Location.LocationCode, Location.Application, Location.LocationId, Location.Permit, Location.HighPublicInterest, Location.Status, Location.OwnerId); qEdefraLocation.Criteria.AddCondition(Location.State, ConditionOperator.Equal, (int)defra_locationState.Active); // Application Locations? if (applicationId.HasValue) { qEdefraLocation.Criteria.AddCondition(Location.Application, ConditionOperator.Equal, applicationId); } // Permit Locations? if (permitId.HasValue) { qEdefraLocation.Criteria.AddCondition(Location.Permit, ConditionOperator.Equal, permitId); } // Add link-entity defra_locationdetails LinkEntity qEdefraLocationDefraLocationdetails = qEdefraLocation.AddLink(LocationDetail.EntityLogicalName, Location.LocationId, LocationDetail.Location, JoinOperator.LeftOuter); qEdefraLocationDefraLocationdetails.EntityAlias = LocationDetail.Alias; qEdefraLocationDefraLocationdetails.Columns.AddColumns(LocationDetail.State, LocationDetail.Location, LocationDetail.Address, LocationDetail.Name, LocationDetail.GridReference, LocationDetail.Status, LocationDetail.LocationDetailId, LocationDetail.Owner); // Only retrieve active location details qEdefraLocationDefraLocationdetails.LinkCriteria.AddCondition(LocationDetail.State, ConditionOperator.Equal, (int)defra_locationdetailsState.Active); // Query CRM return(service.RetrieveMultiple(qEdefraLocation).Entities.ToArray()); }
public static QueryExpression SelectCommentsByPage(PagingInfo pageInfo, Guid regardingobjectid, bool includeUnapprovedComments, bool?chronologicalComments = null) { var query = new QueryExpression("feedback") { PageInfo = pageInfo }; query.Criteria.AddCondition("regardingobjectid", ConditionOperator.Equal, regardingobjectid); query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); query.Criteria.AddCondition("comments", ConditionOperator.NotNull); if (!includeUnapprovedComments) { query.Criteria.AddCondition("adx_approved", ConditionOperator.Equal, true); } query.ColumnSet = new ColumnSet() { Columns = { "createdbycontact", "adx_createdbycontact", "adx_authorurl", "adx_contactemail", "comments", "createdon", "title", "createdbycontact", "adx_approved" } }; query.AddOrder("createdon", chronologicalComments == null || chronologicalComments.Value ? OrderType.Ascending : OrderType.Descending); LinkEntity link = query.AddLink("contact", "createdbycontact", "contactid", JoinOperator.LeftOuter); link.EntityAlias = "author"; link.Columns.AddColumn("fullname"); link.Columns.AddColumn("firstname"); link.Columns.AddColumn("lastname"); link.Columns.AddColumn("emailaddress1"); return(query); }
/// <summary> /// Gets the time zone name from time zone. /// </summary> /// <param name="service">The service.</param> /// <param name="timeZoneId">The time zone id.</param> /// <param name="context">The context.</param> /// <param name="incidentId">The incident.</param> /// <returns>Get Offset</returns> public static string GetTimeZoneNameFromTimeZone(IOrganizationService service, Guid buildingId) { int optionsetValue; string optionsetText = string.Empty; try { if (service != null) { QueryExpression timezonequery = new QueryExpression() { EntityName = "smp_timezone", ColumnSet = new ColumnSet("smp_offset") }; timezonequery.AddLink("smp_building", "smp_timezoneid", "smp_timezoneid", JoinOperator.Inner) .LinkCriteria.AddCondition("smp_buildingid", ConditionOperator.Equal, buildingId); EntityCollection zoneNames = service.RetrieveMultiple(timezonequery); if (zoneNames.Entities.Count > 0) { optionsetValue = ((OptionSetValue)zoneNames.Entities[0]["smp_offset"]).Value; optionsetText = GetOptionsSetTextOnValue(service, "smp_timezone", "smp_offset", optionsetValue); } } return(optionsetText); } catch (Exception ex) { CustomServiceManagementPortalException customEx = new CustomServiceManagementPortalException("Exception while getting offset from Time Zone", ex); throw customEx; } }
private EntityReference GetPluginTypeReference(IOrganizationService service, string assemblyName, string pluginName) { var query = new QueryExpression { EntityName = CrmData.PluginTypeEntityName, ColumnSet = new ColumnSet(CrmData.PluginType_Id) }; query.Criteria.AddCondition( CrmData.PluginType_TypeName, ConditionOperator.Equal, pluginName); var assemblyLink = query.AddLink( CrmData.PluginAssemblyEntityName, CrmData.PluginType_PluginAssemblyId, CrmData.PluginAssembly_Id); assemblyLink.LinkCriteria.AddCondition( CrmData.PluginAssembly_Name, ConditionOperator.Equal, assemblyName); var pluginTypes = service.RetrieveMultiple(query); var pluginType = pluginTypes.Entities.First(); return(pluginType.ToEntityReference()); }
public List<Team> RetrieveTeams() { var query = new QueryExpression("team"); query.NoLock = true; query.Distinct = true; query.ColumnSet = new ColumnSet(true); query.Criteria.AddCondition("isdefault", ConditionOperator.Equal, false); query.Criteria.AddCondition("systemmanaged", ConditionOperator.Equal, false); var bu = query.AddLink("businessunit", "businessunitid", "businessunitid", JoinOperator.Inner); bu.EntityAlias = "businessunitid"; bu.Columns = new ColumnSet("parentbusinessunitid"); var admin = query.AddLink("systemuser", "administratorid", "systemuserid", JoinOperator.LeftOuter); admin.EntityAlias = "administratorid"; admin.Columns = new ColumnSet("domainname"); var result = OrganizationService.RetrieveMultiple(query); return result.Entities.Select(e => { var roles = LoadSecurityRoles(e.Id); return new Team { TeamId = e.Id, Name = e["name"] as string, Type = e.FormattedValues["teamtype"], IsInRootBusinessUnit = GetIsUnderDefaultBusinessUnit(e), BusinessUnit = GetNameFromEntityReference(e, "businessunitid"), AdministratorDomainName = GetAdministrator(e), AdministratorFullName = GetNameFromEntityReference(e, "administratorid"), Currency = GetNameFromEntityReference(e, "transactioncurrencyid"), Attributes = e.Attributes .Where(a => !_attributesToSkip.Contains(a.Key)) .ToDictionary(a => a.Key, a => a.Value), SecurityRoles = roles }; }).OrderBy(e => e.Name).ToList(); }
object DoConnect(object arg) { SendStepChange("Connecting..."); _service = new OrganizationService("Xrm"); _service.Execute(new WhoAmIRequest()); SendStepChange("Connected!"); var solutionName = ConfigHelper.GetEntitiesSolutionUniqueName(); var query = new QueryExpression(Solution.EntityLogicalName); query.ColumnSet.AllColumns = true; query.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solutionName); var linkPublisher = query.AddLink(Publisher.EntityLogicalName, "publisherid", "publisherid"); linkPublisher.EntityAlias = "publisher"; linkPublisher.Columns.AddColumn("customizationprefix"); _solution = _service.RetrieveMultiple(query).Entities.Select(s => s.ToEntity<Solution>()).FirstOrDefault(); return _service; }
private IEnumerable<XrmAutonumber> GetAutonumbers(IEnumerable<ConditionExpression> conditions) { var query = new QueryExpression(Entities.jmcg_autonumber); query.ColumnSet = new ColumnSet(true); if (conditions != null) { foreach (var item in conditions) query.Criteria.AddCondition(item); } var link = query.AddLink(Entities.jmcg_autonumber, Fields.jmcg_autonumber_.jmcg_parentautonumber, Fields.jmcg_autonumber_.jmcg_autonumberid); link.JoinOperator = JoinOperator.LeftOuter; link.EntityAlias = ParentAlias; link.Columns = new ColumnSet(true); return XrmService.RetrieveAll(query) .Select(e => new XrmAutonumber(e)) .ToArray(); }
static public bool TeamMasterLogicMethod(IOrganizationService service, Guid User) { QueryExpression teamQuery = new QueryExpression("team"); ColumnSet teamColumnSet = new ColumnSet("name"); teamQuery.ColumnSet = teamColumnSet; teamQuery.Criteria = new FilterExpression(); teamQuery.Criteria.FilterOperator = LogicalOperator.And; // teamQuery.Criteria.AddCondition("name", ConditionOperator.Equal, "Sales"); teamQuery.AddLink("teammembership", "teamid", "teamid").AddLink("systemuser", "systemuserid", "systemuserid").LinkCriteria.AddCondition("systemuserid", ConditionOperator.Equal, User); EntityCollection teamDetail = service.RetrieveMultiple(teamQuery); foreach (Entity ent in teamDetail.Entities) { string query = generateFetchForTeamMaster(ent.Id.ToString()); if (retrievePermision(service, query)) return true; } return false; }
public void When_querying_nested_link_entities_with_dynamic_entities_right_result_is_returned() { // create a contact var contactId = Guid.NewGuid(); var contact = new Entity { LogicalName = "contact", Id = contactId, Attributes = new AttributeCollection { { "contactid", contactId } } }; // link a child to the contact var childId = Guid.NewGuid(); var child = new Entity { LogicalName = "child", Id = childId, Attributes = new AttributeCollection { { "childid", childId }, { "contactid", new EntityReference("contact", contact.Id) } } }; // link a pet to the child var petId = Guid.NewGuid(); var pet = new Entity { LogicalName = "pet", Id = petId, Attributes = new AttributeCollection { { "petid", petId }, { "childid", new EntityReference("child", child.Id) } } }; // initialise var context = new XrmFakedContext(); context.Initialize(new[] { contact, child, pet }); var service = context.GetFakedOrganizationService(); // 1st Query: join contact and child //var query1 = new QueryExpression("contact"); //var link1 = query1.AddLink("child", "contactid", "contactid", JoinOperator.Inner); //var count1 = service.RetrieveMultiple(query1).Entities.Count; //Console.WriteLine(count1); // returns 1 record (expected) // 2nd Query: join contact and child and pet var query2 = new QueryExpression("contact"); var link2 = query2.AddLink("child", "contactid", "contactid", JoinOperator.Inner); var link22 = link2.AddLink("pet", "childid", "childid", JoinOperator.Inner); var count2 = service.RetrieveMultiple(query2).Entities.Count; Assert.Equal(1, count2); // returns 0 records (unexpected?) }
private Task<List<Assembly>> LoadAssemblies() { return Task.Run(() => { var query = new QueryExpression("pluginassembly"); query.Distinct = true; query.NoLock = true; query.ColumnSet = new ColumnSet("name", "pluginassemblyid"); query.AddOrder("name", OrderType.Ascending); var type = query.AddLink("plugintype", "pluginassemblyid", "pluginassemblyid", JoinOperator.Inner); type.LinkCriteria.AddCondition("typename", ConditionOperator.NotLike, "Microsoft.Crm.%"); type.LinkCriteria.AddCondition("typename", ConditionOperator.NotLike, "ActivityFeeds.%"); var result = _service.RetrieveMultiple(query); var assemblies = result.Entities.Select(e => new Assembly { AssemblyId = e.Id, Export = false, Name = e["name"] as string, RegisteredStepCount = 0 }).ToList(); foreach (var assembly in assemblies) { query = new QueryExpression("sdkmessageprocessingstep"); query.Distinct = true; query.NoLock = true; query.ColumnSet = new ColumnSet("sdkmessageprocessingstepid"); type = query.AddLink("plugintype", "plugintypeid", "plugintypeid"); type.LinkCriteria.AddCondition("pluginassemblyid", ConditionOperator.Equal, assembly.AssemblyId); result = _service.RetrieveMultiple(query); assembly.RegisteredStepCount = result.Entities.Count; } return assemblies; }); }
private Task<List<Privilege>> LoadPrivileges(Guid roleId) { return Task.Run(() => { var query = new QueryExpression("privilege"); query.NoLock = true; query.ColumnSet = new ColumnSet("name", "accessright"); query.AddOrder("name", OrderType.Ascending); var typecode = query.AddLink("privilegeobjecttypecodes", "privilegeid", "privilegeid", JoinOperator.LeftOuter); typecode.EntityAlias = "privilegeobjecttypecode"; typecode.Columns = new ColumnSet("objecttypecode"); var intersect = query.AddLink("roleprivileges", "privilegeid", "privilegeid"); intersect.EntityAlias = "roleprivilege"; intersect.Columns = new ColumnSet("privilegedepthmask"); var role = intersect.AddLink("role", "roleid", "roleid"); role.LinkCriteria.AddCondition("roleid", ConditionOperator.Equal, roleId); var result = _service.RetrieveMultiple(query); return result.Entities.Select(e => new Privilege { PrivilegeId = e.Id, Name = e["name"] as string, AccessRight = GetAccessRight(e), LogicalName = GetEntityName(e), Depth = GetDepth(e) }).ToList(); }); }
/// <summary> /// Return the entity record which is configured as the logical parent of this records autonumber /// </summary> public Entity GetParentEntity(Entity entity, XrmAutonumber autonumber, IEnumerable<string> fields) { //Need to split the links to the parent and create a query which returns the parent record via the links if (!entity.Contains(autonumber.FirstLinkLookup)) return null; //Create a query which traverses through the keys and entities we defined in our autonumber links var query = new QueryExpression(); query.ColumnSet = XrmService.CreateColumnSet(fields); LinkEntity carry = null; //for each foreign key entity pairing work from last to first for (var i = autonumber.LinksToParent.LinkToParents.Count(); i > 0; i--) { var thisLink = autonumber.LinksToParent.LinkToParents.ElementAt(i - 1); //if this is the last item we need to create it as the type of entity we are returning if (i == autonumber.LinksToParent.LinkToParents.Count()) query.EntityName = thisLink.LinkTarget; //otherwise if this is not the last item we need to add a link from the previous type to this type else { var previousPair = autonumber.LinksToParent.LinkToParents.ElementAt(i); if (carry == null) carry = query.AddLink(thisLink.LinkTarget, previousPair.LinkFieldTarget, previousPair.LinkFieldSource); else carry = carry.AddLink(thisLink.LinkTarget, previousPair.LinkFieldTarget, previousPair.LinkFieldSource); } //if this is the first item we need to add a filter on the first id with the value in the lookup from the record we are creating the autonumber for if (i == 1) { var thisLookupId = entity.GetLookupGuid(thisLink.LinkFieldSource); if (!thisLookupId.HasValue) return null; if (autonumber.LinksToParent.LinkToParents.Count() != 1) carry.LinkCriteria.AddCondition(carry.LinkToEntityName + "id", ConditionOperator.Equal, thisLookupId.Value); else query.Criteria.AddCondition(query.EntityName + "id", ConditionOperator.Equal, thisLookupId.Value); } } //Run the query and if a result return it var parent = XrmService.RetrieveMultiple(query); if (parent.Entities.Count > 0) return parent.Entities[0]; return null; }
private Task<IEnumerable<Role>> LoadRoles() { return Task.Run(() => { var query = new QueryExpression("role"); query.NoLock = true; query.ColumnSet = new ColumnSet("name", "roleid"); query.AddOrder("name", OrderType.Ascending); var bu = query.AddLink("businessunit", "businessunitid", "businessunitid"); bu.LinkCriteria.AddCondition("parentbusinessunitid", ConditionOperator.Null); var result = _service.RetrieveMultiple(query); var roles = result.Entities.Select(e => new Role { RoleId = e.Id, Name = e["name"] as string }); return roles; }); }
private List<string> LoadSecurityRoles(Guid teamId) { var query = new QueryExpression("role"); query.NoLock = true; query.Distinct = true; query.ColumnSet = new ColumnSet("name"); var teamroles = query.AddLink("teamroles", "roleid", "roleid", JoinOperator.Inner); teamroles.LinkCriteria.AddCondition("teamid", ConditionOperator.Equal, teamId); var result = OrganizationService.RetrieveMultiple(query); return result.Entities .Select(e => e["name"] as string) .ToList(); }
public IEnumerable<Entity> GetAssociatedEntities(string entity, string entityId, string intersectId1, Guid intersectGuid, string relationshipName, string relatedEntity, string relatedEntityId, string intersectId2) { var query = new QueryExpression(relatedEntity); var link = query.AddLink(relationshipName, intersectId2, intersectId2); var link2 = link.AddLink(entity, intersectId1, entityId); link2.LinkCriteria.AddCondition(new ConditionExpression(entityId, ConditionOperator.Equal, intersectGuid)); query.ColumnSet = CreateColumnSet(null); return RetrieveAll(query); }
public IEnumerable<Entity> GetLinkedRecords(string entity, string entityId, Guid entityGuid, string linkedType, string lookup) { var query = new QueryExpression(linkedType); var link = query.AddLink(entity, lookup, entityId); link.LinkCriteria.AddCondition(new ConditionExpression(entityId, ConditionOperator.Equal, entityGuid)); query.ColumnSet = CreateColumnSet(null); return RetrieveAll(query); }
public Entity GetLinkedRecord(string linkedRecordType, string linkThroughRecordType, string linkFromRecordType, string linkThroughLookup, string linkFromLookup, Guid linkFromId, string[] fields) { var query = new QueryExpression(linkedRecordType); query.ColumnSet = CreateColumnSet(fields); var linkThrough = query.AddLink(linkThroughRecordType, XrmEntity.GetPrimaryKeyName(linkedRecordType), linkThroughLookup); var linkFrom = linkThrough.AddLink(linkFromRecordType, XrmEntity.GetPrimaryKeyName(linkThroughRecordType), linkFromLookup); linkFrom.LinkCriteria.AddCondition(new ConditionExpression(XrmEntity.GetPrimaryKeyName(linkFromRecordType), ConditionOperator.Equal, linkFromId)); return RetrieveFirst(query); }
public void Experiment_For_Filters_1() { // var sql = string.Format("Select C.firstname, C.lastname From contact Where firstname Like '%ax%' "); var connectionString = ConfigurationManager.ConnectionStrings["CrmOrganisation"]; var serviceProvider = new CrmServiceProvider(new ExplicitConnectionStringProviderWithFallbackToConfig() { OrganisationServiceConnectionString = connectionString.ConnectionString }, new CrmClientCredentialsProvider()); var orgService = serviceProvider.GetOrganisationService(); using (orgService as IDisposable) { var query = new QueryExpression("contact"); query.ColumnSet.AddColumn("firstname"); query.ColumnSet.AddColumn("lastname"); // so link in customer address. query.AddLink("customeraddress", "contactid", "parentid", JoinOperator.Inner); var addressLink = query.LinkEntities[0]; addressLink.EntityAlias = "A"; addressLink.IncludeAllColumns(); // conditions for max planck var firstName1Condition = new ConditionExpression("firstname", ConditionOperator.Equal, "Max"); var lastname1Condition = new ConditionExpression("lastname", ConditionOperator.Equal, "Planck"); // Groups those conditions using an "AND" conjunction. var maxPlankFilter = new FilterExpression(LogicalOperator.And); maxPlankFilter.AddCondition(firstName1Condition); maxPlankFilter.AddCondition(lastname1Condition); // conditions for albert einstein var firstname2Condition = new ConditionExpression("firstname", ConditionOperator.Equal, "Albert"); var lastname2Condition = new ConditionExpression("lastname", ConditionOperator.Equal, "Einstein"); // Groups those conditions using an "AND" conjunction. var albertEinsteinFilter = new FilterExpression(LogicalOperator.And); albertEinsteinFilter.AddCondition(firstname2Condition); albertEinsteinFilter.AddCondition(lastname2Condition); // could optionally chain the 2 filters so we get Albert's contitions chained (using AND) to max's conditions // albertEinsteinFilter.AddFilter(maxPlankFilter); // conditions for address line 1 moonbase var addressLine1Filter = new FilterExpression(LogicalOperator.And); // dictates that this filter is chained to var line1Condition = new ConditionExpression("A", "line1", ConditionOperator.Equal, "The secret moonbase"); addressLine1Filter.AddCondition(line1Condition); // add filters to query // ensures each filter that we add to our queries criteria is chained together using an OR. query.Criteria.FilterOperator = LogicalOperator.Or; query.Criteria.AddFilter(albertEinsteinFilter); query.Criteria.AddFilter(maxPlankFilter); query.Criteria.AddFilter(addressLine1Filter); var results = orgService.RetrieveMultiple(query); int resultCount = 0; foreach (var r in results.Entities) { resultCount++; Console.WriteLine(string.Format("{0} {1}", (string)r["firstname"], (string)r["lastname"])); } Console.WriteLine("There were " + resultCount + " results.."); } }
private Task<IEnumerable<User>> RetrieveUsers() { return Task.Run(() => { var query = new QueryExpression("systemuser"); query.NoLock = true; query.ColumnSet = new ColumnSet("domainname", "fullname", "systemuserid"); query.AddOrder("fullname", OrderType.Ascending); if (SelectedRole.RoleId == Guid.Empty) { var userroles = query.AddLink("systemuserroles", "systemuserid", "systemuserid", JoinOperator.LeftOuter); userroles.EntityAlias = "roles"; query.Criteria.AddCondition("roles", "roleid", ConditionOperator.Null); } else { var userroles = query.AddLink("systemuserroles", "systemuserid", "systemuserid"); userroles.LinkCriteria.AddCondition("roleid", ConditionOperator.Equal, SelectedRole.RoleId); } var result = _service.RetrieveMultiple(query); var users = result.Entities.Select(e => new User { UserId = e.Id, DomainName = e.Contains("domainname") ? e["domainname"] as string : null, FullName = e.Contains("fullname") ? e["fullname"] as string : null }); return users; }); }
static public void TeamLogic(IOrganizationService service, Guid User, string Ent, string Event, string Type, string Phase, string ChangeReason) { QueryExpression teamQuery = new QueryExpression("team"); ColumnSet teamColumnSet = new ColumnSet("name"); teamQuery.ColumnSet = teamColumnSet; teamQuery.Criteria = new FilterExpression(); teamQuery.Criteria.FilterOperator = LogicalOperator.And; // teamQuery.Criteria.AddCondition("name", ConditionOperator.Equal, "Sales"); teamQuery.AddLink("teammembership", "teamid", "teamid").AddLink("systemuser", "systemuserid", "systemuserid").LinkCriteria.AddCondition("systemuserid", ConditionOperator.Equal, User); EntityCollection teamDetail = service.RetrieveMultiple(teamQuery); foreach (Entity ent in teamDetail.Entities) { string query = generateFetchForTeam(ent.Id.ToString(), Ent, Event, Type, Phase, ChangeReason); if (retrievePermision(service, query)) return; } }
public void Experiment_For_Filters_3() { // var sql = string.Format("Select C.firstname, C.lastname From contact Where firstname Like '%ax%' "); var connectionString = ConfigurationManager.ConnectionStrings["CrmOrganisation"]; var serviceProvider = new CrmServiceProvider(new ExplicitConnectionStringProviderWithFallbackToConfig() { OrganisationServiceConnectionString = connectionString.ConnectionString }, new CrmClientCredentialsProvider()); var orgService = serviceProvider.GetOrganisationService(); using (orgService as IDisposable) { var query = new QueryExpression("contact"); query.Distinct = true; query.ColumnSet.AddColumns("firstname", "lastname"); query.Criteria.FilterOperator = LogicalOperator.Or; var f = query.Criteria.AddFilter(LogicalOperator.And); f.AddCondition("firstname", ConditionOperator.Equal, "Max"); f.AddCondition("lastname", ConditionOperator.Equal, "Planck"); f = query.Criteria.AddFilter(LogicalOperator.And); f.AddCondition("firstname", ConditionOperator.Equal, "Albert"); f.AddCondition("lastname", ConditionOperator.Equal, "Einstein"); var a = query.AddLink("customeraddress", "contactid", "parentid"); a.LinkCriteria.AddCondition("line1", ConditionOperator.Equal, "The secret moonbase"); // var response = orgService.RetrieveMultiple(query); var results = orgService.RetrieveMultiple(query); int resultCount = 0; foreach (var r in results.Entities) { resultCount++; Console.WriteLine(string.Format("{0} {1}", (string)r["firstname"], (string)r["lastname"])); } Console.WriteLine("There were " + resultCount + " results.."); } }
public IEnumerable<Entity> GetAssociatedEntities(string entityTo, string relationshipName, string entityFromRelationShipId, Guid entityFromId, string toRelationShipId, IEnumerable<string> fields) { var query = new QueryExpression(entityTo); query.ColumnSet = CreateColumnSet(fields); var link = query.AddLink(GetRelationshipEntityName(relationshipName), GetPrimaryKeyName(entityTo), toRelationShipId); link.LinkCriteria.AddCondition(entityFromRelationShipId, ConditionOperator.Equal, entityFromId); return RetrieveAll(query); }
private Task<List<Role>> LoadRoles() { return Task.Run(() => { var query = new QueryExpression("role"); query.NoLock = true; query.ColumnSet = new ColumnSet("name", "roleid"); query.AddOrder("name", OrderType.Ascending); var bu = query.AddLink("businessunit", "businessunitid", "businessunitid"); bu.LinkCriteria.AddCondition("parentbusinessunitid", ConditionOperator.Null); var result = _service.RetrieveMultiple(query); var roles = result.Entities.Select(e => new Role { RoleId = e.Id, Name = e["name"] as string }); roles = roles.Concat(new Role[] { new Role { RoleId = Guid.Empty, Name = " -- Users without an assigned role -- " } }); return roles.OrderBy(r => r.Name).ToList(); }); }
public IEnumerable<Entity> GetUserRoles(Guid userId, string[] columns) { var query = new QueryExpression("role"); query.ColumnSet = new ColumnSet(columns); var userRole = query.AddLink("systemuserroles", "roleid", "roleid"); userRole.LinkCriteria.AddCondition("systemuserid", ConditionOperator.Equal, userId); return RetrieveAll(query); }
private void RemoveRoles(Team team) { var query = new QueryExpression("role"); query.Distinct = true; query.ColumnSet = new ColumnSet("roleid"); if (team.SecurityRoles != null && team.SecurityRoles.Count > 0) { query.Criteria.AddCondition("name", ConditionOperator.NotIn, team.SecurityRoles.ToArray()); } query.Criteria.AddCondition("businessunitid", ConditionOperator.Equal, team.DestinationBusinessUnitId); var teamLink = query.AddLink("teamroles", "roleid", "roleid", JoinOperator.Inner); teamLink.LinkCriteria.AddCondition("teamid", ConditionOperator.Equal, team.TeamId); var result = OrganizationService.RetrieveMultiple(query); if (result == null || result.Entities == null || result.Entities.Count == 0) { // Nothing to remove return; } var roles = result.Entities .Select(e => new EntityReference("role", e.Id)) .ToList(); OrganizationService.Disassociate("team", team.TeamId, new Relationship("teamroles_association"), new EntityReferenceCollection(roles)); }