How can recognize a custom field programmatically?

343 Views Asked by At

In Microsoft Dynamics 365, I need to find custom fields in an entity, I want to get custom fields of an entity with odata(rest api) or with SDK for dynamic purpose. Is there any way to find out as programmatically method?

1

There are 1 best solutions below

2
Alex On BEST ANSWER

You can easily enumerate the customization prefixes of all publishers in your instance by querying the publisher table, you want the column named customizationprefix.

Once you have retrieved all the prefixes, you can filter the result of a RetrieveEntityRequest to extract all the columns where the name starts with "<customizationprefix>_".

Prefixes like adx, cc and msdyn come from add-ons (Portal, Marketing, Field Service etc.), you might want to cherry pick the list of prefixes depending on your specific needs.

Sample code:

var client = new CrmServiceClient( /* ... */ );
const string ENTITY_TO_CHECK = "account";   // logical name

var prefixesQuery = new QueryExpression("publisher") { 
  ColumnSet = new ColumnSet("customizationprefix")
};
var prefixesData = client.RetrieveMultiple(prefixesQuery).Entities
  ?.Select(e => e.GetAttributeValue<string>("customizationprefix"));

Console.WriteLine("Publisher prefixes:");
foreach (var pd in prefixesData)
  Console.WriteLine("> {0}", pd);

var columnsQuery = new RetrieveEntityRequest
{
  LogicalName = ENTITY_TO_CHECK,
  EntityFilters = EntityFilters.Attributes,
  RetrieveAsIfPublished = true
};

var columnsData = (client.Execute(columnsQuery) as RetrieveEntityResponse)?.EntityMetadata?.Attributes
  ?.Where(col => prefixesData.Any(prefix => col.LogicalName.StartsWith($"{prefix}_")))
  .OrderBy(col => col.LogicalName);

Console.WriteLine("{0} custom fields: {1}", ENTITY_TO_CHECK, columnsData.Count());
foreach (var cd in columnsData.Take(1))
  Console.WriteLine("> {0}", cd.LogicalName);

Console.ReadLine();