Archive

Archive for the ‘JScript’ Category

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″ ?>

<Fruits>

<Fruit Code=”App”>

<Name>Apple</Name>

<Price>20</Price>

</Fruit>

<Fruit Code=”Orng”>

<Name>Orange</Name>

<Price>10</Price>

</Fruit>

</Fruits>

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”;

$.ajax({

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)

Solution

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

Implementation

  • 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” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head>

    <title></title>

    <script type=”text/javascript”>

        document.onreadystatechange = function () {

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

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

                getDataParam();

            }

        }

        function getDataParam() {

            var vals = new Array();

            // The parameters we pass comes as query string

            // Read it using “location.search”

            if (location.search != “”) {

                vals = location.search.substr(1).split(“&”);

                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)”

                        parseDataValue(vals[i][1]);

                        break;

                    }

                }

            }

        }

        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 = window.parent.Xrm.Page.data.entity.attributes.get(eval(email_schmaname)).getValue();

                var city = window.parent.Xrm.Page.data.entity.attributes.get(eval(city_schmaname)).getValue();

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

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

            }

        }

    </script>

</head>

<body>

</body></html>

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.

Subgrid

Subgrid

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) {

                    window.parent.location.reload(true);

            }

        }

        // Wait 1 second and then call same function again    

        setTimeout(‘refreshGrids()’, 1000);

    }

return;

}

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 “window.open” 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 “window.open” to open form or web resource from CRM online/Outlook client

Xrm.Utility

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”

Xrm.Utility.openWebResource(“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();

RetrieveUserSetting.open(“GET”, oDataEndpointUrl + “/UserSettingsSet(guid'” + UserID + “‘)”, true);

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

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

RetrieveUserSetting.onreadystatechange = function () {

callBackFunction(this);

};

RetrieveUserSetting.send();

} catch (e) {

alert(“Error on RetrieveUserSettings method”);

}

}

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

RetrieveUserSettings(RetrieveUserSettingCallBack);

  • 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

dateValue.setMinutes(actMinutes);

alert(“Exact datetime – ” + dateValue);

}

}

} catch (e) {

alert(e.Description);

}

}

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 http://xrmservicetoolkit.codeplex.com/

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

Hi,

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=”http://schemas.xmlsoap.org/soap/envelope/“>’ +

‘<s:Body>’ +

‘<Execute xmlns=”http://schemas.microsoft.com/xrm/2011/Contracts/Services” xmlns:i=”http://www.w3.org/2001/XMLSchema-instance“>’ +

‘<request i:type=”a:UpdateRequest” xmlns:a=”http://schemas.microsoft.com/xrm/2011/Contracts“>’ +

‘<a:Parameters xmlns:b=”http://schemas.datacontract.org/2004/07/System.Collections.Generic“>’ +

‘<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>’ +

‘</s:Envelope>’;

var req = new XMLHttpRequest();

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

req.open(“POST”, serverUrl, false);

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

req.setRequestHeader(“SOAPAction”, “http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute“);

req.send(setEntityStateRequest);

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

Hi,

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();

}

🙂

Checking whether user part of team using jscript CRM 2011

June 23, 2012 2 comments

Hi,

We can verify whether the User is part of particular Team using jscript.

Below is the jscript function

function isUserPartOfTeam(userId, teamId) {

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

oDataEndpointUrl += “TeamMembershipSet?$select=BusinessUnitId&$filter=TeamId eq guid'” + teamId + “‘ SystemUserId eq guid'” + userId + “‘”;

var service = GetRequestObject();

if (service != null) {

service.open(“GET”, oDataEndpointUrl, false);

service.setRequestHeader(“X-Requested-Width”, “XMLHttpRequest”);

service.setRequestHeader(“Accept”, “application/json,text/javascript, */*”);

service.send(null);

var requestResults = eval(‘(‘ + service.responseText + ‘)’).d;

if (requestResults != null && requestResults.results.length > 0) {

return true;

}

}

return false;

}

How do I call this method :-

  • Pass User Id & Team Id to the function.
  • Function returns true/false

var userId={User GUID};

var teamId={Team GUID};

var flag= isUserPartOfTeam(userId, teamId);

🙂