Пример #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="bag"></param>
        /// <param name="entity"></param>
        /// <param name="relatedentities"></param>
        /// <param name="intersect"></param>
        /// <param name="batchSize"></param>
        public static void Associate(this IBag bag, Entity entity, List <EntityReference> relatedentities, string intersect, int batchSize)
        {
            EntityRole?role = null;

            if (relatedentities.Count > 0 && relatedentities[0].LogicalName == entity.LogicalName)
            {   // N:N-relation till samma entitet, då måste man ange en roll, tydligen.
                role = EntityRole.Referencing;
            }

            if (batchSize < 1)
            {
                throw new ArgumentException("Must be a positive number", "batchSize");
            }

            var processed = 0;

            while (processed < relatedentities.Count)
            {
                var batch = new EntityReferenceCollection(relatedentities.Skip(processed).Take(batchSize).ToList());
                processed += batch.Count();

                var req = new AssociateRequest
                {
                    Target       = entity.ToEntityReference(),
                    Relationship = new Relationship(intersect)
                    {
                        PrimaryEntityRole = role
                    },
                    RelatedEntities = batch
                };
                bag.Service.Execute(req);
                bag.Logger.Log($"Associated {batch.Count} {(relatedentities.Count > 0 ? relatedentities[0].LogicalName : string.Empty)} with {entity.ToStringExt(bag.Service)}");
            }
        }
Пример #2
0
        public bool UnlinkFrom(IEnumerable <EntityReference> related)
        {
            try
            {
                var batchSize = (related.Count() >= 1000)
                    ? 1000
                    : related.Count();

                var processed = 0;
                while (processed < related.Count())
                {
                    var batch = new EntityReferenceCollection(related.Skip(processed).Take(batchSize).ToList());
                    processed += batch.Count();

                    var req = new DisassociateRequest
                    {
                        Target          = target.ToEntityReference(),
                        Relationship    = new Relationship(intersectionName),
                        RelatedEntities = batch
                    };
                    container.Service.Execute(req);
                    container.Log("Disassociated {0} {1} from {2}", batch.Count, related.Count() > 0 ? related.First().LogicalName : string.Empty, target.LogicalName);
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
        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);
            }
        }
Пример #4
0
        /// <summary>Associates current record with relatedentities, using specified intersect relationship</summary>
        /// <param name="entity"></param>
        /// <param name="container"></param>
        /// <param name="relatedEntities">Collection of the entities to be related to current entity</param>
        /// <param name="intersect">Name of the intersect relationship/entity</param>
        /// <param name="batchSize">Optional. Determines the max number of entities to associate per request</param>
        /// <remarks>To be used with N:N-relationships.</remarks>
        /// <exception cref="FaultException{TDetail}">
        /// <strong>TDetail</strong> may be typed as:
        /// <para>
        /// <see cref="OrganizationServiceFault" />: Thrown when any of the associations already exists.
        /// </para>
        /// </exception>
        public static void Associate(this IExecutionContainer container, Entity entity, EntityCollection relatedEntities, string intersect, int batchSize)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            EntityRole?role = null;

            if (relatedEntities.Entities.Count > 0 && relatedEntities[0].LogicalName == entity.LogicalName)
            {
                // N:N-relation till samma entitet, då måste man ange en roll, tydligen.
                role = EntityRole.Referencing;
            }

            if (batchSize < 1)
            {
                throw new ArgumentException("batchSize must be larger than zero.");
            }

            var entRefCollection = relatedEntities.ToEntityReferenceCollection();
            var processed        = 0;

            while (processed < relatedEntities.Entities.Count)
            {
                var batch = new EntityReferenceCollection(entRefCollection.Skip(processed).Take(batchSize).ToList());
                processed += batch.Count();

                var req = new AssociateRequest
                {
                    Target       = entity.ToEntityReference(),
                    Relationship = new Relationship(intersect)
                    {
                        PrimaryEntityRole = role
                    },
                    RelatedEntities = batch
                };
                container.Service.Execute(req);
                container.Log("Associated {0} {1} with {2}", batch.Count, relatedEntities.Entities.Count > 0 ? relatedEntities[0].LogicalName : "", entity.LogicalName);
            }
        }
Пример #5
0
        public bool LinkTo(IEnumerable <EntityReference> related)
        {
            try
            {
                var batchSize = (related.Count() >= 1000)
                    ? 1000
                    : related.Count();

                var role = default(EntityRole?);
                if (related.Count() > 0 && related.First().LogicalName == target.LogicalName)
                {
                    // N:N-relation till samma entitet, då måste man ange en roll, tydligen.
                    role = EntityRole.Referencing;
                }

                var processed = 0;
                while (processed < related.Count())
                {
                    var batch = new EntityReferenceCollection(related.Skip(processed).Take(batchSize).ToList());
                    processed += batch.Count();

                    var req = new AssociateRequest
                    {
                        Target       = target.ToEntityReference(),
                        Relationship = new Relationship(intersectionName)
                        {
                            PrimaryEntityRole = role
                        },
                        RelatedEntities = batch
                    };
                    container.Service.Execute(req);
                    container.Log("Associated {0} {1} with {2}", batch.Count, related.Count() > 0 ? related.First().LogicalName : string.Empty, target.LogicalName);
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Пример #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="bag"></param>
        /// <param name="entity"></param>
        /// <param name="relatedentities"></param>
        /// <param name="intersect"></param>
        /// <param name="batchSize"></param>
        public static void Disassociate(this IBag bag, Entity entity, List <EntityReference> relatedentities, string intersect, int batchSize)
        {
            if (batchSize < 1)
            {
                throw new ArgumentException("Must be a positive number", "batchSize");
            }

            var processed = 0;

            while (processed < relatedentities.Count)
            {
                var batch = new EntityReferenceCollection(relatedentities.Skip(processed).Take(batchSize).ToList());
                processed += batch.Count();

                var req = new DisassociateRequest
                {
                    Target          = entity.ToEntityReference(),
                    Relationship    = new Relationship(intersect),
                    RelatedEntities = batch
                };
                bag.Service.Execute(req);
                bag.Logger.Log($"Disassociated {batch.Count} {(relatedentities.Count > 0 ? relatedentities[0].LogicalName : "")} from {entity.ToStringExt(bag.Service)}");
            }
        }
        private void AddImplicitAntigens(IOrganizationService organisationService, Rarity_SourceAssociation raritySourceAssoc)
        {
            var sourceId = raritySourceAssoc.Source.Id;
            var rarityId = raritySourceAssoc.Rarity.Id;

            var targetAntigensForRarity = Helper.GetAntigensImpliedByRarity(organisationService, rarityId);

            var currentlyAssociatedAntigens = GetAssociatedSourceAntigens(organisationService, sourceId);

            var intersectEntitiesToBeCreated = new EntityReferenceCollection();

            foreach (var implicitAntigen in targetAntigensForRarity)
            {
                var oldestActiveMatchSameResult = (from associatedAntigen in currentlyAssociatedAntigens
                                                   where associatedAntigen.Antigen.Id == implicitAntigen.Antigen.Id &&
                                                   associatedAntigen.AntigenResult_OptionSetValue.Value == implicitAntigen.AntigenResult_OptionSetValue.Value
                                                   select associatedAntigen).FirstOrDefault();

                var oldestMatchNotExplicitOrImplied = (from associatedAntigen in currentlyAssociatedAntigens
                                                       where associatedAntigen.Antigen.Id == implicitAntigen.Antigen.Id &&
                                                       associatedAntigen.Explicit == false &&
                                                       IsAntigenAssocImpliedByRarityAssoc(organisationService, associatedAntigen, raritySourceAssoc) == false
                                                       select associatedAntigen).FirstOrDefault();

                if (oldestActiveMatchSameResult != null)
                { //If this is the oldest association for that antigen with the same result
                    var isAlreadyLinkedWithRarity = IsAntigenAssocImpliedByRarityAssoc(
                        organisationService,
                        oldestActiveMatchSameResult,
                        raritySourceAssoc);
                    var isAlreadyActive = oldestActiveMatchSameResult.Status == Antigen_SourceAssociation.eStatus.Active;

                    if (!isAlreadyLinkedWithRarity)
                    { //if its not already linked, then do so
                        intersectEntitiesToBeCreated.Add(oldestActiveMatchSameResult.ToEntityReference());
                    }

                    if (!isAlreadyActive)
                    { // and if its not active, then make it so
                        Helper.SetState(
                            organisationService,
                            oldestActiveMatchSameResult,
                            new OptionSetValue((int)ProxyClasses.Antigen_SourceAssociation.eStatus.Active),
                            new OptionSetValue((int)ProxyClasses.Antigen_SourceAssociation.eStatusReason.Active_Active));
                    }
                }
                else if (oldestMatchNotExplicitOrImplied != null)
                //Otherwise, find the oldest antigen association not explicit or implied, with any result/status
                {
                    var isAlreadyActive           = oldestActiveMatchSameResult.Status == Antigen_SourceAssociation.eStatus.Active;
                    var isAlreadyLinkedWithRarity = IsAntigenAssocImpliedByRarityAssoc(
                        organisationService,
                        oldestMatchNotExplicitOrImplied,
                        raritySourceAssoc);

                    if (!isAlreadyActive)
                    { //if its not already active
                        // then Activate the record
                        Helper.SetState(
                            organisationService,
                            oldestMatchNotExplicitOrImplied.ToEntityReference(),
                            new OptionSetValue((int)ProxyClasses.Antigen_RarityAssociation.eStatus.Active),
                            new OptionSetValue((int)ProxyClasses.Antigen_RarityAssociation.eStatusReason.Active_Active));
                    }

                    if (!isAlreadyLinkedWithRarity)
                    { //if its not already linked, then do so
                        intersectEntitiesToBeCreated.Add(oldestMatchNotExplicitOrImplied.ToEntityReference());
                    }

                    if (
                        (implicitAntigen.AntigenResult == ProxyClasses.Antigen_RarityAssociation.eAntigenResult_RarityContext.Present &&
                         oldestMatchNotExplicitOrImplied.AntigenResult != ProxyClasses.Antigen_SourceAssociation.eAntigenResult_SourceContext.Present) ||
                        (implicitAntigen.AntigenResult == ProxyClasses.Antigen_RarityAssociation.eAntigenResult_RarityContext.Absent &&
                         oldestMatchNotExplicitOrImplied.AntigenResult != ProxyClasses.Antigen_SourceAssociation.eAntigenResult_SourceContext.Absent))
                    { //and if the antigen result doesn't match
                        //then update it
                        oldestMatchNotExplicitOrImplied.AntigenResult =
                            (implicitAntigen.AntigenResult == ProxyClasses.Antigen_RarityAssociation.eAntigenResult_RarityContext.Present)
                            ? ProxyClasses.Antigen_SourceAssociation.eAntigenResult_SourceContext.Present
                            : ProxyClasses.Antigen_SourceAssociation.eAntigenResult_SourceContext.Absent;

                        organisationService.Update(oldestMatchNotExplicitOrImplied);
                    }
                }
                else //no matching Antigen Source Association exists so...
                { //we'll create a new association
                    var implicitAntigenSourceAssociation = new ProxyClasses.Antigen_SourceAssociation()
                    {
                        Source        = new EntityReference(ProxyClasses.RareBloodSource.LogicalName, sourceId),
                        Antigen       = implicitAntigen.Antigen,
                        AntigenResult = implicitAntigen.AntigenResult == ProxyClasses.Antigen_RarityAssociation.eAntigenResult_RarityContext.Present ? ProxyClasses.Antigen_SourceAssociation.eAntigenResult_SourceContext.Present : ProxyClasses.Antigen_SourceAssociation.eAntigenResult_SourceContext.Absent
                    };
                    var implicitAntigenSourceAssociationId = organisationService.Create(implicitAntigenSourceAssociation);

                    //and we'll link it to the rarity association
                    intersectEntitiesToBeCreated.Add(new EntityReference(ProxyClasses.Antigen_SourceAssociation.LogicalName, implicitAntigenSourceAssociationId));
                }
            }

            if (intersectEntitiesToBeCreated.Count() > 0)
            {
                //...we need to link this rarity assocation to the antigen associations
                organisationService.Associate(
                    ProxyClasses.Rarity_SourceAssociation.LogicalName,
                    raritySourceAssoc.Id,
                    new Relationship("nhs_AntigenSrcAssoc_nhs_RaritySrcAssoc"),
                    intersectEntitiesToBeCreated);
            }
        }