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 :

private List<Entity> GetTotalRecordsfromFetch(string fetchXML, IOrganizationService orgService)
List<Entity> lstEntity = new List<Entity>();

int fetchCount = 5000;
int pageNumber = 1;
string pagingCookie = null;

while (true)
// Build fetchXml string with the placeholders.
string xml = this.CreateXml(fetchXML, pagingCookie, pageNumber, fetchCount);
RetrieveMultipleRequest fetchRequest = new RetrieveMultipleRequest
Query = new FetchExpression(xml)

var returnCollections = ((RetrieveMultipleResponse)orgService.Execute(fetchRequest)).EntityCollection;

if (returnCollections.Entities.Count >= 1)

if (returnCollections.MoreRecords)

results.pagingCookie = returnCollections.PagingCookie;
// If no more records in the result nodes, exit the loop.

return lstEntity;

public string CreateXml(string xml, string cookie, int page, int count)
StringReader stringReader = new StringReader(xml);
XmlTextReader reader = new XmlTextReader(stringReader);

XmlDocument doc = new XmlDocument();

XmlAttributeCollection attrs = doc.DocumentElement.Attributes;

if (cookie != null)
XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie");
pagingAttr.Value = cookie;

XmlAttribute pageAttr = doc.CreateAttribute("page");
pageAttr.Value = System.Convert.ToString(page);

XmlAttribute countAttr = doc.CreateAttribute("count");
countAttr.Value = System.Convert.ToString(count);

StringBuilder sb = new StringBuilder(1024);
StringWriter stringWriter = new StringWriter(sb);

XmlTextWriter writer = new XmlTextWriter(stringWriter);

return sb.ToString();

Version 2 :

private static List<Entity> GetTotalRecordsFetchXML(OrganizationServiceProxy orgProxy, string fetchXML)
XDocument xDocument = XDocument.Parse(fetchXML);
var fetchXmlEntity = xDocument.Root.Element("entity").ToString();

EntityCollection entityColl = new EntityCollection();
List<Entity> lstEntity = new List<Entity>();
int page = 1;

entityColl = orgProxy.RetrieveMultiple(new FetchExpression(
string.Format("<fetch version='1.0' page='{1}' paging-cookie='{0}'>" + fetchXmlEntity + "</fetch>",
SecurityElement.Escape(entityColl.PagingCookie), page++)));

while (entityColl.MoreRecords);

return lstEntity;

Hope it helps..

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..

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..

Simple Bing Map HTML Web Resource to show Country location in Dynamics 365

Just sharing a HTML Web resource code to show Country location inside the map using name of the country.

Source Code: –

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<title>My Bing Map</title>
<script charset="UTF-8" type="text/javascript" src=""></script>
<script type="text/javascript">
var map = null;

// get the bing map key
var credentials = "AvYH87t36Tv3ybyYagU9HUZKjsrWO2Hcup3nu1fmNhpenHKO_xxxxx";

