Tag: javascript

{Bookmarklet} Refresh Form Data

{Bookmarklet} Refresh Form Data

Recently I was developing a plugin in which, whenever a record updated some of the fields were updated and for reflecting those fields I need to refresh the page. I was tired to refresh the page again and again.so I come up with a solution that would also increase productivity.

I made a small bookmarklet that will help me to refresh form data without refreshing the entire page.

Here is code

javascript: (function () { debugger;(document.querySelectorAll(‘iframe’)).forEach(function (frame, v) { if (frame.style.visibility !== ‘hidden’) { if (frame) { var Xrm = frame.contentWindow.Xrm; Xrm.Page.data.refresh(); alert(‘Form Data Refreshed…’) } else { alert(‘Entity form not detected’); } } }) })();

Note: Before using the above code please update single quotation mark.

For adding this bookmarklet on chrome , refer below link


Hope it’ll help someone.


Multiple views inside a tab on CRM dashboard

Multiple views inside a tab on CRM dashboard

In this blog, we’re going to implement multiple views inside a tab with the help of web resource.

we are showing Active Accounts, Active Contacts, and Open Opportunities views into a tab of a dashboard.

for this, I used Javascript Tabifier library, you can download JS and CSS from below link

Javascript Tabifier library

let’s upload and publish Tabbler.js and their CSS on our CRM Organization.we can use XrmToolbox for maintaining CRM web resources.

create a new HTML web resource i.e. MultiViews. Inside this, we’ll write our code for showing three different views in a web resource.


For showing views in Iframe we need views URL’s.For more info about how to get URL please refer below link

Copy the URL for a View


Here is code for HTML page

<!DOCTYPE html>

<html lang=”en” xmlns=”http://www.w3.org/1999/xhtml”&gt;
<meta charset=”utf-8″ />
<link rel=”stylesheet” href=”../content_/css/example.css” type=”text/css” media=”screen”>

/* Optional: Temporarily hide the “tabber” class so it does not “flash”
on the page as plain HTML. After tabber runs, the class is changed
to “tabberlive” and it will appear. */



Note: Iframe tag is not supported as a text in WordPress so please download the source code from here

In the above code, we’re using Active Accounts, Active Contacts, and Open Opportunities views URL.Now let just add this web resource on dashboard or use a web resource whatever.



That’s it . Now we can see multiple views inside a single web resource.

Here is the link for source code


Thanks for visiting my blog.

{Bookmarklet} Get current record Guid from CRM form

{Bookmarklet} Get current record Guid from CRM form

Most of the time when we developed some new functionality in crm, we need current entity record GUID for debugging and checking our modification using advanced find , Odata query etc.

In this blog I am going to create a simple bookmarklet for getting current enity record GUID.

What is Bookmarklet?

A small software application stored as a bookmark in a web browser, which typically allows a user to interact with the currently loaded web page in some way.

(definition from google)

For more details on bookmarklet creation refer below link


Let’s write a JavaScript code that we use for our bookmarklet.

(function () {
(document.querySelectorAll(‘iframe’)).forEach(function (frame, v) {
if (frame.style.visibility !== ‘hidden’) {
if (frame) {
var Xrm = frame.contentWindow.Xrm;
prompt(“Copy GUID for the current record”, Xrm.Page.data.entity.getId());
} else {
alert(‘Entity form not detected’);


Now add a new page on chrome from bookmark bar


In name give some meaning name like ‘GETID’ and in URL paste our JavaScript code


Now try this on Entity Form, we’ll get the GUID of current record.



That’s it. Hope it’ll help someone 🙂

Thanks for visiting my blog!!!





Angular Interceptor for Converting UTC date time into Local date time

Angular Interceptor for Converting UTC date time into Local date time

Hi Everyone recently I have a requirement in which we have to convert every date time attributes of  AJAX response into local date time because response date time attributes in UTC but we wanted in local date time.

It is always good to save all our date time information into UTC format on server because using of UTC format we can calculate local date time easily with just knowing user timezone.

E.g. In our database we saved date in UTC format that is 2016-05-29 00:00:00(UTC) but we want to show this according to user timezone like for India timezone user that is 2016-05-29 05:30:00(GMT+5:30).

For achieving this I wrote a angular interceptor that runs on every AJAX request and check every AJAX response that have a valid date time attributes then converted  into local.

Let’s start with creating a new angular factory and use into our app.js config section.

1.Add a new JavaScript namespace that contains important function

var dateUTC = {};
dateUTC.checkNested = function (prop, val1) {
//check for string
if (typeof (val1[prop]) == “string”) {
if (isNaN(val1[prop])) {
if (dateUTC.checkISOdate(val1[prop])) {
val1[prop] = moment(moment.utc(val1[prop]).toDate()).format();
//check for object
if (typeof (val1[prop]) == “object”) {
//start loop for array
for (var prp in val1[prop]) {
if (typeof (val1[prop][prp]) == “string”) {
if (dateUTC.checkISOdate(val1[prop][prp])) {
val1[prop][prp] = moment(moment.utc(val1[prop][prp]).toDate()).format();
if (typeof (val1[prop][prp]) == “object”) {
//start loop for nested object
for (var pr in val1[prop][prp]) {
if (typeof (val1[prop][prp][pr]) == “string”) {
if (isNaN(val1[prop][prp][pr])) {
if (dateUTC.checkISOdate(val1[prop][prp][pr])) {
val1[prop][prp][pr] = moment(moment.utc(val1[prop][prp][pr]).toDate()).format();
if (typeof (val1[prop][prp][pr]) == “object”) {
for (var p in val1[prop][prp][pr]) {
dateUTC.checkNested(p, val1[prop][prp][pr]);
dateUTC.checkISOdate = function (date) {
if (moment(date, “YYYY-MM-DDTHH:mm:ss.SSS”, true).isValid()
|| moment(date, “YYYY-MM-DDTHH:mm:ss.SS”, true).isValid()
|| moment(date, “YYYY-MM-DDTHH:mm:ss.S”, true).isValid()
|| moment(date, “YYYY-MM-DDTHH:mm:ss”, true).isValid()) {
return true;
return false;

2.Create a new factory that intercept on every AJAX request

Myservice.factory(‘dateinterceptor’, function () {
return {
request: function (config) {
return config;

requestError: function (config) {
return config;

response: function (res) {
if (typeof (res.data) == “object”) {
if (res.data) {
if (res.data.length) {
angular.forEach(res.data, function (val, key) {
if (typeof (val) == “object”) {
if (val) {
if (val.length) {
angular.forEach(val, function (val1, key1) {
for (var prop in val1) {
dateUTC.checkNested(prop, val1);
else {
for (var prop in val) {
dateUTC.checkNested(prop, val);
else {
for (var prop in res.data) {
dateUTC.checkNested(prop, res.data);
return res;

responseError: function (res) {
return res;


3.Add our date interceptor factory appModule.config section

appModule.config([‘$httpProvider’, function ( $httpProvider) {

Thanks for vising my blog.

Hope it’ll help someone.



Response type ‘token’ is not enabled for the application

Response type ‘token’ is not enabled for the application

Recently I faced problem when I was trying to build client-side app with CRM and Azure.

I was able to login to my APP and adal.js successfully acquired a token for my webApi and injected it into a request.

Then token acquisition for webApi stopped working with error:

“response_type ‘token’ is not enabled for the application”

Here is the steps that resolved my problem.

Note: If we’re building client-side app, so we need to enable Implicit flow from the application manifest.


1. Select the Configure tab of your application’s entry in the Azure Management Portal.

2. Using the Manage Manifest button in the drawer, download the manifest file for the application and save it to your computer.


3. Open the manifest file with a text editor. Search for the oauth2AllowImplicitFlow property. By default it is set to false; change it to true and save the file.


4.Using the Manage Manifest button, upload the updated manifest file.


Logout and Login with again with you app and it’ll work like a charm.

For more info about OAuth Flow please refer below links

Looking at the Different OAuth2 Flows Supported in AzureAD for Office 365 APIs

v2.0 Protocols – SPAs using the implicit flow

An Introduction to OAuth 2

Hope it’ll help someone.

Thanks for visiting my blog.

Add Form Library on CRM Form using C# or javascript

Add Form Library on CRM Form using C# or javascript

Hello Everyone, Today I am going to tell how we can add form library on CRM form using C# or  JavaScript.

We want to add library on account form so for that I created one JavaScript web resources e.g.  am_sample for our demo purpose or you can add existing JS from CRM.


After that we add alert functionality inside this so we’ll found ourselves that our code is executed on onload of account form. We put our code inside self invoking function so it will show alert dialog on load of account form.(By using self invoking function we don’t need to define any function in Event Handlers)

here is demo link for self invoking function in JavaScript.




In below screen we don’t see any library added on account form let’s write some code for adding file here 🙂



C# Code :

First we add one function for get form xml in which we passes logical name of Account entity as its parameter.


public Entity GetForm(string EntityLogicalname)
QueryExpression query = new QueryExpression(“systemform”)
Distinct = false,
ColumnSet = new ColumnSet(new[] { “name”, “formxml”, “objecttypecode” }),
Criteria =
Filters =
new FilterExpression
FilterOperator = LogicalOperator.And,
Conditions =
new ConditionExpression(“objecttypecode”, ConditionOperator.Equal, EntityLogicalname),
new ConditionExpression(“type”, ConditionOperator.Equal, 2),
new ConditionExpression(“iscustomizable”, ConditionOperator.Equal, true),
new ConditionExpression(“formactivationstate”, ConditionOperator.Equal, 1)
return Service.RetrieveMultiple(query).Entities.FirstOrDefault();
catch (Exception)

This function return Entity with formxml attribute.

After that we need to add one more function that change current formxml of Account entity (which return from above function) with new JS that we need to add.

Below is the description of what we’re going to perform in our next funtion :

  • First we select Form node, and formLibraries inside it.
  • If formLibraries not found then we’ll create formLibraries xml node.
  • If formLibraries found then we’ll create Library element inside it with name, libraryUniqueId attributes.
  • After that we append this Library tag into formLibraries and update formxml attribute of Entity.


public void AddLibrary(Entity form, string libraryName, bool addFirst)
var formXml = form.GetAttributeValue<string>(“formxml”);
var formDoc = new XmlDocument();
var formNode = formDoc.SelectSingleNode(“form”);
if (formNode == null)
throw new Exception(“Expected node \”formNode\” was not found”);
var formLibrariesNode = formNode.SelectSingleNode(“formLibraries”);
var eventLibrary = formNode.SelectSingleNode(“events”);
if (formLibrariesNode == null)
formLibrariesNode = formDoc.CreateElement(“formLibraries”);
var libraryNode = formLibrariesNode.SelectSingleNode(string.Format(“Library[@name='{0}’]”, libraryName));
if (libraryNode != null)
Console.WriteLine(“This library is already included in this form”);
var nameAttribute = formDoc.CreateAttribute(“name”);
var libraryUniqueIdAttribute = formDoc.CreateAttribute(“libraryUniqueId”);
nameAttribute.Value = libraryName;
libraryUniqueIdAttribute.Value = Guid.NewGuid().ToString(“B”);
libraryNode = formDoc.CreateElement(“Library”);
if (libraryNode.Attributes != null)
if (formLibrariesNode.ChildNodes.Count > 0 && addFirst)
formLibrariesNode.InsertBefore(libraryNode, formLibrariesNode.FirstChild);
form[“formxml”] = formDoc.OuterXml;


After that we’ll publish Account Entity.

public void PublishForm(Entity en)
var request = new PublishXmlRequest { ParameterXml = String.Format(“<importexportxml><entities><entity>{0}</entity></entities></importexportxml>”, en.GetAttributeValue<string>(“objecttypecode”)) };


Here is calling code

CrmConnection con = CrmConnection.Parse(“Url = https://xxxx.crm5.dynamics.com; Username=xyz@abc.onmicrosoft.com; Password=xyzxyz”);
IOrganizationService Service = new OrganizationService(con);
ScriptManage sc = new ScriptManage(Service);
var EntityName = sc.GetForm(“account”);
sc.AddLibrary(EntityName,”am_sample”, false);

Now you can see JS file is added on account form!! 🙂

For more info about C# code, go through below link.







JS Code :

For using below code we need to add these file references.

  1. ClientGlobalContext.js.aspx
  2. jquery.min.js
  3. Sdk.Soap.min.js
function Getformxml  (EntityLogicalname) {
var SystemForm = new Sdk.Query.QueryExpression(“systemform”);
SystemForm.addCondition(“systemform”, “objecttypecode”, Sdk.Query.ConditionOperator.Equal, new Sdk.Query.Strings([EntityLogicalname]))
SystemForm.addCondition(“systemform”, “type”, Sdk.Query.ConditionOperator.Equal, new Sdk.Query.Ints([2]))
SystemForm.addCondition(“systemform”, “iscustomizable”, Sdk.Query.ConditionOperator.Equal, new Sdk.Query.Booleans([true]))
SystemForm.addCondition(“systemform”, “formactivationstate”, Sdk.Query.ConditionOperator.Equal, new Sdk.Query.Ints([1]))
FormxmlQuery = SystemForm;
return Sdk.jQ.retrieveMultiple(SystemForm).then(
function (ec) {
new ErrorHandler(“An error occured “).getError(err);
function formRequestSuccesscall  (data) {
var $xml, $formtagxml, x = true, xml2 = ”;
if (data.getEntities().getCount() > 0) {
data.getEntities().forEach(function (n, i, arr) {
if (n.view().attributes[‘formxml’])
$xml = $($.parseXML(n.view().attributes[‘formxml’].value));
$formtagxml = $xml.find(“formLibraries”);
$($formtagxml).find(‘Library’).each(function () {
$.each(this.attributes, function (i, attrib) {
if (attrib.name == “name”) {
if (attrib.value == “Content_/scripts/wfHover.js”) {
console.log(‘already add on form!!’);
x = false;
if (x) {
if ($formtagxml.length == 0) {
xml2 += ‘<formLibraries><Library name=“am_sample” libraryUniqueId=”‘ + guid() + ‘” /></formLibraries>’;
$formtagxml = $($.parseXML(xml2)).find(“formLibraries”);
} else {
$formtagxml.append(‘<Library name=“am_sample” libraryUniqueId=”‘ + guid() + ‘” />’)
var oSerializer = new XMLSerializer();
//clone.attributes[‘formxml’].value = oSerializer.serializeToString($xml[0]);
n.setValue(“formxml”, oSerializer.serializeToString($xml[0]));
function (id) {
// console.log(id);
function publishXML (entityName) {
var context = Xrm.Page.context;
var serverUrl = (context.getServerUrl) ? context.getServerUrl() : context.getClientUrl();
var Publishxml = “”;
Publishxml += “<s:Envelope xmlns:s=\”http:\/\/schemas.xmlsoap.org\/soap\/envelope\/\”>”;
Publishxml += ” <s:Body>”;
Publishxml += ” <Execute xmlns=\”http:\/\/schemas.microsoft.com\/xrm\/2011\/Contracts\/Services\” xmlns:i=\”http:\/\/www.w3.org\/2001\/XMLSchema-instance\”>”;
Publishxml += ” <request i:type=\”b:PublishXmlRequest\” xmlns:a=\”http:\/\/schemas.microsoft.com\/xrm\/2011\/Contracts\” xmlns:b=\”http:\/\/schemas.microsoft.com\/crm\/2011\/Contracts\”>”;
Publishxml += ” <a:Parameters xmlns:c=\”http:\/\/schemas.datacontract.org\/2004\/07\/System.Collections.Generic\”>”;
Publishxml += ” <a:KeyValuePairOfstringanyType>”;
Publishxml += ” <c:key>ParameterXml<\/c:key>”;
Publishxml += ” <c:value i:type=\”d:string\” xmlns:d=\”http:\/\/www.w3.org\/2001\/XMLSchema\”>&lt;importexportxml&gt;&lt;entities&gt;&lt;entity&gt;” + entityName + “&lt;\/entity&gt;&lt;\/entities&gt;&lt;\/importexportxml&gt;<\/c:value>”;
Publishxml += ” <\/a:KeyValuePairOfstringanyType>”;
Publishxml += ” <\/a:Parameters>”;
Publishxml += ” <a:RequestId i:nil=\”true\” \/>”;
Publishxml += ” <a:RequestName>PublishXml<\/a:RequestName>”;
Publishxml += ” <\/request>”;
Publishxml += ” <\/Execute>”;
Publishxml += ” <\/s:Body>”;
Publishxml += “<\/s:Envelope>”;
var req = new XMLHttpRequest();
req.open(“POST”, serverUrl + “/XRMServices/2011/Organization.svc/web”, true);
// Responses will return XML. It isn’t possible to return JSON.
req.setRequestHeader(“Accept”, “application/xml, text/xml, */*”);
req.setRequestHeader(“Content-Type”, “text/xml; charset=utf-8”);
req.setRequestHeader(“SOAPAction”, “http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute&#8221;);
req.onreadystatechange = function () {
if (req.readyState === 4) {
if (req.status === 200) {
} else {
alert(“An error occurred ” + req.statusText);

here is caling code for JS

Getformxml  (“account”);


Hope you will like this blog and Thank you for visiting my blog 🙂