Saturday, July 30, 2011

Dynamics CRM 2011 : C# & JScript Code for Retrieving User Assigned Security Roles


You can use the code below to retrieve the user assigned security roles in C# plugin and JScript.
[Plugin: C# Code]


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;

namespace wod.Crm.UserSecurityRoles
{
    public class wod_Plugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            IOrganizationServiceFactory jj_serviceFactory = null;

            IOrganizationService jj_CrmService = null;

            Guid jj_UserGuid = Guid.Empty;

            EntityCollection jj_UserRoles = null;

            string jj_SecurityRole = string.Empty;

            Try
            {
                // Obtain the service factory to get the service object
                jj_serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

                // Obtain service object Imporsonated as plugin calling user
                jj_CrmService = jj_serviceFactory.CreateOrganizationService(context.InitiatingUserId);

                // Setting UserId to plugin initiating User Id
                jj_UserGuid = context.InitiatingUserId;

                //Security Role to Search
                jj_SecurityRole = "Customer Service Representative";

                #region Retrieve records from an intersect table via QueryExpression

                //Create Query Expression to fetch Role Entity
                QueryExpression jj_Query = new QueryExpression()
                {
                    //Setting the link entity condition and filter condition criteria/
                    LinkEntities =
                        {                           
                            new LinkEntity
                            {
                                LinkFromEntityName = "role",
                                LinkFromAttributeName = "roleid",
                                LinkToEntityName = "systemuserroles",
                                LinkToAttributeName = "roleid",
                                LinkCriteria = new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    Conditions =
                                    {
                                        new ConditionExpression
                                        {
                                            AttributeName = "systemuserid",
                                            Operator = ConditionOperator.Equal,
                                            Values = { jj_UserGuid }
                                        }
                                    }
                                }
                            }
                        }
                };

                jj_Query.ColumnSet = new ColumnSet(true);

                // Obtain results from the query expression.
                jj_UserRoles = jj_CrmService.RetrieveMultiple(jj_Query);

                // Searching for a specified Security Role into the list
                Entity jj_UserSecurityRole = jj_UserRoles.Entities.ToList().ToList<Entity>().Find(delegate(Entity jj_RoleEntity)
                {
                    return (string)jj_RoleEntity.Attributes["name"] == jj_SecurityRole;
                });

                if (jj_UserSecurityRole == null)
                {
                    throw new InvalidPluginExecutionException("Security role not assigned to User.");
                }

                #endregion

            }

            catch (System.Web.Services.Protocols.SoapException ex)
            {
                throw new InvalidPluginExecutionException(ex.Detail.InnerText);
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }

    }
}



 [JScript Code]


// Retrieving current login user security roles by using CRM client API method Xrm.Page.context.getUserRoles();
var jj_UserSecurityRoles = Xrm.Page.context.getUserRoles();

// Security role GUID (You can get it by opening Security Role record copy web address and go to the website
// http://meyerweb.com/eric/tools/dencoder , paste the URL and click on Decode button twice then copy Id value

var jj_CustomerServicesRoleId = “{E324246D-B8AF-E011-AA34-C95682B33448}”;
var jj_UserHaveSecurityRole = false;

// Checking if Security Role Id found in User Security Roles
for (var x = 0; x < UserSecurityRoles.length; x++) {

    if (UserSecurityRoles[x] == jj_CustomerServicesRoleId) {
       jj_UserHaveSecurityRole = ture;   
    }
}

if (jj_UserHaveSecurityRole == false) {
   throw new exception (“User has not been assigned Customer Service security role.”)
}