locked
CRM 2013. Could not get lookup RRS feed

  • Question

  • Trying to retrieve lookup field id or value, but always get an error

    Here is the code:

            protected void ExecutePostCaseUpdate(LocalPluginContext localContext)
            {
                if (localContext == null)
                {
                    throw new ArgumentNullException("localContext");
                }
                IPluginExecutionContext context = localContext.PluginExecutionContext;
                IOrganizationService service = localContext.OrganizationService;
                if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity && context.Depth < 2)
                {
                    Entity entity = (Entity)context.InputParameters["Target"];
                    try
                    {
                        if (entity.Attributes.Contains("customerid") == false)
                        {
                            var getLookup = (EntityReference)entity.Attributes["customerid"];
                            var getId = getLookup.Id; //.ToString() does not help too
                            entity["description"] = getId;
                        }
                        service.Update(entity);
                    }
                    catch (FaultException ex)
                    {
                        throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
                    }
                }
            }

    Thanks for suggestions.


    Если сообщение оказалось полезным, пожалуйста, проголосуйте за него или пометьте в качестве ответа.

    Wednesday, May 28, 2014 3:56 PM

Answers

  • Are you sure that you have registered image for your plugin? Seems that not.

    Dynamics CRM MVP/ Technical Evangelist at SlickData LLC
    My blog

    • Marked as answer by Dismantled Thursday, May 29, 2014 11:50 AM
    Thursday, May 29, 2014 11:02 AM
    Moderator
  • Have you declared Image in Pre Image Alias field during creation of a plugin from a screenshot:


    Dynamics CRM MVP/ Technical Evangelist at SlickData LLC
    My blog

    • Marked as answer by Dismantled Thursday, May 29, 2014 11:50 AM
    Thursday, May 29, 2014 11:38 AM
    Moderator

