Dynamics 365 (Dynamics CRM) Web API Record Retrieval Part.Ⅴ
Cheers everyone!
This is Harada, who is suffering from summer fatigue and has been eating a lot of Pino Chocolate Assortment.
Almonds are my favorite! (*`・へ・´*) smug
Well, this time I would like to write about paging when retrieving records and executing FetchXML and paging, as requested.
Dynamics 365 Record Retrieval Paging
When retrieving records with the Web API without paging, there is a limit of up to 5,000 records. While it depends on the number of fields to retrieve and the specifications of the processing side, retrieving 5,000 records at once can take a long time for processing on the client side, which can cause performance issues.
This is where paging comes in. Paging means retrieving 5,000 pieces of data five times, each time retrieving 1,000 pieces of data.
Do you have a general understanding of paging? Whether you understood it or not, please check out the sample below (lol)
var s = '$select=casetypecode,checkemail,_customerid_value,description,';
s += 'exchangerate,followupby,influencescore,numberofchildincidents,';
s += '_owninguser_value,statecode,statuscode,ticketnumber,title,versionnumber';
// execution
execute(encodeURI(apiUrl + '?' + s));function execute(requestUrl) {
var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl, true);
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.setRequestHeader('OData-MaxVersion', '4.0');
xhr.setRequestHeader('OData-Version', '4.0');
// Specifies the number of records per page
xhr.setRequestHeader('Prefer', 'odata.include-annotations="*",odata.maxpagesize=10');
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
console.log(this.response);
var data = JSON.parse(this.response);
// Recursion if there are more records
if (data["@odata.nextLink"])
execute(data["@odata.nextLink"]);
} Else {
var error = JSON.parse(this.response).error;
Xrm.Utility.alertDialog(error.message, function () { });
}
}
};
xhr.send();
}
So, what's different from the previous version? Let me explain briefly.
- Line 1 to Line 4
- We are creating a URL to retrieve the record. This is the same as before.
- Second row
- This calls the function defined below this line.
- Second row
- This specifies the number of records to retrieve at one time. Here, we specify that 1 records will be returned per request.
- Line 23, Line 24
- To check if there are any more records, you can request them again using the URL in the returned data "@odata.nextLink".
It's surprisingly easy, don't you think? However, it's unfortunate that it doesn't seem like it's easy to specify the page number and retrieve it.
Execute FetchXML to get Dynamics 365 records
Next, let's run FetchXML, which we briefly touched on previously. Since it's FetchXML, I thought I'd try aggregation, but paging seemed more difficult, so here's an example of paging with FetchXML. Take a look!
var apiUrl = "https://<ORG>.crm7.dynamics.com/api/data/v8.2/incidents";
var page = 1; // Specify the page
var count = 10; // Specifies the number of records per page
// Defines child elements of the fetch element
var xml = ' ';
xml += ' ';
xml += ' ';
xml += ' ';
xml += ' ';
xml += ' ';
xml += ' ';
xml += ' ';
// execution
executeFetchXml(apiUrl, xml, page, count);function executeFetchXml(apiUrl, fetch, page, count, pagingCookie) {
// Create fetchXml
var fetchXml = 'fetchXml=
fetchXml += ' page="' + page + '"';
fetchXml += ' count="' + count + '"';
if (pagingCookie) {
fetchXml += " " + escape(pagingCookie);
}
fetchXml += '>' + fetch + ' ';
var xhr = new XMLHttpRequest();
xhr.open("GET", encodeURI(apiUrl + "?" + fetchXml), true);
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.setRequestHeader('OData-MaxVersion', '4.0');
xhr.setRequestHeader('OData-Version', '4.0');
// Specifies annotations for paging.
xhr.setRequestHeader('Prefer', 'odata.include-annotations="*"');
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
console.log(this.response);
var data = JSON.parse(this.response);
// Recursion if there are more records
var cookies = data["@Microsoft.Dynamics.CRM.fetchxmlpagingcookie"];
if (cookies) {
page++;
pagingCookie = getPagingCookie(cookies);
executeFetchXml(apiUrl, fetch, page, count, pagingCookie);
}
} Else {
var error = JSON.parse(this.response).error;
Xrm.Utility.alertDialog(error.message, function () { });
}
}
};
xhr.send();
}
function getPagingCookie(pagingCookies) {
var div = document.createElement('div');
div.innerHTML = pagingCookies;
var pageNumber = div.firstChild.attributes.pagenumber.value;
var pagingcookie = div.firstChild.attributes.pagingcookie.value;
pagingcookie = unescape(unescape(pagingcookie));
pagingcookie = pagingcookie.replace(/ /g,'>');
pagingcookie = pagingcookie.replace(/"/g,''').replace(/'/g,'&'+'quot;');
return "paging-cookie='" + pagingcookie + "'";
}
It was quite tricky... To do paging... This can get a little complicated, as you need to change elements.
- Second row
- This is a Web API URL, so no explanation is needed.
- Second row
- Specifies the page number to retrieve.
- Second row
- Specifies the number of records to retrieve.
- Line 5 to Line 12
- FetchXML The following is specified:
- Line 18 to Line 24
- Paging is set for the element.
- Second row
- An annotation is required to retrieve the "@Microsoft.Dynamics.CRM.fetchxmlpagingcookie" used for paging. (I did a little research, but I couldn't find any annotation other than "*" that retrieves it by itself.)
- Line 41 to Line 43
- Whether there are further records is determined by checking whether the returned data "@Microsoft.Dynamics.CRM.fetchxmlpagingcookie" is present, and the page number and cookie are reset to make the recursive call.
- Second row
- "getPagingCookie" retrieves the value of the pagingcookie attribute from the string obtained by "@Microsoft.Dynamics.CRM.fetchxmlpagingcookie". The following string is set in "@Microsoft.Dynamics.CRM.fetchxmlpagingcookie".
<cookie pagenumber="2" pagingcookie="%253ccookie%2520page%253d%25223%2522%253e%253cincidentid%2520last%253d%2522%257bE384A5B4-498A-E711-8118-C4346BC53068%257d%2522%2520first%253d%2522%257bD184A5B4-498A-E711-8118-C4346BC53068%257d%2522%2520%252f%253e%253c%252fcookie%253e" istracking="False" />
Paging with FetchXML looks like this. What do you think? Is it helpful? I'm tired (lol)
This was the first time I implemented paging with FetchXML. I thought I could just increment the pagenumber value in the cookie returned by "@Microsoft.Dynamics.CRM.fetchxmlpagingcookie", but it didn't return the correct value, so I struggled (lol).
The great thing about Dynamics 365 is that there are some things you won't know until you try implementing it.
Next time... I haven't thought about it at all lol I'll try to find something useful to post m(_ _)m
*The content of this article is for personal reference only. Please use the content of this article at your own discretion.
Related articles and pages
Person who wrote this article
Articles in the same category
-
CRM Usage Guide for NPOs and Nonprofit Organizations — Members, Donors, etc. […] -
CRM Usage Guide for Advertising Agencies — Centralizing Clients and Projects […] -
A CRM Usage Guide for Travel Agencies — Using travel history and preferences to make the next proposal […] -
How to interpret the breakdown of CRM initial costs — How to avoid mistakes in quotes […] -
Differences between CRM 4.0 and personalization -
How to utilize customer data in the AI era — "Quality over quantity" is more important than ever before […]
