public List <RelatedEntityType> ReadNNRelationship <RelatedEntityType>(string relationshipName, Entity currentEntity, Func <Entity, RelatedEntityType> crmEntityCreater, params string[] relatedColumns) { List <RelatedEntityType> relatedObjects = new List <RelatedEntityType>(); ColumnSet columns = new ColumnSet(relatedColumns); RetrieveRelationshipRequest request = new RetrieveRelationshipRequest() { Name = relationshipName, }; RetrieveRelationshipResponse response = (RetrieveRelationshipResponse)Connection.Service.Execute(request); ManyToManyRelationshipMetadata metaData = (ManyToManyRelationshipMetadata)response.Results["RelationshipMetadata"]; KeyValuePair <EntityRelationshipInfo, EntityRelationshipInfo> relationshipInfo = EntityRelationshipInfo.GetFromMetaData(currentEntity.LogicalName, metaData); List <Guid> relatedIds = GetRelatedIds(currentEntity.Id, metaData.IntersectEntityName, relationshipInfo.Key.IntersectAttribute, relationshipInfo.Value.IntersectAttribute); foreach (Guid entityId in relatedIds) { Entity relatedEntity = Connection.Service.Retrieve(relationshipInfo.Value.LogicalName, entityId, columns); RelatedEntityType relatedObject = crmEntityCreater(relatedEntity); relatedObjects.Add(relatedObject); } return(relatedObjects); }
public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx) { var retrieveRequest = request as RetrieveRelationshipRequest; if (retrieveRequest == null) { throw new Exception("Only RetrieveRelationshipRequest can be processed!"); } var service = ctx.GetFakedOrganizationService(); var fakeRelationShip = ctx.GetRelationship(retrieveRequest.Name); if (fakeRelationShip == null) { throw new Exception(string.Format("Relationship {0} does not exist in the metadata cache", retrieveRequest.Name)); } var response = new RetrieveRelationshipResponse(); response.Results = new ParameterCollection(); response.Results.Add("RelationshipMetadata", GetRelationshipMetadata(fakeRelationShip)); response.ResponseName = "RetrieveRelationship"; return(response); }
public void UpdateChildRecords(string relationshipName, string parentEntityType, string parentEntityId, string parentFieldNameToUpdate, string setValueToUpdate, string childFieldNameToUpdate) { //1) Get child lookup field name RetrieveRelationshipRequest req = new RetrieveRelationshipRequest() { Name = relationshipName }; RetrieveRelationshipResponse res = (RetrieveRelationshipResponse)service.Execute(req); OneToManyRelationshipMetadata rel = (OneToManyRelationshipMetadata)res.RelationshipMetadata; string childEntityType = rel.ReferencingEntity; string childEntityFieldName = rel.ReferencingAttribute; //2) retrieve all child records QueryByAttribute querybyattribute = new QueryByAttribute(childEntityType); querybyattribute.ColumnSet = new ColumnSet(childEntityFieldName); querybyattribute.Attributes.AddRange(childEntityFieldName); querybyattribute.Values.AddRange(new Guid(parentEntityId)); EntityCollection retrieved = service.RetrieveMultiple(querybyattribute); //2') retrieve parent fielv value var valueToUpdate = new object(); if (parentFieldNameToUpdate != null && parentFieldNameToUpdate != "") { Entity retrievedEntity = (Entity)service.Retrieve(parentEntityType, new Guid(parentEntityId), new ColumnSet(parentFieldNameToUpdate)); if (retrievedEntity.Attributes.Contains(parentFieldNameToUpdate)) { valueToUpdate = retrievedEntity.Attributes[parentFieldNameToUpdate]; } else { valueToUpdate = null; } } else { valueToUpdate = setValueToUpdate; } //3) update each child record foreach (Entity child in retrieved.Entities) { if (childEntityType.ToLower() == "dynamicpropertyinstance") { //pending... UpdateProductPropertiesRequest req2 = new UpdateProductPropertiesRequest(); // req2. break; } Entity entUpdate = new Entity(childEntityType); entUpdate.Id = child.Id; entUpdate.Attributes.Add(childFieldNameToUpdate, valueToUpdate); service.Update(entUpdate); } }
private RetrieveRelationshipResponse HandleRetrieveRelationship(OrganizationRequest orgRequest, EntityReference userRef) { var request = MakeRequest <RetrieveRelationshipRequest>(orgRequest); var resp = new RetrieveRelationshipResponse(); resp.Results["RelationshipMetadata"] = dataMethods.GetRelationshipMetadata(request.Name, request.MetadataId, userRef); return(resp); }
public static EntityRelationship GetEntity(IOrganizationService service, Guid id) { RetrieveRelationshipResponse response = (RetrieveRelationshipResponse)service.Execute( new RetrieveRelationshipRequest() { MetadataId = id } ); return(new EntityRelationship(response.RelationshipMetadata)); }
public static RelationshipMetadataBase GetRelationshipMetadata(IOrganizationService service, Guid objectId) { RetrieveRelationshipRequest attributeRequest = new RetrieveRelationshipRequest { MetadataId = objectId, RetrieveAsIfPublished = true }; RetrieveRelationshipResponse attributeResponse = (RetrieveRelationshipResponse)service.Execute(attributeRequest); return(attributeResponse.RelationshipMetadata); }
public bool QueryOneToManyRelationship() { RetrieveRelationshipRequest request = new RetrieveRelationshipRequest(); request.Name = "contact_customer_accounts"; request.RetrieveAsIfPublished = true; RetrieveRelationshipResponse response = (RetrieveRelationshipResponse)OrganizationServiceProxy.Execute(request); OneToManyRelationshipMetadata relationship = (OneToManyRelationshipMetadata)response.RelationshipMetadata; Assert.AreEqual(relationship.IsCustomRelationship, false); Assert.AreEqual(relationship.SchemaName, "contact_customer_accounts"); Assert.AreEqual(relationship.ReferencedAttribute, "accountid"); return(true); }
public bool QueryManyToManyRelationship() { RetrieveRelationshipRequest request = new RetrieveRelationshipRequest(); request.Name = "accountleads_association"; request.RetrieveAsIfPublished = true; RetrieveRelationshipResponse response = (RetrieveRelationshipResponse)OrganizationServiceProxy.Execute(request); ManyToManyRelationshipMetadata relationship = (ManyToManyRelationshipMetadata)response.RelationshipMetadata; Assert.AreEqual(relationship.IsCustomRelationship, false); Assert.AreEqual(relationship.SchemaName, "accountleads_association"); Assert.AreEqual(relationship.IntersectEntityName, "accountleads"); return(true); }
internal override OrganizationResponse Execute(OrganizationRequest orgRequest, EntityReference userRef) { var request = MakeRequest <RetrieveRelationshipRequest>(orgRequest); if (request.Name == null && request.MetadataId == Guid.Empty) { throw new FaultException("Relationship name is required when MetadataId is not specified"); } var metadata = Utility.GetRelationshipMetadataDefaultNull(this.metadata.EntityMetadata, request.Name, request.MetadataId, userRef); if (metadata == null) { throw new FaultException($"Could not find relationship with name {request.Name} or metadataid {request.MetadataId}"); } var resp = new RetrieveRelationshipResponse(); resp.Results["RelationshipMetadata"] = metadata; return(resp); }
public OneToManyRelationshipMetadata GetRelationshipInfo(string relationshipName, IOrganizationService orgService) { if (String.IsNullOrEmpty(relationshipName)) { throw new NullReferenceException("relationshipName"); } RetrieveRelationshipRequest req = new RetrieveRelationshipRequest() { Name = relationshipName, RetrieveAsIfPublished = false }; RetrieveRelationshipResponse resp = (RetrieveRelationshipResponse)orgService.Execute(req); if (!(resp.RelationshipMetadata is OneToManyRelationshipMetadata)) { throw new InvalidWorkflowException($"The relationship {relationshipName} is not a one to many relationship"); } return((OneToManyRelationshipMetadata)resp.RelationshipMetadata); }
private ManyToManyRelationshipMetadata GetRelationshipInfo(string relationshipName, IOrganizationService orgService) { if (String.IsNullOrEmpty(relationshipName)) { throw new NullReferenceException("relationshipName"); } RetrieveRelationshipRequest request = new RetrieveRelationshipRequest() { Name = relationshipName, RetrieveAsIfPublished = false }; RetrieveRelationshipResponse response = (RetrieveRelationshipResponse)orgService.Execute(request); var relationshipMeta = response.RelationshipMetadata; if (!(relationshipMeta is ManyToManyRelationshipMetadata)) { throw new WorkflowApplicationException($"The relationship {relationshipName} is not a many to many relationship"); } return((ManyToManyRelationshipMetadata)relationshipMeta); }
/// <summary> /// Retrieves related records using a relationship metadata /// </summary> /// <param name="relationshipName">relationship to navigate</param> /// <param name="parentEntityId">Parent Id</param> /// <returns></returns> public EntityCollection GetChildRecords(string relationshipName, string parentEntityId) { //1) Get child lookup field name RetrieveRelationshipRequest req = new RetrieveRelationshipRequest() { Name = relationshipName }; RetrieveRelationshipResponse res = (RetrieveRelationshipResponse)service.Execute(req); OneToManyRelationshipMetadata rel = (OneToManyRelationshipMetadata)res.RelationshipMetadata; string childEntityType = rel.ReferencingEntity; string childEntityFieldName = rel.ReferencingAttribute; //2) retrieve all child records QueryByAttribute querybyattribute = new QueryByAttribute(childEntityType); querybyattribute.ColumnSet = new ColumnSet(childEntityFieldName); querybyattribute.Attributes.AddRange(childEntityFieldName); querybyattribute.Values.AddRange(new Guid(parentEntityId)); EntityCollection retrieved = service.RetrieveMultiple(querybyattribute); return(retrieved); }
/// <summary> /// Create and configure the organization service proxy. /// Create one-to-many relationship. /// Create many-to-many relationship. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetWorkWithRelationships1> bool eligibleCreateOneToManyRelationship = EligibleCreateOneToManyRelationship("account", "campaign"); if (eligibleCreateOneToManyRelationship) { CreateOneToManyRequest createOneToManyRelationshipRequest = new CreateOneToManyRequest { OneToManyRelationship = new OneToManyRelationshipMetadata { ReferencedEntity = "account", ReferencingEntity = "campaign", SchemaName = "new_account_campaign", AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("Account", 1033), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration { Assign = CascadeType.NoCascade, Delete = CascadeType.RemoveLink, Merge = CascadeType.NoCascade, Reparent = CascadeType.NoCascade, Share = CascadeType.NoCascade, Unshare = CascadeType.NoCascade } }, Lookup = new LookupAttributeMetadata { SchemaName = "new_parent_accountid", DisplayName = new Label("Account Lookup", 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Sample Lookup", 1033) } }; CreateOneToManyResponse createOneToManyRelationshipResponse = (CreateOneToManyResponse)_serviceProxy.Execute( createOneToManyRelationshipRequest); _oneToManyRelationshipId = createOneToManyRelationshipResponse.RelationshipId; _oneToManyRelationshipName = createOneToManyRelationshipRequest.OneToManyRelationship.SchemaName; Console.WriteLine( "The one-to-many relationship has been created between {0} and {1}.", "account", "campaign"); } //</snippetWorkWithRelationships1> //<snippetWorkWithRelationships2> bool accountEligibleParticipate = EligibleCreateManyToManyRelationship("account"); bool campaignEligibleParticipate = EligibleCreateManyToManyRelationship("campaign"); if (accountEligibleParticipate && campaignEligibleParticipate) { CreateManyToManyRequest createManyToManyRelationshipRequest = new CreateManyToManyRequest { IntersectEntitySchemaName = "new_accounts_campaigns", ManyToManyRelationship = new ManyToManyRelationshipMetadata { SchemaName = "new_accounts_campaigns", Entity1LogicalName = "account", Entity1AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("Account", 1033), Order = 10000 }, Entity2LogicalName = "campaign", Entity2AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("Campaign", 1033), Order = 10000 } } }; CreateManyToManyResponse createManytoManyRelationshipResponse = (CreateManyToManyResponse)_serviceProxy.Execute( createManyToManyRelationshipRequest); _manyToManyRelationshipId = createManytoManyRelationshipResponse.ManyToManyRelationshipId; _manyToManyRelationshipName = createManyToManyRelationshipRequest.ManyToManyRelationship.SchemaName; Console.WriteLine( "The many-to-many relationship has been created between {0} and {1}.", "account", "campaign"); } //</snippetWorkWithRelationships2> // Publish the customization changes. _serviceProxy.Execute(new PublishAllXmlRequest()); //<snippetWorkWithRelationships.RetrieveRelationship> //You can use either the Name or the MetadataId of the relationship. //Retrieve the One-to-many relationship using the MetadataId. RetrieveRelationshipRequest retrieveOneToManyRequest = new RetrieveRelationshipRequest { MetadataId = _oneToManyRelationshipId }; RetrieveRelationshipResponse retrieveOneToManyResponse = (RetrieveRelationshipResponse)_serviceProxy.Execute(retrieveOneToManyRequest); Console.WriteLine("Retrieved {0} One-to-many relationship by id", retrieveOneToManyResponse.RelationshipMetadata.SchemaName); //Retrieve the Many-to-many relationship using the Name. RetrieveRelationshipRequest retrieveManyToManyRequest = new RetrieveRelationshipRequest { Name = _manyToManyRelationshipName }; RetrieveRelationshipResponse retrieveManyToManyResponse = (RetrieveRelationshipResponse)_serviceProxy.Execute(retrieveManyToManyRequest); Console.WriteLine("Retrieved {0} Many-to-Many relationship by Name", retrieveManyToManyResponse.RelationshipMetadata.MetadataId); //</snippetWorkWithRelationships.RetrieveRelationship> DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
private RetrieveRelationshipResponse ExecuteInternal(RetrieveRelationshipRequest request) { if (string.IsNullOrWhiteSpace(request.Name)) { throw new NotImplementedException("Unable to process a RetrieveRelationshipRequest without a Name"); } PropertyInfo property = null; foreach (var type in CrmServiceUtility.GetEarlyBoundProxyAssembly(Info.EarlyBoundEntityAssembly).GetTypes()) { property = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) .FirstOrDefault(a => { if (a.GetCustomAttributes(typeof(AttributeLogicalNameAttribute), false).Length == 0) { return(false); } var att = a.GetCustomAttributes(typeof(RelationshipSchemaNameAttribute), false); return(att.Length != 0 && ((RelationshipSchemaNameAttribute)att.FirstOrDefault())?.SchemaName == request.Name); }); if (property != null) { break; } } if (property == null) { throw new KeyNotFoundException($"Unable to find a relationship {request.Name}."); } RelationshipMetadataBase relationship; if (typeof(Entity).IsAssignableFrom(property.PropertyType)) { var referencedType = EntityHelper.GetEntityLogicalName(property.PropertyType); relationship = new OneToManyRelationshipMetadata { ReferencedEntity = referencedType, ReferencedAttribute = EntityHelper.GetIdAttributeName(referencedType), ReferencingEntity = EntityHelper.GetEntityLogicalName(property.DeclaringType), ReferencingAttribute = property.GetAttributeLogicalName() }; } else { var att = property.GetAttributeLogicalName(); relationship = new ManyToManyRelationshipMetadata { IntersectEntityName = att.Substring(0, att.Length - "_association".Length) }; } var response = new RetrieveRelationshipResponse { Results = { ["RelationshipMetadata"] = relationship } }; return(response); }
public void UpdateChildRecords(string relationshipName, string parentEntityType, string parentEntityId, string parentFieldNameToUpdate, string setValueToUpdate, string childFieldNameToUpdate, bool _UpdateonlyActive) { //1) Get child lookup field name RetrieveRelationshipRequest req = new RetrieveRelationshipRequest() { Name = relationshipName }; RetrieveRelationshipResponse res = (RetrieveRelationshipResponse)service.Execute(req); OneToManyRelationshipMetadata rel = (OneToManyRelationshipMetadata)res.RelationshipMetadata; string childEntityType = rel.ReferencingEntity; string childEntityFieldName = rel.ReferencingAttribute; //2) retrieve all child records QueryByAttribute querybyattribute = new QueryByAttribute(childEntityType); querybyattribute.ColumnSet = new ColumnSet(childEntityFieldName); if (!_UpdateonlyActive) { querybyattribute.Attributes.AddRange(childEntityFieldName); querybyattribute.Values.AddRange(new Guid(parentEntityId)); } else { querybyattribute.Attributes.AddRange(childEntityFieldName, "statecode"); querybyattribute.Values.AddRange(new Guid(parentEntityId), 0); } EntityCollection retrieved = service.RetrieveMultiple(querybyattribute); //2') retrieve parent fielv value var valueToUpdate = new object(); if (parentFieldNameToUpdate != null && parentFieldNameToUpdate != "") { Entity retrievedEntity = (Entity)service.Retrieve(parentEntityType, new Guid(parentEntityId), new ColumnSet(parentFieldNameToUpdate)); if (retrievedEntity.Attributes.Contains(parentFieldNameToUpdate)) { valueToUpdate = retrievedEntity.Attributes[parentFieldNameToUpdate]; } else { valueToUpdate = null; } } else { valueToUpdate = setValueToUpdate; } //3) update each child record foreach (Entity child in retrieved.Entities) { if (childEntityType.ToLower() == "dynamicpropertyinstance") { //pending... UpdateProductPropertiesRequest req2 = new UpdateProductPropertiesRequest(); // req2. break; } RetrieveAttributeRequest reqAtt = new RetrieveAttributeRequest(); reqAtt.EntityLogicalName = childEntityType; reqAtt.LogicalName = childFieldNameToUpdate; RetrieveAttributeResponse resAtt = (RetrieveAttributeResponse)service.Execute(reqAtt); bool valueToUpdateBool = false; AttributeMetadata meta = resAtt.AttributeMetadata; Entity entUpdate = new Entity(childEntityType); entUpdate.Id = child.Id; if (meta.AttributeType.Value.ToString() == "Boolean") { if (valueToUpdate is bool) { if ((bool)valueToUpdate == true) { valueToUpdate = "1"; } else { valueToUpdate = "0"; } } if (valueToUpdate == "1") { entUpdate.Attributes.Add(childFieldNameToUpdate, true); } else { entUpdate.Attributes.Add(childFieldNameToUpdate, false); } } else { if (meta.AttributeType.Value.ToString() == "Picklist" || meta.AttributeType.Value.ToString() == "Status") { if (valueToUpdate == null) { entUpdate.Attributes.Add(childFieldNameToUpdate, null); } else { if (valueToUpdate is OptionSetValue) { valueToUpdate = ((OptionSetValue)valueToUpdate).Value; } OptionSetValue opt = new OptionSetValue(Convert.ToInt32(valueToUpdate)); entUpdate.Attributes.Add(childFieldNameToUpdate, opt); } } else { entUpdate.Attributes.Add(childFieldNameToUpdate, valueToUpdate); } } service.Update(entUpdate); } }