Wednesday 17 December 2008

Complex Queries in Crm 4

Hi All,

I am not normally a big fan of FetchXml. It is messy and since it is often passed in as a string, it can be prone to syntax errors. But over the years, people have been using Fiddler to extract the SOAP headers to the Crm server in order to catch the FetchXml query. There is nothing new here and it is quite handy if you accept the fact that data will also be returned in xml format, meaning it will have to be iterated to get the needed information. Which can really be a pain. I have spent time writing methods to parse the result xml into a dictionary that I can easily access. But even this can be painful at times.

So the other day I discovered a class called FetchXmlToQueryExpressionRequest. This class can be used to convert any fetchXml to a QueryBase object, that can be fed into a RetrieveMultipleRequest. The beauty of this lies in the fact that it is the best of both worlds. You can use advanced find to build complex queries without having to confuse yourself with linked entities etc AND you can then retrieve the data as a BusinessEntityCollection.

Here's some sample code:

string fetch = @"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='contact'>
<attribute name='mobilephone'/>
<attribute name='lastname'/>
<attribute name='firstname'/>
<attribute name='emailaddress1'/>
<attribute name='contactid'/>
<order attribute='lastname' descending='false'/>
</entity>
</fetch>";
";


FetchXmlToQueryExpressionRequest fetchReq = new FetchXmlToQueryExpressionRequest();

FetchReq.FetchXml = fetch;

FetchXmlToQueryExpressionResponse res = (FetchXmlToQueryExpressionResponse)service.Execute(fetchReq);

RetrieveMultipleRequest req = new RetrieveMultipleRequest();

req.Query = res.Query;

req.ReturnDynamicEntities = true;

RetrieveMultipleResponse recordSet = (RetrieveMultipleResponse)service.Execute(req);

Have a nice day
Paul Reyneke

No comments: