Advertisements

Archive

Archive for January 11, 2012

Auto numbering logic in CRM 2011

January 11, 2012 Leave a comment

Hi,

Auto numbering feature is one of the most frequently asked requirement in CRM projects and below is the sample.

In my sample, I am going to generate an auto number to the each ‘Contact’ that create under a particular ‘Account’. The auto number format will be “Contact – 001, Contact – 002,….”.

To achieve the above requirement,  I am going to

  • Create a Plug-In on “Pre – Create” event of the contact
  • Use the CRM early bound

Steps :-

  • Generate  “Organization Service Context Class” using the Code Generation Tool (CrmSvcUtil.exe). (See)
  • You will get a “ServiceContext.cs” file with all entity wrapper classes.
  • Create a new Plug-In project and add the generated “ServiceContext.cs” file
  • Add a new class “ContactAutoNumber.cs” to the project and paste below code

public class ContactAutoNumber: IPlugin {

private Entity dynEntity;

private contact objContact;

public void Execute(IServiceProvider serviceProvider)        {

this.context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

var service = serviceFactory.CreateOrganizationService(this.context.UserId);

if (this.context.InputParameters.Contains(“Target”) && this.context.InputParameters[“Target”] isEntity)  {

// Obtain the target entity from the input parmameters.

this.dynEntity = (Entity)this.context.InputParameters[“Target”];

// Cast “Dynamic Entity” to “Contact”

this.objContact = this.dynEntity.ToEntity<contact>();

}

// Instantiate “Service Context” (i.e., The name of ‘Organization Service Context Class’)

var svcContext = new ServiceContext(service);

// Get the “Contact” list under parent ‘Account’ by “AccountId”

var contacts = svcContext.ContactSet.Where(

ns => (ns.AccountId.Id ==this.objContact.AccountId.Id));

// Get the count of the contacts

var cntContacts= Enumerable.Count(contacts);

// Increment the suffix count

var strFormat = (cntContacts + 1).ToString();

// Logic to prepare format “001,002,…..”

if (strFormat.Length < 3){

strFormat = (strFormat.Length == 1) ?

“00” + strFormat : “0” + strFormat;

}

// Set the auto number to your attribute

this.objContact.{Attribute_Name}= “contact – “ + strFormat;

}

}

}

Plug – In Registration step :-

Message : Create

Entity : contact

Statge : Pre

  • Register the Plug -in as above mentioned

Hope it helps 🙂

Advertisements