Thursday, October 29, 2009

Auto Numbers in in MS CRM 4.0

I was looking for the simple, supported and mostly acceptable way of auto numbering and got in some blog to use a custom entity in CRM called AutoNumber that tracks the max used autonumber by entity type.

Use a post create callout to populate corresponding entity type’s max value + 1 to the newly-created record, and also to write that new max value to the entry in the AutoNumber record for the entity type.

That way the process fires when offline clients sync their new records to the central database and you end up with no duplicate record contention, since that part of the post callout is (I believe) transaction bound to ensure we don’t get dupes.


There is another simple, supported and mostly acceptable way of auto numbering suggested by “Ayaz Ahmad”.


Read the autonumber attribute Max value and then add 1 to get next auto number. For example you have a custom entity named Project and you want to auto number Project_Ref_Number attribute. But do not retrieve all records. Just retrieve the record with maximum number value by using following two properties of PageInfo Class in SDK and set descending order.

PageInfo.Count = 1;
PageInfo.PageNumber = 1;

Code:-

ColumnSet cols = new ColumnSet();
cols.AddColumns(new string[] { "leadid", "new_autonumber" });

PagingInfo pages = new PagingInfo();
pages.PageNumber = 1;
pages.Count = 1;

QueryExpression query = new QueryExpression();
query.EntityName = EntityName.lead.ToString();
query.ColumnSet = cols;
query.AddOrder("new_autonumber", OrderType.Descending);
query.PageInfo = pages;

RetrieveMultipleRequest request = new RetrieveMultipleRequest();
request.ReturnDynamicEntities = true;
request.Query = query;

RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)service.Execute(request);

if (retrieved.BusinessEntityCollection.BusinessEntities.Count > 0)
{
DynamicEntity results = (DynamicEntity)retrieved.BusinessEntityCollection.BusinessEntities[0];
if (results.Properties.Contains("new_autonumber"))
{
nextNumber = Convert.ToInt32(results.Properties["new_autonumber"].ToString()) + 1;
//add nextNumber as the entity property for the coresponding entity
}
}

One more consideration should be taken in account to register your auto number plugin to at PreCreate rather at PostCreate.

Limitation:
In multi-user environment, this approach can come up with duplicate numbers in Project_Ref_Number when more than one user is creating project records.

1 comment:

Anonymous said...

Great!

Thank you very much!

Regards,
Chris