Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics 365 | Integration, Dataverse...
Suggested answer

Rest API code to retrieve OptionSet metadata in C#

(0) ShareShare
ReportReport
Posted on by Microsoft Employee

Hello,

iam using below code to get optionset metadata details but now i want to get same details using REST API in c# can you please suggest code how to retrieve details ?

 RetrieveAttributeRequest retrieveAttributeRequest = new
RetrieveAttributeRequest
{
EntityLogicalName = entityName,
LogicalName = attributeName,
RetrieveAsIfPublished = true
};
// Execute the request.
RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
// Access the retrieved attribute.
Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata)
retrieveAttributeResponse.AttributeMetadata;// Get the current options list for the retrieved attribute.
OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
int selectedOptionValue = 0;
foreach (OptionMetadata oMD in optionList)
{
if (oMD.Label.LocalizedLabels[0].Label.ToString().ToLower() == selectedLabel.ToLower())
{
selectedOptionValue = oMD.Value.Value;
break;
}
}
return selectedOptionValue;





  • Suggested answer
    cloflyMao Profile Picture
    cloflyMao 25,202 on at
    RE: Rest API code to retrieve OptionSet metadata in C#

    Hi Rugved,

    Which type of authentication did you use? Was it "username and password" or "client id and client credential"?

    If it was the second one, please check whether you have assigned security role to the application user.

    You could refer to my code for iteration.

    public static void RetrieveForms(string authToken, String apiUrl)
    {
        // apiUrl: https://xxxxxx.crm5.dynamics.com/api/data/v9.1/
        HttpClient httpClient = null;
        httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
        httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
    
        httpClient.BaseAddress = new Uri(apiUrl);
        var response = httpClient.GetAsync("EntityDefinitions(LogicalName='contact')/Attributes(LogicalName='new_locations_of_interest')/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)").Result;
    
        if (response.IsSuccessStatusCode)
        {
            var formsResponse = JObject.Parse(response.Content.ReadAsStringAsync().Result);
            dynamic collections = JsonConvert.DeserializeObject(formsResponse.ToString());
            foreach (var data in collections.OptionSet.Options)
            {
                Console.WriteLine(data.Label.UserLocalizedLabel.Label);
            }
            Console.WriteLine("Ok");
        }
        
        else
        {
            Console.WriteLine(response);
        }
    }
     

    pastedimage1601022274449v1.png

    Regards,

    Clofly

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,959 Super User 2024 Season 1 on at
    RE: Rest API code to retrieve OptionSet metadata in C#

    Hi,

    Make sure you are using correct API.

    EntityDefinitions(LogicalName='account')/Attributes(LogicalName='statuscode')/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)

    Based on your field schema name you would need to change your API URL. See below logic.

    if (name1 == "'statecode'")

                       ServiceUrl = apiUrl + "/EntityDefinitions(LogicalName=" + name + ")/Attributes(LogicalName=" + name1 + ")/Microsoft.Dynamics.CRM.StateAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)";

                   else if (name1 == "'statuscode'")

                       ServiceUrl = apiUrl + "/EntityDefinitions(LogicalName=" + name + ")/Attributes(LogicalName=" + name1 + ")/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)";

                   else

                       ServiceUrl = apiUrl + "/EntityDefinitions(LogicalName=" + name + ")/Attributes(LogicalName=" + name1 + ")/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)";

    This code will work only for Local Optionset but not for Global Optionset.

    For Global Optionset you should look at below link,.

    If the attribute used a global optionset, the GlobalOptionSet property would contain the defined options and the OptionSet property would be null.

    Please mark my answer verified if i were helpful

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Rest API code to retrieve OptionSet metadata in C#

    iam getting error at below place where optionset value is getting null. can you help.

    pastedimage1600962744355v1.jpeg

  • Bipin D365 Profile Picture
    Bipin D365 28,959 Super User 2024 Season 1 on at
    RE: Rest API code to retrieve OptionSet metadata in C#

    Hi,

    Use below code to parse the result.

    Dictionary<string, string> result5 = new Dictionary<string, string>();

    responseBody = await createResponse1.Content.ReadAsStringAsync();

                   if (responseBody != "")  //204  

                   {

                       JObject jsonData = JObject.Parse(responseBody);

                       List<string> postTitles = (from p in jsonData["OptionSet"]["Options"] select (string)p["Value"]).ToList();

                       List<string> result2 = (from s1 in jsonData["OptionSet"]["Options"].Children()["Label"]["UserLocalizedLabel"] select (string)s1["Label"]).ToList();

                       for (int i = 0; i < postTitles.Count(); i++)

                       {

                           result5.Add(string.Format("value:" + postTitles[i]), string.Format("Label:" + result2[i]));

                       }

                   }

    createResponse1 is httpresponsemessage object.

    Please mark my answer verified if i were helpful

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Rest API code to retrieve OptionSet metadata in C#

    Iam getting optionset values in httpresponsemessage can you pls help how to read statuscode values from there ?

    using below iam getting response in json format and i want read values in c#

    xxxx.api.crm6.dynamics.com/.../

    Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=GlobalOptionSet($select=Options)

  • Suggested answer
    a33ik Profile Picture
    a33ik 84,325 Most Valuable Professional on at
    RE: Rest API code to retrieve OptionSet metadata in C#

    Code is on you. But as a started you can use following - docs.microsoft.com/.../web-api-samples-csharp

    Good luck.

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Rest API code to retrieve OptionSet metadata in C#

    Thanks for the reply . I have seen that but how to read values from response any sample code  ?

  • Suggested answer
    a33ik Profile Picture
    a33ik 84,325 Most Valuable Professional on at
    RE: Rest API code to retrieve OptionSet metadata in C#

    Hello,

    You can start from this post - docs.microsoft.com/.../retrieve-metadata-name-metadataid

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Congratulations 2024 Spotlight Honorees

Kudos to all of our 2024 community stars! 🎉

Meet the Top 10 leaders for December

Congratulations to our December super stars! 🥳

Start Your Super User Journey

Join the ranks of our community heros! 🦹

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,735 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,466 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans