I am trying to restore a specific version for some given records.
Audit is turned on the entities in question. My program needs to select a certain version from a crm record and reverse all the properties and changes done so the older version of the record gets restored.
This is basically to reverse some changes that happened by accident on a productive system. I am using Xrm to access the server.
Also I tried finding some related functions on the Xrm object or the xrm dataset, but can't find any.
So far I found this way of getting the version history of a given record:
var xrm = new XrmServiceContext(CrmHelper.GetCrmConnection(ConfigurationManager.ConnectionStrings["Xrm"] + "SG"));
var changeRequest = new RetrieveRecordChangeHistoryRequest();
changeRequest.Target = new EntityReference("account", new Guid("{D4E0990C-41C8-E211-B824-005056997F7A}"));
var changeResponse = (RetrieveRecordChangeHistoryResponse)xrm.Execute(changeRequest);
var details = changeResponse.AuditDetailCollection;
for (int i = 0; i < details.Count; i++)
{
if (typeof (AttributeAuditDetail).Name == details[i].GetType().Name)
{
AttributeAuditDetail detail = details[i] as AttributeAuditDetail;
Entity entity = detail.OldValue;
}
}
However, how can I revert the changes back to the detail.OldValue
?
Do I have to make a foreach loop over every attribute and set the record's attribute to the ones from the old one?
Your only option is to reconstruct the original state of your records by traversing the audit history stored in the AuditDetailCollection
all the way to the point in time where the accidental modifications occurred.
Be aware this can be tricky. E.g. you may run into referential integrity issues. Also custom business logic (plugins, business rules) may block intended updates or have undesired side effects (workflows).
Luckily your corrective update will be recorded in the Audit table, so you will be able to correct that too. :-)