/// <summary>
        /// Retrieves the references from the data store that involve the provided entity.
        /// </summary>
        /// <param name="entity">The entity to retrieve the references for.</param>
        /// <param name="activateAll">A value indicating whether to activate the reference by loading the corresponding entities and setting them to the SourceEntity and ReferenceEntity properties.</param>
        /// <returns>A collection of all the references in the store that involve the provided entity.</returns>
        public virtual EntityReferenceCollection GetReferences(IEntity entity, bool activateAll)
        {
            EntityReferenceCollection references = new EntityReferenceCollection();

            using (LogGroup logGroup = LogGroup.StartDebug("Retrieving the references associated with the provided entity."))
            {
                if (entity == null)
                {
                    throw new ArgumentNullException("entity");
                }

                foreach (IDataStore store in DataAccess.Data.Stores)
                {
                    if (IsReferenceStore(store))
                    {
                        if (StoresReferencesToType(store, entity.ShortTypeName))
                        {
                            using (LogGroup logGroup2 = LogGroup.StartDebug("Retrieving the references from '" + store.Name + "'."))
                            {
                                references.AddRange(store.Indexer.GetEntities <EntityReference>("Entity1ID", entity.ID));
                                references.AddRange(store.Indexer.GetEntities <EntityReference>("Entity2ID", entity.ID));
                            }
                        }
                    }
                }
            }

            return(references);
        }
        /// <summary>
        /// Retrieves the references that are no longer active on the provided entity and haven't yet been removed from the data store.
        /// </summary>
        /// <param name="entity">The entity containing the active references to compare with.</param>
        /// <param name="idsOfEntitiesToKeep">An array of IDs of the entities that are still active and are not obsolete.</param>
        /// <returns>A collection of the obsolete references that correspond with the provided entity.</returns>
        public virtual EntityReferenceCollection GetObsoleteReferences(IEntity entity, Guid[] idsOfEntitiesToKeep)
        {
            EntityReferenceCollection collection = new EntityReferenceCollection(entity);

            using (LogGroup logGroup = LogGroup.StartDebug("Retrieving the obsolete references for the entity provided."))
            {
                Type entityType = entity.GetType();

                foreach (PropertyInfo property in entityType.GetProperties())
                {
                    if (EntitiesUtilities.IsReference(entityType, property.Name, property.PropertyType))
                    {
                        LogWriter.Debug("Checking reference property: " + property.Name);

                        Type referencedEntityType = EntitiesUtilities.GetReferenceType(entity, property);

                        // If the referenced entity type is not null then get the obsolete references
                        if (referencedEntityType != null)
                        {
                            collection.AddRange(
                                GetObsoleteReferences(entity,
                                                      property.Name,
                                                      referencedEntityType,
                                                      idsOfEntitiesToKeep
                                                      )
                                );
                        }
                        // else
                        // Otherwise skip it because a null referenced entity type means its a dynamically typed reference property which hasn't been set
                    }
                }
            }
            return(collection);
        }
Beispiel #3
0
        public void Associate(EntityReference entity, string relationship, IList <EntityReference> relatedEntities)
        {
            EntityReferenceCollection collection = new EntityReferenceCollection();

            collection.AddRange(relatedEntities);

            this.Service.Associate(entity.LogicalName, entity.Id, new Relationship(relationship), collection);
        }
        public void AssociateRecords(Microsoft.Xrm.Sdk.EntityReference objectRef, Microsoft.Xrm.Sdk.Relationship relationName, params Microsoft.Xrm.Sdk.EntityReference[] entityReferences)
        {
            var collec = new EntityReferenceCollection();

            collec.AddRange(entityReferences);

            AdminOrganizationService.Associate(objectRef.LogicalName, objectRef.Id, relationName, collec);
        }
Beispiel #5
0
        public void Disassociate(string relationshipName, Associate association)
        {
            Guard.This(relationshipName).AgainstNullOrEmpty();

            var relationship = new Relationship(relationshipName);

            var relatedEntities = new EntityReferenceCollection();

            relatedEntities.AddRange(association.RelatedEntities.Select(s => new EntityReference(s.Value, s.Key)));

            service.Disassociate(association.EntityName, association.EntityId, relationship, relatedEntities);
        }
        /// <summary>
        /// Retrieves all the references between the entities of the specified types.
        /// </summary>
        /// <param name="type1Name">The first type of one of the entities involved in the reference.</param>
        /// <param name="type2Name">The type of the other entity involved in the reference.</param>
        /// <returns>A collection of the entities found in the data store between the two specified types.</returns>
        public virtual EntityReferenceCollection GetReferences(string type1Name, string type2Name)
        {
            string dataStoreName = DataUtilities.GetDataStoreName(type1Name, type2Name);

            EntityReference[] entities =
                Provider.Stores[dataStoreName].Indexer.GetEntities <EntityReference>();

            EntityReferenceCollection references = new EntityReferenceCollection();

            references.AddRange(entities);

            return(references);
        }
        /// <summary>
        /// Retrieves all the data references between all types.
        /// </summary>
        /// <returns>A collection of the entities found in all data stores.</returns>
        public virtual EntityReferenceCollection GetReferences()
        {
            EntityReferenceCollection references = new EntityReferenceCollection();

            foreach (string dataStoreName in DataAccess.Data.GetDataStoreNames())
            {
                // If the name contains a dash then the store contains references
                if (dataStoreName.IndexOf('-') > -1)
                {
                    // Constrain the query to the IEntity type to ensure both EntityReference and EntityReference objects are returned
                    EntityReference[] entities = Collection <EntityReference> .ConvertAll(
                        Provider.Stores[dataStoreName].Indexer.GetEntities());

                    references.AddRange(entities);
                }
            }

            return(references);
        }
Beispiel #8
0
        /// <summary>
        /// Import entities to CRM from dictionary of blocks
        /// </summary>
        /// <param name="blocks">Blocks with entities to import</param>
        /// <returns>Tuple with counters for: Created, Updated, Skipped and Failed records</returns>
        public Tuple <int, int, int, int, int, EntityReferenceCollection> ImportToCRM(ShuffleBlocks blocks)
        {
            log.StartSection("ImportToCRM");
            if (definition == null)
            {
                throw new ArgumentNullException("Definition", "Shuffle definition must be specified to import data");
            }

            int created = 0;
            int updated = 0;
            int skipped = 0;
            int deleted = 0;
            int failed  = 0;
            EntityReferenceCollection references = new EntityReferenceCollection();

            XmlNode xRoot   = CintXML.FindChild(definition, "ShuffleDefinition");
            XmlNode xBlocks = CintXML.FindChild(xRoot, "Blocks");

            if (xBlocks != null)
            {
                guidmap     = new Dictionary <Guid, Guid>();
                stoponerror = CintXML.GetBoolAttribute(xRoot, "StopOnError", false);
                timeout     = CintXML.GetIntAttribute(xRoot, "Timeout", -1);
                double savedtimeout = -1;
                if (timeout > -1)
                {
                    try
                    {
                        SendLine("Setting timeout: {0} minutes", timeout);
                        OrganizationServiceProxy orgsvcpxy = crmsvc.GetService <OrganizationServiceProxy>();
                        savedtimeout      = orgsvcpxy.Timeout.TotalMinutes;
                        orgsvcpxy.Timeout = new TimeSpan(0, timeout, 0);
                    }
                    catch (InvalidPluginExecutionException)
                    {   // Couldn't cast to correct service type, for some reason...
                        savedtimeout = -1;
                    }
                }

                int totalBlocks  = xBlocks.ChildNodes.Count;
                int currentBlock = 0;
                foreach (XmlNode xBlock in xBlocks.ChildNodes)
                {
                    currentBlock++;
                    SendStatus(totalBlocks, currentBlock, -1, -1);
                    if (xBlock.NodeType == XmlNodeType.Element)
                    {
                        switch (xBlock.Name)
                        {
                        case "DataBlock":
                            string name = CintXML.GetAttribute(xBlock, "Name");
                            if (!blocks.ContainsKey(name))
                            {
                                blocks.Add(name, new CintDynEntityCollection());
                            }
                            Tuple <int, int, int, int, int, EntityReferenceCollection> dataresult = ImportDataBlock(xBlock, blocks[name]);
                            created += dataresult.Item1;
                            updated += dataresult.Item2;
                            skipped += dataresult.Item3;
                            deleted += dataresult.Item4;
                            failed  += dataresult.Item5;
                            references.AddRange(dataresult.Item6);
                            break;

                        case "SolutionBlock":
                            var solutionresult = ImportSolutionBlock(xBlock);
                            switch (solutionresult)
                            {
                            case ItemImportResult.Created: created++; break;

                            case ItemImportResult.Updated: updated++; break;

                            case ItemImportResult.Skipped: skipped++; break;

                            case ItemImportResult.Failed: failed++; break;
                            }
                            break;
                        }
                    }
                }
                SendStatus(0, 0, 0, 0);
                if (savedtimeout > -1)
                {
                    OrganizationServiceProxy orgsvcpxy = crmsvc.GetService <OrganizationServiceProxy>();
                    orgsvcpxy.Timeout = new TimeSpan(0, (int)savedtimeout, 0);
                }
            }
            log.EndSection();
            return(new Tuple <int, int, int, int, int, EntityReferenceCollection>(created, updated, skipped, deleted, failed, references));
        }
        /// <summary>
        /// Import entities to CRM from dictionary of blocks
        /// </summary>
        /// <param name="blocks">Blocks with entities to import</param>
        /// <returns>Tuple with counters for: Created, Updated, Skipped and Failed records</returns>
        public Tuple <int, int, int, int, int, EntityReferenceCollection> ImportToCRM(ShuffleBlocks blocks)
        {
            log.StartSection("ImportToCRM");
            if (definition == null)
            {
                throw new ArgumentNullException("Definition", "Shuffle definition must be specified to import data");
            }

            var created    = 0;
            var updated    = 0;
            var skipped    = 0;
            var deleted    = 0;
            var failed     = 0;
            var references = new EntityReferenceCollection();

            if (ShuffleDefinition.Blocks.Items.Any(b => (b is DataBlock data && data.Import != null) || b is SolutionBlock sol && sol.Import != null))
            {
                guidmap     = new Dictionary <Guid, Guid>();
                stoponerror = ShuffleDefinition.StopOnError;
                timeout     = ShuffleDefinition.TimeoutSpecified ? ShuffleDefinition.Timeout : -1;
                double savedtimeout = -1;
                if (timeout > -1)
                {
                    savedtimeout = SetTimeout();
                }

                var totalBlocks  = ShuffleDefinition.Blocks.Items.Length;
                var currentBlock = 0;
                foreach (var block in ShuffleDefinition.Blocks.Items)
                {
                    currentBlock++;
                    SendStatus(totalBlocks, currentBlock, -1, -1);
                    if (block is DataBlock datablock)
                    {
                        var name = datablock.Name;
                        if (!blocks.ContainsKey(name))
                        {
                            blocks.Add(name, new CintDynEntityCollection());
                        }
                        var dataresult = ImportDataBlock(datablock, blocks[name]);
                        created += dataresult.Item1;
                        updated += dataresult.Item2;
                        skipped += dataresult.Item3;
                        deleted += dataresult.Item4;
                        failed  += dataresult.Item5;
                        references.AddRange(dataresult.Item6);
                    }
                    else if (block is SolutionBlock solutionblock)
                    {
                        var solutionresult = ImportSolutionBlock(solutionblock);
                        switch (solutionresult)
                        {
                        case ItemImportResult.Created: created++; break;

                        case ItemImportResult.Updated: updated++; break;

                        case ItemImportResult.Skipped: skipped++; break;

                        case ItemImportResult.Failed: failed++; break;
                        }
                    }
                }
                SendStatus(0, 0, 0, 0);
                if (savedtimeout > -1)
                {
                    ResetTimeout(savedtimeout);
                }
            }
            log.EndSection();
            return(new Tuple <int, int, int, int, int, EntityReferenceCollection>(created, updated, skipped, deleted, failed, references));
        }
