This is a two part series; we’ll show you how you can write cross browser compatible code using Script# and jQuery.
We’ve shown you our Xrm.Page Script# library in our earlier posts, if you haven’t had a change to look at it yet take a look at the CodePlex project (http://sharpxrmpage.codeplex.com). Also see the introduction blog post by Paul http://www.magnetismsolutions.com/blog/paul-nieuwelaars-blog/2012/04/04/Script_C_to_Javascript_Meets_Dynamics_CRM_2011.aspx
Now that Rollup 12 (“Polaris”) has been released we need to ensure javascript code works across Internet Explorer, Firefox, Chrome & Safari. Using Script# and jQuery allows us to write cross browser/UR12 compatible code very easily.
Let’s take a look at how we can retrieve a list of products in Dynamics CRM using FetchXml.
// sample fetchxml: "<fetch mapping='logical'><entity name='product'><all-attributes /></entity></fetch>";
publicvoid RetrieveMultiple(string xml)
{
// we need to wrap our fetchxml query with additional soap elements
xml = WashWithSoap(xml);
jQueryAjaxOptions options = newjQueryAjaxOptions();
// ProcessData, DataType and Data are required, without this jQuery will have trouble parsing the xml
options.ProcessData = false;
options.DataType = "xml";
options.Data = xml;
options.Async = true;
// GetCorrectedServerUrl won't be required with orgs with UR12, you can use getClientUrl instead
options.Url = GetCorrectedServerUrl() + "/xrmservices/2011/organization.svc/web";
options.ContentType = "text/xml; charset=utf-8";
options.Type = "POST";
// Script# doesn't expose the Headers property therefor we need to inject javascript...uuugggllyyyy
Script.Literal("{0}.headers = {{ SOAPAction: 'http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute' }}", options);
options.Success = newAjaxRequestCallback(delegate(object data, string state, jQueryXmlHttpRequest request)
{
// we will show you how to parse the data next time :)
});
jQuery.Ajax(options);
}
// this is specific to retrievemultiple, be careful
privatestring WashWithSoap(string fetchXml)
{
string xml = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\"><request i:type=\"b:RetrieveMultipleRequest\" xmlns:b=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><b:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\"> <b:KeyValuePairOfstringanyType><c:key>Query</c:key><c:value i:type=\"b:FetchExpression\"><b:Query>";
xml += Encode(fetchXml);
xml += "</b:Query></c:value></b:KeyValuePairOfstringanyType></b:Parameters><b:RequestId i:nil=\"true\"/><b:RequestName>RetrieveMultiple</b:RequestName></request></Execute></s:Body></s:Envelope>";
return xml;
}
Keep an eye out for Part 2 where we will show you how to parse the data in a cross browser compatible way.