Tuesday, December 29, 2009

Run Fetch Method using java script

Hi,
Here is an example to execute fetch only in Client Side

// Prepare variables to fetch accounts.
var fetchMapping = "logical";
var entityName = "account";
var firstColumn = "accountid";
var secondColumn = "name";
var linkEntity = "systemuser";
var linkEntityTo ="owninguser";
var filterType = "and";
var conditionAttribute = "lastname";
var operator = "ne";
var value = "Cannon";
var authenticationHeader = GenerateAuthenticationHeader();

// Prepare the SOAP message.
var xml = "<?xml version='1.0' encoding='utf-8'?>"+
"<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'"+
" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"+
" xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"+
authenticationHeader+
"<soap:Body>"+
"<Fetch xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"+
"<fetchXml><fetch mapping='"+fetchMapping+"'>"+
"<entity name='"+entityName+"'>"+
"<attribute name='"+firstColumn+"'/>"+
"<attribute name='"+secondColumn+"'/>"+
"<link-entity name='"+linkEntity+"' to='"+linkEntityTo+"'>"+
"<filter type='"+filterType+"'>"+
"<condition attribute='"+conditionAttribute+"'"+
" operator='"+operator+"' value='"+value+"'/>"+
"</filter>"+
"</link-entity>"+
"</entity>"+
"</fetch></fetchXml>"+
"</Fetch>"+
"</soap:Body>"+
"</soap:Envelope>";
// Prepare the xmlHttpObject and send the request.
var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xHReq.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Fetch");
xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xHReq.setRequestHeader("Content-Length", xml.length);
xHReq.send(xml);
// Capture the result.
var resultXml = xHReq.responseXML;

// Check for errors.
var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0)
{
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);
}

Enjoy,
Rami Heleg