29 September 2010

Call CRM Web Service From JavaScript

There are instructions about calling the CRM Web Services from JavaScript in the SDK however it is necessary to define the SOAPXml that will be executed. There are several ways to define this SOAPXml:

1. Download and use the "JavaScript Web Service Calls 4.0" tool available from Stunware.

2. If you are calling the CRMService you can turn on tracing, perform the search manually, and retrieve the SOAPXml from the logs.

3. Calling the MetaDataService will not log in the tracing, an alternative to tracing is to use Fiddler. Generate code that will perform the query, turn on Fiddler and execute the code. Fiddler will show the SOAPXml executed.

The SOAPHeader must be setup correctly, to generate from within CRM JavaScript use the following:

var soapHeader = GenerateAuthenticationHeader();

This should then be injected into the SOAPXml.

Sample code (retrieve the objecttypecode from the metadata service:

//Get the servername that the current page was called from.
var fullUrl = location.href;
var slashPos = fullUrl.indexOf('/', 7);
var serverName = fullUrl.substr(7, slashPos - 7);

//Get the authentication header, CRM in built function
var soapHeader = GenerateAuthenticationHeader();

//Define the fetchXML that will get the object type code
var xmlPost = '';
xmlPost += '';
xmlPost += ' ';
xmlPost += soapHeader;
xmlPost += ' ';
xmlPost += ' ';
xmlPost += ' ';
xmlPost += ' 00000000-0000-0000-0000-000000000000';
xmlPost += ' EntityOnly';
xmlPost += ' ' + entityName + '';
xmlPost += ' false';
xmlPost += '
';
xmlPost += '
';
xmlPost += '
';
xmlPost += '
';

//Open the CRM metadata service
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://' + serverName + '/mscrmservices/2007/MetadataService.asmx', false);

//Initialise the call to the web service
xmlhttp.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
xmlhttp.setRequestHeader('SOAPAction', 'http://schemas.microsoft.com/crm/2007/WebServices/Execute');

//Call the metadata service
xmlhttp.send(xmlPost);


var objectTypeCode = '-1';

objectTypeCode = xmlhttp.responseXML.selectSingleNode("//ObjectTypeCode").text;