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

🙂