Sunday 9 August 2015

Optimistic Concurrency in Dynamics CRM

When more than one user selects the same record and tries to save the record with different updates at the same time, one of the users will have a data loss. To avoid this, you can enable optimistic concurrency when saving and updating the records.


So the main difference is ability to check the version of the transaction and update only if the version number matches.Optimistic concurrency is supported on all out-of-box entities enabled for offline sync and all custom entities. For OOTB entities check if  the attribute IsOptimisticConcurrencyEnabled is set to true. For custom entities, this property is set to true by default.

Please note for Microsoft Dynamics CRM Online organizations, this feature is available only if your organization has updated to Dynamics CRM Online 2015 Update 1. This feature is not available for Dynamics CRM on-premise.

Here is the code samples:

Update if version number matches:
var account = service.Retrieve("account",accountId, new ColumnSet("name","address1_postalcode","creditlimit"));

if (account != null && account["address1_postalcode"] != null && account["address1_postalcode"] == "90210")
{
    Entity updatedAccount = new Entity(){
                                         LogicalName = account.LogicalName,
                                         Id = account.Id,
                                         RowVersion = account.RowVersion
                                        };

   updatedAccount["creditlimit"] = 1000000;
   UpdateRequest accountUpdate = new UpdateRequest(){
                                                      Target = updatedAccount,                                                   ConcurrencyBehavior = ConcurrencyBehavior.IfVersionMatches
                                                     };
    UpdateResponse accountUpdateResponse = service.Execute<UpdateResponse>(accountUpdate);
}


Delete if version number matches:
 
EntityReference accountToDelete = new EntityReference()
{
    LogicalName = account.LogicalName,
    Id = account.Id,
    RowVersion = account.RowVersion
};

DeleteRequest accountDelete = new DeleteRequest()
{
    Target = accountToDelete,
    ConcurrencyBehavior = ConcurrencyBehavior.IfVersionMatches
};

try
{
    DeleteResponse accountDeleteResponse = service.Execute<DeleteResponse>(accountDelete);
}
catch (FaultException<OrganizationServiceFault> ex)
{
    if (ex.Code == OPTIMISTIC_CONCURRENCY_VIOLATION) {…}
}

No comments:

Post a Comment