Exemple #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)}");
            }
        }
        public string GetNameForRelationship(
            EntityMetadata entityMetadata
            , RelationshipMetadataBase relationshipMetadata
            , EntityRole?reflexiveRole
            , ICodeGenerationServiceProvider iCodeGenerationServiceProvider
            )
        {
            string str = reflexiveRole.HasValue ? reflexiveRole.Value.ToString() : string.Empty;

            string keyRelationship = entityMetadata.MetadataId.Value.ToString() + relationshipMetadata.MetadataId.Value + str;

            if (this._knowNames.ContainsKey(keyRelationship))
            {
                return(this._knowNames[keyRelationship]);
            }

            string validName = NamingService.CreateValidName(relationshipMetadata.SchemaName + (!reflexiveRole.HasValue ? string.Empty : reflexiveRole.Value == EntityRole.Referenced ? "_Referenced" : "_Referencing"));

            Dictionary <string, string> knownNamesForEntityMetadata = this._knowNames.Where(d => d.Key.StartsWith(entityMetadata.MetadataId.Value.ToString())).ToDictionary(d => d.Key, d => d.Value);

            validName = ResolveConflictName(validName, s => this._reservedAttributeNames.Contains(s) || knownNamesForEntityMetadata.ContainsValue(s) || string.Equals(s, _typeName, StringComparison.InvariantCultureIgnoreCase));

            this._knowNames.Add(keyRelationship, validName);

            return(validName);
        }
Exemple #3
0
 public String GetNameForRelationship(
     EntityMetadata entityMetadata, RelationshipMetadataBase relationshipMetadata,
     EntityRole?reflexiveRole, IServiceProvider services)
 {
     return(DefaultNamingService.GetNameForRelationship(
                entityMetadata, relationshipMetadata, reflexiveRole, services));
 }
 /// <summary>
 /// Converts a relationship schema name to a relationship.
 /// </summary>
 /// <param name="schemaName"></param>
 /// <param name="primaryEntityRole"></param>
 /// <returns></returns>
 public static Relationship ToRelationship(this string schemaName, EntityRole?primaryEntityRole = null)
 {
     return(new Relationship(schemaName)
     {
         PrimaryEntityRole = primaryEntityRole
     });
 }
Exemple #5
0
 private RelationshipSchemaNameAttribute(string schemaName, EntityRole?primaryEntityRole)
 {
     if (string.IsNullOrWhiteSpace(schemaName))
     {
         throw new ArgumentNullException(nameof(schemaName));
     }
     this._relationship = new Relationship(schemaName);
     this._relationship.PrimaryEntityRole = primaryEntityRole;
 }
Exemple #6
0
        /// <summary>Determines whether two instances are equal.</summary>
        /// <returns>Type: Returns_Booleantrue if the specified Relationship is equal to the Relationship Object; otherwise, false.</returns>
        /// <param name="obj">Type: Returns_Object. The Relationship to compare with the current Relationship.</param>
        public override bool Equals(object obj)
        {
            if (!(obj is Relationship relationship) || !(this.SchemaName == relationship.SchemaName))
            {
                return(false);
            }
            EntityRole?primaryEntityRole1 = this._primaryEntityRole;
            EntityRole?primaryEntityRole2 = relationship._primaryEntityRole;

            return(primaryEntityRole1.GetValueOrDefault() == primaryEntityRole2.GetValueOrDefault() && primaryEntityRole1.HasValue == primaryEntityRole2.HasValue);
        }
Exemple #7
0
        private static T GetRelated <T>(
            OrganizationServiceContext context,
            Entity entity,
            string relationshipSchemaName,
            EntityRole?primaryEntityRole,
            Func <OrganizationServiceContext, Entity, Relationship, T> action)
        {
            var relationship = new Relationship(relationshipSchemaName)
            {
                PrimaryEntityRole = primaryEntityRole
            };

            return(GetRelated(entity, relationship, () => action(context, entity, relationship)));
        }
Exemple #8
0
        /// <summary>Gets the related entity instance for the specified relationship.</summary>
        /// <returns>Type: <see cref="T:Microsoft.Xrm.Sdk.Entity"></see>The collection of related entity instances for the specified relationship.</returns>
        /// <param name="relationshipSchemaName">Type: Returns_String. The name of the relationship.</param>
        /// <param name="primaryEntityRole">Type: <see cref="T:Microsoft.Xrm.Sdk.EntityRole"></see>. The role of the primary entity in the relationship (referenced or referencing).</param>
        protected virtual TEntity GetRelatedEntity <TEntity>(
            string relationshipSchemaName,
            EntityRole?primaryEntityRole)
            where TEntity : Entity
        {
            if (string.IsNullOrWhiteSpace(relationshipSchemaName))
            {
                throw new ArgumentNullException(nameof(relationshipSchemaName));
            }
            Relationship key = new Relationship(relationshipSchemaName)
            {
                PrimaryEntityRole = primaryEntityRole
            };

            return(!this.RelatedEntities.Contains(key) ? default(TEntity) : (TEntity)this.RelatedEntities[key].Entities.FirstOrDefault <Entity>());
        }
Exemple #9
0
        /// <summary>Gets the collection of related entity instances for the specified relationship.</summary>
        /// <returns>Type: Returns_IEnumerableThe collection of related entity instances for the specified relationship.</returns>
        /// <param name="relationshipSchemaName">Type: Returns_String. The schema name of the relationship.</param>
        /// <param name="primaryEntityRole">The role of the primary entity in the relationship (referenced or referencing).</param>
        protected virtual IEnumerable <TEntity> GetRelatedEntities <TEntity>(
            string relationshipSchemaName,
            EntityRole?primaryEntityRole)
            where TEntity : Entity
        {
            if (string.IsNullOrWhiteSpace(relationshipSchemaName))
            {
                throw new ArgumentNullException(nameof(relationshipSchemaName));
            }
            Relationship key = new Relationship(relationshipSchemaName)
            {
                PrimaryEntityRole = primaryEntityRole
            };

            return(!this.RelatedEntities.Contains(key) ? (IEnumerable <TEntity>)null : this.RelatedEntities[key].Entities.Cast <TEntity>());
        }
Exemple #10
0
        /// <summary>Sets the related entity instance for the specified relationship.</summary>
        /// <param name="relationshipSchemaName">Type: Returns_String. The schema name of the relationship.</param>
        /// <param name="primaryEntityRole">Type: <see cref="T:Microsoft.Xrm.Sdk.EntityRole"></see>. The role of the primary entity in the relationship (referenced or referencing).</param>
        /// <param name="entity">Type: <see cref="T:Microsoft.Xrm.Sdk.Entity"></see>. The entity instance to set.</param>
        protected virtual void SetRelatedEntity <TEntity>(
            string relationshipSchemaName,
            EntityRole?primaryEntityRole,
            TEntity entity)
            where TEntity : Entity
        {
            if (string.IsNullOrWhiteSpace(relationshipSchemaName))
            {
                throw new ArgumentNullException(nameof(relationshipSchemaName));
            }
            if ((object)entity != null && string.IsNullOrWhiteSpace(entity.LogicalName))
            {
                throw new ArgumentException("The entity is missing a value for the 'LogicalName' property.", nameof(entity));
            }
            Relationship key = new Relationship(relationshipSchemaName)
            {
                PrimaryEntityRole = primaryEntityRole
            };
            EntityCollection entityCollection1;

            if ((object)entity == null)
            {
                entityCollection1 = (EntityCollection)null;
            }
            else
            {
                entityCollection1 = new EntityCollection((IList <Entity>) new TEntity[1]
                {
                    entity
                })
                {
                    EntityName = entity.LogicalName
                }
            };
            EntityCollection entityCollection2 = entityCollection1;

            if (entityCollection2 != null)
            {
                this.RelatedEntities[key] = entityCollection2;
            }
            else
            {
                this.RelatedEntities.Remove(key);
            }
        }
Exemple #11
0
        /// <summary>Sets the collection of related entity instances for the specified relationship.</summary>
        /// <param name="relationshipSchemaName">Type: Returns_String. The schema name of the relationship.</param>
        /// <param name="primaryEntityRole">Type: <see cref="T:Microsoft.Xrm.Sdk.EntityRole"></see>. The role of the primary entity in the relationship (referenced or referencing).</param>
        /// <param name="entities">Type: Returns_IEnumerable. The collection of entity instances to set.</param>
        protected virtual void SetRelatedEntities <TEntity>(
            string relationshipSchemaName,
            EntityRole?primaryEntityRole,
            IEnumerable <TEntity> entities)
            where TEntity : Entity
        {
            if (string.IsNullOrWhiteSpace(relationshipSchemaName))
            {
                throw new ArgumentNullException(nameof(relationshipSchemaName));
            }
            if (entities != null && entities.Any <TEntity>((Func <TEntity, bool>)(entity => string.IsNullOrWhiteSpace(entity.LogicalName))))
            {
                throw new ArgumentException("An entity is missing a value for the 'LogicalName' property.", nameof(entities));
            }
            Relationship key = new Relationship(relationshipSchemaName)
            {
                PrimaryEntityRole = primaryEntityRole
            };
            EntityCollection entityCollection1;

            if (entities == null)
            {
                entityCollection1 = (EntityCollection)null;
            }
            else
            {
                entityCollection1 = new EntityCollection((IList <Entity>) new List <Entity>((IEnumerable <Entity>)entities))
                {
                    EntityName = entities.First <TEntity>().LogicalName
                }
            };
            EntityCollection entityCollection2 = entityCollection1;

            if (entityCollection2 != null)
            {
                this.RelatedEntities[key] = entityCollection2;
            }
            else
            {
                this.RelatedEntities.Remove(key);
            }
        }
Exemple #12
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);
            }
        }
Exemple #13
0
        /// <summary>
        /// Modifies a related entity for a specific relationship.
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <param name="relationshipSchemaName"></param>
        /// <param name="primaryEntityRole"></param>
        /// <param name="value"></param>
        public static void SetRelatedEntity <TEntity>(this Entity entity, string relationshipSchemaName, EntityRole?primaryEntityRole, TEntity value) where TEntity : Entity
        {
            relationshipSchemaName.ThrowOnNullOrWhitespace("relationshipSchemaName");

            var relationship = new Relationship(relationshipSchemaName)
            {
                PrimaryEntityRole = primaryEntityRole
            };

            SetRelatedEntity(entity, relationship, value);
        }
 private static T ForEntityRelationship <T>(Entity source, string relationshipSchemaName, EntityRole?primaryEntityRole, Entity target, Func <Entity, Relationship, Entity, T> action)
 {
     return(ForEntityRelationship(source, relationshipSchemaName, primaryEntityRole, relationship => action(source, relationship, target)));
 }
        private static T ForEntityRelationship <T>(Entity source, string relationshipSchemaName, EntityRole?primaryEntityRole, Func <Relationship, T> action)
        {
            source.ThrowOnNull("source");
            relationshipSchemaName.ThrowOnNullOrWhitespace("relationshipSchemaName");

            return(action(relationshipSchemaName.ToRelationship(primaryEntityRole)));
        }
 public static void AddRelatedObject(this OrganizationServiceContext context, Entity source, string relationshipSchemaName, Entity target, EntityRole?primaryEntityRole = null)
 {
     ForEntityRelationship(source, relationshipSchemaName, primaryEntityRole, target, context.AddRelatedObject);
 }
 private static void ForEntityRelationship(Entity source, string relationshipSchemaName, EntityRole?primaryEntityRole, Entity target, Action <Entity, Relationship, Entity> action)
 {
     ForEntityRelationship <object>(source, relationshipSchemaName, primaryEntityRole,
                                    relationship =>
     {
         action(source, relationship, target);
         return(null);
     });
 }
