Tuesday, 17 February 2015

xyz_Scriptsjson2.js

/*
http://www.JSON.org/json2.js
2011-02-23

Public Domain.

NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

See http://www.JSON.org/js.html


This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html

USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.


This file creates a global JSON object containing two methods: stringify
and parse.

JSON.stringify(value, replacer, space)
value       any JavaScript value, usually an object or array.

replacer    an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.

space       an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.

This method produces a JSON text from a JavaScript value.

When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value

For example, this would serialize Dates as ISO strings.

Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}

return this.getUTCFullYear()   + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate())      + 'T' +
f(this.getUTCHours())     + ':' +
f(this.getUTCMinutes())   + ':' +
f(this.getUTCSeconds())   + 'Z';
};

You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.

If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.

Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.

The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.

If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.

Example:

text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'


text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'


JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.

The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.

Example:

// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.

myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});

myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});


This is a reference implementation. You are free to copy, modify, or
redistribute.
*/

/*jslint evil: true, strict: false, regexp: false */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/

if (!this.JSON) { this.JSON = {}; } (function () { function f(n) { return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { var i, k, v, length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } if (typeof rep === 'function') { value = rep.call(holder, key, value); } switch (typeof value) { case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; } gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; } rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } return str('', { '': value }); }; } if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({ '': j }, '') : j; } throw new SyntaxError('JSON.parse'); }; } } ());

XYZ_/Scripts/SDK.REST.js

// =====================================================================
//  This file is part of the Microsoft Dynamics CRM SDK code samples.
//
//  Copyright (C) Microsoft Corporation.  All rights reserved.
//
//  This source code is intended only as a supplement to Microsoft
//  Development Tools and/or on-line documentation.  See these other
//  materials for detailed information regarding Microsoft code samples.
//
//  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
// =====================================================================

if (typeof (SDK) == "undefined")
{ SDK = { __namespace: true }; }
SDK.REST = {
    _Context: function () {
        ///<summary>
        /// Private function that retrieves the context from either the Xrm.Page.context
        /// or the GetGlobalContext function in ClientGlobalContext.js.aspx
        ///</summary>
        var errorMessage = "Context is not available.";
        if (typeof GetGlobalContext != "undefined") {
            return GetGlobalContext();
        }
        else if (typeof Xrm != "undefined") {
            return Xrm.Page.context;
        }
        else if (typeof parent.Xrm.Page.context != "undefined") {
            return parent.Xrm.Page.context;
        }
        else {
            return new Error(errorMessage);
        }
    },
    _ODataUrl: function () {
        ///<summary>
        /// Private function composes the OData URL using the _Context object.
        ///</summary>

        //Detect if the hostname is an IP address then we return the IP address as the server destination instead of the server name (which will be unfound)
        var urlReg = new RegExp(/http[s]?:\/\/[0-9.:]+\/[a-zA-Z0-9.-_~]+/i);
        var ServerUrl = this._Context().getClientUrl();
        if (window.location.href.match(urlReg) != null) {
           // ServerUrl = window.location.href.match(urlReg).toString();
        }
        if (ServerUrl.match(/\/$/)) {
            ServerUrl = ServerUrl.substring(0, ServerUrl.length - 1);
        }
        return ServerUrl + "/XRMServices/2011/OrganizationData.svc";
    },

    retrieveMultipleSync: function (odataSetName, filter, successCallback, errorCallback) {
        ///<summary>
        /// Initiates an asynchronous request for the first 50 records of a given entity that meet the filter criteria
        ///</summary>
        ///<param name="odataSetName" type="String">
        /// The name of the OData resource. For the Account entity, 'AccountSet'.
        ///</param>
        ///<param name="filter" type="String">
        /// The OData system query options to limit the records returned or define which
        /// attributes are returned. These are the query string parameters begining with '?'.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to accept the array of records that are the result of a successful query.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful query.
        ///</param>
        if (!odataSetName)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the odataSetName parameter"); }
        if (!successCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the successCallback parameter"); }
        if (!errorCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the errorCallback parameter"); }

        var req = new XMLHttpRequest();
        req.open("GET", this._ODataUrl() + "/" + odataSetName + filter, false);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            SDK.REST._retrieveMultipleResponse(this, successCallback, errorCallback);
        };
        req.send();

    },

    retrieveMultipleAsync: function (odataSetName, filter, successCallback, errorCallback) {
        ///<summary>
        /// Initiates an asynchronous request for the first 50 records of a given entity that meet the filter criteria
        ///</summary>
        ///<param name="odataSetName" type="String">
        /// The name of the OData resource. For the Account entity, 'AccountSet'.
        ///</param>
        ///<param name="filter" type="String">
        /// The OData system query options to limit the records returned or define which
        /// attributes are returned. These are the query string parameters begining with '?'.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to accept the array of records that are the result of a successful query.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful query.
        ///</param>
        if (!odataSetName)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the odataSetName parameter"); }
        if (!successCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the successCallback parameter"); }
        if (!errorCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the errorCallback parameter"); }

        var req = new XMLHttpRequest();
        req.open("GET", this._ODataUrl() + "/" + odataSetName + filter, true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            SDK.REST._retrieveMultipleResponse(this, successCallback, errorCallback);
        };
        req.send();

    },
    _retrieveMultipleResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// Private function that processes the response from SDK.REST.retrieveMultipleAsync
        ///</summary>
        ///<param name="req" type="XMLHttpRequest">
        /// The XMLHttpRequest representing the response.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to accept the array of records that are the result of a successful query.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful query.
        ///</param>
        if (req.readyState == 4 /* complete */) {
            if (req.status == 200) {
                //Success
                successCallback(JSON.parse(req.responseText, SDK.REST.dateReviver).d.results);
            }
            else {
                errorCallback(JSON.parse(req.responseText).error);
            }
        }
    },
    createAsync: function (odataSetName, object, successCallback, errorCallback) {
        ///<summary>
        /// Initiates an asynchronous request to create a record for a given entity.
        ///</summary>
        ///<param name="odataSetName" type="String">
        /// The name of the OData resource. For the Account entity, 'AccountSet'.
        ///</param>
        ///<param name="object" type="Object">
        /// A JScript object containing valid properties for the entity.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to accept the array of records that are the result of a successful query.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful query.
        ///</param>
        var req = new XMLHttpRequest();
        req.open("POST", this._ODataUrl() + "/" + odataSetName, true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            SDK.REST._createResponse(this, successCallback, errorCallback);
        };
        req.send(JSON.stringify(object));
    },
    _createResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// Private function that processes the response from SDK.REST.createAsync
        ///</summary>
        ///<param name="req" type="XMLHttpRequest">
        /// The XMLHttpRequest representing the response.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to accept the object represnting the created record.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful attempt to create a record.
        ///</param>
        if (req.readyState == 4 /* complete */) {
            if (req.status == 201) {
                //Success
                successCallback(JSON.parse(req.responseText).d);
            }
            else {
                errorCallback(JSON.parse(req.responseText).error);
            }
        }
    },
    updateAsync: function (odataSetName, object, id, successCallback, errorCallback) {
        ///<summary>
        /// Initiates an asynchronous request to update a record for a given entity.
        ///</summary>
        ///<param name="odataSetName" type="String">
        /// The name of the OData resource. For the Account entity, 'AccountSet'.
        ///</param>
        ///<param name="object" type="Object">
        /// A JScript object containing valid properties for the entity.
        ///</param>
        ///<param name="id" type="String">
        /// Provides the GUID unique identifier for the record to be updated.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to acknowlege the successful completion of the update.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful update attempt.
        ///</param>
        var req = new XMLHttpRequest();
        req.open("POST", this._ODataUrl() + "/" + odataSetName + "(guid'" + id + "')", true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("X-HTTP-Method", "MERGE");

        req.onreadystatechange = function () {
            SDK.REST._updateResponse(this, successCallback, errorCallback);
        };
        req.send(JSON.stringify(object));
    },
    _updateResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// Private function that processes the response from SDK.REST.updateAsync
        ///</summary>
        ///<param name="req" type="XMLHttpRequest">
        /// The XMLHttpRequest representing the response.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to acknowlege the successful completion of the update.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful update attempt.
        ///</param>
        if (req.readyState == 4 /* complete */) {
            //There appears to be an issue where IE maps the 204 status to 1223 when no content is returned.
            if (req.status == 204 || req.status == 1223) {
                successCallback();
            }
            else {
                errorCallback(JSON.parse(req.responseText).error);
            }
        }
    },
    deleteAsync: function (odataSetName, id, successCallback, errorCallback) {
        ///<summary>
        /// Initiates an asynchronous request to delete a record for a given entity.
        ///</summary>
        ///<param name="odataSetName" type="String">
        /// The name of the OData resource. For the Account entity, 'AccountSet'.
        ///</param>
        ///<param name="id" type="String">
        /// Provides the GUID unique identifier for the record to be deleted.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to acknowlege the successful deletion of the record.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful delete attempt.
        ///</param>
        var req = new XMLHttpRequest();
        req.open("POST", this._ODataUrl() + "/" + odataSetName + "(guid'" + id + "')", true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("X-HTTP-Method", "DELETE");

        req.onreadystatechange = function () {
            SDK.REST._deleteResponse(this, function () { successCallback(id) }, errorCallback);
        };
        req.send();

    },
    _deleteResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// Private function that processes the response from SDK.REST.deleteAsync
        ///</summary>
        ///<param name="req" type="XMLHttpRequest">
        /// The XMLHttpRequest representing the response.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to acknowlege the successful completion of the delete.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful delete attempt.
        ///</param>
        if (req.readyState == 4 /* complete */) {
            //There appears to be an issue where IE maps the 204 status to 1223 when no content is returned.
            if (req.status == 204 || req.status == 1223) {
                successCallback();
            }
            else {
                errorCallback(JSON.parse(req.responseText).error);
            }
        }
    },

    retrieveSync: function (odataSetName, id, successCallback, errorCallback) {
        ///<summary>
        /// function to retrieve a specific record.
        ///</summary>
        if (!odataSetName)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the odataSetName parameter"); }
        if (!id)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the id parameter"); }
        if (!successCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the successCallback parameter"); }
        if (!errorCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the errorCallback parameter"); }

        var req = new XMLHttpRequest();
        req.open("GET", this._ODataUrl() + "/" + odataSetName + "(guid'" + id + "')", false);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            SDK.REST._retrieveResponse(this, successCallback, errorCallback);
        };
        req.send();

    },

    retrieveAsync: function (odataSetName, id, successCallback, errorCallback) {
        ///<summary>
        /// function to retrieve a specific record.
        ///</summary>
        if (!odataSetName)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the odataSetName parameter"); }
        if (!id)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the id parameter"); }
        if (!successCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the successCallback parameter"); }
        if (!errorCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the errorCallback parameter"); }

        var req = new XMLHttpRequest();
        req.open("GET", this._ODataUrl() + "/" + odataSetName + "(guid'" + id + "')", true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            SDK.REST._retrieveResponse(this, successCallback, errorCallback);
        };
        req.send();

    },
    _retrieveResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// function to retrieve the response from SDK.REST.retrieveAsync
        ///</summary>
        if (req.readyState == 4 /* complete */) {
            if (req.status == 200) {
                //Success
                successCallback(JSON.parse(req.responseText).d);
                //successCallback(JSON.parse(req.responseText, SDK.REST.dateReviver).d.results);
            }
            else {
                errorCallback(JSON.parse(req.responseText).error);
            }
        }
    },
    associateAsync: function (entity1Set, entity1Id, entity2Set, entity2Id, relationship, successCallback, errorCallback) {
        ///<summary>
        /// Unimplemented function placeholder to associate a pair of records.
        ///</summary>
        var entity2 = {};
        entity2.uri = this._ODataUrl() + "/" + entity2Set + "(guid'" + entity2Id + "')";

        var req = new XMLHttpRequest();
        req.open("POST", this._ODataUrl() + "/" + entity1Set + "(guid'" + entity1Id + "')/$links/" + relationship, true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            SDK.REST._associateResponse(this, successCallback, errorCallback);
        };
        req.send(JSON.stringify(entity2));
    },
    _associateResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// Unimplemented function placeholder to retrieve the response from SDK.REST.associateAsync
        ///</summary>
        if (req.readyState == 4 /* complete */) {
            //There appears to be an issue where IE maps the 204 status to 1223 when no content is returned.
            if (req.status == 204 || req.status == 1223) {
                successCallback();
            }
            else {
                errorCallback(JSON.parse(req.responseText).error);
            }
        }
    },
    dissassociateAsync: function (entity1Set, entity1Id, entity2Id, relationship, successCallback, errorCallback) {
        ///<summary>
        /// function to disassociate a pair of records.
        ///</summary>
        var req = new XMLHttpRequest();
        req.open("POST", this._ODataUrl() + "/" + entity1Set + "(guid'" + entity1Id + "')/$links/" + relationship + "(guid'" + entity2Id + "')", true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("X-HTTP-Method", "DELETE");
        req.onreadystatechange = function () {
            SDK.REST._disassociateResponse(this, successCallback, errorCallback);
        };
        req.send();
    },
    _disassociateResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// function to retrieve the response from SDK.REST.dissassociateAsync
        ///</summary>
        if (req.readyState == 4 /* complete */) {
            //There appears to be an issue where IE maps the 204 status to 1223 when no content is returned.
            if (req.status == 204 || req.status == 1223) {
                successCallback();
            }
            else {
                errorCallback(JSON.parse(req.responseText).error);
            }
        }
    },
    dateReviver: function (key, value) {
        ///<summary>
        /// A function to be used as a date reviver parameter to JSON.parse.
        ///</summary>
        ///<param name="key" type="String">
        /// The key for the JSON object
        ///</param>
        ///<param name="value" type="Object">
        /// The value for the JSON object
        ///</param>
        var a;
        if (typeof value === 'string') {
            a = /Date\(([-+]?\d+)\)/.exec(value); //Matches "\/Date(1234567890123)\/ or "\/Date(-1234567890123)\/"
            if (a) {
                return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
            }
        }
        return value;

    },
    __namespace: true
};

ScriptsSDKREST.js

// =====================================================================
//  This file is part of the Microsoft Dynamics CRM SDK code samples.
//
//  Copyright (C) Microsoft Corporation.  All rights reserved.
//
//  This source code is intended only as a supplement to Microsoft
//  Development Tools and/or on-line documentation.  See these other
//  materials for detailed information regarding Microsoft code samples.
//
//  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
// =====================================================================

if (typeof (SDK) == "undefined")
{ SDK = { __namespace: true }; }
SDK.REST = {
    _Context: function () {
        ///<summary>
        /// Private function that retrieves the context from either the Xrm.Page.context
        /// or the GetGlobalContext function in ClientGlobalContext.js.aspx
        ///</summary>
        var errorMessage = "Context is not available.";
        if (typeof GetGlobalContext != "undefined") {
            return GetGlobalContext();
        }
        else if (typeof Xrm != "undefined") {
            return Xrm.Page.context;
        }
        else if (typeof parent.Xrm.Page.context != "undefined") {
            return parent.Xrm.Page.context;
        }
        else {
            return new Error(errorMessage);
        }
    },
    _ODataUrl: function () {
        ///<summary>
        /// Private function composes the OData URL using the _Context object.
        ///</summary>

        //Detect if the hostname is an IP address then we return the IP address as the server destination instead of the server name (which will be unfound)
        var urlReg = new RegExp(/http[s]?:\/\/[0-9.:]+\/[a-zA-Z0-9.-_~]+/i);
        var ServerUrl = this._Context().getServerUrl();
        if (window.location.href.match(urlReg) != null) {
            ServerUrl = window.location.href.match(urlReg).toString();
        }
        if (ServerUrl.match(/\/$/)) {
            ServerUrl = ServerUrl.substring(0, ServerUrl.length - 1);
        }
        return ServerUrl + "/XRMServices/2011/OrganizationData.svc";
    },
    retrieveMultipleSync: function (odataSetName, filter, successCallback, errorCallback) {
        ///<summary>
        /// Initiates an asynchronous request for the first 50 records of a given entity that meet the filter criteria
        ///</summary>
        ///<param name="odataSetName" type="String">
        /// The name of the OData resource. For the Account entity, 'AccountSet'.
        ///</param>
        ///<param name="filter" type="String">
        /// The OData system query options to limit the records returned or define which
        /// attributes are returned. These are the query string parameters begining with '?'.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to accept the array of records that are the result of a successful query.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful query.
        ///</param>
        if (!odataSetName)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the odataSetName parameter"); }
        if (!successCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the successCallback parameter"); }
        if (!errorCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the errorCallback parameter"); }

        var req = new XMLHttpRequest();
        req.open("GET", this._ODataUrl() + "/" + odataSetName + filter, false);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            SDK.REST._retrieveMultipleResponse(this, successCallback, errorCallback);
        };
        req.send();

    },
    retrieveMultipleAsync: function (odataSetName, filter, successCallback, errorCallback) {
        ///<summary>
        /// Initiates an asynchronous request for the first 50 records of a given entity that meet the filter criteria
        ///</summary>
        ///<param name="odataSetName" type="String">
        /// The name of the OData resource. For the Account entity, 'AccountSet'.
        ///</param>
        ///<param name="filter" type="String">
        /// The OData system query options to limit the records returned or define which
        /// attributes are returned. These are the query string parameters begining with '?'.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to accept the array of records that are the result of a successful query.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful query.
        ///</param>
        if (!odataSetName)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the odataSetName parameter"); }
        if (!successCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the successCallback parameter"); }
        if (!errorCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the errorCallback parameter"); }

        var req = new XMLHttpRequest();
        req.open("GET", this._ODataUrl() + "/" + odataSetName + filter, true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            SDK.REST._retrieveMultipleResponse(this, successCallback, errorCallback);
        };
        req.send();

    },
    _retrieveMultipleResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// Private function that processes the response from SDK.REST.retrieveMultipleAsync
        ///</summary>
        ///<param name="req" type="XMLHttpRequest">
        /// The XMLHttpRequest representing the response.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to accept the array of records that are the result of a successful query.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful query.
        ///</param>
        if (req.readyState == 4 /* complete */) {
            if (req.status == 200) {
                //Success
                successCallback(JSON.parse(req.responseText, SDK.REST.dateReviver).d.results);
            }
            else {
                errorCallback(JSON.parse(req.responseText).error);
            }
        }
    },
    createAsync: function (odataSetName, object, successCallback, errorCallback) {
        ///<summary>
        /// Initiates an asynchronous request to create a record for a given entity.
        ///</summary>
        ///<param name="odataSetName" type="String">
        /// The name of the OData resource. For the Account entity, 'AccountSet'.
        ///</param>
        ///<param name="object" type="Object">
        /// A JScript object containing valid properties for the entity.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to accept the array of records that are the result of a successful query.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful query.
        ///</param>
        var req = new XMLHttpRequest();
        req.open("POST", this._ODataUrl() + "/" + odataSetName, true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            SDK.REST._createResponse(this, successCallback, errorCallback);
        };
        req.send(JSON.stringify(object));
    },
    _createResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// Private function that processes the response from SDK.REST.createAsync
        ///</summary>
        ///<param name="req" type="XMLHttpRequest">
        /// The XMLHttpRequest representing the response.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to accept the object represnting the created record.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful attempt to create a record.
        ///</param>
        if (req.readyState == 4 /* complete */) {
            if (req.status == 201) {
                //Success
                successCallback(JSON.parse(req.responseText).d);
            }
            else {
                errorCallback(JSON.parse(req.responseText).error);
            }
        }
    },
    updateAsync: function (odataSetName, object, id, successCallback, errorCallback) {
        ///<summary>
        /// Initiates an asynchronous request to update a record for a given entity.
        ///</summary>
        ///<param name="odataSetName" type="String">
        /// The name of the OData resource. For the Account entity, 'AccountSet'.
        ///</param>
        ///<param name="object" type="Object">
        /// A JScript object containing valid properties for the entity.
        ///</param>
        ///<param name="id" type="String">
        /// Provides the GUID unique identifier for the record to be updated.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to acknowlege the successful completion of the update.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful update attempt.
        ///</param>
        var req = new XMLHttpRequest();
        req.open("POST", this._ODataUrl() + "/" + odataSetName + "(guid'" + id + "')", true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("X-HTTP-Method", "MERGE");

        req.onreadystatechange = function () {
            SDK.REST._updateResponse(this, successCallback, errorCallback);
        };
        req.send(JSON.stringify(object));
    },
    _updateResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// Private function that processes the response from SDK.REST.updateAsync
        ///</summary>
        ///<param name="req" type="XMLHttpRequest">
        /// The XMLHttpRequest representing the response.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to acknowlege the successful completion of the update.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful update attempt.
        ///</param>
        if (req.readyState == 4 /* complete */) {
            //There appears to be an issue where IE maps the 204 status to 1223 when no content is returned.
            if (req.status == 204 || req.status == 1223) {
                successCallback();
            }
            else {
                errorCallback(JSON.parse(req.responseText).error);
            }
        }
    },
    deleteAsync: function (odataSetName, id, successCallback, errorCallback) {
        ///<summary>
        /// Initiates an asynchronous request to delete a record for a given entity.
        ///</summary>
        ///<param name="odataSetName" type="String">
        /// The name of the OData resource. For the Account entity, 'AccountSet'.
        ///</param>
        ///<param name="id" type="String">
        /// Provides the GUID unique identifier for the record to be deleted.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to acknowlege the successful deletion of the record.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful delete attempt.
        ///</param>
        var req = new XMLHttpRequest();
        req.open("POST", this._ODataUrl() + "/" + odataSetName + "(guid'" + id + "')", true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("X-HTTP-Method", "DELETE");

        req.onreadystatechange = function () {
            SDK.REST._deleteResponse(this, function () { successCallback(id) }, errorCallback);
        };
        req.send();

    },
    _deleteResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// Private function that processes the response from SDK.REST.deleteAsync
        ///</summary>
        ///<param name="req" type="XMLHttpRequest">
        /// The XMLHttpRequest representing the response.
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function to acknowlege the successful completion of the delete.
        ///</param>
        ///<param name="errorCallback" type="Function">
        /// The function to accept the error that is the result of an unsuccessful delete attempt.
        ///</param>
        if (req.readyState == 4 /* complete */) {
            //There appears to be an issue where IE maps the 204 status to 1223 when no content is returned.
            if (req.status == 204 || req.status == 1223) {
                successCallback();
            }
            else {
                errorCallback(JSON.parse(req.responseText).error);
            }
        }
    },
    retrieveSync: function (odataSetName, id, successCallback, errorCallback) {
        ///<summary>
        /// function to retrieve a specific record.
        ///</summary>
        if (!odataSetName)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the odataSetName parameter"); }
        if (!id)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the id parameter"); }
        if (!successCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the successCallback parameter"); }
        if (!errorCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the errorCallback parameter"); }

        var req = new XMLHttpRequest();
        req.open("GET", this._ODataUrl() + "/" + odataSetName + "(guid'" + id + "')", false);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            SDK.REST._retrieveResponse(this, successCallback, errorCallback);
        };
        req.send();

    },
    retrieveAsync: function (odataSetName, id, successCallback, errorCallback) {
        ///<summary>
        /// function to retrieve a specific record.
        ///</summary>
        if (!odataSetName)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the odataSetName parameter"); }
        if (!id)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the id parameter"); }
        if (!successCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the successCallback parameter"); }
        if (!errorCallback)
        { throw new Error("SDK.REST.retrieveMultipleAsync requires the errorCallback parameter"); }

        var req = new XMLHttpRequest();
        req.open("GET", this._ODataUrl() + "/" + odataSetName + "(guid'" + id + "')", true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            SDK.REST._retrieveResponse(this, successCallback, errorCallback);
        };
        req.send();

    },
    _retrieveResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// function to retrieve the response from SDK.REST.retrieveAsync
        ///</summary>
        if (req.readyState == 4 /* complete */) {
            if (req.status == 200) {
                //Success
                successCallback(JSON.parse(req.responseText).d);
                //successCallback(JSON.parse(req.responseText, SDK.REST.dateReviver).d.results);
            }
            else {
                errorCallback(JSON.parse(req.responseText).error);
            }
        }
    },
    associateAsync: function (entity1Set, entity1Id, entity2Set, entity2Id, relationship, successCallback, errorCallback) {
        ///<summary>
        /// Unimplemented function placeholder to associate a pair of records.
        ///</summary>
        var entity2 = {};
        entity2.uri = this._ODataUrl() + "/" + entity2Set + "(guid'" + entity2Id + "')";

        var req = new XMLHttpRequest();
        req.open("POST", this._ODataUrl() + "/" + entity1Set + "(guid'" + entity1Id + "')/$links/" + relationship, true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            SDK.REST._associateResponse(this, successCallback, errorCallback);
        };
        req.send(JSON.stringify(entity2));
    },
    _associateResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// Unimplemented function placeholder to retrieve the response from SDK.REST.associateAsync
        ///</summary>
        if (req.readyState == 4 /* complete */) {
            //There appears to be an issue where IE maps the 204 status to 1223 when no content is returned.
            if (req.status == 204 || req.status == 1223) {
                successCallback();
            }
            else {
                errorCallback(JSON.parse(req.responseText).error);
            }
        }
    },
    dissassociateAsync: function (entity1Set, entity1Id, entity2Id, relationship, successCallback, errorCallback) {
        ///<summary>
        /// function to disassociate a pair of records.
        ///</summary>
        var req = new XMLHttpRequest();
        req.open("POST", this._ODataUrl() + "/" + entity1Set + "(guid'" + entity1Id + "')/$links/" + relationship + "(guid'" + entity2Id + "')", true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("X-HTTP-Method", "DELETE");
        req.onreadystatechange = function () {
            SDK.REST._disassociateResponse(this, successCallback, errorCallback);
        };
        req.send();
    },
    _disassociateResponse: function (req, successCallback, errorCallback) {
        ///<summary>
        /// function to retrieve the response from SDK.REST.dissassociateAsync
        ///</summary>
        if (req.readyState == 4 /* complete */) {
            //There appears to be an issue where IE maps the 204 status to 1223 when no content is returned.
            if (req.status == 204 || req.status == 1223) {
                successCallback();
            }
            else {
                errorCallback(JSON.parse(req.responseText).error);
            }
        }
    },
    dateReviver: function (key, value) {
        ///<summary>
        /// A function to be used as a date reviver parameter to JSON.parse.
        ///</summary>
        ///<param name="key" type="String">
        /// The key for the JSON object
        ///</param>
        ///<param name="value" type="Object">
        /// The value for the JSON object
        ///</param>
        var a;
        if (typeof value === 'string') {
            a = /Date\(([-+]?\d+)\)/.exec(value); //Matches "\/Date(1234567890123)\/ or "\/Date(-1234567890123)\/"
            if (a) {
                return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
            }
        }
        return value;

    },

    //Sdk 2013
    _stringParameterCheck: function (parameter, message) {
        ///<summary>
        /// Private function used to check whether required parameters are null or undefined
        ///</summary>
        ///<param name="parameter" type="String">
        /// The string parameter to check;
        ///</param>
        ///<param name="message" type="String">
        /// The error message text to include when the error is thrown.
        ///</param>
        if (typeof parameter != "string") {
            throw new Error(message);
        }
    },
    _callbackParameterCheck: function (callbackParameter, message) {
        ///<summary>
        /// Private function used to check whether required callback parameters are functions
        ///</summary>
        ///<param name="callbackParameter" type="Function">
        /// The callback parameter to check;
        ///</param>
        ///<param name="message" type="String">
        /// The error message text to include when the error is thrown.
        ///</param>
        if (typeof callbackParameter != "function") {
            throw new Error(message);
        }
    },
    _ODataPath: function () {
        ///<summary>
        /// Private function to return the path to the REST endpoint.
        ///</summary>
        ///<returns>String</returns>
        return this._getClientUrl() + "/XRMServices/2011/OrganizationData.svc/";
    },
    _context: function () {
        ///<summary>
        /// Private function to the context object.
        ///</summary>
        ///<returns>Context</returns>
        if (typeof GetGlobalContext != "undefined")
        { return GetGlobalContext(); }
        else {
            if (typeof Xrm != "undefined") {
                return Xrm.Page.context;
            }
            else { throw new Error("Context is not available."); }
        }
    },
    _getClientUrl: function () {
        ///<summary>
        /// Private function to return the server URL from the context
        ///</summary>
        ///<returns>String</returns>
        var clientUrl = this._context().getClientUrl()

        return clientUrl;
    },
    _dateReviver: function (key, value) {
        ///<summary>
        /// Private function to convert matching string values to Date objects.
        ///</summary>
        ///<param name="key" type="String">
        /// The key used to identify the object property
        ///</param>
        ///<param name="value" type="String">
        /// The string value representing a date
        ///</param>
        var a;
        if (typeof value === 'string') {
            a = /Date\(([-+]?\d+)\)/.exec(value);
            if (a) {
                return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
            }
        }
        return value;
    },
    _errorHandler: function (req) {
        ///<summary>
        /// Private function return an Error object to the errorCallback
        ///</summary>
        ///<param name="req" type="XMLHttpRequest">
        /// The XMLHttpRequest response that returned an error.
        ///</param>
        ///<returns>Error</returns>
        //Error descriptions come from http://support.microsoft.com/kb/193625
        if (req.status == 12029)
        { return new Error("The attempt to connect to the server failed."); }
        if (req.status == 12007)
        { return new Error("The server name could not be resolved."); }
        var errorText;
        try
        { errorText = JSON.parse(req.responseText).error.message.value; }
        catch (e)
        { errorText = req.responseText }

        return new Error("Error : " +
              req.status + ": " +
              req.statusText + ": " + errorText);
    },
    retrieveMultipleRecords: function (type, options, successCallback, errorCallback, OnComplete) {
        ///<summary>
        /// Sends an asynchronous request to retrieve records.
        ///</summary>
        ///<param name="type" type="String">
        /// The Schema Name of the Entity type record to retrieve.
        /// For an Account record, use "Account"
        ///</param>
        ///<param name="options" type="String">
        /// A String representing the OData System Query Options to control the data returned
        ///</param>
        ///<param name="successCallback" type="Function">
        /// The function that will be passed through and be called for each page of records returned.
        /// Each page is 50 records. If you expect that more than one page of records will be returned,
        /// this function should loop through the results and push the records into an array outside of the function.
        /// Use the OnComplete event handler to know when all the records have been processed.
        /// </param>
        ///<param name="errorCallback" type="Function">
        /// The function that will be passed through and be called by a failed response.
        /// This function must accept an Error object as a parameter.
        /// </param>
        ///<param name="OnComplete" type="Function">
        /// The function that will be called when all the requested records have been returned.
        /// No parameters are passed to this function.
        /// </param>
        this._stringParameterCheck(type, "SDK.REST.retrieveMultipleRecords requires the type parameter is a string.");
        if (options != null)
            this._stringParameterCheck(options, "SDK.REST.retrieveMultipleRecords requires the options parameter is a string.");
        this._callbackParameterCheck(successCallback, "SDK.REST.retrieveMultipleRecords requires the successCallback parameter is a function.");
        this._callbackParameterCheck(errorCallback, "SDK.REST.retrieveMultipleRecords requires the errorCallback parameter is a function.");
        this._callbackParameterCheck(OnComplete, "SDK.REST.retrieveMultipleRecords requires the OnComplete parameter is a function.");

        var optionsString;
        if (options != null) {
            if (options.charAt(0) != "?") {
                optionsString = "?" + options;
            }
            else { optionsString = options; }
        }
        var req = new XMLHttpRequest();
        req.open("GET", this._ODataPath() + type + "Set" + optionsString, true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            if (this.readyState == 4 /* complete */) {
                req.onreadystatechange = null;
                if (this.status == 200) {
                    var returned = JSON.parse(this.responseText, SDK.REST._dateReviver).d;
                    successCallback(returned.results);
                    if (returned.__next != null) {
                        var queryOptions = returned.__next.substring((SDK.REST._ODataPath() + type + "Set").length);
                        SDK.REST.retrieveMultipleRecords(type, queryOptions, successCallback, errorCallback, OnComplete);
                    }
                    else { OnComplete(); }
                }
                else {
                    errorCallback(SDK.REST._errorHandler(this));
                }
            }
        };
        req.send();
    },
    __namespace: true
};

ExcelUploadUsing Javascripts

--><head>
    <meta charset="utf-8">

    <title></title>
    <link href="../styles/styles.css" rel="stylesheet" type="text/css">
    <script src="../Scripts/JQuery1.4.4.min.js" type="text/javascript"></script>
    <script src="../Scripts/JQueryLibrary.js" type="text/javascript"></script>

    <script src="../Scripts/json2.js" type="text/javascript"></script>
    <script src="../Scripts/XrmServiceToolkitSOAP.js" type="text/javascript"></script>
    <script type="text/javascript">
        function ExcelUpload() {
            debugger;

            if (window.parent.Xrm.Page.data.entity.getId() != null) {
                var guId = window.parent.Xrm.Page.data.entity.getId();

                var FileName = document.getElementById("Browse").value;

                var validExts = new Array(".xlsx", ".xls");
                var fileExt = FileName;
                fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
                if (fileExt == ".xlsx" || fileExt == ".xls") {
                    var fullPath = FileName;
                    var FileType;
                    var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
                    var filename = fullPath.substring(startIndex);
                    if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
                        filename = filename.substring(1);

                        FileType = filename.substr(0, filename.lastIndexOf('.')) || input;
                    }

                    var fetch = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                             "<entity name='hppscm_collectionupload'>" +
                             "<attribute name='hppscm_collectionuploadid' />" +
                              "<attribute name='hppscm_name' />" +
                              "<attribute name='hppscm_mode_of_payment' />" +
                              "<attribute name='hppscm_icr_reference_number' />" +
                               "<attribute name='hppscm_ddnumber' />" +
                               "<attribute name='hppscm_dddate' />" +
                                "<attribute name='hppscm_ddamount' />" +
                                 "<attribute name='hppscm_chequesalename' />" +
                                  "<attribute name='hppscm_bankreconciliation' />" +
                                   "<attribute name='hppscm_bankname' />" +
                                   "<order attribute='hppscm_name' descending='false' />" +
                                      "<filter type='and'>" +
                                       "<condition attribute='hppscm_name' operator='eq' value='hppscm_importdata' />" +
                                         "</filter>" +
                                         "</entity>" +
                                             "</fetch>";
                    var bankreconciliationFileName;
                    var chequesalenameFileName;
                    var modepayment; var icrreferencenumber; var dnumber; var ddate; var damount; var bname;
                    var collectionfiles = XrmServiceToolkit.Soap.Fetch(fetch);
                    if (collectionfiles.length > 0) {

                        if (collectionfiles[0].attributes["hppscm_bankreconciliation"] != undefined && collectionfiles[0].attributes.hppscm_bankreconciliation.value != null) {
                            bankreconciliationFileName = collectionfiles[0].attributes.hppscm_bankreconciliation.value;
                            // chequesalenameFileName = collectionfiles[0].attributes.hppscm_chequesalename.value;
                            modepayment = collectionfiles[0].attributes.hppscm_mode_of_payment.value;
                            icrreferencenumber = collectionfiles[0].attributes.hppscm_icr_reference_number.value;
                            bname = collectionfiles[0].attributes.hppscm_bankname.value;
                            ddate = collectionfiles[0].attributes.hppscm_dddate.value;
                            damount = collectionfiles[0].attributes.hppscm_ddamount.value;
                            dnumber = collectionfiles[0].attributes.hppscm_ddnumber.value;
                        }
                    }


                    if (FileType.toLowerCase() == bankreconciliationFileName.toLowerCase()) {


                        var excel = new ActiveXObject("Excel.Application");
                        var excel_file = excel.Workbooks.Open(FileName);
                        var excel_sheet = excel_file.Worksheets("Sheet1");
                        var Rows = excel_sheet.UsedRange.Cells.Rows.Count;
                        var Columns = excel_sheet.UsedRange.Cells.Columns.Count;
                        var PaymentMode = excel_file.ActiveSheet.Cells(1, 1).Value;
                        var date = excel_file.ActiveSheet.Cells(1, 2).Value;
                        var Number = excel_file.ActiveSheet.Cells(1, 3).Value;
                        var Name = excel_file.ActiveSheet.Cells(1, 4).Value;
                        var ICRefno = excel_file.ActiveSheet.Cells(1, 5).Value;
                        var Amount = excel_file.ActiveSheet.Cells(1, 6).Value;
                        if (PaymentMode.toLowerCase() == modepayment.toLowerCase() && date.toLowerCase() == ddate.toLowerCase() && Number.toLowerCase() == dnumber.toLowerCase() && Name.toLowerCase() == bname.toLowerCase() && ICRefno.toLowerCase() == icrreferencenumber.toLowerCase() && Amount.toLowerCase() == damount.toLowerCase() && Columns == 6) {

                            var GrandTotal = 0;
                            var sum = 0;
                            for (var i = 1; i < Rows  ; i++) {

                                try {

                                    var Paymode = new XrmServiceToolkit.Soap.BusinessEntity("hppscm_paymentmodeselection");


                                    if (excel_file.ActiveSheet.Cells(i + 1, 1).Value != undefined) {
                                        var modeofpayment = excel_file.ActiveSheet.Cells(i + 1, 1).Value;
                                        Paymode.attributes["hppscm_name"] = modeofpayment;

                                    }
                                    if (excel_file.ActiveSheet.Cells(i + 1, 2).Value != undefined) {

                                        var Ddate = new Date(excel_file.ActiveSheet.Cells(i + 1, 2).Value);
                                        Paymode.attributes["hppscm_dddate"] = Ddate;
                                    }


                                    if (excel_file.ActiveSheet.Cells(i + 1, 3).Value != undefined) {
                                        var DDNumber = String(excel_file.ActiveSheet.Cells(i + 1, 3).Value);
                                        Paymode.attributes["hppscm_transactionnumber"] = DDNumber;
                                    }
                                    if (excel_file.ActiveSheet.Cells(i + 1, 4).Value != undefined) {
                                        var BankName = excel_file.ActiveSheet.Cells(i + 1, 4).Value;
                                        Paymode.attributes["hppscm_bankname"] = BankName;

                                    }
                                    if (excel_file.ActiveSheet.Cells(i + 1, 5).Value != undefined) {
                                        var ICRRefno = excel_file.ActiveSheet.Cells(i + 1, 5).Value;
                                        Paymode.attributes["hppscm_referencenumber"] = ICRRefno;
                                    }
                                    if (excel_file.ActiveSheet.Cells(i + 1, 6).Value != undefined) {
                                        var DDAmount = excel_file.ActiveSheet.Cells(i + 1, 6).Value;
                                        Paymode.attributes["hppscm_fees"] = { value: DDAmount, type: "Money" };
                                        sum = sum + DDAmount;


                                    }

                                    Paymode.attributes["hppscm_paymentmodeid"] = { id: guId, logicalName: "hppscm_paymentmodeselection", type: "EntityReference" };
                                    Paymode.attributes["hppscm_bankreconcilation"] = { value: 1, type: "OptionSetValue" };
                                    Paymode.attributes["hppscm_transactionidentifier"] = { value: 2, type: "OptionSetValue" };

                                    var fetchXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' >" +

                              "<entity name='hppscm_modeofpayment'>" +

                              "<attribute name='hppscm_modeofpaymentid' />" +

                              "<attribute name='hppscm_name' />" +

                              "<filter type='and'>" +

                              "<condition attribute='hppscm_name' operator='eq' value='" + modeofpayment + "' />" +

                               "</filter>" +

                               "</entity>" + "</fetch>";

                                    var PaymentMode = XrmServiceToolkit.Soap.Fetch(fetchXML);

                                    if (PaymentMode.length > 0) {
                                        var paymentid = PaymentMode[0].attributes.hppscm_modeofpaymentid.value;
                                        Paymode.attributes["hppscm_paymentmodes"] = { id: paymentid, logicalName: "hppscm_paymentmodeselection", type: "EntityReference" };
                                        XrmServiceToolkit.Soap.Create(Paymode);

                                    }
                                    else {
                                        alert("Mode of Payment doesnot available in paymentmode masters");
                                        XrmServiceToolkit.Soap.CreateErrorLog("RowNumber: " + i, "Mode of Payment doesnot available in paymentmode masters ","Check Payment Masters");
                                        break;
                                    }

                                }
                                catch (error) {
                                    XrmServiceToolkit.Soap.CreateErrorLog("BankReconciliation", error.message, error.stack + "\r\n");
                                }
                            }


                            if (FileType.toLowerCase() == bankreconciliationFileName.toLowerCase() && PaymentMode.length > 0) {

                                alert("Bank Reconciliation file successfully uploaded.");

                                var webResource = window.parent.Xrm.Page.ui.controls.get("WebResource_RICustomHTMLSubgridPaymentSelection");
                                webResource.setSrc(webResource.getSrc());
var webResource =window.parent.Xrm.Page.ui.controls.get("WebResource_PaymentmodeGrandtotals");
    webResource.setSrc(webResource.getSrc());
                                if (window.parent.Xrm.Page.getAttribute("hppscm_total_payments_fee").getValue() != null) {

                                    var payments = window.parent.Xrm.Page.getAttribute("hppscm_total_payments_fee").getValue()
                                    GrandTotal = parseFloat(payments) + parseFloat(sum);
                                    window.parent.Xrm.Page.getAttribute("hppscm_total_payments_fee").setValue(GrandTotal.toString());
                                    window.parent.Xrm.Page.getAttribute("hppscm_total_payments_fee").setSubmitMode("always");
                                    window.parent.Xrm.Page.data.entity.save();
                                }


                                XrmServiceToolkit.Soap.CreateErrorLog("RowNumber: " + i, "Bank Reconciliation file Successfully Uploaded ","Collection data");

                            }




                        }

                        else {
                            alert("Invaild Bank Reconciliation excel file format.");

                        }

                    }
                    else {
                        alert(" Invalid Bank Reconciliation file Name format.");
                    }

                }
                else {

                    alert("Please select a  Bank Reconciliation Excel file to upload.");
                }



            }

        }

    </script>
</head>
<body>