April 18, 2013

Retrieve Entity Logical Name from a record GUID

In the case we have only an anonymous record GUID and we want to know which entity belongs, we can do a "brute force" attack against the CRM using the metadata information.
// Retrieve Metadata for all entities
RetrieveAllEntitiesRequest allEntitiesRequest = new RetrieveAllEntitiesRequest();
allEntitiesRequest.EntityFilters = EntityFilters.Entity;
allEntitiesRequest.RetrieveAsIfPublished = true;
RetrieveAllEntitiesResponse allEntitiesResponse = (RetrieveAllEntitiesResponse)service.Execute(allEntitiesRequest);

// Record ID to check
Guid checkId = new Guid("541067bd-4db1-2208-e5b0-a601ead56d03");

string entityLogicalName = string.Empty;
foreach (EntityMetadata entityMetadata in allEntitiesResponse.EntityMetadata)
{
    try
    {
        // Try to retrieve the record from the current entity
        Entity test = service.Retrieve(entityMetadata.LogicalName, checkId, new ColumnSet(entityMetadata.PrimaryIdAttribute));
        // if the previous instruction didn't throw an exception means that the record exists.
        entityLogicalName = entityMetadata.LogicalName;
        break;
    }
    catch { }
}
if (entityLogicalName != string.Empty)
{
    string foundMessage = string.Format("Record with ID {0} belongs to entity {1}", checkId.ToString(), entityLogicalName);
    Console.WriteLine(foundMessage);
}
else
{
    string notFoundMessage = string.Format("Record with ID {0} not found in any entity", checkId.ToString());
    Console.WriteLine(notFoundMessage);
}

1 comment:

  1. Thanks for sharing! Very useful on extreme situations when there is no other option.

    ReplyDelete