Showing posts with label Web API. Show all posts
Showing posts with label Web API. Show all posts

Dynamics CRM 2016 Web API (OData V4.0)

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Microsoft introduces Web API (OData v4) with the release of Dynamics CRM 2016 to perform CRUD operations and also some other special operations. Following are some posts for CRUD operation...


Retrieve Record using Web API

Retrieve Multiple using Web API

Retrieve Multiple through fetch XML using Web API

Create Record using Web API

Update Record using Web API

Delete Record using Web API

Associate Record using Web API

Disassociate Record using Web API

Calling entity based Action using Web API

Calling Global Action using Web API

Disassociate Record using Web API

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Following is detail sample code to disassociate a record using Web API in Dynamics CRM.
/*
currentEntityPlurarName: currentEntityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
currentEntityId: guid of current entity record
otherEntityPlurarName: otherEntityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
otherEntityId: guid of other entity record       
*/
function disAssociateRequest(currentEntityPlurarName, currentEntityId, relationShipName, otherEntityPlurarName, otherEntityId) {
    var serverURL = Xrm.Page.context.getClientUrl();
    var query = currentEntityPlurarName + "(" + currentEntityId + ")/" + relationShipName + "/$ref?$id=" + serverURL + "/api/data/v8.2/" + otherEntityPlurarName + "(" + otherEntityId + ")";
    var req = new XMLHttpRequest();
    req.open("DELETE", serverURL + "/api/data/v8.2/" + 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 /* complete */) {
            req.onreadystatechange = null;
            if (this.status == 204) {
                //alert('Record Disassociated');
            } else {
                var error = JSON.parse(this.response).error;
                Xrm.Utility.alertDialog(error.message);
            }
        }
    };
    req.send();
}
You can call the disassociate record method as:
    var currentEntityName = "accounts";
    var currentEntityId = removeCurlyBraces(Xrm.Page.data.entity.getId())
    var relationShipName = "new_account_contact";
    var otherEntityName = "contacts";
    var otherEntityId = removeCurlyBraces(Xrm.Page.getAttribute("primarycontactid").getValue()[0].id);
    disAssociateRequest(currentEntityName, currentEntityId, relationShipName, otherEntityName, otherEntityId);

Associate Record using Web API

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Following is detail sample code to Associate a record using Web API in Dynamics CRM.
/*
currentEntityPlurarName: currentEntityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
currentEntityId: guid of current entity record
otherEntityPlurarName: otherEntityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
otherEntityId: guid of other entity record       
*/
function associateRequest(currentEntityPlurarName, currentEntityId, relationShipName, otherEntityPlurarName, otherEntityId) {
    var serverURL = Xrm.Page.context.getClientUrl();
    var associate = {}
    associate["@odata.id"] = serverURL + "/api/data/v8.2/" + otherEntityPlurarName + "(" + otherEntityId + ")"
    
    var req = new XMLHttpRequest();
    req.open("POST", serverURL + "/api/data/v8.2/" + currentEntityPlurarName + "(" + currentEntityId + ")/" + relationShipName + "/$ref", 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 /* complete */) {
            req.onreadystatechange = null;
            if (this.status == 204) {
                //alert('Record Associated');
            } else {
                var error = JSON.parse(this.response).error;
                Xrm.Utility.alertDialog(error.message);
            }
        }
    };
    req.send(JSON.stringify(associate));
}
You can call the associate record method as:
 var currentEntityName = "accounts";
var currentEntityId = removeCurlyBraces(Xrm.Page.data.entity.getId())
var relationShipName = "new_account_contact";
var otherEntityName = "contacts";
var otherEntityId = removeCurlyBraces(Xrm.Page.getAttribute("primarycontactid").getValue()[0].id);
associateRequest(currentEntityName, currentEntityId, relationShipName, otherEntityName, otherEntityId);

Delete Record using Web API

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Following is detail sample code to delete a record using Web API in Dynamics CRM.
/*
entityPlurarName: entityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
id: guid of record going to delete       
*/
function deleteRecord(entityPlurarName, id) {
    id = id.replace('{', '').replace('}', '');
    var IsDeleted = false;
    var serverURL = Xrm.Page.context.getClientUrl();
    var req = new XMLHttpRequest();
    req.open("DELETE", serverURL + "/api/data/v8.2/" + entityPlurarName + "(" + id + ")", 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.send();
    if (req.readyState == 4 /* complete */) {
        if (req.status == 204) {
            IsDeleted = true;
        }
        else {
            var error = JSON.parse(req.response).error;
            Xrm.Utility.alertDialog(error.message);
        }
    }
    return IsDeleted;
}
You can call the delete record method as:
var id=Xrm.Page.data.entity.getId();
alert(deleteRecord("accounts", id));

Retrieve Record using Web API

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Following is detail sample code to retrieve a record using Web API in Dynamics CRM.
/*
entityName: entityName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
entityId: Guid of entity record
return:-Entity record       
*/
function retrieveEntityById(entityName, entityId) {
    entityId = entityId.replace('{', '').replace('}', '');
    var data = null;
    var req = new XMLHttpRequest();
    req.open('GET', Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" + entityName + "(" + entityId + ")", false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Prefer", "odata.include-annotations=*");
    req.send();
    if (req.readyState == 4 /* complete */) {
        if (req.status == 200) {
            data = JSON.parse(req.response);
        }
        else {
            var error = JSON.parse(req.response).error;
            console.log(error.message);
        }
    }
    return data;
}
You can call the retrieve record method as:
var accountId=Xrm.Page.data.entity.getId();
var account=retrieveEntityById("accounts",accountId);
if(account!=null)
var accountName=account.name;
var accountNumber=account.accountnumber;

Update Record using Web API

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Following is detail sample code to update a record using Web API in Dynamics CRM.
/*
entityPlurarName: entityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
id: guid of record going to update
entityObject: entityObject is an object that of entity contians fields and values that needed to be create.
e.g
  var entityObject = {};
      entityObject["originatingleadid@odata.bind"] = "/leads(" + guid + ")";  // lookup    
      contact["firstname"] = string value;  // Single line of text 
      contact["po_preferredlanguage"] = string value; //Option set
      contact["donotemail"] = true/false //two Option
*/
function updateRecord(entityPlurarName, id, entityObject) {
    var IsUpdated = false;
    var req = new XMLHttpRequest();
    req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" + entityPlurarName + "(" + id + ")", false);
    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.send(JSON.stringify(entityObject));
    if (req.readyState === 4) {
        if (req.status === 204) {
            IsUpdated = true;
        }
        else {
            var error = JSON.parse(req.response).error;
            Xrm.Utility.alertDialog(error.message);
        }
    }
    return IsUpdated;
}
You can call the update record method as:
var account = {};
account["name"] = "Test Account name 2";  // Single line of text 
account["paymenttermscode"] = "4";//Text(Net 30) //Option set
account["creditonhold"] = false; //two Option 
alert(updateRecord("accounts", removeCurlyBraces(Xrm.Page.data.entity.getId()), account));

Create Record using Web API

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Following is detail sample code to create a record using Web API in Dynamics CRM.
/*
entityPlurarName: entityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
entityObject: entityObject is an object that of entity contians fields and values that needed to be create.
e.g
  var entityObject = {};
      entityObject["originatingleadid@odata.bind"] = "/leads(" + guid + ")";  // lookup   
      contact["firstname"] = string value;  // Single line of text 
      contact["po_preferredlanguage"] = string value; //Option set
      contact["donotemail"] = true/false //two Option  
*/
function createRecord(entityPlurarName, entityObject) {
    var id = null;
    var req = new XMLHttpRequest();
    req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" + entityPlurarName, false);
    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.send(JSON.stringify(entityObject));
    if (req.readyState === 4) {
        if (req.status === 204) {
            var uri = req.getResponseHeader("OData-EntityId");
            var regExp = /\(([^)]+)\)/;
            var matches = regExp.exec(uri);
            id = matches[1];
        }
        else {
            var error = JSON.parse(req.response).error;
            Xrm.Utility.alertDialog(error.message);
        }
    }
    return id;
}
You can call the create record method as:
var account = {};
account["primarycontactid@odata.bind"] = "/contacts(" + removeCurlyBraces(Xrm.Page.getAttribute("primarycontactid").getValue()[0].id) + ")";  // lookup 
account["name"] = "Test Account name";  // Single line of text 
account["paymenttermscode"] = "1";//Text(Net 30) //Option set
account["creditonhold"] = true; //two Option
var accountid=createRecord("accounts", account);