Exemple #1
0
        /// <summary>
        ///     Deletes items from a given app based in bulk and removes them from all views. The data can no longer be retrieved.
        ///     <para>Podio API Reference: https://developers.podio.com/doc/items/bulk-delete-items-19406111 </para>
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="deleteRequest"></param>
        /// <param name="silent">
        ///     If set to true, the object will not be bumped up in the stream and notifications will not be
        ///     generated
        /// </param>
        /// <returns>Collection of matching items</returns>
        public async Task <BulkDeletionStatus> BulkDeleteItems(int appId, BulkDeleteRequest deleteRequest, bool silent = false)
        {
            string url = string.Format("/item/app/{0}/delete", appId);

            url = Utility.PrepareUrlWithOptions(url, new CreateUpdateOptions(silent));
            return(await _podio.Post <BulkDeletionStatus>(url, deleteRequest));
        }
        public async Task <string> MutipleDeleteAsync(BulkDeleteRequest bulkRequest)
        {
            var context = JsonConvert.SerializeObject(bulkRequest);

            httpClient = _baseAuthorization.GetHttpCliente();

            var ids = "";

            foreach (var id in bulkRequest.RecordId)
            {
                ids += string.Concat(id, bulkRequest.RecordId.LastOrDefault() != id ? "," : "");
            }

            var url = $"{ApiUrl}services/data/v{ApiCofiguration.Version}/composite/sobjects?ids={ids}&allOrNone={bulkRequest.AllOrNone}";

            var request = new HttpRequestMessage(new HttpMethod("DELETE"), url)
            {
                Content = new StringContent(context, Encoding.UTF8, "application/json")
            };
            var result = await _baseAuthorization.GetHttpCliente().SendAsync(request);

            var resultContent = await result.Content.ReadAsStringAsync();

            if (!result.IsSuccessStatusCode)
            {
                throw new Exception($"Error=>> {resultContent} Token Expired In: {ComvertToDateTimeUnixTimestamp(_baseAuthorization.Timeout)}");
            }
            result.EnsureSuccessStatusCode();
            return(resultContent);
        }
 public bool CreateBulkCaseDeletionJob(IOrganizationService service, out string errorMsg)
 {
     try
     {
         ConditionExpression conditionExp = new ConditionExpression(IncidentEntity.ProtectedCase, ConditionOperator.NotEqual, true);
         FilterExpression    filterExp    = new FilterExpression();
         filterExp.AddCondition(conditionExp);
         BulkDeleteRequest request = new BulkDeleteRequest
         {
             JobName           = "Delete Unprotected Records - Bulk Case Deletion",
             ToRecipients      = new Guid[] { },
             CCRecipients      = new Guid[] { },
             RunNow            = true,
             RecurrencePattern = string.Empty,
             QuerySet          = new QueryExpression[]
             {
                 new QueryExpression {
                     EntityName = IncidentEntity.LogicalName, Criteria = filterExp
                 }
             }
         };
         BulkDeleteResponse response = (BulkDeleteResponse)service.Execute(request);
         Trace.WriteLine($"Bulk Deletion Job response: {response.ToString()}");
         errorMsg = null;
         return(true);
     }
     catch (FaultException <OrganizationServiceFault> e)
     {
         errorMsg = e.Message;
         Trace.WriteLine(e.Message);
         return(false);
     }
 }
        public void DeleteAllEntityRecords()
        {
            if (Logging)
            {
                Console.WriteLine("DELETING ALL ENTITY RECORDS");
            }

            BulkDeleteRequest request = new BulkDeleteRequest
            {
                JobName           = "Delete All",
                ToRecipients      = new Guid[] { },
                CCRecipients      = new Guid[] { },
                RecurrencePattern = string.Empty,
                QuerySet          = new[]
                {
                    new QueryExpression {
                        EntityName = EntityName
                    }
                }
            };

            CrmService.Execute(request);

            if (Logging)
            {
                Console.WriteLine("DELETE REQUEST SENT TO THE SERVER");
            }
        }
Exemple #5
0
        /// <summary>
        /// Creates the bulk delete.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="jobName">Name of the job.</param>
        private void CreateBulkDelete(QueryExpression query, string jobName)
        {
            if (Service == null)
            {
                ExecuteMethod(WhoAmI);
                return;
            }

            if (query == null)
            {
                return;
            }

            // Create the bulk delete request.
            var bulkDeleteRequest = new BulkDeleteRequest
            {
                JobName = jobName,

                QuerySet              = new[] { query },
                StartDateTime         = DateTime.Now.AddMinutes(2),
                SendEmailNotification = false,
                ToRecipients          = new Guid[] { },
                CCRecipients          = new Guid[] { },
                RecurrencePattern     = String.Empty
            };

            var bulkDeleteResponse =
                (BulkDeleteResponse)Service.Execute(bulkDeleteRequest);
        }
Exemple #6
0
 private void BatchCreateBulkDeleteJobs(List <BulkDeleteRequest> items, Action completedCallback)
 {
     DelegateItterator.CallbackItterate(delegate(int index, Action nextCallback, ErrorCallBack errorCallBack)
     {
         BulkDeleteRequest pendingDeleteItem = items[index];
         OrganizationServiceProxy.BeginExecute(pendingDeleteItem, delegate(object result)
         {
             try
             {
                 OrganizationServiceProxy.EndExecute(result);
                 IsBusyProgress.SetValue((index / items.Count) * 100);
                 nextCallback();
             }
             catch (Exception ex)
             {
                 errorCallBack(ex);
             }
         });
     },
                                        items.Count,
                                        completedCallback,
                                        delegate(Exception ex)
     {
         // Error
         ReportError(ex);
     });
 }
        public bool CreateSystemJobDeletionJob(IOrganizationService service, out string errorMsg)
        {
            try
            {
                ConditionExpression conEx = new ConditionExpression("statecode", ConditionOperator.Equal, 3);
                FilterExpression    fiEx  = new FilterExpression();
                fiEx.AddCondition(conEx);

                BulkDeleteRequest request = new BulkDeleteRequest
                {
                    JobName           = "Bulk Delete Completed System Jobs",
                    CCRecipients      = new Guid[] { },
                    ToRecipients      = new Guid[] { },
                    RecurrencePattern = string.Empty,
                    QuerySet          = new QueryExpression[]
                    {
                        new QueryExpression {
                            EntityName = "asyncoperation", Criteria = fiEx
                        }
                    }
                };
                BulkDeleteResponse response = (BulkDeleteResponse)service.Execute(request);
                errorMsg = string.Empty;
                return(true);
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                errorMsg = e.Message;
                Trace.WriteLine(e.Message);
                return(false);
            }
        }
        private void BtnBulkDelete_Click(object sender, EventArgs e)
        {
            var entities = txtInput.Text.Split('\n');

            //var queries = new List<QueryExpression>();

            foreach (var en in entities)
            {
                txtLog.AppendText($"Bulk deleting entity: {en}");
                //if(!string.IsNullOrEmpty(en))
                //    queries.Add(new QueryExpression(en));

                var bulkDeleteRequest = new BulkDeleteRequest();
                bulkDeleteRequest.JobName = $"Removing all data from {en}";
                var qe = new QueryExpression(en);
                qe.Criteria.AddCondition("CreatedBy", ConditionOperator.Equal, new Guid("7866A909-07A4-E911-A97E-001DD800C973"));

                bulkDeleteRequest.QuerySet = new QueryExpression[] {
                    new QueryExpression(en)
                }; // queries.ToArray<QueryExpression>();
                bulkDeleteRequest.StartDateTime         = DateTime.Now.ToUniversalTime();
                bulkDeleteRequest.RecurrencePattern     = String.Empty;
                bulkDeleteRequest.SendEmailNotification = false;
                bulkDeleteRequest.ToRecipients          = new Guid[] { };
                bulkDeleteRequest.CCRecipients          = new Guid[] { };
                var _bulkDeleteResponse = (BulkDeleteResponse)CrmConnManager.LService.Execute(bulkDeleteRequest);
                txtLog.AppendText($"{Environment.NewLine}The bulk delete operation has been requested.");
            }
        }
Exemple #9
0
        public void DeleteRecords(IOrganizationService service)
        {
            if (PartialDeleteList.Count() > 0)
            {
                var dateStamp     = DateTime.Now.ToString("MM-dd hh:mm");
                var deleteRequest = new BulkDeleteRequest();
                deleteRequest.JobName = $"[{dateStamp}] Delta Process - Delete {PartialDeleteList.Count()} {EntityName}";

                var qe = new QueryExpression(EntityName);
                //qe.Criteria.AddCondition("CreatedBy", ConditionOperator.Equal, new Guid("7866A909-07A4-E911-A97E-001DD800C973"));
                var guids = PartialDeleteList.ToArray();
                qe.Criteria.AddCondition(PrimaryAttributeName, ConditionOperator.In, guids);
                deleteRequest.QuerySet = new QueryExpression[] { qe };

                deleteRequest.StartDateTime         = DateTime.Now.ToUniversalTime();
                deleteRequest.RecurrencePattern     = String.Empty;
                deleteRequest.SendEmailNotification = false;
                deleteRequest.ToRecipients          = new Guid[] { };
                deleteRequest.CCRecipients          = new Guid[] { };

                if (guids.Length > 0)
                {
                    var _bulkDeleteResponse = (BulkDeleteResponse)service.Execute(deleteRequest);
                    Console.WriteLine($"Requested job: {deleteRequest.JobName}");
                }
            }
        }
Exemple #10
0
 public override Task <BulkDeleteResponse> BulkDelete(BulkDeleteRequest request,
                                                      ServerCallContext context)
 {
     foreach (GrpcSbValue value in request.Values)
     {
         valueStore.RemoveObject(value.Id);
     }
     return(Task.FromResult(new BulkDeleteResponse()));
 }
 public override Task <BulkDeleteResponse> BulkDelete(BulkDeleteRequest request,
                                                      ServerCallContext context)
 {
     foreach (GrpcSbType type in request.Types_)
     {
         typeStore.RemoveObject(type.Id);
     }
     return(Task.FromResult(new BulkDeleteResponse()));
 }
Exemple #12
0
        private void TriggerBulkDelete(bool selectedOnly)
        {
            var recordsToUpdate = GetRecordsToProcess(selectedOnly);

            var request          = new BulkDeleteRequest(new RecordType(QueryViewModel.RecordType, RecordService.GetDisplayName(QueryViewModel.RecordType)), recordsToUpdate);
            var bulkUpdateDialog = new BulkDeleteDialog(RecordService, (IDialogController)ApplicationController.ResolveType(typeof(IDialogController)), request, () => { ClearChildForms(); QueryViewModel.DynamicGridViewModel.ReloadGrid(); });

            LoadChildForm(bulkUpdateDialog);
        }
Exemple #13
0
        public questStatus PerformBulkDelete(BulkDeleteRequest bulkDeleteRequest)
        {
            // Initialize

            ////bulkInsertRequest.Filter.Filter


            return(new questStatus(Severity.Success));
        }
Exemple #14
0
        /*==================================================================================================================================
        * Properties
        *=================================================================================================================================*/
        #endregion


        #region Public Methods

        /*==================================================================================================================================
        * Public Methods
        *=================================================================================================================================*/
        public questStatus GenerateBulkDeleteSQL(BulkDeleteRequest bulkDeleteRequest)
        {
            // Initialize

            ////bulkInsertRequest.Filter.Filter


            return(new questStatus(Severity.Success));
        }
Exemple #15
0
 public override Task <BulkDeleteResponse> BulkDelete(BulkDeleteRequest request,
                                                      ServerCallContext context)
 {
     foreach (GrpcSbThread thread in request.Threads)
     {
         threadStore.RemoveObject(thread.Id);
     }
     return(Task.FromResult(new BulkDeleteResponse()));
 }
 private void TriggerBulkDelete(bool selectedOnly)
 {
     ApplicationController.DoOnAsyncThread(() =>
     {
         var recordsToUpdate           = GetRecordsToProcess(selectedOnly);
         var request                   = new BulkDeleteRequest(new RecordType(QueryViewModel.RecordType, RecordService.GetDisplayName(QueryViewModel.RecordType)), recordsToUpdate);
         request.AllowExecuteMultiples = RecordService.SupportsExecuteMultiple;
         var bulkUpdateDialog          = new BulkDeleteDialog(RecordService, (IDialogController)ApplicationController.ResolveType(typeof(IDialogController)), request, CompleteChildDialogAndReload);
         LoadChildForm(bulkUpdateDialog);
     });
 }
        public void When_execute_is_called_with_a_null_jobname_exception_is_thrown()
        {
            var context           = new XrmFakedContext();
            var executor          = new BulkDeleteRequestExecutor();
            BulkDeleteRequest req = new BulkDeleteRequest
            {
                JobName = null
            };

            Assert.Throws <FaultException <OrganizationServiceFault> >(() => executor.Execute(req, context));
        }
Exemple #18
0
        public string Execute(IDictionary <string, DataSource> dataSources, IQueryExecutionOptions options, IDictionary <string, Type> parameterTypes, IDictionary <string, object> parameterValues)
        {
            _executionCount++;

            try
            {
                if (!dataSources.TryGetValue(DataSource, out var dataSource))
                {
                    throw new QueryExecutionException("Missing datasource " + DataSource);
                }

                using (_timer.Run())
                {
                    var query = ((FetchXmlToQueryExpressionResponse)dataSource.Connection.Execute(new FetchXmlToQueryExpressionRequest {
                        FetchXml = FetchXmlString
                    })).Query;
                    var meta  = dataSource.Metadata[query.EntityName];

                    var req = new BulkDeleteRequest
                    {
                        JobName               = $"SQL 4 CDS {GetDisplayName(0, meta)} Bulk Delete Job",
                        QuerySet              = new[] { query },
                        StartDateTime         = DateTime.Now,
                        RecurrencePattern     = String.Empty,
                        SendEmailNotification = false,
                        ToRecipients          = Array.Empty <Guid>(),
                        CCRecipients          = Array.Empty <Guid>()
                    };

                    var resp = (BulkDeleteResponse)dataSource.Connection.Execute(req);

                    return($"Bulk delete job started: {resp.JobId}");
                }
            }
            catch (QueryExecutionException ex)
            {
                if (ex.Node == null)
                {
                    ex.Node = this;
                }

                throw;
            }
            catch (Exception ex)
            {
                throw new QueryExecutionException(ex.Message, ex)
                      {
                          Node = this
                      };
            }
        }
Exemple #19
0
        /// <summary>
        ///     Creates a <c>BulkDeleteRequest</c>.
        /// </summary>
        /// <param name="queries">The queries which returns the records to delete.</param>
        /// <returns>A <c>BulkDeleteRequest</c> object.</returns>
        private BulkDeleteRequest CreateBulkDeleteRequest(IEnumerable <QueryExpression> queries)
        {
            var bulkDeleteRequest = new BulkDeleteRequest
            {
                JobName               = String.IsNullOrEmpty(BulkDeleteOperationName) ? "Bulk Delete - " + DateTime.Now.ToString("g") : BulkDeleteOperationName,
                QuerySet              = queries.ToArray(),
                StartDateTime         = StartTime == DateTime.MinValue ? DateTime.Now : StartTime,                      // Default is start immediately
                RecurrencePattern     = RecurrencePattern ?? String.Empty,                                              // Default is none (empty)
                SendEmailNotification = SendEmailNotification,                                                          // Default is false
                ToRecipients          = ToRecipients == null ? new Guid[0] : ToRecipients.Select(Guid.Parse).ToArray(), // Default is none (empty)
                CCRecipients          = CcRecipients == null ? new Guid[0] : CcRecipients.Select(Guid.Parse).ToArray(), // Default is none (empty)
            };

            return(bulkDeleteRequest);
        }
        public void When_execute_is_called_with_a_null_ccrecipients_exception_is_thrown()
        {
            var context           = new XrmFakedContext();
            var executor          = new BulkDeleteRequestExecutor();
            BulkDeleteRequest req = new BulkDeleteRequest
            {
                JobName  = "Dummy Job",
                QuerySet = new[]
                {
                    new QueryExpression("account"),
                },
                CCRecipients = null
            };

            Assert.Throws <FaultException <OrganizationServiceFault> >(() => executor.Execute(req, context));
        }
        public virtual void Delete(GrpcConnection connection, GrpcSbFrame grpcSbFrame)
        {
            var client = new RemoteFrameRpcService.RemoteFrameRpcServiceClient(
                connection.CallInvoker);

            connection
            .GetOrCreateBulkDeleter <GrpcSbFrame>()
            .QueueForDeletion(grpcSbFrame, (List <GrpcSbFrame> frames) =>
            {
                var request = new BulkDeleteRequest();
                request.Frames.AddRange(frames);
                connection.InvokeRpc(() =>
                {
                    client.BulkDelete(request);
                });
            });
        }
Exemple #22
0
        /// <summary>
        /// Bulk Delete By Query
        /// </summary>
        /// <param name="query"></param>
        /// <param name="jobName"></param>
        /// <param name="sendEmail"></param>
        /// <returns></returns>
        public Guid BulkDelete(QueryExpression query, string jobName, bool sendEmail = true)
        {
            var wresp = _Service.Execute(new WhoAmIRequest()) as WhoAmIResponse;

            BulkDeleteRequest deleteRequest = new BulkDeleteRequest()
            {
                JobName               = jobName,
                QuerySet              = new[] { query },
                StartDateTime         = DateTime.Now,
                ToRecipients          = new[] { wresp.UserId },
                CCRecipients          = new Guid[] {},
                SendEmailNotification = sendEmail,
                RecurrencePattern     = string.Empty
            };
            var deleteResponse = _Service.Execute(deleteRequest) as BulkDeleteResponse;

            return(deleteResponse.JobId);
        }
