Tuesday, March 6, 2018

MSCRM JavaScript Call Third Party WebApi Using Ajax Request

Source Code:


function CallWebApi(reqType, url, workflowInput, successCallBack, errorCallBack, executionMode) {
        $.ajax({
            type: reqType,
            url: url,
            dataType: "json",
            data: JSON.stringify(workflowInput),
            contentType: "application/json; charset=utf-8",
            async: executionMode,
            cache: false,
            xhrFields:
            {
                withCredentials: true
            },
            crossDomain: true,
            success: function (data) {
                successCallBack(data);
            },
            error: function (error) {
                errorCallBack(error);
            }
        });
}
   

MSCRM JavaScript Create Record Using Xrm.WebApi Request

Source Code:


function createRecordUsingXrm() {
       var recordData =
             {
                    "new_name": "TestXrmWebApiRecord",
                   "new_projecttype": true,
                   "new_percentagecompleted": 100,
                   "new_projectdescription": "Test",
                   "new_budget": 1500.50,
                   "new_noofresources": 30,
                    "new_existingproducts": 1000000,
                    "new_projectduration": 12,
                    "new_account@odata.bind": "/accounts(2123455D-BE62-E411-80D6-B4B52F567EC8)"
         }

         parent.Xrm.WebApi.createRecord("new_myproject", recordData).then(
          function success(result) {
              Xrm.Utility.alertDialog("Record Created Successfully");
          },
          function (error) {
              console.log(error.message);
          });
}

MSCRM JavaScript Change Record Status Using WebAPI Request

Source Code:


function changeRecordStatus() {
          var serverURL = Xrm.Page.context.getClientUrl();
          var recordId = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "");
          var entityStatus = {};
          entityStatus.statuscode = 0;
          entityStatus.statecode = 1;
          var query = serverURL  + "/api/data/v8.2/contacts(recordId)";

          var req = new XMLHttpRequest();
          req.open("PATCH", query, true);
          req.setRequestHeader("Accept", "application/json");
          req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
          req.setRequestHeader("OData-MaxVersion", "4.0");
          req.setRequestHeader("OData-Version", "4.0");
          req.onreadystatechange = function() {
          if (this.readyState == 4) {
              req.onreadystatechange = null;
              if (this.status == 204 || this.status == 200) {
                    Xrm.Utility.alertDialog("Record status changed successfully!");
              } 
              else {
                  var error = JSON.parse(this.response).error;
                  Xrm.Utility.alertDialog(error.message);
              }
          }
      };
      req.send(JSON.stringify(entityStatus));
}

Re-usuable function:


//requestType = Type of Request("POST","GET","PATCH","DELETE").
//query = Your CRM Url + "/api/data/v8.2" + EntitySetName(ex: accounts).
//entityData = If you want to create/update record then send entityData else send null.
//successCallBack = this function will return the response data.
//errorCallBack = this function will return the error data.
//executionMode = asyncronous pass true for synchronous pass false.
function webApiRequest(requestType, query, entityData, successCallback, errorCallback, executionMode) {
        var req = new XMLHttpRequest();
        req.open(requestType, query, executionMode);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 204 || this.status === 200) {
                    var successData;
                    if (this.response != "") {
                        successData = JSON.parse(this.response);
                    }
                    else {
                        var projectUri = this.getResponseHeader("OData-EntityId");
                        successData = projectUri.substr(projectUri.length - 38).substring(1, 37);
                    }
                    successCallback(successData);
                } else {
                    errorCallback(this.statusText);
                }
            }
        };
        if (entityData != null && entityData != undefined && entityData != "")
            req.send(JSON.stringify(entityData));
        else
            req.send();
    };

Detail Information:

1) req.open("Request Type" , Request URL , executionMode(Sync, Async))

    Request Type: 

                     1) POST (To Create Record)
                     2) GET (To Retrieve/Retrieve Multiple Record(s))
                     3)PATCH (To update/status change of a record)
                     4)DELETE (To Delete Record)

    Request URL:

                     1) "Xrm.Page.context.getClientUrl()" is to get the current CRM Url
                     2) "/api/data/v8.2/accounts" ( In this "api/data/v8.2" is common for all webapi                              requests") v8.2 is the api version if you are using 2016 crm version then                                version will be 8.0/8.2  for D365 we will use v9.0
                     3)  "accounts" is an EntitySet name. Suppose if you want to find account                                     entityset name just frame URL like "Your CRM URL"/api/data/v8.2 and hit                               enter then you can find list of entities in your crm. Press control + F and                                 enter "account"(entityname) there you will find entitySet Name as below

     ExecutionMode:

                       1) Synchronous (false)
                       2) Asynchronous (true)

     Note: Must use Schema names for attribute data mapping.
               ex: new_name (Logical Name)
                     Name (Display Name)
                     new_Name (Schema Name) => This type should be used to create entityObj

