Reputation: 870
I am trying to set a field (Record Number) on an entity in Pre-Operation plugin that triggers on create with an incremental number based on previous one. For example if the MAX Previous Record Number is 4 I will set the one being created to 5. I am using LINQ to get the MAX exiting number from entity records and then incremented by 1. My concern is that, what if 2 or more plugins execute at the same time and does the same thing. Does CRM has a sequential mechanism to force the plugins to run in sequential order and if NOT how can I avoid 2 plugins getting the same previous maximum record number?
Upvotes: 0
Views: 595
Reputation: 846
The way CRM supports concurrence is: 1. The plug-in must be in the pre or post operation. 2. You need to update one field on the entity you need. (Whatever value you want). 3. You add your logic here.
The third step will grant you one plug-in execute that logic and the others will wait for it until it ends.
Edit: This is what you need:
Entity context = (Entity)executionContext.InputParameters["Target"];
Entity entity = new Entity { LogicalName = "salesorder", Id = context.Id };
entity["new_dummyfield"] = Guid.NewGuid().ToString();
service.Update(entity); // Lock
entity = service.Retrieve("salesorder", context.Id, new ColumnSet("new_autonumber"));
if (!entity.Contains("new_autonumber"))
{
return;
}
int autonumber = (int)entity["new_autonumber"] + 1;
entity["new_autonumber"] = autonumber;
service.Update(entity);
Upvotes: 2
Reputation: 8508
Multiple plugins can indeed run concurrently therefore you cannot guarantee uniqueness of any values calculated in this way. Many solutions use an external database for auto number but keep in mind you won't be able to access this database from a Sandbox plugin.
There is a way in which you can achieve isolation using a custom entity removing the need for the external database discussed here. However, as you'll read, it's not an out of the box feature.
Upvotes: 1