Beispiel #10
0
        /// <summary>
        /// Retrieves all the entities of the specified type with a reference to any of the provided entities.
        /// </summary>
        /// <param name="propertyName">The name of the property containing the reference.</param>
        /// <param name="referencedEntities">An array of entities to check the reference to.</param>
        /// <returns>An array of the references retrieved.</returns>
        public override T[] GetEntitiesWithReference <T>(string propertyName, IEntity[] referencedEntities)
        {
            List <T> entities = null;

            using (LogGroup logGroup = LogGroup.StartDebug("Querying the data store based on the provided parameters."))
            {
                LogWriter.Debug("Property name: " + propertyName);
                LogWriter.Debug("Referenced entities #: " + referencedEntities.Length);

                if (referencedEntities.Length > 0)
                {
                    Type referencedEntityType = referencedEntities[0].GetType();

                    if (referencedEntityType != null)
                    {
                        LogWriter.Debug("Referenced entity type: " + referencedEntityType.ToString());
                    }
                    else
                    {
                        LogWriter.Debug("Referenced entity type: [null]");
                    }

                    Type type = typeof(T);

                    EntityReferenceCollection references = new EntityReferenceCollection();

                    foreach (IEntity referencedEntity in referencedEntities)
                    {
                        // Load the references all in one go, to avoid individual loads
                        references.AddRange(Provider.Referencer.GetReferences(referencedEntity.GetType(), referencedEntity.ID, typeof(T), false));
                    }

                    Db4oDataStore store = (Db4oDataStore)GetDataStore(type);

                    IObjectContainer container = store.ObjectContainer;

                    entities = new List <T>(
                        container
                        .Query <T>(
                            delegate(T e)
                    {
                        bool matches = true;

                        using (LogGroup logGroup2 = LogGroup.Start("Querying entity.", NLog.LogLevel.Debug))
                        {
                            LogWriter.Debug("Checking type " + e.GetType().ToString());
                            LogWriter.Debug("Entity ID: " + e.ID);

                            bool foundReference = references.Includes(e.ID, propertyName);

                            // If referenced entities were provided then entities match if a reference exists
                            if (referencedEntities != null && referencedEntities.Length > 0)
                            {
                                matches = foundReference;
                            }
                            // Otherwise the calling code is trying to get entities where NO reference exists, therefore it matches when no reference is found
                            else
                            {
                                matches = !foundReference;
                            }

                            LogWriter.Debug("Matches: " + matches);
                        }
                        return(matches);
                    }));



                    if (entities != null)
                    {
                        LogWriter.Debug("entities != null");
                    }
                    else
                    {
                        LogWriter.Debug("entities == null");
                    }

                    LogWriter.Debug("Total objects: " + entities.Count);
                }
            }
            return(Release(entities.ToArray()));
        }
        /// <summary>
        /// Retrieves the references from the data store that involve the provided entity.
        /// </summary>
        /// <param name="entity">The entity to retrieve the references for.</param>
        /// <param name="activateAll">A value indicating whether to activate the reference by loading the corresponding entities and setting them to the SourceEntity and ReferenceEntity properties.</param>
        /// <returns>A collection of all the references in the store that involve the provided entity.</returns>
        public virtual EntityReferenceCollection GetReferences(IEntity entity, bool activateAll)
        {
            EntityReferenceCollection references = new EntityReferenceCollection();

            using (LogGroup logGroup = LogGroup.StartDebug("Retrieving the references associated with the provided entity."))
            {
                if (entity == null)
                    throw new ArgumentNullException("entity");

                foreach (IDataStore store in DataAccess.Data.Stores)
                {
                    if (IsReferenceStore(store))
                    {
                        if (StoresReferencesToType(store, entity.ShortTypeName))
                        {
                            using (LogGroup logGroup2 = LogGroup.StartDebug("Retrieving the references from '" + store.Name + "'."))
                            {
                                references.AddRange(store.Indexer.GetEntities<EntityReference>("Entity1ID", entity.ID));
                                references.AddRange(store.Indexer.GetEntities<EntityReference>("Entity2ID", entity.ID));
                            }
                        }
                    }
                }
            }

            return references;
        }
        /// <summary>
        /// Retrieves all the references between the entities of the specified types.
        /// </summary>
        /// <param name="type1Name">The first type of one of the entities involved in the reference.</param>
        /// <param name="type2Name">The type of the other entity involved in the reference.</param>
        /// <returns>A collection of the entities found in the data store between the two specified types.</returns>
        public virtual EntityReferenceCollection GetReferences(string type1Name, string type2Name)
        {
            string dataStoreName = DataUtilities.GetDataStoreName(type1Name, type2Name);

            EntityReference[] entities =
                Provider.Stores[dataStoreName].Indexer.GetEntities<EntityReference>();

            EntityReferenceCollection references = new EntityReferenceCollection();

            references.AddRange(entities);

            return references;
        }
        /// <summary>
        /// Retrieves all the data references between all types.
        /// </summary>
        /// <returns>A collection of the entities found in all data stores.</returns>
        public virtual EntityReferenceCollection GetReferences()
        {
            EntityReferenceCollection references = new EntityReferenceCollection();

            foreach (string dataStoreName in DataAccess.Data.GetDataStoreNames())
            {
                // If the name contains a dash then the store contains references
                if (dataStoreName.IndexOf('-') > -1)
                {
                    // Constrain the query to the IEntity type to ensure both EntityReference and EntityReference objects are returned
                    EntityReference[] entities = Collection<EntityReference>.ConvertAll(
                        Provider.Stores[dataStoreName].Indexer.GetEntities());

                    references.AddRange(entities);
                }
            }

            return references;
        }
        /// <summary>
        /// Retrieves the references that are no longer active on the provided entity and haven't yet been removed from the data store.
        /// </summary>
        /// <param name="entity">The entity containing the active references to compare with.</param>
        /// <param name="idsOfEntitiesToKeep">An array of IDs of the entities that are still active and are not obsolete.</param>
        /// <returns>A collection of the obsolete references that correspond with the provided entity.</returns>
        public virtual EntityReferenceCollection GetObsoleteReferences(IEntity entity, Guid[] idsOfEntitiesToKeep)
        {
            EntityReferenceCollection collection = new EntityReferenceCollection(entity);

            using (LogGroup logGroup = LogGroup.StartDebug("Retrieving the obsolete references for the entity provided."))
            {
                Type entityType = entity.GetType();

                foreach (PropertyInfo property in entityType.GetProperties())
                {
                    if (EntitiesUtilities.IsReference(entityType, property.Name, property.PropertyType))
                    {
                        LogWriter.Debug("Checking reference property: " + property.Name);

                        Type referencedEntityType  = EntitiesUtilities.GetReferenceType(entity, property);

                        // If the referenced entity type is not null then get the obsolete references
                        if (referencedEntityType != null)
                        {
                            collection.AddRange(
                                GetObsoleteReferences(entity,
                                                      property.Name,
                                                      referencedEntityType,
                                                      idsOfEntitiesToKeep
                                                     )
                            );
                        }
                        // else
                        // Otherwise skip it because a null referenced entity type means its a dynamically typed reference property which hasn't been set
                    }
                }
            }
            return collection;
        }