Saturday, July 31, 2021

Custom Workflow activity to get and set partylist lookup field using C# code

Follow the step-by-step process to Get the value from the email activity From field and set the value in the customer type lookup field.

In my scenario, I want to Get the value from the email activity From partylist field and Set the value in the custom field which is of Customer Type. (i.e. From & Customer)

 Step by step follow below custom activity code:

// Declare InArgument & OutArgument

//Pass email input argument to workflow
        [RequiredArgument]
        [Input("Email")]
        [ReferenceTarget("Email")]
        public InArgument<EntityReference> Email { get; set; }

//Return output parameter which is of contact type in my case
        [ReferenceTarget("contact")]
        [Output("customer")]
        public OutArgument<EntityReference> customer { get; set; }


Write below code inside execute method:


var email = Email.Get(context);
var emailDetails = service.Retrieve(email.LogicalName, email.Id, new ColumnSet("from"));
                    if (emailDetails.Contains("from") && emailDetails["from"] != null)
                    {
                        EntityCollection FromCollection = emailDetails.GetAttributeValue<EntityCollection>("from");


//To get the from reference and set on the Email customer lookup

                        EntityReference fromContact = GetFromContact(FromCollection);
                        customer.Set(context, fromContact);
                    }

//Method to get the value from From field and Set it to Customer Lookup

public EntityReference GetFromContact(EntityCollection fromCollection)
        {
            EntityReference contact = null;
            try
            {
                if (fromCollection != null && fromCollection.Entities.Count > 0)
                {
                    var from = fromCollection.Entities.First();

//To get the entity type
                    var partyId = from.GetAttributeValue<EntityReference>("partyid");
                    tracingService.Trace("PartyId: " + partyId.Id + " PartyId LogicalName: " + partyId.LogicalName);
                    if (partyId.LogicalName == "contact")
                    {

//To set the customer lookup
                        contact = new EntityReference(partyId.LogicalName, partyId.Id);
                    }
 
                }
            }
            catch (Exception ex)
            {
            }
            return contact;

        }


Build, Sign and register the workflow activity code using the Plugin registration tool

Create an OOB Workflow Activity and add the input variable and set the output variable to update.


Thank you..

Keep Learning..!!