locked
Get Guid of a Entity in a Plugin RRS feed

  • Question

  • Hi. I ned get the guid of a entity, but the problem is that I know only one value of a second custom ID. This second ID is a attribute as anyother. I will need its GUID because i have to create a LookUp later.

     

    I have tried the next code, but the Guid return me its different to the GUID for these entity in CRM. Anybody know why?

     

            /// <summary>
            /// Obtiene el Guid de una entidad cuyo campo cbsjv_codigo coincide con el valor indicado.
            /// </summary>
            /// <param name="crmService">service </param>
            /// <param name="strEntidad">Entity name for to get the GUID</param>
            /// <param name="strAtributo">Attribute name for to check the value and to get the GUID in the entity</param>
            /// <param name="valor">value to match in the collection of entities strEntidad and the attribute strAtibute</param>
            /// <returns>Entity Guid </returns>
            public static Guid ObtenerGuidEntidad(ICrmService crmService, string strEntidad, string strAtributo, string valor)
            {
                try
                {
                    // Create the request object.
                    RetrieveMultipleRequest retrieveMultiple = new RetrieveMultipleRequest();
    
                    // Create the ConditionExpression.
                    ConditionExpression condition = new ConditionExpression();
                    condition.AttributeName = strAtributo; //atributo sobre el que se buscará el valor.
                    condition.Operator = ConditionOperator.Equal;
                    condition.Values = new string[] { valor };
    
                    FilterExpression filter = new FilterExpression();
                    filter.FilterOperator = LogicalOperator.And;
                    filter.Conditions.Add(condition);
    
                    QueryExpression query = new QueryExpression();
                    query.EntityName = strEntidad;
                    query.ColumnSet = new AllColumns();
                    query.Criteria = filter;
    
                    // Set the properties of the request object.
                    retrieveMultiple.Query = query;
                    retrieveMultiple.ReturnDynamicEntities = true;
    
                    // Execute the request.
                    RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)crmService.Execute(retrieveMultiple);
    
    
                    //Comprobamos que sólo haya una entidad revuelta.
                    if (retrieved.BusinessEntityCollection.BusinessEntities.Count > 0)
                    {
                        //Comprobamos que solo haya uno.
                        if (retrieved.BusinessEntityCollection.BusinessEntities.Count == 1)
                        {
                            foreach (object property in ((DynamicEntity)retrieved.BusinessEntityCollection.BusinessEntities[0]).Properties)
                            {
                                if (property is KeyProperty)
                                {
                                    Key k = ((KeyProperty)property).Value;
                                    return k.Value;
                                }
                            }
                        }
                        else
                        {
                            throw new Exception(string.Format("Se ha encontrado más de un registro para la entidad {0} cuyo atributo {1} coincida con el valor {2}", strEntidad, condition.AttributeName, valor));
                        }
                    }
                    else
                    {
                        throw new Exception(string.Format("No se ha encontrado ningun registro en la entidad {0} cuyo atributo {1} coincida con el valor {2}",strEntidad,condition.AttributeName,valor));
                    }
    
                    return new Guid();
                }
                catch (Exception exp)
                {
                    throw new NotImplementedException("ERROR en ObtenerGuidEntidad: " + exp.Message);
                }
            }

     

    Tuesday, April 6, 2010 8:03 AM

Answers

  • yes, the GUID name is ALWAYS entityname + id

    so use strEntidad + "id" to find the key name then

     

    Guid g = ((Key)(DynamicEntity)retrieved.BusinessEntityCollection.BusinessEntities[0])[strEntidad + "id"]).Value;


    My blog : http://mscrmtools.blogspot.com
    You will find:
    Bulk Delete LauncherView Layout replicator
    ISV.Config Manager Form Javascript Manager
    Assembly RecoveryAnd others (use tool tag on my blog)
    • Marked as answer by yerayvg Tuesday, April 6, 2010 10:23 AM
    Tuesday, April 6, 2010 9:49 AM
    Moderator

All replies

  • Your code seems well build...

    As you look for the KeyProperty, that should be the correct GUID...


    My blog : http://mscrmtools.blogspot.com
    You will find:
    Bulk Delete LauncherView Layout replicator
    ISV.Config Manager Form Javascript Manager
    Assembly RecoveryAnd others (use tool tag on my blog)
    Tuesday, April 6, 2010 8:25 AM
    Moderator
  • Tuesday, April 6, 2010 8:31 AM
  • But the problem its that guids arent same....I know it because I create other entity that register the GUIDs of this entities when I retrieve them for UI. Do you can probe these on your Organization of CRM please, and check it? If I dont miss, you will get diferents GUID...I dont understand why.

    Oter razon because I know this: Later i create a look up whit this guid, and I try create the entity but I recive a SOAP error:

     

    ......
    
    Lookup lookup = new Lookup("TargetEntity", my_Guid);
    LookupProperty lookupProp = new LookupProperty("attributeForLinkTheLookUp", lookup);
    newEntity.Properties.Add(lookupProp);
    
    Guid guidResultante = CrmService.Create(newEntity);

     

     

     

    ERROR to Create the entity (CrmService.Create) : 

      0x80040217

      Contact With Id = 6b771d45-3173-4825-afb3-a47504898bf3 Does Not Exist

      Platform

    ERROR - Server was unable to process request.

     

     

     

    The problem its that the real GUID is AEBF7BE5-9640-DF11-99B4-005056B822A2.

    • Edited by yerayvg Tuesday, April 6, 2010 8:50 AM modify example code.
    Tuesday, April 6, 2010 8:48 AM
  • I find the real problem. Contact Entity have two primarykey : contactid and address1_addressid. Then, when my foreach look for each property, find first the KeyProperty associate to address1_addressid, and return the these GUID... :S I have a problem, because I can´t hardcode this property name because its a general process in execute time....

     

    Any idea?

    Tuesday, April 6, 2010 9:44 AM
  • yes, the GUID name is ALWAYS entityname + id

    so use strEntidad + "id" to find the key name then

     

    Guid g = ((Key)(DynamicEntity)retrieved.BusinessEntityCollection.BusinessEntities[0])[strEntidad + "id"]).Value;


    My blog : http://mscrmtools.blogspot.com
    You will find:
    Bulk Delete LauncherView Layout replicator
    ISV.Config Manager Form Javascript Manager
    Assembly RecoveryAnd others (use tool tag on my blog)
    • Marked as answer by yerayvg Tuesday, April 6, 2010 10:23 AM
    Tuesday, April 6, 2010 9:49 AM
    Moderator
  • foreach (object property in ((DynamicEntity)retrieved.BusinessEntityCollection.BusinessEntities[0]).Properties)
                            {
                                if (property is KeyProperty)
                                {
                                    Key k = ((KeyProperty)property).Value;
                                    return k.Value;
                                }
                            }

    Above code will loop though all properties of current record. In which all related entities loopup values {type of KeyProperty} and Guid {type of KeyProperty} of current record are included.

    Your code will return first comming KeyProperty type value, which can be of any related entity or of current reocrd Guid.
    You need to fetch your property with property name, so that you clearly know which entity type you are reffering in lookup. Like

    return property["propertyname"].Value;


    http://www.allaboutdynamics.com
    Tuesday, April 6, 2010 9:51 AM