Introduction
In Part 1, I talked about creating audit trail objects using the object state entries. As I said earlier, in the second part I will talk about roll back feature of this audit trail. In the first part, I already described that to get the Rollback feature from that audit trail, we have to consider some issues. We have to maintain the order of entity graph while inserting and deleting. That means the root entity has been inserted before the children and during deletion, we have to reverse it. The most important issue is that we have to make sure that each audit trail entry has been inserted according to this order. So during insertion of object, we also need to consider these things:
- Maintain insertion date-time to sort the audit trial
- Store the old data and new data
- Store the state of the data as audit action
If user chooses a certain time to roll back, we have to start with last audits and do the roll back action for each audit till a certain time. So now the question is what the roll back action will be. You can guess that it’s depending on the Audit action of each entity. During rollback:
- Inserted data will be deleted.
- Deleted data will be inserted.
- Modified data will be replaced by the old one.
If we see the conceptual model, our Entity set for Audit was:
Here “RevisionStamp
” holds the audit insertion date-time, Actions hold the audit action of the entity object (Insert/deleted/modified). Other properties describe themselves with their names.
So here “Deleted
” and “Modified
” objects will be rolled back with “Old data” property. And Inserted
data will be rolled back with “New data” property.
Using the Code
So first, I am going to retrieve all the audits that happen after a specific date-time. This specific date-time is taken from the user. What we have to do is, rollback action for each audit till a specific date and we have to start with the last one (bottom to top). That is why we are going to sort the audit with “RevisionStamp
” in a descending order and start doing rollback.
public static bool RollBack(DateTime rollBackDate, string userName)
{
using (TransactionScope transactionScope =
new TransactionScope(System.Transactions.TransactionScopeOption.Required,
TimeSpan.FromMinutes(30)))
{
AdventureWorksEntities context =new AdventureWorksEntities();
try
{
if (context.Connection.State != ConnectionState.Open)
{
context.Connection.Open();
}
IEnumerable<DBAudit> auditsToRollBack = DataAdapter.GetEntity
<DBAudit>(context, a => a.RevisionStamp >= rollBackDate );
if (null != auditsToRollBack && auditsToRollBack.Count() > 0)
{
IEnumerable<DBAudit> orderedAudits =
auditsToRollBack.OrderByDescending(a => a.RevisionStamp);
foreach (var audit in orderedAudits)
{
AuditTrailHelper.DoRollBackAction(ref context, audit, userName);
}
int i =context.SaveChanges();
if (i > 0)
{
transactionScope.Complete();
return true;
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
context.Dispose();
}
}
return false;
}
In DoRollBackAction
as I said before, “Deleted
” and “Modified
” objects will be rolled back with “Old data” property. And Inserted
data will be rolled back with “New data” property.
As I stored old data and new data with XML Serialization while creating the Audit
object, I have to deserialise that data into “EntityObject
” and do the reverse action according to the audit action.
private static void DoRollBackAction
(ref AdventureWorksEntities context, DBAudit auditInfo, string userName)
{
if (auditInfo.Actions == AuditTrailHelper.AuditActions.U.ToString() ||
auditInfo.Actions == AuditTrailHelper.AuditActions.D.ToString())
{
object oldData = AuditTrailHelper.GetAuditObjectFromXML
(auditInfo.OldData, auditInfo.TableName);
if (oldData is EntityObject)
{
EntityObject oldEntity = (EntityObject)oldData;
oldEntity.EntityKey = null;
DataAdapter.EditEntity(ref context, oldEntity);
}
}
else if (auditInfo.Actions == AuditTrailHelper.AuditActions.I.ToString())
{
object newData = AuditTrailHelper.GetAuditObjectFromXML
(auditInfo.NewData, auditInfo.TableName);
if (newData is EntityObject)
{
EntityObject newEntity = (EntityObject)newData;
newEntity.EntityKey = null;
EntityKey key = context.CreateEntityKey
(newEntity.GetType().Name, newEntity);
object objToRemoved = null;
if (context.TryGetObjectByKey(key, out objToRemoved))
{
context.DeleteObject(objToRemoved);
}
}
}
context.DeleteObject(auditInfo);
}
}
After serializing the entity Object, we get the XML string like this:
<SalesOrderDetail xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<EntityKey>
<EntitySetName>SalesOrderDetail</EntitySetName>
<EntityContainerName>AdventureWorksEntities</EntityContainerName>
</EntityKey>
<SalesOrderID>1</SalesOrderID>
<SalesOrderDetailID>0</SalesOrderDetailID>
<OrderQty>1</OrderQty>
<UnitPrice>1898.0944</UnitPrice>
<UnitPriceDiscount>0</UnitPriceDiscount>
<LineTotal>0</LineTotal>
<rowguid>6bfaa372-292a-4fd6-84d3-c4e900f09589</rowguid>
<ModifiedDate>2009-03-26T16:16:41.9691358+06:00</ModifiedDate>
<SalesOrderHeaderReference />
<SpecialOfferProductReference>
<EntityKey>
<EntitySetName>SpecialOfferProduct</EntitySetName>
<EntityContainerName>AdventureWorksEntities</EntityContainerName>
<EntityKeyValues>
<EntityKeyMember>
<Key>SpecialOfferID</Key>
<Value xsi:type="xsd:int">1</Value>
</EntityKeyMember>
<EntityKeyMember>
<Key>ProductID</Key>
<Value xsi:type="xsd:int">777</Value>
</EntityKeyMember>
</EntityKeyValues>
</EntityKey>
</SpecialOfferProductReference>
</SalesOrderDetail>
I have to deserialize this XML string. During deserializing, I have created an XML document and an XML reader using that document. Using that reader, I deserialized the entity object. The method to deserialize the entityobject
is:
public static object GetAuditObjectFromXML(string ObjectInXML, string typeName)
{
XDocument doc = XDocument.Parse(ObjectInXML);
XmlReader reader = doc.CreateReader();
Type entityType = Assembly.GetExecutingAssembly().GetType
("ImplAuditTrailUsingEF." + typeName);
XmlSerializer ser = new XmlSerializer(entityType);
return ser.Deserialize(reader);
}
For inserting deleted object or to change back modified object, I wrote a single method to edit the object:
EditEntity(ref AdventureWorksEntities context, EntityObject entity)
Is this method, I change the existence object and attach it to the container otherwise I have inserted the entityObject
into the context. To save all of this change, we need an entry in Object state cache.
public static void EditEntity
(ref AdventureWorksEntities context, EntityObject entity)
{
EntityKey key;
object originalItem;
if (entity.EntityKey == null)
{
key = context.CreateEntityKey(entity.GetType().Name, entity);
}
else
{
key = entity.EntityKey;
}
try
{
if (context.TryGetObjectByKey(key, out originalItem))
{
context.ApplyPropertyChanges(
key.EntitySetName, entity);
}
else
{
context.AddObject(entity.GetType().Name, entity);
}
}
catch (System.Data.MissingPrimaryKeyException ex)
{
throw ex;
}
catch (System.Data.MappingException ex)
{
throw ex;
}
catch (System.Data.DataException ex)
{
throw ex;
}
}
}
That is all for implementing rollback mechanism in our audit trail. Now all we have to do is just call the “RollBack
” method and give it a specific date to roll back.
private void btnRollBack_Click(object sender, RoutedEventArgs e)
{
if (AuditTrailHelper.RollBack(dtpRollBackDate.SelectedDate.Value, "Admin"))
{
MessageBox.Show("Successfully Roll Backed!!");
}
}
That’s all for implementation of Audit trial with entity framework. Here I have deleted the audits which have been rolled back. Definitely each rollback operation is also a DB operation and I did an audit for each rollback operation.
Is the sample project, I have used the free version of Xeed. You may need to download that Library, otherwise you can replace it with the WPF toolkit. It has just been used for getting a date-time from user to rollback.
History
- 1st April, 2009: Initial post