Archive

Posts Tagged ‘OData’

Reading related records using OData and Jscript – CRM 2011

I have 1:N relationship between “Contact” entity and custom entity “Bikes” (i.e., 1 contact can have N no of Bikes).

If I want to read all “Bikes” along with my “Contact” information using OData service, I can use the “$expand” keyword of OData protocol.

Below is the generic function to prepare the OData URL and make a Asynchronous service call

function retrieveMultiple(odataSetName, select, filter, expand, successCallback) {

var serverUrl = Xrm.Page.context.getServerUrl();

var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;

var odataUri = serverUrl + ODATA_ENDPOINT + “/” + odataSetName + “?”;

if (select) {

odataUri += “$select=” + select;

}

if (expand) {

odataUri += “&” + “$expand=” + expand;

}

if (filter) {

odataUri += “&” + “$filter=” + filter;

}

$.ajax({

type: “GET”,

contentType: “application/json; charset=utf-8”,

datatype: “json”,

url: odataUri,

beforeSend: function (XMLHttpRequest) {

XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);

},

success: function (data, textStatus, XmlHttpRequest) {

if (successCallback) {

if (data && data.d && data.d.results) {

successCallback(data.d.results, textStatus, XmlHttpRequest);

}

else if (data && data.d) {

successCallback(data.d, textStatus, XmlHttpRequest);

}

else {

successCallback(data, textStatus, XmlHttpRequest);

}

}

},

error: function (XmlHttpRequest, textStatus, errorThrown) {

if (XmlHttpRequest && XmlHttpRequest.responseText) {

alert(“Error while retrieval of ” + odataSetName + ” ; Error – ” + XmlHttpRequest.responseText);

}

}

});

}

How do I use above function

  • Consider my “Contact” & “Bike” scenario and set required the columns and “expand” option and call the above “retrieveMultiple” function
  • Below is the function to define properties

function retrieveBikesByContactId() {

// Pass ‘Contact’ set name

var oDataSetName = “ContactSet”;

// Set Contact GUID

var contactId = {Contact GUID};

// Prepare filter

var filter = “ContactId eq guid'” + contactId + “‘”;

// Set expand (i.e., Relationship name of ‘Contact’ and ‘Bike’)

var expand = “honda_contact_honda_bikeinformation”;

// Column names of ‘Contact’ and ‘Bikes’

// Since Bike is related entity specify Bike columns as (Relationship name\column name) (i.e., honda_contact_honda_bikeinformation/honda_name)

var columns = “FullName,honda_contact_honda_bikeinformation/honda_name,honda_contact_honda_bikeinformation/honda_Year”;

retrieveMultiple(oDataSetName, columns, filter, expand, readDataOnSuccess);

}

  • After the success of data retrieval, parse the result using “readDataOnSuccess” method

function readDataOnSuccess(data, textStatus, XmlHttpRequest) {

if (data && data.length > 0) {

for (var indx = 0; indx < data.length; indx++) {

if (data[indx].honda_contact_honda_bikeinformation) {

              // Read the child entity records using “expand.results” (i.e., honda_contact_honda_bikeinformation.results)

var childResults = data[indx].honda_contact_honda_bikeinformation.results;

for (var indxChild = 0; indxChild < childResults.length; indxChild++) {

alert(childResults[indxChild].honda_name);

}

}

}

}

}

Use the “OData Query Designer” tool to get the “expand” name and column names

  • To get related entity record fields, click “One To Many” tab and choose the relationship
Get Related Entity Fields

Get Related Entity Fields

URL with Related records columns

URL with Related records columns

Related records result set

Related records result set

Checking whether user part of team using jscript CRM 2011

June 23, 2012 2 comments

Hi,

We can verify whether the User is part of particular Team using jscript.

Below is the jscript function

function isUserPartOfTeam(userId, teamId) {

var oDataEndpointUrl = serverUrl + “/XRMServices/2011/OrganizationData.svc/”;

oDataEndpointUrl += “TeamMembershipSet?$select=BusinessUnitId&$filter=TeamId eq guid'” + teamId + “‘ SystemUserId eq guid'” + userId + “‘”;

var service = GetRequestObject();

if (service != null) {

service.open(“GET”, oDataEndpointUrl, false);

service.setRequestHeader(“X-Requested-Width”, “XMLHttpRequest”);

service.setRequestHeader(“Accept”, “application/json,text/javascript, */*”);

service.send(null);

var requestResults = eval(‘(‘ + service.responseText + ‘)’).d;

if (requestResults != null && requestResults.results.length > 0) {

return true;

}

}

return false;

}

How do I call this method :-

  • Pass User Id & Team Id to the function.
  • Function returns true/false

var userId={User GUID};

var teamId={Team GUID};

var flag= isUserPartOfTeam(userId, teamId);

🙂

Deleting notes attachments using jscript in CRM 2011

Hi,

In CRM, we can add files as attachments to the Notes.

Notes with attachment

Notes with attachment

  • All the notes get saved in to “Annotation” entity in the data base.
  • The attachment information get saved in to below columns of “Annotation” entity
    • Document Body
    • File Name
    • File Size
    • Is Document
Notes with attachments - Data base columns

Notes with attachments – Data base columns

Deleting attachments using  script:-

To delete the attachment using jscript,

  • Update the “Document Body,File Name,File Size” fields to null
  • And “IsDocument = false” using OData as below

function deleteAttachments(){

var notesId = {GUID of notes};

var objNotes = new Object();

objNotes.DocumentBody = null;

objNotes.FileName = null;

objNotes.FileSize = null;

objNotes.IsDocument = false;

updateRecord(notesId, objNotes, “AnnotationSet”);

}

function updateRecord(id, entityObject, odataSetName) {

var jsonEntity = window.JSON.stringify(entityObject);

var serverUrl = Xrm.Page.context.getServerUrl();

var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;

var updateRecordReq = new XMLHttpRequest();

var ODataPath = serverUrl + ODATA_ENDPOINT;

updateRecordReq.open(‘POST’, ODataPath + “/” + odataSetName + “(guid'” + id + “‘)”, false);

updateRecordReq.setRequestHeader(“Accept”, “application/json”);

updateRecordReq.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);

updateRecordReq.setRequestHeader(“X-HTTP-Method”, “MERGE”);

updateRecordReq.send(jsonEntity);

}

🙂

 

Retrieve multiple records synchronously using OData & JQuery in CRM 2011

Hi,

Below is the Jscript function to retrieve multiple records synchronously using OData & JQuery.

function retrieveMultipleSync(odataSetName, select, filter) {

var serverUrl = Xrm.Page.context.getServerUrl();

var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;

var odataUri = serverUrl + ODATA_ENDPOINT + “/” + odataSetName + “?”;

if (select) {

odataUri += “$select=” + select ;

}

if (filter) {

odataUri += “&” + “$filter=” + filter;

}

var service = GetRequestObject();

if (service != null) {

service.open(“GET”, odataUri, false);

service.setRequestHeader(“X-Requested-Width”, “XMLHttpRequest”);

service.setRequestHeader(“Accept”, “application/json,text/javascript, */*”);

service.send(null);

var requestResults = eval(‘(‘ + service.responseText + ‘)’).d;

return requestResults;

}

}

function GetRequestObject() {

var req = false;

if (window.XMLHttpRequest) {

req = new XMLHttpRequest();

} else if (window.ActiveXObject) {

req = new ActiveXObject(“Microsoft.XMLHTTP”);

}

return req;

}

  • Copy & Paste above method to a new .jscript file
  • Replace double quotes(“) symbols with your keyboard double quotes
  • Add the new .jscript file as web resource to CRM application
  • Add “Jquery” & json” helper classes as web resources

How do I call this method :-

  • In my sample below, I will show you how to read “Contacts” of an “Account”

function retrieveContactsByAccountId(accountId) {

// Pass ‘Contact’ set name since we are reading Contacts

var oDataSetName = “ContactSet”;

// Column names of ‘Contact’ (Pass * to read all columns)

var columns = “FirstName,LastName”;

// Prepare filter

var filter = “AccountId/Id eq guid'” + accountId + “‘”;

var requestResults  = retrieveMultipleSync(oDataSetName, columns, filter);

if (requestResults != null) {

if (requestResults.results != null && requestResults.results.length > 0) {

for (var indxContacts = 0; indxContacts < requestResults.results.length; indxContacts++) {

var contact = requestResults.results[indxContacts];

if (contact.FirstName) {

alert(“Contact’s First Name – ” + contact.FirstName);

}

}

}

}

else {

alert(“Error while retrieving; Error – ” + service.responseText);

}

}

Get OData URI conventions from here

🙂

Limitation of OData End Point – Setting Activity Parties

Hi,

In one of my requirement, I had to create an “Appointment” record programmatically using Jscript by populating field ‘required attendees’ (i.e., ActivityParty) to it.

I followed below steps to complete the requirement

  • Created the “Appointment” record first
  • Added 2 contacts as “Required Attendees” to Appointment, for which I used below code and called it 2 times since I need to create 2 activity parties

var activityParty = new Object();

activityParty.PartyId = {

Id: participentId,

LogicalName: participentLogicalName

};

activityParty.ActivityId = {

Id: activityId,

LogicalName: “appointment”

};

activityParty.ParticipationTypeMask = { Value: 5 }; //5 = Required Attendees

var activityParty = createRecord (activityParty, “ActivityPartySet”);

Issue I faced :-

  • The problem I faced was,
    • only one “Contact” added as “Required Attendees” (i.e., Only 1 Activity Party is creating) instead of 2
    • When I debug the script and DB, I observed that 1st activity party is getting created initially but once after the 2nd activity party created, the first one is getting deleted

Reason & Workaround :-

  • Later I came to know that, this is the limitation of OData end point.
  • As a workaround, I registered a Plugin on post create of “Appointment” and added “Activity Parties”

🙂

Delete record synchronously using OData and JScript in CRM 2011

April 25, 2012 1 comment

Hi,

Below is the script to delete record synchronously

function deleteRecordSync(recordId, odataSetName) {

// Get Server URL

var serverUrl = Xrm.Page.context.getServerUrl();

//The OData end-point

var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;

var deleteRecordReq = new XMLHttpRequest();

var ODataPath = serverUrl + ODATA_ENDPOINT;

deleteRecordReq.open(‘POST’, ODataPath + “/” + odataSetName + “(guid'” + recordId + “‘)”, false);

deleteRecordReq.setRequestHeader(“Accept”, “application/json”);

deleteRecordReq.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);

deleteRecordReq.setRequestHeader(“X-HTTP-Method”, “DELETE“);

deleteRecordReq.send(null);

}

How do I call this method :-

  • To delete an “Account”
  • Pass account GUID and OData Set name (i.e.,AccountSet)

Var accountId=”{Account GUID}”;

deleteRecordSync (accountId , “AccountSet”);

🙂

Update record synchronously using OData and JScript in CRM 2011

Hi,

Below is the Jscript function to update record synchronously using OData and Jscript

function updateRecordSync(id, entityObject, odataSetName) {

var jsonEntity = window.JSON.stringify(entityObject);

// Get Server URL

var serverUrl = Xrm.Page.context.getServerUrl();

//The OData end-point

var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;

var updateRecordReq = new XMLHttpRequest();

var ODataPath = serverUrl + ODATA_ENDPOINT;

updateRecordReq.open(‘POST’, ODataPath + “/” + odataSetName + “(guid'” + id + “‘)”, false);

updateRecordReq.setRequestHeader(“Accept”, “application/json”);

updateRecordReq.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);

updateRecordReq.setRequestHeader(“X-HTTP-Method”, “MERGE“);

updateRecordReq.send(jsonEntity);

}

How do I call this method :-

  • Create a new .jscript file (i.e., “account.js”)
  • Copy & Paste above code
  • Add “account.js” as a webresource in CRM
  • Add “Json2.js” & “jquery1.4.1.min.js” helper script files as webresources
  • Get the helper files from CRM 2011 SDk under path “\sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts”
  • To update an “Account”
  • Pass “Account” object and GUID and OData Set name (i.e.,AccountSet)

Var accountId=”{Account GUID}”;

var account = new Object();

account.Name = “Rajeev Pentyala”;

updateRecordSync (accountId ,account, “AccountSet”);

🙂

Create record synchronously using OData and JScript in CRM 2011

April 19, 2012 4 comments

Hi,

Below is the Jscript function to create record synchronously using OData and Jscript

function createRecordSync(entityObject, odataSetName) {

var jsonEntity = window.JSON.stringify(entityObject);

// Get Server URL

var serverUrl = Xrm.Page.context.getServerUrl();

//The OData end-point

var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;

var createRecordReq = new XMLHttpRequest();

var ODataPath = serverUrl + ODATA_ENDPOINT;

createRecordReq.open(‘POST’, ODataPath + “/” + odataSetName, false);

createRecordReq.setRequestHeader(“Accept”, “application/json”);

createRecordReq.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);

createRecordReq.send(jsonEntity);

var newRecord = JSON.parse(createRecordReq.responseText).d;

return newRecord;

}

How do I call this method :-

  • Create a new .jscript file (i.e., “account.js”)
  • Copy & Paste above code
  • Add “account.js” as a webresource in CRM
  • Add “Json2.js” & “jquery1.4.1.min.js” helper script files as webresources
  • Get the helper files from CRM 2011 SDk under path “\sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts”
  • To create an “Account”
  • Pass “Account” object, OData Set name (i.e.,AccountSet)

var account = new Object();

account.Name = “Rajeev Pentyala”;

var createdAccount = createRecordSync(account, “AccountSet”);

if (createdAccount) {

alert(“New Account Created !!!; Id – “+createdAccount.AccountId);

}

🙂

Retrieve multiple records using OData & JQuery in CRM 2011

March 26, 2012 5 comments

Hi,

Below are the Jscript functions to retrieve multiple records using OData & JQuery.

function retrieveMultiple(odataSetName, select, filter, successCallback) {

var serverUrl = Xrm.Page.context.getServerUrl();

var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;

var odataUri = serverUrl + ODATA_ENDPOINT + “/” + odataSetName + “?”;

if (select) {

odataUri += “$select=” + select + “&”;

}

if (filter) {

odataUri += “$filter=” + filter;

}

//Asynchronous AJAX function to Retrieve CRM records using OData

$.ajax({

type: “GET”,

contentType: “application/json; charset=utf-8”,

datatype: “json”,

url: odataUri,

beforeSend: function (XMLHttpRequest) {

//Specifying this header ensures that the results will be returned as JSON.

XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);

},

success: function (data, textStatus, XmlHttpRequest) {

if (successCallback) {

if (data && data.d && data.d.results) {

successCallback(data.d.results, textStatus, XmlHttpRequest);

}

else if (data && data.d) {

successCallback(data.d, textStatus, XmlHttpRequest);

}

else {

successCallback(data, textStatus, XmlHttpRequest);

}

}

},

error: function (XmlHttpRequest, textStatus, errorThrown) {

if (XmlHttpRequest && XmlHttpRequest.responseText) {

alert(“Error while retrieval ; Error – ” + XmlHttpRequest.responseText);

}

}

});

}

function readRecordsOnSuccess(data, textStatus, XmlHttpRequest) {

// Loop through the retrieved records

for (var indx = 0; indx < data.length; indx++) {

alert(“Name – ” + data[indx].name);

}

}

  • Copy & Paste above methods to a new .jscript file
  • Replace double quotes(“) symbols with your keyboard double quotes
  • Add the new .jscript file as web resource to CRM application
  • Add “Jquery” & json” helper classes as web resources

How do I call this method :-

  • In my sample below, I will show you how to read “Contacts” for an “Account”

function retrieveContactsByAccountId() {

// Pass ‘Contact’ set name since we are reading Contacts

var oDataSetName = “ContactSet”;

// Column names of ‘Contact’ (Pass * to read all columns)

var columns = “FirstName,LastName”;

// Read Account Guid

var accountId = Xrm.Page.data.entity.getId()

// Prepare filter

var filter = “AccountId/Id eq guid'” + accountId + “‘”;

retrieveMultiple(oDataSetName, columns, filter, readRecordsOnSuccess);

}

Note :- Import “ODataQueryDesigner” solution to prepare the Filters easily.

Hope it helps 🙂

Reading option set using JScript in CRM 2011

March 8, 2012 7 comments

Hi,

Below is the Jscript functions to read “Option set” and get the option text by option value.

In this approach I have 3 methods and details are below

  • getOptionSet() – Returns optionset object
    • Parameters
      • Entity Name           (Entity logical name)
      • Attribute Name        (i.e., Option set field name)
      • retrieveAsIfPublished (True/False)
  • getTextByValue() – Returns option set text by passing value
    • Parameters
      • optionSet        (i.e., Option set object got from above method)
      • attributeValue   (Option set field value)
  • getSOAPWrapper – Helper method

function getOptionSet (entityLogicalName, attributeLogicalName, retrieveAsIfPublished) {

var serverUrl = Xrm.Page.context.getServerUrl();

var ODataPath = serverUrl + “/XRMServices/2011/Organization.svc/web”;

var MetadataId = “00000000-0000-0000-0000-000000000000”;

var request = “<Execute xmlns=\”http://schemas.microsoft.com/xrm/2011/Contracts/Services\” xmlns:i=\”http://www.w3.org/2001/XMLSchema-instance\“>”;

request += “<request i:type=\”a:RetrieveAttributeRequest\” xmlns:a=\”http://schemas.microsoft.com/xrm/2011/Contracts\“>”;

request += “<a:Parameters xmlns:b=\”http://schemas.datacontract.org/2004/07/System.Collections.Generic\“>”;

request += “<a:KeyValuePairOfstringanyType>”;

request += “<b:key>EntityLogicalName</b:key>”;

request += “<b:value i:type=\”c:string\” xmlns:c=\”http://www.w3.org/2001/XMLSchema\“>” + entityLogicalName + “</b:value>”;

request += “</a:KeyValuePairOfstringanyType>”;

request += “<a:KeyValuePairOfstringanyType>”;

request += “<b:key>MetadataId</b:key>”;

request += “<b:value i:type=\”ser:guid\”  xmlns:ser=\”http://schemas.microsoft.com/2003/10/Serialization/\“>” + MetadataId + “</b:value>”;

request += “</a:KeyValuePairOfstringanyType>”;

request += “<a:KeyValuePairOfstringanyType>”;

request += “<b:key>RetrieveAsIfPublished</b:key>”;

request += “<b:value i:type=\”c:boolean\” xmlns:c=\”http://www.w3.org/2001/XMLSchema\“>” + retrieveAsIfPublished + “</b:value>”;

request += “</a:KeyValuePairOfstringanyType>”;

request += “<a:KeyValuePairOfstringanyType>”;

request += “<b:key>LogicalName</b:key>”;

request += “<b:value i:type=\”c:string\”   xmlns:c=\”http://www.w3.org/2001/XMLSchema\“>” + attributeLogicalName + “</b:value>”;

request += “</a:KeyValuePairOfstringanyType>”;

request += “</a:Parameters>”;

request += “<a:RequestId i:nil=\”true\” /><a:RequestName>RetrieveAttribute</a:RequestName></request>”;

request += “</Execute>”;

request = _getSOAPWrapper(request);

var req = new XMLHttpRequest();

req.open(“POST”, ODataPath, false);

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“);

req.send(request);

if (req.responseXML != null) {

var attributeData = req.responseXML.selectSingleNode(“//b:value”);

if (attributeData != null) {

var attributeType = attributeData.selectSingleNode(“c:AttributeType”).text;

switch (attributeType) {

case “Picklist”:

return attributeData;

break;

default:

break;

}

}

}

}

function _getSOAPWrapper(request) {

var SOAP = “<soapenv:Envelope xmlns:soapenv=\”http://schemas.xmlsoap.org/soap/envelope/\“><soapenv:Body>”;

SOAP += request;

SOAP += “</soapenv:Body></soapenv:Envelope>”;

return SOAP;

}

function getTextByValue(optionSet, attributeValue) {

var options = optionSet.selectSingleNode(“c:OptionSet//c:Options”);

for (var i = 0; i < options.childNodes.length; i++) {

var value = options.childNodes[i].selectSingleNode(“c:Value”).text;

if (value == attributeValue) {

var text = options.childNodes[i].selectSingleNode(“c:Label”).selectSingleNode(“a:UserLocalizedLabel”).selectSingleNode(“a:Label”).text;

return text;

}

}

}

How do I call this method

  • Copy the above functions and create a Jscript webresource in CRM
  • In below example I am reading “Address Type” option set of entity “Contact”

// Get option set object by passing params

// Entity name, Optionset field name, true/false

var optionSet = getOptionSet(“contact”, “address1_addresstypecode”, true);

if (optionSet) {

// Read option text of value ‘2’

var optionValue = 2;

var optionText = getTextByValue(optionSet, optionValue);

alert(“Text of option value – ” + optionValue + ” is -” + optionText);

// Read option text of value ‘10001’

optionValue = 10001;

optionText = getTextByValue(optionSet, optionValue);

alert(“Text of option value – ” + optionValue + ” is -” + optionText);

}

else {

alert(“Invalid Option set”);

}

Note :-  *** If you copy the code please replace double quotes(“) symbols with your keyboard double quotes ***

Hope it helps 🙂