Wednesday, 13 March 2013

Retrieve OptionSet Label value in MS Dynamics CRM 2011

A method I used to retrieve the label, i.e. text of an option set (I would say more but I honestly can't remember what on Earth we use it for, if we still do use it).

string GetOptionSetLabel(IOrganizationService service, string entityName, string attributeName, int attributeValue)
{
  string result = string.Empty;

  try
  {
      RetrieveAttributeRequest request = new RetrieveAttributeRequest()
      {
        EntityLogicalName = entityName,
        LogicalName = attributeName,
        RetrieveAsIfPublished = true
      };

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

      if (resp.AttributeMetadata.AttributeType != null && resp.AttributeMetadata.AttributeType == AttributeTypeCode.Picklist)
      {

        result = (from x in ((OptionSetMetadata)((PicklistAttributeMetadata)resp.AttributeMetadata).OptionSet).Options
                  where x.Value == attributeValue
                  select x.Label.UserLocalizedLabel.Label).FirstOrDefault();
      }
      else
      {
          result = "Attribute is not picklist";
      }
  }
  catch (Exception ex)
  {
      result = string.Format("Exception of type {0} occurred: {1}", ex.GetType(), ex.Message);
  }

  return result;
}

No comments:

Post a Comment