///
<summary>
/// This class is hooked into the Save pipeline to allow us to audit changes to data.
/// </summary>
public class AuditingSaveInterceptor : EntityServerSaveInterceptor
{
protected override bool ExecuteSave()
{
var entitiesBeingAdded = EntityManager.FindEntities(EntityState.Added).OfType<Entity>().ToList(); //get a concrete list, not a queryable.
var entitiesBeingUpdated = EntityManager.FindEntities(EntityState.Modified).OfType<Entity>().ToList();
AuditUpdates(entitiesBeingUpdated);
var entitiesBeingDeleted = EntityManager.FindEntities(EntityState.Deleted).OfType<Entity>().ToList();
AuditDeletes(entitiesBeingDeleted);
if (!base.ExecuteSave())
{
return false; //don't go any further if that bit of work failed.
}
//TODO: Audit inserts later on. See http://www.ideablade.com/forum/forum_posts.asp?TID=2717&PID=10825#10825
//AuditInserts(entitiesBeingAdded);
// return base.ExecuteSave(); //doesn't save the new Added audit records, attempts to re-save the items saved above.\
return true;
}
private void AuditDeletes(IEnumerable<Entity> entitiesBeingUpdated)
{
AuditChanges(entitiesBeingUpdated,
"Delete");
}
private void AuditUpdates(IEnumerable<Entity> entitiesBeingUpdated)
{
AuditChanges(entitiesBeingUpdated,
"Edit");
}
private void AuditInserts(IEnumerable<Entity> entitiesBeingAdded)
{
AuditChanges(entitiesBeingAdded,
"Add");
}
private void AuditChanges(IEnumerable<Entity> entitiesBeingUpdated, string auditType)
{
if (Principal == null || Principal.Identity.AuthenticationType == "Anonymous")
{
// we can't audit this without a proper ID to record it against
Debug.Assert(false, "DANGER: Not recording audit information as there's no authentication information available.");
return;
}
var userId = ((HCareIdentity) Principal.Identity).UserID;
foreach (var entity in entitiesBeingUpdated)
{
var audit = EntityManager.CreateEntity<Audit>();
audit.EntityAspect.AddToManager();
audit.AuditTime =
DateTime.Now;
audit.AuditType = auditType;
audit.EntityName = entity.GetType().Name;
audit.EntityID = (
long)entity.GetType().GetProperty("ID").GetValue(entity, null); // All our tables have a "ID" column storing the identity value.
audit.ChangeByID = userId;
}
}
}