Question

In MS CRM 4, using c#, I am trying to query all accounts where a field that's picklist, is equal to "No". I know that picklists contain both an id and a value for each item but I want to query just for the value.

Here's my code currently:

ConditionExpression serviceContractCondition = new ConditionExpression();
        serviceContractCondition.AttributeName = "kez_servicecontracttype"; 
        serviceContractCondition.Operator = ConditionOperator.Equal; 
        serviceContractCondition.Values = new string[] { "Everything" };

In the code above im testing it by seeing if it can find only the accounts whos service contract type is equal to Everything (i changed the conditionOperator to equal). Instead of working i get this exception

System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) at crm.CrmService.Execute(Request Request) in c:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\crmcustoms\3e2de0cf\f06ef1a\App_WebReferences.iwjjnsp-.0.cs:line 116 at crmCustoms.MetricFunctions.Retrieve_SC_Total() in e:\Projects\Kezber\crmCustoms\App_Code\MetricFunctions.cs:line 421

Server was unable to process request.

Was it helpful?

Solution

Picklist items have a display label and an internal (numeric) value. First, you need to find the value that corresponds to No. The MetadataService allows you to do that. First, instantiate that service:

var metaservice = new MetadataService();.
metaservice.Url = "http://localhost/mscrmservices/2007/metadataservice.asmx";

metadata.Credentials = "same as you use for the crm webservice";

Then, use this method to retrieve the value of the picklist label:

int getPicklistValueByName(string picklistName, string entityLogicalName, string logicalName, MetadataService metaService)
{     
   RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest();
   attributeRequest.EntityLogicalName = entityLogicalName;
   attributeRequest.LogicalName = kogicalName;

   var attributeResponse = (RetrieveAttributeResponse)metaService.Execute(attributeRequest);
   var picklist = (PicklistAttributeMetadata)attributeResponse.AttributeMetadata;

   return picklist.Options.Where(op => op.Label.UserLocLabel.Label == picklistName).Single().Value.Value;
}

A call could looke like this:

var value = getPicklistValueByName("kez_servicecontracttype", "key_entitytype", "No", metaService)

Now, use this value in your condition expression. The alternative is to hardcode the numerical value as a constant in your program - which is better depends on your scenario.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top