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 Issue in C# getting value from lookup field - ‘Object not set to an instance of an object’

(0) ShareShare
ReportReport
Posted on by 1,589

I have an entity named ace_s_main which contains three fields.

  • The first field is a text box named ace_name
  • The second field is a lookup field named ace_mystate
  • The third field is a textbox named ace_mystatetext

The lookup field ace_mystate links back to the field named ace_state on the entity named ace_s_state

I have a plugin that fires post-op on ace_s_main during an update.

The plugin is supposed to call a protected string method named GetValueFromLookup and pass it the name of the field to pull the value from.

Once GetValueFromLookup receives the passed information and runs, it is supposed to look at the current record that is undergoing the update, and pull the current value out from the ace_mystate lookup field, then return that value as a string.

My problem is I am encountering an error in the very first TRY section of the GetValueFromLookup method when the plugin attempts to access and pull the data from the lookup field.

I get a tracking message ‘Object not set to an instance of an object’

I am hoping someone can explain to me what I am doing incorrectly here and can show me what specific change I need to make to my code to fix it while keeping the general structure intact.

Here is the ExecutePostMainUpdate section.

 protected void ExecutePostMainUpdate(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
                {
                    Entity ace_s_main = (Entity)context.InputParameters["Target"];

                    //var TextBoxValue = GetValueFromTextbox(service, localContext, ace_s_main, "ace_mystatetext");

                    var LookupBoxValue = GetValueFromLookup(service, localContext, ace_s_main, "ace_mystate");

                }
                catch (Exception ex) { throw new Exception("Error 100 in top level code. Initial TRY Failure. Code is not even entering business logic." + ex.Message); }
            }
            else
            {
                throw new InvalidPluginExecutionException("Error 200 in top level code. The code went to the ELSE section instead of executing IF portion. "); 
            }

        }

Here is the GetValueFromLookup method where the error occurs. I placed a comment in this method so you can see exactly where it occurs. The problem occurs with the code that starts between line 10 and line 15 below.

  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"];
               ///THIS IS WHERE THE ERROR IS OCCURRING --- THE PLUGIN IS BOMBING OUT HERE VIA CATCH ERROR 500 SHOWN BELOW IN THE CUSTOM CATCH AREA
                try
                {
                    var FieldValue = PassedEntity.GetAttributeValue<EntityReference>(PassedField);
                    var FieldValueAsString = FieldValue.Name.ToString();
                                 
                    if (String.IsNullOrEmpty(FieldValueAsString))
                    {
                        try
                        {
                            var result = "The field is null or empty";
                            throw new InvalidPluginExecutionException("The Value of The Lookup is: " + result);
                            //return result;
                        }
                        catch (Exception ex) { throw new Exception("Error 300 - Catch Error in  " + ex.Message); }
                    }
                    else
                    {
                        try
                        {
                            var result2 = FieldValueAsString;
                            throw new InvalidPluginExecutionException("The Value of The Lookup is: " + result2);
                            //return result2;

                        }
                        catch (Exception ex) { throw new Exception("Error 400 - Error in ELSE/TRY GetValueFromLookup methpd: " + ex.Message); }

                    }
                }
                // THIS IS WHERE THE CODE IS GOING. IT IS NOT SUCCESSFULLY ACCESSING AND PULLING THE VALUE OUT FROM THE LOOKUP FIELD. 
                catch (Exception ex) { throw new Exception("Error 500 - Error in top level of GetValueFromLookup method: " + ex.Message); }

            }
            return null;
        }


 

What is odd to me, is that I have a method named GetValueFromTextbox that operates almost the exact same as GetValueFromLookup, it just looks at a textbox field named ace_mystatetext that I used for testing and the GetValueFromTextbox method works fine, so I am thinking there is something in the GetValueFromLookup method that isn’t coded correctly or is missing that is causing this to occur, given that similar code works fine pulling values from a text box.

