CRM 2011 – using Javascript intellisense and Testpage.htm

I have been doing some Javascript development this past couple of days and although I have been using the CRM development toolkit it was more focused on plugins rather than writing javascript.

I then noticed a folder in the CRM 2011 SDK called templates and in there was a folder called xrm.pagescriptprojejcttemplate, this has been blogged about by the Microsoft team and you can read their version here or continue reading mine

CRM 2011\sdk\templates\xrm.pagescriptprojecttemplate

interesting.

There was a readme file with instructions on how to setup the project.

I won’t go through it all here because the readme file does a great job of going through setting up the project step by step.

There are a number of parts to the solution.

It has a visual studio template which creates XmlPageJScriptLibrary project.

This project creates a few pages but the most important ones are

XrmPageTemplate.js

The js script above has the functionality to add intellisense for the Xrm.Page commands.

For any new Javascript files you create you add a reference to this file and then when you type in Xrm you get intellisense for it.

You add the reference by adding the line to the top of your Javascript file

/// <reference path=”XrmPageTemplate.js” />

Now this is one part of the solution, which when you think about it has involved a good work around by the Microsoft team to come up with a solution.

You now have the Xrm.Page intellisense and now you need the intellisense for the entities and especially your entities, so you can access your custom variables you have added to entities.

There is a solution project you need to import into your organisation.

What this does is add a button onto all the Forms in CRM.  The button is XrmPagesnapshot is used to create the snapshot of your form for either onLoad, OnSave or onChange of a variable.

You go to customize on the entity form you want to write some Javascript for, you then press the XRM Page snapshot button.  This pops up a form and you can then copy the code to clipboard.

You then take this code and paste it into a file into you visual studio XRMPAge project into a file called PageData.js

The XrmPage Project has a TestPage.htm which allows you to test your code.

The TestPage is a nice way to test the code quickly.  The snapshot creates the variables in the state you took the snapshot.

So in my case I writing a function to test when a drop down was a certain value.  I could use the the testPage to test my function, it would open the function and the values of the variables would be set to the snapshot.

This means you don’t have to keep uploaded and publishing.

The only downside is we still don’t have proper intellisense for the entites unlike the workaround in CRM 4 – http://crm.vdsnickt.eu/ms-crm-javascript-intellisense-generator/

but its better than nothing.

Also the snapshot code does generate all the variables for you to look at, this means you can see all the variables and their potential values.  Below is dropdown I have with two values, property and person.  Below you can see the values and the int number for the dropdown.  This alone could save you some time.  Combined with the functionality of being able to quickly test this using the testPage.html makes Javascript development a bit easier.

{ “Name”: “meta_contacttype”, “Value”: 951850000, “Type”: “optionset”, “Format”: null, “IsDirty”: false, “RequiredLevel”: “none”, “SubmitMode”: “dirty”, “UserPrivilege”: { “canRead”: true, “canUpdate”: true, “canCreate”: true }, “InitialValue”: 951850000, “Options”: [{ “text”: “Property”, “value”: 951850000 }, { “text”: “Person”, “value”: 951850001}], “SelectedOption”: { “option”: “Property”, “value”: 951850000 }, “Text”: “Property”, “Controls”: [{ “Name”: “meta_contacttype”}] }

 

Overall I think the most useful part is the XrmPageTemplate.js file which I think you can use even without the whole javascript intellisense project.

The way Javascript works in CRM makes it very difficult to create proper intellisense.  I think what would be useful is perhaps code shortcuts and Javascript validation.

 

CRM 2011 – Javascript to update variables only on Create

[tweetmeme source=”BenHosk” only_single=false]

I had an interesting problem, I wanted to default a drop downlist on an onload event but only if the user was creating a new contact.

The reason I wanted it only for a create is because it would overwrite the value of the variable if I had it on the onload event of the contact because my drop down list had two values and no unassigned value.

http://msdn.microsoft.com/en-us/library/0375b206-d2bf-4034-a41d-fb476ecb4438#BKMK_getFormType

getFormType

Indicates the form context for the record.

Xrm.Page.ui.getFormType()
Return Value
Type: Number
The following table lists the form types that correspond to the return value.
Value Form Type
0 Undefined
1 Create
2 Update
3 Read Only
4 Disabled
5 Quick Create (Deprecated)
6 Bulk Edit

Example: The SDK.UISamples.getFormType alerts the user with a different message depending on the current form type.

getFormType: function () {

 var FORM_TYPE_CREATE = 1;
 var FORM_TYPE_UPDATE = 2;
 var FORM_TYPE_READ_ONLY = 3;
 var FORM_TYPE_DISABLED = 4;
 var FORM_TYPE_QUICK_CREATE = 5;
 var FORM_TYPE_BULK_EDIT = 6;

 var formType = Xrm.Page.ui.getFormType();
 if (formType == FORM_TYPE_CREATE) {
  alert("This record has not yet been created.");
 }
 else {
  alert("This record exists in the database.");
 }
},

CRM 2011 Solution – Shrpr Web Resource Editor

The file editor when editing Web Resources is as basic as they come in CRM 2011 (and all the previous versions).  It would be such a nice gesture for Microsoft to create an editor with a few basic features like syntax checking and formatting.

Microsoft have yet to do anything in this area so one someone got bored of waiting and has started the process by creating the Shrpr Web Resource Editor.   You can read more about the editor in this blog post and you can download the solution (a CRM solution which you can import) here  Downloads 

It has features like

Syntax highlighting

Line numbering

matching braces

simple code completion

 

When I imported the solution I couldn’t figure out where the editor was or if it did anything, this was because I went into a form and tried editing some Javascript.  Unfortunately there isn’t any documentation yet so you have to figure it out yourself.  After reading the title again, I went to Web Resource and then clicked on some javascript, you then see there isa new button on the top right to open the web resource with the editor.   Below is a screenshot

 

I think this is a really good start because syntax highlighting is very useful and the matching braces is fantastic.  Hopefully if people start using it and giving some feed back he will continue to work on the product.

So thanks Roman Gebesmair and keep up the good work

 

CRM 2011 – Getting the ServerUrl in Javascript and using Xrm.page

Whilst I was developing I had hard coded the serverUrl which I then used whilst doing an oData query.

So when I moved the code from the Dev system to production for the first time, my trusty Javascript stopped working.  I know you shouldn’t hard code stuff like this and I had only done it in development to get oData working.

The quick answer for those of you who have Googled your way to my blog, is you use the Xrm.page.context and use the method getServerUrl();  This will return you the url, including the organisation.  After that all you have to do is paste the oData address.

var serverUrl = Xrm.Page.context.getServerUrl();
var GlobalODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";

this is the code I used to do the oData call
function retrieveUserRecord(Id) {

var select = "/SystemUserSet?$select=InternalEMailAddress&$filter=SystemUserId eq guid'" + Id + "'";

    ///SystemUserSet?(guid'4d82f1fc-262e-e011-9645-00155d106b02')
    showMessage("retrieveUserRecord function START");
    var retrieveUserReq = new XMLHttpRequest();
    retrieveUserReq.open("GET", GlobalODataPath + select, true);
    retrieveUserReq.setRequestHeader("Accept", "application/json");
    retrieveUserReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    retrieveUserReq.onreadystatechange = function () {
        retrieveUserReqCallBack(this);
    };
    retrieveUserReq.send();
    // showMessage("retrieveAccountRecord function END.");
    showMessage("retrieveAccountRecord function END.");
}

function retrieveUserReqCallBack(retrieveUserReq) {
    if (retrieveUserReq.readyState == 4 /* complete */) {
        if (retrieveUserReq.status == 200) {
            //Success
            var retrievedUser = JSON.parse(retrieveUserReq.responseText).d;
            showMessage("ACTION: Retrieved email address = \"" + retrievedUser.results[0].InternalEMailAddress);
            setValuesIFrameQueryString(retrievedUser.results[0].InternalEMailAddress);
        }
        else {
            //Failure
            showMessage("retrieveAccountReqCallBack function failure END");

        }
    }

}

Although the initial change from CRM 4 to CRM 2011 Javascript has a steep learning curve, once you are get used to it the CRM 2011 is I think better than CRM 4.  One of the cool new features is the Xrm.page object.  This is a object which Microsoft generate and fill with lots of lovely variables and methods.

It has three useful parts to it.  What I really like is the separation Microsoft has done here, it’s logical and easy to use.

