Retrieve records using FetchXML & C# SDK in CRM

Task: Write a Console Application to Retrieve the following attributes from Contact record, where Full Name = Arun Potti & Status = Active, using FetchXML.

Retrieve Multiple - FetchXML SDK

Solution: Follow the below Steps,

Step 1: Include the below References in your project, you can get the same from Latest SDK.
Goto the path, SDK->Bin for the dlls

Microsoft.Crm.Sdk.Proxy
Microsoft.Xrm.Sdk

Step 2: Include the below Framework Assemblies in your project,

Reference Manager - ConnectToCRM

Step 3: Add the below namespaces in your class file,

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Query;

Step 4: Download the fetchxml from CRM Advance Find,

<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
<entity name="contact">
<attribute name="fullname" />
<attribute name="contactid" />
<attribute name="parentcustomerid" />
<attribute name="gendercode" />
<attribute name="birthdate" />
<attribute name="creditlimit" />
<attribute name="donotsendmm" />
<order attribute="fullname" descending="false" />
<filter type="and">
<condition attribute="statecode" operator="eq" value="0" />
<condition attribute="fullname" operator="eq" value="Arun Potti" />
</filter>
</entity>
</fetch>

Step 5: Use FetchXML Formatter Tool, to format the fetchXML. For More Details about FetchXML Formatter Tool Click Here

Finally the Formatted FetchXML is as follows,

@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='contact'>
<attribute name='fullname' />
<attribute name='contactid' />
<attribute name='parentcustomerid' />
<attribute name='gendercode' />
<attribute name='birthdate' />
<attribute name='creditlimit' />
<attribute name='donotsendmm' />
<order attribute='fullname' descending='false' />
<filter type='and'>
<condition attribute='statecode' operator='eq' value='0' />
<condition attribute='fullname' operator='eq' value='Arun Potti' />
</filter>
</entity>
</fetch>"

Step 6: First we have to connect to CRM, for details Click Here 

Step 7: Below Method is useful for retrieving the values from FetchXML,

public static EntityCollection ExecuteFetch(string fetchXmlString)
{
return _service.RetrieveMultiple(new FetchExpression(fetchXmlString));
}

Step 8: Final code is here, 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Query;

namespace ConnectToCRM
{
class Program
{
static IOrganizationService _service;
static void Main(string[] args)
{
try
{
ConnectToMSCRM("arunpotti@XXXXXX.onmicrosoft.com", "XXXXXXX", "https://XXXXXX.api.crm5.dynamics.com/XRMServices/2011/Organization.svc");
Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;
if (userid == Guid.Empty) return;//Check for CRM Connection Establishment. If Not return, other wise will proceed to next step
string fetchXmlString = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='contact'>
<attribute name='fullname' />
<attribute name='contactid' />
<attribute name='parentcustomerid' />
<attribute name='gendercode' />
<attribute name='birthdate' />
<attribute name='creditlimit' />
<attribute name='donotsendmm' />
<order attribute='fullname' descending='false' />
<filter type='and'>
<condition attribute='statecode' operator='eq' value='0' />
<condition attribute='fullname' operator='eq' value='Arun Potti' />
</filter>
</entity>
</fetch>";

EntityCollection ec = ExecuteFetch(fetchXmlString);
if (ec.Entities.Count > 0)
{
string output = string.Empty;
foreach (var item in ec.Entities)
{
//String
if (item.Attributes.Contains("fullname")) //Check for fullname value exists or not in Entity Collection
output += "Full Name : " + item.Attributes["fullname"] + "\n";

//Lookup
if (item.Attributes.Contains("parentcustomerid")) //Check for parentcustomerid exists or not in Entity Collection
output += "Company : " + ((EntityReference)item.Attributes["parentcustomerid"]).Name + "\n";

//OptionSet
if (item.Attributes.Contains("gendercode")) //Check for gendercode exists or not in Entity Collection
output += "Gender : Name - " + item.FormattedValues["gendercode"] + ", Value - " + ((OptionSetValue)item.Attributes["gendercode"]).Value + "\n";

//Date
if (item.Attributes.Contains("birthdate")) //Check for birthdate exists or not in Entity Collection
output += "Birthday : " + ((DateTime)item.Attributes["birthdate"]).ToLocalTime().ToShortDateString().ToString() + "\n";

//Currency
if (item.Attributes.Contains("creditlimit")) //Check for creditlimit exists or not in Entity Collection
output += "Credit Limit : " + ((Money)item.Attributes["creditlimit"]).Value + "\n";

//Two Options
if (item.Attributes.Contains("donotsendmm")) //Check for donotsendmm exists or not in Entity Collection
output += "Send Marketing Materials : Name - " + item.FormattedValues["donotsendmm"] + ", Value - " + ((Boolean)item.Attributes["donotsendmm"]).ToString();
}

Console.WriteLine(output);
Console.ReadKey();
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public static EntityCollection ExecuteFetch(string fetchXmlString)
{
return _service.RetrieveMultiple(new FetchExpression(fetchXmlString));
}

public static void ConnectToMSCRM(string UserName, string Password, string SoapOrgServiceUri)
{
try
{
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = UserName;
credentials.UserName.Password = Password;
Uri serviceUri = new Uri(SoapOrgServiceUri);
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
proxy.EnableProxyTypes();
_service = (IOrganizationService)proxy;
}
catch (Exception ex)
{
Console.WriteLine("Error while connecting to CRM " + ex.Message);
Console.ReadKey();
}
}
}
}

Step 9: Build the project and Click on Start, you can see the below output,

Retrieve Multiple - FetchXML SDK Output

Provide your valuable feedback.

7 thoughts on “Retrieve records using FetchXML & C# SDK in CRM

  1. I’ve been bгoѡsing online more than 2 hours today, yet I
    never found any interesting article like yours.
    It is prettʏ worth enoᥙgh for me. Ꮲersonally, if all
    site owneгs and bloggers made good content as you did, the net will be a lot
    more useful tһan ever before.

  2. I’ᴠe been surfing online more than 3 hours nowɑdays, yet I by no means
    discovered any interesting artiϲle like yourѕ. It is beautiful price
    sufficient for mе. Pеrsonalⅼy, if all website owners and Ƅloggers made exceⅼlent content material as yοu
    did, the net will be a lot more helpfuⅼ than ever
    before.

  3. That is really attention-grabbіng, You are an excessively skilled blogger.
    I’ve joined your rss feed аnd stay up for searсhing for more
    of your magnificent post. Also, I’ve shared yߋur site in my social networks

Leave a Reply