Wednesday, March 23, 2011

Set HTML Rendered Within IFrame in CRM 2011 in Jscript OnLoad Event

So yesterday's post covered how to update the contents of a web resource in C# and in Jscript using the SDK.  Now on to part 2.

Today I am going to build a little on the Jscript version of that concept to show you how to use this to determine the HTML rendered in an Iframe in the form OnLoad event. 

There isn't much more to it, here goes!

1.  Upload a blank or next to blank HTML page to act as a web resource placeholder that we will change in code and make note of the URL, we will use it in our Jscript.




Next, we need to modify yesterday's Jscript so that we are setting the Iframe source URL to the edited web resource in the appropriate place in the response after it is published.

I will re-paste the entire code here, make note of the publish response function of the entity and you will see where we are setting the Iframe source.  All you have to do is publish an event handler in the GUI that calls the runme function of this library after you swap our your specific web resource GUID.



function runme() {
    
    var guidWebResource = "ADFA33CB-7050-E011-9CF8-080027AD5B6E";

    var strContentHTML = "<html><body><h1>HELLO WORLD!!<h1></body</html>";
    var enc = encode64(strContentHTML);
    SDK.SAMPLES.UpdateWebResourceRequest(guidWebResource, enc);
    SDK.SAMPLES.PublishWebResourceRequest(guidWebResource);

 


}

function encode64(input) {
    var keyStr = "ABCDEFGHIJKLMNOP" +
               "QRSTUVWXYZabcdef" +
               "ghijklmnopqrstuv" +
               "wxyz0123456789+/" +
               "=";

    //input = escape(input);
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;

    do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output +
           keyStr.charAt(enc1) +
           keyStr.charAt(enc2) +
           keyStr.charAt(enc3) +
           keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
    } while (i < input.length);

    return output;
}

function decode64(input) {
    var keyStr = "ABCDEFGHIJKLMNOP" +
               "QRSTUVWXYZabcdef" +
               "ghijklmnopqrstuv" +
               "wxyz0123456789+/" +
               "=";

    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;

    // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
    var base64test = /[^A-Za-z0-9\+\/\=]/g;
    if (base64test.exec(input)) {
        alert("There were invalid base64 characters in the input text.\n" +
              "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
              "Expect errors in decoding.");
    }
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    do {
        enc1 = keyStr.indexOf(input.charAt(i++));
        enc2 = keyStr.indexOf(input.charAt(i++));
        enc3 = keyStr.indexOf(input.charAt(i++));
        enc4 = keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }

        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";

    } while (i < input.length);

    return unescape(output);
}


if (typeof (SDK) == "undefined")
{ SDK = { __namespace: true }; }
//This will establish a more unique namespace for functions in this library. This will reduce the 
// potential for functions to be overwritten due to a duplicate name when the library is loaded.
SDK.SAMPLES = {
    _getServerUrl: function () {
        ///<summary>
        /// Returns the URL for the SOAP endpoint using the context information available in the form
        /// or HTML Web resource.
        ///</summary>
        var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
        var serverUrl = "";
        if (typeof GetGlobalContext == "function") {
            var context = GetGlobalContext();
            serverUrl = context.getServerUrl();
        }
        else {
            if (typeof Xrm.Page.context == "object") {
                serverUrl = Xrm.Page.context.getServerUrl();
            }
            else
            { throw new Error("Unable to access the server URL"); }
        }
        if (serverUrl.match(/\/$/)) {
            serverUrl = serverUrl.substring(0, serverUrl.length - 1);
        }
        return serverUrl + OrgServicePath;
    },
    UpdateWebResourceRequest: function (guidWebResourceID, strEncodedContent) {
        var requestMain = "";
        requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
        requestMain += "  <s:Body>";
        requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
        requestMain += "      <request i:type=\"a:UpdateRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\">";
        requestMain += "        <a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <b:key>Target</b:key>";
        requestMain += "            <b:value i:type=\"a:Entity\">";
        requestMain += "              <a:Attributes>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>webresourceidunique</b:key>";
        requestMain += "                  <b:value i:type=\"c:guid\" xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/\">434e47dd-8cb5-427f-8e5f-72b7ed93dcf6</b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>organizationid</b:key>";
        requestMain += "                  <b:value i:type=\"a:EntityReference\">";
        requestMain += "                    <a:Id>a2fe1552-7977-4d92-a730-05eeb167afb5</a:Id>";
        requestMain += "                    <a:LogicalName>organization</a:LogicalName>";
        requestMain += "                    <a:Name>crm</a:Name>";
        requestMain += "                  </b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>displayname</b:key>";
        requestMain += "                  <b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">new_webresourceiframe</b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>iscustomizable</b:key>";
        requestMain += "                  <b:value i:type=\"a:BooleanManagedProperty\">";
        requestMain += "                    <a:CanBeChanged>true</a:CanBeChanged>";
        requestMain += "                    <a:ManagedPropertyLogicalName>iscustomizableanddeletable</a:ManagedPropertyLogicalName>";
        requestMain += "                    <a:Value>true</a:Value>";
        requestMain += "                  </b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>solutionid</b:key>";
        requestMain += "                  <b:value i:type=\"c:guid\" xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/\">fd140aae-4df4-11dd-bd17-0019b9312238</b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>languagecode</b:key>";
        requestMain += "                  <b:value i:type=\"c:int\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">1033</b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>modifiedon</b:key>";
        requestMain += "                  <b:value i:type=\"c:dateTime\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">2011-03-19T23:12:38Z</b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>ismanaged</b:key>";
        requestMain += "                  <b:value i:type=\"c:boolean\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">false</b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>createdby</b:key>";
        requestMain += "                  <b:value i:type=\"a:EntityReference\">";
        requestMain += "                    <a:Id>81ed14d9-4441-e011-963a-080027ad5b6e</a:Id>";
        requestMain += "                    <a:LogicalName>systemuser</a:LogicalName>";
        requestMain += "                    <a:Name i:nil=\"true\" />";
        requestMain += "                  </b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>webresourcetype</b:key>";
        requestMain += "                  <b:value i:type=\"a:OptionSetValue\">";
        requestMain += "                    <a:Value>1</a:Value>";
        requestMain += "                  </b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>canbedeleted</b:key>";
        requestMain += "                  <b:value i:type=\"a:BooleanManagedProperty\">";
        requestMain += "                    <a:CanBeChanged>true</a:CanBeChanged>";
        requestMain += "                    <a:ManagedPropertyLogicalName>canbedeleted</a:ManagedPropertyLogicalName>";
        requestMain += "                    <a:Value>true</a:Value>";
        requestMain += "                  </b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>componentstate</b:key>";
        requestMain += "                  <b:value i:type=\"a:OptionSetValue\">";
        requestMain += "                    <a:Value>0</a:Value>";
        requestMain += "                  </b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>modifiedby</b:key>";
        requestMain += "                  <b:value i:type=\"a:EntityReference\">";
        requestMain += "                    <a:Id>81ed14d9-4441-e011-963a-080027ad5b6e</a:Id>";
        requestMain += "                    <a:LogicalName>systemuser</a:LogicalName>";
        requestMain += "                    <a:Name i:nil=\"true\" />";
        requestMain += "                  </b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>ishidden</b:key>";
        requestMain += "                  <b:value i:type=\"a:BooleanManagedProperty\">";
        requestMain += "                    <a:CanBeChanged>true</a:CanBeChanged>";
        requestMain += "                    <a:ManagedPropertyLogicalName>ishidden</a:ManagedPropertyLogicalName>";
        requestMain += "                    <a:Value>false</a:Value>";
        requestMain += "                  </b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>webresourceid</b:key>";
        requestMain += "                  <b:value i:type=\"c:guid\" xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + guidWebResourceID + "</b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>createdon</b:key>";
        requestMain += "                  <b:value i:type=\"c:dateTime\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">2011-03-17T08:30:20Z</b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>name</b:key>";
        requestMain += "                  <b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">new_webresourceiframe</b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "                <a:KeyValuePairOfstringanyType>";
        requestMain += "                  <b:key>content</b:key>";
        requestMain += "                  <b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">" + strEncodedContent + "</b:value>";
        requestMain += "                </a:KeyValuePairOfstringanyType>";
        requestMain += "              </a:Attributes>";
        requestMain += "              <a:EntityState i:nil=\"true\" />";
        requestMain += "              <a:FormattedValues>";
        requestMain += "                <a:KeyValuePairOfstringstring>";
        requestMain += "                  <b:key>iscustomizable</b:key>";
        requestMain += "                  <b:value>True</b:value>";
        requestMain += "                </a:KeyValuePairOfstringstring>";
        requestMain += "                <a:KeyValuePairOfstringstring>";
        requestMain += "                  <b:key>languagecode</b:key>";
        requestMain += "                  <b:value>1,033</b:value>";
        requestMain += "                </a:KeyValuePairOfstringstring>";
        requestMain += "                <a:KeyValuePairOfstringstring>";
        requestMain += "                  <b:key>modifiedon</b:key>";
        requestMain += "                  <b:value>3/19/2011 4:12 PM</b:value>";
        requestMain += "                </a:KeyValuePairOfstringstring>";
        requestMain += "                <a:KeyValuePairOfstringstring>";
        requestMain += "                  <b:key>ismanaged</b:key>";
        requestMain += "                  <b:value>Unmanaged</b:value>";
        requestMain += "                </a:KeyValuePairOfstringstring>";
        requestMain += "                <a:KeyValuePairOfstringstring>";
        requestMain += "                  <b:key>webresourcetype</b:key>";
        requestMain += "                  <b:value>Web Page (HTML)</b:value>";
        requestMain += "                </a:KeyValuePairOfstringstring>";
        requestMain += "                <a:KeyValuePairOfstringstring>";
        requestMain += "                  <b:key>canbedeleted</b:key>";
        requestMain += "                  <b:value>True</b:value>";
        requestMain += "                </a:KeyValuePairOfstringstring>";
        requestMain += "                <a:KeyValuePairOfstringstring>";
        requestMain += "                  <b:key>componentstate</b:key>";
        requestMain += "                  <b:value>Published</b:value>";
        requestMain += "                </a:KeyValuePairOfstringstring>";
        requestMain += "                <a:KeyValuePairOfstringstring>";
        requestMain += "                  <b:key>ishidden</b:key>";
        requestMain += "                  <b:value>False</b:value>";
        requestMain += "                </a:KeyValuePairOfstringstring>";
        requestMain += "                <a:KeyValuePairOfstringstring>";
        requestMain += "                  <b:key>createdon</b:key>";
        requestMain += "                  <b:value>3/17/2011 1:30 AM</b:value>";
        requestMain += "                </a:KeyValuePairOfstringstring>";
        requestMain += "              </a:FormattedValues>";
        requestMain += "              <a:Id>adfa33cb-7050-e011-9cf8-080027ad5b6e</a:Id>";
        requestMain += "              <a:LogicalName>webresource</a:LogicalName>";
        requestMain += "              <a:RelatedEntities />";
        requestMain += "            </b:value>";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "        </a:Parameters>";
        requestMain += "        <a:RequestId i:nil=\"true\" />";
        requestMain += "        <a:RequestName>Update</a:RequestName>";
        requestMain += "      </request>";
        requestMain += "    </Execute>";
        requestMain += "  </s:Body>";
        requestMain += "</s:Envelope>";
        var req = new XMLHttpRequest();
        req.open("POST", SDK.SAMPLES._getServerUrl(), true)
        // Responses will return XML. It isn't possible to return JSON.
        req.setRequestHeader("Accept", "application/xml, text/xml, */*");
        req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        var successCallback = null;
        var errorCallback = null;
        req.onreadystatechange = function () { SDK.SAMPLES.UpdateWebResourceResponse(req, successCallback, errorCallback); };
        req.send(requestMain);
    },
    UpdateWebResourceResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// Recieves the assign response
        ///</summary>
        ///<param name="req" Type="XMLHttpRequest">
        /// The XMLHttpRequest response
        ///</param>
        ///<param name="successCallback" Type="Function">
        /// The function to perform when an successfult response is returned.
        /// For this message no data is returned so a success callback is not really necessary.
        ///</param>
        ///<param name="errorCallback" Type="Function">
        /// The function to perform when an error is returned.
        /// This function accepts a JScript error returned by the _getError function
        ///</param>
        if (req.readyState == 4) {
            if (req.status == 200) {
                if (successCallback != null)
                { successCallback(); }
            }
            else {
                errorCallback(SDK.SAMPLES._getError(req.responseXML));
            }
        }
    },
    PublishWebResourceRequest: function (guidID) {
        var requestMain = "";
        requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
        requestMain += "  <s:Body>";
        requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
        requestMain += "      <request i:type=\"b:PublishXmlRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
        requestMain += "        <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <c:key>ParameterXml</c:key>";
        requestMain += "            <c:value i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">&lt;importexportxml&gt;&lt;webresources&gt;&lt;webresource&gt;" + guidID + "&lt;/webresource&gt;&lt;/webresources&gt;&lt;/importexportxml&gt;</c:value>";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "        </a:Parameters>";
        requestMain += "        <a:RequestId i:nil=\"true\" />";
        requestMain += "        <a:RequestName>PublishXml</a:RequestName>";
        requestMain += "      </request>";
        requestMain += "    </Execute>";
        requestMain += "  </s:Body>";
        requestMain += "</s:Envelope>";
        var req = new XMLHttpRequest();
        req.open("POST", SDK.SAMPLES._getServerUrl(), true)
        // Responses will return XML. It isn't possible to return JSON.
        req.setRequestHeader("Accept", "application/xml, text/xml, */*");
        req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        var successCallback = null;
        var errorCallback = null;
        req.onreadystatechange = function () { SDK.SAMPLES.PublishWebResourceResponse(req, successCallback, errorCallback); };
        req.send(requestMain);
    },
    PublishWebResourceResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// Recieves the assign response
        ///</summary>
        ///<param name="req" Type="XMLHttpRequest">
        /// The XMLHttpRequest response
        ///</param>
        ///<param name="successCallback" Type="Function">
        /// The function to perform when an successfult response is returned.
        /// For this message no data is returned so a success callback is not really necessary.
        ///</param>
        ///<param name="errorCallback" Type="Function">
        /// The function to perform when an error is returned.
        /// This function accepts a JScript error returned by the _getError function
        ///</param>
        if (req.readyState == 4) {
            if (req.status == 200) {
                
                //****************************************
                //BELOW IS WHERE WE ARE SETTING THE IFRAME SOURCE
                //******************************************
                var iframeObject = Xrm.Page.getControl("IFRAME_testiframe");
                iframeObject.setSrc("http://win-fo6aph8hsbq/crm/WebResources/new_webresourceiframe");

                //                if (successCallback != null)
                //                { successCallback(); }
            }
            else {
                errorCallback(SDK.SAMPLES._getError(req.responseXML));
            }
        }
    },
    RetrieveWebResourceRequest: function (guidID) {
        var requestMain = ""
        requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
        requestMain += "  <s:Body>";
        requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
        requestMain += "      <request i:type=\"a:RetrieveMultipleRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\">";
        requestMain += "        <a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <b:key>Query</b:key>";
        requestMain += "            <b:value i:type=\"a:QueryExpression\">";
        requestMain += "              <a:ColumnSet>";
        requestMain += "                <a:AllColumns>false</a:AllColumns>";
        requestMain += "                <a:Columns xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">";
        requestMain += "                  <c:string>content</c:string>";
        requestMain += "                </a:Columns>";
        requestMain += "              </a:ColumnSet>";
        requestMain += "              <a:Criteria>";
        requestMain += "                <a:Conditions>";
        requestMain += "                  <a:ConditionExpression>";
        requestMain += "                    <a:AttributeName>webresourceid</a:AttributeName>";
        requestMain += "                    <a:Operator>Equal</a:Operator>";
        requestMain += "                    <a:Values xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">";
        requestMain += "                      <c:anyType i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">" + guidID + "</c:anyType>";
        requestMain += "                    </a:Values>";
        requestMain += "                  </a:ConditionExpression>";
        requestMain += "                </a:Conditions>";
        requestMain += "                <a:FilterOperator>And</a:FilterOperator>";
        requestMain += "                <a:Filters />";
        requestMain += "              </a:Criteria>";
        requestMain += "              <a:Distinct>false</a:Distinct>";
        requestMain += "              <a:EntityName>webresource</a:EntityName>";
        requestMain += "              <a:LinkEntities />";
        requestMain += "              <a:Orders />";
        requestMain += "              <a:PageInfo>";
        requestMain += "                <a:Count>0</a:Count>";
        requestMain += "                <a:PageNumber>0</a:PageNumber>";
        requestMain += "                <a:PagingCookie i:nil=\"true\" />";
        requestMain += "                <a:ReturnTotalRecordCount>false</a:ReturnTotalRecordCount>";
        requestMain += "              </a:PageInfo>";
        requestMain += "              <a:NoLock>false</a:NoLock>";
        requestMain += "            </b:value>";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "        </a:Parameters>";
        requestMain += "        <a:RequestId i:nil=\"true\" />";
        requestMain += "        <a:RequestName>RetrieveMultiple</a:RequestName>";
        requestMain += "      </request>";
        requestMain += "    </Execute>";
        requestMain += "  </s:Body>";
        requestMain += "</s:Envelope>";
        var req = new XMLHttpRequest();
        req.open("POST", SDK.SAMPLES._getServerUrl(), true)
        // Responses will return XML. It isn't possible to return JSON.
        req.setRequestHeader("Accept", "application/xml, text/xml, */*");
        req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        var successCallback = null;
        var errorCallback = null;
        req.onreadystatechange = function () { SDK.SAMPLES.RetrieveWebResourceResponse(req, successCallback, errorCallback); };
        req.send(requestMain);
    },
    RetrieveWebResourceResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// Recieves the assign response
        ///</summary>
        ///<param name="req" Type="XMLHttpRequest">
        /// The XMLHttpRequest response
        ///</param>
        ///<param name="successCallback" Type="Function">
        /// The function to perform when an successfult response is returned.
        /// For this message no data is returned so a success callback is not really necessary.
        ///</param>
        ///<param name="errorCallback" Type="Function">
        /// The function to perform when an error is returned.
        /// This function accepts a JScript error returned by the _getError function
        ///</param>
        if (req.readyState == 4) {
            if (req.status == 200) {
                return req.responseXML.xml.toString();
                //if (successCallback != null)
                //{ successCallback(); }
            }
            else {
                errorCallback(SDK.SAMPLES._getError(req.responseXML));
            }
        }
    },
    _getError: function (faultXml) {
        ///<summary>
        /// Parses the WCF fault returned in the event of an error.
        ///</summary>
        ///<param name="faultXml" Type="XML">
        /// The responseXML property of the XMLHttpRequest response.
        ///</param>
        var errorMessage = "Unknown Error (Unable to parse the fault)";
        if (typeof faultXml == "object") {
            try {
                var bodyNode = faultXml.firstChild.firstChild;
                //Retrieve the fault node
                for (var i = 0; i < bodyNode.childNodes.length; i++) {
                    var node = bodyNode.childNodes[i];
                    //NOTE: This comparison does not handle the case where the XML namespace changes
                    if ("s:Fault" == node.nodeName) {
                        for (var j = 0; j < node.childNodes.length; j++) {
                            var faultStringNode = node.childNodes[j];
                            if ("faultstring" == faultStringNode.nodeName) {
                                errorMessage = faultStringNode.text;
                                break;
                            }
                        }
                        break;
                    }
                }
            }
            catch (e) { };
        }
        return new Error(errorMessage);
    },
    __namespace: true
};

Thats all there is to it!
Now let's look at our result when we open the preview form, it takes about 1.5 seconds to show our updated Jscript on my low powered dev box.



I hope this helps!

No comments:

Post a Comment