Dynamics 365 - Xrm WebAPI


Microsoft has come up with latest Client APIs for Customer Engagement V9.0. These APIs stream line a lot of stuff we used to do with Javascript in earlier versions.

Let’s look in depth into the APIs now.
  • Create Record
  • Update Record
  • Delete Record
  • Retrieve Record
  • Retrieve Multiple Records
  • Execute  
Each function has callback functions to handle success and failures.

Create Record
Syntax:
Xrm.WebApi.createRecord(entityLogicalName, data).then(successCallback, errorCallback);

Parameters:
entityLogicalName – logical name of the entity
data – JSON data
successCallback - success function with parameters entityType and id(entityId)
errorCallback – error function with parameters errorCode and message(errorMessage)

Example:
var data =
    {
        "name": "Chandrahas",
        "address1_address": "Chandrahas Address",
        "description": "Sample Description",
    }

Xrm.WebApi.createRecord("contact", data).then(
    function success(result) {
        console.log("Contact has been created with ID: " + result.id);
    },
    function (error) {
        console.log(error.errorCode + error.message);
    });



Update Record
Syntax:
Xrm.WebApi.updateRecord(entityLogicalName, id, data).then(successCallback,errorCallback);

Parameters:
entityLogicalName – logical name of the entity
id – entity Guid
data – JSON data
successCallback - success function with parameters entityType and id(entityId)
errorCallback – error function with parameters errorCode and message(errorMessage)

Example:
var data =
    {
        "name": "Updating Contact",
        "address1_address": "Chandrahas Address",
        "description": "Sample Description",
    }

Xrm.WebApi.updateRecord("contact", "6756d753-95bc-e711-c94e-400d3a51e685", data).then(
    function success(result) {
        console.log("Contact has been updated" + result.id);
    },
    function (error) {
        console.log(error.message);
    });


Delete Record
Syntax:
Xrm.WebApi.deleteRecord(entityLogicalName, id).then(successCallback, errorCallback);

Parameters:
entityLogicalName – logical name of the entity
id – entity Guid
successCallback - success function with parameters entityType, id(entityId)and name(record name)
errorCallback – error function with parameters errorCode and message(errorMessage)

Example:
Xrm.WebApi.deleteRecord("contact", "6756d753-95bc-e711-c94e-400d3a51e685").then(
    function success(result) {
        console.log("Contact has been deleted");
    },
    function (error) {
        console.log(error.message);
    });


Retrieve Record
Syntax:
Xrm.WebApi.retrieveRecord(entityLogicalName, id, options).then(successCallback, errorCallback);

Parameters:
entityLogicalName – logical name of the entity
id – entity Guid
options - $select and $expand options to retrieve data
successCallback – JSON data
errorCallback – error function with parameters errorCode and message(errorMessage)

Example:
Xrm.WebApi.retrieveRecord("contact", "6756d753-95bc-e711-c94e-400d3a51e685", "?$select=fullname,emailid&$expand=accountid($select=accountid,name").then(
    function success(result) {
        console.log("Retrieved values: FullName: " + result.fullname + ", Account name: " + result.accountid.name);
    },
    function (error) {
        console.log(error.message);
    });


Retrieve Multiple Records
Syntax:
Xrm.WebApi.retrieveMultipleRecords(entityLogicalName, options, maxPageSize).then(successCallback, errorCallback);

Parameters:
entityLogicalName – logical name of the entity
options - $select, $top, $filter, $orderby and $expand options to retrieve data. Fetchxml can also be used
maxPageSize – no of entity records to retrieve
successCallback - success function with parameters entities, nextLink
errorCallback – error function with parameters errorCode and message(errorMessage)

Example:
Xrm.WebApi.retrieveMultipleRecords("contact", "?$select=fullname", 10).then(
    function success(result) {
        for (var i = 0; i < result.entities.length; i++) {
            console.log(result.entities[i].fullname);
        }
        console.log("Next page link: " + result.nextLink);
    },
    function (error) {
        console.log(error.message);
    });



Execute
Syntax:
Xrm.WebApi.online.execute(request).then(successCallback, errorCallback);

Parameters:
request – CRUD request object(getMetadata).
       boundParameter – (optional) parameters are undefined/null/entity
operationName – (optional) parameters are Create/Retrieve/RetrieveMultiple/Update/Delete
operationType – (optional) parameters are 0(action)/1(function)/2(crud)
parameterTypes – Object
       enumProperties – (optional) name, value
structuralProperty – category type. Parameters are 0(unknown)/1(primitivetype) /2(complextype)/3(enumerationtype)/4(collection)/5(entitytype)
typeName – parameter type name
successCallback - success function
       body – response body
headers –response headers
ok – true/false, indicates response is successful or not
status – response status code
statusText – response status description
type – type of response. Type can be empty string (default)/arraybuffer/blob/ document/json/text.
url – request url
errorCallback – error function with parameters errorCode and message(errorMessage)

Example:
Execute Action:

var Sdk = window.Sdk || {};
Sdk.WinOpportunityRequest = function (opportunityClose, status) {
    this.OpportunityClose = opportunityClose;
    this.Status = status;

    this.getMetadata = function () {
        return {
            boundParameter: null,
            parameterTypes: {
                "OpportunityClose": {
                    "typeName": "mscrm.opportunityclose",
                    "structuralProperty": 5 // Entity Type
                },
                "Status": {
                    "typeName": "Edm.Int32",
                    "structuralProperty": 1 // Primitive Type
                }
            },
            operationType: 0, // This is an action. Use '1' for functions and '2' for CRUD
            operationName: "WinOpportunity",
        };
    };
};

var opportunityClose = {
    "opportunityid@odata.bind": "/opportunities(c60e0283-5bf2-e311-945f-6c3be5a8dd64)",
    "description": "Product and maintainance for 2018",
    "subject": "Contract for 2018"
}
// Construct a request object from the metadata
var winOpportunityRequest = new Sdk.WinOpportunityRequest(opportunityClose, 3);

// Use the request object to execute the function
Xrm.WebApi.online.execute(winOpportunityRequest).then(
    function (result) {
        if (result.ok) {
            console.log("Status: %s %s", result.status, result.statusText);
            // perform other operations as required;
        }
    },
    function (error) {
        console.log(error.message);
        // handle error conditions
    });


Execute Function:

var Sdk = window.Sdk || {};

Sdk.WhoAmIRequest = function () {};
Sdk.WhoAmIRequest.prototype.getMetadata = function () {
    return {
        boundParameter: null,
        parameterTypes: {},
        operationType: 1, //This is a function.Use '0' for actions and '2' for CRUD
        operationName: "WhoAmI",
    };
};

// Construct a request object from the metadata
var whoAmIRequest = new Sdk.WhoAmIRequest();

// Use the request object to execute the function
Xrm.WebApi.online.execute(whoAmIRequest).then(
    function (result) {
        if (result.ok) {
            console.log("Status: %s %s", result.status, result.statusText);
            result.json().then(
                function (response) {
                    console.log("User Id: %s", response.UserId);
                    // perform other operations as required;
                });
        }
    },
    function (error) {
        console.log(error.message);
        // handle error conditions
    });

Comments

Popular posts from this blog

Dynamics 365 - Dynamically create Custom Lookup View(JavaScript)

Microsoft Portal JavaScript