예제 #1
0
        /// <summary>
        /// Deletes all records returned by this Query. Executed in a single Bulk Delete request
        /// </summary>
        /// <param name="query">QueryBase implementation (QueryExpression, QueryByAttribute, FetchQuery</param>
        /// <param name="organizationService">IOrganization implementation</param>
        /// <param name="maxRecordsToDelete">Set max number of records to allow deletion to prevent accidental deletion of too man records. Defaults to 50</param>
        /// <param name="expectedResultsToDelete">Set the expected number of records to delete. If this exact number is not returned, no records are deleted</param>
        /// <exception cref="QueryBaseException">Throws if the number of records returned byt eh query exceeds the maxRecordsToDelete parameter (default is 50)</exception>
        /// <exception cref="OperationPreventedException">Throws if the number of records returned is not exactly the same as the expectedResultsToDelete parameter (if not null)</exception>
        /// <returns>True if all records were deleted with no errors being thrown</returns>
        public static bool DeleteAllResults(this QueryBase query, IOrganizationService organizationService,
                                            int maxRecordsToDelete = 50, int?expectedResultsToDelete = null)
        {
            var results          = query.RetrieveMultiple(organizationService);
            var entitiesReturned = results.Entities.Count;

            if (entitiesReturned > maxRecordsToDelete)
            {
                throw new QueryBaseException($"DeleteAllResults query returned too many results to proceed. " +
                                             $"Threshold was set to {maxRecordsToDelete}");
            }

            if (expectedResultsToDelete != null && expectedResultsToDelete != entitiesReturned)
            {
                throw new OperationPreventedException($"Could not safely delete results of query. " +
                                                      $"Expected {expectedResultsToDelete} but actual was {entitiesReturned}");
            }

            var request = new ExecuteMultipleRequest()
            {
                Settings = new ExecuteMultipleSettings()
                {
                    ContinueOnError = false,
                    ReturnResponses = true
                },
                Requests = new OrganizationRequestCollection()
            };

            foreach (var result in results.Entities)
            {
                var deleteRequest = new DeleteRequest()
                {
                    Target = result.ToEntityReference()
                };
                request.Requests.Add(deleteRequest);
            }

            var response = (ExecuteMultipleResponse)organizationService.Execute(request);

            return(!response.IsFaulted);
        }