16/07/2014

Sample CRM 2011 Plugin on Contact

Suppose we want to write a plugin which fires on Update and on Insert to populate Nickname with the first name it’s empty. The plugin is quite straight forward on Insert of the record if the target does not contain nickname it means the user hasn’t provided any value. For update, one way is to compare Pre Image with Post Image to see if the value of nickname is changed. However, the easier option is to have a look at the target message, if preferredname is not in the message it means it hasn’t been updated, however if it is in the message and it’s “empty” it means the user set it to empty and clicked on save. The target entity will contain all the fields which has been changed and they are empty if the attribute has been emptied out.

 
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hooman.Crm.Plugins.Common;
using Hooman.Enterprise.Integration.DynamicsCrm;
using Enums = Hooman.Enterprise.Integration.DynamicsCrm.Enumerations;

namespace Hooman.Crm.Plugins.MAMR2.Contact
{
    /// 
    /// This plugin is responsible for populating Contact's Preferred Name when the record is been created or updated with no preferred name.
    /// 
    /// PostOperation-Create and PostOperation-Update (PreImage) of contact
    /// 
    public class ContactPopulatePrefferedNameWithFirstName : IPlugin
    {
            public void Execute(IServiceProvider serviceProvIder)
            {
                try
                {
                    // Get plugin execution context
                    IPluginExecutionContext context = serviceProvIder.GetPluginExecutionContext();

                    // Get tracing service
                    ITracingService tracingService = (ITracingService)serviceProvIder.GetService(typeof(ITracingService));

                    // Obtain the organization service reference
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvIder
                                                                    .GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                    //The plugin should be registered for create and update of a contact
                    if ((context.MessageName == Messages.Create || context.MessageName == Messages.Update) && context.Stage == Stages.PostOperation)
                    {
                        if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                        {
                            Entity target = ((Entity)context.InputParameters["Target"]);
                            tracingService.Trace("UpdateContactPreferredName. Starting message processing");

                            //Check if the plugin registered on contact
                            if (target.LogicalName.EqualsIgnoreCase(Hooman.Enterprise.Integration.DynamicsCrm.Contact.EntityLogicalName))
                            {
                                tracingService.Trace("UpdateContactPreferredName. creating service context");

                                // I have a wrapper class but you can create your own notmal CRM Service Context instead
                                var crmServiceContext = new CrmServiceContextWrapper(new CrmServiceContext(service));
                                Hooman.Enterprise.Integration.DynamicsCrm.Contact contactEntity 
                                    = target.ToEntity();
                                tracingService.Trace("UpdateContactPreferredName. retirve contact from context.");
                                contactEntity = crmServiceContext.ContactSet.FirstOrDefault(c => c.ContactId == target.Id);

                                // If Preferred Name (NickName) is not in the message and previously empty, update it with FirstName
                                tracingService.Trace("UpdateContactPreferredName. Update the nickname (Preferred Name) with first name.");

                                // on create if the nickname is not in the target message we will populate it from firstname
                                if (context.MessageName.EqualsIgnoreCase(Messages.Create) && !target.Contains("nickname"))
                                {
                                    tracingService.Trace("UpdateContactPreferredName. On create populate the nickname (Preferred Name) with first name.");
                                    target["nickname"] = target["firsname"];
                                }
                                // If the plugin fired on update
                                // if target entity we have recieved does not have nickname and the value in CRM is already emtpy populate it 
                                // with the first name
                                // or if nickname is in the target and is empty (the user deliberately emptied it out) populate it with the first name
                                else if (context.MessageName.EqualsIgnoreCase(Messages.Update) &&
                                    ((!target.Contains("nickname") && contactEntity.NickName == null && contactEntity.FirstName != null)
                                        ||
                                     (target.Contains("nickname") && target.Attributes["nickname"].ToString() == string.Empty)))
                                {
                                        tracingService.Trace("UpdateContactPreferredName. Update the nickname (Preferred Name) with first name.");
                                        target["nickname"] = contactEntity.FirstName.ToString();

                                        tracingService.Trace("UpdateContactPreferredName. about to update the service context.");
                                        service.Update(target);
                                 }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Throw an error message to be displayed in a dialog of the Web application.
                    throw new InvalidPluginExecutionException(Utils.BuildError(ex));
                }
            }
        }
}

No comments:

Post a Comment