Keeping your Dynamics365 Audit Logs Tidy

Audits are a great way to see what has happened on records, what they did and more importantly who did it.

But if you have automated processes running that are pumping data into Dynamics because a field or two has changed, you might end up with an Audit History looking something like this.

In this case, an update was triggered, but it wasn’t until the fourth update that there was an actual difference in the data being changed.  Even then, when we sent the whole packet of data, we sent it all.

With only four feels you can already see this gets a little painful to follow.

Capture.PNG

To get around this problem, you need to get a Pre-Image of the data before you modify it (in a plugin context you might already have this, but if you’re outside the execution context you won’t).

Very simply, this can be accomplished using the following code.

private static Entity ValidateFieldsToSend(Entity PostImage, Guid Id, IOrganizationService service)
{
Entity PreImage = service.Retrieve(PostImage.LogicalName, Id, new ColumnSet(true));

foreach (KeyValuePair<string, object> attribute in PreImage.Attributes)
{
if (PostImage.Contains(attribute.Key) && !attribute.Key.Contains("id"))
{
if (PostImage[attribute.Key].ToString() == PreImage[attribute.Key].ToString())
{
//They are the same, clear them out.
PostImage.Attributes.Remove(attribute);
}
}
}

return PostImage;
}

Important to note – when we process the Update we have added the “id” field (Dynamics Guid) to the entity object.  In this case, you cannot remove the “id” field from the new PostImage object (otherwise it will not know what to update).

When our code is re-run again using the ValidateFieldsToSend your results in the audit history will only show those fields that have actually changed (in this case a Lead).

Capture222

Granted there is a performance hit on doing these checks and if I was doing this against a mass migration operation, I would figure out a better way to cache, lock, re-apply but if you’re looking for a simply solution to keep your logs clean when synchronizing your data, this will get you over that hurdle.

Post A Reply

%d bloggers like this: