Updating from party in Email

Introduction
Recently while working on one business requirement where client had two business unit and they were using contacts specific to business unit which means they can have duplicate records for contact or account. While email coming into CRM they wanted to update email from with correct contact from correct business unit if wrong contact is auto populated by CRM. In this article we are going to provide details how we can update from using pre operation plugin.

Requirement
Check from party contact business unit, if it’s not correct update from with correct contact.

Details
We can retrieve from party list from entity object and loop through it like following

if (emailEntity.Contains("from")) {
 EntityCollection from = emailEntity.GetAttributeValue < EntityCollection > ("from");
 //create sender list
 EntityCollection senderList = new EntityCollection();
 if (from != null) {
  from.Entities.ToList().ForEach(party => {
   Guid newContact = Guid.Empty;

   //get party list
   EntityReference partyId = party.GetAttributeValue < EntityReference > ("partyid");
   string contactName = party.GetAttributeValue<string>("addressused");
   
   //process partylist
  
  });

 }

}

Our requirement is to check if from party list is contact type if yes, get and check if it is from correct BU if not get contact from correct BU, if not present create it and set it under from

if (partyId.LogicalName != null && partyId.LogicalName == "contact") {
 //retrieve current associated contact
 Entity currentAssociatedContact = emailLogic.GetContact(partyId.Id);

 //validate for correct contact 
 if (!CheckContactForBU(currentAssociatedContact, ownerid)) {
  //create contact in correct BU
  newContact = CreateContact(contactName, ownerid);

  //add partylist to from
  Entity partyFrom = new Entity("activityparty");
  partyFrom["partyid"] = new EntityReference("contact", newContact);
  partyFrom["addressused"] = contactName;

  senderList.Entities.Add(partyFrom);
 }
}

And finally we can assign sender list to from like following

if (senderList.Entities.Count > 0)
                            {

                                emailEntity["from"] = senderList;
                             }

We need to use this code on pre operation of email entity.This way we can change from email address before creation as after record created it can’t be changed.

Hope it will help someone !!

Leave a Reply

Your email address will not be published. Required fields are marked *