MSCRM JavaScript Delete Record Using WebAPI Request

Source Code:


function deleteRecord() {
          var serverUrl = Xrm.Page.context.getClientUrl();
          var req = new XMLHttpRequest();
          req.open("DELETE", serverUrl  + "/api/data/v8.2/accounts(D7F0BEBA-EBDF-E711-A94E-000D3AF0396C)", false);
          req.setRequestHeader("Accept", "application/json");
          req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
          req.setRequestHeader("OData-MaxVersion", "4.0");
          req.setRequestHeader("OData-Version", "4.0");
          req.onreadystatechange = function() {
          if (this.readyState == 4) {
              req.onreadystatechange = null;
              if (this.status == 204 || this.status == 200) {
                    Xrm.Utility.alertDialog("Record deleted successfully!");
              } else {
                  var error = JSON.parse(this.response).error;
                  Xrm.Utility.alertDialog(error.message);
              }
          }
      };
      req.send();
}

Detail Information:

1) req.open("Request Type" , Request URL , executionMode(Sync, Async))

    Request Type: 

                     1) POST (To Create Record)
                     2) GET (To Retrieve/Retrieve Multiple Record(s))
                     3)PATCH (To update/status change of a record)
                     4)DELETE (To Delete Record)

    Request URL:

                     1) "Xrm.Page.context.getClientUrl()" is to get the current CRM Url
                     2) "/api/data/v8.2/accounts" ( In this "api/data/v8.2" is common for all webapi                              requests") v8.2 is the api version if you are using 2016 crm version then                                version will be 8.0/8.2  for D365 we will use v9.0
                     3)  "accounts" is an EntitySet name. Suppose if you want to find account                                     entityset name just frame URL like "Your CRM URL"/api/data/v8.2 and hit                               enter then you can find list of entities in your crm. Press control + F and                                 enter "account"(entityname) there you will find entitySet Name as below

     ExecutionMode:

                       1) Synchronous (false)
                       2) Asynchronous (true)

     Note: Must use Schema names for attribute data mapping.
               ex: new_name (Logical Name)
                     Name (Display Name)
                     new_Name (Schema Name) => This type should be used to create entityObj
              If you are using this code in html page use parent.Xrm.Page instead of Xrm.Page

MSCRM Javascript Retrieve Record Using WebAPI Request

Source Code:


function retrieveRecord() {
          var req = new XMLHttpRequest();
          req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts", true);
          req.setRequestHeader("Accept", "application/json");
          req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
          req.setRequestHeader("OData-MaxVersion", "4.0");
          req.setRequestHeader("OData-Version", "4.0");
          req.onreadystatechange = function() {
          if (this.readyState == 4) {
              req.onreadystatechange = null;
              if (this.status == 204 || this.status == 200) {
                    //do something
                    var records = JSON.parse(this.response);
                    Xrm.Utility.alertDialog(records.value.length + " Record(s) retrieved successfully!");
              }
              else {
                  var error = JSON.parse(this.response).error;
                  Xrm.Utility.alertDialog(error.message);
              }
          }
      };
      req.send();
}

Re-usuable function:


//requestType = Type of Request("POST","GET","PATCH","DELETE").
//query = Your CRM Url + "/api/data/v8.2" + EntitySetName(ex: accounts).
//entityData = If you want to create/update record then send entityData else send null.
//successCallBack = this function will return the response data.
//errorCallBack = this function will return the error data.
//executionMode = asyncronous pass true for synchronous pass false.
function webApiRequest(requestType, query, entityData, successCallback, errorCallback, executionMode) {
        var req = new XMLHttpRequest();
        req.open(requestType, query, executionMode);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 204 || this.status === 200) {
                    var successData;
                    if (this.response != "") {
                        successData = JSON.parse(this.response);
                    }
                    else {
                        var projectUri = this.getResponseHeader("OData-EntityId");
                        successData = projectUri.substr(projectUri.length - 38).substring(1, 37);
                    }
                    successCallback(successData);
                } else {
                    errorCallback(this.statusText);
                }
            }
        };
        if (entityData != null && entityData != undefined && entityData != "")
            req.send(JSON.stringify(entityData));
        else
            req.send();
    };

Detail Information:

