Exemple #1
0
        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 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);
            }
        }
Exemple #3
0
        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);
        }
Exemple #4
0
        /// <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);
            }
        }
        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]);
        }
Exemple #6
0
        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();
        }
Exemple #7
0
 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);
     }
 }
Exemple #8
0
        /// <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;
            }
        }
Exemple #9
0
        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);
        }
Exemple #10
0
        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"]);
            }
        }
        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);
            }
        }
Exemple #12
0
        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
        }
    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);
        }
    }