Xrm.Page.context
Xrm.Page.context provides methods to retrieve information specific to an organization, a user, or parameters that were passed to the form in a query string
Xrm.Page.data.entity
Xrm.Page.data provides an entity object that provides collections and methods to manage data within the entity form
Xrm.Page.ui
Xrm.Page.ui provides collections and methods to manage the user interface of the form.
Out of the the three the one I use the most is Xrm.page and it has some great methods to get default/organisational information from.
  • getAuthenticationHeader: Returns the encoded SOAP header necessary to use Microsoft Dynamics CRM 4.0 Web service calls usingJScript.
  • getCurrentTheme Returns a string representing the current Microsoft Office Outlook theme chosen by the user.
  • getOrgLcid: Returns the LCID value that represents the Microsoft Dynamics CRM Language Pack that is the base language for the organization.
  • getOrgUniqueName: Returns the unique text value of the organizations name.
  • getQueryStringParameters: Returns an array of key value pairs representing the query string arguments that were passed to the page.
  • getServerUrl: Returns the base server URL. When a user is working offline with the Microsoft Dynamics CRM for Microsoft Office Outlook client, the URL is to the local Microsoft Dynamics CRM Web services.
  • getUserId: Returns GUID value of the SystemUser.id value for the current user.
  • getUserLcid: Returns the LCID value that represents the Microsoft Dynamics CRM Language Pack that is the user selected as their preferred language.
  • getUserRoles: Returns an array of strings representing the GUID values of each of the security roles that the user is associated with.
  • isOutlookClient: Returns a Boolean value indicating if the user is using the Microsoft Dynamics CRM for Microsoft Office Outlook client.
  • isOutlookOnline: Returns a Boolean value indicating whether the user is connected to the Microsoft Dynamics CRM server while using the Microsoft Dynamics CRM for Microsoft Office Outlook with Offline Access client. When this function returns false, the user is working offline without a connection to the server. They are interacting with an instance of Microsoft Dynamics CRM running on their local computer.
  • prependOrgName: Prepends the organization name to the specified path.

CRM 2011 – Javascript and Subgrids code example

Someone posted a comment on my blog asking about Javascript and subgrids.  Although I don’t yet need to do anything with Javascript and subgrids I thought I would.  It certainly shows the benefit of Microsoft having forums for CRM problems.

Firstly the question is how to get the values from a subgrid, I found this good forum post and the Javascript is below

You can inspect the subgrid values on save by doing the following:

var gridControl = document.getElementById('subgrid_id').control; 
var ids = gridControl.get_allRecordIds(); 
 for(i = 0; i < ids.length; i++) 

 var cellValue = gridControl.getCellValue('column_name', ids[i]); 
 // logic 
 } 

Doing this on load is a bit more challenging since subgrids are loaded asynchronously and aren’t likely to be done loading when the form onload event fires. You can check the grid periodically though to see when it’s done loading by calling a function like the following in your form onload:

function subGridOnload() 

var grid = document.getElementById('grid_identifications'); 
 if (grid.readyState!="complete") 

 // delay one second and try again. 
 setTimeout(subGridOnload, 1000); 
 return; 

// logic 
}

I then also found a forum post on attaching events to a subgrid, which you can read here

For CRM 2011, your code should look like this:

if (Xrm.Page.ui.getFormType() != 1) {

  Xrm.Page.ui.controls.get("IFRAME_OpportunityLines").setSrc(GetFrameSource("fj_opportunity_new_opportunitymanagementmodu"));;
  Xrm.Page.ui.controls.get("IFRAME_OpportunityLines").onreadystatechange = function oppLineTotals() {
    if (Xrm.Page.ui.controls.get("IFRAME_OpportunityLines").readyState == 'complete') {
      var iFrame = frames[window.event.srcElement.id];
      iFrame.document.all.crmGrid.attachEvent("onrefresh", GridRefresh);
    }
  }
}

Funny thing, the sdk recomended function did not work for me (i.e. Xrm.Page.ui.controls.get(“GridName”) ), and yet the following works (tested!)

var grid = document.getElementById("GridName");
grid.attachEvent("onrefresh", EventHandlerFunction);

because the grid.htc (Html Component) actually includes a public event “onrefresh”… And this event can be handled with any function. We dont need to dive into the eventManager and scriptEvents.

CRM 2011 – How to set focus using Javascript

I had a coding problem today, I was doing some validation in Javascript and then wanted to set the focus on the area.  You can also use this code on the page load if you want to set a default field to start with

var control = Xrm.Page.ui.controls.get(“AttributeName”);

control.setFocus();

CRM 2011 – How to execute Fetch XML in Javascript

[tweetmeme source=”BenHosk” only_single=false]

The chaps over at Customer Effective blog have written a really interesting blog post this week.  It’s called

