Friday, July 22, 2011

Using OData Service with Dynamics CRM 2011

Microsoft Dynamics CRM 2011 provides developers with different options to query data. The Open Data Protocol (OData) is one of the Query options provided by Dynamics CRM 2011 and enables the creation of REST-based data services, which allow resources, identified using Uniform Resource Identifiers (URIs) and defined in a data model, to be published and edited by Web clients using simple HTTP messages.

The following lists the query string options defined in the OData protocol that are implemented in the REST endpoint for Microsoft Dynamics CRM.

Option Description
$expand : Directs that related records should be retrieved in the record or collection being retrieved.
$filter : Specifies an expression or function that must evaluate to ‘true’ for a record to be returned in the collection.
$order : Determines what values are used to order a collection of records.
$select : Specifies a sub set of properties to return.
$skip : Sets the number of records to skip before it retrieves records in a collection.
$top : Determines the maximum number of records to return.

The following code illustrates how the OData Service is used to connect and query the data.

raise the request and return the value.
function RetrieveData(url) {

var org = Xrm.Page.context.getOrgUniqueName()
var oDataEndpointUrl = "/" + org + "/XRMServices/2011/OrganizationData.svc/";
oDataEndpointUrl += url;

var service = GetRequestObject();
if (service != null) {"GET", oDataEndpointUrl, false);
service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
service.setRequestHeader("Accept", "application/json, text/javascript, */*");
// alert(service.responseText);
var results = eval('(' + service.responseText + ')').d;
return results;

// Create the XMLHTTP Object
function GetRequestObject() {
if (window.XMLHttpRequest) {
return new window.XMLHttpRequest;
else {
try {
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
catch (ex) {
return null;

// OData Query to get Parent Customer Corporate
function getParentCorporate(contactid) {
var url = "ContactSet?$select=ParentCustomerId&$filter=ContactId eq (guid'" + contactid+ "')";
var vaParentCustomerId = RetrieveData(url);
if (vaParentCustomerId.results != null && vaParentCustomerId.results != "")
return vaParentCustomerId.results[0].ParentCustomerId;
return null;

While building the URI, make sure you use the Schema Name to define the attributes and entities in CRM and the URI is case sensitive.

You can test the URI using the IE by posting the URI and it will return the result on IE.

Hope this helps you all. Good Luck!