Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

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

While associate subgrid records in case getting error Cannot insert Duplicate Key in CRM 9.0 Onpremise

(0) ShareShare
ReportReport
Posted on by 2,665

Hi All,

I am using below code to associate subgrid in case which is user subgrid taking value from Asset or Division & in both Asset & Division entity user subgrid is there.From there getting User records & associating in case.But while updating asset & division chnge on case its not disassociating & getting error cannot insert duplicate key.

What Could be the issue ?

using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
 
namespace MIC_CRM.GroupCompliance.Plugins.Case.Conflict_of_Interest
{
    public class UpdateGEComplianceCounsel : IPlugin
    {
        IOrganizationService organizationService;
        Guid divisionId = Guid.Empty, assetId = Guid.Empty;
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                IPluginExecutionContext executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                organizationService = serviceFactory.CreateOrganizationService(executionContext.UserId);
                bool IsGridData = false;
                if (executionContext.MessageName.ToUpper() == "UPDATE")
                {
                    if (executionContext.InputParameters.Contains("Target") && (executionContext.InputParameters["Target"] is Entity))
                    {
                        Entity incident = (Entity)executionContext.InputParameters["Target"];
                        if (incident == null || incident.LogicalName != "incident")
                        {
                            tracingService.Trace("Target is not as expected");
                            return;
                        }
                        ColumnSet attributes = new ColumnSet(new string[] { "mdc_relateddivision", "mdc_relatedasset" });
                       Entity entityCase = organizationService.Retrieve(incident.LogicalName, incident.Id, attributes);
                        tracingService.Trace("Retrieved Incident");
                        //EntityReference division = entityCase.Attributes.Contains("mdc_relateddivision") ? entityCase?.GetAttributeValue<EntityReference>("mdc_relateddivision") : null;
                        var division = entityCase.Contains("mdc_relateddivision") ? ((EntityReference)entityCase["mdc_relateddivision"]).Id : Guid.Empty;
                        tracingService.Trace("Division got....");
                        //EntityReference asset = entityCase.Attributes.Contains("mdc_relatedasset") ? entityCase?.GetAttributeValue<EntityReference>("mdc_relatedasset") : null;
                        var asset = entityCase.Contains("mdc_relatedasset") ? ((EntityReference)entityCase["mdc_relatedasset"]).Id : Guid.Empty;
                        tracingService.Trace("Asset value got....");
 
                        if (asset != Guid.Empty)
                        {
                            //assetId = (entityCase?.GetAttributeValue<EntityReference>("mdc_relatedasset")).Id;
                            DisassociateComplianceCounselGrid(incident, tracingService, ref IsGridData);
                            if (IsGridData)  //Check Compliance Counsel grid has no records then Associate Users
                            {
                                tracingService.Trace($"Grid has no records");
                                QueryExpression query = new QueryExpression();
                                query.EntityName = "systemuser";
                                query.ColumnSet = new ColumnSet(true);
                                Relationship relationship = new Relationship();
                                query.Criteria = new FilterExpression();
                                relationship.SchemaName = "mdc_mdc_asset_systemuser";
                                tracingService.Trace($"Relationship exists");
                                RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();
                                relatedEntity.Add(relationship, query);
                                RetrieveRequest request = new RetrieveRequest();
                                request.RelatedEntitiesQuery = relatedEntity;
                                request.ColumnSet = new ColumnSet("mdc_assetid");
                                if (asset != null)
                                    request.Target = new EntityReference { Id = asset, LogicalName = "mdc_asset" };
                                RetrieveResponse response = (RetrieveResponse)organizationService.Execute(request);
                                tracingService.Trace($"Got Response");
                                List<Entity> relatedEntities = new List<Entity>();
                                if (((((RelatedEntityCollection)(response.Entity.RelatedEntities)))).Contains(new Relationship("mdc_mdc_asset_systemuser")) &&
                                ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_asset_systemuser")].Entities.Count > 0)
                                {
                                    foreach (var item in ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_asset_systemuser")].Entities)
                                    {
                                        relatedEntities.Add(item);
                                        AssociateRequest request1 = new AssociateRequest();
                                        if (incident.Id != null)
                                            request1.Target = new EntityReference(incident.LogicalName, incident.Id);
                                        request1.RelatedEntities = new EntityReferenceCollection();
                                        if (item.Id != null)
                                            request1.RelatedEntities.Add(new EntityReference("systemuser", item.Id));
                                        request1.Relationship = new Relationship("mdc_incident_systemusernew");
                                        organizationService.Execute(request1);
                                        tracingService.Trace($"Associated Users for Asset successfully");
                                    }
                                }
                            }
                        }
                        else if (division != Guid.Empty)
                        {
                            //divisionId = (entityCase?.GetAttributeValue<EntityReference>("mdc_relateddivision")).Id;
                            DisassociateComplianceCounselGrid(incident, tracingService, ref IsGridData);
                            if (IsGridData)  //Check Compliance Counsel grid has no records then Associate Users
                            {
                                tracingService.Trace($"Grid has no records");
                                QueryExpression query = new QueryExpression();
                                query.EntityName = "systemuser";
                                query.ColumnSet = new ColumnSet(true);
                                Relationship relationship = new Relationship();
                                query.Criteria = new FilterExpression();
                                relationship.SchemaName = "mdc_mdc_division_systemuser";
                                tracingService.Trace($"Relationship exists");
                                RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();
 
                                relatedEntity.Add(relationship, query);
                                RetrieveRequest request = new RetrieveRequest();
                                request.RelatedEntitiesQuery = relatedEntity;
                                request.ColumnSet = new ColumnSet("mdc_divisionid");
                                if (division != null)
                                    request.Target = new EntityReference { Id = division, LogicalName = "mdc_division" };
                                RetrieveResponse response = (RetrieveResponse)organizationService.Execute(request);
                                tracingService.Trace($"Got Response");
                                List<Entity> relatedEntities = new List<Entity>();
                                if (((((RelatedEntityCollection)(response.Entity.RelatedEntities)))).Contains(new Relationship("mdc_mdc_division_systemuser")) &&
                                ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_division_systemuser")].Entities.Count > 0)
                                {
                                    foreach (var item in ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_division_systemuser")].Entities)
                                    {
                                        relatedEntities.Add(item);
                                        AssociateRequest request1 = new AssociateRequest();
                                        if (incident.Id != null)
                                            request1.Target = new EntityReference(incident.LogicalName, incident.Id);
                                        request1.RelatedEntities = new EntityReferenceCollection();
                                        if (item.Id != null)
                                            request1.RelatedEntities.Add(new EntityReference("systemuser", item.Id));
                                        request1.Relationship = new Relationship("mdc_incident_systemusernew");
                                        organizationService.Execute(request1);
                                        tracingService.Trace($"Associated Users successfully");
                                    }
                                }
                            }
 
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException("An error occurred in the Update GE Compliance counsel Plug-in: " + ex.Message, ex);
            }
        }
        private void DisassociateComplianceCounselGrid(Entity incident, ITracingService tracingService, ref bool IsGridData)
        {
            try
            {
                //Retrieving Compliance Counsel grid records
                ConditionExpression condition = new ConditionExpression();
                condition.AttributeName = "mdc_compliancecounselid";
                condition.Operator = ConditionOperator.Equal;
                if (incident.Id != null)
                   condition.Values.Add(incident.Id);
                tracingService.Trace("incident exists");
                //Create a column set.
                ColumnSet columns = new ColumnSet(true);
                QueryExpression query1 = new QueryExpression();
                query1.ColumnSet = columns;
                query1.EntityName = "systemuser";
                query1.Criteria.AddCondition(condition);
                List<Entity> relatedUsers = new List<Entity>();
                EntityCollection resColl = organizationService.RetrieveMultiple(query1);
                tracingService.Trace($"Subgrid records found");
                if (resColl?.Entities != null)
                {
                    IsGridData = true;
                    tracingService.Trace($"subgrid has data");
                    foreach (var r in resColl.Entities)
                    {
                        relatedUsers.Add(r);
                        DisassociateRequest disassociateReq = new DisassociateRequest();
                        if (incident.Id != null)
                            disassociateReq.Target = new EntityReference("incident", incident.Id);
                        disassociateReq.RelatedEntities = new EntityReferenceCollection();
                        if (r.Id != null)
                            disassociateReq.RelatedEntities.Add(new EntityReference("systemuser", r.Id));
                        disassociateReq.Relationship = new Relationship("mdc_incident_systemusernew");
                        organizationService.Execute(disassociateReq);
                        tracingService.Trace($"Disaasociated Users successfully");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException("An error occurred in the DisassociateComplianceCounselGrid method: " + ex.Message, ex);
            }
        }
    }
}
Thanks,
Jharana
  • Jharana Baliyar Singh Profile Picture
    2,665 on at
    RE: While associate subgrid records in case getting error Cannot insert Duplicate Key in CRM 9.0 Onpremise

    Association on create also working fine by mistakely i was calling same method twice.

    Thanks for the help !!

  • Jharana Baliyar Singh Profile Picture
    2,665 on at
    RE: While associate subgrid records in case getting error Cannot insert Duplicate Key in CRM 9.0 Onpremise

    The above one I just updated bool IsGridData = false; to true it worked on update its working fine.The same code am using for associate only on create of case but there getting error cannot insert duplicate key.

    I am not able to understand what could be the cause becz only n:n schema name need to update in Associate method.

    or is there anything am missing

  • Jharana Baliyar Singh Profile Picture
    2,665 on at
    RE: While associate subgrid records in case getting error Cannot insert Duplicate Key in CRM 9.0 Onpremise

    Hi Charan,

    Disassociation is working fine now but association not happening based on field change , below latest code am using now:

    using System;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Client;

    using System.Collections.Generic;

    using System.Text;

    using System.Linq;

    using Microsoft.Xrm.Sdk.Query;

    using Microsoft.Xrm.Sdk.Messages;

    namespace MIC_CRM.GroupCompliance.Plugins.Case.Conflict_of_Interest

    {

       public class UpdateGEComplianceCounsel : IPlugin

       {

           OrganizationServiceContext organizationServiceContext;

           IOrganizationService organizationService;

           Guid divisionId = Guid.Empty, assetId = Guid.Empty;

           public void Execute(IServiceProvider serviceProvider)

           {

               try

               {

                   IPluginExecutionContext executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                   ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

                   IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

                   organizationService = serviceFactory.CreateOrganizationService(executionContext.UserId);

                   organizationServiceContext = new OrganizationServiceContext(organizationService);

                   bool IsGridData = false;

                   if (executionContext.MessageName.ToUpper() == "UPDATE")

                   {

                       if (executionContext.InputParameters.Contains("Target") && (executionContext.InputParameters["Target"] is Entity))

                       {

                           Entity incident = (Entity)executionContext.InputParameters["Target"];

                          if (incident == null || incident.LogicalName != "incident")

                           {

                               tracingService.Trace("Target is not as expected");

                               return;

                           }

                           organizationServiceContext.ClearChanges();

                           var incidentdtls = (from tra in organizationServiceContext.CreateQuery("incident")

                                               where (Guid)tra["incidentid"] == incident.Id

                                               select new

                                               {

                                                   Isactive = tra.Contains("statecode") ? ((OptionSetValue)tra["statecode"]).Value : 0,

                                                   division = tra.Contains("mdc_relateddivision") ? ((EntityReference)tra["mdc_relateddivision"]).Id : Guid.Empty,

                                                   asset = tra.Contains("mdc_relatedasset") ? ((EntityReference)tra["mdc_relatedasset"]).Id : Guid.Empty

                                               }).FirstOrDefault();

                           //ColumnSet attributes = new ColumnSet(new string[] { "mdc_relateddivision", "mdc_relatedasset" });

                           //Entity entityCase = organizationService.Retrieve(incident.LogicalName, incident.Id, attributes);

                           //tracingService.Trace("Retrieved Incident");

                           //EntityReference division = entityCase.Attributes.Contains("mdc_relateddivision") ? entityCase?.GetAttributeValue<EntityReference>("mdc_relateddivision") : null;

                           //var division = entityCase.Contains("mdc_relateddivision") ? ((EntityReference)entityCase["mdc_relateddivision"]).Id : Guid.Empty;

                           var division = incidentdtls.division;

                           tracingService.Trace("Division got....");

                           //EntityReference asset = entityCase.Attributes.Contains("mdc_relatedasset") ? entityCase?.GetAttributeValue<EntityReference>("mdc_relatedasset") : null;

                           //var asset = entityCase.Contains("mdc_relatedasset") ? ((EntityReference)entityCase["mdc_relatedasset"]).Id : Guid.Empty;

                           var asset = incidentdtls.asset;

                           tracingService.Trace("Asset value got....");

                           //throw new InvalidPluginExecutionException("Asset : ")

                           if (asset != Guid.Empty)

                           {

                               if (incidentdtls.Isactive == 0)

                               {

                                   DisassociateNtoNRecords(organizationService, "incident", "systemuser", "mdc_incident_systemusernew", incident.Id, ref IsGridData);

                                   //assetId = (entityCase?.GetAttributeValue<EntityReference>("mdc_relatedasset")).Id;

                                   // DisassociateComplianceCounselGrid(incident, tracingService, ref IsGridData);

                                   if (IsGridData)  //Check Compliance Counsel grid has no records then Associate Users

                                   {

                                       tracingService.Trace($"Grid has no records");

                                       QueryExpression query = new QueryExpression();

                                       query.EntityName = "systemuser";

                                       query.ColumnSet = new ColumnSet(true);

                                       Relationship relationship = new Relationship();

                                       query.Criteria = new FilterExpression();

                                       relationship.SchemaName = "mdc_mdc_asset_systemuser";

                                       tracingService.Trace($"Relationship exists");

                                       RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();

                                       relatedEntity.Add(relationship, query);

                                       RetrieveRequest request = new RetrieveRequest();

                                       request.RelatedEntitiesQuery = relatedEntity;

                                       request.ColumnSet = new ColumnSet("mdc_assetid");

                                       request.Target = new EntityReference { Id = asset, LogicalName = "mdc_asset" };

                                       RetrieveResponse response = (RetrieveResponse)organizationService.Execute(request);

                                       tracingService.Trace($"Got Response");

                                       List<Entity> relatedEntities = new List<Entity>();

                                       if (((((RelatedEntityCollection)(response.Entity.RelatedEntities)))).Contains(new Relationship("mdc_mdc_asset_systemuser")) &&

                                       ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_asset_systemuser")].Entities.Count > 0)

                                       {

                                           foreach (var item in ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_asset_systemuser")].Entities)

                                           {

                                               relatedEntities.Add(item);

                                               AssociateRequest request1 = new AssociateRequest();

                                               if (incident.Id != Guid.Empty)

                                                   request1.Target = new EntityReference(incident.LogicalName, incident.Id);

                                              request1.RelatedEntities = new EntityReferenceCollection();

                                               if (item.Id != Guid.Empty)

                                                   request1.RelatedEntities.Add(new EntityReference("systemuser", item.Id));

                                               request1.Relationship = new Relationship("mdc_incident_systemusernew");

                                               organizationService.Execute(request1);

                                               tracingService.Trace($"Associated Users for Asset successfully");

                                           }

                                       }

                                   }

                               }

                           }

                           else if (division != Guid.Empty)

                           {

                               if (incidentdtls.Isactive == 0)

                               {

                                   //divisionId = (entityCase?.GetAttributeValue<EntityReference>("mdc_relateddivision")).Id;

                                   // DisassociateComplianceCounselGrid(incident, tracingService, ref IsGridData);

                                   DisassociateNtoNRecords(organizationService, "incident", "systemuser", "mdc_incident_systemusernew", incident.Id, ref IsGridData);

                                   if (IsGridData)  //Check Compliance Counsel grid has no records then Associate Users

                                   {

                                       tracingService.Trace($"Grid has no records");

                                       QueryExpression query = new QueryExpression();

                                       query.EntityName = "systemuser";

                                       query.ColumnSet = new ColumnSet(true);

                                       Relationship relationship = new Relationship();

                                       query.Criteria = new FilterExpression();

                                       relationship.SchemaName = "mdc_mdc_division_systemuser";

                                       tracingService.Trace($"Relationship exists");

                                       RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();

                                       relatedEntity.Add(relationship, query);

                                       RetrieveRequest request = new RetrieveRequest();

                                       request.RelatedEntitiesQuery = relatedEntity;

                                       request.ColumnSet = new ColumnSet("mdc_divisionid");

                                       request.Target = new EntityReference { Id = division, LogicalName = "mdc_division" };

                                       RetrieveResponse response = (RetrieveResponse)organizationService.Execute(request);

                                       tracingService.Trace($"Got Response");

                                       List<Entity> relatedEntities = new List<Entity>();

                                       if (((((RelatedEntityCollection)(response.Entity.RelatedEntities)))).Contains(new Relationship("mdc_mdc_division_systemuser")) &&

                                       ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_division_systemuser")].Entities.Count > 0)

                                       {

                                           foreach (var item in ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_division_systemuser")].Entities)

                                           {

                                               relatedEntities.Add(item);

                                               AssociateRequest request1 = new AssociateRequest();

                                               if (incident.Id != Guid.Empty)

                                                   request1.Target = new EntityReference(incident.LogicalName, incident.Id);

                                               request1.RelatedEntities = new EntityReferenceCollection();

                                               if (item.Id != Guid.Empty)

                                                   request1.RelatedEntities.Add(new EntityReference("systemuser", item.Id));

                                               request1.Relationship = new Relationship("mdc_incident_systemusernew");

                                               organizationService.Execute(request1);

                                               tracingService.Trace($"Associated Users successfully");

                                           }

                                       }

                                   }

                               }

                           }

                       }

                   }

               }

               catch (Exception ex)

               {

                   throw new InvalidPluginExecutionException("An error occurred in the Update GE Compliance counsel Plug-in: " + ex.Message, ex);

               }

           }

           private void DisassociateNtoNRecords(IOrganizationService service, string entity1Name, string entity2Name, string NtoNRelationshipName, Guid entity1Id, ref bool IsGridData)

           {

               try

               {

                   QueryExpression query = new QueryExpression(entity2Name)

                   {

                       LinkEntities = {

               new LinkEntity(entity2Name, NtoNRelationshipName, entity2Name + "id", entity2Name + "id", JoinOperator.Inner)

               {

                   Columns = new ColumnSet(true),

                   LinkCriteria = { Conditions = { new ConditionExpression(entity1Name + "id", ConditionOperator.Equal, entity1Id ) }},

               }

           }

                   };

                   EntityCollection entity2NameRecords = service.RetrieveMultiple(query);

                   if (entity2NameRecords.Entities.Count > 0)

                   {

                       IsGridData = true;

                       EntityReferenceCollection entity2ReferenceCollection = new EntityReferenceCollection(entity2NameRecords.Entities.Select(a => a.ToEntityReference()).ToList());

                       DisassociateRequest disAssociateReq = new DisassociateRequest()

                       {

                           Target = new EntityReference(entity1Name, entity1Id),

                           RelatedEntities = entity2ReferenceCollection,

                           Relationship = new Relationship(NtoNRelationshipName)

                       };

                       service.Execute(disAssociateReq);

                   }

               }

               catch (Exception ex)

               {

                   throw new InvalidPluginExecutionException("An error occurred in the DisassociateNtoNRecords method: " + ex.Message, ex);

               }

           }

       }

    }

    For association direct AssociateRequest am using & here am using n:n relationship schema too.what could be the cause

    any idea would be appreciated.

    Thanks,

    Jharana

  • Jharana Baliyar Singh Profile Picture
    2,665 on at
    RE: While associate subgrid records in case getting error Cannot insert Duplicate Key in CRM 9.0 Onpremise

    Thanks For your response will try above one & will let you know.

  • Verified answer
    Charan Raju C R Profile Picture
    7 Moderator on at
    RE: While associate subgrid records in case getting error Cannot insert Duplicate Key in CRM 9.0 Onpremise

    Try below function to disassociate System User from Case. Your calling method should be like this: DisassociateNtoNRecords(organizationService, "incident", "systemuser", "mdc_incident_systemusernew", incident.Id, ref IsGridData);

    private void DisassociateNtoNRecords(IOrganizationService service, string entity1Name, string entity2Name, string NtoNRelationshipName, Guid entity1Id, ref bool IsGridData)
    {
        QueryExpression query = new QueryExpression(entity2Name)
        {
            LinkEntities = {
                new LinkEntity(entity2Name, NtoNRelationshipName, entity2Name + "id", entity2Name + "id", JoinOperator.Inner)
                {
                    Columns = new ColumnSet(true),
                    LinkCriteria = { Conditions = { new ConditionExpression(entity1Name + "id", ConditionOperator.Equal, entity1Id ) }},
                }
            }
        };
        EntityCollection entity2NameRecords = service.RetrieveMultiple(query);


        if (entity2NameRecords.Entities.Count > 0)
        {
            IsGridData = true;
            EntityReferenceCollection entity2ReferenceCollection = new EntityReferenceCollection(entity2NameRecords.Entities.Select(a => a.ToEntityReference()).ToList());

            DisassociateRequest disAssociateReq = new DisassociateRequest()
            {
                Target = new EntityReference(entity1Name, entity1Id),
                RelatedEntities = entity2ReferenceCollection,
                Relationship = new Relationship(NtoNRelationshipName)
            };
            service.Execute(disAssociateReq);
        }
    }

  • Jharana Baliyar Singh Profile Picture
    2,665 on at
    RE: While associate subgrid records in case getting error Cannot insert Duplicate Key in CRM 9.0 Onpremise

    Anyone could help on this it would be helpful.

    Thanks

  • Jharana Baliyar Singh Profile Picture
    2,665 on at
    RE: While associate subgrid records in case getting error Cannot insert Duplicate Key in CRM 9.0 Onpremise

    Hi Charan,

    Thanks for your response.Yes earlier i was using 1: N between case&  User entity but now i have created new N:N relationship as it didn't worked for all the case so we need ti use here N:N & here user is modifying has admin access

    & in plugin reg tool am using message on update post operation

    & below modified code am using : & getting error now

    An error occurred in the Update GE Compliance counsel Plug-in: An error occurred in the DisassociateComplianceCounselGrid method: Incident With Id = 8c3d6504-0fa3-ea11-a81d-001dd8b70014 Does Not Exist

    Anything wrong in below code ?

    using System;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Client;

    using System.Collections.Generic;

    using System.Text;

    using System.Linq;

    using Microsoft.Xrm.Sdk.Query;

    using Microsoft.Xrm.Sdk.Messages;

    namespace MIC_CRM.GroupCompliance.Plugins.Case.Conflict_of_Interest

    {

       public class UpdateGEComplianceCounsel : IPlugin

       {

           OrganizationServiceContext organizationServiceContext;

           IOrganizationService organizationService;

           Guid divisionId = Guid.Empty, assetId = Guid.Empty;

           public void Execute(IServiceProvider serviceProvider)

           {

               try

               {

                   IPluginExecutionContext executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                   ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

                   IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

                   organizationService = serviceFactory.CreateOrganizationService(executionContext.UserId);

                   organizationServiceContext = new OrganizationServiceContext(organizationService);

                   bool IsGridData = true;

                   if (executionContext.MessageName.ToUpper() == "UPDATE")

                   {

                       if (executionContext.InputParameters.Contains("Target") && (executionContext.InputParameters["Target"] is Entity))

                       {

                           Entity incident = (Entity)executionContext.InputParameters["Target"];

                           if (incident == null || incident.LogicalName != "incident")

                           {

                               tracingService.Trace("Target is not as expected");

                               return;

                           }

                           organizationServiceContext.ClearChanges();

                           var incidentdtls = (from tra in organizationServiceContext.CreateQuery("incident")

                                               where (Guid)tra["incidentid"] == incident.Id

                                               select new

                                               {

                                                   division = tra.Contains("mdc_relateddivision") ? ((EntityReference)tra["mdc_relateddivision"]).Id : Guid.Empty,

                                                   asset = tra.Contains("mdc_relatedasset") ? ((EntityReference)tra["mdc_relatedasset"]).Id : Guid.Empty

                                               }).FirstOrDefault();

                           //ColumnSet attributes = new ColumnSet(new string[] { "mdc_relateddivision", "mdc_relatedasset" });

                           //Entity entityCase = organizationService.Retrieve(incident.LogicalName, incident.Id, attributes);

                           //tracingService.Trace("Retrieved Incident");

                           //EntityReference division = entityCase.Attributes.Contains("mdc_relateddivision") ? entityCase?.GetAttributeValue<EntityReference>("mdc_relateddivision") : null;

                           //var division = entityCase.Contains("mdc_relateddivision") ? ((EntityReference)entityCase["mdc_relateddivision"]).Id : Guid.Empty;

                           var division = incidentdtls.division;

                           tracingService.Trace("Division got....");

                           //EntityReference asset = entityCase.Attributes.Contains("mdc_relatedasset") ? entityCase?.GetAttributeValue<EntityReference>("mdc_relatedasset") : null;

                           //var asset = entityCase.Contains("mdc_relatedasset") ? ((EntityReference)entityCase["mdc_relatedasset"]).Id : Guid.Empty;

                           var asset = incidentdtls.asset;

                           tracingService.Trace("Asset value got....");

                           //throw new InvalidPluginExecutionException("Asset : ")

                           if (asset != Guid.Empty)

                           {

                               //assetId = (entityCase?.GetAttributeValue<EntityReference>("mdc_relatedasset")).Id;

                               DisassociateComplianceCounselGrid(incident, tracingService, ref IsGridData);

                               if (IsGridData)  //Check Compliance Counsel grid has no records then Associate Users

                               {

                                   tracingService.Trace($"Grid has no records");

                                   QueryExpression query = new QueryExpression();

                                   query.EntityName = "systemuser";

                                   query.ColumnSet = new ColumnSet(true);

                                   Relationship relationship = new Relationship();

                                   query.Criteria = new FilterExpression();

                                   relationship.SchemaName = "mdc_mdc_asset_systemuser";

                                   tracingService.Trace($"Relationship exists");

                                   RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();

                                   relatedEntity.Add(relationship, query);

                                   RetrieveRequest request = new RetrieveRequest();

                                   request.RelatedEntitiesQuery = relatedEntity;

                                   request.ColumnSet = new ColumnSet("mdc_assetid");

                                   request.Target = new EntityReference { Id = asset, LogicalName = "mdc_asset" };

                                   RetrieveResponse response = (RetrieveResponse)organizationService.Execute(request);

                                   tracingService.Trace($"Got Response");

                                   List<Entity> relatedEntities = new List<Entity>();

                                   if (((((RelatedEntityCollection)(response.Entity.RelatedEntities)))).Contains(new Relationship("mdc_mdc_asset_systemuser")) &&

                                   ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_asset_systemuser")].Entities.Count > 0)

                                   {

                                       foreach (var item in ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_asset_systemuser")].Entities)

                                       {

                                           relatedEntities.Add(item);

                                           AssociateRequest request1 = new AssociateRequest();

                                           if (incident.Id != Guid.Empty)

                                               request1.Target = new EntityReference(incident.LogicalName, incident.Id);

                                           request1.RelatedEntities = new EntityReferenceCollection();

                                           if (item.Id != Guid.Empty)

                                               request1.RelatedEntities.Add(new EntityReference("systemuser", item.Id));

                                           request1.Relationship = new Relationship("mdc_incident_systemusernew");

                                           organizationService.Execute(request1);

                                           tracingService.Trace($"Associated Users for Asset successfully");

                                       }

                                   }

                               }

                           }

                           else if (division != Guid.Empty)

                           {

                               //divisionId = (entityCase?.GetAttributeValue<EntityReference>("mdc_relateddivision")).Id;

                               DisassociateComplianceCounselGrid(incident, tracingService, ref IsGridData);

                               if (IsGridData)  //Check Compliance Counsel grid has no records then Associate Users

                               {

                                   tracingService.Trace($"Grid has no records");

                                   QueryExpression query = new QueryExpression();

                                   query.EntityName = "systemuser";

                                   query.ColumnSet = new ColumnSet(true);

                                   Relationship relationship = new Relationship();

                                   query.Criteria = new FilterExpression();

                                   relationship.SchemaName = "mdc_mdc_division_systemuser";

                                   tracingService.Trace($"Relationship exists");

                                   RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();

                                   relatedEntity.Add(relationship, query);

                                   RetrieveRequest request = new RetrieveRequest();

                                   request.RelatedEntitiesQuery = relatedEntity;

                                   request.ColumnSet = new ColumnSet("mdc_divisionid");

                                   request.Target = new EntityReference { Id = division, LogicalName = "mdc_division" };

                                   RetrieveResponse response = (RetrieveResponse)organizationService.Execute(request);

                                   tracingService.Trace($"Got Response");

                                   List<Entity> relatedEntities = new List<Entity>();

                                   if (((((RelatedEntityCollection)(response.Entity.RelatedEntities)))).Contains(new Relationship("mdc_mdc_division_systemuser")) &&

                                   ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_division_systemuser")].Entities.Count > 0)

                                   {

                                       foreach (var item in ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_division_systemuser")].Entities)

                                       {

                                           relatedEntities.Add(item);

                                           AssociateRequest request1 = new AssociateRequest();

                                           if (incident.Id != Guid.Empty)

                                               request1.Target = new EntityReference(incident.LogicalName, incident.Id);

                                           request1.RelatedEntities = new EntityReferenceCollection();

                                           if (item.Id != Guid.Empty)

                                               request1.RelatedEntities.Add(new EntityReference("systemuser", item.Id));

                                           request1.Relationship = new Relationship("mdc_incident_systemusernew");

                                           organizationService.Execute(request1);

                                           tracingService.Trace($"Associated Users successfully");

                                       }

                                   }

                               }

                           }

                       }

                   }

               }

               catch (Exception ex)

               {

                   throw new InvalidPluginExecutionException("An error occurred in the Update GE Compliance counsel Plug-in: " + ex.Message, ex);

               }

           }

           private void DisassociateComplianceCounselGrid(Entity incident, ITracingService tracingService, ref bool IsGridData)

           {

               try

               {

                   Guid emailSendID = Guid.Empty;

                   if (incident != null)

                   {

                       QueryExpression query = new QueryExpression("systemuser"); //Name of the entity to be passed whose records need to be retrieved

                       var nIsToNRelationshipName = "mdc_incident_systemusernew"; //schema name of N:N relationship

                       query.ColumnSet = new ColumnSet(true);

                       var link = query.AddLink(nIsToNRelationshipName, "systemuserid", "systemuserid");

                       //Method Signature: AddLink("N:N schema name to be passed", "Primary key ID schema name of entity record to be retrieved", "schema name of attribute in the N:N relationship")

                      // emailSendID = incident.Id;//sample ID of Email Send record for which we are retrieving related records

                       link.LinkCriteria = new FilterExpression()

                       {

                           Conditions =

                        {

                         new ConditionExpression("incidentid", ConditionOperator.Equal, incident.Id)

                        // Filter condition to get related marketing lists of an Email Send record

                    }

                       };

                       EntityCollection collRecords = organizationService.RetrieveMultiple(query);

                       if (collRecords != null && collRecords.Entities != null && collRecords.Entities.Count > 0)

                       {

                           EntityReferenceCollection collection = new EntityReferenceCollection();

                           foreach (var entity in collRecords.Entities)

                           {

                               var reference = new EntityReference("systemuser", entity.Id);

                               collection.Add(reference); //Create a collection of entity references

                           }

                           Relationship relationship = new Relationship("mdc_incident_systemusernew"); //schema name of N:N relationship

                           organizationService.Disassociate("systemuser", incident.Id, relationship, collection); //Pass the entity reference collections to be disassociated from the specific Email Send record

                       }

                   }

                   ////Retrieving Compliance Counsel grid records

                   //ConditionExpression condition = new ConditionExpression();

                   ////condition.AttributeName = "mdc_incident_systemusernew";

                   //condition.AttributeName = "mdc_compliancecounselid";

                   //condition.Operator = ConditionOperator.Equal;

                   //if (incident.Id != Guid.Empty)

                   //    condition.Values.Add(incident.Id);

                   //tracingService.Trace("incident exists");

                   ////Create a column set.

                   //ColumnSet columns = new ColumnSet(true);

                   //QueryExpression query1 = new QueryExpression();

                   //query1.ColumnSet = columns;

                   //query1.EntityName = "systemuser";

                   //query1.Criteria.AddCondition(condition);

                   //List<Entity> relatedUsers = new List<Entity>();

                   //EntityCollection resColl = organizationService.RetrieveMultiple(query1);

                   //tracingService.Trace($"Subgrid records found");

                   //if (resColl?.Entities.Count > 0)

                   //{

                   //    IsGridData = true;

                   //    tracingService.Trace($"subgrid has data");

                   //    foreach (var r in resColl.Entities)

                   //    {

                   //        relatedUsers.Add(r);

                   //        DisassociateRequest disassociateReq = new DisassociateRequest();

                   //        if (incident.Id != Guid.Empty)

                   //            disassociateReq.Target = new EntityReference("incident", incident.Id);

                   //        disassociateReq.RelatedEntities = new EntityReferenceCollection();

                   //        if (r.Id != Guid.Empty)

                   //            disassociateReq.RelatedEntities.Add(new EntityReference("systemuser", r.Id));

                   //        disassociateReq.Relationship = new Relationship("mdc_incident_systemusernew");

                   //        organizationService.Execute(disassociateReq);

                   //        tracingService.Trace($"Disaasociated Users successfully");

                   //    }

                   //}

               }

               catch (Exception ex)

               {

                   throw new InvalidPluginExecutionException("An error occurred in the DisassociateComplianceCounselGrid method: " + ex.Message, ex);

               }

           }

       }

    }

    Thanks,

    Jharana

  • Charan Raju C R Profile Picture
    7 Moderator on at
    RE: While associate subgrid records in case getting error Cannot insert Duplicate Key in CRM 9.0 Onpremise

    Hi Jharana,

    I can understand that you are facing error in disassociating System User records from Case. Please provide below details to understand more about the problem.

    1. What type of relationship (1:N or N:N) is between Case and System User?

    2. Is mdc_compliancecounselid a lookup to Case on System User and it's relationship name is mdc_incident_systemusernew?

    3. Does the user who is modifying a Case has read access to all the users associated with the case?

        You can try below to retrieve related user records without any permission issue:

         organizationService = serviceFactory.CreateOrganizationService(null);

    4. Add below tracing statement in DisassociateComplianceCounselGrid() function before if (resColl.Entities != null) to make sure the retrieved users count is not 0:

      tracingService.Trace("Users Count: " + resColl.Entities.Count);

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

🌸 Community Spring Festival 2025 Challenge 🌸

WIN Power Platform Community Conference 2025 tickets!

Jonas ”Jones” Melgaard – Community Spotlight

We are honored to recognize Jonas "Jones" Melgaard as our April 2025…

Kudos to the March Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 294,261 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 233,011 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,158 Moderator

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans