CRM 2011 Validate User Security Roles using JavaScript/REST

This example I’m sharing today is demonstrating a few techniques which promote JavaScript and REST, along with using namespaces and creating a library of functions/properties. This example declares a library Security.UserInRole and defines a number of properties and functions. The general idea is to allow the data access via REST to be asynchronous which then offers a valid and invalid function callback option to be defined to handle the outcome. You can specify an array of security roles to check against the current user and then with the callback functions you can perform the actions that you require.

Ideally I want to call a function that is easy to use and it will look like this.
Security.UserInRole.checkUserInRole(
["System Administrator", "System Customizer", "Custom Role Name"],
function(){alert("valid"); // The user is in one of the specifed roles.
},
function(){alert("invalid"); // The user is not in one of the specifed roles.
}
}

To define the library namespace and object we use
//If the Security namespace object is not defined, create it.
if (typeof (Security) == "undefined")
{ Security = {}; }
// Create Namespace container for functions in this library;
if (typeof (Security.UserInRole) == "undefined") {
Security.UserInRole = {
__namespace: true
};
}

 

The library functions and properties declared include the following
Security.UserInRole = {
isInRole: null,
roleIdValues: [],
validFunction: null,
invalidFunction: null,
checkRoles: [],
checkUserInRole: function (roles, validFunc, invalidFunc) {},
getAllowedSecurityRoleIds: function () {},
validateSecurityRoles: function () {},
querySecurityRoles: function (queryString) {},
__namespace: true
};

 

The entire library is implemented so that you call a function, it performs the processing asynchronously and then gives you the outcome to handle the response. Whether you want to show/hide form elements or disable fields etc, you can handle this in the callback function parameters validFunc and invalidFunc defined in the checkUserInRole function. The entire library content can be placed in a CRM webresource and added to a form. The full library is as shown below.

//If the Security namespace object is not defined, create it.
if (typeof (Security) == "undefined")
{ Security = {}; }
// Create Namespace container for functions in this library;
if (typeof (Security.UserInRole) == "undefined") {
Security.UserInRole = {
isInRole: null,
roleIdValues: [],
validFunction: null,
invalidFunction: null,
checkRoles: [],
checkUserInRole: function (roles, validFunc, invalidFunc) {
validFunction = validFunc;
invalidFunction = invalidFunc;
checkRoles = roles;
Security.UserInRole.getAllowedSecurityRoleIds();
},
getAllowedSecurityRoleIds: function () {
var filter = "";
for (var i = 0; i < checkRoles.length; i++) {
if(filter == "") {
filter = "Name eq '" + checkRoles[i] + "'";
}
else {
filter += " or Name eq '" + checkRoles[i] + "'";
}
}
Security.UserInRole.querySecurityRoles("?$select=RoleId,Name&$filter=" + filter);
},
validateSecurityRoles: function () {
switch (Security.UserInRole.isInRole) {
//If the user has already been discovered in role then call validFunc
case true:
validFunction.apply(this, []);
break;
default:
var userRoles = Xrm.Page.context.getUserRoles();
for (var i = 0; i < userRoles.length; i++) {
var userRole = userRoles[i];
for (var n = 0; n < Security.UserInRole.roleIdValues.length; n++) {
var role = Security.UserInRole.roleIdValues[n];
if (userRole.toLowerCase() == role.toLowerCase()) {
Security.UserInRole.isInRole = true;
// Call function when role match found
validFunction.apply(this, []);
return true;
}
}
}
// Call function when no match found
invalidFunction.apply(this, []);
break;
}
},
querySecurityRoles: function (queryString) {
var req = new XMLHttpRequest();
var url = "";
// Try getClientUrl first (available post Rollup 12)
if (Xrm.Page.context.getClientUrl) {
url = Xrm.Page.context.getClientUrl();
}
else {
url = Xrm.Page.context.getServerUrl();
}
req.open("GET", url + "/XRMServices/2011/OrganizationData.svc/RoleSet" + queryString, true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req.onreadystatechange = null; //Addresses memory leak issue with IE.
if (this.status == 200) {
var returned = window.JSON.parse(this.responseText).d;
for (var i = 0; i < returned.results.length; i++) {
Security.UserInRole.roleIdValues.push(returned.results[i].RoleId);
}
if (returned.__next != null) {
//In case more than 50 results are returned.
// This will occur if an organization has more than 16 business units
var queryOptions = returned.__next.substring((url + "/XRMServices/2011/OrganizationData.svc/RoleSet").length);
Security.UserInRole.querySecurityRoles(queryOptions);
}
else {
//Now that the roles have been retrieved, try again.
Security.UserInRole.validateSecurityRoles();
}
}
else {
var errorText;
if (this.status == 12029)
{ errorText = "The attempt to connect to the server failed."; }
if (this.status == 12007)
{ errorText = "The server name could not be resolved."; }
try {
errorText = window.JSON.parse(this.responseText).error.message.value;
}
catch (e)
{ errorText = this.responseText }
}
}
};
req.send();
},
__namespace: true
};
}

 