All replies

  • Seems to be a problem with the condition check of 'customerid'. Should be like the below one.

    if (entity.Attributes.Contains("customerid"))
    {
          
     }

    Thanks & Regards
    Vinoth


    Wednesday, May 28, 2014 4:12 PM
  • You need to change the if condition from false to true.

    My blog: www.crmanswers.net - Rockstar 365 Profile

    Wednesday, May 28, 2014 4:13 PM
  • Hello,

    I believe that your Update step doesn't handle Update of customerid field so this field would not be in Target entity. To get customerid you should use Image. Recheck this article.


    Dynamics CRM MVP/ Technical Evangelist at SlickData LLC
    My blog

    Wednesday, May 28, 2014 4:17 PM
    Moderator
  • Changing condition does not show any result. Description field does not change.

    The same result with:

                IPluginExecutionContext context = localContext.PluginExecutionContext;
                IOrganizationService service = localContext.OrganizationService;
                //if (context.InputParameters.Contains("Target") &&
                //context.InputParameters["Target"] is Entity && context.Depth < 2)
                if (context.PostEntityImages.Contains("PostImage") &&
                context.PostEntityImages["PostImage"] is Entity && context.Depth < 2)
                {
                    Entity entity = (Entity)context.PostEntityImages["PostImage"];
                    //Entity entity = (Entity)context.InputParameters["Target"];
                    try
                    {
    
                        if (entity.Attributes.Contains("customerid") == true)
                        {
                            var getLookup = (EntityReference)entity.Attributes["customerid"];
                            var getId = getLookup.Id;
                            entity["description"] = getId;
                        }
    
                        service.Update(entity);
                        
                        
                    }
                    catch (FaultException ex)
                    {
                        throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
                    }
                }


    Если сообщение оказалось полезным, пожалуйста, проголосуйте за него или пометьте в качестве ответа.

    Wednesday, May 28, 2014 4:31 PM
  • Just curious - why do you need it?

    Dynamics CRM MVP/ Technical Evangelist at SlickData LLC
    My blog

    Wednesday, May 28, 2014 4:50 PM
    Moderator
  • Did you debug test it to see if the if condition gets hit? Also, try creating a new entity to update and see if that works.
    Wednesday, May 28, 2014 6:16 PM
  • Just curious - why do you need it?

    Dynamics CRM MVP/ Technical Evangelist at SlickData LLC
    My blog

    I try to understand how it works on easy examples. How to get data, put data etc. Need to begin from something.

    Finally i need make the solution like in that JS script:

    function GetCategory() {
    	var Attribute, GUID;
    	var Attributelookup = [];   
    	Attributelookup = Xrm.Page.getAttribute("customerid").getValue();
    	if (Attributelookup != null) {
    		Name = Attributelookup[0].name;
    		SDK.JQuery.retrieveMultipleRecords(
    			"Contact",
    			"$select=FullName,ParentCustomerId&$filter=FullName eq '"+ encodeURI(Name) +"'",
    			function (results) {
    				if (results == null || results[0] == null) {
    					alert("Организация не опеределена");
    				}
    				else {
    					GUID = results[0].ParentCustomerId.Id;
    					SDK.JQuery.retrieveMultipleRecords(
    						"Account",
    						"$select=Fax,AccountCategoryCode&$filter=AccountId eq guid'"+ GUID +"'",
    						function (results) {
    							if (results == null || results[0] == null) {
    								alert("Категория не опеределена");
    							}
    							else {
    								var result = SDK.Metadata.SyncGetOptionSetLabels("Account", "AccountCategoryCode");
    								var optionsetValue = eval(results[0].AccountCategoryCode.Value);
    								for (var i = 0; i < result.OptionSet.Options.length; i++) {
    									var text = result.OptionSet.Options[i].Label.LocalizedLabels[0].Label;
    									var value = result.OptionSet.Options[i].Value;
    									if (value == optionsetValue) {
    										Xrm.Page.getAttribute("dt_client_category_case").setValue(text);
    									}
    								}
    							}
    						},
    						function (error) { alert(error) },
    						function () {}
    					);
    				}
    			},
    			function (error) { alert(error) },
    			function () {}
    		);
    	}
    }
    This script works on form update. To update the newly created entity I need the plugin.


    Если сообщение оказалось полезным, пожалуйста, проголосуйте за него или пометьте в качестве ответа.

    Wednesday, May 28, 2014 6:40 PM
  • Maybe problem here:

            public PostCaseUpdate()
                : base(typeof(PostCaseUpdate))
            {
                base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(40, "Update", "incident", new Action<LocalPluginContext>(ExecutePostCaseUpdate)));
    
                // Note : you can register for more events here if this plugin is not specific to an individual entity and message combination.
                // You may also need to update your RegisterFile.crmregister plug-in registration file to reflect any change.
            }


    Если сообщение оказалось полезным, пожалуйста, проголосуйте за него или пометьте в качестве ответа.

    Wednesday, May 28, 2014 7:02 PM
  • Trying to register "Pre-Validation" plugin instead "Post-Operation". Does not help.

    Seems like as  there is no "customerid" attribute in the case entity. :(

    If condition true - nothing happens. If false - error like on pic in the my first post.

    Does not thought what it so problematic to get the lookup attribute (id, value, etc).


    Если сообщение оказалось полезным, пожалуйста, проголосуйте за него или пометьте в качестве ответа.


    • Edited by Dismantled Wednesday, May 28, 2014 8:57 PM
    Wednesday, May 28, 2014 8:57 PM
  • if (entity.Attributes.Contains("customerid"))

    Never returns TRUE. "customerid" is a standart attribute of the incident entity.

    No more ideas?

    I deploy the plugin like in this post:

    http://mscrmshop.blogspot.ru/2012/01/step-by-step-plugin-tutorial-using.html

    • Edited by Dismantled Thursday, May 29, 2014 7:50 AM
    Thursday, May 29, 2014 7:45 AM
  • Could you please provide screenshot of your step registration and image registration from Plugin Registration Tool and full final code that you use at the moment?

    Dynamics CRM MVP/ Technical Evangelist at SlickData LLC
    My blog

    Thursday, May 29, 2014 10:15 AM
    Moderator
  • I do not use Plugin Registration Tool.

    I use this solution http://mscrmshop.blogspot.ru/2012/01/step-by-step-plugin-tutorial-using.html Deploy to CRM from VS.

    Full code on that moment is:

    namespace MyPluginPackage.Plugins

    { using System; using System.ServiceModel; using Microsoft.Xrm.Sdk; public class PreValidateCaseUpdate: Plugin { public PreValidateCaseUpdate() : base(typeof(PreValidateCaseUpdate)) { base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(10, "Update", "incident", new Action<LocalPluginContext>(ExecutePreValidateCaseUpdate))); } protected void ExecutePreValidateCaseUpdate(LocalPluginContext localContext) { if (localContext == null) { throw new ArgumentNullException("localContext"); } IPluginExecutionContext context = localContext.PluginExecutionContext; IOrganizationService service = localContext.OrganizationService; if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity && context.Depth < 2) { Entity entity = (Entity)context.InputParameters["Target"]; try { if (entity.Attributes.Contains("customerid")) { //Some code. For example updates incident entity description entity["description"] = "Test"; } service.Update(entity); } catch (FaultException ex) { throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex); } } } }

    }




    • Edited by Dismantled Thursday, May 29, 2014 10:37 AM
    Thursday, May 29, 2014 10:30 AM
  • During test - what field do you change?

    In case you would not change customerid - it would not be in Target. That's why I suggested to use Image and I don't see that you've defined image for this step.


    Dynamics CRM MVP/ Technical Evangelist at SlickData LLC
    My blog

    Thursday, May 29, 2014 10:45 AM
    Moderator
  • This construction does not work too (and PostEntityImages). I tried it many times.

                IPluginExecutionContext context = localContext.PluginExecutionContext;
                IOrganizationService service = localContext.OrganizationService;
                if (context.PreEntityImages.Contains("PreImage") &&
                context.PreEntityImages["PreImage"] is Entity)
                {
                    Entity entity = (Entity)context.PreEntityImages["PreImage"];
                    try
                    {
    
                        if (entity.Attributes.Contains("customerid"))
                        {
                            //Some code. For example updates incident entity description
                            entity["description"] = "Test";
                        }
    
                        service.Update(entity);
                    }
                    catch (FaultException ex)
                    {
                        throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
                    }
                }



    • Edited by Dismantled Thursday, May 29, 2014 10:47 AM
    Thursday, May 29, 2014 10:47 AM
  • Are you sure that you have registered image for your plugin? Seems that not.

    Dynamics CRM MVP/ Technical Evangelist at SlickData LLC
    My blog

    • Marked as answer by Dismantled Thursday, May 29, 2014 11:50 AM
    Thursday, May 29, 2014 11:02 AM
    Moderator
  • Sorry, i'am dummy. Could you explain what did you mean about "registered image"?

    • Edited by Dismantled Thursday, May 29, 2014 11:17 AM
    Thursday, May 29, 2014 11:17 AM
  • Have you declared Image in Pre Image Alias field during creation of a plugin from a screenshot:


    Dynamics CRM MVP/ Technical Evangelist at SlickData LLC
    My blog

    • Marked as answer by Dismantled Thursday, May 29, 2014 11:50 AM
    Thursday, May 29, 2014 11:38 AM
    Moderator
  • Thanks God! Thanks Andreii! It works!

                IPluginExecutionContext context = localContext.PluginExecutionContext;
                IOrganizationService service = localContext.OrganizationService;
    
                Entity preImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains(this.preImageAlias)) ? context.PreEntityImages[this.preImageAlias] : null;
                Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains(this.postImageAlias)) ? context.PostEntityImages[this.postImageAlias] : null;
    
                //IPluginExecutionContext context = localContext.PluginExecutionContext;
    
                if (context.PostEntityImages.Contains("PostImage") &&
                context.PostEntityImages["PostImage"] is Entity && context.Depth < 2)
                {
                    //Entity entity = (Entity)context.PreEntityImages["PreImage"];
                    try
                    {
    
                        if (postImageEntity.Attributes.Contains("customerid"))
                        {
                            //Some code. For example updates incident entity description
                            postImageEntity["description"] = "Test";
                        }
    
                        service.Update(postImageEntity);
                    }
                    catch (FaultException ex)
                    {
                        throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
                    }
                }

    Thursday, May 29, 2014 11:49 AM