This documentation is archived and is not being maintained.

Back Up Records and Bulk Delete

Dynamics
banner art

[Applies to: Microsoft Dynamics CRM 4.0]

Find the latest SDK documentation: CRM 2015 SDK

The following code example shows how to bulk delete records that have been manually exported. Scenario: a user wants to make a backup of all closed opportunities and all activities by exporting these records and then deleting them to free space. The exporting of the records is a manual process in Microsoft Dynamics CRM 4.0. The following procedure contains the manual steps required to export the records and the sample code shows how to do a bulk delete operation on the exported records.

This sample code can be found in the following files in the SDK download:

Server\HowTo\CS\BulkDelete\BulkDeleteBackup.cs

For more information about the helper methods in the Microsoft.Crm.Sdk.Utility.CrmServiceUtility namespace, see Utility Sample Code.

To Export Opportunity records to Excel

Before you run the bulk delete operation, you must manually backup/export the desired records to disk.

  1. In Microsoft Dynamics CRM 4.0, select Sales from the navigation pane, and then select Opportunities. This displays a grid of all opportunities that match the selected View.
  2. In the View drop-down list, select Closed Opportunities.
  3. On the Action toolbar, click Export to an Excel Worksheet. The Export Data to Excel dialog box is displayed.
  4. In the Export Data to Excel dialog box, select the Make this data available for re-import by including required columns check box. Leave Use this type of worksheet set to Static worksheet with records from this page.
  5. Click Export. The File Download dialog box will appear.
  6. On the File Download dialog box, click the Save button and then select a location to save the file.

To Export Activity records to Excel

  1. In Microsoft Dynamics CRM 4.0, select Workflow from the navigation pane, and then select Activities. This displays a grid of all activities that match the selected View.
  2. In the View drop-down list, select Closed Activities.
  3. On the Action toolbar, click Export to an Excel Worksheet. The Export Data to Excel dialog box will appear.
  4. In the Export Data to Excel dialog box, select the Make this data available for re-import by including required columns check box. Leave Use this type of worksheet set to Static worksheet with records from this page.
  5. Click Export. The File Download dialog box will appear.
  6. On the File Download dialog box, click the Save button and then select a location to save the file.
  7. Build and run the sample. The sample code will create a bulk delete operation to remove the exported records.

Example

[C#]
using System;
using System.Xml;
using CrmSdk;
using Microsoft.Crm.Sdk.Utility;

namespace Microsoft.Crm.Sdk.HowTo.BulkDelete
{
   /// <summary>
   /// This sample shows how to perform a bulk delete asynchronous 
   ///   operation for records that have been manually exported.
   /// </summary>
   public class BulkDeleteBackup
   {
      public BulkDeleteBackup()
      {

      }

      public static bool Run(string crmServerUrl, string orgName)
      {
         bool success = true;

         try
         {
            // Set up the CRM Service. 
            CrmService service = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.GetCrmService(crmServerUrl, orgName);
            service.PreAuthenticate = true;

            // Query for a system user to send an e-mail to after the bulk delete operation is completed.
            WhoAmIRequest userRequest = new WhoAmIRequest();
            WhoAmIResponse userResponse = (WhoAmIResponse)service.Execute(userRequest);
            Guid currentUserId = userResponse.UserId;
            
            // Create a condition for a bulk delete request.
            // NOTE: This sample uses two very specific queries so that the exact records exported 
            // in a previous step are now deleted in order to free space.
            QueryExpression opportunitiesQuery = BuildOpportunityQuery();
            QueryExpression activitiesQuery = BuildActivityQuery();
            
            // Create the bulk delete request
            BulkDeleteRequest bulkDeleteRequest = new BulkDeleteRequest();

            // Set the request properties
            bulkDeleteRequest.JobName = "Backup Bulk Delete";
            bulkDeleteRequest.QuerySet = new QueryBase[] { opportunitiesQuery, activitiesQuery };

            // Set the start time for the bulk delete
            bulkDeleteRequest.StartDateTime = new CrmDateTime();
            bulkDeleteRequest.StartDateTime.Value = DateTime.Now.ToString();
            
            // Set the required recurrence pattern
            bulkDeleteRequest.RecurrencePattern = string.Empty;

            // Set e-mail activity properties.
            bulkDeleteRequest.SendEmailNotification = true;
            bulkDeleteRequest.ToRecipients = new Guid[] { currentUserId };
            bulkDeleteRequest.CCRecipients = new Guid[] { };

            // Submit the bulk delete job.
            // NOTE: Because this is an asynchronous operation, the response will be immediate.
            BulkDeleteResponse bulkDeleteResponse = (BulkDeleteResponse)service.Execute(bulkDeleteRequest);

            #region check success
            
            // Query for bulk delete operation and check for status
            QueryByAttribute bulkQuery = new QueryByAttribute();
            // Be aware that using AllColumns may adversely affect
            // performance and cause unwanted cascading in subsequent 
            // updates. A best practice is to retrieve the least amount of 
            // data required.
            bulkQuery.ColumnSet = new AllColumns();
            bulkQuery.EntityName = EntityName.bulkdeleteoperation.ToString();

            // NOTE: When the bulk delete operation was submitted, the GUID that was returned 
            // was the asyncoperationid, not the bulkdeleteoperationid.
            bulkQuery.Attributes = new string[] { "asyncoperationid" };
            bulkQuery.Values = new object[1];
            bulkQuery.Values[0] = bulkDeleteResponse.JobId;

            // With only the asyncoperationid at this point, a RetrieveMultiple is required to get the
            // bulk delete operation that was created.
            BusinessEntityCollection entityCollection = service.RetrieveMultiple(bulkQuery);
            bulkdeleteoperation createdBulkDeleteOperation = null;

            // Monitor the async operation through polling until it is complete or max polling time expires.
            const int ARBITRARY_MAX_POLLING_TIME = 60;
            int secondsTicker = ARBITRARY_MAX_POLLING_TIME;
            while (secondsTicker > 0)
            {
               // Make sure that the async operation was retrieved.
               if (entityCollection.BusinessEntities.Length > 0)
               {
                  // Grab the one bulk operation that was created.
                  createdBulkDeleteOperation = (bulkdeleteoperation)entityCollection.BusinessEntities[0];

                  // Check the operation's state
                  if (createdBulkDeleteOperation.statecode.Value != BulkDeleteOperationState.Completed)
                  {
                     // The operation has not yet completed. Wait a second for the status to change.
                     System.Threading.Thread.Sleep(1000);
                     secondsTicker--;

                     // Retrieve a fresh version the bulk delete operation
                     entityCollection = service.RetrieveMultiple(bulkQuery);
                  }
                  else
                  {
                     // Stop polling because the operation's state is now completed.
                     secondsTicker = 0;
                  }
               }
               else
               {
                  // Wait a second for async operation to become active.
                  System.Threading.Thread.Sleep(1000);
                  secondsTicker--;

                  // Retrieve the entity again
                  entityCollection = service.RetrieveMultiple(bulkQuery);
               }
            }

            // Validate that the operation was completed.
            if (createdBulkDeleteOperation.statecode.Value != BulkDeleteOperationState.Completed)
            {
               // This happens if it took longer than the polling time allowed 
               // for this operation to finish.
               success = false;
            }
            else
            {
               if (createdBulkDeleteOperation.statuscode.name != "Succeeded")
               {
                  success = false;
               }
            }

            #endregion

            #region Remove Data Required for this Sample

            // NOTE: The bulkdeleteoperation entity cannot be removed from the database

            #endregion
         }
         catch (System.Web.Services.Protocols.SoapException)
         {
            // Perform error handling here.
            throw;
         }
         catch (Exception)
         {
            throw;
         }

         return success;
      }
      /// <summary>
      /// 
      /// </summary>
      /// <param name="entityType"></param>
      /// <returns></returns>
      public static QueryExpression BuildOpportunityQuery()
      {
         ConditionExpression closedCondition = new ConditionExpression();
         closedCondition.AttributeName = "statecode";
         closedCondition.Operator = ConditionOperator.NotEqual;
         closedCondition.Values = new object[1];
         closedCondition.Values[0] = 0; // open

         // Create a fiter expression for a buld delete request
         FilterExpression closedFilter = new FilterExpression();
         closedFilter.Conditions = new ConditionExpression[] { closedCondition };

         // Create the bulk delete query set. One for the opportunities, one for the activities
         QueryExpression qryExpression = new QueryExpression();
         
         // Set query properties
         qryExpression.EntityName = EntityName.opportunity.ToString();
         qryExpression.Criteria = closedFilter;

         // Return all records
         qryExpression.Distinct = false;
   
         return qryExpression;      
      }
      
      public static QueryExpression BuildActivityQuery()
      {
         ConditionExpression canceledCondition = new ConditionExpression();
         canceledCondition.AttributeName = "statecode";
         canceledCondition.Operator = ConditionOperator.Equal;
         canceledCondition.Values = new object[1];
         canceledCondition.Values[0] = 2;  // canceled

         ConditionExpression completedCondition = new ConditionExpression();
         completedCondition.AttributeName = "statecode";
         completedCondition.Operator = ConditionOperator.Equal;
         completedCondition.Values = new object[1];
         completedCondition.Values[0] = 1;  // completed
         
         // Create a fiter expression for a buld delete request
         FilterExpression closedFilter = new FilterExpression();
         closedFilter.Conditions = new ConditionExpression[] { canceledCondition, completedCondition };

         // Create the bulk delete query set. One for the opportunities, one for the activities
         QueryExpression qryExpression = new QueryExpression();
         
         // Set query properties
         qryExpression.EntityName = EntityName.activitypointer.ToString();
         qryExpression.Criteria = closedFilter;

         // Return all records
         qryExpression.Distinct = false;
   
         return qryExpression;      
      }
   }
}

See Also

Concepts

Reference


© 2010 Microsoft Corporation. All rights reserved.


Show: