Sample code to retrieve more than 5000 records using FetchXML in CRM


Sharing a sample code to retrieve more than 5000 records using the Fetch XML.

Version 1 :

<p>private List&lt;Entity&gt; GetTotalRecordsfromFetch(string fetchXML, IOrganizationService orgService)<br />
{<br />
List&lt;Entity&gt; lstEntity = new List&lt;Entity&gt;();</p>
<p>int fetchCount = 5000;<br />
int pageNumber = 1;<br />
string pagingCookie = null;</p>
<p>while (true)<br />
{<br />
// Build fetchXml string with the placeholders.<br />
string xml = this.CreateXml(fetchXML, pagingCookie, pageNumber, fetchCount);<br />
RetrieveMultipleRequest fetchRequest = new RetrieveMultipleRequest<br />
{<br />
Query = new FetchExpression(xml)<br />
<p>var returnCollections = ((RetrieveMultipleResponse)orgService.Execute(fetchRequest)).EntityCollection;</p>
<p>if (returnCollections.Entities.Count &gt;= 1)<br />
{<br />
lstEntity.AddRange(returnCollections.Entities);<br />
<p>if (returnCollections.MoreRecords)<br />
{<br />
<p>results.pagingCookie = returnCollections.PagingCookie;<br />
}<br />
else<br />
{<br />
// If no more records in the result nodes, exit the loop.<br />
break;<br />
}<br />
<p>return lstEntity;<br />
<p>public string CreateXml(string xml, string cookie, int page, int count)<br />
{<br />
StringReader stringReader = new StringReader(xml);<br />
XmlTextReader reader = new XmlTextReader(stringReader);</p>
<p>XmlDocument doc = new XmlDocument();<br />
<p>XmlAttributeCollection attrs = doc.DocumentElement.Attributes;</p>
<p>if (cookie != null)<br />
{<br />
XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie");<br />
pagingAttr.Value = cookie;<br />
attrs.Append(pagingAttr);<br />
<p>XmlAttribute pageAttr = doc.CreateAttribute("page");<br />
pageAttr.Value = System.Convert.ToString(page);<br />
<p>XmlAttribute countAttr = doc.CreateAttribute("count");<br />
countAttr.Value = System.Convert.ToString(count);<br />
<p>StringBuilder sb = new StringBuilder(1024);<br />
StringWriter stringWriter = new StringWriter(sb);</p>
<p>XmlTextWriter writer = new XmlTextWriter(stringWriter);<br />
doc.WriteTo(writer);<br />
<p>return sb.ToString();<br />

Version 2 :

<p>private static List&lt;Entity&gt; GetTotalRecordsFetchXML(OrganizationServiceProxy orgProxy, string fetchXML)<br />
{<br />
XDocument xDocument = XDocument.Parse(fetchXML);<br />
var fetchXmlEntity = xDocument.Root.Element("entity").ToString();</p>
<p>EntityCollection entityColl = new EntityCollection();<br />
List&lt;Entity&gt; lstEntity = new List&lt;Entity&gt;();<br />
int page = 1;<br />
do<br />
<p>entityColl = orgProxy.RetrieveMultiple(new FetchExpression(<br />
string.Format("&lt;fetch version='1.0' page='{1}' paging-cookie='{0}'&gt;" + fetchXmlEntity + "&lt;/fetch&gt;",<br />
SecurityElement.Escape(entityColl.PagingCookie), page++)));</p>
<p>lstEntity.AddRange(entityColl.Entities);<br />
}<br />
while (entityColl.MoreRecords);</p>
<p>return lstEntity;<br />

Hope it helps..


Missing RemoveListMembersListRequest in CRM.

In one of our recent implementations, we were working with Marketing List which could be in millions.

So we had the recent request wherein we split the marketing list into groups.

For adding members to a marketing list we have the following request


which is quite efficient as we can add multiple members in a single request.

However, when it comes to removing a member from marketing, we do not have a corresponding Remove request like RemoveListMembersListRequest.

We only have RemoveMemberListRequest, which only removes 1 member at a time, which is highly inefficient when we are taking in consideration large number of records.

Kindly vote up for this idea !!

More details

System.Security.SecurityException: That assembly does not allow partially trusted callers while using HttpUtility.UrlEncode in CRM


We got the below error in one of our Sandboxed Plugins

“System.Security.SecurityException: That assembly does not allow partially trusted callers”.

We realised it was because of using System.Web.HttpUtility class

We replaced it with EscapeDataString method and this fixed the issue.


Helpful thread

Hope it helps..

Using ILMerge for Plugin in CRM

If we make use of external assembly in our Plugin (sandboxed) we will get the exception of FileNotFound.

So here we can make use of ILMerge which basically merges the assembly referenced and the plugin into a single assembly.

Install the following NuGet Package.

This adds the following files in our Plugin project.

We need to set Copy Local as true for all our referenced assembly that we want to merge with our plugin.

We need to set Copy Local as false for all other assemblies that we do not want to be merged with plugin.

Just build the project and we are done.

The assembly inside Reflector: –

Hope it helps.


Using WebClient to call external service from CRM Online Sandboxed Plugin (HTTP POST and JSON)

Sharing a sample code that can be used to send JSON data using POST to an external service inside CRM Online Plugin. As plugin runs in sandbox mode we cannot reference Newtonsoft’s JSON.NET library The other option could be to use ILMerge, which isn’t that elegant.

Here, basically we are passing some information related to lead to an external service on Post Create of it.

<p>using Microsoft.Xrm.Sdk;<br />
using System;<br />
using System.IO;<br />
using System.Net;<br />
using System.Runtime.Serialization.Json;<br />
using System.Text;</p>
<p>namespace MyTestPlugin<br />
<p> public class Lead<br />
 {<br />
 public string Topic { get; set; }<br />
 public string FullName { get; set; }<br />
 public string Email { get; set; }<br />
<p> public class MyPluginClass : IPlugin<br />
 {<br />
 public void Execute(IServiceProvider serviceProvider)<br />
 {<br />
 try<br />
 {<br />
 // Obtain the execution context from the service provider.<br />
 IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));</p>
<p> // The InputParameters collection contains all the data passed in the message request.<br />
 if (context.InputParameters.Contains("Target") &amp;&amp; context.InputParameters["Target"] is Entity)<br />
 {<br />
 // Obtain the target entity from the input parameters.<br />
 Entity entity = (Entity)context.InputParameters["Target"];</p>
<p> using (WebClient client = new WebClient())<br />
 {<br />
 var myLead = new Lead();<br />
 myLead.Topic = entity.Attributes["subject"].ToString();<br />
 myLead.FullName = entity.Attributes["fullname"].ToString();<br />
 myLead.Email = entity.Attributes["emailaddress1"].ToString();</p>
<p> DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Lead));<br />
 MemoryStream memoryStream = new MemoryStream();<br />
 serializer.WriteObject(memoryStream, myLead);<br />
 var jsonObject = Encoding.Default.GetString(memoryStream.ToArray());</p>
<p> var webClient = new WebClient();<br />
 webClient.Headers[HttpRequestHeader.ContentType] = "application/json";<br />
 var code = "key";<br />
 var serviceUrl = "" + code;</p>
<p> // upload the data using Post mehtod<br />
 string response = webClient.UploadString(serviceUrl, jsonObject);<br />
 }<br />
 }<br />
 }<br />
 catch (Exception ex)<br />
 {<br />
 throw new InvalidPluginExecutionException(ex.Message);<br />
 }<br />
 }<br />
 }<br />
}<br />

Hope it helps..


Add hyperlink (and button) in Form Notification in Dynamics 365 (CRM 2016 and earlier)

Recently we were working on a requirement wherein we wanted to add a hyperlink to the Notification that we were showing on the form.

For this we can use the following Jscript library

The JScript code:


Clicking on Details opens the page specified in the callback function.

The other option is to show hyperlink within a web resource and putting it inside the form.

Hope it helps..