using System; using System.Collections.Generic; using System.Linq; namespace Salesforce.NET { /// /// Allows for an object to track changes made /// /// public class Trackable { private readonly Type type; private T value; private IDictionary modified; private readonly IDictionary originalPropertyValues = new Dictionary(); private readonly IDictionary latestPropertyValues = new Dictionary(); public Trackable(T value) { this.value = value; type = value.GetType(); SetPropertyValues(originalPropertyValues); } public T Value { get => value; protected set => this.value = value; } /// /// Gets a dictionary of modified fields since the object was created /// public IDictionary Modified { get { SetPropertyValues(latestPropertyValues); return originalPropertyValues .Join(latestPropertyValues, o => o.Key, l => l.Key, (o, l) => new { Original = o, Latest = l }) .Where(p => !object.Equals(p.Original.Value, p.Latest.Value)) .Select(p => p.Latest) .ToDictionary(t => t.Key, t => t.Value); } protected set => modified = value; } private void SetPropertyValues(IDictionary propertyValues) { type .GetProperties() .ToList() .ForEach(p => propertyValues[p.Name] = p.GetValue(value)?.ToString()); } } public static class Trackable { /// /// Allows an object to track changes for the Salesforce API update /// /// /// /// public static Trackable AsTrackable(this T value) { return new Trackable(value); } } }