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)

Syntax & Structure Assistance with C# Plugin Getting Value of Lookup

(0) ShareShare
ReportReport
Posted on by 1,589

Before we begin, I want to make sure I correctly understand and articulate what I am trying to do, so want to confirm that my understanding of a Lookup is correct first (shown below) before moving into my actual question which is further below.

It is my understanding that a lookup field in CRM 2011 has three attributes, (1) entitytype, (2) id, and (3) name as shown below, and that the end user readable value of what is stored in the lookup field is contained in the name attribute. 

Assuming that is true, and if an end user selects from the lookup the "John Smith" choice, and the field name is new_mylookup, and since it is the only lookup filed I am looking at programmatically I will simply use element [0], then am I correct in my understanding that the text "John Smith" would be contained in new_mylookup[0].name?

And if I wanted to get the GUID of the lookup field, that links back to the parent entity, I would look at new_mylookup[0].id correct?

new_mylookup[0].entitytype
new_mylookup[0].id
new_mylookup[0].name

Assuming the answer to each of those two quick pre-requisite questions' are "YES" it is now time for my actual question which asked in two parts below:

How can I edit the code below so that instead of getting the value of a standard text field, I am getting the value of the name attribute of a lookup filed in element [0] which is expected to be "John Smith"?

I am guessing that part of my problem rests in the fact that in addition to altering the syntax of how I look at the value inside the passed text field, I also have to change the data type of the field I am passing to the subroutine shown below so that I can properly access and grab the contents from the name attribute, but I am not entirely certain of what to do.

I am hoping that someone could edit the code below to set me on the right track so I know how to deal with this type of issue moving forward.

PART # 1

/**** THE FOLLOWING LINE OF CODE IS CALLED IN THE MAIN EXECUTUON CONTEXT OF MY PLUGIN ***/

ExtractNameStatusGUID(service, NameStatusResultData, "new_s_namestatusid");


/**** THE FOLLOWING LINE OF CODE IS CALLED IN THE MAIN EXECUTUON CONTEXT OF MY PLUGIN ***/

protected string ExtractNameStatusGUID(IOrganizationService ExtractGUIDService, EntityCollection PassedEntityCollection, string PassedFieldToExtract)
        {
                Entity e = PassedEntityCollection.Entities[0];
                var Myname = e.GetAttributeValue<string>(PassedFieldToExtract);
                var MyNameAsString = MyName.ToString();
                return MyNameAsString;
             
        }


I basically pass it the name of the text field and I grab the data inside of that text field.

The code works great if its a standard text field, but not if its a lookup field.

So I need to be able to pass it the name of the lookup field and get the same data from that, returning what I get as a string.

PART # 2

In the same manner, I would also like to extract the GUID value of the lookup field I pass in as PassedFieldToExtract, which I am assuming is contained inside the fieldname[0].id attribute of the PassedFieldToExtract.

The code shown below works great if I am dealing with a text field that contains a GUID, but it obviously does not work if I pass it the name of a lookup field.


/**** THE FOLLOWING LINE OF CODE IS CALLED IN THE MAIN EXECUTUON CONTEXT OF MY PLUGIN ***/

ExtractNameStatusGUID(service, NameStatusResultData, "new_s_namestatusid");


/**** THE FOLLOWING LINE OF CODE IS CALLED IN THE MAIN EXECUTUON CONTEXT OF MY PLUGIN ***/

protected string ExtractNameStatusGUID(IOrganizationService ExtractGUIDService, EntityCollection PassedEntityCollection, string PassedFieldToExtract)
        {
                Entity e = PassedEntityCollection.Entities[0];
                var MyGUID = e.GetAttributeValue<Guid>(PassedFieldToExtract);
                var MyGUIDAsString = MyGUID.ToString();
                return MyGUIDAsString;
             
        }

Any help on re-purposing this code so that it operates in accordance with my lookup value and id extraction needs would be greatly appreciated.

*This post is locked for comments

I have the same question (0)
  • Verified answer
    Aiden Kaskela Profile Picture
    19,696 on at

    Hi Jim,

    A lookup value on an Entity record is typed as an EntityReference, which has Id, LogicalName (the entity name), and Name (the displayname). Here's how you'd get currency info from a Contact:

    ((Microsoft.Xrm.Sdk.EntityReference)contact["transactioncurrencyid"]).Id == "12341234-1234-1234-1234-123412341234"
    ((Microsoft.Xrm.Sdk.EntityReference)contact["transactioncurrencyid"]).Name == "US Dollar"
    ((Microsoft.Xrm.Sdk.EntityReference)contact["transactioncurrencyid"]).LogicalName == "transactioncurrency"


    Your method would be similar. To get the Guid:

    protected string ExtractNameStatusGUID(IOrganizationService ExtractGUIDService, EntityCollection PassedEntityCollection, string PassedFieldToExtract)
            {
                    Entity e = PassedEntityCollection.Entities[0];
                    return ((Microsoft.Xrm.Sdk.EntityReference)e[PassedFieldToExtract]).Id;           
            }


    and to get the name, return the Name or LogicalName field.

    This doesn't have null checks though, so make sure to check that e.Contains(theAttribute) before trying to get a value off the attribute.

    Hope this helps! I'd appreciate if you'd mark this as a Verified answer.

    Thanks,

      Aiden

  • Verified answer
    Royal King Profile Picture
    27,686 on at

    you need to pass right datatype to get lookup value from the collection. Also its worth checking for null before retrieveing it. take look at below code that should get what you are looking for. Lookup is of type EntityReference so while gettign value you have to cast it.

    protected string ExtractNameStatusGUID(IOrganizationService ExtractGUIDService, EntityCollection PassedEntityCollection, string PassedFieldToExtract)

           {

                   Entity e = PassedEntityCollection.Entities[0];

    if( if (e.Attributes.Contains(PassedFieldToExtract))

    {

     var MyGUID = e.GetAttributeValue<EntityReference>(PassedFieldToExtract);

                   var MyGUIDAsString = MyGUID.Id; // this will give you guid of the record

                         var nameString =            MyGUID.Name // this will give Name  ( "Josh Smith")

    //Below line gets name directly

    var directname = ((EntityReference)e.Attributes[PassedFieldToExtract]).Name;

                   return MyGUIDAsString;

    }

           }

  • ACECORP Profile Picture
    1,589 on at

    I am unable to test this within the original construct I used in my example for a number of reasons I cannot go into, but I tried to adapt it to fit into the code I am currently working with as shown below.

    Specifically, the problem I face occurs when I try and replace the method that grabs the value from the text field named GetValueFromRecord, with the method that's exactly the same but grabs the value from the .name attribute of the lookup field named GetValueFromLookup.


    I edited the code to match what it looks like everyone is saying and when I run the updated code that now executes the GetValueFromLookup method, I get an error "Update: Error in GetTransactionMethod: The given key was not present in the dictionary."

    There is a value present in the lookup field on the current open record that my plugin is trying to look at.  Originally, I used javascript to copy the value that's in the lookup to a text box as the end user fills out the form, so I can use the GetValueFromRecord method and grab the value from the text box, but that isn't the best way to do this, I should be able to grab the info directly from the lookup field on the form and not have to copy it to a text box so I can grab it from there. I posted my entire code below in the hope that someone can help me understand what is causing this error.

    Code line 35 and 120 are where the problem is.

     

          public class PostParkingAssignmentUpdate: Plugin
        {
             public PostParkingAssignmentUpdate()
                : base(typeof(PostParkingAssignmentUpdate))
            {
                base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(40, "Update", "new_s_parkingassignment", new Action<LocalPluginContext>(ExecutePostParkingAssignmentUpdate)));
    
                 }
    
                    protected void ExecutePostParkingAssignmentUpdate(LocalPluginContext localContext)
            {
                if (localContext == null)
                {
                    throw new ArgumentNullException("localContext");
                }
    
                // TODO: Implement your custom Plug-in business logic.
                IPluginExecutionContext context = localContext.PluginExecutionContext;
                IOrganizationService service = localContext.OrganizationService;
                ITracingService TracingSvc = localContext.TracingService;
                TracingSvc.Trace("Plugin has started.");
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    try
                    {
                        //Set Up Process
                        Entity new_s_parkingassignment = (Entity)context.InputParameters["Target"];
    
                        var IsExpirySet = GetValueOfExpiryOnRecord(service, localContext, new_s_parkingassignment, "new_expirystatus");
    
                        if (IsExpirySet == true)
                        {
    
                            //var ParkingSpaceValue = GetValueFromRecord(service, localContext, new_s_parkingassignment, "new_pkspace");
    
                            var ParkingSpaceValue = GetValueFromLookup(service, localContext, new_s_parkingassignment, "new_parkingspace");
    
                            var ParkingPermitValue = GetValueFromRecord(service, localContext, new_s_parkingassignment, "new_permitnum");
    
                            var ParkingSpaceResultData = GetRecordContaningValue(service, "new_s_parkingspace", "new_parkingspace", ParkingSpaceValue);
    
                            var ParkingPermitResultsData = GetRecordContaningValue(service, "new_s_permit", "new_permit", ParkingPermitValue);
    
                            if (ParkingSpaceResultData != null)
                            {
                                var ParkingValue = "NO";
                                PerformFieldUpdateOnRecord(service, localContext, ParkingSpaceResultData, ParkingValue, "new_assigned");
                            }
    
                            if (ParkingPermitResultsData != null)
                            {
                                var PermitValue = "NO";
                                PerformFieldUpdateOnRecord(service, localContext, ParkingPermitResultsData, PermitValue, "new_assigned");
    
                            }
    
                        }
    
                    }
                    catch (Exception ex) { throw new Exception("Error in top level Parking Assignment Update: " + ex.Message); }
                }
                else
                {
                    throw new InvalidPluginExecutionException("Error in top level Parking Assignment Update - code went to ELSE section instead of executing"); 
                }
    
            }
           
    
    
            //BUSINESS LOGIC FUNCTIONS
    
              protected string GetValueFromRecord(IOrganizationService EntityService, LocalPluginContext EntityLocalContext, Entity PassedEntity, string PassedField)
            {
                IPluginExecutionContext context = EntityLocalContext.PluginExecutionContext;
    
                EntityService = EntityLocalContext.OrganizationService;
    
                ITracingService TracingSvc = EntityLocalContext.TracingService;
    
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    PassedEntity = (Entity)context.InputParameters["Target"];
                    //Entity new_s_testentity = (Entity)context.InputParameters["Target"];
    
                    try
                    {
                        var TranscationID = PassedEntity.GetAttributeValue<string>(PassedField);
    
    
                        //var TranscationID = PassedEntity.GetAttributeValue<string>("new_testentityinfoid");
                        if (String.IsNullOrEmpty(TranscationID))
                        {
                            try
                            {
                                var result = "The ID is null or empty";
                                return result;
                            }
                            catch (Exception ex) { throw new Exception("Error in IF/TRY TransactionID Check: " + ex.Message); }
                        }
                        else
                        {
                            try
                            {
                                var result2 = TranscationID;
                                return result2;
    
                            }
                            catch (Exception ex) { throw new Exception("Error in ELSE/TRY TransactionID Check: " + ex.Message); }
    
                        }
                    }
    
                    catch (Exception ex) { throw new Exception("Error in GetTransactionMethod: " + ex.Message); }
    
                }
                return null;
            }
    
            protected string GetValueFromLookup(IOrganizationService EntityService, LocalPluginContext EntityLocalContext, Entity PassedEntity, string PassedField)
            {
                IPluginExecutionContext context = EntityLocalContext.PluginExecutionContext;
    
                EntityService = EntityLocalContext.OrganizationService;
    
                ITracingService TracingSvc = EntityLocalContext.TracingService;
    
           if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    PassedEntity = (Entity)context.InputParameters["Target"];
                    
                    try
                    {
    
                        //var TranscationID = PassedEntity.GetAttributeValue<string>(PassedField);
                        var FieldValue = ((EntityReference)PassedEntity.Attributes[PassedField]).Name;
                        var FieldValueAsString = FieldValue.ToString();
                      
                        //var TranscationID = PassedEntity.GetAttributeValue<string>("new_testentityinfoid");
                        if (String.IsNullOrEmpty(FieldValueAsString))
                        {
                            try
                            {
                                var result = "The ID is null or empty";
                                return result;
                            }
                            catch (Exception ex) { throw new Exception("Error in IF/TRY TransactionID Check: " + ex.Message); }
                        }
                        else
                        {
                            try
                            {
                                var result2 = FieldValueAsString;
                                return result2;
    
                            }
                            catch (Exception ex) { throw new Exception("Error in ELSE/TRY TransactionID Check: " + ex.Message); }
    
                        }
                    }
    
                    catch (Exception ex) { throw new Exception("Error in GetTransactionMethod: " + ex.Message); }
    
                }
                return null;
            }
    
    
            protected EntityCollection GetRecordContaningValue(IOrganizationService StatusService, string PassedEntity, string qField1, string qField1SrchValue)//, string QVal1, bool QVal2, string qEntityName, string queryField1, string queryField2, string qUpdFieldName)
            {
                QueryExpression query = new QueryExpression();
                query.EntityName = PassedEntity;
                //query.EntityName = "new_s_licenseinformation";
                query.ColumnSet = new ColumnSet() { AllColumns = true };
                query.Criteria = new FilterExpression();
                query.Criteria.FilterOperator = LogicalOperator.And;
                query.Criteria.Conditions.Add(new ConditionExpression(qField1, ConditionOperator.Equal, qField1SrchValue));
                //query.Criteria.Conditions.Add(new ConditionExpression("new_cashouttransactionnum", ConditionOperator.Null));
                EntityCollection MyReturnedRecords = StatusService.RetrieveMultiple(query);
                if (MyReturnedRecords.Entities.Count > 0)
                {
                    return MyReturnedRecords;
                }
                else
                {
                    //throw new InvalidPluginExecutionException("ELSE Error - code went to ELSE inside the UpdateLicenseRecordsWithTransactionID method.");
                    return null;
                }
            }
    
            protected void PerformFieldUpdateOnRecord(IOrganizationService UpdateService, LocalPluginContext UpdateLocalContext, EntityCollection PassedEntityCollection, string PassedAssignmentStatusValue, string PassedUpdateField)
            {
                IPluginExecutionContext context = UpdateLocalContext.PluginExecutionContext;
                UpdateService = UpdateLocalContext.OrganizationService;
                ITracingService TracingSvc = UpdateLocalContext.TracingService;
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    try
                    {
                        //EVERYTHING UP TO THIS POINT WORKS
                        foreach (Entity e in PassedEntityCollection.Entities)
                        {
                            var AssignmentStatusVal = PassedAssignmentStatusValue;
                            //var submissionstatusid = PassedSubmissionStatusID;
                            //var submissionstatusname = PassedSubmissionStatusName;
                            //e[PassedUpdateField] = new EntityReference(PassedRelatedEntityName, new Guid(AssignmentStatus));
                            //e[PassedUpdateField2] = new EntityReference(PassedRelatedEntityName2, new Guid(submissionstatusid));
                            e[PassedUpdateField] = AssignmentStatusVal;
                            UpdateService.Update(e);
                        }
                        //EVERYTHING BELOW THIS POINT WORKS
                    }
                    catch (Exception ex) { throw new Exception("Error in IF/TRY Failed to Update Entities: " + ex.Message); }
                }
                else
                {
                    try
                    {
                        TracingSvc.Trace("Error! Code went to ELSE/TRY in PerformUpdate method and should have never went here.");
    
                    }
                    catch (Exception ex) { throw new Exception("Error in ELSE/TRY in PerformUpdate method and should have never went here. Code went to Catch but should never have entered this entire section." + ex.Message); }
    
                }
    
            }
    
            protected bool GetValueOfExpiryOnRecord(IOrganizationService CheckValueService, LocalPluginContext CheckValueContext, Entity PassedEntity, string PassedField)
            {
                IPluginExecutionContext context = CheckValueContext.PluginExecutionContext;
    
                CheckValueService = CheckValueContext.OrganizationService;
    
                ITracingService TracingSvc = CheckValueContext.TracingService;
    
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    PassedEntity = (Entity)context.InputParameters["Target"];
                    //Entity new_s_testentity = (Entity)context.InputParameters["Target"];
    
                    if (PassedEntity.Contains(PassedField) && PassedEntity.GetAttributeValue<bool>(PassedField))
                    {
                        //try
                        //{
                           var ExpValue = PassedEntity.GetAttributeValue<bool>(PassedField);
                           //var ExpValAsString = ExpValue.ToString();
                           //return ExpValAsString;
                           return ExpValue;
                     
    
                //           //var TranscationID = PassedEntity.GetAttributeValue<string>("new_testentityinfoid");
                //           if (String.IsNullOrEmpty(TranscationID))
                //           {
                //               try
                //               {
                //                   var result = "The ID is null or empty";
                //                   return result;
                //               }
                //               catch (Exception ex) { throw new Exception("Error in IF/TRY TransactionID Check: " + ex.Message); }
                //           }
                //           else
                //           {
                //               try
                //               {
                //                   var result2 = TranscationID;
                //                   return result2;
    
                //               }
                //               catch (Exception ex) { throw new Exception("Error in ELSE/TRY TransactionID Check: " + ex.Message); }
    
                //           }
                //        }
    
                //        catch (Exception ex) { throw new Exception("Error in GetTransactionMethod: " + ex.Message); }
    
                    }
                    //return null;
                //}
                else
                {
                //    throw new InvalidPluginExecutionException("ELSE Error - code went to ELSE In Main Area");
    
                    return false; 
                }
            
               }
    
            else {return false;}
            }
        }

  • ACECORP Profile Picture
    1,589 on at

    I also tried changing the code so like this, but I get an error stating "Object reference not set to an instance of an object" - any help on this would be greatly appreciated. Clearly there is something major I am not quite grasping here.

    protected string GetValueFromLookup(IOrganizationService EntityService, LocalPluginContext EntityLocalContext, Entity PassedEntity, string PassedField)
            {
                IPluginExecutionContext context = EntityLocalContext.PluginExecutionContext;
    
                EntityService = EntityLocalContext.OrganizationService;
    
                ITracingService TracingSvc = EntityLocalContext.TracingService;
    
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    PassedEntity = (Entity)context.InputParameters["Target"];
                    //Entity new_s_testentity = (Entity)context.InputParameters["Target"];
    
                    try
                    {
                        var TranscationID = PassedEntity.GetAttributeValue<EntityReference>(PassedField);
                        var FieldValueAsString = TranscationID.Name.ToString();
    
    
                        //var TranscationID = PassedEntity.GetAttributeValue<string>("new_testentityinfoid");
                        if (String.IsNullOrEmpty(FieldValueAsString))
                        {
                            try
                            {
                                var result = "The ID is null or empty";
                                return result;
                            }
                            catch (Exception ex) { throw new Exception("Error in IF/TRY TransactionID Check: " + ex.Message); }
                        }
                        else
                        {
                            try
                            {
                                var result2 = FieldValueAsString;
                                return result2;
    
                            }
                            catch (Exception ex) { throw new Exception("Error in ELSE/TRY TransactionID Check: " + ex.Message); }
    
                        }
                    }
    
                    catch (Exception ex) { throw new Exception("Error in GetTransactionMethod: " + ex.Message); }
    
                }
                return null;
            }


  • ACECORP Profile Picture
    1,589 on at

    I'll mark these responses as answers since they most likely solved the question the original way I asked it and will most a more specific question to deal with the modified issue in another post.

  • ACECORP Profile Picture
    1,589 on at

    I put my new question here --- hoping someone can take a read of this and the asnwer ends up being something incredibly easy that I am just completely missing - community.dynamics.com/.../460990

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