Thursday, June 10, 2010

CRM 4 Auto-Numbering – A plugin approach




CRM 4 has lots of excellent customization options, one of which is the auto-numbering of entities:

The Settings – Administration section allows you to setup some options for auto-numbering your entities, you can choose the prefix, and the suffix length:









This feature is pretty powerful, but how would approach this problem if you needed your entities to have a more complex numbering scheme? So I would start with a plugin that implements the IPlugin interface:



public class AutoNumber : IPlugin

Then we need to implement the Execute method such as:

public void Execute(IPluginExecutionContext context)
{
   if (context.InputParameters.Properties.Contains("Target"))
   {
     DynamicEntity entity = (DynamicEntity)context.InputParameters.Properties["Target"];

         if (entity != null)
      {
            if (!entity.Properties.Contains("AttributeName"))
          {
                 entity.Properties.Add(new StringProperty("AttributeName", GetAutoNumber()));
         } 
      }
   }
}


Explanation:- The above code will check to make sure the input properties contains the ‘Target’ parameter, this will be the entity that is affected by the plugin. From here we can cast it to a DynamicEntity which will make it easier to work with. Once we have an instance of DynamicEntity the whole task of updating and attributes becomes trivial, the above code just creates a new property and calls some method that will generate the complex AutoNumber.


Once the plugin has been developed, the next important step is to register the plugin. The best tool for the job is probably the CRM Plugin Registration Tool:


NOTE:-

For above Plug-in we will choose the following options:

Message: Create (since we are doing an auto number, it makes sense to only run the plugin at the create stage)

Primary Entity: Your choice

Post Stage: we want to run it after the entity has been created, otherwise the built in CRM auto numbering will overwrite our value.

Synchronous: lets fire the event synchronously, no reason not to, the end user will be presented with a consistent interface this way.

Step Deployment: your choice

Triggering Pipeline: Parent



 

No comments:

Post a Comment