Wednesday, August 5, 2009

MS CRM : Creating bulk deletion job

Microsoft Dynamics CRM 4.0 allow users to bulk delete records using its interface, but is limited to a maximum of 250 records at a time. This is not a feasible solution if you have thousands of records to be deleted as a part of the campaign process.

CRM 4.0 supports bulk delete operation, but this functionality is not available out of box. You have to create an application which could perform this job using Dot Net.

The below code explains how you could perform a bulk delete operation on the leads entity.

You have to specify the Entity where the record need to be deleted and the Array of Lead Id's which needs to be deleted.

static void CreateBulkDeleteProcess()

// Create a query expression that retrieves all records for the entity.
QueryExpression qry = new QueryExpression();
qry.EntityName = EntityName.lead.ToString();
qry.ColumnSet = new AllColumns();

// Retrieve the accounts where the last name is not Cannon.
ConditionExpression condition = new ConditionExpression();
condition.AttributeName = "leadid";
condition.Operator = ConditionOperator.Equal;
condition.Values = new string[] { leadArray.ToString() };

// Build the filter based on the condition.
FilterExpression filter = new FilterExpression();
filter.FilterOperator = LogicalOperator.And;
qry.Criteria = filter;

// Create a request.
BulkDeleteRequest request = new BulkDeleteRequest();
request.JobName = "Delete (" + iLoop +") + " lead records";
request.QuerySet = new QueryBase[] { qry };
request.SendEmailNotification = false;
request.ToRecipients = new Guid[0];
request.CCRecipients = new Guid[0];
request.RecurrencePattern = string.Empty;
request.StartDateTime = new CrmDateTime();
TimeSpan ts = new TimeSpan(0, 5, 0);
request.StartDateTime.Value = DateTime.Now.Add(ts).ToString("s");

// Execute the request.
BulkDeleteResponse response = (BulkDeleteResponse)oService.Execute(request);
Guid jobId = response.JobId;
Console.WriteLine("Job Id: " + jobId.ToString());
catch (Exception ex)
string sMsg = "Error creating deletion job for " + sEntityName + ": " + ex.Message;
throw new Exception(sMsg, ex);

We can schedule the start time for the bulk delete operation and leave it run during the off peak hours. Also an email notification to the user who needs to be intimated regarding this task could be allocated. If this process needs to be recurrent, a recurrent pattern could be defined.

This is really a cool way of deleting the records rather than going through the hurdles which CRM gives for bulk delete process.

No comments: