/// <summary>
        /// Compare the entites and return the minimum set of changes that need to be made inorder to make the base entity
        /// the same as the updated entity
        /// </summary>
        /// <param name="baseEntity"></param>
        /// <param name="updatedEntity"></param>
        public static Entity Delta(this Entity baseEntity, Entity updatedEntity)
        {
            //Clone the attribute
            Entity clone = updatedEntity.Clone();

            //Create a delta (do not update fields that have not changed)
            foreach (var att in baseEntity.Attributes)
            {
                //Remove unchanged fields from the delta
                if (clone.Attributes.Contains(att.Key))
                {
                    //TODO: Clean up Attribute comparisons
                    var updatedAttribute = updatedEntity.Attributes.Where(a => a.Key == att.Key).First();
                    if (JsonAttribute.Create(att).Equals(JsonAttribute.Create(updatedAttribute)))
                    {
                        clone.Attributes.Remove(att.Key);
                    }
                }
            }

            List <String> attributesToRemove = new List <string>();

            foreach (var att in updatedEntity.Attributes)
            {
                //Do not set fields to NULL that are already not present
                if (!baseEntity.Attributes.Contains(att.Key) && att.Value == null)
                {
                    clone.Attributes.Remove(att.Key);
                }
            }

            clone.Id = updatedEntity.Id;
            return(clone);
        }
Example #2
0
        /// <summary>
        /// Customized Write to include type information and omit redundant information
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="serializer"></param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            Entity entity = (Entity)value;

            writer.WriteStartObject();
            writer.WritePropertyName(nameof(entity.LogicalName));
            writer.WriteValue(entity.LogicalName);
            writer.WritePropertyName(nameof(entity.Id));
            writer.WriteValue(entity.Id);

            writer.WritePropertyName(nameof(entity.Attributes));
            writer.WriteStartArray();

            foreach (var item in entity.Attributes)
            {
                serializer.Serialize(writer, JsonAttribute.Create(item));
            }
            writer.WriteEndArray();
            writer.WriteEndObject();
        }