You can use optimistic concurrency to detect whether an entity has been modified since it was last retrieved. If the entity you intend to update or delete has changed on the server since you retrieved it, you may not want to complete the update or delete operation. By applying the pattern shown here you can detect this situation, retrieve the most recent version of the entity, and apply any necessary criteria to re-evaluate whether to try the operation again.
Request
PATCH [Organization
URI]/api/data/v8.2/accounts(00000000-0000-0000-0000-000000000001) HTTP/1.1
If-Match: W/"470867"
Accept: application/json
OData-MaxVersion: 4.0
OData-Version: 4.0
{"name":"Updated Account
Name"}
Response
HTTP/1.1 412 Precondition Failed
Content-Type: application/json;
odata.metadata=minimal
OData-Version: 4.0
{
"error":{
"code":"","message":"The version of
the existing record doesn't match the RowVersion property provided.",
"innererror":{
"message":"The version of the existing record doesn't
match the RowVersion property provided.",
"type":"System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault,
Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35]]",
"stacktrace":" <stack trace details omitted for
brevity>
}
}
}
------------------------------------------------------------------------------------------------------
The following update request for an account with accountid of 00000000-0E99-E711-8127-000000000001 fails because the ETag value sent with the If-Match header is different from the current value. If the value had matched means the data which is retrieved is not edited and you have the latest data, a 204 (No Content) status is expected.
function updateLatestData() { // Using optimistic concurrency
function updateLatestData() { // Using optimistic concurrency
var entityName = "accounts";
var clientURL =
Xrm.Page.context.getClientUrl();
var req = new XMLHttpRequest();
req.open("PATCH", encodeURI(clientURL + "/api/data/v8.2/" + entityName + "(00000000-0E99-E711-8127-000000000001)", true));
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("If-Match", "W/\"470867\"");
req.onreadystatechange = function () {
if (this.readyState === 4 /* complete */) {
req.onreadystatechange = null;
if (this.status === 204) {
alert("Record
updated");
}
else {
var error = JSON.parse(this.response).error;
alert(error.message);
}
}
};
req.send(JSON.stringify(
{
name: "Sample Account
updated"
}));
}
No comments:
Post a Comment