Click here to Skip to main content
Click here to Skip to main content
Go to top

Implementing Audit Trail using Entity Framework - Part 2

, 1 Apr 2009
Rate this:
Please Sign up or sign in to vote.
Implementing Audit Trail using Entity Framework's caching entries

Click to enlarge image

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: 

  1. Maintain insertion date-time to sort the audit trial
  2. Store the old data and new data
  3. 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:

  1. Inserted data will be deleted.
  2. Deleted data will be inserted.
  3. 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

UserDateInput.JPG

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)
            {//Open the connection
                context.Connection.Open();
            }//end if 
            //find all audits to roll back
            IEnumerable<DBAudit> auditsToRollBack = DataAdapter.GetEntity
			<DBAudit>(context, a => a.RevisionStamp >= rollBackDate );
             if (null != auditsToRollBack && auditsToRollBack.Count() > 0)
            {//if any data found to roll back
                //Order by the audits by creation datetime
                IEnumerable<DBAudit> orderedAudits = 
		auditsToRollBack.OrderByDescending(a => a.RevisionStamp);
                 foreach (var audit in orderedAudits)
                {//iterate each audit 
                    AuditTrailHelper.DoRollBackAction(ref context, audit, userName);
                }//end foreach
                int i =context.SaveChanges();
                if (i > 0)
                {
                    transactionScope.Complete();
                    return true;
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            // Explicitly dispose of the context, 
            // which closes the connection. 
            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())
            {//For action of Update and Delete
                //Deserialized old data from the XML
                object oldData = AuditTrailHelper.GetAuditObjectFromXML
				(auditInfo.OldData, auditInfo.TableName);

                if (oldData is EntityObject)
                {
                    EntityObject oldEntity = (EntityObject)oldData;
                    oldEntity.EntityKey = null;
                    //add in case of delete or edit the current one with old data 
                    DataAdapter.EditEntity(ref context, oldEntity);
                }
            }
            else if (auditInfo.Actions == AuditTrailHelper.AuditActions.I.ToString())
            {//For Insert Action
                object newData = AuditTrailHelper.GetAuditObjectFromXML
				(auditInfo.NewData, auditInfo.TableName);

                if (newData is EntityObject)
                {
                    //Otherwise, delete the entity that has been inserted before
                    EntityObject newEntity = (EntityObject)newData;
                    newEntity.EntityKey = null;
                    EntityKey key = context.CreateEntityKey
				(newEntity.GetType().Name, newEntity);

                    object objToRemoved = null;
                    if (context.TryGetObjectByKey(key, out objToRemoved))
                    {//delete the entity
                        context.DeleteObject(objToRemoved);
                    }//end if 
                }
            }
            //delete the audit
            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);
    //Assuming doc is an XML document containing a 
    //serialized object and objType is a System.Type set to the type of the object.
    XmlReader reader = doc.CreateReader();
    //get the Type of entity object  
    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)
    {
        // Define an ObjectStateEntry and EntityKey for the current object.
        EntityKey key;
        object originalItem;
        // Get the detached object's entity key.
        if (entity.EntityKey == null)
        {
            // Get the entity key of the updated object.
            key = context.CreateEntityKey(entity.GetType().Name, entity);
        }
        else
        {
            key = entity.EntityKey;
        }
        try
        {
            // Get the original item based on the entity key from the context
            // or from the database.
            if (context.TryGetObjectByKey(key, out originalItem))
            {//accept the changed property
                 // Call the ApplyPropertyChanges method to apply changes
                // from the updated item to the original version.
                context.ApplyPropertyChanges(
                    key.EntitySetName, entity);                    
            }
            else
            {//add the new entity
                context.AddObject(entity.GetType().Name, entity);
            }//end else
        }
        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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Morshed Anwar
Team Leader Adaptive Enterprise Limited (www.ael-bd.com)
Bangladesh Bangladesh
No Biography provided

Comments and Discussions

 
QuestionSequence contains no elements PinmemberMember 831715423-Apr-13 18:41 
AnswerRe: Sequence contains no elements PinmemberMorshed Anwar24-Apr-13 5:49 
GeneralRe: Sequence contains no elements PinmemberMember 831715424-Apr-13 21:19 
GeneralRe: Sequence contains no elements PinmemberMorshed Anwar25-Apr-13 0:17 
GeneralRe: Sequence contains no elements PinmemberMember 831715425-Apr-13 2:06 
GeneralRe: Sequence contains no elements PinmemberMorshed Anwar25-Apr-13 3:22 
GeneralMy vote of 5 PinmemberTridip Bhattacharjee10-May-12 20:31 
QuestionRetrieve change data for a specific record. Pinmemberjabit22-Jun-11 8:30 
GeneralGood work if you are doing audit from the front end PinmemberDonsw3-May-09 11:32 
Good work if you are doing audit from the front end, I prefer having a trigger do the work.
 
cheers,
Donsw
My Recent Article : Ajax Calendar Control

GeneralRe: Good work if you are doing audit from the front end PinmemberMorshed Anwar3-May-09 23:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 1 Apr 2009
Article Copyright 2009 by Morshed Anwar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid