Sep 2, 2014

Update the same entity on Deactivation

This is the code snippet to de activate an entity and it’s straightforward;

SetStateRequest setStateRequest = new SetStateRequest()
    EntityMoniker = new EntityReference
        Id = _accountid,
        LogicalName = "account"
    State = new OptionSetValue(1),
    Status = new OptionSetValue(2)

Now, we will see the tricky part. Sometimes we are asked to update some fields in an entity when deactivated. For example, you are required to modify the field values before deactivating an account. Problem is, once you deactivate it, you are not allowed to modify the values. Hence, you need to do it before deactivation. For this we need to register a plug-in for pre- stage of account for state change. (register two steps; setState and setState Dynamic Entity). Below is the code;

public class AccountDeactivation : IPlugin
public void Execute(IServiceProvider serviceProvider)
    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

        IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
        IOrganizationService crmService = factory.CreateOrganizationService(context.UserId);
        Entities.OrgOrionDatamodel orgSvcContext = new Entities.OrgOrionDatamodel(crmService);

        if ((context.InputParameters.Contains("EntityMoniker")) && (context.InputParameters["EntityMoniker"] is EntityReference))
            var targetEntity = (EntityReference)context.InputParameters["EntityMoniker"];
            var state = (OptionSetValue)context.InputParameters["State"];
            var status = (OptionSetValue)context.InputParameters["Status"];

            if (targetEntity.LogicalName != "account")
            { return; }

            if ((state.Value == 1) && (status.Value == 2)) //Identify when the Deactivation is occuring
                //Logic here
    catch (Exception ex)
        throw new InvalidPluginExecutionException("[" + ex.Message + "]" + ex.StackTrace, ex);
        context = null;

This plug-in fires on (actually before) deactivation of account. Why?
To fire this below conditions should be met;
- State change should occur
- Resulting values of state and status should be 1 and 2 respectively.
(in fact, this satisfies only when deactivation). Since we register the plug-in in pre stage we still can modify the entity itself if needed.

This code is working fine for account and many other entities including custom entities. Please check if you need to implement this to entities with complex state and status values such as lead and opportunity. Change the values of conditions (state and status) to pick the correct occurrence you are interested in.

Related Posts;
Sample Plug-in: State change

No comments:

Post a Comment