Exemple #23
0
        private void CreateBulkDeleteJob(int months)
        {
            if (!BulkDeleteJobExists())
            {
                string frequency =
                    String.Format(System.Globalization.CultureInfo.InvariantCulture,
                                  "FREQ=DAILY;INTERVAL={0};", DailyInterval);


                QueryExpression query = new QueryExpression
                {
                    EntityName = "msdyn_analysisresult",
                    ColumnSet  = new ColumnSet("msdyn_name"),
                    Criteria   = new FilterExpression
                    {
                        Conditions =
                        {
                            new ConditionExpression
                            {
                                AttributeName = "createdon",
                                Operator      = ConditionOperator.OlderThanXMonths,
                                Values        = { months }
                            }
                        }
                    }
                };

                BulkDeleteRequest bulkDeleteRequest =
                    new BulkDeleteRequest
                {
                    JobName               = jobName,
                    QuerySet              = new QueryExpression[] { query },
                    StartDateTime         = DateTime.Now.Date,
                    RecurrencePattern     = frequency,
                    SendEmailNotification = false,
                    ToRecipients          = new Guid[] { },
                    CCRecipients          = new Guid[] { }
                };

                CrmSvc.Execute(bulkDeleteRequest);
            }
        }
 // Disposing indicates whether this method has been called by user's code or by the
 // the destructor. In the latter case, we should not reference managed objects as we cannot
 // know if they have already been reclaimed by the garbage collector.
 protected virtual void Dispose(bool disposing)
 {
     if (!disposed)
     {
         // We only have unmanaged resources to dispose of in this class.
         connection
         .GetOrCreateBulkDeleter <GrpcSbFrame>()
         .QueueForDeletion(grpcSbFrame, (List <GrpcSbFrame> frames) =>
         {
             var request = new BulkDeleteRequest();
             request.Frames.AddRange(frames);
             connection.InvokeRpc(() =>
             {
                 client.BulkDelete(request);
             });
         });
         gcHandle.Free();
         disposed = true;
     }
 }
        /*==================================================================================================================================
        * Public Methods
        *=================================================================================================================================*/
        public questStatus DoBulkDelete(BulkDeleteViewModel bulkDeleteViewModel)
        {
            // Initialize
            questStatus status = null;


            // TODO: PREP REQUEST
            BulkDeleteRequest bulkDeleteRequest = new BulkDeleteRequest();


            // Perform bulk delete.
            BulkDeleteMgr bulkDeleteMgr = new BulkDeleteMgr(this.UserSession);

            status = bulkDeleteMgr.PerformBulkDelete(bulkDeleteRequest);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }
            return(new questStatus(Severity.Warning, "Not implemented"));
        }
        /*==================================================================================================================================
        * Public Methods
        *=================================================================================================================================*/
        public questStatus PerformBulkDelete(BulkDeleteRequest bulkDeleteRequest)
        {
            // Initialize
            questStatus status = null;


            // Generate the SQL
            status = _dbBulkDeleteMgr.GenerateBulkDeleteSQL(bulkDeleteRequest);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }


            // Perform bulk delete.
            status = _dbBulkDeleteMgr.PerformBulkDelete(bulkDeleteRequest);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }
            return(new questStatus(Severity.Success));
        }
        public void BulkActivityDeletion(IOrganizationService _orgServ)
        {
            OrganizationServiceContext _orgContext = new OrganizationServiceContext(_orgServ);

            ConditionExpression conEx = new ConditionExpression("regardingobjectid", ConditionOperator.Null);
            FilterExpression    fiEx  = new FilterExpression();

            fiEx.AddCondition(conEx);
            BulkDeleteRequest request = new BulkDeleteRequest
            {
                JobName           = "Delete unlinked activites",
                ToRecipients      = new Guid[] { },
                CCRecipients      = new Guid[] { },
                RecurrencePattern = string.Empty,
                QuerySet          = new QueryExpression[]
                {
                    new QueryExpression {
                        EntityName = "activitypointer", Criteria = fiEx
                    }
                }
            };
            BulkDeleteResponse response = (BulkDeleteResponse)_orgServ.Execute(request);
        }
        public void BulkCaseDeletion(IOrganizationService _orgServ)
        {
            OrganizationServiceContext _orgContext = new OrganizationServiceContext(_orgServ);

            ConditionExpression conEx = new ConditionExpression("shg_casesavefield", ConditionOperator.NotEqual, true);
            FilterExpression    fiEx  = new FilterExpression();

            fiEx.AddCondition(conEx);
            BulkDeleteRequest request = new BulkDeleteRequest
            {
                JobName           = "Delete unsaved cases",
                ToRecipients      = new Guid[] { },
                CCRecipients      = new Guid[] { },
                RecurrencePattern = string.Empty,
                QuerySet          = new QueryExpression[]
                {
                    new QueryExpression {
                        EntityName = "incident", Criteria = fiEx
                    }
                }
            };
            BulkDeleteResponse response = (BulkDeleteResponse)_orgServ.Execute(request);
        }
Exemple #29
0
        public void CreateBulkDeleteJob(string entityName, int executeTimePerday)
        {
            var  req  = new WhoAmIRequest();
            var  res  = (WhoAmIResponse)CRMOrganizationService.Execute(req);
            Guid guid = res.UserId;

            var condition = new ConditionExpression("statecode", ConditionOperator.NotNull);
            var filter    = new FilterExpression();

            filter.AddCondition(condition);
            var query = new QueryExpression
            {
                EntityName = entityName,
                Distinct   = false,
                Criteria   = filter
            };
            DateTime now   = DateTime.Now;
            DateTime start = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0).AddHours(1);
            int      steps = 24 * 60 / executeTimePerday;

            for (int i = 0; i < executeTimePerday; i++)
            {
                var request = new BulkDeleteRequest
                {
                    JobName               = "Bulk Delete " + entityName + start.ToString(" HH-mm-ss"),
                    QuerySet              = new[] { query },
                    StartDateTime         = start,
                    SendEmailNotification = false,
                    RecurrencePattern     = "FREQ=DAILY;INTERVAL=1;",
                    ToRecipients          = new Guid[] { guid },
                    CCRecipients          = new Guid[] { }
                };
                CRMOrganizationService.Execute(request);
                start = start.AddMinutes(steps);
            }
        }
