Sample Code to bulk update the record using ExecuteMultiple in Dynamics 365


Sharing a sample code that can be used ExecuteMultiple to bulk update the records.


private void MyForm_Load(object sender, EventArgs e)
{

var orgProxy = GetOrgProxy();

// place your fetch xml code to retrieve the records to be updated
var fetchXML = @"FetchXMLQuery";

var multipleRequest = new ExecuteMultipleRequest()
{
// Assign settings that define execution behavior: continue on error, return responses.
Settings = new ExecuteMultipleSettings()
{
ContinueOnError = true,
ReturnResponses = true
},
// Create an empty organization request collection.
Requests = new OrganizationRequestCollection()
};

// get all the records > 5000
var totalRecords = GetTotalRecordsFetchXML(orgProxy, fetchXML);

// split the lst of entity to child list
// specify the size of the batch i.e. 500 here
var lstlstEntity = SplitList(totalRecords, 500);

// loop through each of the list and create the request and add it to Execute Multiple Request
foreach(var lstEntity in lstlstEntity)
{
multipleRequest.Requests.Clear();
foreach (var entity in lstEntity)
{
UpdateRequest createRequest = new UpdateRequest { Target = entity };
// add the field to be updated
entity.Attributes["sab_referencenumber"] = "1000";
multipleRequest.Requests.Add(createRequest);
}

ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)orgProxy.Execute(multipleRequest);
}
}

/// <summary>
/// Function to split the list into child list
/// </summary>
/// <param name="locations"></param>
/// <param name="nSize"></param>
/// <returns></returns>
public static List<List<Entity>> SplitList(List<Entity> locations, int nSize = 30)
{
var list = new List<List<Entity>>();
for (int i = 0; i < locations.Count; i += nSize)
{
list.Add(locations.GetRange(i, Math.Min(nSize, locations.Count - i)));
}
return list;
}

 

private static List<Entity> GetTotalRecordsFetchXML(OrganizationServiceProxy orgProxy, string fetchXML)
{
XDocument xDocument = XDocument.Parse(fetchXML);
var fetchXmlEntity = xDocument.Root.Element("entity").ToString();

EntityCollection entityColl = new EntityCollection();
List<Entity> lstEntity = new List<Entity>();
int page = 1;
do
{
entityColl = orgProxy.RetrieveMultiple(new FetchExpression(
string.Format("<fetch version='1.0' page='{1}' paging-cookie='{0}'>" + fetchXmlEntity + "</fetch>",
SecurityElement.Escape(entityColl.PagingCookie), page++)));

lstEntity.AddRange(entityColl.Entities);
}
while (entityColl.MoreRecords);

return lstEntity;
}

 

// Get service instance
public static OrganizationServiceProxy GetOrgProxy()
{
IServiceManagement<IOrganizationService> orgServiceManagement =
ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri("https://orgname.crm4.dynamics.com/XRMServices/2011/Organization.svc"));

AuthenticationCredentials authCredentials = new AuthenticationCredentials();
authCredentials.ClientCredentials.UserName.UserName = "username";
authCredentials.ClientCredentials.UserName.Password = "password";
AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials);

return new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.SecurityTokenResponse);

}

Hope it helps..

 

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

7 thoughts on “Sample Code to bulk update the record using ExecuteMultiple in Dynamics 365”

  1. Hi Nishant,
    I have been trying ExecuteMultiple for a while. Its been working for updating, deleting records but its now working for Create operation. Any idea what should be the issue..? I am using Online Dynamics 365 V9 and getting SQL server Time Out Error each time.

    Thanks for your time.

    Like

Please share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

CRM for You and Me

Customer Relationship Mgt App for the Professional

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog

Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform

Knowhere365

Specific topics by Django Lohn on the whole Microsoft365 Stack

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions

MG

Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue MVP

A Microsoft Business Applications MVP

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

Two Bite Tips

Valuable Tips To Grow Your Business

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM

CRM TIPS BY PRM

Mail to crmtipsbyprm@gmail.com for queries and suggestions

nijos.dev

Giving back to the community what I have learned

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.

CRM Keeper

Dynamics 365 Customer Engagement, CRM, Microsoft CRM, Dynamics CRM

EVOLVED365

Step into the world of a Dynamics 365 Consultant

Dianamics PCF Lady

Diana & Dynamics 365 & Power Platform

Sara Lagerquist

No Code Customization Concepts

innovativeaj

developer, designer, writer, fun loving, patriotic, humble and a sweet person inside out :) love and respect people who have a great sense of humor.

Temmy Wahyu Raharjo

Dreaming to be a clean coder and TDD minded programmer.

Transform 365

We blog about problems we face and code we write to help others

%d bloggers like this: