/// <summary> /// Deserializes a surrogate object. /// </summary> /// <param name="value">The surrogate.</param> /// <returns>The object.</returns> private static object Deserialize(object value) { // convert from surrogate type to actual type if (value is long) { // for object references, the default json numeric type is long but the end result should be int return(Convert.ToInt32(value)); } if (value is JsonGuid) { return(new Guid(((JsonGuid)value).Value)); } if (value is JsonEntityFilters) { return((EntityFilters)((JsonEntityFilters)value).Value); } if (value is JsonList <KeyValuePair <Relationship, QueryBase> > ) { var dictionary = new RelationshipQueryCollection(); dictionary.AddRange(((JsonList <KeyValuePair <Relationship, QueryBase> >)value).Value); return(dictionary); } return(value); }
public void TestAssocNNTwoWay() { using (var context = new Xrm(orgAdminUIService)) { var relatedAccounts = new EntityReferenceCollection(); relatedAccounts.Add(new EntityReference(Account.EntityLogicalName, account1.Id)); relatedAccounts.Add(new EntityReference(Account.EntityLogicalName, account2.Id)); relatedAccounts.Add(new EntityReference(Account.EntityLogicalName, account3.Id)); var relatedContacts = new EntityReferenceCollection(); relatedContacts.Add(new EntityReference(Contact.EntityLogicalName, contact1.Id)); relatedContacts.Add(new EntityReference(Contact.EntityLogicalName, contact2.Id)); Relationship relationship = new Relationship(dg_account_contact.EntityLogicalName); orgAdminUIService.Associate(Account.EntityLogicalName, account1.Id, relationship, relatedContacts); var relationQuery = new RelationshipQueryCollection(); var query = new QueryExpression(Contact.EntityLogicalName); query.ColumnSet = new ColumnSet("firstname"); relationQuery.Add(relationship, query); var req = new RetrieveRequest(); req.ColumnSet = new ColumnSet("name"); req.RelatedEntitiesQuery = relationQuery; req.Target = new EntityReference(Account.EntityLogicalName, account1.Id); var retrievedAccount = (orgAdminUIService.Execute(req) as RetrieveResponse).Entity as Account; var related = retrievedAccount.RelatedEntities[relationship].Entities; Assert.AreEqual(2, related.Count()); Assert.AreEqual(contact1.Id, related.FirstOrDefault(e => (e as Contact).FirstName == contact1.FirstName).Id); Assert.AreEqual(contact2.Id, related.FirstOrDefault(e => (e as Contact).FirstName == contact2.FirstName).Id); } }
protected override RetrieveRequest ToRetrieveRequest(EntityReference id) { // build the related entity queries var externalIdentityFetch = new Fetch { Entity = new FetchEntity("adx_externalidentity", UserConstants.ExternalIdentityAttributes.Columns) { Filters = new[] { new Filter { Conditions = GetActiveStateConditions().ToArray() } } } }; var relatedEntitiesQuery = new RelationshipQueryCollection { { UserConstants.ContactExternalIdentityRelationship, externalIdentityFetch.ToFetchExpression() }, }; // retrieve the contact by ID including its related entities var request = new RetrieveRequest { Target = id, ColumnSet = new ColumnSet(this.GetContactAttributes().ToArray()), RelatedEntitiesQuery = relatedEntitiesQuery }; return(request); }
protected abstract void Execute( IOrganizationService organizationService, IPluginExecutionContext pluginExecutionContext, ITracingService tracingService, EntityReference targetEntityReference, ColumnSet columnSet, bool returnNotifications, RelationshipQueryCollection relatedEntitiesQuery);
protected void PullThePlugin(LocalPluginContext localContext) { if (!localContext.PluginExecutionContext.InputParameters.Contains("RecordId")) { return; } string RecordId = (string)localContext.PluginExecutionContext.InputParameters["RecordId"]; IOrganizationService service = localContext.OrganizationService; Relationship relationship = new Relationship(); relationship.SchemaName = "new_new_task12child_new_task12main"; QueryExpression query = new QueryExpression(); query.EntityName = "new_task12child"; query.ColumnSet = new ColumnSet(true); query.Criteria = new FilterExpression(); query.Criteria.AddCondition(new ConditionExpression("statecode", ConditionOperator.Equal, "Active")); RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection(); relatedEntity.Add(relationship, query); RetrieveRequest request = new RetrieveRequest(); request.ColumnSet = new ColumnSet("new_name"); request.Target = new EntityReference { Id = new Guid(RecordId), LogicalName = "new_task12main" }; request.RelatedEntitiesQuery = relatedEntity; RetrieveResponse response = (RetrieveResponse)service.Execute(request); DataCollection <Entity> RelatedEntitis = ((DataCollection <Relationship, EntityCollection>) (((RelatedEntityCollection)(response.Entity.RelatedEntities)))) [new Relationship("new_new_task12child_new_task12main")].Entities; foreach (var RelatedEntity in RelatedEntitis) { SetStateRequest setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = RelatedEntity.Id, LogicalName = RelatedEntity.LogicalName, }, State = new OptionSetValue(1), Status = new OptionSetValue(2) }; service.Execute(setStateRequest); } localContext.PluginExecutionContext.OutputParameters["Out"] = string.Format("Deativated {0} ", RelatedEntitis.Count); }
/// <summary>The get dependencies.</summary> /// <param name="collection">The collection.</param> /// <param name="isSingle">The is single.</param> /// <returns>The dependencies.</returns> private IEnumerable <string> GetDependencies(RelationshipQueryCollection collection, bool isSingle) { foreach (var relatedEntitiesQuery in collection) { foreach (var dependency in this.GetDependencies(relatedEntitiesQuery.Value, isSingle)) { yield return(dependency); } } }
/// <summary> /// Returns a list of records of the specified type that are related to the target record /// via the specified relationshp. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="TargetRecord"></param> /// <param name="Relationship"></param> /// <param name="EntityLogicalName"></param> /// <param name="columms"></param> /// <returns></returns> public IList <T> GetAssociatedRecords <T>(EntityReference TargetRecord, Relationship Relationship, string EntityLogicalName, ColumnSet columms = null) where T : Entity { try { if (TargetRecord == null) { throw new ArgumentNullException("TargetRecord is required."); } if (Relationship == null) { throw new ArgumentNullException("Relationship is required."); } if (string.IsNullOrEmpty(EntityLogicalName)) { throw new ArgumentNullException("EntityLogicalName is required."); } if (columms == null) { columms = new ColumnSet(EntityLogicalName + "id"); } var associatedRecords = new List <T>(); var qry = new QueryExpression { EntityName = EntityLogicalName, ColumnSet = columms }; var qryCollection = new RelationshipQueryCollection(); qryCollection.Add(Relationship, qry); var req = new Microsoft.Xrm.Sdk.Messages.RetrieveRequest(); req.RelatedEntitiesQuery = qryCollection; req.Target = TargetRecord; req.ColumnSet = new ColumnSet(TargetRecord.LogicalName + "id"); var resp = (RetrieveResponse)OrganizationService.Execute(req); if (resp.Entity.RelatedEntities.Contains(Relationship)) { foreach (var record in resp.Entity.RelatedEntities[Relationship].Entities) { associatedRecords.Add((T)record); } } return(associatedRecords); } catch (Exception ex) { throw new Exception(string.Format("Error in GetAssociatedRecords: {0}", ex.Message), ex); } }
internal Entity GetDbEntityWithRelatedEntities(EntityReference reference, EntityRole primaryEntityRole, EntityReference userRef) { var entity = db.GetEntityOrNull(reference); if (entity == null) { return(null); } var metadata = this.metadata.EntityMetadata.GetMetadata(entity.LogicalName); if (entity.RelatedEntities.Count() > 0) { var clone = entity.CloneEntity(metadata, new ColumnSet(true)); db.Update(clone); entity = clone; } var relationQuery = new RelationshipQueryCollection(); var relationsMetadata = primaryEntityRole == EntityRole.Referenced ? metadata.OneToManyRelationships : metadata.ManyToOneRelationships; foreach (var relationshipMeta in relationsMetadata) { var query = new QueryExpression( primaryEntityRole == EntityRole.Referenced ? relationshipMeta.ReferencingEntity : relationshipMeta.ReferencedEntity) { ColumnSet = new ColumnSet(true) }; relationQuery.Add(new Relationship() { SchemaName = relationshipMeta.SchemaName, PrimaryEntityRole = primaryEntityRole }, query); } foreach (var relationshipMeta in metadata.ManyToManyRelationships) { var query = new QueryExpression(relationshipMeta.IntersectEntityName) { ColumnSet = new ColumnSet(true) }; relationQuery.Add(new Relationship() { SchemaName = relationshipMeta.SchemaName }, query); } AddRelatedEntities(entity, relationQuery, userRef); return(entity); }
public static EntityCollection GetRelatedEntities(this IOrganizationService organizationService, EntityReference entity, Relationship relationship, ColumnSet columnSet) { RelationshipQueryCollection relationshipQueryCollection; RelatedEntityCollection relatedEntities; EntityReference entityReference; RetrieveRequest retrieveRequest; string relatedEntityName; if (entity == null) { throw new ArgumentNullException(nameof(entity), $"The parameter {nameof(entity)} cannot be null."); } if (relationship == null) { throw new ArgumentNullException(nameof(entity), $"The parameter {nameof(relationship)} cannot be null."); } if (columnSet == null) { throw new ArgumentNullException(nameof(entity), $"The parameter {nameof(columnSet)} cannot be null."); } relatedEntityName = organizationService.GetRelatedEntityName(entity, relationship); relationshipQueryCollection = new RelationshipQueryCollection(); QueryExpression queryExpression = new QueryExpression(relatedEntityName) { ColumnSet = columnSet }; relationshipQueryCollection.Add(relationship, queryExpression); entityReference = new EntityReference(entity.LogicalName, entity.Id); retrieveRequest = new RetrieveRequest() { Target = entityReference, ColumnSet = new ColumnSet(), RelatedEntitiesQuery = relationshipQueryCollection }; relatedEntities = (organizationService.Execute(retrieveRequest) as RetrieveResponse).Entity.RelatedEntities; if (!relatedEntities.Contains(relationship)) { return(new EntityCollection()); } return(relatedEntities[relationship]); }
static void Main(string[] args) { OrganizationServiceProxy serviceProxy = ConnectHelper.CrmService; var service = (IOrganizationService)serviceProxy; Relationship relationship = new Relationship(); relationship.SchemaName = "new_new_task12child_new_task12main"; QueryExpression query = new QueryExpression(); query.EntityName = "new_task12child"; query.ColumnSet = new ColumnSet(true); query.Criteria = new FilterExpression(); query.Criteria.AddCondition(new ConditionExpression("statecode", ConditionOperator.Equal, "Active")); RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection(); relatedEntity.Add(relationship, query); RetrieveRequest request = new RetrieveRequest(); request.ColumnSet = new ColumnSet("new_name"); request.Target = new EntityReference { Id = new Guid("{DE4B6AB0-7F9A-E911-8122-00155D06F203}"), LogicalName = "new_task12main" }; request.RelatedEntitiesQuery = relatedEntity; RetrieveResponse response = (RetrieveResponse)service.Execute(request); Console.WriteLine("NameMain: " + response.Entity["new_name"]); DataCollection <Entity> RelatedEntitis = ((DataCollection <Relationship, EntityCollection>) (((RelatedEntityCollection)(response.Entity.RelatedEntities)))) [new Relationship("new_new_task12child_new_task12main")].Entities; Console.WriteLine("Related Childs:"); foreach (var RelatedEntity in RelatedEntitis) { Console.WriteLine(" - " + RelatedEntity["new_name"] + "Id: " + RelatedEntity.Id); } Console.WriteLine("Press Enter"); Console.ReadLine(); }
internal static string Trace(RelationshipQueryCollection relationshipQueryCollection) { if (relationshipQueryCollection == null) { return(Environment.NewLine); } var sb = new StringBuilder(); foreach (KeyValuePair <Relationship, QueryBase> keyValuePair in relationshipQueryCollection) { sb.AppendLine(string.Format(CultureInfo.InvariantCulture, ParameterText, Trace(keyValuePair.Key))); sb.AppendLine(string.Format(CultureInfo.InvariantCulture, ParameterText, Trace(keyValuePair.Value))); } return(Trace(sb)); }
private static void IncludeRelatedEntitiesInRetrieveRequest(OrganizationRequest request, Hashtable related) { if (related != null && related.Count > 0) { RelationshipQueryCollection relatedEntities = new RelationshipQueryCollection(); foreach (string relatedEntityName in related.Keys) { QueryExpression relatedQuery = new QueryExpression(relatedEntityName) { ColumnSet = new ColumnSet(true) }; Relationship relationship = new Relationship((string)related[relatedEntityName]); relatedEntities.Add(relationship, relatedQuery); } request.Parameters.Add("RelatedEntitiesQuery", relatedEntities); } }
/// <summary> /// GetAssociatedEntityItems method is to get related entity details /// </summary> /// <param name="primaryEntityName"></param> /// <param name="_primaryEntityId"></param> /// <param name="relatedEntityName"></param> /// <param name="relationshipName"></param> /// <param name="serviceProxy"></param> /// <returns></returns> private EntityCollection GetAssociatedEntityItems(string primaryEntityName, Guid _primaryEntityId, string relatedEntityName, string relationshipName, IOrganizationService serviceProxy) { try { tracingService.Trace("Entering into InvokeWorkflows method...."); EntityCollection result = null; QueryExpression relatedEntityQuery = new QueryExpression(); relatedEntityQuery.EntityName = relatedEntityName; relatedEntityQuery.ColumnSet = new ColumnSet(false); Relationship relationship = new Relationship(); relationship.SchemaName = relationshipName; //relationship.PrimaryEntityRole = EntityRole.Referencing; RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection(); relatedEntity.Add(relationship, relatedEntityQuery); RetrieveRequest request = new RetrieveRequest(); request.RelatedEntitiesQuery = relatedEntity; request.ColumnSet = new ColumnSet(true); request.Target = new EntityReference { Id = _primaryEntityId, LogicalName = primaryEntityName }; RetrieveResponse response = (RetrieveResponse)serviceProxy.Execute(request); RelatedEntityCollection relatedEntityCollection = response.Entity.RelatedEntities; tracingService.Trace("After get the RelatedEntityCollection"); if (relatedEntityCollection != null) { tracingService.Trace("RelatedEntityCollection Count: {0}, RelatedEntityCollection.Values.Count:{1}", relatedEntityCollection.Count, relatedEntityCollection.Values.Count); if (relatedEntityCollection.Count > 0 && relatedEntityCollection.Values.Count > 0) { result = (EntityCollection)relatedEntityCollection.Values.ElementAt(0); } } return(result); } catch (Exception ex) { throw; } }
public static EntityCollection RetrieveManyToManyRelationship(string currentEntityLogicalName , string otherEntityPrimaryIdAttribute , Microsoft.Xrm.Sdk.EntityReference otherEntityReference , string relationshipSchemaName , IOrganizationService organizationService ) { EntityCollection entityCollection = null; Microsoft.Xrm.Sdk.Relationship relationship = new Microsoft.Xrm.Sdk.Relationship(relationshipSchemaName); QueryExpression query = new QueryExpression(); query.EntityName = currentEntityLogicalName; query.ColumnSet = new ColumnSet(true); RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection(); relatedEntity.Add(relationship, query); RetrieveRequest request = new RetrieveRequest(); request.RelatedEntitiesQuery = relatedEntity; request.ColumnSet = new ColumnSet(otherEntityPrimaryIdAttribute); request.Target = otherEntityReference; RetrieveResponse response = (RetrieveResponse)organizationService.Execute(request); if (((DataCollection <Microsoft.Xrm.Sdk.Relationship, Microsoft.Xrm.Sdk.EntityCollection>)(((RelatedEntityCollection)(response.Entity.RelatedEntities)))).Contains(new Microsoft.Xrm.Sdk.Relationship(relationshipSchemaName)) && ((DataCollection <Microsoft.Xrm.Sdk.Relationship, Microsoft.Xrm.Sdk.EntityCollection>)(((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Microsoft.Xrm.Sdk.Relationship(relationshipSchemaName)].Entities.Any()) { DataCollection <Microsoft.Xrm.Sdk.Entity> results = ((DataCollection <Microsoft.Xrm.Sdk.Relationship, Microsoft.Xrm.Sdk.EntityCollection>)(((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Microsoft.Xrm.Sdk.Relationship(relationshipSchemaName)].Entities; if (results != null && results.Any()) { entityCollection = new EntityCollection(); entityCollection.Entities.AddRange(results); } } return(entityCollection); }
protected override RetrieveRequest ToRetrieveRequest(EntityReference id) { // build the related entity queries var siteSettingFetch = new Fetch { Entity = new FetchEntity("adx_sitesetting", WebsiteConstants.WebsiteSettingAttributes.ToFilteredColumns(this.BaseSolutionCrmVersion)) { Filters = new[] { new Filter { Conditions = GetActiveStateConditions().ToArray() } } } }; var bindingFetch = new Fetch { Entity = new FetchEntity("adx_websitebinding", WebsiteConstants.WebsiteBindingAttributes.ToFilteredColumns(this.BaseSolutionCrmVersion)) { Filters = new[] { new Filter { Conditions = GetActiveStateConditions().ToArray() } } } }; var relatedEntitiesQuery = new RelationshipQueryCollection { { WebsiteConstants.WebsiteSiteSettingRelationship, siteSettingFetch.ToFetchExpression() }, { WebsiteConstants.WebsiteBindingRelationship, bindingFetch.ToFetchExpression() }, }; // retrieve the local identity by ID including its related entities var request = new RetrieveRequest { Target = id, ColumnSet = new ColumnSet(this.GetWebsiteAttributes().ToArray()), RelatedEntitiesQuery = relatedEntitiesQuery }; return(request); }
public static DataCollection <Entity> GetRelatedEntities(this IOrganizationService service, string primaryEntityName, Guid primaryEntityId, string relationshipName, string targetEntityName) { //the related entity we are going to retrieve var query = new QueryExpression { EntityName = targetEntityName, ColumnSet = new ColumnSet() }; query.ColumnSet.AllColumns = true; //the relationship that links the primary to the target var relationship = new Relationship(relationshipName) { PrimaryEntityRole = EntityRole.Referenced }; //important if the relationship is self-referencing //the query collection which forms the request var relatedEntity = new RelationshipQueryCollection { { relationship, query } }; //the request to get the primary entity with the related records var request = new RetrieveRequest { RelatedEntitiesQuery = relatedEntity, ColumnSet = new ColumnSet(), Target = new EntityReference(primaryEntityName, primaryEntityId) }; var response = (RetrieveResponse)service.Execute(request); //query the returned collection for the target entity ids return(response.Entity.RelatedEntities[relationship].Entities); }
public void TestAssocDissocNN() { using (var context = new Xrm(orgAdminUIService)) { var relatedAccounts = new EntityReferenceCollection { new EntityReference(Account.EntityLogicalName, account1.Id), new EntityReference(Account.EntityLogicalName, account2.Id), new EntityReference(Account.EntityLogicalName, account3.Id) }; var relatedContacts = new EntityReferenceCollection { new EntityReference(Contact.EntityLogicalName, contact1.Id), new EntityReference(Contact.EntityLogicalName, contact2.Id) }; Relationship relationship = new Relationship(dg_account_contact.EntityLogicalName); orgAdminUIService.Associate(Contact.EntityLogicalName, contact1.Id, relationship, relatedAccounts); orgAdminUIService.Associate(Contact.EntityLogicalName, contact2.Id, relationship, relatedAccounts); var relationQuery = new RelationshipQueryCollection(); var query = new QueryExpression(Account.EntityLogicalName) { ColumnSet = new ColumnSet("name") }; relationQuery.Add(relationship, query); var req = new RetrieveRequest { ColumnSet = new ColumnSet("firstname"), RelatedEntitiesQuery = relationQuery, Target = new EntityReference(Contact.EntityLogicalName, contact1.Id) }; var retrievedContact = (orgAdminUIService.Execute(req) as RetrieveResponse).Entity as Contact; var related = retrievedContact.RelatedEntities[relationship].Entities; Assert.AreEqual(3, related.Count()); Assert.AreEqual(account1.Id, related.FirstOrDefault(e => (e as Account).Name == account1.Name).Id); Assert.AreEqual(account2.Id, related.FirstOrDefault(e => (e as Account).Name == account2.Name).Id); Assert.AreEqual(account3.Id, related.FirstOrDefault(e => (e as Account).Name == account3.Name).Id); orgAdminUIService.Disassociate(Contact.EntityLogicalName, contact1.Id, relationship, relatedAccounts); relationQuery = new RelationshipQueryCollection(); query = new QueryExpression(Account.EntityLogicalName) { ColumnSet = new ColumnSet("name") }; relationQuery.Add(relationship, query); req = new RetrieveRequest { ColumnSet = new ColumnSet("firstname"), RelatedEntitiesQuery = relationQuery, Target = new EntityReference(Contact.EntityLogicalName, contact1.Id) }; retrievedContact = (orgAdminUIService.Execute(req) as RetrieveResponse).Entity as Contact; Assert.AreEqual(0, retrievedContact.RelatedEntities.Count); relationQuery = new RelationshipQueryCollection(); query = new QueryExpression(Account.EntityLogicalName) { ColumnSet = new ColumnSet("name") }; relationQuery.Add(relationship, query); req = new RetrieveRequest { ColumnSet = new ColumnSet("firstname"), RelatedEntitiesQuery = relationQuery, Target = new EntityReference(Contact.EntityLogicalName, contact2.Id) }; retrievedContact = (orgAdminUIService.Execute(req) as RetrieveResponse).Entity as Contact; related = retrievedContact.RelatedEntities[relationship].Entities; Assert.AreEqual(3, related.Count()); Assert.AreEqual(account1.Id, related.FirstOrDefault(e => (e as Account).Name == account1.Name).Id); Assert.AreEqual(account2.Id, related.FirstOrDefault(e => (e as Account).Name == account2.Name).Id); Assert.AreEqual(account3.Id, related.FirstOrDefault(e => (e as Account).Name == account3.Name).Id); } }
public static EntityReference RetrieveParentRecord(string expression, IOrganizationService service, IWorkflowContext context, ITracingService trace) { if (service == null) { throw new InvalidPluginExecutionException("service is null"); } if (context == null) { throw new InvalidPluginExecutionException("context is null"); } string sourceId = string.Empty; EntityReference returnValue = null; #region ParseString trace.Trace("Parsing the string - Start"); string[] separators = { "||" }; string[] words = expression.Split(separators, StringSplitOptions.RemoveEmptyEntries); trace.Trace("Parsing the string - End"); #endregion ParseString #region RetrievParentRecord trace.Trace("RetrievParentRecord - Start"); for (var i = 0; i < words.Length - 1; i++) { List <Entity> parentEntityRecords = new List <Entity>(); //the related entity we are going to retrieve QueryExpression query = new QueryExpression(); query.EntityName = words[i + 1].Substring(words[i + 1].IndexOf(";") + 1); query.ColumnSet = new ColumnSet(); //check relationship Exist or not in the CRM system RelationshipExistOrNot(words[i + 1].Substring(0, words[i + 1].IndexOf(";")), service); //the relationship that links the primary to the target Relationship relationship = new Relationship(words[i + 1].Substring(0, words[i + 1].IndexOf(";"))); relationship.PrimaryEntityRole = EntityRole.Referenced; //important if the relationship is self-referencing //the query collection which forms the request RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection(); relatedEntity.Add(relationship, query); //the request to get the primary entity with the related records RetrieveRequest request = new RetrieveRequest(); request.RelatedEntitiesQuery = relatedEntity; request.ColumnSet = new ColumnSet(); if (i == 0) { if (context.PrimaryEntityName != words[i].Substring(words[i].IndexOf(";") + 1)) { throw new InvalidPluginExecutionException("First Entity name should be the name of workflow execution entity "); } request.Target = new EntityReference(context.PrimaryEntityName, context.PrimaryEntityId); } else { request.Target = new EntityReference(words[i].Substring(words[i].IndexOf(";") + 1), new Guid(sourceId)); } RetrieveResponse response = (RetrieveResponse)service.Execute(request); //query the returned collection for the target entity ids parentEntityRecords = response.Entity.RelatedEntities[relationship].Entities.Select(e => e).ToList(); if (parentEntityRecords.Count > 0) { sourceId = parentEntityRecords[0].Id.ToString(); if (i == (words.Length - 2)) { returnValue = new EntityReference(words[i + 1].Substring(words[i + 1].IndexOf(";") + 1), parentEntityRecords[0].Id); } } } trace.Trace("RetrievParentRecord - End"); return(returnValue); #endregion RetrievParentRecord }
public void TestRetrieveRelatedEntities() { using (var context = new Xrm(orgAdminUIService)) { var accountName = "Litware, Inc."; var _accountId = orgAdminUIService.Create( new Account { Name = accountName, Address1_StateOrProvince = "Colorado" }); // Create the two contacts. var _contact1Id = orgAdminUIService.Create( new Contact() { FirstName = "Ben", LastName = "Andrews", EMailAddress1 = "*****@*****.**", Address1_City = "Redmond", Address1_StateOrProvince = "WA", Address1_Telephone1 = "(206)555-5555", ParentCustomerId = new EntityReference { Id = _accountId, LogicalName = Account.EntityLogicalName } }); var _contact2Id = orgAdminUIService.Create( new Contact() { FirstName = "Alan", LastName = "Wilcox", EMailAddress1 = "*****@*****.**", Address1_City = "Bellevue", Address1_StateOrProvince = "WA", Address1_Telephone1 = "(425)555-5555", ParentCustomerId = new EntityReference { Id = _accountId, LogicalName = Account.EntityLogicalName } }); //create the query expression object QueryExpression query = new QueryExpression(); //Query on reated entity records query.EntityName = "contact"; //Retrieve the all attributes of the related record query.ColumnSet = new ColumnSet(true); //create the relationship object Relationship relationship = new Relationship(); //add the condition where you can retrieve only the account related active contacts query.Criteria = new FilterExpression(); query.Criteria.AddCondition(new ConditionExpression("address1_city", ConditionOperator.Equal, "Bellevue")); // name of relationship between account & contact relationship.SchemaName = "contact_customer_accounts"; //create relationshipQueryCollection Object RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection(); //Add the your relation and query to the RelationshipQueryCollection relatedEntity.Add(relationship, query); //create the retrieve request object RetrieveRequest request = new RetrieveRequest(); //add the relatedentities query request.RelatedEntitiesQuery = relatedEntity; //set column to and the condition for the account request.ColumnSet = new ColumnSet("accountid"); request.Target = new EntityReference { Id = _accountId, LogicalName = "account" }; //execute the request RetrieveResponse response = (RetrieveResponse)orgAdminUIService.Execute(request); Assert.AreEqual(1, response.Entity.RelatedEntities.Count); var collection = response.Entity.RelatedEntities.Values.First(); Assert.AreEqual(1, collection.Entities.Count); var entity = collection.Entities.First(); Assert.IsTrue(entity.Attributes.ContainsKey("firstname")); Assert.AreEqual("Alan", entity.Attributes["firstname"]); } }
//TODO: update to also take in cascading filtering on Assign, Delete, Merge, reparent, rollup internal Entity GetDbEntityWithRelatedEntities(EntityReference reference, EntityRole primaryEntityRole, EntityReference userRef, CascadeSelection cascadeSelection = null, params Relationship[] relations) { var entity = db.GetEntityOrNull(reference); if (entity == null) { return(null); } var metadata = this.metadata.EntityMetadata.GetMetadata(entity.LogicalName); if (entity.RelatedEntities.Count() > 0) { var clone = entity.CloneEntity(metadata, new ColumnSet(true)); db.Update(clone); entity = clone; } var relationQuery = new RelationshipQueryCollection(); var relationsMetadata = primaryEntityRole == EntityRole.Referenced ? metadata.OneToManyRelationships : metadata.ManyToOneRelationships; if (cascadeSelection != null) { relationsMetadata.Where(x => CascadeCompare(x.CascadeConfiguration, cascadeSelection)); } if (relations.Any()) { relationsMetadata = relationsMetadata.Join(relations, x => x.SchemaName, y => y.SchemaName, (r1, r2) => r1).ToArray(); } relationQuery.AddRange( relationsMetadata .Select(relationshipMeta => { var rel = new Relationship() { SchemaName = relationshipMeta.SchemaName, PrimaryEntityRole = primaryEntityRole }; var query = new QueryExpression() { EntityName = primaryEntityRole == EntityRole.Referenced ? relationshipMeta.ReferencingEntity : relationshipMeta.ReferencedEntity, ColumnSet = new ColumnSet(true) }; return(new KeyValuePair <Relationship, QueryBase>(rel, query)); })); foreach (var relationshipMeta in relationsMetadata) { } if (cascadeSelection == null) { var relationShipManyMetadata = metadata.ManyToManyRelationships; if (relations.Any()) { relationShipManyMetadata = relationShipManyMetadata.Join(relations, x => x.SchemaName, y => y.SchemaName, (r1, r2) => r1).ToArray(); } relationQuery.AddRange(relationShipManyMetadata .Select(relationshipMeta => { var rel = new Relationship() { SchemaName = relationshipMeta.SchemaName }; var query = new QueryExpression(relationshipMeta.IntersectEntityName) { ColumnSet = new ColumnSet(true) }; return(new KeyValuePair <Relationship, QueryBase>(rel, query)); })); } AddRelatedEntities(entity, relationQuery, userRef); return(entity); }
protected override void Execute(CodeActivityContext executionContext) { //Create the tracing service ITracingService tracingService = executionContext.GetExtension <ITracingService>(); //Create the context IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); Relationship primaryContactRelationship = new Relationship("account_primary_contact"); Guid primaryContactId = service.Create(new Contact() { LastName = RootContactLastName.Get <string>(executionContext) }); //tracingService.Trace("Create an Account with an existing primary contact"); Account rootAccount = new Account() { Name = RelatedAccountName.Get <string>(executionContext) }; Contact primaryContact = new Contact() { EntityState = EntityState.Changed, Id = primaryContactId, FirstName = RootContactFirstName.Get <string>(executionContext) }; rootAccount.RelatedEntities[primaryContactRelationship] = new EntityCollection(new Entity[] { primaryContact }) { EntityName = Contact.EntityLogicalName }; tracingService.Trace("Execute the Create/Update"); rootAccount.Id = service.Create(rootAccount); //Create the related entities query RelationshipQueryCollection retrieveRelatedEntities = new RelationshipQueryCollection(); retrieveRelatedEntities[primaryContactRelationship] = new QueryExpression(Account.EntityLogicalName) { ColumnSet = new ColumnSet("name"), Criteria = new FilterExpression() }; //Create the request RetrieveResponse response = (RetrieveResponse)service.Execute(new RetrieveRequest() { ColumnSet = new ColumnSet("firstname"), RelatedEntitiesQuery = retrieveRelatedEntities, Target = new EntityReference(primaryContact.LogicalName, primaryContact.Id) }); tracingService.Trace("Retrieve the record with its related entities"); Contact retrievedContact = (Contact)response.Entity; Account retrievedAccount = (Account)retrievedContact.RelatedEntities[primaryContactRelationship][0]; tracingService.Trace("Ensure the first name was updated"); if (retrievedContact.FirstName == primaryContact.FirstName) { tracingService.Trace("Primary Contact name is correct"); } else { tracingService.Trace("First Name is \"{0}\", expected \"{1}\".", retrievedContact.FirstName, primaryContact.FirstName); throw new InvalidPluginExecutionException("The first name was not changed"); } }
protected override void Execute(CodeActivityContext executionContext) { //Create the tracing service ITracingService tracingService = executionContext.GetExtension<ITracingService>(); //Create the context IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); Relationship primaryContactRelationship = new Relationship("account_primary_contact"); Guid primaryContactId = service.Create(new Contact() { LastName = RootContactLastName.Get<string>(executionContext) }); //tracingService.Trace("Create an Account with an existing primary contact"); Account rootAccount = new Account() { Name = RelatedAccountName.Get<string>(executionContext) }; Contact primaryContact = new Contact() { EntityState = EntityState.Changed, Id = primaryContactId, FirstName = RootContactFirstName.Get<string>(executionContext) }; rootAccount.RelatedEntities[primaryContactRelationship] = new EntityCollection(new Entity[] { primaryContact }) { EntityName = Contact.EntityLogicalName }; tracingService.Trace("Execute the Create/Update"); rootAccount.Id = service.Create(rootAccount); //Create the related entities query RelationshipQueryCollection retrieveRelatedEntities = new RelationshipQueryCollection(); retrieveRelatedEntities[primaryContactRelationship] = new QueryExpression(Account.EntityLogicalName) { ColumnSet = new ColumnSet("name"), Criteria = new FilterExpression() }; //Create the request RetrieveResponse response = (RetrieveResponse)service.Execute(new RetrieveRequest() { ColumnSet = new ColumnSet("firstname"), RelatedEntitiesQuery = retrieveRelatedEntities, Target = new EntityReference(primaryContact.LogicalName, primaryContact.Id) }); tracingService.Trace("Retrieve the record with its related entities"); Contact retrievedContact = (Contact)response.Entity; Account retrievedAccount = (Account)retrievedContact.RelatedEntities[primaryContactRelationship][0]; tracingService.Trace("Ensure the first name was updated"); if (retrievedContact.FirstName == primaryContact.FirstName) { tracingService.Trace("Primary Contact name is correct"); } else { tracingService.Trace("First Name is \"{0}\", expected \"{1}\".", retrievedContact.FirstName, primaryContact.FirstName); throw new InvalidPluginExecutionException("The first name was not changed"); } }
internal void AddRelatedEntities(Entity entity, RelationshipQueryCollection relatedEntityQuery, EntityReference userRef) { foreach (var relQuery in relatedEntityQuery) { var relationship = relQuery.Key; var queryExpr = relQuery.Value as QueryExpression; if (queryExpr == null) { queryExpr = XmlHandling.FetchXmlToQueryExpression(((FetchExpression)relQuery.Value).Query); } var relationshipMetadata = Utility.GetRelatedEntityMetadata(metadata.EntityMetadata, queryExpr.EntityName, relationship.SchemaName); var oneToMany = relationshipMetadata as OneToManyRelationshipMetadata; var manyToMany = relationshipMetadata as ManyToManyRelationshipMetadata; if (oneToMany != null) { if (relationship.PrimaryEntityRole == EntityRole.Referencing) { var entityAttributes = db.GetEntityOrNull(entity.ToEntityReference()).Attributes; if (entityAttributes.ContainsKey(oneToMany.ReferencingAttribute) && entityAttributes[oneToMany.ReferencingAttribute] != null) { var referencingGuid = Utility.GetGuidFromReference(entityAttributes[oneToMany.ReferencingAttribute]); queryExpr.Criteria.AddCondition( new ConditionExpression(oneToMany.ReferencedAttribute, ConditionOperator.Equal, referencingGuid)); } } else { queryExpr.Criteria.AddCondition( new ConditionExpression(oneToMany.ReferencingAttribute, ConditionOperator.Equal, entity.Id)); } } if (manyToMany != null) { if (db[manyToMany.IntersectEntityName].Count() > 0) { var conditions = new FilterExpression(LogicalOperator.Or); if (entity.LogicalName == manyToMany.Entity1LogicalName) { queryExpr.EntityName = manyToMany.Entity2LogicalName; var relatedIds = db[manyToMany.IntersectEntityName] .Where(row => row.GetColumn <Guid>(manyToMany.Entity1IntersectAttribute) == entity.Id) .Select(row => row.GetColumn <Guid>(manyToMany.Entity2IntersectAttribute)); foreach (var id in relatedIds) { conditions.AddCondition( new ConditionExpression(null, ConditionOperator.Equal, id)); } } else { queryExpr.EntityName = manyToMany.Entity1LogicalName; var relatedIds = db[manyToMany.IntersectEntityName] .Where(row => row.GetColumn <Guid>(manyToMany.Entity2IntersectAttribute) == entity.Id) .Select(row => row.GetColumn <Guid>(manyToMany.Entity1IntersectAttribute)); foreach (var id in relatedIds) { conditions.AddCondition( new ConditionExpression(null, ConditionOperator.Equal, id)); } } queryExpr.Criteria = conditions; } } var entities = new EntityCollection(); if ((oneToMany != null || manyToMany != null) && queryExpr.Criteria.Conditions.Count > 0) { var handler = RequestHandlers.Find(x => x is RetrieveMultipleRequestHandler); var req = new RetrieveMultipleRequest { Query = queryExpr }; var resp = handler.Execute(req, userRef) as RetrieveMultipleResponse; entities = resp.EntityCollection; } if (entities.Entities.Count() > 0) { entity.RelatedEntities.Add(relationship, entities); } } }
private static void Initialize() { const string fetchXml = "__fetchXml__"; const string schemaName = "__schemaName__"; const string entityName = "__entityName__"; const string logicalName = "__logicalName__"; const string attributeName = "__attributeName__"; const EntityFilters filters = EntityFilters.All; var id = new Guid("ffffffff-ffff-ffff-ffff-ffffffffffff"); var retrieveRequest = new RetrieveRequest { ColumnSet = new ColumnSet(true), Target = new EntityReference(logicalName, id) }; _serializedRetrieveRequestFormat = SerializeForFormat(retrieveRequest) .Replace(logicalName, @"{0}") .Replace(id.ToString(), @"{1}"); var relationship = new Relationship(schemaName) { PrimaryEntityRole = EntityRole.Referencing }; var query = new RelationshipQueryCollection { { relationship, new QueryExpression(entityName) { ColumnSet = new ColumnSet(true) } } }; var retrieveRequestWithRelatedQuery = new RetrieveRequest { ColumnSet = new ColumnSet(), Target = new EntityReference(logicalName, id), RelatedEntitiesQuery = query }; _serializedRetrieveRequestWithRelatedQueryFormat = SerializeForFormat(retrieveRequestWithRelatedQuery) .Replace(logicalName, @"{0}") .Replace(id.ToString(), @"{1}") .Replace(schemaName, @"{2}") .Replace(@"""PrimaryEntityRole"":0", @"""PrimaryEntityRole"":{3}") .Replace(entityName, @"{4}"); var retrieveAllEntitiesRequest = new RetrieveAllEntitiesRequest { EntityFilters = filters, RetrieveAsIfPublished = true }; _serializedRetrieveAllEntitiesRequestFormat = SerializeForFormat(retrieveAllEntitiesRequest) .Replace(((int)filters).ToString(), @"{0}") .Replace("true", @"{1}"); var retrieveEntityRequest = new RetrieveEntityRequest { EntityFilters = filters, LogicalName = logicalName, RetrieveAsIfPublished = true }; _serializedRetrieveEntityRequestFormat = SerializeForFormat(retrieveEntityRequest) .Replace(((int)filters).ToString(), @"{0}") .Replace(logicalName, @"{1}") .Replace("true", @"{2}"); var retrieveMultipleRequest = new RetrieveMultipleRequest { Query = new QueryExpression(logicalName) { Distinct = true } }; _serializedRetrieveMultipleRequestFormat = SerializeForFormat(retrieveMultipleRequest) .Replace(logicalName, @"{0}") .Replace("true", @"{1}"); var retrieveMultipleFetchExpressionRequest = new RetrieveMultipleRequest { Query = new FetchExpression(fetchXml) }; _serializedRetrieveMultipleFetchExpressionFormat = SerializeForFormat(retrieveMultipleFetchExpressionRequest) .Replace(fetchXml, @"{0}"); var retrieveRelationshipRequest = new RetrieveRelationshipRequest { Name = logicalName, RetrieveAsIfPublished = true }; _serializedRetrieveRelationshipRequestFormat = SerializeForFormat(retrieveRelationshipRequest) .Replace(logicalName, @"{0}") .Replace("true", @"{1}"); var retrieveLocLabelsRequest = new RetrieveLocLabelsRequest { EntityMoniker = new EntityReference(logicalName, id), AttributeName = attributeName, IncludeUnpublished = true }; _serializedRetrieveLocLabelsRequestFormat = SerializeForFormat(retrieveLocLabelsRequest) .Replace(logicalName, @"{0}") .Replace(id.ToString(), @"{1}") .Replace(attributeName, @"{2}") .Replace("true", @"{3}"); var retrieveProvLangsRequest = new RetrieveProvisionedLanguagesRequest(); _serializedRetrieveProvisionedLanguagesRequestFormat = SerializeForFormat(retrieveProvLangsRequest); }
protected void Page_Load(object sender, EventArgs e) { ClientScriptManager csm = Page.ClientScript; string display = ""; string prodid = Request["prodid"]; string connectionString = GetServiceConfiguration(); Dictionary <string, object> result = new Dictionary <string, object>(); string json = ""; if (connectionString != null && prodid != null) { display = "Invalid prodid"; csm.RegisterClientScriptBlock(this.GetType(), "Pop", "alert('" + display + "');", true); CrmServiceClient conn = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionString); _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy; DataSet dataSet = new DataSet("product"); DataTable table = new DataTable("products"); DataColumn col_product_id = new DataColumn("productId"); DataColumn col_product_name = new DataColumn("productName"); DataColumn col_product_number = new DataColumn("productNumber"); DataColumn col_product_parent = new DataColumn("productcategory"); DataColumn col_amount_value = new DataColumn("productprice"); //DataColumn col_product_description = new DataColumn("description"); DataColumn col_product_image = new DataColumn("image"); DataColumn col_product_url = new DataColumn("url"); table.Columns.Add(col_product_id); table.Columns.Add(col_product_name); table.Columns.Add(col_product_parent); table.Columns.Add(col_product_number); table.Columns.Add(col_amount_value); //table.Columns.Add(col_product_description); table.Columns.Add(col_product_image); table.Columns.Add(col_product_url); dataSet.Tables.Add(table); QueryExpression qe = new QueryExpression("product"); qe.ColumnSet = new ColumnSet("name", "productnumber", "price", "parentproductid", "description", "adx_partialurl"); qe.Criteria.AddCondition("productnumber", ConditionOperator.Equal, prodid); EntityCollection results = _orgService.RetrieveMultiple(qe); if (results.Entities != null) { foreach (Entity product in results.Entities) { DataRow newRow = table.NewRow(); newRow["productId"] = product.Id.ToString(); newRow["productName"] = product["name"]; newRow["productNumber"] = product["productnumber"]; newRow["productcategory"] = product.GetAttributeValue <EntityReference>("parentproductid").Name; newRow["productprice"] = ((Money)(product["price"])).Value.ToString("0.00", CultureInfo.InvariantCulture); //newRow["description"] = product["description"]; newRow["url"] = product["adx_partialurl"]; EntityReference productRef = new EntityReference("product", new Guid(product.Id.ToString())); RelationshipQueryCollection relationshipQueryColl = new RelationshipQueryCollection(); Relationship relationship = new Relationship(); relationship.SchemaName = "productsalesliterature_association"; QueryExpression qe2 = new QueryExpression("salesliterature"); qe2.ColumnSet = new ColumnSet(true); relationshipQueryColl.Add(relationship, qe2); RetrieveRequest retrieveRequest = new RetrieveRequest(); retrieveRequest.RelatedEntitiesQuery = relationshipQueryColl; retrieveRequest.Target = productRef; retrieveRequest.ColumnSet = new ColumnSet(true); //CrmConnection connection = new CrmConnection("CRM"); string connectionString2 = GetServiceConfiguration(); //using (var _serviceProxy = new OrganizationService(connection)) if (connectionString2 != null) { //OrganizationResponse response = _serviceProxy.Execute(retrieveRequest); CrmServiceClient conn2 = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionString2); _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy; OrganizationResponse response = _orgService.Execute(retrieveRequest); Entity product2 = (Entity)response.Results["Entity"]; EntityCollection ecRelatedSalesLiterature = product2.RelatedEntities[relationship]; if (ecRelatedSalesLiterature.Entities != null) { QueryExpression qe3 = new QueryExpression("salesliteratureitem"); qe3.ColumnSet = new ColumnSet(true); qe3.Criteria.AddCondition("salesliteratureid", ConditionOperator.Equal, ecRelatedSalesLiterature.Entities[0].Id); EntityCollection results2 = _orgService.RetrieveMultiple(qe3); if (results2.Entities != null) { newRow["image"] = results2.Entities[0]["documentbody"]; } } // do whatever you want } table.Rows.Add(newRow); } } json = JsonConvert.SerializeObject(dataSet, Formatting.Indented); Response.ContentType = "application/json; charset=utf-8"; Response.Write(json); } else { display = "Invalid prodid"; csm.RegisterClientScriptBlock(this.GetType(), "Pop", "alert('" + display + "');", true); } }