Exemple #18
0
        /// <inheritdoc />
        public string GetNameForRelationship(EntityMetadata entityMetadata, RelationshipMetadataBase relationshipMetadata, EntityRole?reflexiveRole, IServiceProvider services)
        {
            string value = _defaultService.GetNameForRelationship(entityMetadata, relationshipMetadata, reflexiveRole, services);

            value = ModifyPublisher(value);
            return(value);
        }
 public static void DeleteLink(this OrganizationServiceContext context, Entity source, string relationshipSchemaName, Entity target, EntityRole?primaryEntityRole = null)
 {
     ForEntityRelationship(source, relationshipSchemaName, primaryEntityRole, target, context.DeleteLink);
 }
Exemple #20
0
        /// <summary>
        /// Retrieves the collection of related entities for a specific relationship.
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="context"></param>
        /// <param name="relationshipSchemaName"></param>
        /// <param name="primaryEntityRole"></param>
        /// <returns></returns>
        public static IEnumerable <Entity> GetRelatedEntities(this Entity entity, OrganizationServiceContext context, string relationshipSchemaName, EntityRole?primaryEntityRole = null)
        {
            context.ThrowOnNull("context");
            entity.ThrowOnNull("entity");
            relationshipSchemaName.ThrowOnNullOrWhitespace("relationshipSchemaName");

            return(GetRelated(context, entity, relationshipSchemaName, primaryEntityRole, GetRelatedEntities <Entity>));
        }
Exemple #21
0
        /// <summary>
        /// Retrieves the collection of related entities for a specific relationship.
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <param name="relationshipSchemaName"></param>
        /// <param name="primaryEntityRole"></param>
        /// <returns></returns>
        /// <remarks>
        /// The entity's <see cref="P:Microsoft.Xrm.Sdk.Entity.RelatedEntities"/> collection should be loaded by first calling the <see cref="M:Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.LoadProperty(Microsoft.Xrm.Sdk.Entity,Microsoft.Xrm.Sdk.Relationship)"/> method.
        /// </remarks>
        public static IEnumerable <TEntity> GetRelatedEntities <TEntity>(this Entity entity, string relationshipSchemaName, EntityRole?primaryEntityRole = null) where TEntity : Entity
        {
            relationshipSchemaName.ThrowOnNullOrWhitespace("relationshipSchemaName");

            var relationship = new Relationship(relationshipSchemaName)
            {
                PrimaryEntityRole = primaryEntityRole
            };

            return(GetRelatedEntities <TEntity>(entity, relationship));
        }
Exemple #22
0
        public string GetNameForRelationship(EntityMetadata entityMetadata, RelationshipMetadataBase relationshipMetadata, EntityRole?reflexiveRole, IServiceProvider services)
        {
            var defaultName = DefaultService.GetNameForRelationship(entityMetadata, relationshipMetadata, reflexiveRole, services);

            return(CamelCaseMemberNames
                ? CamelCaser.Case(defaultName)
                : defaultName);
        }
Exemple #23
0
        public override string GetNameForRelationship(EntityMetadata entityMetadata, RelationshipMetadataBase relationshipMetadata, EntityRole?reflexiveRole, IServiceProvider services)
        {
            string returnValue  = string.Empty;
            string defaultValue = base.GetNameForRelationship(entityMetadata, relationshipMetadata, reflexiveRole, services);

            foreach (var namer in _namers)
            {
                Trace.Debug($"Executing naming rule {nameof(GetNameForRelationship)} using {namer.GetType().FullName}");

                returnValue = namer.GetNameForRelationship(entityMetadata, relationshipMetadata, reflexiveRole, services);
            }

            if (string.IsNullOrEmpty(returnValue))
            {
                returnValue = defaultValue;
            }

            var cacheItem = DynamicsMetadataCache.Relationships.GetOrParse(relationshipMetadata);

            if (cacheItem != null)
            {
                cacheItem.GeneratedTypeName = returnValue;
            }

            DynamicsMetadataCache.Relationships.Set(cacheItem);

            return(string.IsNullOrEmpty(returnValue) ? defaultValue : returnValue);
        }
