Wednesday, March 23, 2011

Generate enum for option set / Picklist

While exposing CRM metadata to other applications, for consistency purposes its important to have optionset values represented as enums. CrmSvcUtil does not do this by default for all the Option Sets. However SDK provides extensibility points where we can inject our own code that drives the behaviour of CrmSvcUtil. There’s a good article by Erik which covers this possibility.

However, going that path very soon you will face an issue where you will see enum values not following C# naming rules like should start with letter, should not contain special characters. I have a written a method below which takes care of this requirement and generates valid enums.

public bool GenerateOption(OptionMetadata optionMetadata, IServiceProvider services)
        {
 
            string label = optionMetadata.Label.UserLocalizedLabel.Label;
            //remove spaces and special characters
            label = Regex.Replace(label, @"[^a-zA-Z0-9]", string.Empty);
            if (label.Length > 0 && !char.IsLetter(label, 0))
            {
                label = "Number_" + label;
            }
            else if (label.Length == 0)
            {
                label = "empty";
            }
 
            optionMetadata.Label = new Label(label, 1033);
 
            return _defaultService.GenerateOption(optionMetadata, services);
        }
 
        public bool GenerateOptionSet(OptionSetMetadataBase optionSetMetadata, IServiceProvider services)
        {
            return true;
        }




Technorati Tags: ,,