Tuesday, 2 August 2022

Dynamics Portal Web Api

     You can use the Web API to perform create, read, update, and delete operations across all Microsoft Dataverse tables from your portals pages. Below set of Operations can be performed using Portal Web Apis : 

    

  • Read records from a table
  • Create a record in a table
  • Update and delete records in a table

  • Associate and disassociate tables

Design Flow : 



Steps to enable Portal Web Api in your CRM Organization : 

1. Create Site setting for Web Api to use particular Entity as shown below :

    > Site Settings > 


2. Create another site setting for the Entity fields to use as shown below : 

                  

3. Enable Entity Permissions for the Contact by using Table permissions setting and provide add newly created  Web Role to provide access to your web api 

4. Once all the above steps are completed - you can update your contact Record from portal pages using below code with the help of Portal Web api as shown below : 

(function(webapi, $){
function safeAjax(ajaxOptions) {
var deferredAjax = $.Deferred();
shell.getTokenDeferred().done(function (token) {
// add headers for ajax
if (!ajaxOptions.headers) {
$.extend(ajaxOptions, {
headers: {
"__RequestVerificationToken": token
}
}); 
} else {
ajaxOptions.headers["__RequestVerificationToken"] = token;
}
$.ajax(ajaxOptions)
.done(function(data, textStatus, jqXHR) {
validateLoginSession(data, textStatus, jqXHR, deferredAjax.resolve);
}).fail(deferredAjax.reject); //ajax
}).fail(function () {
deferredAjax.rejectWith(this, arguments); // on token failure, pass the token ajax and args
});
return deferredAjax.promise();
}
webapi.safeAjax = safeAjax;
})(window.webapi = window.webapi || {}, jQuery)



// Notification component
var notificationMsg = (function() {
var $processingMsgEl = $('#processingMsg'),
_msg = 'Processing...',
_stack = 0,
_endTimeout;
return {
show: function(msg) {
$processingMsgEl.text(msg || _msg);
if (_stack === 0) {
clearTimeout(_endTimeout);
$processingMsgEl.show();
}
_stack++;
},
hide: function() {
_stack--;
if (_stack <= 0) {
_stack = 0;
clearTimeout(_endTimeout);
_endTimeout = setTimeout(function() {
$processingMsgEl.hide();
}, 500);
}
}
}
})();

//Applicaton ajax wrapper 
function appAjax(processingMsg, ajaxOptions) {
notificationMsg.show(processingMsg);
return webapi.safeAjax(ajaxOptions)
.fail(function(response) {
if (response.responseJSON) {
alert("Error: " + response.responseJSON.error.message)
} else {
alert("Error: Web API is not available... ")
}
}).always(notificationMsg.hide);
}

var userGuid = $("#adx_user_guid").val();
     appAjax('Updating...', {
      type: "PATCH",
url: "/_api/contacts("+userGuid+")",
contentType: "application/json",
data: JSON.stringify({
" Login Time": dateTime,
}),
success: function (res) {
console.log(res);
}
        });


The above code should update your contact record with Logged in user Date time. Hope it helps. 

Thank You!