Tuesday, November 15, 2011

MSCRM 2011 Set Guid (Any Entity Id) Plugin

MSCRM 2011 Set Guid (Any Entity Id) Plugin

http://dynamicslollipops.blogspot.com/2011/10/mscrm-2011-workflow-assembly-get.html

Because it's impossiable to use workflow assembly in Microsoft Dynamics CRM 2011,
This is the piece of code needed for creating plugin that's sets any entity GUID into any test field you choose.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;

namespace MSCRM2011SetGuidPlugin
{
    public class MSCRM2011SetGuidPlugin : IPlugin
    {
        public readonly string rAttributeSchemaName = "new_guid";
        public string m_SecureConfig { get; set; }
        public string m_Config { get; set; }

        public MSCRM2011SetGuidPlugin(string i_Config, string i_SecureConfig)
        {
            m_Config = i_Config;
            m_SecureConfig = i_SecureConfig;
        }


        /// <summary>
        /// A plugin that creates a follow-up task activity when a new account is created.
        /// </summary>
        /// <remarks>Register this plug-in on the Create message, account entity,
        /// and asynchronous mode.
        /// </remarks>
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            tracingService.Trace("Config: " + m_Config);
            string attr = rAttributeSchemaName;
            if (!String.IsNullOrEmpty(m_Config))
            {
                attr = m_Config;
            }
            tracingService.Trace("attr: " + attr);
            tracingService.Trace("id: " + context.PrimaryEntityId);
            Guid id = context.PrimaryEntityId;

            Entity entity = new Entity(context.PrimaryEntityName);
            entity.Id = id;
            entity.Attributes.Add(attr, id.ToString());
            service.Update(entity);
        }
    }

}

If no attribute is in the configuration, then it tries to place the GUID into new_guid.

The complate code project and dll

No comments:

Post a Comment