Create a bunch of CRM fields with code

Today I encountered the task I hate the most: brainless repetitive tasks in the CRM UI. I had to create 18 fields with the same names on 6 entities. It sounds like I screwed up in database normalization, but it actually makes perfectly good sense – the values of the fields are different on the various entities.

Anyway, I was left with two choices – create the 108 fields in the CRM UI (and suffer mouse injury to my right arm) or do it with code. It’s probably easy to guess what the nerd chose.

First I compiled the list of the 18 fields to be created. They are all of the same type so that makes it easy:

List<KeyValuePair<string, string>> liste = new List<KeyValuePair<string, string>>(); 

liste.Add(new KeyValuePair<string, string>("pa_fee1", "Fee 1")); 
liste.Add(new KeyValuePair<string, string>("pa_fee2", "Fee 2")); 
liste.Add(new KeyValuePair<string, string>("pa_feetotal", "Fee Total")); 

(…) 

That’s nice and easy. Now all I had to do was to loop the list and create the fields:

   foreach (var keyValuePair in liste) 
   { 
      var attrib = new DecimalAttributeMetadata 
      { 
         SchemaName = keyValuePair.Key, 
         LogicalName = keyValuePair.Key, 
         DisplayName = new Label(keyValuePair.Value, 1033), 
         RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), 
         IsAuditEnabled = new BooleanManagedProperty(true), 
         MaxValue = 1000000000, 
         MinValue = -1000000000, 
         Precision = 2, 
      }; 

      CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest 
      { 
         EntityName = pa_quoteobject.EntityLogicalName, 
         Attribute = attrib 
      }; 
      IOrganizationService service = GetOrgService(); // use a simplified connection (CrmConnection) or something to create an IOrganizationService
      service.Execute(createAttributeRequest); 
   } 

Hit F5 – go get a cup of hot chocolate – and my fields are all there. Now I just had to replace the entity name 5 times and drink another 5 cups of hot chocolate and I was done.

Summary
In this post I have shown how to create fields in a simple manner. They are all of the same type, and have the same properties (precision, min value, max value etc) but the code can be extended to suit your needs.