Joseph Michael Pesch
VP Programming

MS CRM Get Picklist Values from Web Service SDK

by 1. September 2010 21:21

This code will get picklist name/value pairs from MS CRM.  Passing the Entity and Attribute being searched.

public sealed class AuthenticationType

{

    // Fields

    public const int AD = 0;

    public const int Passport = 1;

    public const int Spla = 2;

}

 

public static CrmService GetCrmService()

{

    CrmSdk.CrmAuthenticationToken token = new CrmSdk.CrmAuthenticationToken();

    token.AuthenticationType = AuthenticationType.AD;

    token.OrganizationName = Crm.Organization;

 

    CrmService crmService = new CrmService();

    crmService.Url = "http://CRM:80/MSCRMServices/2007/CrmService.asmx";

    crmService.CrmAuthenticationTokenValue = token;

    crmService.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

 

    return crmService;

}

public static MetadataService GetMetadataService()

{

    CrmMeta.CrmAuthenticationToken token = new CrmMeta.CrmAuthenticationToken();

    token.AuthenticationType = AuthenticationType.AD;

    token.OrganizationName = Crm.Organization;

 

    MetadataService svc = new MetadataService();

    crmService.Url = "http://CRM:80/MSCRMServices/2007/MetadataService.asmx";

    svc.CrmAuthenticationTokenValue = token;

    svc.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

 

    return svc;

}

 

public class PickListOptions

{

    public PickListOptions() { }

    public string ItemLabel { get; set; }

    public string ItemValue { get; set; }

}

static public List<PickListOptions> GetPickList(string EntityName, string AttributeName)

{

    // Sample: EntityName = "new_debttransaction"; AttributeName = "new_stage"

    // Setup the request

    RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest();

    // Entity reference

    attributeRequest.EntityLogicalName = EntityName;

    // Picklist attribute inside of entity

    attributeRequest.LogicalName = AttributeName;

    attributeRequest.RetrieveAsIfPublished = true;

    // Post the request

    RetrieveAttributeResponse response = (RetrieveAttributeResponse)GetMetadataService().Execute(attributeRequest);

    PicklistAttributeMetadata picklist = (PicklistAttributeMetadata)response.AttributeMetadata;

    // Convert the results

    List<PickListOptions> lst = new List<PickListOptions>();

    foreach (Option o in picklist.Options)

    {

    lst.Add(new PickListOptions() { ItemLabel = o.Label.LocLabels[0].Label

           , ItemValue = o.Value.Value.ToString() });

    }

    return lst;

}

 

 Note: You may receive a server error when attempting to run the code if you CRM user account does not have the appropriate security settings shown below.  Click the “Customization” tab, and then set the “Read” permissions on “Entity”, “Attribute” and “Relationship” as shown below:

Tags:

[None]

Comments are closed