Archive for the ‘JScript’ Category

Reading related records using OData and Jscript – CRM 2011

I have 1:N relationship between “Contact” entity and custom entity “Bikes” (i.e., 1 contact can have N no of Bikes).

If I want to read all “Bikes” along with my “Contact” information using OData service, I can use the “$expand” keyword of OData protocol.

Below is the generic function to prepare the OData URL and make a Asynchronous service call

function retrieveMultiple(odataSetName, select, filter, expand, successCallback) {

var serverUrl = Xrm.Page.context.getServerUrl();

var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;

var odataUri = serverUrl + ODATA_ENDPOINT + “/” + odataSetName + “?”;

if (select) {

odataUri += “$select=” + select;


if (expand) {

odataUri += “&” + “$expand=” + expand;


if (filter) {

odataUri += “&” + “$filter=” + filter;



type: “GET”,

contentType: “application/json; charset=utf-8”,

datatype: “json”,

url: odataUri,

beforeSend: function (XMLHttpRequest) {

XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);


success: function (data, textStatus, XmlHttpRequest) {

if (successCallback) {

if (data && data.d && data.d.results) {

successCallback(data.d.results, textStatus, XmlHttpRequest);


else if (data && data.d) {

successCallback(data.d, textStatus, XmlHttpRequest);


else {

successCallback(data, textStatus, XmlHttpRequest);




error: function (XmlHttpRequest, textStatus, errorThrown) {

if (XmlHttpRequest && XmlHttpRequest.responseText) {

alert(“Error while retrieval of ” + odataSetName + ” ; Error – ” + XmlHttpRequest.responseText);





How do I use above function

  • Consider my “Contact” & “Bike” scenario and set required the columns and “expand” option and call the above “retrieveMultiple” function
  • Below is the function to define properties

function retrieveBikesByContactId() {

// Pass ‘Contact’ set name

var oDataSetName = “ContactSet”;

// Set Contact GUID

var contactId = {Contact GUID};

// Prepare filter

var filter = “ContactId eq guid'” + contactId + “‘”;

// Set expand (i.e., Relationship name of ‘Contact’ and ‘Bike’)

var expand = “honda_contact_honda_bikeinformation”;

// Column names of ‘Contact’ and ‘Bikes’

// Since Bike is related entity specify Bike columns as (Relationship name\column name) (i.e., honda_contact_honda_bikeinformation/honda_name)

var columns = “FullName,honda_contact_honda_bikeinformation/honda_name,honda_contact_honda_bikeinformation/honda_Year”;

retrieveMultiple(oDataSetName, columns, filter, expand, readDataOnSuccess);


  • After the success of data retrieval, parse the result using “readDataOnSuccess” method

function readDataOnSuccess(data, textStatus, XmlHttpRequest) {

if (data && data.length > 0) {

for (var indx = 0; indx < data.length; indx++) {

if (data[indx].honda_contact_honda_bikeinformation) {

              // Read the child entity records using “expand.results” (i.e., honda_contact_honda_bikeinformation.results)

var childResults = data[indx].honda_contact_honda_bikeinformation.results;

for (var indxChild = 0; indxChild < childResults.length; indxChild++) {







Use the “OData Query Designer” tool to get the “expand” name and column names

  • To get related entity record fields, click “One To Many” tab and choose the relationship
Get Related Entity Fields

Get Related Entity Fields

URL with Related records columns

URL with Related records columns

Related records result set

Related records result set

Read and Parse XML web resource using Jscript – CRM 2011

April 25, 2013 3 comments

I have a XML file with below content added as a web resource (new_fruitsxml) in my CRM application

<?xml version=”1.0″ encoding=”utf-8″ ?>


<Fruit Code=”App”>




<Fruit Code=”Orng”>





Below is the Jscript code to read and parse the XML.

Note – The code uses JQuery to parse the XML, so you have to refer “jquery1.4.1.min.js” file to make the code works.

function ReadXML() {

try {

var xmlPath = “../WebResources/new_fruitsxml”;


type: “GET”,

url: xmlPath,

dataType: “xml”,

success: parseXML


} catch (e) {

alert(“Error while reading XML; Description – ” + e.description);



function parseXML(xml) {

$(xml).find(“Fruit”).each(function () {

// Read attribute

alert(“Fruit Code – ” + $(this).attr(“Code”));

// Read Nodes

alert(“Fruit Name – ” + $(this).find(“Name”).text());

alert(“Fruit Price – ” + $(this).find(“Price”).text());



  • In “ReadXML()” function we read the webresource and if the read succeeds, we mention the “parseXML()” function in “success: parseXML”
  • So, on success, control comes to “parseXML()” function where we parse the XML


Passing multiple values to web resource(HTML/Silverlight) in CRM 2011

March 7, 2013 2 comments

Lets assume a requirement as below

  • I need to show a custom HTML page on my “Account” form
  • Read few “Account” entity field values (i.e.,  Address1_line1,City etc…) from my HTML page
  • Account fields to pass to HTML need to be configurable (i.e., Fields I need to read in my HTML may change)


In CRM 2011, we can

  • Add a HTML file as web resource and add it to entity form
  • We can pass a single custom parameter called data
Custom Parameter (data)

Custom Parameter (data)

  • Since only one value can be passed within the data , we can pass a multi-line string separated by special character


  • Create a blank HTML file using visual studio  and add this as web resource to CRM
  • Open the “Account” customization form and add the HTML web resource added in above step
Add web resource to Account entity

Add web resource to Account entity

  • After you chosen the HTML as web resource, you get a “Web Resource Properties” section and looks as below
Web Resource Properties

Web Resource Properties

  • In the “Web Resource Properties” section, below is the description of each field
    • Custom Parameter(data)         – The values you want to pass to your web resource.
      • Since I want Address1_line1,City fields of account, I provided those 2 fields separated by  ,(comma)
      • We can read the value passed as query string
      • Sample query string looks as ?data=%22emailaddress1%22%2c%22address1_city%22
    • Restrict cross-frame scripting –  Uncheck this to read content from CRM form
    • Pass record object-type code and unique identifier as parameters – By choosing this, we can read entity information(i.e., Record Id, orglcid, orgname,objecttypecode etc..) as query string parameters
      • The sample query string looks as id=%7b44623C6A-4452-E211-8FB3-00155DC87C64%7d&orglcid=1033&orgname=ABCD&type=1&typename=account&userlcid=1033
  • Now open the “HTML” web resource and copy and paste the below content

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “”&gt;

<html xmlns=””&gt;



    <script type=”text/javascript”>

        document.onreadystatechange = function () {

            // If page load completes call the “getDataParam()” to read parameters

            if (document.readyState == “complete”) {




        function getDataParam() {

            var vals = new Array();

            // The parameters we pass comes as query string

            // Read it using “”

            if ( != “”) {

                vals =“&”);

                for (var i in vals) {

                    vals[i] = vals[i].replace(/\+/g, ” “).split(“=”);


                // Look for the parameter named ‘data’ among query string parameters

                for (var i in vals) {

                    if (vals[i][0].toLowerCase() == “data”) {

                        // Call parseDataValue to read params passed in “Custom Parameter(data)”







        function parseDataValue(datavalue) {

            if (datavalue != “”) {

                var vals = new Array();

                vals = decodeURIComponent(datavalue).split(“&”);

                // You get “emailaddress1″,”address1_city” as a string in vals[0]

                // Split with , (comma) to read the schema name

                var email_schmaname = vals[0].split(‘,’)[0];

                var city_schmaname = vals[0].split(‘,’)[1];

                // Get the values of account’s email & city using the schema names we passed in (data)

                var emailAddress =;

                var city =;

                alert(“Account’s email – ” + emailAddress);

                alert(“Account’s city – ” + city);







The HTML file script has 2 functions

  • getDataParam: Called from the body.onload event, this function retrieves any query string parameters passed to the page and locates one named data.
  • parseDataValue: Receives the “data” parameter from getDataParam function.

Points to ponder

  • We can’t access ‘Xrm’ object directly, use window.parent.Xrm
  • document.readyState == “complete” will become true if the page load complets
  • Refer the inline comments of HTML file to understand the jscript


CRM 2011 sub grid grey out/freezing issue – workaround

January 30, 2013 Leave a comment

We have a custom entity form having 2 sub grids.



The problem was, when we open the record and click on ‘Save’ ribbon button (I.e., updating record)

  • Sub grids are not getting refreshed
  • Sub grid section is greying out
Subgrid - grey out

Subgrid – greyed out

To fix the sub grid refresh issue, we used below retry logic as workaround

Retry logic

  • On page load, check for the “ready state” of your ‘Sub grid’
  • If sub grid load properly (i.e., readyState == “complete”) no issues
  • Else If readyState != “complete”
    • Wait for 1 second and check for the sub grid state
    • Repeat  it for 5 times (i.e., Wait for 5 seconds)
    • If sub grid not loaded thereafter also, reload the page

Jscript to implement the Retry logic

function refreshGrids() {

    var mySubgrid = document.getElementById(“{Sub grid name}“);

    if (mySubgrid == null || mySubgrid.readyState != “complete”) {

        if (indxCount == 5) {

            // Reload the page after 5 attempts

            if (window && window.parent) {




        // Wait 1 second and then call same function again    

        setTimeout(‘refreshGrids()’, 1000);




Where to place the above function

  • Register “refreshGrids()” function, on “onload” event of JScript


Xrm.Utility functions to open Entity forms or Web resources

November 1, 2012 1 comment

In CRM, we can open the entity forms using “” method

  • With UR 8, a couple new client-side JavaScript functions were added to open entity forms and web resources
  • These functions fixes the prompt the user to login again issue when you use “” to open form or web resource from CRM online/Outlook client


The Xrm.Utility object provides a container for useful functions. Following MSDN blog which talks extensively on the same

For quick glance below are few samples

Open a new “Account” record form

Xrm.Utility.openEntityForm(“account”); // Pass ‘Account’ schema name

Open an existing “Account” record form

Xrm.Utility.openEntityForm(“account”,”A85C0252-DF8B-E111-997C-00155D8A8410″); // Pass ‘Account’ schema name & GUID

Open a new “Account” record form and setting default values

var parameters = {};

parameters[“formid”] = “b053a39a-041a-4356-acef-ddf00182762b”;

parameters[“name”] = “Test”;

parameters[“telephone1”] = “(425) 555-1234”;

Xrm.Utility.openEntityForm(“account”, null, parameters);

Open an HTML web resource named “new_webResource.htm”



Fixing time zone issues while reading datetime fields using jscript in CRM 2011

When you read datetime field values using OData or SOAP , you may not get exact datetime values if your CRM application is using by users from different time zones.

We can fix the problem by using the “timezonebias” field from current users “UserSettings“

timezonebias & timezonedaylightbias are system-calculated fields based on the time zone of current user

Follow below steps to fix the problem

  • Read the “timezonebias” &“timezonedaylightbias”  field by querying  “UserSettings“ by current user id
  • Get your datetime field and substract the “timezonebias & timezonedaylightbias” fields to get exact value

Below is the script for the above steps

  • Read Current UserSettings

function RetrieveUserSettings(callBackFunction) {

try {

var serverUrl = Xrm.Page.context.getServerUrl();

var oDataEndpointUrl = serverUrl + “/XRMServices/2011/OrganizationData.svc/”;

//get current user id from context

var UserID = Xrm.Page.context.getUserId();

var RetrieveUserSetting = new XMLHttpRequest();“GET”, oDataEndpointUrl + “/UserSettingsSet(guid'” + UserID + “‘)”, true);

RetrieveUserSetting.setRequestHeader(“Accept”, “application/json”);

RetrieveUserSetting.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);

RetrieveUserSetting.onreadystatechange = function () {




} catch (e) {

alert(“Error on RetrieveUserSettings method”);



  • Call the above function to get “timezonebias & timezonedaylightbias” fields


  • Read the “timezonebias” & “timezonedaylightbias” field from Call Back function and substract it from your datatime field value

   function RetrieveUserSettingCallBack(retrievedUserSetting) {

try {

if (retrievedUserSetting.readyState == 4) {

if (retrievedUserSetting.status == 200) {

var retrievedUser = this.parent.JSON.parse(retrievedUserSetting.responseText).d;

// Assume you got datetime field to below object

var dateValue;

var actMinutes = dateValue.getMinutes();

alert(“Skewed datetime – ” + dateValue); 

if (userSettings.TimeZoneBias != null) { 
            dateValue.setMinutes(userSettings.TimeZoneBias * -1); 

if (userSettings.TimeZoneDaylightBias != null) { 
            dateValue.setMinutes(userSettings.TimeZoneDaylightBias * -1); 
// Add the actual minutes


alert(“Exact datetime – ” + dateValue);



} catch (e) {




Here is the article on handling the time zone differences  in Plug-ins


Filtering partylist entities using jscript in CRM

August 2, 2012 5 comments

In CRM, partylist Party List is a data type, using which you can set more than one type of entity records for a single field

For example,

  • In the ‘Appointment’ entity, field “requiredattendees” is a ‘Party List’ type
  • We can select multiple records of different      type (i.e., Accounts, Users, Contacts…)

In one of my requirement, I have to restrict the party list field to show only ‘Contacts’. (i.e., I can only choose Contacts)

We can achieve by setting below properties to partylist field using jscript

crmForm.all.requiredattendees.setAttribute(“defaulttype”, “2”);

crmForm.all.requiredattendees.setAttribute(“lookuptypes”, “2”);

crmForm.all.requiredattendees.setAttribute(“lookuptypeIcons”, “/_imgs/ico_16_2.gif”);

Here ‘2’ is the Entity Type Code of ‘Contact’ entity

After setting the properties, the partylist look as below with ‘Contact’ chosen as default and in disabled state to restrict other entity selction

Filtered Party List

Filtered Party List

In case you have to filter 2 entities, let’s say Contact & User you have to set “lookuptypes & lookuptypenames & lookuptypeIcons” properties

            lookuptypeIcons = ‘/_imgs/ico_16_2.gif:/_imgs/ico_16_8.gif’;

lookuptypenames = ‘contact:2:Contact,systemuser:8:User’;

lookuptypes = ‘2,8’;

crmForm.all.requiredattendees.setAttribute(“lookuptypes”, lookuptypes);

crmForm.all.requiredattendees.setAttribute(“lookuptypenames”, lookuptypenames);

crmForm.all.requiredattendees.setAttribute(“lookuptypeIcons”, lookuptypeIcons);


XrmServiceToolkit for CRM 2011

XrmServiceToolkit is a JavaScript library which can be used for JavaScript Development under the platform for CRM 2011 environments.

Download from Codeplex link

It contains single jscirpt file “XrmServiceToolkit.js

The library contains three major parts regarding functions.

  • Common: General Methods used for various purpose.
  • Rest: Organization Data Service functions including CRUD, Associate, Disassociate, etc
  • Soap: Organization Service functions including CRUD, Fetch, Associate, Disassociate, etc


Activate or Deactivate record using jscript


Below is the script to Activate or Deactivate record using jscript.

// ‘State’  – Activate 0; InActive 1

// ‘Status’ – Active 1; InActive 2

function ActivateOrDeactivate(entityName, entityId, status, state) {

var setStateRequest = ‘<s:Envelope xmlns:s=”“>’ +

‘<s:Body>’ +

‘<Execute xmlns=”” xmlns:i=”“>’ +

‘<request i:type=”a:UpdateRequest” xmlns:a=”“>’ +

‘<a:Parameters xmlns:b=”“>’ +

‘<a:KeyValuePairOfstringanyType>’ +

‘<b:key>EntityMoniker</b:key>’ +

‘<b:value i:type=”a:EntityReference”>’ +

‘<a:Id>’ + entityId + ‘</a:Id>’ +

‘<a:LogicalName>’ + entityName + ‘</a:LogicalName>’ +

‘<a:Name i:nil=”true”></a:Name>’ +

‘</b:value>’ +

‘</a:KeyValuePairOfstringanyType>’ +

‘<a:KeyValuePairOfstringanyType>’ +

‘<b:key>State</b:key>’ +

‘<b:value i:type=”a:OptionSetValue”>’ +

‘<a:Value>’ + state + ‘</a:Value>’ +

‘</b:value>’ +

‘</a:KeyValuePairOfstringanyType>’ +

‘<a:KeyValuePairOfstringanyType>’ +

‘<b:key>Status</b:key>’ +

‘<b:value i:type=”a:OptionSetValue”>’ +

‘<a:Value>’ + status + ‘</a:Value>’ +

‘</b:value>’ +

‘</a:KeyValuePairOfstringanyType>’ +

‘</a:Parameters>’ +

‘<a:RequestId i:nil=”true”></a:RequestId>’ +

‘<a:RequestName>SetState</a:RequestName>’ +

‘</request>’ +

‘</Execute>’ +

‘</s:Body>’ +


var req = new XMLHttpRequest();

var serverUrl = Xrm.Page.context.getServerUrl();“POST”, serverUrl, false);

req.setRequestHeader(“Content-Type”, “text/xml; charset=utf-8”);

req.setRequestHeader(“SOAPAction”, ““);


if (req.status != 200) {

alert(“Error while set status – “+req.responseXML);



How Do I call this method :-

  • Below is the sample to activate “Contact” record

var contactId={contact GUID};

ActivateOrDeactivate(“contact”, contactId, 0, 1);


Object doesn’t support this property or method XMLHttpRequest error – FIX


I was getting “object doesn’t support this property or method jquery” error when I was initializing

var request = new XMLHttpRequest();

Reason :-

  • This is a problem with Internet Explorer browser (ActiveX to be precise)

Fix :-

  • If the browser is detected as Internet Explorer, load ActiveX instead of XMLHttpRequest
  • Below condition check would solve the problem

var request;

if ($.browser.msie) {

request = new ActiveXObject(“Microsoft.XMLHTTP”);

} else {

request = new XMLHttpRequest();