82 lines
2.3 KiB
C#
82 lines
2.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
|
|
namespace Salesforce.NET
|
|
{
|
|
/// <summary>
|
|
/// Allows for an object to track changes made
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
public class Trackable<T>
|
|
{
|
|
private readonly Type type;
|
|
|
|
private T value;
|
|
private IDictionary<string, string> modified;
|
|
|
|
private readonly IDictionary<string, string> originalPropertyValues = new Dictionary<string, string>();
|
|
private readonly IDictionary<string, string> latestPropertyValues = new Dictionary<string, string>();
|
|
|
|
public Trackable(T value)
|
|
{
|
|
this.value = value;
|
|
|
|
type = value.GetType();
|
|
|
|
SetPropertyValues(originalPropertyValues);
|
|
}
|
|
|
|
public T Value
|
|
{
|
|
get => value;
|
|
protected set => this.value = value;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets a dictionary of modified fields since the <see cref="Trackable{T}"/> object was created
|
|
/// </summary>
|
|
public IDictionary<string, string> 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<string, string> propertyValues)
|
|
{
|
|
type
|
|
.GetProperties()
|
|
.ToList()
|
|
.ForEach(p => propertyValues[p.Name] = p.GetValue(value)?.ToString());
|
|
}
|
|
}
|
|
|
|
public static class Trackable
|
|
{
|
|
/// <summary>
|
|
/// Allows an object to track changes for the Salesforce API update
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
/// <param name="value"></param>
|
|
/// <returns></returns>
|
|
public static Trackable<T> AsTrackable<T>(this T value)
|
|
{
|
|
return new Trackable<T>(value);
|
|
}
|
|
}
|
|
}
|