In this post let’s write a reusable C# method which replaces an entity using OCC, in the sense, if someone else has updated the entity before we could update it, we will have to pull the entity again, make our changes to the entity and write it to the storage.
In short, If the ETag maintained on the server is different from the one on the entity sent from client, azure storage service doesn’t update the entity, instead it throws an exception with HTTP status code 409.
Let us define the helper method to replace entity:
As you can see, method ReplaceEntityOptimistically iterates over retryCount and tries to update the entity. If fails, it pulls a latest copy of the entity from server, makes necessary changes on the entity using entityUpdateAction and tries to update the entity again. RetrieveEntity method is a trivial method to retrieve the entity again from server.
Now, using this method is simple. All we need is an action to make changes to the entity properties. For example: