protected void PostCreateExecution(IServiceProvider serviceProvider)
        {
            // Use a 'using' statement to dispose of the service context properly
            // To use a specific early bound entity replace the 'Entity' below with the appropriate class type
            using (var localContext = new LocalPluginContext <Entity>(serviceProvider))
            {
                var organisationService = localContext.OrganizationService;
                var newEntity           = new ProxyClasses.Rarity_SourceAssociation((Entity)localContext.PluginExecutionContext.InputParameters["Target"]);

                var targetEntity = DeduplicateRarityAssociation(localContext, newEntity);

                if (targetEntity == newEntity)
                {
                    AddImplicitAntigens(organisationService, newEntity);
                }
            }
        }
        private ProxyClasses.Rarity_SourceAssociation DeduplicateRarityAssociation(LocalPluginContext <Entity> localContext, ProxyClasses.Rarity_SourceAssociation subjectRarityAssociation)
        {
            // get all the pre-existing associations between this source and rarity

            var sourceId = subjectRarityAssociation.Source.Id;
            var rarityId = subjectRarityAssociation.Rarity.Id;

            var allMatchedAssocs = GetMatchedRarityAssocs(localContext.OrganizationService, sourceId, rarityId);

            // if there only is on matching rarity, then no need to continue with the deduplication
            if (allMatchedAssocs.Count == 1)
            { //just return the subject association
                return(subjectRarityAssociation);
            }
            else
            {
                //Work out which is the older matching association
                var oldestMatchingRarityAssociation = (
                    from matchedRarityAssoc in allMatchedAssocs
                    orderby matchedRarityAssoc.CreatedOn ascending
                    select matchedRarityAssoc).FirstOrDefault();

                //Test whether the oldest record is still active
                var isOldestActive = oldestMatchingRarityAssociation.Status == Rarity_SourceAssociation.eStatus.Active;

                //detect any other stray matching associations that are still active
                //shouldn't happen - but helps recover from an error state
                var otherActiveMatchingRarityAssocsNotOldest = (
                    from matchedRarityAssoc in allMatchedAssocs
                    where matchedRarityAssoc.Id != oldestMatchingRarityAssociation.Id
                    where matchedRarityAssoc.Status == Rarity_SourceAssociation.eStatus.Active
                    select matchedRarityAssoc);

                //If the oldest is not active,
                if (!isOldestActive)
                {
                    //Then reactivate the oldest record
                    Helper.SetState(
                        localContext.OrganizationService,
                        oldestMatchingRarityAssociation.ToEntityReference(),
                        new OptionSetValue((int)ProxyClasses.Rarity_SourceAssociation.eStatus.Active),
                        new OptionSetValue((int)ProxyClasses.Rarity_SourceAssociation.eStatusReason.Active_Active));
                }

                //Loop through other matching associations that are still active
                foreach (var redundantRarityAssoc in otherActiveMatchingRarityAssocsNotOldest)
                {
                    //and deactivate them, as they are redundant
                    Helper.SetState(
                        localContext.OrganizationService,
                        redundantRarityAssoc.ToEntityReference(),
                        new OptionSetValue((int)ProxyClasses.Rarity_SourceAssociation.eStatus.Inactive),
                        new OptionSetValue((int)ProxyClasses.Rarity_SourceAssociation.eStatusReason.MergedWithDuplicate_Inactive));
                }

                return(oldestMatchingRarityAssociation);
            }
        }
        private void RemoveImplicitAntigens(IOrganizationService organisationService, ProxyClasses.Rarity_SourceAssociation raritySourceAssoc)
        {
            Guid sourceId      = raritySourceAssoc.Rarity.Id;
            Guid rarityAssocId = raritySourceAssoc.Id;

            var antigenAssocsToBeDisassociated = new EntityReferenceCollection();

            //...get all the antigen assocaitions implied by this rarity
            var matchingRarityIntersectRecords = GetAllSourceIntersectRecordsForRarity(organisationService, rarityAssocId);

            //For each antigen assoc implied by this rarity assoc
            foreach (nhs_AnitenSrcAssoc_nhs_RaritySrcAssoc rarityIntersectRecord in matchingRarityIntersectRecords)
            {
                var antigenAssocId = rarityIntersectRecord.Nhs_antigensourceassociationid;

                //Get the antigen association as an entity reference
                var antigenAssocEntityRef = new EntityReference(
                    Antigen_SourceAssociation.LogicalName,
                    (Guid)antigenAssocId);

                var matchingAntigenIntersectRecords = GetAllSourceIntersectRecordsForAntigen(organisationService, antigenAssocId);

                // Add the intersect entity to the list of relationships to be deleted
                antigenAssocsToBeDisassociated.Add(antigenAssocEntityRef);

                //Test whether this antigen association is implied by other rarities
                //i.e. work out if any other rarities imply this same antigen source association
                var isAntigenImpliedByOtherRarities = (from antigenIntersectRecord in matchingAntigenIntersectRecords
                                                       where antigenIntersectRecord.Nhs_antigensourceassociationid == rarityIntersectRecord.Nhs_antigensourceassociationid && //its for the same antigen assoc
                                                       antigenIntersectRecord.Nhs_AnitenSrcAssoc_nhs_RaritySrcAssocId != rarityIntersectRecord.Nhs_AnitenSrcAssoc_nhs_RaritySrcAssocId //but a implied by a different rarity
                                                       select antigenIntersectRecord).Count() > 0;


                // check if the antigen source association is explicit
                var isExplicit = (bool)rarityIntersectRecord.GetAttributeValue <AliasedValue>("antigenSourceAssoc.nhs_isexplicit").Value;

                //If there are no other rarities implying this antigen assoc
                // and the antigen association is also not explicit.
                if (!isAntigenImpliedByOtherRarities && !isExplicit)
                {
                    //Deactivate the antigen source association
                    Helper.SetState(
                        organisationService,
                        antigenAssocEntityRef,
                        new OptionSetValue((int)ProxyClasses.Antigen_SourceAssociation.eStatus.Inactive),
                        new OptionSetValue((int)ProxyClasses.Antigen_SourceAssociation.eStatusReason.Inactive_Inactive));
                }
            }
            if (antigenAssocsToBeDisassociated.Count() > 0)
            {
                //...we need to unlink this any deactivated rarity assocations from their respective antigen associations
                organisationService.Disassociate(
                    ProxyClasses.Rarity_SourceAssociation.LogicalName,
                    raritySourceAssoc.Id,
                    new Relationship("nhs_AntigenSrcAssoc_nhs_RaritySrcAssoc"),
                    antigenAssocsToBeDisassociated);
            }
        }