Friday, June 15, 2012

Synchronous Retrieve Query

Previously I provided an approach for constructing retrieve queries in CRM 2011. That approach used an asyncronous technique for running the query. That is, the form jscript does not wait for the results of the query to be obtained but instead continues to process with the query being executed in a separate thread. The benefit to this kind of approach is improved performance. For example, if a form field needs to be set then in most cases using an aysnchronous query should work (as long as that query doesn't take too long to execute).

However in many cases it is also necessary to run such queries syncronously in order to accomodate dependency logic in the jscript. The following provides a technique for constructing the synchronous version of this query (please refer to prerequisites mentioned in my previous post).

First of all place the following function into one of your form jscript resources:

function retrieveEntityByIdSync(entity,entityid,fields) {

    try {
		var context = Xrm.Page.context;
		var serverUrl = context.getServerUrl();
		var query = new XMLHttpRequest();
		var oDataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc/" + entity + "Set(guid'" + entityid + "')" + fields + "";'GET', oDataSelect, false);
		query.setRequestHeader("Accept", "application/json");
		query.setRequestHeader("Content-Type", "application/json; charset=utf-8");
		return JSON.parse(query.responseText).d;
	} catch (e) {
		alert("Retrieve multiple failed to return results");


The next step is to call the above function to retrieve the values you are looking for by passing the following parameters:
  • entity - the entity logical name e.g. Product, Contact, Account
  • entityid - the id of the passed in entity
  • fields - you wish returned from the retrieve query. NB: These are case sensitive so be sure to ensure to check how they are defined on the entity. You also can use the OData Query tool to get the syntax. Errors encountered with configuring this are most likely to be in this area.

For example, the following will retrieve the first and last name from the system user entity using a synchronous query:

	var e1 = retrieveEntityByIdSync("SystemUser",Xrm.Page.context.getUserId(),"?$select=FirstName,LastName");


  1. Thanks for sharing your technique, I hope it could be helpful to me. I am very glad to have this code.

  2. No problem. Hope it comes in handy.