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)

Populate a lookup field with the GUID from a record found in FetchXML

(0) ShareShare
ReportReport
Posted on by

Hello

Im trying to write a plugin so that when a record is created it searches for a matching record with the same email address and then creates a relationship to the existing record.

This is what ive got, first issue is the search is finding itself and then i just get an error at the service.Update point

So i dont think the guid from the record found in the FetchXML is coming across but can't work out how to get it or how i exclude itself from the search!

if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity ent = (Entity)context.InputParameters["Target"];

                ContactEmailAddress1 = ent.GetAttributeValue<string>("emailaddress1");
               
                if (ContactEmailAddress1 != null)
                {

        string LeadFetchXml = @"<fetch mapping='logical' version='1.0' output-format='xml - platform' distinct='false'>
        <entity name = 'lead'>
       <attribute name = 'fullname'/>
       <attribute name = 'leadid'/>
       <attribute name = 'mobilephone'/>
       <attribute name = 'emailaddress3'/>
       <attribute name = 'emailaddress2'/>
       <attribute name = 'emailaddress1'/>
       <attribute name = 'parentcontactid'/>
       <attribute name = 'leadenquiry'/>
       <attribute name = 'enquirylookup'/>
            <order descending = 'false' attribute = 'fullname'/>
                <filter type = 'and'>
                    <filter type ='and'>
                        <filter type = 'or'>";

                    if (ContactEmailAddress1 != null)
                        LeadFetchXml += @"<condition attribute='emailaddress1' operator='eq' value='" + ContactEmailAddress1.ToString() + @"'/>
                            <condition attribute='emailaddress2' operator='eq' value='" + ContactEmailAddress1.ToString() + @"'/>
                            <condition attribute='emailaddress3' operator='eq' value='" + ContactEmailAddress1.ToString() + @"'/>";

                    LeadFetchXml += @"                        
                   </filter>
                   <condition attribute='parentcontactid' operator='null' />
                   </filter>
                 </filter>
                </entity>
               </fetch>";

                    EntityCollection sresult = service.RetrieveMultiple(new FetchExpression(LeadFetchXml));
                    {
                        foreach (var c in sresult.Entities)
                        {
                            //How do i exclude itself here?????
                            ParentGuid = (Guid)c.Attributes["leadid"];

                            ent.Attributes["leadenquiry"] = new EntityReference("lead", ParentGuid);
                            ent.Attributes["enquirylookup"] = new EntityReference("lead", ParentGuid);
                            //If i exclude itself, it then Fails here
                            service.Update(ent);

                        }

                    }
                                       
                }
                               
            }
                               
            }
        }
    }

*This post is locked for comments

I have the same question (0)
  • Verified answer
    Mahendar Pal Profile Picture
    45,095 on at

    Hi,

    You can simply change your code to run on precreate, during create iteself you can add reference for the related record. While on pre create you can add attributes to collection. No need to use update call.

  • Suggested answer
    ashlega Profile Picture
    34,477 on at

    What is the error? If it's a recursion, see what Mahender suggested.

    If you wanted to exclude your "current" id from the search, just add a condition:

    $"<condition attribute='leadid' operator='ne' value='{context.PrimaryEntityId}' />"

  • Suggested answer
    Preeti Sharma Profile Picture
    2,678 on at

    Hi,

    Rather than getting id from "leadid" attribute try using context.primaryentityid to get target entity.

    Hope this helps:)

  • gdas Profile Picture
    50,091 Moderator on at

    Hi ,

       EntityCollection result = new EntityCollection();

                           result = service.RetrieveMultiple(new FetchExpression(fetchQuery));

                           if (result != null && result.Entities.Count > 0)

                           {

                               foreach (Entity _entity in result.Entities)

                               {

                                   if (_entity.Contains("attributename"))

                                   {

                                       EntityReference Queuelookup = (EntityReference)_entity.Attributes["attributename"];

                                       destinationQueueId = (Guid)Queuelookup.Id;

                                   }

                               }

                           }

    Please mark this as answer if its helps.

    Thanks

    Goutam

  • DynamicsStu Profile Picture
    on at

    [quote user="gdas"]

    [/quote]

    Thanks ive tried the following but im getting a Business Process Error

    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Client;
    using Microsoft.Xrm.Sdk.Query;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace EnquiriesDataImport
    {
        public class ContactEnquiryLink : IPlugin
        {
            private string LeadEmailAddress1;
            
                    
            public void Execute(IServiceProvider serviceProvider)
            {
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
    
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity ent = (Entity)context.InputParameters["Target"];
    
                    LeadEmailAddress1 = ent.GetAttributeValue<string>("emailaddress1");
                   
                    if (LeadEmailAddress1 != null)
                    {
    
            string LeadFetchXml = @"<fetch mapping='logical' version='1.0' output-format='xml - platform' distinct='false'>
            <entity name = 'lead'>
           <attribute name = 'fullname'/>
           <attribute name = 'leadid'/>
           <attribute name = 'mobilephone'/>
           <attribute name = 'emailaddress3'/>
           <attribute name = 'emailaddress2'/>
           <attribute name = 'emailaddress1'/>
           <attribute name = 'parentcontactid'/>
           <attribute name = 'leadenquiry'/>
           <attribute name = 'enquirylookup'/>
                <order descending = 'false' attribute = 'fullname'/>
                    <filter type = 'and'>
                        <filter type ='and'>
                            <filter type = 'or'>";
    
                        if (LeadEmailAddress1 != null)
                            LeadFetchXml += @"<condition attribute='emailaddress1' operator='eq' value='" + LeadEmailAddress1.ToString() + @"'/>
                                <condition attribute='emailaddress2' operator='eq' value='" + LeadEmailAddress1.ToString() + @"'/>
                                <condition attribute='emailaddress3' operator='eq' value='" + LeadEmailAddress1.ToString() + @"'/>";
    
                        LeadFetchXml += @"                        
                       </filter>
                       <condition attribute='parentcontactid' operator='null' />
                       <condition attribute='description' operator='like' value='%Work dam it%' />
                       </filter>
                     </filter>
                    </entity>
                   </fetch>";
    
                       EntityCollection result = new EntityCollection();
    
                        result = service.RetrieveMultiple(new FetchExpression(LeadFetchXml));
    
    
    
                         {
                            
                            foreach(Entity _entity in result.Entities)
                            {
     EntityReference Queuelookup = (EntityReference)_entity.Attributes["leadenquiry"];
    
                                
    
                                
                                ent.Attributes["enquirylookup"] = new EntityReference("lead", Queuelookup.Id);
                                ent.Attributes["leadenquiry"] = new EntityReference("lead", Queuelookup.Id);
                                
                          
                                                    }
    
                        }
                                           
                    }
                                   
                }
                                   
                }
            }
        }
  • ashlega Profile Picture
    34,477 on at

    Hi,

     add try-catch around your code.

     try

     {

     }

     catch(Exception ex){

         throw new InvalidPluginExecutionException(ex.Message);

     }

     at least that will give you the error message.

     Wondering if the error is happening in this line:

    ntityReference Queuelookup = (EntityReference)_entity.Attributes["leadenquiry"];

     You are not verifying if your entity contains "leadenquiry" attribute, so it might be failing there.

  • DynamicsStu Profile Picture
    on at

    Hello,

    Its failing at the following line with the message below

    result = service.RetrieveMultiple(new FetchExpression(LeadFetchXml));

    Exception: Exception thrown: 'System.Collections.Generic.KeyNotFoundException' in mscorlib.dll ("The given key was not present in the dictionary."). Exception thrown: 'System.Collections.Generic.KeyNotFoundException' in mscorlib.dll ("The given key was not present in the dictionary.")

  • ashlega Profile Picture
    34,477 on at

    Hm.. I think it's not failing in that line since CRM would give you a different message it it were a problem with Fetch.

    Try commenting out eveyrthing inside your for loop (just keep the for loop itself) and see if the error is still there. If it's gone after that, then it's likely the line I mentioned above.

  • DynamicsStu Profile Picture
    on at

    It still errors in Dynamics but runs through in the debug

    I inspected "Result" and it has the record returned by the fetchXML

  • ashlega Profile Picture
    34,477 on at

    Did you try adding try-catch and rethrowing the error as InvalidPluginExecutionException?

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