Friday, February 17, 2017

Web API Retrieve Single Record

Today I am showing how to select an entity record by passing Guid and get back desired fields.
I am running this code on 'Contact' entity and retrieving two fields. I have to remove starting and ending brackets as Web API is not accepting while processing Guids
I am using below javascript code in webresource. For application outside CRM in separate application, u have to first authenticate using Azure / AD depending upon deployment (Online / On-Premises). Refer to this link for this feature.


Code Start:


function MySelectUsingWebAPI() {



var id = Xrm.Page.data.entity.getId();



             id = id.replace("{", "");

            id = id.replace("}", "");









            var selectQuery = "contacts(" + id + ")?$select=sms_issync,statecode";

            var selectResult = WebAPISelect(selectQuery);



            var value = selectResult.statecode;

         

             return  {IsSync:selectResult.sms_issync,

                          State: value         }





}





function WebAPISelect(select) {

    var result = null;

    var serverUrl = Xrm.Page.context.getClientUrl();

    var oDataSelect = serverUrl + "/api/data/v8.1/" + select;

    console.log("oDataSelect ", oDataSelect);



    var retrieveReq = new XMLHttpRequest();

    retrieveReq.open("GET", oDataSelect, false);

    retrieveReq.setRequestHeader("Accept", "application/json");

    retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");

    retrieveReq.setRequestHeader("OData-MaxVersion", "4.0");

    retrieveReq.setRequestHeader("OData-Version", "4.0");

    retrieveReq.onreadystatechange = function () {

        //GetContractData(this);


        if (retrieveReq.readyState == 4) {

            if (retrieveReq.status == 200) {

                result = JSON.parse(this.responseText);



                //result = 1;



                // alert(ParentEntityId);

            }

            else { // not success

                //var error = JSON.parse(this.response).error;

                result = JSON.parse(this.responseText);

                console.log(result.message);

            }

        }

    };


    try {

        retrieveReq.send();

    }

    catch (error) {

        result = "Unable to send the request. " + error.message;

    }


    return result;



}


// Code End:

 
㉺㉼㉴㉳㉽㉾㈕㈔㈆㈅㈄㈄㈃㈁㈀㉤
Ali Hamza Wadood 
Microsoft Dynamics CRM Developer | Software Engineer - Microsoft Technologies(Asp.Net, Asp.Net MVC)
LinkedIn

Asp.Net MVC (5) - Exception Filter - HandleError

Applicable on Asp.Net MVC5 HandleError Filter This belongs to Exception Filters category (Authentication Filter, Authoriz...