Execute Fetch from Javascript in CRM 2011

They actually also wrote an interesting article about why Microsoft buying skype made sense, which you can read here, I found this interesting because I was thinking Microsoft had completely overpaid but then the article  mentions skype have 636 million users, Microsoft paid $8.6 billion and that works out at $14.70 per/user price.  Now that’s not much for each users and you would probably think that skype is going to grow the number of users it has.  You can see Microsoft bundling skype in with Xbox, CRM and office etc.  The last thought I had was Microsoft has money burning a hole in it’s pocket.  The only danger is that someone else/Google could create a skype competitor but then I thought the same about youtube when google brought that and it seems to be working out ok.

Anyway I’m here to talk about Javascript running fetch xml.  The article has some neat javascript, so neat that I read it about 4 times, thinking that is nice and simple (like all good code).

below is the code from the blog.   Brilliant blog entry and if you are interesting in CRM 2011 then you really should subscribe to the Customer Effective Blog because it is one of the best CRM blogs out there, go on go and subscribe here.

FetchUtil.js

var XMLHTTPSUCCESS = 200;
var XMLHTTPREADY = 4;

function FetchUtil(sOrg,sServer)
{
this.org = sOrg;
this.server = sServer;

if (sOrg == null) {
if (typeof(ORG_UNIQUE_NAME) != “undefined”) {
this.org = ORG_UNIQUE_NAME;
}
}

if (sServer == null){
this.server = window.location.protocol + “//” + window.location.host;
}
}

