Wednesday 23 January 2013

Use metadata service in MS Dynamics CRM 2011 to list Entities' Display Names and logical names

I normally try to keep the entity's Display Name as close to the Logical Name as possible, but more often than not, even with the best of intentions, the names go out of sync. This can be a problem for many reasons, so I created a quick console app to write the Display Names and corresponding Logical Names to a file, for quick reference.

The code will only write to file the custom and customizable entities, ignoring system entities and intersect entities, those created by N:N relationships (oh, yes, behind the scenes it's similar to two 1:N relationships).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk;
using System.IO;

namespace XRM.Metadata
{
    public class Metadata
    {
      public List<EntityMetadata> RetrieveAllEntities(IOrganizationService service)
        {
            RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
            {
                EntityFilters = EntityFilters.Entity,
                RetrieveAsIfPublished = true
            };

            RetrieveAllEntitiesResponse resp = (RetrieveAllEntitiesResponse)service.Execute(request);

            return resp.EntityMetadata.OrderBy(x => x.LogicalName).ToList();          
        }

        public void WriteDetailsToFile(string fileName, List<EntityMetadata> entitiesMeta)
        {
            using (StreamWriter sw = new StreamWriter(fileName))
            {
                foreach (var entmeta in entitiesMeta)
                {
                    if (((bool)entmeta.IsCustomEntity || entmeta.IsCustomizable.Value) && !(bool)entmeta.IsIntersect)
                    {
                        if (entmeta.DisplayName.UserLocalizedLabel != null)
                        {
                            sw.WriteLine(string.Format("Display Name: {0} - Logical Name: {1}.", entmeta.DisplayName.UserLocalizedLabel.Label, entmeta.LogicalName));
                        }
                        else if (entmeta.Description.UserLocalizedLabel != null)
                        {
                            sw.WriteLine(string.Format("Display Name: {0} - Logical Name: {1} - Description: {2}", "Unknown", entmeta.LogicalName, entmeta.Description.UserLocalizedLabel.Label));

                        }

                        else
                        {
                            sw.WriteLine(string.Format("Display Name: {0} - Logical Name: {1} - Description: {2}", "Unknown", entmeta.LogicalName, "Unknown"));
                        }
                    }
                }
            }
        }
    }
}

No comments:

Post a Comment