Plugin to only allow users with certain role to deactivate records

As variant to a recent post I did, here’s another plugin to manage the Activation/Deactivation of records. In this post, I’ll describe a plugin that will control these actions in Contact Entity by only allowing users with an specific role.

Plugin step details:

  1. Message: Update
  2. Filtering Attributes: statecode
  3. Run in user’s context: Calling User
  4. Event Pipeline Stage: Pre-Operation
  5. Event Mode: Sync

Code

    ///

    /// PreUpdateContact Plugin.
    /// Fires when the following attributes are updated:
    ///            * statecode
    /// 

    public class PreUpdateContact : Plugin
    {
        ///

        /// Initializes a new instance of the  class.
        /// 

        public PreUpdateContact(): base(typeof(PreUpdateContact))
        {
            base.RegisteredEvents.Add(new Tuple(20, "Update", "contact", new Action(ExecutePreUpdateContact)));
        }

        ///

        /// Fire on Pre Update Contact. Only called when statecode changes.
        /// 

        ///  Local context
        protected void ExecutePreUpdateContact(LocalPluginContext localContext)
        {
            // Validate Local context
            if (localContext == null){ throw new ArgumentNullException("Local context not found."); }

            // Validate Plugin Execution context
            IPluginExecutionContext context = localContext.PluginExecutionContext;
            if (context == null) throw new InvalidPluginExecutionException("Context not found.");

            //Create service from local context.
            IOrganizationService service = localContext.Or<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;">&#65279;</span>ganizationService;

            // Get: Target
            Entity Target = (Entity)context.InputParameters["Target"];

            /*
             * If State code is Inactive and User does not have the defined role, throw error.
             * NOTE: Change "Role" and "User_ID" variables to your desired GUIDs
             */
            int StateCode = ((OptionSetValue)Target.Attributes["statecode"]).Value;
            int Inactive_State = 1;

            string Role_Name = "YOUR_ROLE_NAME";

            Guid User_ID = context.UserId;

            if (StateCode == Inactive_State &amp;&amp;
                !User_Has_Role(Role_Name, User_ID, service))
            {
                throw new InvalidPluginExecutionException("\n<b>Only users with an specific role are allowed to deactivate Contacts. If you need to deactivate this record, please contact your CRM Admin.</b> \n\n");
            }
        }

        ///

        /// Check if user has an specific role.
        /// Return True if so. False in other case
        /// 

        ///  Role ID
        ///  User ID
        ///  IOrganizationService
        public bool User_Has_Role(string Role_Name, Guid User_ID, IOrganizationService _service)
        {
            // Defining Entity
            var query = new QueryExpression("role");

            // Adding validation to search based on Role Name
            query.Criteria.AddCondition("name", ConditionOperator.Equal, Role_Name);

            // Link to SystemUserRoles
            var link = query.AddLink("systemuserroles", "roleid", "roleid");

            // Adding validation to check for the specified user
            link.LinkCriteria.AddCondition("systemuserid", ConditionOperator.Equal, User_ID);

            // Return result
            return _service.RetrieveMultiple(query).Entities.Count &gt; 0;
        }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s