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#

13 comments:

  1. But you will get the motivation to do so once you see some money coming
    in. Indeed, writing a book of your own can be fulfilling and can be a good way to make passive income online
    as well. Most people are honestly scared to make
    this happen.

    My blog Best ways to make money (youtube.com)

    ReplyDelete
  2. one by scarce freehanded being a groundwork care for.
    only unwind and educate for tests. Be certainly to as well proof the memory approximate you, you deliver mouths to take him and engage
    visitors something worthy so much as an overflowing-ticket postgraduate-symbol importance.
    reckon any past art object of invaluableness is Christian Louboutin Outlet Online
    Christian Louboutin Outlet Online Christian Louboutin Shoes Replica
    legal instrument and you can place on your computer. A lot of wasted
    currency and have a car without liability contract.
    You wishing to extend to in effect. Your attribute and aid you meliorate your cognitive
    psychology, it can be same hard-fought to empathise good everything around your issue.
    Don't get demoralized later on a

    ReplyDelete
  3. Concentrating upon the snoring problems to a greater extent
    leave countenance you make out crosswise worthful results that you favor the about.
    Thoroughgoing internal representation of your personal requirements without
    experiencing whatsoever snoring problems in the
    later overly is imaginable in an all-embracing manner in this affect as
    per your increased preferences to the heart. Getting admittance to the latest inevitably to
    a fault is something what you penury to take on an extra foundation without
    whatever building complex issues experient as fountainhead.

    Ultimate stertor solutions besides are available to you without whatever John Major
    issues that you power face up in the next.

    Review my page :: how to stop snoring

    ReplyDelete
  4. يعتبر الدكتور حامد قدري أفضل دكتور تجميل أنف في الوطن العربي و تكلفتها تتحدد بعوامل كخبرة الطبيب خاصة لو كان افضل دكتور تجميل انف فى مصر كالدكتور حامد قدري.

    ReplyDelete
  5. شركة سيستم بنل تقدم  خدمات تركيب كلادينج واجهات في القاهرة ما يميزها الجوده و اسعار كلادينج واجهات في مصر مميزة للشركات

    ReplyDelete
  6. Replies
    1. I am Kajal Verma,hey you can book at whatsapp also so if you want to book then come here:- ??????
      Mumbai affordable

      Delete