4
votes

I'm trying to pull information from a CRM installation and so far this is fine for using the default fields. However I'm having difficulty retrieving custom fields, for example Contacts have a custom field called web_username.

My code at present is

        QueryExpression query = new QueryExpression();
        query.EntityName = "contact";
        ColumnSet cols = new ColumnSet();
        cols.Attributes = new string[] { "firstname", "lastname" };
        query.ColumnSet = cols;

        BusinessEntityCollection beReturned = tomService.RetrieveMultiple(query);
        foreach (contact _contact in beReturned.BusinessEntities)
        {
            DataRow dr = dt.NewRow();
            dr["firstname"] = _contact.firstname;
            dr["lastname"] = _contact.lastname;
            dt.Rows.Add(dr);
        }

How do I include custom fields in my query? I've tried searching around but with no luck yet but I could be searching incorrectly as I'm not used to CRM terms.

Cheers in advance!

2
you can refer this link for your solution. [stackoverflow.com/questions/43984397/…Piyush

2 Answers

6
votes

I've since been able to solve this. In case it is of use to anyone else this is what I did. The query is set up as before except I've added my custom field to the ColumnSet.

cols.Attributes = new string[] { "firstname", "lastname", "new_web_username" };

And then used RetrieveMultipleResponse and Request with ReturnDynamicEntities set to true

        RetrieveMultipleResponse retrived = new RetrieveMultipleResponse();

        RetrieveMultipleRequest retrive = new RetrieveMultipleRequest();
        retrive.Query = query;
        retrive.ReturnDynamicEntities = true;

        retrived = (RetrieveMultipleResponse)tomService.Execute(retrive);

Please still comment if there is a better way for me to do this.

EDIT Using the example in my original question if you cast to a contact

contact myContact = (contact)myService.Retrieve(EntityName.contact.ToString(), userID, cols);

You can then access properties of the object

                phone = myContact.telephone1;
            password = myContact.new_password;

If you update your CRM webreference custom fields you've added in CRM are available.

0
votes
    public List<Entity> GetEntitiesCollection(IOrganizationService service, string entityName, ColumnSet col)
  {
                        try
                        {
                            QueryExpression query = new QueryExpression
                            {
                                EntityName = entityName,
                                ColumnSet = col
                            };
                            var testResult = service.RetrieveMultiple(query);
                            var testResultSorted = testResult.Entities.OrderBy(x => x.LogicalName).ToList();

             foreach (Entity res in testResultSorted)
                        {
                            var keySorted = res.Attributes.OrderBy(x => x.Key).ToList();
                            DataRow dr = null;
                            dr = dt.NewRow();
                            foreach (var attribute in keySorted)
                            {
                                try
                                {
                                    if (attribute.Value.ToString() == "Microsoft.Xrm.Sdk.OptionSetValue")
                                    {
                                        var valueofattribute = GetoptionsetText(entityName, attribute.Key, ((Microsoft.Xrm.Sdk.OptionSetValue)attribute.Value).Value, _service);
dr[attribute.Key] = valueofattribute;


                                        }
                                        else if (attribute.Value.ToString() == "Microsoft.Xrm.Sdk.EntityReference")
                                        {
                                            dr[attribute.Key] = ((Microsoft.Xrm.Sdk.EntityReference)attribute.Value).Name;
                                        }
                                        else
                                        {
                                            dr[attribute.Key] = attribute.Value;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Response.Write("<br/>optionset Error is :" + ex.Message);
                                    }
                                }
                                dt.Rows.Add(dr);
                            }
                 return testResultSorted;
                 }
                        catch (Exception ex)
                        {
                            Response.Write("<br/> Error Message : " + ex.Message);
                            return null;
                        }
            }

//here i have mentioned one another function:

 var valueofattribute = GetoptionsetText(entityName, attribute.Key, ((Microsoft.Xrm.Sdk.OptionSetValue)attribute.Value).Value, _service);

//definition of this function is as below:

public static string GetoptionsetText(string entityName, string attributeName, int optionSetValue, IOrganizationService service)
    {
                 string AttributeName = attributeName;
        string EntityLogicalName = entityName;
        RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest
        {
            EntityFilters = EntityFilters.All,
            LogicalName = entityName
        };
        RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)service.Execute(retrieveDetails);
        Microsoft.Xrm.Sdk.Metadata.EntityMetadata metadata = retrieveEntityResponseObj.EntityMetadata;
        Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals(attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata;
        Microsoft.Xrm.Sdk.Metadata.OptionSetMetadata options = picklistMetadata.OptionSet;

        IList<OptionMetadata> OptionsList = (from o in options.Options
                                             where o.Value.Value == optionSetValue
                                             select o).ToList();
        string optionsetLabel = (OptionsList.First()).Label.UserLocalizedLabel.Label;
        return optionsetLabel;
    }