oData and JScript in CRM 2011

oData and JScript in CRM 2011

Before going through the usage of oData in CRM 2011 first let us understand what is oData and why it is introduced in CRM 2011.

What is oData ?

oData is also referred as Open Data Protocol. CRM 2011 mainly uses Windows Communication Foundation (WCF) data services framework to provide oData Endpoint which is nothing but a REST based data service. The address for the endpoint is:

http://{OrganizationRootUrl} /XRMServices/2011/OrganizationData.svc

Now What is REST ?

REST(Representational State Transfer) is an style of referring data in which every resource can be referenced by a URL mainly in Microsoft CRM. Here resource is nothing but the entity or record or an image etc. So now in CRM 2011 we can reach to the record collection by the URL (properly defined syntax).  Microsoft has provided some syntax styles  which should be followed to access a resource.

oData uses some data  format for sending and receiving the data. Basically it uses the following two formats.

  1. ATOM: It is an Xml based format mainly used for the RSS feeds.
  2. JSON: JavaScript Object Notation is a text formats which makes very easy for the developers to understand the response what we get. For more info please visit:  www.json.org

For eg: For getting all the contact record set the URL can be like

http://{OrganizationRootUrl} /XRMServices/2011/OrganizationData.svc/ContactSet

We can also select few attributes by using a” select “command.

          http://{OrganizationRootUrl} /XRMServices/2011/OrganizationData.svc/ContactSet?$select=FirstName,LastName

This will give a collection of First Name and Last Name for all the contacts. Lot of other stuffs is also possible like filtering, ordering, paging etc.

Now we will see how we can implement in Jscript in CRM 2011. Below is the sample code for fetching the Contact’s PrimaryEmailId form an Account form. Save the code as some js file and upload as a WebResource(Jscript). Refer this in accounts WebResources and call the function OnLoad() in the OnLoad event of account entity.

function OnLoad() {
    var serverUrl = "http://" + window.location.host + "/" + Xrm.Page.context.getOrgUniqueName();
    var primarycontact = Xrm.Page.getAttribute("primarycontactid").getValue();
    var primarycontactid = primarycontact[0].id;

 // Creating the Odata Endpoint
    var oDataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
    var retrieveReq = new XMLHttpRequest();
    var Odata = oDataPath + "/ContactSet?$select=EMailAddress1&$filter=ContactId eq guid'" + primarycontactid + "'";
    retrieveReq.open("GET", Odata, false);
    retrieveReq.setRequestHeader("Accept", "application/json");
    retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    retrieveReq.onreadystatechange = function () { retrieveReqCallBack(this); };

function retrieveReqCallBack(retrieveReq) {
    if (retrieveReq.readyState == 4 /* complete */) {
        var retrieved = this.parent.JSON.parse(retrieveReq.responseText).d;
        var EmailAddress = retrieved.results[0].EMailAddress1;

Test: Create a contact record and put some email id in the Email field. Save the record. Now create one account record and refer this contact in the primarycontact field.  Now whenever you open a account record that has primarycontact the email id will be alerted.      Note: The name of the attributes in the select and the filter criteria are not the actual attributes names but these are the schemas names for that fields so please be careful while referring to the values.Hope this gives a basic idea of oData in CRM 2011…… Happy Reading !!!!!!!!!!!!!!!!!!!!!!!!!!!!!1


, , , ,

  1. #1 by TheeNerd on January 1, 2012 - 2:34 pm

    I have a problem, i want to retrive a value of an attribut with “Lookup type” but is not working , how can i do? i idid exactly as you did, but in my case my EmailAddress is an lookup Field , alert returnn (Object object) and my emailAdress value intern is like
    “Value”: [{ “entityType”: “pricelevel”, “id”: “{71EC7A08-3411-E111-8415-BC305BD0C8E3}”, “name”: “TSF Standardpreise”}], “Type”: “lookup”, “Format”: null,
    and i want to retrive the id of the emailaddress?
    if i say var EmailAddress = retrieved.results[0].EMailAddress1.id; alert will give me undefined?
    how can i retrieve the value of my loookup field?

    • #2 by deepakkumar5035 on January 2, 2012 - 6:47 am

      Are you giving the Schema name correct ? Is your attribute name is EmailAddress or EmailAddress1 Please give the correct name ….and try again …..

      • #3 by TheeNerd on January 2, 2012 - 5:33 pm

        Hi thanks for you reply, you’re right there was an error in my code , the correct answer was var EmailAddress = retrieved.results[0].EMailAddress.Id, thanks for your Post
        Thumbs up

  2. #4 by theenerd on January 6, 2012 - 11:31 am

    Please i have a problem setting the Dafult value of a lookup field when the value of another lookup field change. The value will be set but disspaear immediatly , you can see it if you call an alert() after setting the value . The Vaue will be set and no dissapear when an exception occur after setting the lookup field value. This is a bit weird
    Do you know where bug is comming from i’ve trie everything , Here is the code that set the defaul value wiht an exception

    function sleep(milliSeconds) {
    var startTime = new Date().getTime(); // get the current time
    while (new Date().getTime() < startTime + milliSeconds); // hog cpu
    function GetODataPath() {
    return Xrm.Page.context.getServerUrl() + "/xrmservices/2011/organizationdata.svc";

    function SetLookup(fieldName, idValue, textValue, typeValue) {
    var value = new Array();
    value[0] = new Object();
    value[0].id = idValue;
    value[0].name = textValue;
    value[0].entityType = typeValue;


    //Set the Default Unit for a specific Opportunity Product

    function SetDefaultOpportunityProductUnit() {

    //Get the value or name and Id of the selected Product
    var productItem = Xrm.Page.getAttribute("productid").getValue();
    var Defaultunitname = productItem[0].name;

    //Builld the Filter for the Query
    var filter = "/ProductSet?$select=DefaultUoMId&$filter=Name eq '" + Defaultunitname + "'";

    // Creating the Odata Endpoint Send query and retrieve the result
    function RetrieveDefaultOpportunityProductUnit(filter) {

    var retrieveRecordsReq = new XMLHttpRequest();
    retrieveRecordsReq.open("GET", GetODataPath() + filter, false);
    retrieveRecordsReq.setRequestHeader("Accept", "application/json");
    retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    if (retrieveRecordsReq.readyState == 4 && retrieveRecordsReq.status == 200) {
    var retrievedRecords = this.parent.JSON.parse(retrieveRecordsReq.responseText).d;
    var Result = retrievedRecords.results[0];
    var lookup = new Object();
    var lookupValue = new Array();
    SetLookup("uomid", Result.DefaultUoMId.Id, Result.DefaultUoMId.Name, "uom");
    } else {
    alert("EinFehler ist aufgetreten,Einheit wurde nicht gesetzt");


  3. #5 by theenerd on January 12, 2012 - 2:20 pm

    Please i have one Request can you do a Tutorial about how to automatic set the Default value of an opportunity Product when a Product has been selected? I ve tried everything but is not working
    i m been working since 2 twos week with no improvements
    Your hel will be appreciate

  4. #6 by ashish sharma on March 1, 2012 - 5:47 pm

    Hi i am copy data from another custom entity to main custom entity how to i implement?

    • #7 by deepakkumar5035 on March 2, 2012 - 4:53 am

      Hi Ashish,

      I am not sure whether you want to copy while the form is created but if so, then probably you can write a function for OnLoad event and check whether the form type is create then using the oData you can fetch the data to be copied and then you can set the values in the form.

      Deepak K

  5. #8 by Adam Roberts (@Strawsnake) on August 6, 2012 - 1:41 pm

    Found this very useful. Thank you!

  6. #9 by shaffi on October 4, 2012 - 8:34 am

    Hi Deepak,

    You are a star man, Keep up the good work.

  7. #10 by SamehSenosi on October 30, 2012 - 8:35 am

    Excellent Article Keep going

  8. #11 by Saroj Kumar on November 12, 2012 - 11:30 am

    HI Deepak Your Odata Jscript helped me a lot. Thank you Very much

  9. #12 by Chad on November 26, 2012 - 5:19 pm

    Hi Deepak–will this work over https?

  10. #13 by Eliza on April 24, 2013 - 10:16 pm

    What’s up friends, its enormous post regarding cultureand fully explained, keep it up all the time.

  11. #14 by merchant cash advances on May 12, 2013 - 5:56 am

    Howdy! This blog post could not be written much better!

    Looking through this article reminds me of my previous roommate!
    He continually kept talking about this. I will forward this post to him.
    Fairly certain he’ll have a great read. Thank you for sharing!

  12. #15 by 1stmerchant61i1.thoughts.com on July 11, 2013 - 12:28 pm

    Admiring the persistence you put into your website
    and in depth information you provide. It’s awesome to come across a blog every once in a while that isn’t the same outdated rehashed information.
    Great read! I’ve saved your site and I’m adding your RSS feeds to my Google

  13. #16 by Sharath Somanathan on March 7, 2014 - 4:30 am

    Very nice and easy to understand. Thanks for the post! (-:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: