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..

 

Advertisements

Author: Nishant Rana

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

6 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 )

Google+ photo

You are commenting using your Google+ 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.