Dynamics SDK Batch Requests

In this blog, I will discuss requesting and executing batch operations which is one of the Dynamics SDK capabilities for manipulating large amounts of data to increase overall performance of the dynamics applications.

The batch operation is useful to use in your interaction with Dynamics API in such a way that, instead of sending requests to Dynamics API one at a time and wait for a response, batch request operation will allow you to perform one request, one execution and multi responses in a single transaction. For example, you can create an account, update a contact and read an activity.

Learn more about our Microsoft Dynamics 36 Services 

Learn More

Batch Requests Advantages

Some of the benefits of batch requests are:

  1. Reduced network traffic and latency
  2. More efficient code
  3. Reduced number of API calls.

The example below will show you how to execute a batch request for multiple accounts and one contact entity.

  1. Create a console application in VS. Call it AB.CRM.BatchRequest.
  2. Add the XRMtool core assembly to the solution.
  3. Enter the below statements:
    1. using Microsoft.Xrm.Sdk;
    2. using Microsoft.Xrm.Sdk.Messages;
    3. using Microsoft.Xrm.Tooling.Connector;
  4. Create A Class called BatchRequest.cs
  5. Copy and paste the code given below.

namespace AB.CRM.BatchRequest
{
    class BatchRequest
    {
        private string connectionString;
       private CrmServiceClient crmSvc;
        public BatchRequest(string connectionString)
        {
            this.connectionString = connectionString;
        }
        public void CreateCRMService()
        {
            crmSvc = new CrmServiceClient(this.connectionString);
        }
        public OrganizationRequestCollection BuildData()
        {
            using (var serviceProxy = this.crmSvc.OrganizationServiceProxy)
            {
                //Create request collection
                 var data = new OrganizationRequestCollection()
                {
                    new CreateRequest
                    {
                    Target = new Entity(“account”)
                    {
                        [“name”] = “AB”
                    }
                },
                new CreateRequest
                {
                    Target = new Entity(“account”)
                    {
                        [“name”] = “AB1”
                    }
                },
                new CreateRequest
                {
                    Target = new Entity(“account”)
                    {
                        [“name”] = “AB2”
                    }
                },
                new CreateRequest
                {
                    Target = new Entity(“contact”)
                    {
                        [“firstname”] = “First Name”,
                        [“lastname”] = “Last Name”
                    }
                }
            };
               return data;             }
        }
        public ExecuteMultipleResponse ExecuteBatch(object data)
        {
            using (var serviceProxy = this.crmSvc.OrganizationServiceProxy)
            {
                //Create Transaction and pass  created data request collection
                var requestToCreateRecords = new ExecuteMultipleRequest()
               {
                    Requests = (OrganizationRequestCollection)data,
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = true,
                        ReturnResponses = true
                    }
                };
                //Execute requests
                return (ExecuteMultipleResponse)serviceProxy.Execute(requestToCreateRecords);                 
            }
        }
    }
}

  1. In the main method, add the following code:

        static void Main(string[] args)
{
BatchRequest request = new BatchRequest(“AuthType=Office365;Username=;Password=;Url=https:// “);
request.CreateCRMService();
OrganizationRequestCollection data = request.BuildData();
ExecuteMultipleResponse response  = request.ExecuteBatch(data);
//Print the Guid of records
foreach (var responseItem in response.Responses)
{
Console.WriteLine(“Record Created with GUID {0}”, responseItem.Response.Results[“id”]);
}
}

The application above starts by connecting to Dynamics 365 online by providing a simple connection string into the CRMServiceClient class. This class comes as part of the Microsoft.Xrm.Tooling namespace.

Once the connection has been established and CRM Service is created, we create a data request collection with several account creation requests and one contact request. Then we pass the data request collection to the ExecuteMultipleRequest class and we setup the execution properties such as ContinueOnError and ReturnResponses.

Once the execution is complete, the response collection is returned and, in the response, we can find out the result of the request for each data request.

To Handle any error in the response item, you can use the code below:

(responseItem.Fault != null)
                Console.WriteLine(“Error {0}”, response.Requests[responseItem.RequestIndex] +  
                responseItem.RequestIndex + “message” +  responseItem.Fault);

The SDK uses the SQL transaction capabilities to start batch and complete batch execution. The maximum batch request is 1000 with a single transaction batch request. If you try to exceed the allowed limit, a fault is thrown before the first request is executed.

If you have any question or queries, do not hesitate to reach out to us