To use the library in the onload event of an entity form simply add the Security.UserInRole library webresource to the form and create a another JavaScript web resource to hold the onload function. The onload function may look like this. You define the roles to check as an array and pass this to the checkUserInRole function along with the valid and invalid callback functions. You don’t have to define the functions as anonymous functions like my example below but it can sometimes feel cleaner.

function onload()
{
Security.UserInRole.checkUserInRole(
["System Administrator", "System Customizer", "Custom Role Name"],
function(){alert("valid"); // The user is in one of the specifed roles.
},
function(){alert("invalid"); // The user is not in one of the specifed roles.
}
);
}

 

I would like to mention Jim Daly from the MS CRM Team for his examples of namespace and library structure along with his REST query code as this example I have created is derived from his outstanding work.

Happy Coding..

CRM 2011 SDK version 5.0.13 available

The MS CRM Team have released an updated CRM 2011 SDK version 5.0.13 which can be downloaded here http://www.microsoft.com/en-us/download/details.aspx?id=24004 or viewed on MSDN here http://msdn.microsoft.com/en-us/library/gg309408.aspx Check out the release notes here http://msdn.microsoft.com/en-us/library/jj863620.aspx

Quick Overview

  • Custom workflow activities can now be registered in the sandbox and are supported by Microsoft Dynamics CRM Online.
  • The Developer Toolkit for Microsoft Dynamics CRM 2011 and Microsoft Dynamics CRM Online now supports Microsoft Visual Studio 2012.
  • Added information about the new getClientUrl method. This method returns the base URL that was used to access the application. This is now the recommended method to use to access the organization URL. The getServerUrl method is deprecated.
  • Updated the metadata browser to version 2.0
  • Added a new topic for the new metadata query capabilities included in the Microsoft.Xrm.Sdk.Metadata.Query namespace.
  • Updated the topic to include information related to support for browsers other than Internet Explorer.
  • Added information about the new Like/Unlike feature. Updated information about default number of records that you can follow, and the maximum allowed number of characters in the post and the post comment. Also, updated configuration information about obtaining full functionality for activity feeds.
  • Updated exported ribbon definitions for Microsoft Dynamics CRM 2011
  • Added support for the Microsoft online services environment to connect to Microsoft Office 365.
  • Added a new topic to address issues related to solution development when Microsoft Dynamics CRM Online includes features that cannot be enabled in an on-premises deployment of Microsoft Dynamics CRM 2011.
  • Added a note to the Export an Unmanaged Solution section to indicate that, after Microsoft Dynamics CRM 2011 Update Rollup 12 and Microsoft Dynamics CRM December 2012 Service Update, un-customized form definitions will no longer be exported with unmanaged solutions.
  • Added new and updated information about using Windows Azure with Microsoft Dynamics CRM 2011 and Microsoft Dynamics CRM Online.
  • Added a new sample to show a way to deal with the situation where portions of the Xrm.Page object load into the updated forms asynchronously so they may not be available to scripts in HTML web resources at load time.
  • Updated these samples to build with newer versions of the Windows Azure SDK, version 1.7 or 1.8.
  • A bunch of sdk samples have been added and others updated.

Prepare for Dynamics CRM Rollup 12

Are you ready for the multi browser support of your customisations with Dynamics CRM Rollup 12, do you even care? It sounds great doesn’t it, IE, Chrome, Safari, Firefox, take your pick but will your CRM script customisations be supported. I guarantee this is the number one question facing CRM implementers/developers/testers right now and hopefully most have had a chance to test against the latest build of Rollup 12.

If you are a single browser environment and it remains as IE then you may be feeling comfortable but I recommend you follow-up with some testing and review time before applying Rollup 12.

There are some key areas that need looking at and you can find a list of impacted areas here

Resolve Breaking Script Issues When Upgrading Microsoft Dynamics CRM

 

To aid in the validation there is a tool available from Microsoft called the Microsoft Dynamics CRM 2011 Custom Code Validation Tool  which helps to identify potential issues with custom JavaScript in JavaScript libraries and HTML web resources.

To see an overview of problem areas you can see the release blog regarding the validation tool which highlights and lists the various potential issues that have been identified.

Microsoft Dynamics CRM 2011 Custom Code Validation Tool Released

 

The biggest threat to some may be the support of CRM 4 client side script or the lack there of as this becomes obsolete and unsupportable as CRM moves forward.

In many cases business requirements come first and in a perfect world we would never need to venture outside of the CRM 2011 client API so the main thought here should be before implementing unsupported customisations ask yourself if there is an alternative option to avoid future pain.

Don’t forget to check out the latest SDK when its available and read through the documentation covering this as it’s fairly complete and highly detailed for our needs.

CRM 2011 SDK version 5.0.12 available

The MS CRM Team have released an updated CRM 2011 SDK version 5.0.12 which can be downloaded here http://www.microsoft.com/en-us/download/details.aspx?id=24004 or viewed on MSDN here http://msdn.microsoft.com/en-us/library/gg309408.aspx Check out the release notes here http://msdn.microsoft.com/en-us/library/hh547453.aspx#bkmk_ReleaseHistory

In Summary the update contains

  • Updated assemblies for Microsoft Dynamics CRM 2011 Update Rollup 10. http://www.microsoft.com/en-gb/download/details.aspx?id=30711
  • A new Form Scripting Quick Reference that provides simple explanations and examples of the Xrm.Page object methods on a single page. http://msdn.microsoft.com/en-us/library/jj602964
  • A new topic called Choose your Development Style for Managed Code that describes the choices of tools and classes you can use when you write managed code and provides information to help you decide what is best for your needs.
  • A new topic called Create Accessible Web Resources that provides an introduction to creating web resources that offer equivalent functionality for all users so that people with disabilities will be able to use your web resources. http://technet.microsoft.com/en-us/library/jj602917.aspx
  • Improved authentication helper code and a new sample that demonstrates how to connect to the web services without using helper code.
  • Code changes to work in browsers to be supported in a later release, and information to guide you in making those changes.
  • Delivered the Solution Packaging Tool!
  • And much more… read the Release History for complete details. http://msdn.microsoft.com/en-us/library/hh547453.aspx#bkmk_ReleaseHistory

CRM 2011 SDK version 5.0.9 available

The MS CRM Team have released an updated CRM 2011 SDK version 5.0.9 which can be downloaded here http://www.microsoft.com/download/en/details.aspx?id=24004 or viewed on MSDN here http://msdn.microsoft.com/en-us/library/gg309408.aspx Check out the release notes here http://msdn.microsoft.com/en-us/library/hh547453.aspx#bkmk_ReleaseHistory

In Summary the update contains

  • Updated assemblies for Microsoft Dynamics CRM 2011 Update Rollup 6 and the Microsoft Portal developer toolkit and developer extensions.
  • Information about creating localized dialog processes.
  • New samples that authenticate the user with the web services without using the helper code
  • New topic to help developers find information about using JavaScript with various features that support it.

CRM 2011 SDK version 5.0.8 available

The MS CRM Team have released an updated CRM 2011 SDK version 5.0.8 which can be downloaded here http://www.microsoft.com/download/en/details.aspx?id=24004 or viewed on MSDN here http://msdn.microsoft.com/en-us/library/gg309408.aspx

Check out the release notes here http://msdn.microsoft.com/en-us/library/hh547453.aspx#bkmk_ReleaseHistory

Updated CRM 2011 Download Links

Here is an updated list of available CRM 2011 RTM downloads. It is good practice to have these files on a portable drive but it’s also recommended to have an updated list of download links.

Component URL
Server http://www.microsoft.com/download/en/details.aspx?id=27822
Outlook Client http://www.microsoft.com/download/en/details.aspx?id=27821
Language Pack http://www.microsoft.com/download/en/details.aspx?id=27819
Email Router http://www.microsoft.com/download/en/details.aspx?id=27818
Report Extension http://www.microsoft.com/download/en/details.aspx?id=27823
SharePoint List http://www.microsoft.com/download/en/details.aspx?id=5283
Software Development Kit http://www.microsoft.com/download/en/details.aspx?id=24004
Implementation Guide along with additiional Planning Tools http://www.microsoft.com/download/en/details.aspx?id=3621

CRM 2011 SDK version 5.0.7 available

The MS CRM Team have released an updated CRM 2011 SDK version 5.0.7 which can be downloaded here http://www.microsoft.com/download/en/details.aspx?id=24004 or viewed on MSDN here http://msdn.microsoft.com/en-us/library/gg309408.aspx

There are a number of things in this release that relate to the Microsoft Dynamics CRM UR5 and the Microsoft Dynamics CRM Online November Service Release

There is loads to read and discover.

 

CRM 2011 SDK version 5.0.6 available

The MS CRM Team have released an updated CRM 2011 SDK version 5.0.6 which can be downloaded here http://www.microsoft.com/download/en/details.aspx?id=24004 or viewed on MSDN here http://msdn.microsoft.com/en-us/library/gg309408.aspx

Some of the additions include:

  • Added Plugin Registration tool support for Windows Azure AppFabric Access Control Services (ACS) 2.0.
  • Updated the AppFabric SDK links and added information on how to use Windows Azure AppFabric ACS 2.0.
  • Added documentation for the Plug-in Profiler tool.
  • Added guidance recommending the use of PNG web resources for icons.
  • Added comment to clarify about the supported use of jQuery.
  • Added guidance for improving performance using the setVisible method.