web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics 365 | Integration, Dataverse...
Suggested Answer

Rest API code to retrieve OptionSet metadata in C#

(0) ShareShare
ReportReport
Posted on by

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;





I have the same question (0)
  • Suggested answer
    a33ik Profile Picture
    84,331 Most Valuable Professional on at

    Hello,

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

  • Community Member Profile Picture
    on at

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

  • Suggested answer
    a33ik Profile Picture
    84,331 Most Valuable Professional on at

    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
    on at

    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)

  • Bipin D365 Profile Picture
    28,983 Moderator on at

    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
    on at

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

    pastedimage1600962744355v1.jpeg

  • Suggested answer
    Bipin D365 Profile Picture
    28,983 Moderator on at

    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

  • Suggested answer
    cloflyMao Profile Picture
    25,210 on at

    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

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Microsoft Dynamics 365 | Integration, Dataverse, and general topics

#1
Martin Dráb Profile Picture

Martin Dráb 62 Most Valuable Professional

#2
#ManoVerse Profile Picture

#ManoVerse 57

#3
Pallavi Phade Profile Picture

Pallavi Phade 49

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans