2010-02-04

Get Picklist Value By Picklist Name

I wrote some method to get picklist value by knowing picklist name.

namespace test
{
    public class CrmServiceProvider
    {

  private WebMetadataService.MetadataService _MetaService = null;
  
  ///* Create a MetadataService end point */
        private WebMetadataService.MetadataService MetaService
        {
            get
            {
                if (_MetaService == null)
                {
                    _MetaService = new WebMetadataService.MetadataService();
                    _MetaService.Url = "http://localhost/mscrmservices/2007/metadataservice.asmx";

                    // Use a special user credentials
     NetworkCredential cred = new NetworkCredential();
                    cred.Domain = ConfigurationManager.AppSettings["Domain"];
                    cred.UserName = ConfigurationManager.AppSettings["UserName"];
                    cred.Password = ConfigurationManager.AppSettings["PassWord"];

                    _MetaService.UseDefaultCredentials = false;
                    _MetaService.Credentials = cred;

                    _MetaService.UnsafeAuthenticatedConnectionSharing = true;

                    WebMetadataService.CrmAuthenticationToken token = new WebMetadataService.CrmAuthenticationToken();
                    token.AuthenticationType = 0;
                    token.OrganizationName = ConfigurationManager.AppSettings["Organization"];

                    _MetaService.CrmAuthenticationTokenValue = token;
                }
                return _MetaService;
            }
        }


  public int GetPicklistValueByPicklistName(string PicklistName, string EntityLogicalName, string LogicalName)
  {
   int retval = -1;
   
   /* Retrieve the attribute metadata */
   WebMetadataService.RetrieveAttributeRequest attributeRequest = new WebMetadataService.RetrieveAttributeRequest();
   attributeRequest.EntityLogicalName = EntityLogicalName;
   attributeRequest.LogicalName = LogicalName; //picklist

   WebMetadataService.RetrieveAttributeResponse attributeResponse =
      (WebMetadataService.RetrieveAttributeResponse)MetaService.Execute(attributeRequest);

   /* Cast the attribute metadata to a picklist metadata */
   WebMetadataService.PicklistAttributeMetadata picklist =
      (WebMetadataService.PicklistAttributeMetadata)attributeResponse.AttributeMetadata;


   foreach (WebMetadataService.Option op in picklist.Options)
   {
    if (op.Label.UserLocLabel.Label == PicklistName)
     retval = op.Value.Value;
   }

   return retval;
  }
 }
}

To call this method use the next construction:
int psv = GetPicklistValueByPaymentSystemName(categorycode, "account", "accountcategorycode");
if (psv > 0)
{
 acc.accountcategorycode = new Picklist();
 acc.accountcategorycode.Value = psv;
}

Комментариев нет: