web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

System Job -> "waiting for retry due to error" but it worked?

(0) ShareShare
ReportReport
Posted on by 8,270

Hi guys,

I have a plugin that each time a custom record is created, it checks if it already exists; if so, it deletes the new record to avoid duplicates.

Then if I check the System Jobs, it shows "waiting for retry due to error". But then I check the record and there are not duplicates.

The detailed message is:  "new_customentity With Id = 30689d76-3457-e511-8103-c4346bac9948 Does Not Exist" So it's like it tries to double delete or something like that? I don't get it.

So, it works, but still there is this Job saying that there is an error :(

Any ideas to solve this please?

Regards,

Raúl

*This post is locked for comments

I have the same question (0)
  • Sartaj Profile Picture
    880 on at

    Hi Raul,

    Just as a thought , why you are not using OTB duplicate detection rule? I think this will give more control to the user while they are creating a record weather they want to go ahead with duplication or not. In-fact the plugin which you are using will delete record without any notification to user ,thanks.

    Sartaj

  • Suggested answer
    Aiden Kaskela Profile Picture
    19,696 on at

    Hi Raul,

    If I'm reading your post correctly, your custom workflow queries for a record, and based on some conditions, it will delete the newly created record. Is it possible you already have duplicate detection setup? This could cause the record to be deleted before your (async, I assume) workflow runs.

    If that's not the case, it might be a plain old bug in your code. If you posted the code, another set of eyes might be helpful.

    Thanks,

     Aiden

  • RaulOcana Profile Picture
    8,270 on at

    Hi Sartaj,

    Didn't know DDR worked with custom entities. I will try that, but one question, I'm creating these records through a plug-in not manually, will this work too?

    Regards,

    Raúl

  • RaulOcana Profile Picture
    8,270 on at

    Hi Aiden,

    Thanks for your help, here is the code:

    public void Execute(IServiceProvider serviceProvider)
            {
                //Extract the tracing service for use in debugging sandboxed plug-ins.
                ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
    
                // Obtain the execution context from the service provider.
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    
                // The InputParameters collection contains all the data passed in the message request.
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    // Obtain the target entity from the input parameters.
                    Entity entity = (Entity)context.InputParameters["Target"];
    
                    // Verify that the target entity represents a MAI. If not, this plug-in was not registered correctly.
                    if (entity.LogicalName != "new_marketingactivityinstance")
                        return;
    
                    try 
                    {
                        if (entity.Attributes.Contains("new_marketingactivitiesid"))
                        {
                            Guid _newLeadGuid = ((EntityReference)entity.Attributes["new_marketingactivitiesid"]).Id;
    
                            // Create query to get MAIs
                            ConditionExpression condition = new ConditionExpression();
                            condition.AttributeName = "new_marketingactivitiesid";
                            condition.Operator = ConditionOperator.Equal;
                            condition.Values.Add(_newLeadGuid);
    
                            FilterExpression filter = new FilterExpression();
                            filter.Conditions.AddRange(condition);
    
                            QueryExpression query = new QueryExpression("new_marketingactivityinstance");
                            query.ColumnSet = new ColumnSet(true);
                            query.Criteria.AddFilter(filter);
                            query.AddOrder("new_marketingactivityid", OrderType.Ascending);
    
                            // Obtain the organization service reference.
                            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
    
                            // Obatin MA id
                            if (entity.Contains("new_marketingactivityid"))
                            {
                                Guid _newMAI = ((Guid)entity.Attributes["new_marketingactivityinstanceid"]);
                                Guid _newMA = ((EntityReference)entity.Attributes["new_marketingactivityid"]).Id;
    
                                // Obtain MAIs regarding the Lead
                                DataCollection<Entity> _marketingactivityinstances = service.RetrieveMultiple(query).Entities;
                                foreach (Entity MAI in _marketingactivityinstances)
                                {
                                    // Obtain MA id
                                    if (MAI.Contains("new_marketingactivityid"))
                                    {
                                        Guid _oldMAI = ((Guid)MAI.Attributes["new_marketingactivityinstanceid"]);
                                        Guid _oldMA = ((EntityReference)MAI.Attributes["new_marketingactivityid"]).Id;
    
                                        if (_oldMA == _newMA && _oldMAI != _newMAI)
                                        {
                                            // Delete new duplicated MAI in Microsoft Dynamics CRM.
                                            if (ExistsById(service, _newMAI))
                                            {
                                                tracingService.Trace("CleanMAIDuplicates: Deleting the duplicated MAI.");
                                                service.Delete("new_marketingactivityinstance", _newMAI);
    
                                                ExecuteWorkflowRequest req = new ExecuteWorkflowRequest();
                                                ExecuteWorkflowResponse resp = new ExecuteWorkflowResponse();
                                            
                                                // Update Lead's Score (New MAI)
                                                req.WorkflowId = new Guid("3648262F-7617-4B7D-B0AE-9946DBDE08F2");
                                                req.EntityId = _newLeadGuid;
                                                //req.EntityId = new EntityReference("lead", _newLeadGuid).Id;
    
                                                tracingService.Trace("CleanMAIDuplicates: Triggering the Update Lead's Score (New MAI) plug-in.");
                                                resp = (ExecuteWorkflowResponse)service.Execute(req);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (FaultException<OrganizationServiceFault> ex)
                    {
                        tracingService.Trace("Clean MAI Duplicates: " + ex.Message + " |-| " + ex.StackTrace);
                        throw new InvalidPluginExecutionException("An error occurred in the CleanMAIDuplicates plug-in.", ex);
                    }
                    catch (Exception ex)
                    {
                        tracingService.Trace("Clean MAI Duplicates: {0}", ex.ToString());
                        throw;
                    }
                }
            }


  • Suggested answer
    Aiden Kaskela Profile Picture
    19,696 on at

    Hi Raul,

    If I'm reading your code correctly, a marketing activity instance has a lookup to marketing activity. When a marketing activity instance is created, you query for marketing activity instances for the marketing activity, and if the ID is different for an existing one, delete the new activity.

     

    I see two issues with the code, one would definitely cause your error.

     

    Minor: Line 21 you're referencing "new_marketingactivitiesid" and in 47, "new_marketingactivityid" on the incoming Entity. I assume these are two lookups to the activity and if they're both set, everything works fine. If one is set and not the other, your code won't run in one case, and you'll get a null reference exception in the other.

     

    Major: Since your delete call is inside the for loop, if there are two MAI records already, you're going to try and delete the new one twice. Change your query to get back MAI records for the MA, ordered by the created on date, then delete all the results that aren't the oldest one. Not only will it work if there are existing duplicates, but it'll clean up the older duplicates.

     

    Hope this helps! If you could mark this as the verified answer, I'd appreciate it lots.

     

    Thanks,

      Aiden

  • RaulOcana Profile Picture
    8,270 on at

    Hi Aiden,

    Thanks for your help.

    The new record is only created if those two "fields" exist, so it wont be a problem :)

    In the line 60 (_oldMA == _newMA && _oldMAI != _newMAI) I'm making sure that the record (MA) is equal (duplicated found!) and that the record (MAI) is not the older one. So it will only Delete if the MA is duplicated and if the MAI is different from the old one.

    But still something is missing because it does look like it's trying to delete the same record twice.

    Regards,

    Raúl

  • Verified answer
    Aiden Kaskela Profile Picture
    19,696 on at

    Hi Raul,

    I'm pretty sure it's the case that if your query brought back 100 MAI records, you would loop through that foreach loop and try to delete the new one 99 times. The MA Id would match and the MAI ID would be different in all but one case. In the delete call, you're always passing the ID of the new record, so it would attempt to delete many times.

    Thanks,

     Aiden

  • Aiden Kaskela Profile Picture
    19,696 on at

    If you're trying to delete the older records, you should be passing the oldId to the delete call. If you only want to delete the new record no matter how many instances of the existing record there are, change the foreach loop to an if, then it'll only run once for the new record.

  • RaulOcana Profile Picture
    8,270 on at

    Thanks Aiden!

  • Aiden Kaskela Profile Picture
    19,696 on at

    Absolutely! Glad it's working.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans