How to – Using Server-side concurrency control with Dynamics CRM
Concurrency control is the mechanism through which outcome of the update \ delete operation of a record is defined, when you have multiple user working on a same record at the same time i.e. concurrently.
We have basically 2 types of concurrency control.
Optimistic concurrency control in which you don’t allow update to the record, if it is updated since it was retrieved.
In Pessimistic concurrency control, the record is itself locked so that other users are not able to access them.
Dynamics CRM currently offers only Optimistic Concurrency control. It is supported on all OOB entities enable for offline sync along with all the custom entities.
You can check for IsOptimisticConcurrencyEnabled property for the entity to check if is Optimistic Concurrency is enabled of the entity or not.
To apply this behaviour, you can use ConcurrencyBehaviour property of UpdateRequest and DeleteRequest. This property can also available for OrganizationServiceContext class, which effectively applies to all the update and delete requests using that context.
To see it in action, CRM programmers will take an example of an existing contact record in Dynamics CRM.
Let us create a sample application to test the concurrency behaviour.
Create a sample console or windows application in Visual Studio.
Add reference to following NuGet package
Use the below sample code for retrieving the record and then update the record.
Run the application and wait at the breakpoint.
Now go and update the contact record retrieved from Microsoft Dynamics CRM web application.
Run the remaining code block after the breakpoint which updates the same contact record retrieved.
You will get the below exception.
“The version of the existing record doesn’t match the RowVersion property provided”
You will get this error because after retrieving the contact record in code and then updating it in from the CRM’s web application changes the RowVersion of that record.
The same can be tested for the DeleteRequest.
In the background the concurrency is managed using the VersionNumber column of the underlying SQL tables.
Thus, we saw how easily the Optimistic Concurrency can be applied in Microsoft Dynamics CRM, which insures and reduces that there are no data loss when we have chances of multiple users working with the same record.