Showing posts with label CRM User Security Roles. Show all posts
Showing posts with label CRM User Security Roles. Show all posts

Sunday, April 22, 2012

Dynamics CRM 2011 : Restrict/Hide Settings Sitemap Area by Security Role

In Dynamics CRM 2011 we can restrict the entity privileges to none for hiding the Sitemap SubArea navigation item but there is no security role privilege available for hiding some of Settings area SubArea items i.e. System Jobs, Administration, Business Administration etc...

To hide the Settings area from the sitemap via security role, we have to restrict all SubArea navigation items privileges to none and required to add the privilege node to the SubArea items which do not have any security privileges mentioned in Security Role setup.

[Solution Steps]

The following steps below describe the solution for hiding the Sitemap area.

1.    Export SiteMap solution, go to Settings Customization Solutions and click on new button. Enter solution detials and add the SiteMap item and export the unmagaed solution

2.    Create new custom entity with name Priv : Site Map Settings (logical Name: wod_privsitemapsettings)

3.    Unzip solution file and open customizations.xml file into visual studio, notepad or Xml editor

4.    Search for Setttings area node <Area Id="Settings" ResourceId="Area_Settings"

5.    Add the following privlege node into all of SubArea items which does not have privlege node

<Privilege Entity="wod_privsitemapsettings" Privilege="Read "/>

6.     Save file, zip all files and import the solution into the system

7.    Publish all customizations and in User Secruity role change the entity Priv : Site Map Settings privleges to none
[Sample SiteMap Settings Area XML Code]


<Area Id="Settings" ResourceId="Area_Settings" ShowGroups="true" Icon="/_imgs/settings_24x24.gif"
 DescriptionResourceId="Settings_Area_Description">
        <Group Id="Business_Setting" ResourceId="Menu_Label_Business"
        DescriptionResourceId="Menu_Label_Business">

                <SubArea Id="nav_businessmanagement" ResourceId="Homepage_BusinessManagement"
                 DescriptionResourceId="BizManagement_SubArea_Description"
                 Icon="/_imgs/ico_18_busmanagement.gif" Url="/tools/business/business.aspx"
                 AvailableOffline="false" >
                        <!—Custom Privilege Node.... -->
                        <Privilege Entity="wod_privsitemapsettings" Privilege="Read "/>
                </SubArea>

                <SubArea Id="nav_template" ResourceId="Homepage_Template"                                      
                 DescriptionResourceId="Template_SubArea_Description" Icon="/_imgs/ico_18_templates.gif"
                 Url="/tools/templates/templates.aspx" AvailableOffline="false" >
                        <!—Custom Privilege Node.... -->
                        <Privilege Entity="wod_privsitemapsettings" Privilege="Read "/>
                </SubArea>

                <SubArea Id="nav_productcatalog" ResourceId="Homepage_ProductCatalog"
                 DescriptionResourceId="ProductCatalog_SubArea_Description"
                 Icon="/_imgs/ico_18_productcatalog.gif" Url="/tools/productcatalog/productcatalog.aspx"                       
                 AvailableOffline="false">
                        <!—System Defined Privilege Node.... -->
                        <Privilege Entity="product" Privilege="Read" />
                </SubArea>
        </Group>
        <!--Other Groups.... -->
</Area>

Tuesday, April 17, 2012

Dynamics CRM 2011 : Restrict Entity Activate, Deactivate Security Privileges

In Dynamics CRM 2011 we can restrict the user security privileges for entities, Misc. Privileges, fields etc. via Security Roles or Field level security but for certain actions i.e. Record Activate, Deactivate, Lead Qualify, Quote Activate etc.. We cannot restrict these privileges via security role or Field level security.

As there is no standard feature available to control these privileges so one of the possible way is to control these privileges by developing and registering a plugin on SetStateDynamicEntity Message for an entity in Pre-Operation stage, the plugin code should check if record is activated and specified user or user with specified Security Role or having entity privilege is activating quote then allow execution else abort execution and throw exception. The following plugin code below is used for restricting record deactivation.

[C# Code : Restrict Entity Deactivate Privleges Example]


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

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

            IOrganizationServiceFactory wod_serviceFactory = null;

            IOrganizationService wod_CrmService = null;

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

                // Obtain service objec
                wod_CrmService = wod_serviceFactory.CreateOrganizationService(context.UserId);

                if (context.InputParameters.Contains("EntityMoniker")
                 && context.InputParameters["EntityMoniker"] is EntityReference)
                {
                    switch (context.MessageName)
                    {
                        case "SetStateDynamicEntity":

                            // Check if the entity status has been updated
                            if (context.InputParameters.Contains("Status"))
                            {
                                // Check if user is deactivating the record
                              if (((OptionSetValue)context.InputParameters["Status"]).Value == 2)
                                {
                                    // Check if current user has not been assigned a security
                                    role "Sales Manager" then throw exception
                                    if (CheckUserHasSecurityRole(wod_CrmService
                                      , context.InitiatingUserId, "Sales Manager") == false)
                                        throw new InvalidPluginExecutionException(
                                        "Not enough privelegs to deactivate record.");
                                }
                            }

                            break;
                    }
                }
            }

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

        //Helper method for checking if user is assigned particular security role
        private bool CheckUserHasSecurityRole(IOrganizationService prmCrmService
              , Guid prmUserId, string prmSecurityRoleName)
        {
            bool wod_UserHasSecurityRole = false;

            EntityCollection wod_UserRoles = null;

            //Create Query Expression to fetch Role Entity
            QueryExpression wod_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 = { prmUserId }
                                        }
                                    }
                                }
                            }
                        }
            };

            wod_Query.EntityName = "role";

            wod_Query.ColumnSet = new ColumnSet(true);

            // Obtain results from the query expression.
            wod_UserRoles = prmCrmService.RetrieveMultiple(wod_Query);

            // Searching for a specified Security Role into the list
            Entity wod_UserSecurityRole = wod_UserRoles.Entities.ToList().ToList<Entity>()
                  .Find(delegate(Entity wod_RoleEntity)
            {
                return (string)wod_RoleEntity.Attributes["name"] == prmSecurityRoleName;
            });

            if (wod_UserSecurityRole != null)
            {
                wod_UserHasSecurityRole = true;
            }

            return wod_UserHasSecurityRole;
        }
    }
}


Files Download Link:

Plugin C# Project file: Record Deactivation Security Privileges.zip 
https://skydrive.live.com/?cid=06f61fc8aa6032c9&id=6F61FC8AA6032C9%21151#