Skip to main content

Notifications

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

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

Announcing the Engage with the Community forum!

This forum is your space to connect, share, and grow!

🌸 Community Spring Festival 2025 Challenge Winners! 🌸

Congratulations to all our community participants!

Adis Hodzic – Community Spotlight

We are honored to recognize Adis Hodzic as our May 2025 Community…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Daivat Vartak (v-9davar) Profile Picture

Daivat Vartak (v-9d... 225 Super User 2025 Season 1

#2
Eugen Podkorytov Profile Picture

Eugen Podkorytov 106

#2
Muhammad Shahzad Shafique Profile Picture

Muhammad Shahzad Sh... 106 Most Valuable Professional

Overall leaderboard

Product updates

Dynamics 365 release plans