Checking Dynamics CRM user team membership with organization data service
With the all the recent news about Dynamics 365, this post probably seems a tad outdated, but today I had a colleague ask me for a way to check whether a user is a member of a team in a Dynamics CRM 2015 organization using JavaScript. Without further commentary, here goes:
//get the userid
var userid = Xrm.Page.context.getUserId();
//check if the user is on the team using a synchronous odata call
function isUserOnTeam(userid, teamid){
//assume user is not on the team
var returnvalue = false;
var oDataSetName = "TeamMembershipSet";
var filter = "SystemUserId eq guid' " + userid + " ' and TeamId eq guid' " + teamid + "'";
var columns = "*";
var requestResults = retrieveMultipleSync(oDataSetName, columns, filter);
if (requestResults != null) {
//more than zero results -> user is on the team
if(requestResults.results.length>0){
returnvalue = true;
}
}
return returnvalue;
}
//helper function for making sync odata calls - taken from https://rajeevpentyala.com/2012/05/27/retrieve-multiple-records-synchronously-using-odata-jquery-in-crm-2011/
function retrieveMultipleSync(odataSetName, select, filter) {
// Get Server URL
var serverUrl = "";
if (Xrm.Page.context.getClientUrl) {
//Post UR 12
serverUrl = Xrm.Page.context.getClientUrl();
}
else {
//Pre UR 12
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;
}
}
//helper function for making xmlhttp requests
function getRequestObject() {
if (window.XMLHttpRequest) {
return new window.XMLHttpRequest;
}
else {
try {
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch (ex) {
return null;
}
}
}