Monday, 2 June 2014

Create OptionSet in MS Dynamics CRM 2011/2013 programmatically

I was asked last week to create a new entity with a few drop down menus, our analyst is still not quite with the Dynamics CRM lingo :).

There was one for Title or Salutation, which contained just about every title you could possibly imagine, from military ranks to various religious positions to academia, you name it, it was there. Similarly, there was another one for ethnicity, which I pointed out customers are loath to divulge, but no matter we needed that as well with its myriad categories, all in all I was looking at upwards of 100 options in total across 5 option sets so I thought that this might be a good time to look up how to create a global option set programmatically.

At any rate, here's the code:


/// <summary>
/// Creates Global OptionSet against Solution.
/// </summary>
/// <param name="service"/>Crm Service</param>
/// <param name="filePath"/>Path to a file that contains the optionset labels, one per line</param>
/// <param name="optionSetName"/>Unique Name of OptionSet</param>
/// <param name="displayName"/>Display Name of OptionSet</param>
/// <param name="solution"/>Unique Name of Solution OptionSet will be created against</param>
/// <param name="initialValue"/>Solution's OptionSet number prefix</param>
private void CreateOptionSet(IOrganizationService service, string filePath, string optionSetName, string displayName, string solution, int initialValue)
{
    try
    {
        int languageCode = 1033;

        OptionMetadataCollection options = new OptionMetadataCollection();

        using (StreamReader reader = new StreamReader(filePath))
        {
            while (!reader.EndOfStream)
            {
                options.Add(new OptionMetadata(new Label(reader.ReadLine(), languageCode), initialValue));
                initialValue++;
            }
        }

        OptionSetMetadata optionSet = new OptionSetMetadata();
        optionSet.Name = optionSetName;
        optionSet.DisplayName = new Label(displayName, 1033);
        optionSet.IsGlobal = true;
        optionSet.OptionSetType = OptionSetType.Picklist;

        CreateOptionSetRequest request = new CreateOptionSetRequest();
        request.OptionSet = optionSet;
        request.SolutionUniqueName = solution;

        service.Execute(request);
       
        foreach (var item in options)
        {
            InsertOptionValueRequest insertRequest = new InsertOptionValueRequest();
            insertRequest.OptionSetName = optionSetName;
            insertRequest.Label = item.Label;
            insertRequest.Value = item.Value;

            service.Execute(insertRequest);

            Console.WriteLine("Added OptionSet Item {0} with Value {1}", item.Label, item.Value); 
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("An error occurred creating OptionSet {0}. Exception: {1}", optionSetName, ex);
    }
}

No comments:

Post a Comment