XrmServiceToolkit.Soap Methods

These examples are built and combined with qunit. Please check  http://docs.jquery.com/QUnit  for more details if you are new to it. Note You do need the qUnit code when using these methods in development.

Execute

test("Test XrmServiceToolkit.Soap.Execute() method using WhoAmIRequest message to get current user's ID", function () {

            var request = "<request i:type='b:WhoAmIRequest' xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts' xmlns:b='http://schemas.microsoft.com/crm/2011/Contracts'>" +
                            "<a:Parameters xmlns:c='http://schemas.datacontract.org/2004/07/System.Collections.Generic' />" +
                            "<a:RequestId i:nil='true' />" +
                            "<a:RequestName>WhoAmI</a:RequestName>" +
                          "</request>";
            var whoAmI = XrmServiceToolkit.Soap.Execute(request);
            whoamiUserId = whoAmI.getElementsByTagName("a:Results")[0].childNodes[0].childNodes[1].text;
            ok(guidExpr.test(whoamiUserId), "WhoAmI request should returned a valid GUID. ");

});

GetCurrentUserId

test("Test XrmServiceToolkit.Soap.GetCurrentUserId() method to get current user's ID", function () {

            currentUserId = XrmServiceToolkit.Soap.GetCurrentUserId();
            equals(currentUserId, whoamiUserId, "getCurrentUserId() method should return the same user ID as WhoAmI request. ");

});

IsCurrentUserInRole

test("Test XrmServiceToolkit.Soap.IsCurrentUserInRole() method to check if current user is a System Administrator.", function () {

            var isSystemAdministrator = XrmServiceToolkit.Soap.IsCurrentUserRole("System Administrator");
            ok(isSystemAdministrator, "You ought to be a System Administrator to run test for isCurrentUserInRole() method. ");

});

GetCurrentUserRoles

test("Test XrmServiceToolkit.Soap.GetCurrentUserRoles() method to get all the system roles that the current user has been assigned to.", function () {

            var roles = XrmServiceToolkit.Soap.GetCurrentUserRoles();
            ok(roles.constructor.toString().indexOf("Array") != -1, "getCurrentUserRoles() method should an array of user roles. ");

        });
Create
test("Test XrmServiceToolkit.Soap.Create() method to create a CRM record (contact)", function () {

            var createContact = new XrmServiceToolkit.Soap.BusinessEntity("contact");
            createContact.attributes["firstname"] = "Diane";
            createContact.attributes["lastname"] = "Morgan";
            createContact.attributes["middlename"] = "<&>";   // Deliberate special characters to ensure that the toolkit can handle special characters correctly.
            createContact.attributes["gendercode"] = { value: 2, type: "OptionSetValue" };
            createContact.attributes["familystatuscode"] = { value: 1, type: "OptionSetValue" }; // Picklist : Single - 1
            createContact.attributes["creditlimit"] = { value: 2, type: "Money" };
            createContact.attributes["birthdate"] = birthDate;
            createContact.attributes["donotemail"] = true;
            createContact.attributes["donotphone"] = false;
            createContact.attributes["parentcustomerid"] = { id: accountId, logicalName: "account", type: "EntityReference" };

            contactId = XrmServiceToolkit.Soap.Create(createContact);

            ok(guidExpr.test(contactId), "Creating a contact should returned the new record's ID in GUID format. ");

});

Update

test("Test XrmServiceToolkit.Soap.Update() method to update a CRM record (contact)", function () {

            equals(contactId, contactId, "ContactID");
            var updateContact = new XrmServiceToolkit.Soap.BusinessEntity("contact", contactId);
            updateContact.attributes["firstname"] = "Diane";
            updateContact.attributes["lastname"] = "Lopez";
            updateContact.attributes["donotpostalmail"] = null;
            updateContact.attributes["familystatuscode"] = { value: 2, type: "OptionSetValue" }; // Married

            var updateResponse = XrmServiceToolkit.Soap.Update(updateContact);

            ok(updateResponse === "", "The contact should be able to be updated.");
});

Retrieve

test("Test XrmServiceToolkit.Soap.Retrieve() method to retrieve a CRM record (contact)", function () {

            var cols = ["firstname", "lastname", "middlename", "familystatuscode", "ownerid", "creditlimit", "birthdate", "donotemail", "donotphone"];
            var retrievedContact = XrmServiceToolkit.Soap.Retrieve("contact", contactId, cols);

            equals(retrievedContact.attributes['lastname'].value, "Lopez", "A retrieve of just updated contact has proved that its last name has actually been updated. ");
            equals(retrievedContact.attributes['firstname'].value, "Diane", "firstname matches");
            equals(retrievedContact.attributes['middlename'].value, "<&>", "middlename matches");
            equals(retrievedContact.attributes['familystatuscode'].value, 2, "familystatuscode matches");
            equals(retrievedContact.attributes['familystatuscode'].type, "OptionSetValue", "CRM picklist's JavaScript type should be OptionSetValue");
            ok(CompareGuid(retrievedContact.attributes['ownerid'].id, currentUserId), "ownerid matches");
            equals(retrievedContact.attributes['creditlimit'].value, 2, "creditlimit matches");
            equals(retrievedContact.attributes['creditlimit'].type, "Money", "CRM number's JavaScript type should be Money");
            equals(retrievedContact.attributes['birthdate'].value.getTime(), birthDate.getTime(), "birthdate matches");
            equals(retrievedContact.attributes['donotemail'].value, true, "donotemail matches");
            equals(retrievedContact.attributes['donotemail'].type, "boolean", "CRM bit field's value type should be boolean (donotemail)");
            equals(retrievedContact.attributes['donotphone'].value, false, "donotphone matches");
            equals(retrievedContact.attributes['donotphone'].type, "boolean", "CRM bit's JavaScript type should be boolean (donotphone");
            same(typeof retrievedContact.attributes['donotpostalmail'], "undefined", "donotpostalmail matches");
});

RetrieveMultiple

test("Test XrmServiceToolkit.Soap.RetrieveMultiple() method to retrieve a CRM record (contact)", function () {

            var query =
                     "<a:ColumnSet>" +
                      "<a:AllColumns>false</a:AllColumns>" +
                      "<a:Columns xmlns:b='http://schemas.microsoft.com/2003/10/Serialization/Arrays'>" +
                        "<b:string>firstname</b:string>" +
                        "<b:string>lastname</b:string>" +
                        "<b:string>middlename</b:string>" +
                        "<b:string>familystatuscode</b:string>" +
                        "<b:string>ownerid</b:string>" +
                        "<b:string>creditlimit</b:string>" +
                        "<b:string>birthdate</b:string>" +
                        "<b:string>donotemail</b:string>" +
                        "<b:string>donotphone</b:string>" +
                      "</a:Columns>" +
                    "</a:ColumnSet>" +
                    "<a:Criteria>" +
                      "<a:Conditions />" +
                      "<a:FilterOperator>And</a:FilterOperator>" +
                      "<a:Filters>" +
                        "<a:FilterExpression>" +
                          "<a:Conditions>" +
                            "<a:ConditionExpression>" +
                              "<a:AttributeName>contactid</a:AttributeName>" +
                              "<a:Operator>Equal</a:Operator>" +
                              "<a:Values xmlns:b='http://schemas.microsoft.com/2003/10/Serialization/Arrays'>" +
                                "<b:anyType i:type='c:string' xmlns:c='http://www.w3.org/2001/XMLSchema'>"+ contactId +"</b:anyType>" +
                              "</a:Values>" +
                            "</a:ConditionExpression>" +
                          "</a:Conditions>" +
                          "<a:FilterOperator>And</a:FilterOperator>" +
                          "<a:Filters />" +
                        "</a:FilterExpression>" +
                      "</a:Filters>" +
                    "</a:Criteria>" +
                    "<a:Distinct>false</a:Distinct>" +
                    "<a:EntityName>contact</a:EntityName>" +
                    "<a:LinkEntities />" +
                    "<a:Orders />" +
                    "<a:PageInfo>" +
                      "<a:Count>0</a:Count>" +
                      "<a:PageNumber>0</a:PageNumber>" +
                      "<a:PagingCookie i:nil='true' />" +
                      "<a:ReturnTotalRecordCount>false</a:ReturnTotalRecordCount>" +
                    "</a:PageInfo>" +
                    "<a:NoLock>false</a:NoLock>";

            var retrievedContacts = XrmServiceToolkit.Soap.RetrieveMultiple(query);

            equals(retrievedContacts.length, 1, "only last created contact should be found");
            equals(retrievedContacts[0].attributes['lastname'].value, "Lopez", "A retrieve of just updated contact has proved that its last name has actually been updated. ");
            equals(retrievedContacts[0].attributes['firstname'].value, "Diane", "firstname matches");
            equals(retrievedContacts[0].attributes['middlename'].value, "<&>", "middlename matches");
            equals(retrievedContacts[0].attributes['familystatuscode'].value, 2, "familystatuscode matches");
            equals(retrievedContacts[0].attributes['familystatuscode'].type, "OptionSetValue", "CRM picklist's JavaScript type should be OptionSetValue");
            ok(CompareGuid(retrievedContacts[0].attributes['ownerid'].id, currentUserId), "ownerid matches");
            equals(retrievedContacts[0].attributes['creditlimit'].value, 2, "creditlimit matches");
            equals(retrievedContacts[0].attributes['creditlimit'].type, "Money", "CRM number's JavaScript type should be Money");
            equals(retrievedContacts[0].attributes['birthdate'].value.getTime(), birthDate.getTime(), "birthdate matches");
            equals(retrievedContacts[0].attributes['donotemail'].value, true, "donotemail matches");
            equals(retrievedContacts[0].attributes['donotemail'].type, "boolean", "CRM bit field's value type should be boolean (donotemail)");
            equals(retrievedContacts[0].attributes['donotphone'].value, false, "donotphone matches");
            equals(retrievedContacts[0].attributes['donotphone'].type, "boolean", "CRM bit's JavaScript type should be boolean (donotphone");
            same(typeof retrievedContacts[0].attributes['donotpostalmail'], "undefined", "donotpostalmail matches");

});

Fetch

test("Test XrmServiceToolkit.Soap.Fetch() method to retrieve a CRM record (contact)", function () {

            var fetchXml =
                    "<fetch mapping='logical'>" +
                       "<entity name='contact'>" +
                          "<attribute name='contactid' />" +
                          "<attribute name='firstname' />" +
                          "<attribute name='lastname' />" +
                          "<attribute name='middlename' />" +
                          "<attribute name='familystatuscode' />" +
                          "<attribute name='ownerid' />" +
                          "<attribute name='creditlimit' />" +
                          "<attribute name='birthdate' />" +
                          "<attribute name='accountrolecode' />" +
                          "<attribute name='donotemail' />" +
                          "<attribute name='donotphone' />" +
                          "<filter>" +
                             "<condition attribute='contactid' operator='eq' value='" + contactId + "' />" +
                          "</filter>" +
                       "</entity>" +
                    "</fetch>";

            var retrievedContacts = XrmServiceToolkit.Soap.Fetch(fetchXml);

            equals(retrievedContacts.length, 1, "only last created contact should be found");
            equals(retrievedContacts[0].attributes['lastname'].value, "Lopez", "A retrieve of just updated contact has proved that its last name has actually been updated. ");
            equals(retrievedContacts[0].attributes['firstname'].value, "Diane", "firstname matches");
            equals(retrievedContacts[0].attributes['middlename'].value, "<&>", "middlename matches");
            equals(retrievedContacts[0].attributes['familystatuscode'].value, 2, "familystatuscode matches");
            equals(retrievedContacts[0].attributes['familystatuscode'].type, "OptionSetValue", "CRM picklist's JavaScript type should be OptionSetValue");
            ok(CompareGuid(retrievedContacts[0].attributes['ownerid'].id, currentUserId), "ownerid matches");
            equals(retrievedContacts[0].attributes['creditlimit'].value, 2, "creditlimit matches");
            equals(retrievedContacts[0].attributes['creditlimit'].type, "Money", "CRM number's JavaScript type should be Money");
            equals(retrievedContacts[0].attributes['birthdate'].value.getTime(), birthDate.getTime(), "birthdate matches");
            equals(retrievedContacts[0].attributes['donotemail'].value, true, "donotemail matches");
            equals(retrievedContacts[0].attributes['donotemail'].type, "boolean", "CRM bit field's value type should be boolean (donotemail)");
            equals(retrievedContacts[0].attributes['donotphone'].value, false, "donotphone matches");
            equals(retrievedContacts[0].attributes['donotphone'].type, "boolean", "CRM bit's JavaScript type should be boolean (donotphone");
            same(typeof retrievedContacts[0].attributes['donotpostalmail'], "undefined", "donotpostalmail matches");

});
test("Test XrmServiceToolkit.Soap.Fetch() method to do an aggregation query", function () {

            var fetchXml =
                "<fetch mapping='logical' aggregate='true'>" +
                   "<entity name='contact'>" +
                      "<attribute name='contactid' aggregate='count' alias='count' />" +
                      "<filter>" +
                         "<condition attribute='contactid' operator='eq' value='" + contactId + "' />" +
                      "</filter>" +
                   "</entity>" +
                "</fetch>";

            var fetchedContacts = XrmServiceToolkit.Soap.Fetch(fetchXml);

            equals(fetchedContacts.length, 1, "only one record should be returned when doing aggregation.");
            equals(fetchedContacts[0].attributes['count'].formattedValue, "1", "only one contact record would match the id.");
});

QueryByAttribute

test("Test XrmServiceToolkit.Soap.QueryByAttribute() method to retrieve a CRM record (contact) using two criteria", function () {
            var queryOptions = {
                entityName: "contact",
                attributes: ["firstname", "middlename", "lastname"],
                values: ["Diane", "<&>", "Lopez"],
                columnSet: ["firstname", "lastname", "middlename", "familystatuscode", "ownerid", "creditlimit", "birthdate", "donotemail", "donotphone"],
                orderby: ["firstname", "lastname"] // Order by firstname and then lastname even though we are only getting one record back
            };

            var fetchedContacts = XrmServiceToolkit.Soap.QueryByAttribute(queryOptions);

            ok(fetchedContacts.length >= 1, "at least there should be one matched contact record, which is what we just created");
});

Last edited Nov 3, 2013 at 8:10 PM by jaimieji, version 16

Comments

KingRider Dec 30, 2015 at 12:41 PM 
Where a solution create from birthDate.... wtf!! kkkk
*** createContact.attributes["birthdate"] = birthDate; ***

Example:
var today = new Date("1978/4/12");
var birthDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());

KingRider Dec 4, 2015 at 4:04 PM 
@deadrabit: change ur frame from console and look example http://prntscr.com/9aa6yb

@csgexec: Not use IF of undefined is exist bug ... but use scripts a example: [code]Try { console.log(XrmServiceToolkit.Soap.GetCurrentUserId()); } catch {e} { console.log('Error ID'); }[/code]

deadrabit Nov 6, 2013 at 5:00 PM 
How can I handle errors in asynchronous requests?
and could I be cheeky and request some "real world" samples, featuring things like error handling, asynchronous code and initialising the library.

it seems both csgexec and I had the same trouble using the library in web resources, because the code is loaded in an IFRAME it has to get the context from the parent object:
if( typeof Xrm === "undefined" ) Xrm = window.parent.Xrm;

but if you're trying to test your web resource locally, you can also mock the Xrm object, IIRC the code is:
window.Xrm = {
Page: {
context: {
getServerUrl: function() { return "http://your.mscrm:5555/Organisation/"; }
}
}
};
which gets most of the functions working

the other thing I've found is that in RU12-RU14 the loading order of form libraries is not guarenteed which means that since this library is fairly large it will probably load after your form javascript onload functions have tried to execute "XrmServiceToolkit is undefined". FYI - best solution to this is to rollup to 15.

But anyway yeah, I'm refactoring synchronous code to be asynchronous using the JQuery deferred object but I'm halfway through and growing concerned that I've removed all error-handling from my project.

jaimieji Mar 5, 2012 at 10:23 AM 
Cheers. csgexec. Will update code soon

csgexec Feb 28, 2012 at 12:17 AM 
I got it to work by revising the _context function as such:
if (typeof GetGlobalContext != "undefined") {
return GetGlobalContext();
}
else {
if (typeof Xrm != "undefined") {
return Xrm.Page.context;
}
else {
if (typeof window.parent.Xrm != "undefined") {
return window.parent.Xrm.Page.context;
}
else {
throw new Error("Context is not available.");
}
}

}

csgexec Feb 27, 2012 at 7:41 PM 
Actually I receive 'Context is not available' from just about any of the functions, which is concerning because I assume most times the library will be referenced in a web resource, which will be an iFrame and not have the parent's context.

csgexec Feb 27, 2012 at 7:05 PM 
I receive 'Context is not available.' when trying to use SOAP functions (specifically GetCurrentUserId). The library is referenced in an HTML web resource.