Tuesday, December 29, 2009

Retrieve Method Using JScript

Hi,
Here is an example to retrieve data only in Client Side

// Prepare variables for a contact to retrieve.
var contactid = "4696f8cb-9a1c-dd11-ad3a-0003ff9ee217";
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>"+
"<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"+
"<entityName>contact</entityName>"+
"<id>"+contactid+"</id>"+
"<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>"+
"<q1:Attributes>"+
"<q1:Attribute>fullname</q1:Attribute>"+
"</q1:Attributes>"+
"</columnSet>"+
"</Retrieve>"+
"</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/Retrieve");
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);
}
// Display the retrieved value.
else
{
alert(resultXml.selectSingleNode("//q1:fullname").nodeTypedValue);
}
The following is an example of a successful response:

<?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">
<soap:Body>
<RetrieveResponse xmlns="http://schemas.microsoft.com/crm/2007/WebServices">
<RetrieveResult xmlns:q1="http://schemas.microsoft.com/crm/2007/WebServices" xsi:type="q1:contact">
<q1:fullname>Jesper Aaberg</q1:fullname>
<q1:contactid>{4696F8CB-9A1C-DD11-AD3A-0003FF9EE217}</q1:contactid>
<q1:owningbusinessunit>{0EA35030-3EC9-DC11-A8D2-0003FF9EE217}</q1:owningbusinessunit>
</RetrieveResult>
</RetrieveResponse>
</soap:Body>
</soap:Envelope>

Enjoy,
Rami Heleg