FetchUtil.prototype._ExecuteRequest = function(sXml, sMessage, fInternalCallback, fUserCallback)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open(“POST”, this.server + “/XRMServices/2011/Organization.svc/web”,(fUserCallback!=null));
xmlhttp.setRequestHeader(“Accept”, “application/xml, text/xml, */*”);
xmlhttp.setRequestHeader(“Content-Type”, “text/xml; charset=utf-8”);
xmlhttp.setRequestHeader(“SOAPAction”, “http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute“);

if (fUserCallback!=null)
{
//asynchronous: register callback function, then send the request.
var crmServiceObject = this;
xmlhttp.onreadystatechange = function(){ fInternalCallback.call(crmServiceObject,xmlhttp,fUserCallback) };
xmlhttp.send(sXml);
}
else
{
//synchronous: send request, then call the callback function directly
xmlhttp.send(sXml);
return fInternalCallback.call(this,xmlhttp,null);
}
}

FetchUtil.prototype._HandleErrors = function(xmlhttp)
{
/// <summary>(private) Handles xmlhttp errors</summary>
if (xmlhttp.status != XMLHTTPSUCCESS) {
var sError = “Error: ” + xmlhttp.responseText + ” ” + xmlhttp.statusText;
alert(sError);
return true;
} else {
return false;
}
}

FetchUtil.prototype.Fetch = function(sFetchXml, fCallback)
{
/// <summary>Execute a FetchXml request. (result is the response XML)</summary>
/// <param name=”sFetchXml”>fetchxml string</param>
/// <param name=”fCallback” optional=”true” type=”function”>(Optional) Async callback function if specified. If left null, function is synchronous </param>
var request = “<s:Envelope xmlns:s=\”http://schemas.xmlsoap.org/soap/envelope/\“>”;
request += “<s:Body>”;

request += ‘<Execute xmlns=”http://schemas.microsoft.com/xrm/2011/Contracts/Services“>’ +
‘<request i:type=”b:RetrieveMultipleRequest” ‘ +
‘ xmlns:b=”http://schemas.microsoft.com/xrm/2011/Contracts“‘ +
‘ xmlns:i=”http://www.w3.org/2001/XMLSchema-instance“>’ +
‘<b:Parameters xmlns:c=”http://schemas.datacontract.org/2004/07/System.Collections.Generic“>’ +
‘<b:KeyValuePairOfstringanyType>’ +
‘<c:key>Query</c:key>’ +
‘<c:value i:type=”b:FetchExpression”>’ +
‘<b:Query>’;

request += CrmEncodeDecode.CrmXmlEncode(sFetchXml);

request += ‘</b:Query>’ +
‘</c:value>’ +
‘</b:KeyValuePairOfstringanyType>’ +
‘</b:Parameters>’ +
‘<b:RequestId i:nil=”true”/>’ +
‘<b:RequestName>RetrieveMultiple</b:RequestName>’ +
‘</request>’ +
‘</Execute>’;

request += ‘</s:Body></s:Envelope>’;

return this._ExecuteRequest(request,”Fetch”, this._FetchCallback, fCallback);
}

FetchUtil.prototype._FetchCallback = function(xmlhttp,callback)
{
///<summary>(private) Fetch message callback.</summary>
//xmlhttp must be completed
if (xmlhttp.readyState != XMLHTTPREADY)
{
return;
}

//check for server errors
if (this._HandleErrors(xmlhttp))
{
return;
}

var xmlReturn = xmlhttp.responseXML.xml;
xmlReturn = xmlReturn.replace(/</g, ‘&lt;’);
xmlReturn = xmlReturn.replace(/>/g, ‘&gt;’);

results = xmlReturn;

//return entity id if sync, or call user callback func if async
if (callback != null)
{
callback(results);
}
else
{
return results;
}
}

fetchExample.htm

<html>
<head>
<title>Fetch 2011 JavaScript Example</title>
<link rel=”stylesheet” type=”text/css” href=”/_common/styles/theme.css.aspx” />
<link rel=”stylesheet” type=”text/css” href=”/_common/styles/global.css.aspx” />
<link rel=”stylesheet” type=”text/css” href=”/_common/styles/fonts.css.aspx” />
<link rel=”stylesheet” type=”text/css” href=”/_common/styles/Dialogs.css.aspx” />

<script src=”ClientGlobalContext.js.aspx”></script>
<script src=”{pub}_FetchUtil.js”></script>

<script type=”text/javascript”>

var _oService;
var _sOrgName = “”;
var _sServerUrl = “https://{org}.api.crm.dynamics.com”;
function executeFetchCommand()
{

var sFetch = document.getElementById(‘txtFetch’).value;
_oService = new FetchUtil(_sOrgName, _sServerUrl);
var oEntity = _oService.Fetch(sFetch, myCallBack);
}

function myCallBack(results){
var sOut = “”;
sOut += “<b>XML Response</b><br />”;
sOut += results;
document.getElementById(‘dvData’).innerHTML = sOut;
}

</script>

</head>
<body>
<table style=”width: 100%; height: 100%;” cellspacing=”0″ cellpadding=”0″ border=”0″>
<tr>
<td id=”tdDialogHeader”>
<div id=”divTitle”>Executing Fetch from JavaScript in CRM 2011</div>
<div id=”divInstructions”>Enter some FetchXML to be executed against your CRM environment</div>
</td>
</tr>
<tr>
<td style=”height: 100%;”>
<div style=”padding: 14px;”>
<label>Fetch Command</label><br />
<textarea id=”txtFetch” rows=”8″ width=”100%” cols=”100″ ></textarea><br />
<input type=”Submit” value=”Fetch” onClick=”javascript:executeFetchCommand();” style=”width:100px;height:24px;”>
<div id=’dvData’ style=”width: 100%; height: 100%;”></div>
</div>
</td>
</tr>
<tr>
<td id=”tdDialogFooter”>
<table cellspacing=”0″ cellpadding=”0″>
<tr>
<td width=”100%”></td>
<td>&nbsp;<button onclick=”window.close();”>Done</button></td>
</tr>
</table>
</td>
</tr>
</table>

</body>
</html>

Now that we have our JavaScript utility and our Fetch example, we need to do a few things.

  1. We need a solution to put these two files into (feel free to add it to an existing solution or create one named whatever you like).
  2. Let’s now import the FetchUtil.js file and publish. Take note of the Publisher Prefix (the letters in front of the name).
  3. We now need to modify the fetchExample.htm file to point to this FetchUtil.js by replacing the {pub} with your Publisher Prefix (ex. “new_FetchUtil.js”).
  4. We also need to modify the _sServerUrl and change the {org} to the appropriate organization abbreviation. If you are using the onsite, you will need to change the entire URL to match accordingly.
  5. Finally, let’s upload the fetchExample.htm file and publish.

This should now bring you to a super fancy screen to paste some Fetch into.

image

Well there you have it. The next step is to parse the XML with jQuery, RegEx, traversing the nodes, or however you prefer. Hope you enjoy!

CRM 2011 – How to retrieve Users using Javascript

one my favourite CRM bloggers and a very good source of Javascript examples is Jamie Miley, you should definitely check his blog out Life and Technology and subscribe to it.  In fact not only does he consistently write good blog posts but he does it often.

He recently posted a blog post showing how to get users/System Users using Javascript, click on the link below to read the whole thing

How to: Retrieve Users / SystemUsers for an Organization Using Jscript or .NET in Microsoft Dynamics CRM 2011

What I like about Jamie’s blog posts is he shows you the code first in C# and then shows you the code in Javascript.  I’m guessing most CRM developers are C# programmers first and then to use CRM you have to learn the slightly unusual world of scripting and Javascript.  Showing the C# first makes it easier for me to understand the Javascript.

Initially I wondered how useful this code would be especially with CRM 2011 because you can have different forms for different users but then I thought this is the kind of code you don’t realise is useful until you need to do it.  I have also seen recently an example of looking up user roles and if the role was a developer then it would pop a message up warning that testing results will be different because of the extra privileges.

The blog post also had  a useful link to another blog post about parsing Javascript in CRM 2011 compared to CRM 4

http://mileyja.blogspot.com/2011/03/microsoft-dynamics-crm-2011-parsing.html

To borrow a paragraph or two from the blog post above, he describes how the parsing of Javascript has changed from CRM 4 to CRM 2011.  I advise you to read the whole blog post above if you are interested because it goes into a lot more depth than the snippet below

Now let’s look at how this might be parsed. In CRM 4.0 each attribute had it’s own matching tag name so you could just search for the tag and grab the value using the DOM parsar. That is not the case here as each attribute is wrapped in a then the first child node contains the name of the attribute. The following child nodes contain the data associated with the attribute. For an ntext or a number field you will only have two total subkeys, one for the attribute name and one for the value.

This means we can parse out most simple types above using a function like this:

function parseResponse(responseXML, attributename) { 
debugger; xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); 
xmlDoc.async="false"; xmlDoc.loadXML(responseXML); 
x=xmlDoc.getElementsByTagName("a:KeyValuePairOfstringanyType"); 
 for (i=0;i<x.length;i++) { 
 if (x[i].childNodes[0].text == attributename) { 
 //we decode the base 64 contents and alert the HTML of the Iframe 
 alert(x[i].childNodes[1].text); 


} 

Just pass in the xml from the response containing your entity and your attribute you are looking for.

This function iterates through the attributes by grabbing a collection of attributes and walking through them, searches for our “attributename” in the first child node, and if it’s found, alerts our second child node that represents the value for the attribute.

You will notice that in the XML that there are exceptions to this rule. When it comes to a lookup field (called an “entityreference”) type above you have info representing ID (GUID ID Value), Logical name (Type of entity), and value(usually the name attribute of that entity). You also have attributes of type “BooleanManagedProperty” where you have a “CanBeChanged” child node in between the name of the attribute an the value. I am sure there are more examples but here is how to tackle this.

CRM 2011 – Javascript Date Difference Code

The excellent Pogo69 blog, which is an excellent resource for CRM developers has a blog post with a nice piece of Javascript to find the difference between two dates using Javascript.

He mentions that he is starting to build a Javascript library, which thanks to CRM 2011 we can now do because you can use the same Javascript file in many forms.

I am surprised that Microsoft haven’t already created some general Javascript libraries for everyone to use, surely their developers would have already done something like that or at least created enough Javascript to make one.

if (typeof DateLib == 'undefined') {
	DateLib = {};
}

DateLib.Diff = function (from, to) {
	return to - from;
}
DateLib.DiffMinutes = function (from, to) {
	return DateLib.Diff(from, to) / (1000 * 60);
}
DateLib.DiffParts = function (from, to) {
	var diff = DateLib.DiffMinutes(from, to);

	var parts = new Object();

	parts.Days = Math.floor(diff / (60 * 24));
	diff -= (parts.Days * 60 * 24);
	parts.Hours = Math.floor(diff / 60);
	diff -= (parts.Hours * 60);
	parts.Minutes = Math.floor(diff);

	parts.Display =
			(parts.Days > 0 ? parts.Days + " days, " : "") +
			(parts.Hours > 0 ? parts.Hours + " hrs, " : "") +
			(parts.Minutes + " mins");

	return parts;
}

CRM 2011 – Using Javascript to identifying if a form is in Create or Update Context

Here is a quick tip to tell if a form is being created or updated in Javascript, this can be very useful for form load events and creating code which needs to be run when a form is being created, like setting the values of variables when a form is created.

var  formType= Xrm.Page.ui.getFormType();
getFormType() function returns a number
If the return value is 1 –  Form context is Create
If the return value is 2 –  Form context is Update