I have also included the code for GetValueFromTextbox below so you can see how that is almost identical to the GetValueFromLookup code.

 protected string GetValueFromTextbox(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
                {
                    string MyFieldValue = PassedEntity.GetAttributeValue<String>(PassedField);
                  
                    if (String.IsNullOrEmpty(MyFieldValue))
                    {
                        try
                        {
                            var result = "The ID is null or empty";
                            throw new InvalidPluginExecutionException("The Value of The Textbox is: " + result);
                           // return result;
                        }
                        catch (Exception ex) { throw new Exception("Catch Error in  " + ex.Message); }
                    }
                    else
                    {
                        try
                        {
                            var result2 = MyFieldValue;
                            throw new InvalidPluginExecutionException("The Value of The Textbox is: " + result2);
                           // return result2;

                        }
                        catch (Exception ex) { throw new Exception("Error in ELSE/TRY GetValueFromTextbox methpd: " + ex.Message); }

                    }
                }

                catch (Exception ex) { throw new Exception("Error in top level of GetValueFromTextbox method: " + ex.Message); }

            }
            return null;
        }

If anyone can explain to me what I am doing incorrectly in my GetValueFromLookup method and can show me what specific change I need to make to my code to fix it while keeping the general structure intact, I would greatly appreciate it.

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Bas van de Sande Profile Picture
    4,383 on at

    Hi Jim,

    did you register an image on the plugin step? In order to get access to all values passed in you need to specify in the plugin registration tool, what attributes should be passed in the plugin as well.

    Thus: If you want to know what properties were changed during update, just look into InputParameters. There will be only updated properties values.

    Pre-Entity images are available for Update message, but not for Create (it's impossible to have an image before entity instance was actually created). But Post-Entity image presents in case of both Create and Update messages.

    on sumedha8.blogspot.nl/.../sample-plug-in-compare-pre-and-post.html you can find an example on working with pre and post entity images

    I hope this points you in the right direction

    Bas

  • ACECORP Profile Picture
    1,589 on at

    I also tried replacing this since I get 'object reference not set to instance of an object' in the trace when it errors out:

     var FieldValue = PassedEntity.GetAttributeValue<EntityReference>(PassedField);
                        var FieldValueAsString = FieldValue.Name.ToString();
    


     

    With this:

     EntityReference FieldValue = (EntityReference)PassedEntity.Attributes[PassedField];
                        var FieldName = FieldValue.Name;
                        string FieldValueAsString = FieldName.ToString();


    But when I do that, I just get a different error "The given key was not present in the dictionary"


    I am so close but clearly I am missing something or do not understand something quite right. Any help would be greatly appreciated. I need to understand how to get the value of the name attribute in this way, and I just can't figure it out.

  • ACECORP Profile Picture
    1,589 on at

    I am not sure what you are talking about when you talk about registering an "image" in the plugin registration tool. I use visual studio 2012 to do everything and do not use the plugin registration tool. I have used plugins to update and check values of text fields many times. But this is the first time I am trying to get the value of a lookup field on the currently open record on update. I think that example shows option sets but my code is looking at a lookup field, not an option set. My plugin executes on update, post-operation. It works fine if I point it to a text box and use the other method I mentioned, but I am trying to do the same thing on a lookup field, and not a text box, and that is my problem. I get errors I mentioned when the code runs up against the specific lookup field on the open record. If I use the other method and point it to a textbox field, its fine. So I am not doing something right when I point it to a lookup and that's what I am trying to understand.

  • Bas van de Sande Profile Picture
    4,383 on at

    Can you show me the plugin code? I want to see what you do with the incoming values. Are you just reading the "Target" inputparameter, or are you working as well with any pre and or post entity images (in this case pre entity image)?

    Then you could do something like:

    PreImage = (Entity)context.PreEntityImages["THE NAME YOU SPECIFIED IN HERE"];

    if (PreImage.Contains("ace_mystate"))

    {

      var x  = ((OptionSetValue)PreImage["ace_mystate"]).Value;

    }

    In order for this to work you have to specify a pre entity image on the plugin step

    Please tell me if I'm making any sense?

    Bas

  • ACECORP Profile Picture
    1,589 on at

    I think I am just using the target input paramter since all I care about is the currently open record that's being udpated. I just need to look inside one of the fields that happens to be a lookup box and read its text/name value.

    I can do exactly what I am doing with text boxes without error. I just need to do the same thing with lookups and that's where I am encountering this probelm. I am very new to CRM so I am still getting my head around things.

    I believe I am telling the plugin to look at the current record that is open, its the same plugin code I use to do the same thing with a text box, and it works for a text box. Just not with a lookup.  I pass it the name of the field to look at in the via the PassedField variable.   

    For example, Here is my code for getting the value of a specific text box in the currently open record during update.  It works great.

     public class PostMainUpdate: Plugin
        {
           public PostMainUpdate()
                : base(typeof(PostMainUpdate))
            {
                base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(40, "Update", "ace_s_main", new Action<LocalPluginContext>(ExecutePostMainUpdate)));
            }
    
            protected void ExecutePostMainUpdate(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
                    {
                        Entity ace_s_main = (Entity)context.InputParameters["Target"];
     
                      //var TextBoxValue = GetValueFromTextbox(service, localContext, ace_s_main, "ace_mystatetext");
     
                        var LookupBoxValue = GetValueFromLookup(service, localContext, ace_s_main, "ace_mystate");
     
                    }
                  catch (Exception ex) { throw new Exception("Error 100 in top level code. Initial TRY Failure. Code is not even entering business logic." + ex.Message); }
                }
                else
                {
                    throw new InvalidPluginExecutionException("Error 200 in top level code. The code went to the ELSE section instead of executing IF portion. "); 
               }
     
            }

    The specific method I call to actually look inside the textbox and grab the text value is this:

    protected string GetValueFromTextbox(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
    
    {
    
    string MyFieldValue = PassedEntity.GetAttributeValue<String>(PassedField);
    
    
    
    
    if (String.IsNullOrEmpty(MyFieldValue))
    
    {
    
    try
    
    {
    
    var result = "The ID is null or empty";
    
    throw new InvalidPluginExecutionException("The Value of The Textbox is: " + result);
    
    // return result;
    
    }
    
    catch (Exception ex) { throw new Exception("Catch Error in " + ex.Message); }
    
    }
    
    else
    
    {
    
    try
    
    {
    
    var result2 = MyFieldValue;
    
    throw new InvalidPluginExecutionException("The Value of The Textbox is: " + result2);
    
    // return result2;
    
    }
    
    catch (Exception ex) { throw new Exception("Error in ELSE/TRY GetValueFromTextbox methpd: " + ex.Message); }
    
    }
    
    }
    
    catch (Exception ex) { throw new Exception("Error in top level of GetValueFromTextbox method: " + ex.Message); }
    
    }
    
    return null;
    
    }
    
    
    
    
    }
    
    }
    

    Now... all I want to do is instead of look inside a text box and get the text. I just want to look inside the lookup field, and get the text or name attribute.

    So I replaced the GetValueFromTextbox shown above with the GetValueFromLookup method shown below:

     

      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"];
                   ///THIS IS WHERE THE ERROR IS OCCURRING --- THE PLUGIN IS BOMBING OUT HERE VIA CATCH ERROR 500 SHOWN BELOW IN THE CUSTOM CATCH AREA
                    try
                    {
                        var FieldValue = PassedEntity.GetAttributeValue<EntityReference>(PassedField);
                        string FieldValueAsString = FieldValue.Name.ToString();
                                     
                        if (String.IsNullOrEmpty(FieldValueAsString))
                        {
                            try
                            {
                                var result = "The field is null or empty";
                                throw new InvalidPluginExecutionException("The Value of The Lookup is: " + result);
                                //return result;
                            }
                            catch (Exception ex) { throw new Exception("Error 300 - Catch Error in  " + ex.Message); }
                        }
                        else
                        {
                            try
                            {
                                var result2 = FieldValueAsString;
                                throw new InvalidPluginExecutionException("The Value of The Lookup is: " + result2);
                                //return result2;
    
                            }
                            catch (Exception ex) { throw new Exception("Error 400 - Error in ELSE/TRY GetValueFromLookup methpd: " + ex.Message); }
    
                        }
                    }
                    // THIS IS WHERE THE CODE IS GOING. IT IS NOT SUCCESSFULLY ACCESSING AND PULLING THE VALUE OUT FROM THE LOOKUP FIELD. 
                    catch (Exception ex) { throw new Exception("Error 500 - Error in top level of GetValueFromLookup method: " + ex.Message); }
    
                }
                return null;
            }
    



    My problem is when I do that, I get the 'Object reference not set to an instance of an object' error in the trace. 

  • ACECORP Profile Picture
    1,589 on at

    I think your question is regarding this

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


    But I think my code is getting passed this to the try/catch area.... its just not entering the try and is instead hitting the "catch".

    I am pretty certain my problem has something to do this this and because something it wrong with the first two lines in the try block, such as something causing 'object reference not set to instance of an object' the plugin is jumping down to the catch block :

     try
                    {
                        var FieldValue = PassedEntity.GetAttributeValue<EntityReference>(PassedField);
                        string FieldValueAsString = FieldValue.LogicalName.ToString();
                                     
                        if (String.IsNullOrEmpty(FieldValueAsString))
                        {


  • Bas van de Sande Profile Picture
    4,383 on at

    Hi Jim,

    have you tried to attached a debugger (or profiler) to debug your code.

    Then you can see what comes in and if you have the field "PassedField" within the passed entity.

    What you can do furthermore is to check if the passed entity contains the key PassedField. This can be achieved by doing:

    if (PassedEntity.Contains(PassedField))  

    // do my stuff

    I want to take a look at your code if you would like me to. Please send it to bas@vd-sande.nl  and I'll take a plunge.

    For now, I'm going to catch some zzzz's  It's getting pretty late at UTC+1. But I can do it right away tomorrow morning

    cheers

    Bas

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

    Hi Jim,

    In these two lines, you may get a null reference exception if the PassedField doesn't exist in your entity. FieldValie would be null, and FieldValue.LogicalName would throw a null reference exception.

    var FieldValue = PassedEntity.GetAttributeValue<EntityReference>(PassedField);

    string FieldValueAsString = FieldValue.LogicalName.ToString();

    If the PassedField doesn't have a value any you attempted PassedEntity[PassedField], you would get a key not found exception.

    If you want to ensure you're returning the right value and checking for null, do something like this:

    string returnValue = String.Empty;
    if (PassedEntity.Contains(PassedField))
    {
     EntityReference entityReference = PassedEntity[PassedField] as EntityReference;
     if (entityReference != null) // if should never be null but it doesn't hurt to check
     { 
      returnValue = entityReference.Name; // or whatever property you want to return
     }
    }
    return returnValue;


    Hope this helps! Let me know if I misunderstood the issue (there was a lot of code to look at in this thread.

    Thanks!

     Aiden

  • ACECORP Profile Picture
    1,589 on at

    Makes sense. I'll build it out a little more with the check you suggested,  but there is a value in the lookup because I selected it when I created the record. When I open the record for update, the value is present in the lookup and I can see what it is, so when I add additional info to some of the other fields and hit save to update the record, that's when the plugin runs, post-operation, and that's why it doesn't make sense as to the reason why this error is occurring, since the lookup has been selected with a value.

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

    Hi Jim,

    Looking at one of your responses above:

    EntityReference FieldValue = (EntityReference)PassedEntity.Attributes[PassedField];

    var FieldName = FieldValue.Name;

    string FieldValueAsString = FieldName.ToString();

    results in Key not found exception

    This can only be because the PassedField doesn't exist in the PassedEntity. It could be a typo in the field name or maybe you aren't getting the value passed in from CRM, but if you get that error, that's absolutely the cause of it.

    You could try troubleshooting this by throwing an exception with all of the attributes in your collection just to see what's there. This would do it:

    string allAttributesText = "All attributes are: " + String.Join(", ", contact.Attributes.Select(a => a.Key));

    // throw exception with allAttributesText

    Thanks,

     Aiden

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