If you had a requirement where you want to retrieve a list of options of an option set in your CRM/365 organization depending on the language, for example if you pass to the method 1025 it will return the options in Arabic, if you pass 1033 it will return the options in English and so on.
public Dictionary<int, string> LocalOptionSetList(String entityName, String optionSetName, int lcid)
{
try
{
if (lcid == 0)
lcid = 1033;// default english
using (var xrmContext = new XrmServiceContext(CRMConnection.CRM))
{
RetrieveAttributeRequest raRequest = new RetrieveAttributeRequest
{
EntityLogicalName = entityName,
LogicalName = optionSetName,
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse raResponse = (RetrieveAttributeResponse)xrmContext.Execute(raRequest);
PicklistAttributeMetadata paMetadata = (PicklistAttributeMetadata)raResponse.AttributeMetadata;
OptionMetadata[] optionList = paMetadata.OptionSet.Options.ToArray();
Dictionary<int, string> dic = new Dictionary<int, string>();
foreach (OptionMetadata oMD in optionList)
{
dic.Add((int)oMD.Value, oMD.Label.LocalizedLabels.Where(x => x.LanguageCode == lcid).FirstOrDefault().Label.ToString());
}
return dic;
//StatusAttributeMetadata message if you want to retrieve options from a status reason field
}
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
For example, if you are integrating your Dynamics 365 with a portal, and you want to create a drop down list of these options coming from an option set in the 365, and this options maybe changed in the future, so its not practical to change the drop down list options.
In this case, I'm going to give you a code I was using to listing data from CRM 2016 to SharePoint 2016.
public Dictionary<int, string> LocalOptionSetList(String entityName, String optionSetName, int lcid)
{
try
{
if (lcid == 0)
lcid = 1033;// default english
using (var xrmContext = new XrmServiceContext(CRMConnection.CRM))
{
RetrieveAttributeRequest raRequest = new RetrieveAttributeRequest
{
EntityLogicalName = entityName,
LogicalName = optionSetName,
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse raResponse = (RetrieveAttributeResponse)xrmContext.Execute(raRequest);
PicklistAttributeMetadata paMetadata = (PicklistAttributeMetadata)raResponse.AttributeMetadata;
OptionMetadata[] optionList = paMetadata.OptionSet.Options.ToArray();
Dictionary<int, string> dic = new Dictionary<int, string>();
foreach (OptionMetadata oMD in optionList)
{
dic.Add((int)oMD.Value, oMD.Label.LocalizedLabels.Where(x => x.LanguageCode == lcid).FirstOrDefault().Label.ToString());
}
return dic;
//StatusAttributeMetadata message if you want to retrieve options from a status reason field
}
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
No comments:
Post a Comment