Archiv für den Monat: Juni 2010

Howto: Use pre-generated Guids for records

A customer asked me recently if it is possible to get the id of a record in a pre-create plugin. By default, it is not possible because the record is not yet created at this point and has not got an id.

However, Dynamics CRM allows you to create your own id for a record. The primary key of a record is stored in its Key-Property. On all default entities, for example account, the id property is marked as Valid for create (see accountid). This means, the sdk allows you to pass your own id.

using System;
using Microsoft.Crm.Sdk;
 
namespace PreCreateKeyPlugin
{
    public class PreCreateKeyPlugin : IPlugin
    {
        public void Execute(IPluginExecutionContext context)
        {
            if (IsPreCreate(context))
            {
                if (context.InputParameters.Contains(ParameterName.Target))
                {
                    DynamicEntity target = context.InputParameters[ParameterName.Target] as DynamicEntity;
 
                    if (target != null)
                    {
                        Guid customId = new Guid("{d7256b93-a5b5-45f9-9f2d-a1838279c35c}");
 
                        target["accountid"] = new Key(customId);
                    }
                }
            }
        }
 
        private bool IsPreCreate(IPluginExecutionContext context)
        {
            return  context.MessageName == MessageName.Create && 
                    context.Stage == MessageProcessingStage.BeforeMainOperationOutsideTransaction;
        }
    }
}

If you register this plugin for pre-create on the account entity and create a new account, it will have the provided id.

Please keep in mind, that you are in the responsibility to assign an new GUID for every execution of this plugin, but this should be clear when working with primary keys.