Using ExecuteMultiple C# in Dynamics 365

4 Comments

ExecuteMultiple in Dynamics 365 is used to execute multiple requests, as opposed to executing requests one at a time. For example, if you wanted to create 5 contacts in Dynamics 365 through code, you could call Create 5 times, or you could call ExecuteMultiple once, with the 5 entity objects defined. This is useful if network latency is an issue.

Let’s create a console app that creates 5 contacts using Create vs 5 creating 5 contacts using ExecuteMultiple.

Create a new Console App:

Click Create:

Add Microsoft.CrmSdk.Xrm.Tooling.CoreAssembly using NuGet.

Now the code. Let’s see how it would look if we used 5 separate Creates:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Xrm.Tooling.Connector;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using System.ServiceModel;

namespace Carl.Dynamics365ExecuteMultiple
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var connectionString = @"AuthType = Office365; Url = https://yourorg.crm.dynamics.com/;Username=your@email;Password=yourpassword";
                CrmServiceClient conn = new CrmServiceClient(connectionString);

                IOrganizationService service;
                service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

                for (int i = 0; i < 5; i++)
                {
                    Entity contact = new Entity("contact");
                    contact["firstname"] = "Bob " + i.ToString();
                    contact["lastname"] = "Smith";
                    Guid contactId = service.Create(contact);
                    Console.WriteLine("New contact id: {0}.", contactId.ToString());
                }
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
    }
}

Running the code, 5 new contacts are created. For each line there is a slight delay as we are sending a new request each time:

Now let’s use ExecuteMultiple. In this code, we bundle up the create requests into one ExecuteMultiple request:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Xrm.Tooling.Connector;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using System.ServiceModel;

namespace Carl.Dynamics365ExecuteMultiple
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var connectionString = @"AuthType = Office365; Url = https://yourorg.crm.dynamics.com/;Username=your@email;Password=yourpassword";
                CrmServiceClient conn = new CrmServiceClient(connectionString);

                IOrganizationService service;
                service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

                var request = new ExecuteMultipleRequest()
                {
                    Requests = new OrganizationRequestCollection(),
                    Settings = new ExecuteMultipleSettings
                    {
                        ContinueOnError = false,
                        ReturnResponses = true
                    }
                };

                for (int i = 0; i < 5; i++)
                {
                    Entity contact = new Entity("contact");
                    contact["firstname"] = "Bob " + i.ToString();
                    contact["lastname"] = "Smith";

                    var createRequest = new CreateRequest()
                    {
                        Target = contact
                    };
                    request.Requests.Add(createRequest);
                }

                Console.WriteLine("Before execute");
                var response = (ExecuteMultipleResponse)service.Execute(request);
                Console.WriteLine("After execute");

                foreach (var r in response.Responses)
                {
                    if (r.Response != null)
                        Console.WriteLine("Success");
                    else if (r.Fault != null)
                        Console.WriteLine(r.Fault);
                }

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
    }
}

When we run this, there is a slight delay between “before execute” and “after execute”, then the contacts are displayed quickly, as they were created in the single request:

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

4 Responses to Using ExecuteMultiple C# in Dynamics 365

  1. Hi Carl,

    Could this be used in conjunction with a retrieve multiple?

    I’m trying to switch to a new Business Process Flow which can only be done in code since SetProcess has been depreciated.

    I want to RetrieveMultiple to get the GUID of each opportunity then create a record in the BPF entity for each retrieved record.

    Many thanks
    Jason

  2. I read so many blog for ExecuteMultipleRequest but they are very complex but in your blog you have explained in very simple way so anyone can understand very easily.
    Thanks

  3. Extremely useful and to the point! I have referred many articles on Microsoft Docs but none was of use. Thanks for sharing the code. Would like to further know about how to retrieve, Compare and Upsert into the Entities. I currently need to read some data from the CSV files and need to perform all the above mentioned operations on the different entities on my portal to have the data on sync with the CSV file database.Your valuable inputs will be appreciated TIA 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *