Thursday, June 11, 2009

MSCRM: testing a User's Role (CRM 3.0 only)

This is quite an old tip now, on several blogs and forums, but we'd thought we'd repeat it here to keep it with the updated code for MSCRM 4.0 (see next post). The code below needs to be put in either the global.js file (by default located here C:\Program Files\Microsoft CRM\CRMWeb\_common\scripts\) of in the top of each Form event where you need to call the function. It's then just a case of calling the following in the Form Event:

if(currentUserHasRole(‘System Administrator’)){
//do this stuff
}else{
//do other stuff
}


Note that putting the code in the global.js is a risky strategy as if a patch or update is installed, then the changes may be lost. It does save copy/pasting into each and every Event; the choice is yours!

Java script code to test whether a User has a particular Role:

function getUserId()
{
try
{
var command = new RemoteCommand("SystemUser", "WhoAmI", "/MSCRMServices/");
var oResult = command.Execute();

if (oResult.Success)
{
return oResult.ReturnValue.UserId;
}
}
catch(e)
{
alert("Error while retrieving userid.");
}
return null;
}

function getUserRoles(userId)
{
try
{
var command = new RemoteCommand("UserManager", "GetUserRoles");
command.SetParameter("userIds", "<guid>" + userId + "</guid>");

var oResult = command.Execute();

if (oResult.Success)
{
return oResult.ReturnValue;
}
}
catch(e)
{
alert("Error while retrieving roles.");
}
return null;
}

function userHasRole(userId, roleName)
{
result = getUserRoles(userId);
if (result != null)
{
var oXml = new ActiveXObject("Microsoft.XMLDOM");
oXml.resolveExternals = false;
oXml.async = false;
oXml.loadXML(result);

roleNode = oXml.selectSingleNode("/roles/role[name='" + roleName + "']");
if (roleNode != null)
{
if (roleNode.selectSingleNode("roleid[@checked='true']") != null)
return true;
}
}
return false;
}

function currentUserHasRole(roleName)
{
userId = getUserId();
return userHasRole(userId, roleName);
}

No comments: