web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

No record found.

News and Announcements icon
Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Unanswered

Associate / Disassociate Plugin Event

(0) ShareShare
ReportReport
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

I have the same question (0)

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Introducing the 2026 Season 1 community Super Users

Congratulations to our 2026 Super Stars!

Meet the Microsoft Dynamics 365 Contact Center Champions

We are thrilled to have these Champions in our Community!

Congratulations to the March Top 10 Community Leaders

These are the community rock stars!

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
11manish Profile Picture

11manish 176

#2
ManoVerse Profile Picture

ManoVerse 158 Super User 2026 Season 1

#3
Jimmy Passeti Profile Picture

Jimmy Passeti 57 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans