Saturday 2 July 2011

CRM 2011 – Get Optionset labels in Silverlight 4 using SOAP endpoints

 

Recently, I need to fetch the optionset values of one of the custom entities named as ‘Candidate’. It has one a custom attribute like job type. The job type is having values like Permanent, Temporary, Part time, on contract. I developed a Silverlight 4  data grid control to show the all candidates with some search criteria. By design, using OData service reference you can’t fetch the metadata of CRM entity. So here only get the related values of the optionset like 1 for Permanent, 2 for Temporary and so on. So, if you would like to show the label you have to choose the SOAP endpoint service reference.

Now, to start with SOAP endpoint development I referred a very useful link of MSDN. I am sharing the same here,

http://msdn.microsoft.com/en-us/library/gg594452.aspx 

With the help of this link you can setup the required service reference and the utility classes to use messages or methods of CRM SDK.

Below is the code snippet which I have used to fetch the labels using SOAP endpoints in my candidates.xaml.cs file. You can use the same code by just passing the entity and attribute names. I hope this will be helpful. 

   1: /// <summary>
   2: /// Get options set labels for specified entity's optionset type attribute
   3: /// </summary>
   4: /// <param name="entityName"></param>
   5: /// <param name="attributeName"></param>
   6: private void GetOptionSetLabels(string entityName, string attributeName)
   7: {
   8:     OrganizationRequest request = new OrganizationRequest();
   9:     request.RequestName = "RetrieveAttribute";
  10:     request["EntityLogicalName"] = entityName;
  11:     request["LogicalName"] = attributeName;
  12:     request["MetadataId"] = Guid.Empty;
  13:     request["RetrieveAsIfPublished"] = true;
  14:  
  15:     IOrganizationService service = SilverlightUtility.GetSoapService();
  16:     service.BeginExecute(request, new AsyncCallback(OnGetOptionSetLabelsComplete), service);
  17: }
  18:  
  19:  
  20:  
  21: /// <summary>
  22: /// Retrieve the resutls
  23: /// </summary>
  24: /// <param name="result"></param>
  25: private void OnGetOptionSetLabelsComplete(IAsyncResult result)
  26: {
  27:     //Get the original query back from the result.
  28:     OrganizationResponse response = ((IOrganizationService)result.AsyncState).EndExecute(result);
  29:  
  30:     if (response != null && response.Results.Count > 0)
  31:     {
  32:  
  33:         //Get the actual optionset meta data
  34:         OptionSetMetadata optionSetMetadata = ((EnumAttributeMetadata)(response.Results[0].Value)).OptionSet; 
  35:  
  36:         //Set the metadata object in required field
  37:         Common.JobTypeOptionSetMetadata = optionSetMetadata;
  38:     }
  39: }