Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM forum
Unanswered

Associate / Disassociate Plugin Event

Posted on by 120

Hi there folks,

Today I come to you because I create a plugin to add an User to a specific Security Profile when the users is added / removed to an specific Security Role. This plugin is registered for the Associate and Disassociate events (messages). 

The plugin work very well when directly in the system you give / remove the Security Role to / from the User.

The issue start when through an interface the Security Role is given through and interface with a central tool we have in the company where I works from. This interface is base on a Web Adapter. The Security Role is correctly assigned to the user but the plugin is not fired.

Any of you have a clue about the reason why the plugin is not fired up?

Here is the code of my plugin

using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

namespace TTMSCRM.Plugins.TurnoverPerformance
{
    public partial class PostOperationTurnoverPerformanceSecurityProfile : IPlugin
    {
        private IPluginExecutionContext context;
        private IOrganizationService service;
        private ITracingService tracingService;
        private string relationshipName = string.Empty;
        private EntityReference targetEntity = null;
        private EntityReferenceCollection relatedEntities = null;
        private EntityReference relatedEntity = null;
        private Guid SecurityProfileId = new Guid("7C1D1DAE-9F08-EB11-814C-005056BE0CB9");

        public void Execute(IServiceProvider serviceProvider)
        {
            #region setup

            context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            service = ((IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory))).CreateOrganizationService(new Guid?(context.UserId));
            tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            #endregion setup

            #region ValidationToExecuteThePlugin

            tracingService.Trace("Depth: {0}", context.Depth);

            //if (context.Depth > 1)
            //    return;

            tracingService.Trace("Validating the Message");
            try
            {
                switch (context.MessageName.ToLower())
                {
                    case "associate":
                    case "disassociate":
                        // Get the "Relationship" Key from context
                        if (context.InputParameters.Contains("Relationship"))
                        {
                            // Get the Relationship name for which this plugin fired
                            relationshipName = ((Relationship)context.InputParameters["Relationship"]).SchemaName;
                        }

                        // Check the "Relationship Name" with your intended one
                        if (relationshipName != "systemuserroles_association")
                        {
                            return;
                        }

                        UserToSecurityProfile();
                        break;

                    default:
                        return;
                }
            }
            catch (Exception Ex)
            {
                throw new Exception("\n\n-----------------------------------------------\n"  
                                    "\nErro Message:\n"   Ex.Message.ToString()  
                                    "\nException:\n"   Ex.ToString()  
                                    "\n\n-----------------------------------------------\n\n");
            }

            #endregion ValidationToExecuteThePlugin
        }

        public void UserToSecurityProfile()
        {
            // Get Entity 1 reference from "Target" Key from context
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
            {
                targetEntity = (EntityReference)context.InputParameters["Target"];
            }

            // Get Entity 2 reference from " RelatedEntities" Key from context
            if (context.InputParameters.Contains("RelatedEntities") && context.InputParameters["RelatedEntities"] is EntityReferenceCollection)
            {
                relatedEntities = context.InputParameters["RelatedEntities"] as EntityReferenceCollection;
                relatedEntity = relatedEntities[0];
                var SecurityRole = service.Retrieve(relatedEntity.LogicalName, relatedEntity.Id, new ColumnSet(true));

                if (!SecurityRole.Attributes.Contains("name"))
                    return;
                if (!SecurityRole.Attributes["name"].Equals("TT Financial"))
                    return;
            }

            if (targetEntity == null && relatedEntity == null)
                return;

            Relationship relationship = new Relationship("systemuserprofiles_association");
            EntityReferenceCollection collection = new EntityReferenceCollection();
            collection.Add(new EntityReference("fieldsecurityprofile", SecurityProfileId));

            switch (context.MessageName.ToLower())
            {
                case "associate":
                    service.Associate(targetEntity.LogicalName, targetEntity.Id, relationship, collection);
                    break;

                case "disassociate":
                    service.Disassociate(targetEntity.LogicalName, targetEntity.Id, relationship, collection);
                    break;

                default:
                    return;
            }
        }
    }
}

This is how I register the plugin

pastedimage1613131936651v1.png

Helpful resources

Quick Links

Replay now available! Dynamics 365 Community Call (CRM Edition)

Catch up on the first D365 Community Call held on 7/10

Community Spotlight of the Month

Kudos to Saurav Dhyani!

Congratulations to the June Top 10 community leaders!

These stars go above and beyond . . .

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 288,459 Super User

#2
Martin Dráb Profile Picture

Martin Dráb 225,783 Super User

#3
nmaenpaa Profile Picture

nmaenpaa 101,148

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans