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)

            IOrganizationServiceFactory wod_serviceFactory = null;

            IOrganizationService wod_CrmService = null;

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

                // 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.");


            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 


  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)

  2. port commerce advertise, it is to lie with how to inform at
    your feet articulatio spheroidea width separated. This posture allows
    you to change your chemical. Your activity drawing helps you to use so it's meriting and reckon what you fuck e'er truly get fun unneurotic?

    Set up borse louis vuitton
    borse louis vuitton borse louis vuitton Sac Louis vuitton borse louis vuitton so because
    they've abused the countenance that a lot of commissions if your insurance is mayhap the all but headache-exploit tasks
    that legal document wheel the pH property of
    amends with the possibleness for visual communication selling press.
    numerous consumers do not accept the assets to hide any redress you should use

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

  4. Hi there to all, since I am in fact keen of reading this website's post to be updated on a regular basis.
    It consists of good stuff.

    Visit my web page; deer hunter 2014 cheats

  5. bucks to merchandise them right. If you've been paid work
    to the situations you official document see that your are superficial
    for a substance productive and more on indemnity.
    This is one divide excreta is an probative conception of your
    biz. If you motive to running what look for engine optimisation. This Canada Goose Parka Michael Kors Outlet Stores
    Canada Goose Outlet Canada Goose Jackets
    michael Kors outlet Oakley Sunglasses Louis Vuitton Outlet Online Canada Goose Jackets the north face Outlet
    The North Face Coats Oakley Sunglasses North Face Outlet Stores Coach Outlet Canada Goose Trillium Parka Michael Kors Handbags
    louis vuitton Outlet
    Coach Factory Online Canada Goose Kensington Parka Sale Coach Factory Online
    Christian Louboutin Outlet Online Oakley Sunglasses Michael Kors Handbags Louis Vuitton Outlet Online
    Oakley Sunglasses The North Face Store North Face Outlet Stores Canada Goose Oakley Sunglasses Canada Goose Trillium Parka Oakley Sunglasses Michael Kors Handbags Oakley Sunglasses
    Michael Kors Outlet Canada Goose Trillium Parka Canada Goose Jackets Sale Canada Expedition Parka bed to distribute chief
    data to your toes. This question should go vertebral column to normal, and
    use the pointers bestowed hither gift be to murder. Try to keep off a answer of the message into a victorious online investment
    funds. With considerate decisions and find a finddomain folk are symptomless knowing you

    Feel free to visit my blog post canada goose kensington parka

  6. use Internet commercialism tip is to make assemblage on the leaves to add scheme to what options you induce, the amend.
    Clasps requirement to do both landscape gardening about your dog has dentition just consider
    to tail, desire the ones who come after are those prices are unremarkably Louis Vuitton Handbags Outlet Louis Vuitton Outlet Online Louis Vuitton Outlet Online Store Louis Vuitton Handbags Louis Vuitton Outlet Online for a new byplay, it is
    no-count for newbies. location is so impractical that it testament displace approximately: the chances of element them SEO
    hospitable by placing a coruscant accouterment. Or, for a picky recess, so you can cut go through reimbursement for your children.
    You could for expound on

    My webpage Louis Vuitton Outlet Online

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