Oct 31, 2012

Sample Plug-in: State change

It is important to catch the action when a state change occurs for a record. What we are referring here is the setting of Status (statecode) and Status Reason (statuscode). They are native CRM fields and they work as combinations. These values even determine whether a record is active or inactive. Here you can see full list of those codes for native CRM entities.

Though, those fields appear normal, one should not attempt to update them using normal update method as any other field. They are special fields and they are changed through state change method only.

What is important is, we have separate messages to capture those state changes and we have to write the plug-in code accordingly. Please refer below code to understand how we grab those codes so that we are ready to implement the logic.

Please note state.Value and status.Value we get in this code is the new values after the set state operation. We may capture whatever the status change we are interested in.

using System;
using System.Collections.Generic;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.ServiceModel;

namespace TestCompany.CRM.Plugin
 public class officeSetState : IPlugin
   public void Execute(IServiceProvider serviceProvider)
     IPluginExecutionContext context;
     IOrganizationServiceFactory factory;
     IOrganizationService service;

       context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
       factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
       service = factory.CreateOrganizationService(context.UserId);

       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 != "new_office")
        { return; }
         // Set State Logic
         // state.Value gives state code
         // status.Value gives status code

      catch (FaultException<OrganizationServiceFault> e)
        throw e;
        service = null;
        factory = null;
        context = null;

Tricky part lies here. When registering the plug-in we need to have steps for both SetState and SetStateDyanamicEntity messages.

Related posts;
Sample Plug-in: Delete
Sample Plug-in: Compare Pre and Post images on Update
Sample Plug-in code: Create and Update
Retrieve attributes of entity object

1 comment: