Quantcast
Channel: Sam's Activities
Viewing all articles
Browse latest Browse all 3363

Execute fetchxml using Web API in Dynamics CRM 2016

$
0
0

Introduction

Microsoft Dynamics CRM Online 2016 Update and Microsoft Dynamics CRM 2016 (on-premises) introduced new concept called The Web API. It can be used across a wide variety of programming languages, platforms, and devices. The Web API implements the OData (Open Data Protocol), version 4.0, an OASIS standard for building and consuming Restful APIs.

Basically Web API is advanced version of old OData. With the help of Web API you can perform following operation.

  • Create
  • Update
  • Delete
  • Retrieve
  • Retrieve multiple( using odata query and fetch)
  • Execute Web API functions
  • Execute Web API Actions
  • Execute Web API Query Functions

Walkthrough

As earlier version of Odata does not support to execute the fetchxml. To execute fetchxml you have to use SOAP. Now using Web API you can execute the fetchxml.

Below is example that used to execute the fetchxml.

First define your fetchxml and execute using Web API using following code.

If you want retrieve formatted value and data about lookup properties. You have add following line in request header.

Below is the entire code.

// This function is used to retrieve records using fetchxml
            fetch: function (originalFetch, entitySetName, retrieveUsingFetchSuccess, retrieveUsingFetchError) {

                var fetch = null;
                try {
                    //create the fetch
                    fetch = ["<fetch mapping='logical'>", originalFetch, "</fetch>"].join("");
                    //encode the fetchxml
                    fetch = escape(fetch);
                    //create AJAX request
                    $.ajax({
                        type: "GET",
                        contentType: "application/json; charset=utf-8",
                        datatype: "json",
                        //async: false,
                        url: this.getWebAPIPath() + entitySetName + "?fetchXml=" + fetch,
                        beforeSend: function (xhr) {
                            //Specifying this header ensures that the results will be returned as JSON.
                            xhr.setRequestHeader("Accept", "application/json");
                            xhr.setRequestHeader("Content-Type", "application/json; odata.metadata=minimal");
                            xhr.setRequestHeader("OData-MaxVersion", "4.0");
                            xhr.setRequestHeader("OData-Version", "4.0");
                            ////xhr.setRequestHeader("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
                            xhr.setRequestHeader("Prefer", "odata.include-annotations=*");
                        },
                        success: function (data, textStatus, xhr) {

                            if (data != null) {

                                var entityObj = [];                              
                                var pagingInfo = null;

                                //Check if results contains cookies 
                                //if yes then retrieve next set of records
                                if (data["@Microsoft.Dynamics.CRM.fetchxmlpagingcookie"] != null) {

                                    //get the pagingcookie
                                    pagingInfo = Inogic.ApiLib.getPagingCookie(data["@Microsoft.Dynamics.CRM.fetchxmlpagingcookie"]);
                                
                                    //call this function create json object
                                    Inogic.ApiLib.createJsonObject(data, entityObj);

                                    //call this to retrieve more records
                                    Inogic.ApiLib.fetchMore(originalFetch, entitySetName, retrieveUsingFetchSucess, retrieveUsingFetchError,pagingInfo.pageCokies,pagingInfo.pageNumber, entityObj);

                                }
                            }
                                //get the results and create json object
                            else {

                                var entityObj = [];

                                // This function is used to create the json object
                                Inogic.ApiLib.createJsonObject(data, entityObj);

                                //call successcallback
                                retrieveUsingFetchSuccess(entityObj);
                            }
                        },
                        error: function (xhr, textStatus, errorThrown) {
                            retrieveUsingFetchError(Inogic.ApiLib.errorHandler(xhr));
                        }
                    });
                } catch (e) {
                    throw new Error(e);
                }

            };

Web API return 5000 records at time, to retrieve more than 5000 records you have to use paging cookie. To identify more records you can use @Microsoft.Dynamics.CRM.fetchxmlpagingcookie. If query has more records then @Microsoft.Dynamics.CRM.fetchxmlpagingcookie contains value. The format of it given below

From above pagingcookie  you can extract the cookie part & pagenumber and add this to fetchxml  and pass this updated fetchxml to retrieve more records.

When you execute fetch it return data in json format.

To get the value of from result use following code.

1. String/Number etc

var name = data.value[0].name;

2. Lookup(Entity Reference)

id: data.value[0]._primarycontactid_value,

name: data.value[0]["_primarycontactid_value@OData.Community.Display.V1.FormattedValue"],

logicalname: data.value[0]["_primarycontactid_value@Microsoft.Dynamics.CRM.lookuplogicalname"],

3. Option set/Money/DataTime/Boolean

value: data.value[0].revenue

formattedValue :data.value[0]["revenue@OData.Community.Display.V1.FormattedValue"]