Exemple #30
0
        /// <inheritdoc/>
        protected override object ExecuteInternal(IOrganizationService org, IAttributeMetadataCache metadata, IQueryExecutionOptions options)
        {
            // Check if the query is allowed
            if (options.Cancelled)
            {
                return(null);
            }

            if (options.BlockDeleteWithoutWhere && !FetchXml.Items.OfType <FetchEntityType>().Single().Items.OfType <filter>().Any())
            {
                throw new InvalidOperationException("DELETE without WHERE is blocked by your settings");
            }

            var meta = metadata[EntityName];

            // If we are using a bulk delete job, start the job
            if (options.UseBulkDelete && Extensions.Count == 0 && meta.IsIntersect != true)
            {
                var query = ((FetchXmlToQueryExpressionResponse)org.Execute(new FetchXmlToQueryExpressionRequest {
                    FetchXml = Serialize(FetchXml)
                })).Query;

                var bulkDelete = new BulkDeleteRequest
                {
                    JobName               = $"SQL 4 CDS {meta.DisplayCollectionName.UserLocalizedLabel.Label} Bulk Delete Job",
                    QuerySet              = new[] { query },
                    StartDateTime         = DateTime.Now,
                    RunNow                = true,
                    RecurrencePattern     = String.Empty,
                    SendEmailNotification = false,
                    ToRecipients          = new Guid[0],
                    CCRecipients          = new Guid[0]
                };

                org.Execute(bulkDelete);

                return("Bulk delete job started");
            }

            // Otherwise, get the records to delete
            var count    = 0;
            var entities = RetrieveAll(org, metadata, options).Entities;

            if (entities == null)
            {
                return(null);
            }

            // Check again if the query is allowed
            if (!options.ConfirmDelete(entities.Count, meta))
            {
                throw new OperationCanceledException("DELETE cancelled by user");
            }

            ExecuteMultipleRequest multiple = null;

            // Delete hte records in batches
            foreach (var entity in entities)
            {
                if (options.Cancelled)
                {
                    break;
                }

                if (options.BatchSize == 1)
                {
                    options.Progress($"Deleting {meta.DisplayName.UserLocalizedLabel.Label} {count + 1:N0} of {entities.Count:N0}...");
                    org.Execute(CreateDeleteRequest(meta, entity));
                    count++;
                }
                else
                {
                    if (multiple == null)
                    {
                        multiple = new ExecuteMultipleRequest
                        {
                            Requests = new OrganizationRequestCollection(),
                            Settings = new ExecuteMultipleSettings
                            {
                                ContinueOnError = false,
                                ReturnResponses = false
                            }
                        };
                    }

                    multiple.Requests.Add(CreateDeleteRequest(meta, entity));

                    if (multiple.Requests.Count == options.BatchSize)
                    {
                        options.Progress($"Deleting {meta.DisplayCollectionName.UserLocalizedLabel.Label} {count + 1:N0} - {count + multiple.Requests.Count:N0} of {entities.Count:N0}...");
                        var resp = (ExecuteMultipleResponse)org.Execute(multiple);
                        if (resp.IsFaulted)
                        {
                            throw new ApplicationException($"Error deleting {meta.DisplayCollectionName.UserLocalizedLabel.Label}");
                        }

                        count += multiple.Requests.Count;

                        multiple = null;
                    }
                }
            }

            if (!options.Cancelled && multiple != null)
            {
                options.Progress($"Deleting {meta.DisplayCollectionName.UserLocalizedLabel.Label} {count + 1:N0} - {count + multiple.Requests.Count:N0}...");
                var resp = (ExecuteMultipleResponse)org.Execute(multiple);
                if (resp.IsFaulted)
                {
                    throw new ApplicationException($"Error deleting {meta.DisplayCollectionName.UserLocalizedLabel.Label}");
                }

                count += multiple.Requests.Count;
            }

            return($"{count:N0} {meta.DisplayCollectionName.UserLocalizedLabel.Label} deleted");
        }
        //public static OpStat ProcessAllEntities(this IOrganizationService service, IEnumerable<Entity> entities,
        //    Action<IEnumerable<Entity>> action)
        //{
        //    action(entities);
        //}
        public static bool DeleteBulkAsync(this IOrganizationService service, params QueryExpression[] set)
        {
            try
            {
                if (set == null || !set.Any())
                {
                    throw new ArgumentNullException("set");
                }

                // Create the bulk delete request.
                BulkDeleteRequest bulkDeleteRequest = new BulkDeleteRequest();

                // Set the request properties.
                bulkDeleteRequest.JobName = "Bulk Delete";

                // Querying activities
                bulkDeleteRequest.QuerySet = set;

                // Set the start time for the bulk delete.
                bulkDeleteRequest.StartDateTime = DateTime.Now;

                // Set the required recurrence pattern.
                bulkDeleteRequest.RecurrencePattern = String.Empty;

                var currentUserId = Guid.Empty;

                WhoAmIRequest request = new WhoAmIRequest();
                WhoAmIResponse response = (WhoAmIResponse)service.Execute(request);
                if (response != null)
                    currentUserId = response.UserId;

                // Set email activity properties.
                bulkDeleteRequest.SendEmailNotification = false;
                bulkDeleteRequest.ToRecipients = new[] { currentUserId };
                bulkDeleteRequest.CCRecipients = new Guid[] { };

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

                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }
        private static BulkDeleteResult DeleteInternal(IOrganizationService service, QueryExpression[] querySets)
        {
            BulkDeleteResult result = new BulkDeleteResult();

            // Create the bulk delete request
            BulkDeleteRequest bulkDeleteRequest = new BulkDeleteRequest()
            {
                // Set the request properties
                JobName = "Temp Bulk Delete " + DateTime.Now,
                QuerySet = querySets,
                ToRecipients = new Guid[0],
                CCRecipients = new Guid[0],
                RecurrencePattern = string.Empty
            };

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

            Guid asyncId = response.JobId;
            var bulkOperation = GetBulkDeleteOperation(service, asyncId);

            // Monitor the async operation through polling until it is complete or max polling time expires.
            int secondsTicker = MaxAsynchronousRequestTimeout;
            while (secondsTicker > 0)
            {
                // Make sure that the async operation was retrieved.
                if (bulkOperation != null && bulkOperation.StateCode.Value == BulkDeleteOperationState.Completed)
                {
                    result.TimedOut = false;
                    break;
                }

                // Wait a second for async operation to become active.
                System.Threading.Thread.Sleep(1000);
                secondsTicker--;

                // Retrieve the entity again
                bulkOperation = GetBulkDeleteOperation(service, asyncId);
            }

            if (result.TimedOut == null)
            {
                result.TimedOut = true;
            }

            // Validate that the operation was completed.
            if (bulkOperation == null)
            {
                result.Result = "The Bulk Operation for Async " + asyncId + " was not found.";
            }
            else
            {
                result.DeletedCount = bulkOperation.SuccessCount ?? 0;
                result.DeleteFailedCount = bulkOperation.FailureCount ?? 0;
                if (bulkOperation.StateCode.Value != BulkDeleteOperationState.Completed ||
                    bulkOperation.StatusCode.Value != (int)bulkdeleteoperation_statuscode.Succeeded)
                {
                    // This happens if it took longer than the polling time allowed 
                    // for this operation to finish.
                    result.Result = "The operation took longer than the polling time allowed for this operation to finish.";
                }
                else if (result.DeleteFailedCount > 0)
                {
                    result.Result = string.Format("The opertion had {0} failures and {1} successful deletions",
                            result.DeletedCount, result.DeleteFailedCount);
                }
                else
                {
                    result.Result = string.Format("The operation had {0} successful deletions",
                        result.DeletedCount);
                }
            }

            service.Delete(BulkDeleteOperation.EntityLogicalName, bulkOperation.Id);

            // We have to update the AsyncOperation to be in a Completed state before we can delete it.
            service.InitializeEntity<Entities.AsyncOperation>(bulkOperation.AsyncOperationId.Id,
                    a => { a.StateCode = AsyncOperationState.Completed; });

            // Not sure if the status code needs to be set...
            //a.StatusCode = new OptionSetValue((int)asyncoperation_statuscode.Succeeded) });
            service.Delete(Entities.AsyncOperation.EntityLogicalName, bulkOperation.AsyncOperationId.Id);
            return result;
        }
        /// <summary>
        /// Perform the main action of the sample - issuing a BulkDeleteRequest.
        /// </summary>
        /// <param name="useRecurrence">
        /// whether or not to create a recurring BulkDeleteRequest.
        /// </param>
        private void PerformBulkDelete(bool useRecurrence, bool promptToDelete)
        {
            try
            {
                Console.WriteLine("Performing Bulk Delete Operation");

                // Query for a system user to send an email to after the bulk delete
                // operation completes.
                var userRequest = new WhoAmIRequest();
                var userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);
                Guid currentUserId = userResponse.UserId;

                Console.WriteLine("  Requesting user retrieved.");

                // Create a condition for a bulk delete request.
                // NOTE: If no records are found that match this condition, the bulk delete
                // will not fail.  It will succeed with 0 successes and 0 failures.
                var deleteCondition = new ConditionExpression(
                    "name", ConditionOperator.Equal, "Fourth Coffee");

                // Create a fiter expression for the bulk delete request.
                var deleteFilter = new FilterExpression();
                deleteFilter.Conditions.Add(deleteCondition);

                // Create the bulk delete query set.
                var bulkDeleteQuery = new QueryExpression
                {
                    EntityName = Account.EntityLogicalName,
                    Distinct = false,
                    Criteria = deleteFilter
                };

                // Create the bulk delete request.
                var bulkDeleteRequest = new BulkDeleteRequest
                {
                    JobName = "Sample Bulk Delete",
                    QuerySet = new[] { bulkDeleteQuery },
                    StartDateTime = DateTime.Now,
                    ToRecipients = new[] { currentUserId },
                    CCRecipients = new Guid[] {},
                    SendEmailNotification = true,
                    RecurrencePattern = String.Empty
                    
                };

                // Create a recurring BulkDeleteOperation.
                if (useRecurrence)
                {
                    bulkDeleteRequest.RecurrencePattern = "FREQ=DAILY;INTERVAL=1;";
                }

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

                Console.WriteLine("  The Bulk Delete Request was made and the Bulk\n" +
                                  "    Delete Operation should be created.");

                // To monitor the asynchronous operation, retrieve the
                // bulkdeleteoperation object.
                // NOTE: There will be a period of time from when the async operation
                // request was submitted to the time when a successful query for that
                // async operation can be made.  When using plug-ins, events can be
                // subscribed to that will fire when the async operation status changes.
                var bulkQuery = new QueryByAttribute();
                bulkQuery.ColumnSet = new ColumnSet(true);
                bulkQuery.EntityName = BulkDeleteOperation.EntityLogicalName;

                // NOTE: When the bulk delete operation was submitted, the GUID that was
                // returned was the asyncoperationid, not the bulkdeleteoperationid.
                bulkQuery.Attributes.Add("asyncoperationid");
                bulkQuery.Values.Add(bulkDeleteResponse.JobId);

                // With only the asyncoperationid at this point, a RetrieveMultiple is
                // required to get the bulk delete operation created above.
                var entityCollection =
                    _serviceProxy.RetrieveMultiple(bulkQuery);
                BulkDeleteOperation createdBulkDeleteOperation = null;
                
                // When creating a recurring BulkDeleteOperation, the BulkDeleteOperation
                // will be in suspended status after the current instance has completed.
                // When creating a non-recurring BulkDeleteOperation, it will be in
                // Completed status when it is finished.
                var bulkOperationEnded = useRecurrence
                    ? BulkDeleteOperationState.Suspended
                    : BulkDeleteOperationState.Completed;

                createdBulkDeleteOperation = RetrieveBulkDeleteOperation(
                    bulkQuery, entityCollection, bulkOperationEnded);
                _bulkDeleteOperationId = createdBulkDeleteOperation.Id;

                if (createdBulkDeleteOperation != null)
                {
                    // If the BulkDeleteOperation is recurring, the status will be
                    // "Waiting" after the operation completes this instance.  If it is
                    // non-recurring, the status will be "Succeeded".
                    var bulkOperationSuccess = useRecurrence
                        ? bulkdeleteoperation_statuscode.Waiting
                        : bulkdeleteoperation_statuscode.Succeeded;

                    InspectBulkDeleteOperation(createdBulkDeleteOperation,
                        bulkOperationEnded, bulkOperationSuccess, useRecurrence);

                    DeleteRecords(promptToDelete);
                }
                else
                {
                    Console.WriteLine("  The Bulk Delete Operation could not be retrieved.");
                }
            }
            catch (System.Web.Services.Protocols.SoapException)
            {
                // Perform error handling here.
                throw;
            }
        }
