Wednesday, January 30, 2013

CRM 2011 - ExecuteMultipleRequest provides increased performance for bulk updates

A new request called ExecuteMultipleRequest has been added to the SDK as part of the Dynamics CRM Dec 2011 update aka Polaris. This request allows multiple requests to be submitted in one request increasing performance and throughput.

Many applications developed to do bulk updates have performance issues because they do a single service call for each of their updates. The ExecuteMultipleRequest request allows a collection of requests to be submitted with a single request. The code sample below shows a simple example that creates a collection of requests and executes them in a batch.  As you can see from the example you can mix request and entity types. In this scenario we are creating an account, updating an account and creating a contact on one request.

The settings allow us to configure if we require responses and how to proceed when an error occurs.  If you run the code below this you will find that that the second request fails as we did not provide the id of the account to update. Because we set the Settings option ContinueOnError to true the final request is processed even though the second failed.  If you set ContinueOnError to false the first account will be created and an exception will be thrown once the second request is reached and so any subsequent requests are not processed.

var connection = new CrmConnection("Xrm");
using (OrganizationService _orgService = new OrganizationService(connection))
    ExecuteMultipleRequest emRequests = new ExecuteMultipleRequest();
    emRequests.Requests =  new OrganizationRequestCollection() ;
    emRequests.Settings= new ExecuteMultipleSettings()
                ContinueOnError = false,
                ReturnResponses = true

    CreateRequest accRequest = new CreateRequest();
    Account acc = new Account { Name = "Joe Gill" };
    accRequest.Target = acc;

    UpdateRequest failRequest = new UpdateRequest();
    Account accFail = new Account();
    failRequest.Target = accFail;

    CreateRequest ctRequest = new CreateRequest();
    Contact ct = new Contact { LastName = "Gill" , FirstName="Joe" };
    ctRequest.Target = ct;

    ExecuteMultipleResponse emResults =  (ExecuteMultipleResponse)_orgService.Execute(emRequests);

    foreach (var rep in emResults.Responses)
        if (rep.Fault != null)
            Console.WriteLine("Failed " + rep.Fault.Message) ;


No comments:

Post a Comment