Get Faults from an ExecuteMultipleRequest

If you have multiple entities to create or update in a plugin, it can be useful to package all entity create messages up into one bundle and send the request off at once. It is possible to see a performance benefit from this, but typically it's used to fulfill a business requirement. However, it can be trickier to establish if any errors have occurred. When only one request is sent, such as executing a create request for one new entity, typically the request is wrapped in a try/catch block.

Here's an example showing how to bundle multiple UpsertRequests into one ExecuteMultipleRequest:

var entityCollection; // your EntityCollection
var requests = new ExecuteMultipleRequest();
foreach (var entity in entityCollection.Entities) {
var upsertRequest = new UpsertRequest { Target = entity };
requests.Requests.Add(upsertRequest);
}

requests can then be executed to return a list of responses, which can be iterated over. For each response in the iteration, we can determine if a fault occurred and if it did, add the error to a list of errors:

var responses = service.Execute(requests);
var errors = new List<Entity>();
foreach (var response in responses.Responses) {
if (response.Fault) {
var entity = entityCollection[response.RequestIndex];
errors.Add(entity);
}
}
view raw responses.cs hosted with ❤ by GitHub

Notes:
  • response.RequestIndex is used to aaccess the response's corresponding request by matching their indexes.
  • responses.Responses contains a collection of ExecuteMultipleResponseItems.

No comments:

Post a Comment