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..

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.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 Client Diagnostics Tool for On Premise

Previously only available for CRM Online, the CRM Diagnostics tool is now released with CRM 2011 Update Rollup 4 for On Premise installations.

It runs a couple of tests, measuring latency to the datacenter/server, bandwidth, and performs a few Javascript performance tests to measure the CPU/browser performance of the machine.

You can access the tool using the following URL after you install UR4 or later.
http://<serverUrl>/tools/diagnostics/diag.aspx

The latency and bandwidth test the download speed across the wire from the CRM web site to the client browser. A low latency and high bandwidth is ideal. If your values show a high latency and low bandwidth then your CRM experience may be slow depending on the extremity of the range. For some performance reading you can take a look here.

Optimizing and Maintaining Client Performance for Microsoft Dynamics CRM 2011 and CRM Online
http://www.microsoft.com/download/en/details.aspx?id=23261

Optimizing Performance for CRM Online 2011
http://community.dynamics.com/product/crm/crmnontechnical/b/crmonlineteam/archive/2011/04/08/optimizing-performance-for-crm-online-2011.aspx – even though this is for Online there are some important points

Microsoft Dynamics CRM 2011 Performance and Scalability with Intel
http://www.microsoft.com/download/en/details.aspx?id=16673

Improving Microsoft Dynamics CRM Performance and Securing Data with Microsoft SQL Server 2008
http://www.microsoft.com/download/en/details.aspx?id=8438

Optimizing and Maintaining the Performance of a Microsoft Dynamics CRM 2011 Server Infrastructure
http://www.microsoft.com/download/en/details.aspx?id=27139

The above documents should give you a solid understanding of performance related improvements you can apply to your Dynamics CRM deployment.

The JavaScript test items are testing your CPU/browser performance of your machine. Ideally you want low values here and upgrading your IE browser to the latest version should give you the best results.

Happy tuning.

Cheers,

Rhett Clinton

CRM 2011 Tools by Tanguy Touzard CRM MVP

Nobody has produced more CRM 2011 tools than fellow CRM MVP Tanguy Touzard. There are a number of CRM 4 tools Tanguy has created as well which you can find on his blog and codeplex.

You can find his blog here http://mscrmtools.blogspot.com

The list of CRM 2011 tools that can be found on codeplex so far include

SiteMap Editor for Microsoft Dynamics CRM 2011

Ribbon Browser for Microsoft Dynamics CRM 2011

JavaScript Web Resource Manager for Microsoft Dynamics CRM 2011

View Layout Replicator for Microsoft Dynamics CRM 2011

Searchable Property Updater for Microsoft Dynamics CRM 2011

Let’s thank Tanguy for his hard work and for sharing these great tools with the CRM community.

You can also find these tools along with more development resources for Dynamics CRM on the Microsoft Dynamics CRM TechNet Wiki here http://social.technet.microsoft.com/wiki/contents/articles/microsoft-dynamics-crm-2011-development-resources.aspx

Microsoft Dynamics CRM TechNet Wiki

Microsoft Dynamics TechNet Wiki

The purpose of this wiki is to provide a comprehensive guide for IT professionals to learn about then implement, configure, customize, maintain and support Microsoft Dynamics CRM.

Just like the CRM SDK, CRM Forums, books and CRM Blogs, this repository of CRM knowledge based articles and general Dynamics CRM information is a great place to learn and expand your CRM knowledge. The CRM MVP’s and various others have been working hard to build up a knowledge base to help the community find useful information with topics covering a wide array of Dynamics CRM and related technologies.

Check it out and learn something new…

Updated CRM 2011 SDK version 5.0.3 available

Today the MS CRM Team released an updated CRM 2011 SDK version 5.0.3 which can be downloaded here http://www.microsoft.com/downloads/en/details.aspx?FamilyID=420f0f05-c226-4194-b7e1-f23ceaa83b69

Microsoft Dynamics CRM 2011 SDK Download Contents

 The Microsoft Dynamics CRM 2011 SDK download package includes the following files and folders:

  • Bin Folder – Contains the assemblies needed for development using Microsoft Dynamics CRM 2011.
  • HandsOnLabs – Contains training materials for learning to use Microsoft Dynamics CRM 2011.
  • Resources Folder – Contains development resources such as a style guide, images, data import maps and other templates.
  • SampleCode Folder – Contains sample code to demonstrate how to develop using Microsoft Dynamics CRM 2011.
  • Schemas Folder – Contains the schemas used for validation using Microsoft Dynamics CRM 2011.
  • Solutions Folder – Contains sample solutions for use with Microsoft Dynamics CRM 2011.
  • Tools Folder - Contains the tools needed to register plug-ins and workflows, and to create strongly typed classes.
  • Walkthroughs Folder – Contains the completed solutions that correspond to walkthroughs presented in the SDK documentation.
  • LicenseTerms.docx - The Microsoft software license terms for this SDK.
  • CrmSdk2011.chm – The help file containing SDK documentation.
  • Microsoft_Dynamics_CRM_2011_SDK_Readme.htm – This readme file.

Dynamics CRM 2011 Developer Training Kit

Brief Description


This training kit is for .NET developers to learn the development features of Dynamics CRM and help them build applications using Microsoft Dynamics CRM 2011 and CRM Online.

The training kit includes various resources such as

  • Presentations – Presentation decks in PowerPoint (.pptx) format that you can use to learn the concepts.
  • Videos – Video recordings of the presentation along with demos delivered by expert trainers.
  • Hands-on Labs – Hands-on labs with detailed instructions and source code that will walk you through the various development features.

Download the training kit here: Dynamics CRM 2011 Developer Training Kit

Girish Raja originally posted about the kit release and you can see the blog post here

Default Customer Lookup to Contact in CRM 2011

There has been a slight change in the way you default the Customer Lookup field to Contact in CRM 2011 compared with CRM 4.

Use the following code to set the Customer Lookup to Contact instead of Account and set the default view.


document.getElementById("customerid").setAttribute("defaulttype", "2");
Xrm.Page.getControl("customerid").setDefaultView("a2d479c5-53e3-4c69-addd-802327e67a0d");

The first line sets the default entity type to Contact for the Customer Lookup dialog.

The second line sets the Customer Lookup dialog’s view to the ‘Contacts Lookup View’ using its guid value. If you do not use this line of code it will default to the ‘My Active Contacts View’ or whatever you have selected as the default Contact view.