Merge accounts using C# in Dynamics CRM 2011

When merging two records, you specify one record as the master record, and Microsoft Dynamics CRM treats the other record as the child record or subordinate record. It will deactivate the child record and copies all of the related records (such as activities, contacts, addresses, cases, notes, and opportunities) to the master record.

Here is the same code to merge two accounts.


 // Merge Accounts
        public void MergeAccounts(Guid masterAccountId, Guid subOrdinateAccountId)
        {
            try
            {
                //Create CRM Connection        
                IOrganizationService crmConnection = GetCRMConnection();

                //Create the target for the request.        
                EntityReference target = new EntityReference();

                //Id is the GUID of the account that is being merged into.        
                //LogicalName is the type of the entity being merged to, as a string        
                target.Id = masterAccountId;
                target.LogicalName = "account";

                //Create the request.        
                MergeRequest merge = new MergeRequest();

                // SubordinateId is the GUID of the account merging.    
                merge.SubordinateId = subOrdinateAccountId;
                merge.Target = target;
                merge.PerformParentingChecks = false;
                Entity updateContent = new Entity("account");
                var cols = new ColumnSet(new[] { "primarycontactid", "websiteurl", "telephone1", "fax", "emailaddress1" });

                //Get Master Account Primary Contact,Website,Phone,Fax,Email
                var masterAccount = crmConnection.Retrieve("account", masterAccountId, cols);

                //Get Subordinate Account Primary Contact,Website,Phone,Fax,Email
                var subOrdinateAccount = crmConnection.Retrieve("account", subOrdinateAccountId, cols);

                //If PrimaryContact,Website,Phone,Fax,Email fields data are populated on the Subordinate Account and NOT populated on the Master Account. updated these Subordinate account values to the Master record.                  
                if (!masterAccount.Contains("primarycontactid") && subOrdinateAccount.Contains("primarycontactid"))
                    updateContent.Attributes.Add("primarycontactid", new EntityReference("contact", subOrdinateAccount.GetAttributeValue<EntityReference>("primarycontactid").Id));

                if (!masterAccount.Contains("websiteurl") && subOrdinateAccount.Contains("websiteurl"))
                    updateContent.Attributes.Add("websiteurl", subOrdinateAccount.Attributes["websiteurl"]);

                if (!masterAccount.Contains("telephone1") && subOrdinateAccount.Contains("telephone1"))
                    updateContent.Attributes.Add("telephone1", subOrdinateAccount.Attributes["telephone1"]);

                if (!masterAccount.Contains("fax") && subOrdinateAccount.Contains("fax"))
                    updateContent.Attributes.Add("fax", subOrdinateAccount.Attributes["fax"]);

                if (!masterAccount.Contains("emailaddress1") && subOrdinateAccount.Contains("emailaddress1"))
                    updateContent.Attributes.Add("emailaddress1", subOrdinateAccount.Attributes["emailaddress1"]);

                merge.UpdateContent = updateContent;

                // Execute the request.   
                MergeResponse mergeRes = (MergeResponse)crmConnection.Execute(merge);
            }
            catch (Exception ex)
            {
                //Throw the exception        
                throw ex;
            }
        }

‘Entity role must be specified for reflexive relationship’ exception in Dynamics CRM 2011

This exception comes when you are trying to associate a record (account) to another record (account) having N:N relationship using C#. In my case account can have multiple payer accounts, got this exception when I was trying to associate payer account.

If you get this exception you need to mention relationship PrimaryEntityRole is EntityRole.Referenced or EntityRole.Referencing. Here is sample code


   public static void CreateAccountPayerRelationship(IOrganizationService service, Guid accountId, Guid payerAccountId)
        {
            Relationship relation = new Relationship("ls_account_account_payer");

            relation.PrimaryEntityRole = EntityRole.Referenced;

            EntityReference erPayerAccount = new EntityReference("account", payerAccountId);

            service.Associate("account", accountId, relation, new EntityReferenceCollection() { erPayerAccount });
        }

Share records using C# in Dynamics CRM 2011

These examples shows how to grant/modify/revoke access privileges for a record with team.


        //Share a record Read,Write and Append privileges with Team
        private void SharePrivileges(string targetEntityName, Guid targetRecordID, Guid teamID, bool read_Access, bool write_Access, bool append_Access, IOrganizationService orgService)
        {
            try
            {
                //Get User or Team reference and Target Entity and record ID that needs to be shared.      
                var recordRef = new EntityReference(targetEntityName, targetRecordID);
                var teamRef = new EntityReference("team", teamID);
                AccessRights Access_Rights = new AccessRights();
                Access_Rights = AccessRights.None;
                //Read Access           
                if (read_Access == true)
                    Access_Rights = AccessRights.ReadAccess;
                //Write Access (or) Read, Write Access        
                if (write_Access == true)
                    if (Access_Rights == AccessRights.None)
                        Access_Rights = AccessRights.WriteAccess;
                    else
                        Access_Rights = Access_Rights | AccessRights.WriteAccess;
                //Append Access or all or any two accesses         
                if (append_Access == true)
                    if (Access_Rights == AccessRights.None)
                        Access_Rights = AccessRights.AppendToAccess | AccessRights.AppendAccess;
                    else
                        Access_Rights = Access_Rights | AccessRights.AppendToAccess | AccessRights.AppendAccess;
                var grantAccess = new GrantAccessRequest
                {
                    PrincipalAccess = new PrincipalAccess
                    {
                        AccessMask = Access_Rights,
                        Principal = teamRef
                    },
                    Target = recordRef
                };
                // Execute the Request      
                orgService.Execute(grantAccess);
            }
            catch (Exception ex)
            {
                throw new Exception("An error occured while applying Sharing rules for the record." + ex.Message);
            }
        }
        //Code to modify privileges for the target record and team   
        private void ModifyAccess(string targetEntityName, Guid targetRecordID, Guid teamID, IOrganizationService orgService)
        {
            try
            {
                //Get User or Team reference and Target Entity and record ID that needs to be shared.          
                var RecordReference = new EntityReference(targetEntityName, targetRecordID);
                var teamRef = new EntityReference("team", teamID);
                AccessRights accessRights = new AccessRights();
                accessRights = AccessRights.DeleteAccess;
                var modifyAcess = new ModifyAccessRequest
                {
                    PrincipalAccess = new PrincipalAccess
                    {
                        AccessMask = accessRights,
                        Principal = teamRef
                    },
                    Target = RecordReference
                };
                // Execute the Request   
                orgService.Execute(modifyAcess);
            }
            catch (Exception ex)
            {
                throw new Exception("An error occured in Modifying access." + ex.Message);
            }
        }
        //Code to remvove the sharing privileges for the target record and team    
        private void RevokeAccess(string targetEntityName, Guid targetRecordID, Guid teamID, IOrganizationService orgService)
        {
            try
            {
                //Get User or Team reference and Target Entity and record ID that needs to be shared.        
                var recordRef = new EntityReference(targetEntityName, targetRecordID);
                var teamRef = new EntityReference("team", teamID);
                var revokeAcess = new RevokeAccessRequest
                {
                    Revokee = teamRef,
                    Target = recordRef
                };
                // Execute the Request        
                orgService.Execute(revokeAcess);
            }
            catch (Exception ex)
            {
                throw new Exception("An error occured in Revoking access." + ex.Message);
            }
        }

Assign a record to a Team using C# in Dynamics CRM 2011

Here is sample C# code how to assign a record to a team.

       //Assign a record to a team
        private void AssignRecord(Entity TargetEntity, Guid TargetRecordID, Guid OwningTeamID, IOrganizationService orgService)
        {
            try
            {
                // Create the Request Object and Set the Request Object's Properties
                AssignRequest assign = new AssignRequest
                {
                    Assignee = new EntityReference("team", OwningTeamID),
                    Target = new EntityReference(TargetEntity.LogicalName, TargetRecordID)
                };

                // Execute the Request
                orgService.Execute(assign);
            }
            catch (Exception ex)
            {
                throw new Exception("An error occured while assinging Team to a record." + ex.Message);
            }
        }