C# ChangeBuilder

Date: 2021-11-23

Detect and visualize property value changes

public class ChangeBuilder
{
    public class CompareProp
    {
        public CompareProp(string description, string left, string right)
        {
            Description = description;
            Left = left;
            Right = right;
        }
        public string Description { get; set; }
        public string Left { get; set; }
        public string Right { get; set; }
    }

    private readonly List<CompareProp> compareProps = new List<CompareProp>();
    public ChangeBuilder Add(string description, string left, string right)
    {
        compareProps.Add(new CompareProp(description, left, right));
        return this;
    }
    public IEnumerable<CompareProp> GetChanges() => compareProps.Where(x => !StringHelper.StrEquals(x.Left, x.Right)).ToList();
}

// Use:

private static void LogChanges(string message, IEnumerable<ChangeBuilder.CompareProp> changes)
{
    var changesDescription = string.Join(Environment.NewLine, changes.Select(x => $"{x.Description}: '{x.Left}' => '{x.Right}'"));
    _ = DomainPorts.LogMessageStore.Info($"{message}{Environment.NewLine}{changesDescription}");
}

var registrationChanges = new ChangeBuilder()
    .Add("FreightRegistrationId", existingOrder.FreightRegistrationId, registration.Id.ToString())
    .Add("DeliveryDate", existingOrder.DeliveryDate?.ToString("yyyy-MM-dd"), registration.FreightRegistrationTimeSlot.Date.ToString("yyyy-MM-dd"))
    .Add("MiddleOfTimeSlotString", existingOrder.MiddleOfTimeSlotString, registration.FreightRegistrationTimeSlot?.MiddleOfTimeSlot.ToAs400Time())
    .Add("LicensePlateName", existingOrder.LicensePlateName, registration.LicensePlate?.Name ?? string.Empty)
    .Add("LicensePlateNumber", existingOrder.LicensePlateNumber, registration.LicensePlate?.LicensePlateNumber)
    .Add("SaveLicensePlate", existingOrder.SaveLicensePlate, registration.LicensePlate?.SaveAsNewLicensePlate.ToAs400String())
    .GetChanges();

if (registrationChanges.Any()) {
    LogChanges($"{transportOrder.OrderNumber}: Has registration changes:", registrationChanges);
}
57220cookie-checkC# ChangeBuilder