System jobs in Dynamics

For DevOps, we have to handle each and everything from code behind and in automated way. Thus, wrote code to create manage System jobs to delete records every night in Dynamics. Here are the main points from my understanding ..

The BulkDeleteRequest message will create a bulk delete job that will be automatically executed on a specified interval for a specified set of data.  The job will be executed by the CRM Asynchronous service.

The following properties need to be set:

JobNameThis is the name of the job which will be displayed on the Bulk Record Deletion job list
QuerySetThis is a collection of QueryExpressions that CRM will use to determine what records to delete.Note: my example is not real-world.
StartDateTimeThis is the start date for the job. If you don’t specify this date, the date and time the job was created will be used.
RecurrencePatternHow frequently do you wish to run this job. More information about the possible recurrence patterns can be found here: Recurrence Pattern in Asynchronous Job Execution
SendEmailNotificationIs set to true if you would like to send an email to someone when the job has completed.
ToRecipientsList of CRM users to send an email to.
CCRecipientsList of CRM users to CC when the email is sent.Note: this field needs to be specified, even if it is empty.

… and here is code snippet for it …

  1. Find specified jobs and delete those ..
private void FindAndDeleteExistingSystremJobs()

            var qeBulkDeleteOperation = new QueryExpression("bulkdeleteoperation");
            qeBulkDeleteOperation.ColumnSet.AllColumns = true;

            // Define Condition Values
            var user_fullname = "SYSTEM";

            var qeSystemuser = new QueryExpression("systemuser");


            qeSystemuser.Criteria.AddCondition("fullname", ConditionOperator.Equal, user_fullname);
            EntityCollection users = msdService.orgService.RetrieveMultiple(qeSystemuser);

            if (!(users.Entities.Count == 1))
                throw new Exception("Data issue: Found multiple System users. Please fix the data.");

            Entity sysUser = users.Entities.FirstOrDefault();

            //qeBulkDeleteOperation.Criteria.AddCondition("orderedquerysetxml", ConditionOperator.Like, "%dhhs_recurringprocess%");
            //qeBulkDeleteOperation.Criteria.AddCondition("statuscode", ConditionOperator.Equal, 10); //waiting
            qeBulkDeleteOperation.Criteria.AddCondition("ownerid", ConditionOperator.NotEqual, sysUser.Id);

            EntityCollection bulkDeleteJobs = msdService.orgService.RetrieveMultiple(qeBulkDeleteOperation);
            //Helper.Log($"{bulkDeleteJobs.Entities.Count} system jobs found.");

            foreach (Entity systemJob in bulkDeleteJobs.Entities)
                if ((string)systemJob["name"] != "Delete Booking Change records")
                    msdService.orgService.Delete(systemJob.LogicalName, systemJob.Id);

2. Recreate the system job with desired criteria …

 private void CreateBulkDeleteSystremJob()
            string jobName = "Bulk Delete job for 'RecurringProcess'";
            //int interval = 30;
            string frequency = String.Format(System.Globalization.CultureInfo.InvariantCulture, "FREQ=DAILY;"); // INTERVAL={0};", interval);
            WhoAmIRequest userRequest = new WhoAmIRequest();
            WhoAmIResponse userResponse = (WhoAmIResponse)msdService.orgService.Execute(userRequest);
            Guid currentUserId = userResponse.UserId;
            // Create the bulk delete query set.
            var bulkDeleteQuery = new QueryExpression
                EntityName = "soft_recurringprocess",
                Distinct = false,
                Criteria = new FilterExpression()

            DateTime today = DateTime.Now;

            BulkDeleteRequest bulkDeleteRequest =
                new BulkDeleteRequest
                    JobName = jobName,
                    QuerySet = new QueryExpression[] { bulkDeleteQuery },
                    StartDateTime = new DateTime(today.Year, today.Month, today.Day, 23, 30, 00),
                    RecurrencePattern = frequency,
                    SendEmailNotification = true,
                    ToRecipients = new Guid[] { currentUserId },
                    CCRecipients = new Guid[] { }

            var id = msdService.orgService.Execute(bulkDeleteRequest);

That’s it for this time. Explore more on SDK of Delete bulk jobs here. Thanks!!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s