Since there were requests to include the code in the API, I have added the code of the functions used here. This is our implementation and not necessarily the only or the best way to have it developed. We have been using XrmServiceToolkit for a while and the code here is a similar implementation for WEB API.

 //This function is used to get paging cookies
            getPagingCookie: function (pageCokies) {
                var pagingInfo = {};
                var pageNumber = null;
 
                try {
                    //get the page cokies
                    pageCokies = unescape(unescape(pageCokies));
 
                    //get the pageNumber
                    pageNumber = parseInt(pageCokies.substring(pageCokies.indexOf("=") + 1, pageCokies.indexOf("pagingcookie")).replace(/\"/g, '').trim());
 
                    // this line is used to get the cookie part
                    pageCokies = pageCokies.substring(pageCokies.indexOf("pagingcookie"), (pageCokies.indexOf("/>") + 12));
                    pageCokies = pageCokies.substring(pageCokies.indexOf("=") + 1, pageCokies.length);
                    pageCokies = pageCokies.substring(1, pageCokies.length - 1);
 
                    //replace special character
                    pageCokies = pageCokies.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '\'').replace(/\'/g, '&' + 'quot;');
 
                    //append paging-cookie
                    pageCokies = "paging-cookie ='" + pageCokies + "'";
 
                    //set the parameter
                    pagingInfo.pageCokies = pageCokies;
                    pagingInfo.pageNumber = pageNumber;
 
                } catch (e) {
                    throw new Error(e);
                }
 
                return pagingInfo;
            },
 
            // This function is used to fetchmore records
            fetchMore: function (originalFetch, entitySetName, retrieveUsingFetchSucess, errorCallback, pageCookies, pageNumber, entityObj) {
 
                var fetch = null;
                try {
 
                    //add the pageCookies and pageNumber into FetchXML
                    var fetch = ["<fetch mapping='logical' page='" + pageNumber + "' " + pageCookies + ">", originalFetch, "</fetch>"].join("");
 
                    //encode the fetchxml
                    fetch = escape(fetch);
 
                    //Create AJAX request
                    $.ajax({
                        type: "GET",
                        contentType: "application/json; charset=utf-8",
                        datatype: "json",
                        //async: false,
                        url: this.getWebAPIPath() + entitySetName + "?fetchXml=" + fetch,
                        beforeSend: function (xhr) {
                            //Specifying this header ensures that the results will be returned as JSON.
                            xhr.setRequestHeader("Accept", "application/json");
                            xhr.setRequestHeader("Content-Type", "application/json; odata.metadata=minimal");
                            xhr.setRequestHeader("OData-MaxVersion", "4.0");
                            xhr.setRequestHeader("OData-Version", "4.0");
                            ////xhr.setRequestHeader("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
                            xhr.setRequestHeader("Prefer", "odata.include-annotations=*");
                        },
                        success: function (data, textStatus, xhr) {
 
                            if (data != null) {
 
                                var pagingInfo = null;
 
                                //Check if results contains cookies
                                //if yes then retrieve next set of records
                                if (data["@Microsoft.Dynamics.CRM.fetchxmlpagingcookie"] != null) {
 
                                    //get the pagingcookie
                                    pagingInfo = Inogic.ApiLib.getPagingCookie(data["@Microsoft.Dynamics.CRM.fetchxmlpagingcookie"]);
 
                                    //call this function create json object
                                    Inogic.ApiLib.createJsonObject(data, entityObj);
 
                                    //call this to retrieve more records
                                    Inogic.ApiLib.fetchMore(originalFetch, entitySetName, retrieveUsingFetchSucess, retrieveUsingFetchError, pagingInfo.pageCokies, pagingInfo.pageNumber, entityObj);
 
                                }
                                else {
 
                                    // This function is used to create the json object
                                    Inogic.ApiLib.createJsonObject(data, entityObj);
 
                                    retrieveUsingFetchSucess(entityObj);
                                }
                            }
                        },
                        error: function (xhr, textStatus, errorThrown) {
                            errorCallback(Inogic.ApiLib.errorHandler(xhr));
                        }
                    });
                } catch (e) {
                    throw new Error(e);
 
                }
            },

Conclusion

In this way, We can use Web API to execute fetchxml instead of SOAP.

Before you move on to the next post, check our Maplytics InfoCenter.

There's much more, for more Dynamics CRM Tips and Tricks head on to Inogic Blog. If you have any questions on Dynamics CRM or need any help in implementation, customization, upgradation of Dynamics CRM or are looking to get more out of your CRM, feel free to reach us at crm@inogic.com today!

The post Execute fetchxml using Web API in Dynamics CRM 2016 appeared first on Inogic Blog.


Viewing all articles
Browse latest Browse all 3363

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>