示例#1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SerializableRelatedEntityCollection"/> class.
 /// </summary>
 /// <param name="col">The col.</param>
 public SerializableRelatedEntityCollection(RelatedEntityCollection col)
 {
     foreach (var related in col)
     {
         Add(new KeyValuePairOfRelationshipEntityCollectionX_PsK4FkN(related.Key, related.Value));
     }
 }
示例#2
0
        public void RelatedEntityCollectionInObjectCanBeSerializedAndDeserialized()
        {
            RelatedEntityCollectionContainer relatedEntityCollectionContainer = new RelatedEntityCollectionContainer();
            RelatedEntityCollection          relatedEntityCollection          = new RelatedEntityCollection();

            relatedEntityCollectionContainer.RelatedEntityCollection = relatedEntityCollection;
            Relationship relationship = new Relationship("related_entity");

            relatedEntityCollection.Add(relationship, new EntityCollection());
            JsonSerializer serializer = new JsonSerializer();

            serializer.TypeNameHandling = TypeNameHandling.All;
            serializer.ContractResolver = new XrmContractResolver();
            MemoryStream memoryStream = new MemoryStream(new byte[9000], true);

            using (StreamWriter writer = new StreamWriter(memoryStream))
            {
                serializer.Serialize(new JsonTextWriter(writer), relatedEntityCollectionContainer);
            }

            RelatedEntityCollectionContainer deserializedRelatedEntityCollectionContainer;

            memoryStream = new MemoryStream(memoryStream.ToArray());
            using (StreamReader reader = new StreamReader(memoryStream))
            {
                deserializedRelatedEntityCollectionContainer = (RelatedEntityCollectionContainer)serializer.Deserialize(new JsonTextReader(reader));
            }

            Assert.Equal(relatedEntityCollectionContainer.GetType(), deserializedRelatedEntityCollectionContainer.GetType());
            RelatedEntityCollection deserializedRelatedEntityCollection = (RelatedEntityCollection)deserializedRelatedEntityCollectionContainer.RelatedEntityCollection;

            Assert.Equal(relatedEntityCollection.Count, deserializedRelatedEntityCollection.Count);
            Assert.Equal(relatedEntityCollection.Keys.First(), deserializedRelatedEntityCollection.Keys.First());
            Assert.Equal(relatedEntityCollection.Values.First().Entities.Count, deserializedRelatedEntityCollection.Values.First().Entities.Count);
        }
示例#3
0
        public void SerializeOdataOjectAsJsonTest()
        {
            // Arrange
            var expected = "{\"Id\":10,\"Object\":{\"Id\":10,\"CreateDate\":\"0001-01-01T00:00:00\",\"CreatedBy\":0,\"Entity\":null,\"EntityId\":null,\"LastUpdated\":null,\"LastUpdatedBy\":null,\"Property\":\"A\",\"Value\":\"B\"},\"RelatedEntityCollection\":[{\"Count\":2,\"RelatedEntity\":\"Fake\",\"RelatedEntities\":[{\"Id\":\"1\",\"Object\":{ \"Id\" : \"1\" },\"Uri\":null},{\"Id\":\"2\",\"Object\":{ \"Id\" : \"2\" },\"Uri\":null}]}],\"Uri\":null}";
            var relatedEntityCollection = new RelatedEntityCollection {
                Entity = "Addendum", EntityId = "10", RelatedEntity = "Fake"
            };
            var json1          = "{ \"Id\" : \"1\" }";
            var jObject1       = JObject.Parse(json1);
            var json2          = "{ \"Id\" : \"2\" }";
            var jObject2       = JObject.Parse(json1);
            var relatedEntity1 = new RelatedEntity {
                Id = jObject1.GetValue("Id").ToString(), Object = new JRaw(json1)
            };
            var relatedEntity2 = new RelatedEntity {
                Id = jObject2.GetValue("Id").ToString(), Object = new JRaw(json2)
            };

            relatedEntityCollection.Add(relatedEntity1);
            relatedEntityCollection.Add(relatedEntity2);
            var odata = new OdataObject <Addendum, long>()
            {
                Object = new Addendum {
                    Id = 10, Property = "A", Value = "B"
                }
            };

            odata.RelatedEntityCollection.Add(relatedEntityCollection);

            // Act
            var actual = new Serializer().Json(odata, ContractResolver.Instance);

            // Assert
            Assert.AreEqual(expected, Encoding.UTF8.GetString(actual));
        }
示例#4
0
        internal async Task <List <RelatedEntityCollection> > GetRelatedExtensionEntitiesAsync(IEnumerable <TInterface> entities, IEnumerable <string> extensionEntitiesToExpand)
        {
            if (entities == null || !entities.Any())
            {
                return(null);
            }
            var list   = new List <RelatedEntityCollection>();
            var entity = typeof(TEntity).Name;

            foreach (var extensionEntity in extensionEntitiesToExpand)
            {
                var client            = ClientsCache.Json[extensionEntity];
                var entityIdentifiers = entities.Select(e => new EntityIdentifier {
                    Entity = entity, EntityId = e.Id.ToString()
                }).ToList();
                var json = await client.GetByCustomUrlAsync($"{client.EntityPluralized}/EntityIdentifiers", client.HttpClient.PostAsync, entityIdentifiers);

                var extensionEntities = JsonConvert.DeserializeObject <OdataObjectCollection>(json);
                var sortDetails       = new SortDetails(entity, extensionEntity, RelatedEntity.Type.OneToMany)
                {
                    EntityToRelatedEntityProperty = "EntityId"
                };
                RelatedEntityCollection collection = extensionEntities;
                var collections = Sorter.Sort(entities, collection, sortDetails);
                if (collections != null && collections.Any())
                {
                    list.AddRange(collections);
                }
            }
            return(list);
        }
示例#5
0
        public void GetRelatedEntity_NotGeneric_RelatedEntitiesDifferentEntity_Test()
        {
            // Arrange
            var odataUser = new OdataObject <User, int>();
            var re1       = new RelatedEntity {
                Id = "7"
            };
            var person1 = new Person {
                Id = 7, FirstName = "Jared"
            };
            var json1 = JsonConvert.SerializeObject(person1);

            re1.Object = new JRaw(json1);

            var rec = new RelatedEntityCollection {
                re1
            };

            rec.RelatedEntity = "Person";
            odataUser.RelatedEntityCollection.Add(rec);

            // Act
            var odataPersonCollection = odataUser.GetRelatedEntityCollection(nameof(Smile));

            // Assert
            Assert.IsNull(odataPersonCollection);
        }
示例#6
0
        public void ShouldSerializePopulatedRelatedEntityCollection()
        {
            // Arrange
            var relatedEntityCollection = new RelatedEntityCollection {
                Entity = "Addendum", EntityId = "10", RelatedEntity = "Fake"
            };
            var json1          = "{ \"Id\" : \"1\" }";
            var jObject1       = JObject.Parse(json1);
            var json2          = "{ \"Id\" : \"2\" }";
            var jObject2       = JObject.Parse(json1);
            var relatedEntity1 = new RelatedEntity {
                Id = jObject1.GetValue("Id").ToString(), Object = new JRaw(json1)
            };
            var relatedEntity2 = new RelatedEntity {
                Id = jObject2.GetValue("Id").ToString(), Object = new JRaw(json2)
            };

            relatedEntityCollection.Add(relatedEntity1);
            relatedEntityCollection.Add(relatedEntity2);
            var odata = new OdataObject <Addendum, long>()
            {
                Object = new Addendum {
                    Id = 10, Property = "A", Value = "B"
                }
            };

            odata.RelatedEntityCollection.Add(relatedEntityCollection);

            // Act & Assert
            Assert.IsTrue(ExcludeEmptyEnumerablesContractResolver.Instance.ShouldSerialize(odata, new JsonProperty {
                PropertyName = "RelatedEntityCollection", UnderlyingName = "RelatedEntityCollection"
            }));
        }
        public void SetValue(object target, object value)
        {
            RelatedEntityCollection attributeCollection = (RelatedEntityCollection)target;
            IEnumerable <KeyValuePair <Relationship, EntityCollection> > values = (IEnumerable <KeyValuePair <Relationship, EntityCollection> >)value;

            foreach (var item in values)
            {
                attributeCollection.Add(item);
            }
        }
示例#8
0
        public void ImplicitConversionNullTest()
        {
            // Arrange
            OdataObjectCollection obj = null;

            // Act
            RelatedEntityCollection c = obj;

            // Assert
            Assert.IsNull(c);
        }
示例#9
0
        public void ParentIsSetAfterDeserializationAndCast()
        {
            // Arrange
            var json = "{\"Count\":1,\"Entities\":[{\"Id\":1,\"Object\":{\"Id\":1,\"UserId\":7247,\"UserRoleId\":1},\"RelatedEntityCollection\":[{\"Count\":1,\"RelatedEntity\":\"UserRole\",\"RelatedEntities\":[{\"Id\":\"1\",\"Object\":{\"Id\":1,\"Name\":\"Admin\",\"CreateDate\":\"2017-12-04T03:39:26.683\",\"CreatedBy\":2,\"Description\":\"A role to indicate that the user is an administrator\",\"Enabled\":true,\"LastUpdated\":null,\"LastUpdatedBy\":null},\"Uri\":\"http://localhost:3896/UserRoleService.svc/UserRoles/Ids(1)\"}]}]}],\"Entity\":\"UserRoleMembership\"}";
            var ooc  = JsonConvert.DeserializeObject <OdataObjectCollection>(json);

            // Act
            RelatedEntityCollection rec = ooc;

            // Assert
            Assert.AreEqual(rec, rec.RelatedEntities.Parent);
            Assert.AreEqual(rec, rec[0].Parent);
        }
示例#10
0
        public void ImplicitConversionDefaultNewTest()
        {
            // Arrange
            var obj = new OdataObjectCollection();

            // Act
            RelatedEntityCollection c = obj;

            // Assert
            Assert.IsNotNull(c);
            Assert.IsNull(c.Entity);
            Assert.AreEqual(0, c.Count);
        }
示例#11
0
        /// <summary>
        /// GetAssociatedEntityItems method is to get related entity details
        /// </summary>
        /// <param name="primaryEntityName"></param>
        /// <param name="_primaryEntityId"></param>
        /// <param name="relatedEntityName"></param>
        /// <param name="relationshipName"></param>
        /// <param name="serviceProxy"></param>
        /// <returns></returns>
        private EntityCollection GetAssociatedEntityItems(string primaryEntityName, Guid _primaryEntityId, string relatedEntityName, string relationshipName, IOrganizationService serviceProxy)
        {
            try
            {
                tracingService.Trace("Entering into InvokeWorkflows method....");
                EntityCollection result             = null;
                QueryExpression  relatedEntityQuery = new QueryExpression();
                relatedEntityQuery.EntityName = relatedEntityName;
                relatedEntityQuery.ColumnSet  = new ColumnSet(false);

                Relationship relationship = new Relationship();
                relationship.SchemaName = relationshipName;
                //relationship.PrimaryEntityRole = EntityRole.Referencing;
                RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();
                relatedEntity.Add(relationship, relatedEntityQuery);

                RetrieveRequest request = new RetrieveRequest();
                request.RelatedEntitiesQuery = relatedEntity;
                request.ColumnSet            = new ColumnSet(true);
                request.Target = new EntityReference
                {
                    Id          = _primaryEntityId,
                    LogicalName = primaryEntityName
                };

                RetrieveResponse        response = (RetrieveResponse)serviceProxy.Execute(request);
                RelatedEntityCollection relatedEntityCollection = response.Entity.RelatedEntities;

                tracingService.Trace("After get the RelatedEntityCollection");
                if (relatedEntityCollection != null)
                {
                    tracingService.Trace("RelatedEntityCollection Count: {0}, RelatedEntityCollection.Values.Count:{1}", relatedEntityCollection.Count, relatedEntityCollection.Values.Count);
                    if (relatedEntityCollection.Count > 0 && relatedEntityCollection.Values.Count > 0)
                    {
                        result = (EntityCollection)relatedEntityCollection.Values.ElementAt(0);
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
示例#12
0
        public void GetRelatedEntity_NotGeneric_Test()
        {
            // Arrange
            var odataUser = new OdataObject <User, int>();
            var re1       = new RelatedEntity {
                Id = "7"
            };
            var smile1 = new Smile {
                Id = 7, SmileType = "Wide"
            };
            var json1 = JsonConvert.SerializeObject(smile1);

            re1.Object = new JRaw(json1);

            var re2 = new RelatedEntity {
                Id = "8"
            };
            var smile2 = new Smile {
                Id = 8, SmileType = "Flat"
            };
            var json2 = JsonConvert.SerializeObject(smile2);

            re2.Object = new JRaw(json2);
            var rec = new RelatedEntityCollection {
                re1, re2
            };

            rec.RelatedEntity = "Smile";
            odataUser.RelatedEntityCollection.Add(rec);

            // Act
            var odataSmileCollection = odataUser.GetRelatedEntityCollection(nameof(Smile));

            // Assert
            Assert.AreEqual(2, odataSmileCollection.Count);
            Assert.AreEqual("7", odataSmileCollection[0].Id);
            var jObj0 = JObject.Parse(odataSmileCollection[0].Object.ToString());

            Assert.AreEqual("Wide", jObj0["Type"]);
            Assert.AreEqual("8", odataSmileCollection[1].Id);
            var jObj1 = JObject.Parse(odataSmileCollection[1].Object.ToString());

            Assert.AreEqual("Flat", jObj1["Type"]);
        }
示例#13
0
        public void GetRelatedEntity_Generic_Test()
        {
            // Arrange
            var odataUser = new OdataObject <User, int>();
            var re1       = new RelatedEntity {
                Id = "7"
            };
            var smile1 = new Smile {
                Id = 7, SmileType = "Wide"
            };
            var json1 = JsonConvert.SerializeObject(smile1);

            re1.Object = new JRaw(json1);

            var re2 = new RelatedEntity {
                Id = "8"
            };
            var smile2 = new Smile {
                Id = 8, SmileType = "Flat"
            };
            var json2 = JsonConvert.SerializeObject(smile2);

            re2.Object = new JRaw(json2);
            var rec = new RelatedEntityCollection {
                re1, re2
            };

            rec.RelatedEntity = "Smile";
            odataUser.RelatedEntityCollection.Add(rec);

            // Act
            var odataSmileCollection = odataUser.GetRelatedEntityCollection <Smile, int>();

            // Assert
            Assert.AreEqual(2, odataSmileCollection.Count);
            Assert.AreEqual(7, odataSmileCollection[0].Id);
            Assert.AreEqual("Wide", odataSmileCollection[0].Object.SmileType);
            Assert.AreEqual(8, odataSmileCollection[1].Id);
            Assert.AreEqual("Flat", odataSmileCollection[1].Object.SmileType);
        }
        internal async Task <List <RelatedEntityCollection> > GetRelatedEntitiesAsync(IEnumerable <TInterface> entities, IEnumerable <RelatedEntityAttribute> attributes, IEnumerable <ExpandPath> expandPaths)
        {
            if (entities == null || !entities.Any())
            {
                return(null);
            }
            var list = new List <RelatedEntityCollection>();

            foreach (RelatedEntityAttribute a in attributes)
            {
                var expandPath = expandPaths.FirstOrDefault(ep => a.RelatedEntity == ep.Entity);
                RelatedEntityCollection relatedEntities = await GetRelatedEntities(entities, a.RelatedEntity, a.Property, expandPath?.Parenthesis); // Cast is intentional

                var sortDetails = new SortDetails(typeof(TEntity).Name, a.RelatedEntity, RelatedEntity.Type.ManyToOne)
                {
                    EntityToRelatedEntityProperty = a.Property
                };
                var collections = Sorter.Sort(entities, relatedEntities, sortDetails);
                list.AddRange(collections);
            }
            return(list);
        }
示例#15
0
        public void CollatePropertyOtherThanIdTest()
        {
            // Arrange
            var user1 = new User2 {
                Id = 1, Name = "User1", UserTypeName = "Example Users1"
            }.AsOdata <User2, int>();
            var user2 = new User2 {
                Id = 2, Name = "User2", UserTypeName = "Example Users1"
            }.AsOdata <User2, int>();
            var user3 = new User2 {
                Id = 3, Name = "User3", UserTypeName = "Example Users2"
            }.AsOdata <User2, int>();
            var entities = new List <OdataObject <User2, int> > {
                user1, user2, user3
            };

            var userType1 = new UserType {
                Id = 3, Name = "Example Users1"
            };
            var userType2 = new UserType {
                Id = 4, Name = "Example Users2"
            };
            var userType1Json = new JRaw(JsonConvert.SerializeObject(userType1.AsOdata <UserType, int>()));
            var userType2Json = new JRaw(JsonConvert.SerializeObject(userType2.AsOdata <UserType, int>()));

            var relatedEntity1 = new RelatedEntity {
                Object = userType1Json, Id = userType1.Name, IdProperty = "Name"
            };
            var relatedEntity2 = new RelatedEntity {
                Object = userType1Json, Id = userType1.Name, IdProperty = "Name"
            };
            var relatedEntity3 = new RelatedEntity {
                Object = userType2Json, Id = userType2.Name, IdProperty = "Name"
            };

            var collection1 = new RelatedEntityCollection {
                Entity = "User", EntityId = "1", RelatedEntity = "UserType"
            };

            collection1.RelatedEntities.Add(relatedEntity1);

            var collection2 = new RelatedEntityCollection {
                Entity = "User", EntityId = "2", RelatedEntity = "UserType"
            };

            collection2.RelatedEntities.Add(relatedEntity2);

            var collection3 = new RelatedEntityCollection {
                Entity = "User", EntityId = "3", RelatedEntity = "UserType"
            };

            collection3.RelatedEntities.Add(relatedEntity3);

            var collections = new List <RelatedEntityCollection> {
                collection1, collection2, collection3
            };

            var sorter = new RelatedEntitySorter <User2, int>();

            // Act
            sorter.Collate(entities, collections);

            // Assert
            Assert.AreEqual(1, user1.RelatedEntityCollection.Count);
            Assert.AreEqual(user1.RelatedEntityCollection[0], collection1);

            Assert.AreEqual(1, user2.RelatedEntityCollection.Count);
            Assert.AreEqual(user2.RelatedEntityCollection[0], collection2);

            Assert.AreEqual(1, user3.RelatedEntityCollection.Count);
            Assert.AreEqual(user3.RelatedEntityCollection[0], collection3);
        }
示例#16
0
 private IEnumerable <string> GetDependencies(RelatedEntityCollection relationships)
 {
     return(relationships.SelectMany(r => GetDependencies(r.Value)));
 }
示例#17
0
        /// <summary>
        /// Handle general related entity collection construction
        /// </summary>
        /// <param name="rootExpando">Object being added too</param>
        /// <param name="entityName">parent entity</param>
        /// <param name="entityCollection">collection of relationships</param>
        /// <param name="mUtil">meta-data utility</param>
        /// <returns></returns>
        internal static ExpandoObject ReleatedEntitiesToExpandoObject(ExpandoObject rootExpando, string entityName, RelatedEntityCollection entityCollection, MetadataUtility mUtil)
        {
            if (rootExpando == null)
            {
                return(rootExpando);
            }

            if (entityCollection != null && entityCollection.Count == 0)
            {
                // nothing to do, just return.
                return(rootExpando);
            }

            foreach (var entItem in entityCollection)
            {
                string        key             = "";
                bool          isArrayRequired = false;
                dynamic       expando         = new ExpandoObject();
                var           expandoObject   = (IDictionary <string, object>)expando;
                ExpandoObject childEntities   = new ExpandoObject();

                List <ExpandoObject> childCollection = new List <ExpandoObject>();

                // Get the Entity relationship key and entity and reverse it back to the entity key name
                var eData = mUtil.GetEntityMetadata(Xrm.Sdk.Metadata.EntityFilters.Relationships, entItem.Value.Entities[0].LogicalName);

                // Find the relationship that is referenced.
                var ERM21 = eData.ManyToOneRelationships.FirstOrDefault(w1 => w1.SchemaName.ToLower().Equals(entItem.Key.SchemaName.ToLower()));
                var ERM2M = eData.ManyToManyRelationships.FirstOrDefault(w2 => w2.SchemaName.ToLower().Equals(entItem.Key.SchemaName.ToLower()));
                var ER12M = eData.OneToManyRelationships.FirstOrDefault(w3 => w3.SchemaName.ToLower().Equals(entItem.Key.SchemaName.ToLower()));

                // Determine which one hit
                if (ERM21 != null)
                {
                    isArrayRequired = true;
                    key             = ERM21.ReferencedEntityNavigationPropertyName;
                }
                else if (ERM2M != null)
                {
                    isArrayRequired = true;
                    if (ERM2M.Entity1LogicalName.ToLower().Equals(entityName))
                    {
                        key = ERM2M.Entity1NavigationPropertyName;
                    }
                    else
                    {
                        key = ERM2M.Entity2NavigationPropertyName;
                    }
                }
                else if (ER12M != null)
                {
                    key = ER12M.ReferencingAttribute;
                }

                if (string.IsNullOrEmpty(key)) // Failed to find key
                {
                    throw new DataverseOperationException($"Relationship key {entItem.Key.SchemaName} cannot be found for related entities of {entityName}.");
                }

                foreach (var ent in entItem.Value.Entities)
                {
                    // Check to see if the entity itself has related entities
                    if (ent.RelatedEntities != null && ent.RelatedEntities.Count > 0)
                    {
                        childEntities = ReleatedEntitiesToExpandoObject(childEntities, entityName, ent.RelatedEntities, mUtil);
                    }

                    // generate object.
                    ExpandoObject ent1 = ToExpandoObject(ent, mUtil);

                    if (((IDictionary <string, object>)childEntities).Count() > 0)
                    {
                        foreach (var item in (IDictionary <string, object>)childEntities)
                        {
                            ((IDictionary <string, object>)ent1).Add(item.Key, item.Value);
                        }
                    }
                    childCollection?.Add((ExpandoObject)ent1);
                }
                if (childCollection.Count == 1 && isArrayRequired == false)
                {
                    ((IDictionary <string, object>)rootExpando).Add(key, childCollection[0]);
                }
                else
                {
                    ((IDictionary <string, object>)rootExpando).Add(key, childCollection);
                }
            }
            return(rootExpando);
        }
 /// <summary>The get dependencies.</summary>
 /// <param name="relationships">The relationships.</param>
 /// <param name="isSingle">The is single.</param>
 /// <returns>The dependencies.</returns>
 private IEnumerable <string> GetDependencies(RelatedEntityCollection relationships, bool isSingle)
 {
     return(relationships.SelectMany(e => this.GetDependencies(e, isSingle)));
 }
        public object GetValue(object target)
        {
            RelatedEntityCollection value = (RelatedEntityCollection)target;

            return(value);
        }
示例#20
0
 private static IEnumerable <XElement> GetContentValues(RelatedEntityCollection relationships, IEnumerable <Entity> path)
 {
     return(relationships.OrderBy(r => r.Key.SchemaName).Select(r => new XElement("relationship", new XAttribute("name", r.Key.SchemaName), GetContentValue(r.Value, path))));
 }