My blog has moved!

Please visit
http://crmdude.wordpress.com/
and update your bookmarks.

Wednesday, 4 February 2009

Performing a Javascript Web Service call to the Metadata Service

About a week ago a colleague of mine told me that he'd been able to use my JS script to retrieve fields from a related record upon the change of a lookup value- which worked exactly as he wanted. However, one of the fields he retrieved was a Picklist value- which was obviously a numeric value and pretty pointless since the field he was displaying the value in was nvarchar.

He had three options;

1) Hard code the text values for each option value in his code (yeah, right!),

2) Create a picklist with the same values (text and numeric) as the source picklist and ensure that his documentation clearly outlines that the two picklists will forever have to kept in sync (umm, no thanks),

3) Perform a web service call to the Metadata service and retrieve the options for the source picklist (!).

So I decided to put together the JavaScript code to achieve (3). In the example below, I'm retrieving the accountcategorycode field from the Account entity.



var request = "" +
"<?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\">" +
GenerateAuthenticationHeader() +
" <soap:Body>" +
" <Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <Request xsi:type=\"RetrieveAttributeRequest\">" +
" <MetadataId>00000000-0000-0000-0000-000000000000</MetadataId>" +
" <EntityLogicalName>account</EntityLogicalName>" +
" <LogicalName>accountcategorycode</LogicalName>" +
" <RetrieveAsIfPublished>false</RetrieveAsIfPublished>" +
" </Request>" +
" </Execute>" +
" </soap:Body>" +
"</soap:Envelope>" +
"";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

xmlHttpRequest.Open("POST", "/mscrmservices/2007/MetadataService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Execute");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", request.length);
xmlHttpRequest.send(request);

var result = xmlHttpRequest.responseXML;
alert(result.xml);


Hope that helps somebody out there!

2 comments:

  1. Great timing as this is just what I was after, however I'm getting SOAP errors typing to process this code. Server-side trace tells me:
    InnerException: System.ArgumentNullException: Value cannot be null.
    Parameter name: request

    Any ideas?

    g.

    ReplyDelete
  2. Hi, upon closer inspection of the code (the XML fragment in particular) I realised that Blogger had added extra characters in some places and removed some other words/characters. I've posted an HTML friendly now (and tested to make sure it works!).

    Hope that helps.

    ReplyDelete