Search This Blog

Friday, April 7, 2023

MICROSOFT DYNAMICS 365: SERVER SIDE BULK RECORDS OPERATIONS

 In Microsoft Dynamics 365 Customer Engagement server side automation, e.g. plugins and custom workflow activities, we can write code to create, retrieve, update and delete individual records. When we need to carry out these operations on multiple records, we can use a loop and query the database for each record. However, a much more efficient way to carry out bulk operations is to use the ExecuteMultipleRequest message (to Create, Update and Delete records in bulk), the focus on this article. Also, the application example demonstrates how to make use of these bulk operations methods as well as makes use of the RetrieveMultiple Query Expression (i.e. how to retrieve multiple records in single query) .

The bulk operations suite of methods below can be incorporated into a Dynamics 365 project and be called upon to carry out bulk operations. These methods provide an efficient way of carrying out operations on multiple records, thereby enhancing web pages response rates and user experience.

Bulk Create Records

public static void BulkCreateRecords(IOrganizationService service, EntityCollection entityCollection)
{            
	var multipleRequest = new ExecuteMultipleRequest()
	{                 
		Settings = new ExecuteMultipleSettings()
		{
			ContinueOnError = false,
			ReturnResponses = true
		},                
		Requests = new OrganizationRequestCollection()
	};

	foreach (Entity entity in entityCollection.Entities)
	{
		CreateRequest createRequest = new CreateRequest { Target = entity };
		multipleRequest.Requests.Add(createRequest);
	}

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

Bulk Update Records

public static void BulkUpdateRecords(IOrganizationService service, EntityCollection entityCollection)
{           
	var multipleRequest = new ExecuteMultipleRequest()
	{               
		Settings = new ExecuteMultipleSettings()
		{
			ContinueOnError = false,
			ReturnResponses = true
		},               
		Requests = new OrganizationRequestCollection()
	};
   
	foreach (Entity entity in entityCollection.Entities)
	{
		UpdateRequest updateRequest = new UpdateRequest { Target = entity };
		multipleRequest.Requests.Add(updateRequest);
	}

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

Bulk Delete Records

public static void BulkDeleteRecords(IOrganizationService service, EntityCollection entityCollection)
{            
	var multipleRequest = new ExecuteMultipleRequest()
	{ 
		Settings = new ExecuteMultipleSettings()
		{
			ContinueOnError = false,
			ReturnResponses = true
		},                
		Requests = new OrganizationRequestCollection()
	};
   
	foreach (Entity entity in entityCollection.Entities)
	{
		EntityReference entityRef = new EntityReference(entity.LogicalName, entity.Id);

		DeleteRequest deleteRequest = new DeleteRequest { Target = entityRef };
		multipleRequest.Requests.Add(deleteRequest);
	}

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

Example: Calling bulk operations methods and a demonstration of RetrieveMultiple

In the example below, we show how the methods provided above can be put to use to carry out bulk operations, by calling the bulk delete records method, as well as we make use of the RetrieveMultiple Query expression to retrieve multiple records in single database query (see the code below the comment “RetrieveMultiple Query Expression”).

About the plugin

The plugin example below is registered on the Update message Synchronously on the Account entity and PreOperation event pipeline stage of execution. The plugin is triggered by a custom Two Option field called Delete Tasks (logical name: “hos_deletetasks”) field. Therefore, when the user changes the value of the “hos_deletetasks” field from No/false to Yes/true, the plugin retrieves all the tasks that relate to that account and deletes them.

Other things to note

I have added the BulkCreateteRecords, BulkUpdateRecords and BulkDeleteRecords methods to my D365Helpers class, which contains my other reusable methods, so that they can used across multiple server-side automation classes.

using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;

namespace ItsFascinating.Plugins.D365
{
    public class DeleteFollowUpTasks : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {                  
            if (serviceProvider == null)
            {
                throw new ArgumentNullException("localContext");
            }
            #region Plugin Setup Variables
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            #endregion
            #region Validation Prior Execution
            string pluginMessageUpdate = "update";           

            if (context.Stage != 20)
            {
                tracingService.Trace("Invalid Stage: Stage = {0}", context.Stage);
                return;
            }
            
            if (!context.MessageName.ToLower().Equals(pluginMessageUpdate))
            {
                tracingService.Trace("Invalid Message: MessageName = {0}", context.MessageName);
                return;
            }
            #endregion
           
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity primaryEntity = context.InputParameters["Target"] as Entity;
                string accountLogicalName = "account";

                if (primaryEntity.LogicalName != accountLogicalName)
                {
                    tracingService.Trace("Invalid Entity: EntityName = {0}", primaryEntity.LogicalName);
                    return;
                }                    

                try
                {
                    if (primaryEntity.LogicalName.Equals(accountLogicalName))
                        DeleteTasks(service, primaryEntity, tracingService);                   
                }                
                catch (FaultException ex)
                {
                    throw new InvalidPluginExecutionException(string.Format("An error occurred in the DeleteFollowUpTasks plug-in. {0}", ex.Message));
                }
                catch (Exception ex)
                {
                    tracingService.Trace(string.Format("DeleteFollowUpTasks plugin: {0}", ex.ToString()));
                    throw new Exception(string.Format("An error occurred in the DeleteFollowUpTasks plug-in. {0}", ex.Message));
                }
            }
        }

        private static void DeleteTasks(IOrganizationService service, Entity primaryEntity, ITracingService tracingService)
        {
            object deleteTasksFieldObj = new object(); ;
            string deleteTasksLogicalName = "hos_deletetasks";
            bool deleteTasks;
            string taskLogicalName = "task";
            string subject = "subject";
            string description = "description";
            string accountRegardingFieldLogicalName = "regardingobjectid";
            bool containsDeleteTasks = primaryEntity.Attributes.TryGetValue(deleteTasksLogicalName, out deleteTasksFieldObj);

            if (containsDeleteTasks)
            {
                deleteTasks = (bool)deleteTasksFieldObj;

                if (deleteTasks)
                {
                    //RetrieveMultiple Query Expression
                    var tasksQuery = new QueryExpression(taskLogicalName);
                    tasksQuery.ColumnSet = new ColumnSet(subject, description);
                    tasksQuery.Criteria.AddCondition(accountRegardingFieldLogicalName, ConditionOperator.Equal, primaryEntity.Id);
                    var tasksResults = service.RetrieveMultiple(tasksQuery);

                    if (tasksResults.Entities.Count > 0)
                        D365Helpers.BulkDeleteRecords(service, tasksResults);
                }
            }
        }
    }
}