1) req.open("Request Type" , Request URL , executionMode(Sync, Async))

    Request Type: 

                     1) POST (To Create Record)
                     2) GET (To Retrieve/Retrieve Multiple Record(s))
                     3)PATCH (To update/status change of a record)
                     4)DELETE (To Delete Record)

    Request URL:

                     1) "Xrm.Page.context.getClientUrl()" is to get the current CRM Url
                     2) "/api/data/v8.2/accounts" ( In this "api/data/v8.2" is common for all webapi                              requests") v8.2 is the api version if you are using 2016 crm version then                                version will be 8.0/8.2  for D365 we will use v9.0
                     3)  "accounts" is an EntitySet name. Suppose if you want to find account                                     entityset name just frame URL like "Your CRM URL"/api/data/v8.2 and hit                               enter then you can find list of entities in your crm. Press control + F and                                 enter "account"(entityname) there you will find entitySet Name as below

     ExecutionMode:

                       1) Synchronous (false)
                       2) Asynchronous (true)

     Note: Must use Schema names for attribute data mapping.
               ex: new_name (Logical Name)
                     Name (Display Name)
                     new_Name (Schema Name) => This type should be used to create entityObj

MSCRM JavaScript Update Record Using WebAPI Request

Snippet:

function UpdateRecord()
{
          var serverURL = Xrm.Page.context.getClientUrl();
          var project = {};
          project["new_name"] = "WebAPIUpdateProject";
          project["new_projectdescription"] = "Test Update WebApi project";
          project["new_account@odata.bind"] = "/accounts(2123455D-BE62-E411-80D6-B4B52F567EC8)";  //setting existing lookup
          project["new_existingproducts"] = 100000003;
          project["new_projecttype"] = true;
          project["new_noofresources"] = 29;
          project["new_projectduration"] = new Date();
          project["new_percentagecompleted"] = 85.16;
          project["new_budget"] = 9582.50;

          var req = new XMLHttpRequest();
          req.open("PATCH", serverURL + "/api/data/v8.2/new_myprojects(21084B81-B4E0-E711-A94E-000D3AF0396C)", true);
          req.setRequestHeader("Accept", "application/json");
          req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
          req.setRequestHeader("OData-MaxVersion", "4.0");
          req.setRequestHeader("OData-Version", "4.0");
          req.onreadystatechange = function() {
          if (this.readyState == 4) {
              req.onreadystatechange = null;
              if (this.status == 204 || this.status == 200) {
                    Xrm.Utility.alertDialog("Record updated successfully!");
              } 
              else {
                  var error = JSON.parse(this.response).error;
                  Xrm.Utility.alertDialog(error.message);
              }
          }
      };
      req.send(JSON.stringify(project));
}

Re-usuable function:


//requestType = Type of Request("POST","GET","PATCH","DELETE").
//query = Your CRM Url + "/api/data/v8.2" + EntitySetName(ex: accounts).
//entityData = If you want to create/update record then send entityData else send null.
//successCallBack = this function will return the response data.
//errorCallBack = this function will return the error data.
//executionMode = asyncronous pass true for synchronous pass false.
function webApiRequest(requestType, query, entityData, successCallback, errorCallback, executionMode) {
        var req = new XMLHttpRequest();
        req.open(requestType, query, executionMode);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 204 || this.status === 200) {
                    var successData;
                    if (this.response != "") {
                        successData = JSON.parse(this.response);
                    }
                    else {
                        var projectUri = this.getResponseHeader("OData-EntityId");
                        successData = projectUri.substr(projectUri.length - 38).substring(1, 37);
                    }
                    successCallback(successData);
                } else {
                    errorCallback(this.statusText);
                }
            }
        };
        if (entityData != null && entityData != undefined && entityData != "")
            req.send(JSON.stringify(entityData));
        else
            req.send();
    };

Detail Information:

1) req.open("Request Type" , Request URL , executionMode(Sync, Async))

    Request Type: 

                     1) POST (To Create Record)
                     2) GET (To Retrieve/Retrieve Multiple Record(s))
                     3)PATCH (To update/status change of a record)
                     4)DELETE (To Delete Record)

    Request URL:

                     1) "Xrm.Page.context.getClientUrl()" is to get the current CRM Url
                     2) "/api/data/v8.2/accounts" ( In this "api/data/v8.2" is common for all webapi                              requests") v8.2 is the api version if you are using 2016 crm version then                                version will be 8.0/8.2  for D365 we will use v9.0
                     3)  "accounts" is an EntitySet name. Suppose if you want to find account                                     entityset name just frame URL like "Your CRM URL"/api/data/v8.2 and hit                               enter then you can find list of entities in your crm. Press control + F and                                 enter "account"(entityname) there you will find entitySet Name as below

     ExecutionMode:

                       1) Synchronous (false)
                       2) Asynchronous (true)

     Note: Must use Schema names for attribute data mapping.
               ex: new_name (Logical Name)
                     Name (Display Name)
                     new_Name (Schema Name) => This type should be used to create entityObj

MSCRM JavaScript Create Record Using WebAPI Request

       Source Code:

           var entityObj = {};
           entityObj["name"] = "TestAccount";

           //Other Data Types FYI. Must Use Attribute Schema names.
          //entityObj["new_name"] = "WebAPIUpdateProject"; //Single Line of Text
          //entityObj["new_projectdescription"] = "Test Update WebApi project"; //Multiple Line of Text
          //entityObj["new_contact@odata.bind"] = "/contacts(2123455D-BE62-E411-80D6-B4B52F567EC8)";  //Lookup
          //entityObj["new_existingproducts"] = 100000003; // Whole Number
          //entityObj["new_projecttype"] = true; // Two Options
          //entityObj["new_noofresources"] = 29.32; //Floating Point Number
          //entityObj["new_projectduration"] = new Date();
          //entityObj["new_percentagecompleted"] = 85.161245; //Decimal Number

          //entityObj["new_budget"] = 9582.50; // Currency
          

          var req = new XMLHttpRequest();
          req.open("POST",  Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts", true);
          req.setRequestHeader("Accept", "application/json");
          req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
          req.setRequestHeader("OData-MaxVersion", "4.0");
          req.setRequestHeader("OData-Version", "4.0");
          req.onreadystatechange = function() {
          if (this.readyState == 4) {
              req.onreadystatechange = null;
              if (this.status == 204 || this.status == 200) {
                  var projectUri = this.getResponseHeader("OData-EntityId");
                  var ID = projectUri.substr(projectUri.length - 38).substring(1, 37); //newly created record 
                                guid.
                  Xrm.Utility.openEntityForm("account", ID); //Open newly created account record
                   Xrm.Utility.alertDialog("Record created successfully");
              } 
              else {
                  var error = JSON.parse(this.response).error;
                  Xrm.Utility.alertDialog(error.message);
              }
          }
      };
      req.send(JSON.stringify(entityObj));


Re-usuable function:



//requestType = Type of Request("POST","GET","PATCH","DELETE").
//query = Your CRM Url + "/api/data/v8.2" + EntitySetName(ex: accounts).
//entityData = If you want to create/update record then send entityData else send null.
//successCallBack = this function will return the response data.
//errorCallBack = this function will return the error data.
//executionMode = asyncronous pass true for synchronous pass false.
function webApiRequest(requestType, query, entityData, successCallback, errorCallback, executionMode) {
        var req = new XMLHttpRequest();
        req.open(requestType, query, executionMode);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 204 || this.status === 200) {
                    var successData;
                    if (this.response != "") {
                        successData = JSON.parse(this.response);
                    }
                    else {
                        var projectUri = this.getResponseHeader("OData-EntityId");
                        successData = projectUri.substr(projectUri.length - 38).substring(1, 37);
                    }
                    successCallback(successData);
                } else {
                    errorCallback(this.statusText);
                }
            }
        };
        if (entityData != null && entityData != undefined && entityData != "")
            req.send(JSON.stringify(entityData));
        else
            req.send();

    };


Detail Information:

1) req.open("Request Type" , Request URL , executionMode(Sync, Async))

    Request Type
                     1) POST (To Create Record)
                     2) GET (To Retrieve/Retrieve Multiple Record(s))
                     3)PATCH (To update/status change of a record)
                     4)DELETE (To Delete Record)

    Request URL:
                     1) "Xrm.Page.context.getClientUrl()" is to get the current CRM Url
                     2) "/api/data/v8.2/accounts" ( In this "api/data/v8.2" is common for all webapi requests")
                           v8.2 is the api version if you are using 2016 crm version then version will be 8.0/8.2
                           for D365 we will use v9.0
                     3)  "accounts" is an EntitySet name. Suppose if you want to find account entityset name
                           just frame URL like "Your CRM URL"/api/data/v8.2 and hit enter then you can find                             list of entities in your crm. Press control + F and enter "account"(entityname) there
                           you will find entitySet Name as below



     ExecutionMode:
                       1) Synchronous (false)
                       2) Asynchronous (true)

     Note: Must use Schema names for attribute data mapping.
               ex: new_name (Logical Name)
                     Name (Display Name)
                     new_Name (Schema Name) => This type should be used to create entityObj