function GetMap() {

// countryName - name of the country from the CRM's form
var countryName = parent.Xrm.Page.getAttribute("new_name").getValue();

// calling virtual earth api
var geocodeRequest = "" + countryName + "&key=" + credentials + "&jsonp=GeocodeCallback";


function GeocodeCallback(result) {

if (result && result.resourceSets && result.resourceSets.length > 0 && result.resourceSets[0].resources && result.resourceSets[0].resources.length > 0) {

var coordinates = result.resourceSets[0].resources[0].point.coordinates;
var centerPoint = new Microsoft.Maps.Location(coordinates[0], coordinates[1]);

map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),
credentials: credentials,
center: centerPoint,
mapTypeId: Microsoft.Maps.MapTypeId.road,
zoom: 5

var pushpin = new Microsoft.Maps.Pushpin(map.getCenter());

function CallRestService(request) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request);
<body onload="GetMap();">
<div id='mapDiv' style="position: relative; width: 600px; height: 300px;"></div>

Check this helpful post as well

Hope it helps..

Deployment Manager – To create a new organization, the wizard must remove the current organization in Dynamics 365 message.

While creating a new organization using Deployment Manager we got the below message

It was because we had entered the Workgroup Product key which restricts it to only organization.

Changing the product key to the server one, allowed creating the new organizations.

Hope it helps..

Using Lookup, LookupSet and Multilookup function in SSRS (Dynamics 365)

Using the Lookup, LookupSet and Multilookup functions we can basically combine values from 2 different data set.

The definition of them are

Lookup/LookupSet/Multilookup(source_expression, destination_expression, result_expression, dataset)

source expression – the field from the source data set (for e.g. primary key)

destination expression – the field to be matched from the destination dataset (sort of foreign key)

result expression – the field whose value has to be returned from the destination dataset

dataset – destination dataset name.

For e.g. we have custom entity Team and Team Members (1 à n)

We have following two DataSet one for Team and one for Team Members.

  1. DSTeam

  1. DSPlayer

The sample report has the Tablix which is bound to DSTeam and has two columns one which is bound new_name field of DSTeam dataset and the second column which gets the player name from DSPlayer dataset.


Lookup function picks the “first matching value” from the second dataset DSPlayer.

To get all the matching we need to use the LookupSet function (along with Join)


To understand Multilookup, let us create one more entity Tournament that will have a text attribute which stores comma separated team name.

Let us create one more dataset DSTournament and bound it to a new table. Which have one column which lists the Tournament name and the other column that does the multilookup to DSPlayer to get the player name.

It brings the first matching value, by searching (doing lookup) on multiple value i.e. India and South Africa

Hope it helps..

Nice Videos on understanding “Package Deployer Tool” and “Configuration Migration Tool” in CRM.

While going through various videos on Microsoft Dynamics CRM, found these 2 nice videos on Package Deployer Tool and Configuration Tool.

Do check it out

Hope it helps..

The ‘distinct’ attribute is not declared error while trying to import solution in CRM 2016 (and earlier)


Got this error while trying to import a managed solution in CRM 2016 Online.

During analysis we figured out that it was pointing to one of the charts created for System User Entity. It seemed like chart’s xml was modified after export and then imported. The xml definition of the chart contained distinct keyword.

Removing the distinct keyword from the Chart definition and importing it back and then importing the managed solution with this updated chart got imported without any error.

Hope it helps..

IPluginExecutionContext Depth is 2 in Create Plugin during Import of records in CRM 2015 (and earlier)

We had one of our plugins on Create of Opportunity however during the import of the Opportunity record it was not working properly. We had the Depth check in our plugin code to check for infinite loop as the same plugin was being used for Update also.

After some debugging we realized that Depth value is 2 instead of 1 during import.

To test this, we created a sample plugin for create of Test entity record and then imported the Test entity records.

As expected the import failed and we got our custom exception in it.

Hope this helps..

Sample code to update Access Mode of System User in C# (CRM 2016 or earlier)

Recently had a requirement to set Access Mode of around 500 users to Administrative from Read – Write. We wrote an on demand workflow for that. However, running that workflow on those 500 records in a batch of 100 records was causing them to stuck in waiting stage and we had to then manually resume those workflow instance. So we ended up writing a Console Application for that.

   QueryExpression queryExpression = new QueryExpression();
            queryExpression.EntityName = "systemuser";
            queryExpression.ColumnSet = new ColumnSet();

            ConditionExpression conditionExpression1 = new ConditionExpression();
            conditionExpression1.AttributeName = "tk_businessarea";
            conditionExpression1.Operator = ConditionOperator.Equal;

            ConditionExpression conditionExpression2 = new ConditionExpression();
            conditionExpression2.AttributeName = "isdisabled";
            conditionExpression2.Operator = ConditionOperator.Equal;

            // access mode ==> 0 --> Read Write and 1 --> Adminstrative
            ConditionExpression conditionExpression3 = new ConditionExpression();
            conditionExpression3.AttributeName = "accessmode";
            conditionExpression3.Operator = ConditionOperator.Equal;

            queryExpression.Criteria.FilterOperator = LogicalOperator.And;

            EntityCollection entityColl = organizationProxy.RetrieveMultiple(queryExpression);
            foreach(var entity in entityColl.Entities)
                Entity userEntity = new Entity("systemuser");
                userEntity.Id = entity.Id;
                userEntity.Attributes["accessmode"] = new OptionSetValue(0);

Hope it helps !!

Generic SQL error in CRM 2015 Online (and earlier)

Recently we were getting the Generic SQL Error in one of our Plugin which was registered in Create of Opportunity Line.

The scenario was that on qualifying the lead, opportunity was getting created and we had Async Plugin on Create of Opportunity that will create an Opportunity Line and had Sync Plugin on Create of Opportunity Line that was updating the parent Opportunity. This issue was occurring randomly.

We observed the following, that if both the Plugin are registered as Sync or Async the issue doesn’t occur. It also doesn’t occur if we have Opportunity Plugin on Create as Sync and the one on Opp. Line as Async.

The other way of solving the issue was to introduce delay before updating the Parent Opportunity from the child opportunity line create Plugin.

Hope this helps..

SandboxFault.ThrowIfGuidEmpty: entityId in CRM 2015.


We had one of our Plugins registered in RetrieveMultiple of an entity. And one of the JavaScript was using FetchXML to retrieve that particular entity records. This JavaScript was throwing the following exception

Putting the Guid.Empty check for the OutputParameter EntityCollection fixed the issue.

Hope it helps..

“The content of the import file is not valid. You must select a text file” – Error on Solution Import in CRM 2015 (and earlier)


We got this issue while importing (managed) solution from dev to test organization. We had recently deleted one of our existing 1 – n relationship and had created a new n – n relationship between those entities. The issue was that the new relationship had exactly the same schema name as the old relationship which we deleted.

The solution was to delete the newly created n – n relationship in Dev and create a new one with different schema name. After this change we were able to import the solution successfully.

Hope it helps..

Sample code to close a quote as won using WinQuoteRequest in CRM 2016 (and earlier)

Just sharing a sample code to close quote as won through C#

WinQuoteRequest winQuoteRequest = new WinQuoteRequest();
Entity quoteClose = new Entity("quoteclose");
quoteClose.Attributes["quoteid"] = new EntityReference("quote", new Guid("015816C2-2F10-E611-8112-3863BB353ED0"));
quoteClose.Attributes["subject"] = "Quote Close" + DateTime.Now.ToString();
winQuoteRequest.QuoteClose = quoteClose;
winQuoteRequest.Status = new OptionSetValue(-1);

Hope it helps..

Using Rollup fields with Account Hierarchy in CRM 2015.

We recently had a requirement wherein we had one custom entity Financial Detail associated to Account as many to one relationship.

i.e. One account record can have multiple Financial Details records associated.

We had this field Total (currency) in Financial Detail entity of type currency.

The requirement was to have sum of Total of all related Financial Details records of the Account record plus of any Sub Accounts (child accounts up to n level).

It would have been painful if we had to implement the same using Plugin.

This we can achieve easily using Rollup Field in Account

Below is the definition of the Roll up field named Total Rollup

  • Set Hierarchy as Yes.
  • Select Financial Details as the related entity.
  • Filter based only Active records.
  • In Aggregation specify Sum of Total (currency field in Financial Details record).


Hope it helps.

Set PartyList field To in Email in CRM 2015 (and earlier)

Sample code to set the PartyList field for Email Activity.

function setContact() {

var partlistData = new Array();
partlistData[0] = new Object();

// guid of the record
partlistData[0].id = "8B2AD82B-30D6-E511-811F-3863BB356F90";

// name of the record
partlistData[0].name = "Hugh Grant";

// entity schema name
partlistData[0].entityType = "contact";


Hope it helps..

The selected translations file is either invalid or does not conform to the required translations file schema error while importing translations in CRM 2015 (and earlier)


While importing translations we got the below error

On opening the CrmTranslations.xml we saw the translations missing for that row.

On specifying the values for those fields and importing it back fixed the issue.

Hope it helps..

Plugin on update of Quote Detail in CRM 2015 firing on Quote Create Issue.


We were facing one issue recently on creating Quote, where in we were getting exception on our Plugin that was registered in Post Update of Quote Detail.

It was kind of surprise for us that why it was getting triggered.

We removed all our others plugin and workflow on Quote and Quote Line but still that plugin was getting triggered. So we thought of trying it out on Vanilla instance of CRM 2016. In case of CRM 2016 the plugin registered on Post Update of Quote Detail didn’t trigger.

We then tried it on Vanilla instance of CRM 2015 On Premise (no online available), and we saw the same case i.e. Plugin getting triggered.

We were getting the following detail on Context.ParentContext (in case where Plugin on Update of Post Quote Detail is asynchronous)

                     Message – Update

         Stage – 30

         EntityReference (Target) – Quote

For Synchronous the message will be Retrieve

Hope it helps..

Import Solution progress bar rolls back without any error in CRM 2015\CRM 2013 Online.


Occasionally while importing the solution to our UAT environment we have faced this issue where the solution hasn’t imported, didn’t give any error but has rolled back.

This issue seems to be occurring when we are facing Network Issues and Internet connection intermittently goes down.

Trying it again once the network is stable resolves this.

Hope it helps..

Unit Testing (Microsoft Fakes) RetrieveSharedPrincipalsAndAccessResponse in Plugin in CRM 2016 (and earlier)


While trying to write Fakes for RetrieveSharedPrincipalsAndAccessResponse we’d realize that PrincipalAccess is read only property and the class itself is sealed.

So to unit test it we need to write a wrapper class as suggested here

The wrapper class

/// <summary>
/// Wrapper class for retrieve response
/// </summary>
[DataContract(Namespace = "")]
public class RetrieveSharedPrincipalsAndAccessResponseWrapper : OrganizationResponse
/// <summary>
/// The _entity
/// </summary>
private PrincipalAccess[] _principalaccess;

/// <summary>
/// Initializes a new instance of the <see cref="RetrieveResponseWrapper"/> class.
/// </summary>
/// <param name="response">The response.</param>
public RetrieveSharedPrincipalsAndAccessResponseWrapper(OrganizationResponse response)
this.PrincipalAccesses = ((RetrieveSharedPrincipalsAndAccessResponseWrapper)response).PrincipalAccesses;
this.PrincipalAccesses = ((RetrieveSharedPrincipalsAndAccessResponse)response).PrincipalAccesses;

/// <summary>
/// Gets or sets the PrincipalAccesses.
/// </summary>
/// <value>
/// The entity.
/// </value>
public PrincipalAccess[] PrincipalAccesses
return _principalaccess;

_principalaccess = value;

The unit test

 organizationService.ExecuteOrganizationRequest = request =>
 RetrieveSharedPrincipalsAndAccessResponseWrapper retrieveResponseWrapper = new RetrieveSharedPrincipalsAndAccessResponseWrapper(new RetrieveSharedPrincipalsAndAccessResponse());
 PrincipalAccess[] principalAccess = new PrincipalAccess[1]; 
 PrincipalAccess pAccess = new PrincipalAccess();
 pAccess.AccessMask = AccessRights.CreateAccess;
 pAccess.Principal = new EntityReference("team", new Guid("9A69533A-2306-4DFC-9662-65ABFAB41348"));
 principalAccess[0] = pAccess;
 retrieveResponseWrapper.PrincipalAccesses = principalAccess; 
 return retrieveResponseWrapper;


Change in the Plugin code using Wrapper instead of original class

 IOrganizationService orgService = serviceFactory.CreateOrganizationService(context.UserId);

 var accessRequest = new RetrieveSharedPrincipalsAndAccessRequest
 Target = new EntityReference("projectsite", new Guid("CDF30DD5-C64E-4EF5-ABA6-C9715C10A07D"))

 RetrieveSharedPrincipalsAndAccessResponseWrapper accessResponse = (new RetrieveSharedPrincipalsAndAccessResponseWrapper(orgService.Execute(accessRequest)));

Hope it helps

The type or namespace name ‘RSASignaturePadding’ does not exist in the namespace ‘System.Security.Cryptography’ (are you missing an assembly reference?) in Unit Test Project.

Was getting the below error while trying to build a unit test project (framework version 4.5.2) in VS 2012.

Delete the .messages file as suggested in some forums, but that didn’t help.

Just tried building the project by changing the Target Framework to 4.6.

That worked and after that on switching back the target version to 4.5.2 also worked.

Helpful post

Hope it helps..

Xrm.Utility.openEntityForm with Regarding field in CRM 2015.


We recently had a requirement to open new Task form on click of a ribbon button with Regarding field prefilled.

And as mentioned in the SDK, we can’t set the values for regarding lookups.

The workaround is to create custom parameters, set its value in JavaScript and use these values on the onLoad of the Form.

Hope it helps..

Administration Mode Enabled. Only system administrators and system customizers can sign in at this time in CRM 2015 Online.


After we copied our Dev instance to another Sandbox instance we got this message on opening CRM.

To disable it.

Go to Office 365 Administration Section

Select your sandbox instance.

Select Admin

Uncheck Enable Administration Mode

Hope it helps.

DateTime fields in CRM 2015


We recently had a requirement wherein we were working with DateTime fields in a Plugin. It was related to Time Zone.

These articles were of extreme help.

Sample Code to use LocalTimeFromUtcTimeRequest

var currentUserSettings = organizationProxy.RetrieveMultiple(
new QueryExpression("usersettings")
ColumnSet = new ColumnSet("timezonecode"),
Criteria = new FilterExpression
Conditions =
new ConditionExpression("systemuserid", ConditionOperator.EqualUserId)

var timeZoneCode = currentUserSettings.Attributes["timezonecode"].ToString();

DateTime time1 = DateTime.UtcNow;

LocalTimeFromUtcTimeRequest convert = new LocalTimeFromUtcTimeRequest();
convert.UtcTime = time1.ToUniversalTime();
convert.TimeZoneCode = Convert.ToInt32(timeZoneCode);
LocalTimeFromUtcTimeResponse response = (LocalTimeFromUtcTimeResponse)organizationProxy.Execute(convert);


The interesting part was that our plugin was running under the context of System account, so to get the logged in user from UI, we added an additional field and populated the value of time zone in it on on load using current logged in user’s information, and used the same field in plugin.

Hope it helps..

Plugin on Retrieve Multiple in CRM 2015.

Recently we had a requirement to filter sub grid on one of the forms. We thought of using Plugin on Retrieve Multiple for this.

Here we were showing Opportunity Sub Grid on Account form.

So we created a view for Opportunity that will be used as Sub Grid. Used it as Related Record Sub Grid so that we can have the GUID of the Account record being passed to the plugin.

The problem we faced à Sorting and Paging stopped working for the Sub Grid.

void IPlugin.Execute(IServiceProvider serviceProvider)
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)

// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Query") && context.InputParameters["Query"] is QueryExpression && context.MessageName == "RetrieveMultiple")
QueryExpression qe = (QueryExpression)context.InputParameters["Query"];
if (qe.EntityName == "opportunity")
string currentCustomerId = string.Empty;
ConditionExpression[] filters = qe.Criteria.Conditions.ToArray();
foreach (var filter in filters)
currentCustomerId = filter.Values[0].ToString();

FetchXmlToQueryExpressionRequest req = new FetchXmlToQueryExpressionRequest();
req.FetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
"<entity name='opportunity'>" +
" <attribute name='name' />" +
"<attribute name='customerid' />" +
"<attribute name='estimatedvalue' />" +
"<attribute name='statuscode' />" +
"<attribute name='opportunityid' />" +
"<order attribute='name' descending='false' />" +
"<link-entity name='account' from='accountid' to='parentaccountid' alias='ad'>" +
" <filter type='and'>" +
" <filter type='or'>" +
" <condition attribute='accountid' operator='eq' uiname='aaass' uitype='account' value=' " + currentCustomerId + "' />" +
" <condition attribute='accountid' operator='under' uiname='aaass' uitype='account' value='" + currentCustomerId + "' />" +
"</filter>" +
"</filter>" +
"</link-entity>" +
"</entity>" +
FetchXmlToQueryExpressionResponse resp = (FetchXmlToQueryExpressionResponse)service.Execute(req);
context.InputParameters["Query"] = resp.Query;


Hope it helps..

The records were not updated because the following Microsoft Dynamics CRM fields were not found during Import in CRM 2015.

Was getting the below error while trying to import few records

The reason being there were two field in the entity having same Display Name. Renaming one of the fields fixed the issue and import ran successfully.

Hope it helps ..

Add Find Columns to Lookup View in CRM.


Recently we had a requirement to search based on a particular attribute within the lookup view. The initial thought was to add a Find Columns to the lookup view. But then realized we do not have option of adding Find Columns to the lookup view.

The next thought was if I add that particular field to the list of Find Columns in Quick Find view will it work in Lookup View also? And it worked, basically adding any fields in the Find Column will make it Searchable.

The search works properly in the Lookup View as well as Lookup Inline View.

Hope it helps..

Sample Fetch XML Report using Multivalued Parameter (in Operator) in CRM


Sharing a sample report which shows the usage of Multi Value parameter in filter.

Replace the Condition generated in the Fetch xml query using Advanced Find

As following

Create another DataSet to provide value for @gendercodevalue parameter.

Set @gendercodevalue parameter as following ( internal – if we do not want user to select or specify value for it in report)


Hope it helps..