Exemple #34
0
        /// <summary>
        /// Performs the main operation of the sample - performs a bulk delete on inactive
        /// opportunities and activities to remove them from the system.
        /// </summary>
        private void PerformBulkDeleteBackup()
        {
            try
            {
                // Query for a system user to send an email to after the bulk delete
                // operation completes.
                var userRequest = new WhoAmIRequest();
                var userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);
                Guid currentUserId = userResponse.UserId;

                //<snippetBulkDelete>
                // Create a condition for a bulk delete request.
                // NOTE: This sample uses very specific queries for deleting records
                // that have been manually exported in order to free space.
                QueryExpression opportunitiesQuery = BuildOpportunityQuery();

                // Create the bulk delete request.
                BulkDeleteRequest bulkDeleteRequest = new BulkDeleteRequest();

                // Set the request properties.
                bulkDeleteRequest.JobName = "Backup Bulk Delete";

                // Querying activities
                bulkDeleteRequest.QuerySet = new QueryExpression[]
                {
                    opportunitiesQuery,
                    BuildActivityQuery(Task.EntityLogicalName),
                    BuildActivityQuery(Fax.EntityLogicalName),
                    BuildActivityQuery(PhoneCall.EntityLogicalName),
                    BuildActivityQuery(Email.EntityLogicalName),
                    BuildActivityQuery(Letter.EntityLogicalName),
                    BuildActivityQuery(Appointment.EntityLogicalName),
                    BuildActivityQuery(ServiceAppointment.EntityLogicalName),
                    BuildActivityQuery(CampaignResponse.EntityLogicalName),
                    BuildActivityQuery(RecurringAppointmentMaster.EntityLogicalName)
                };

                // Set the start time for the bulk delete.
                bulkDeleteRequest.StartDateTime = DateTime.Now;

                // Set the required recurrence pattern.
                bulkDeleteRequest.RecurrencePattern = String.Empty;

                // Set email activity properties.
                bulkDeleteRequest.SendEmailNotification = false;
                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)_serviceProxy.Execute(bulkDeleteRequest);
                Console.WriteLine("The bulk delete operation has been requested.");
                //</snippetBulkDelete>

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