Exemple #24
0
 protected override IEnumerable <TEntity> GetRelatedEntities <TEntity>(string relationshipSchemaName, EntityRole?primaryEntityRole)
 {
     return(_context != null
                         ? this.GetRelatedEntities(_context, relationshipSchemaName, primaryEntityRole).Cast <TEntity>()
                         : base.GetRelatedEntities <TEntity>(relationshipSchemaName, primaryEntityRole));
 }
Exemple #25
0
        /// <summary>
        /// Modifies the collection of related entities for a specific relationship.
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <param name="relationshipSchemaName"></param>
        /// <param name="primaryEntityRole"></param>
        /// <param name="entities"></param>
        public static void SetRelatedEntities <TEntity>(this Entity entity, string relationshipSchemaName, EntityRole?primaryEntityRole, IEnumerable <TEntity> entities) where TEntity : Entity
        {
            relationshipSchemaName.ThrowOnNullOrWhitespace("relationshipSchemaName");

            if (entities != null && entities.Any(e => string.IsNullOrWhiteSpace(e.LogicalName)))
            {
                throw new ArgumentException("An entity is missing a value for the 'LogicalName' property.", "entities");
            }

            var relationship = new Relationship(relationshipSchemaName)
            {
                PrimaryEntityRole = primaryEntityRole
            };

            SetRelatedEntities(entity, relationship, entities);
        }
Exemple #26
0
 protected override TEntity GetRelatedEntity <TEntity>(string relationshipSchemaName, EntityRole?primaryEntityRole)
 {
     return(_context != null
                         ? this.GetRelatedEntity(_context, relationshipSchemaName, primaryEntityRole) as TEntity
                         : base.GetRelatedEntity <TEntity>(relationshipSchemaName, primaryEntityRole));
 }
 public static bool DetachLink(this OrganizationServiceContext context, Entity source, string relationshipSchemaName, Entity target, EntityRole?primaryEntityRole = null)
 {
     return(ForEntityRelationship <bool>(source, relationshipSchemaName, primaryEntityRole, target, context.DetachLink));
 }
 public static void IsAttached(this OrganizationServiceContext context, Entity source, string relationshipSchemaName, Entity target, EntityRole?primaryEntityRole = null)
 {
     ForEntityRelationship <bool>(source, relationshipSchemaName, primaryEntityRole, target, context.IsAttached);
 }
        /// <summary>
        /// Loads the related entity collection for the specified relationship.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="entity"></param>
        /// <param name="relationshipSchemaName"></param>
        /// <param name="primaryEntityRole"></param>
        public static void LoadProperty(this OrganizationServiceContext context, Entity entity, string relationshipSchemaName, EntityRole?primaryEntityRole = null)
        {
            relationshipSchemaName.ThrowOnNullOrWhitespace("relationshipSchemaName");

            var relationship = new Relationship(relationshipSchemaName)
            {
                PrimaryEntityRole = primaryEntityRole
            };

            context.LoadProperty(entity, relationship);
        }
Exemple #30
0
        /// <summary>
        /// Modifies the collection of related entities for a specific relationship.
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="propertyName"></param>
        /// <param name="relationshipSchemaName"></param>
        /// <param name="primaryEntityRole"></param>
        /// <param name="entities"></param>
        /// <remarks>
        /// Raises the property change events.
        /// </remarks>
        protected virtual void SetRelatedEntities <TEntity>(string propertyName, string relationshipSchemaName, EntityRole?primaryEntityRole, IEnumerable <TEntity> entities)
            where TEntity : Entity
        {
            propertyName.ThrowOnNullOrWhitespace("propertyName");
            relationshipSchemaName.ThrowOnNullOrWhitespace("relationshipSchemaName");

            // check that the new value is different from the current value
            // TODO: perform comparison

            RaisePropertyChanging(propertyName);

            EntityExtensions.SetRelatedEntities(this, relationshipSchemaName, primaryEntityRole, entities);

            RaisePropertyChanged(propertyName);
        }